code stringlengths 2 1.05M |
|---|
import Ember from 'ember';
import AuthenticateRoute from 'wholetale/routes/authenticate';
export default AuthenticateRoute.extend({
userAuth: Ember.inject.service(),
model() {
let currentUserId = this.get('userAuth').getCurrentUserID();
let catalogItems = {
mine: Ember.A(),
used: Ember.A(),
all: Ember.A()
};
let route = this;
return this.get('store').query('dataset', {
reload: true,
adapterOptions: {
queryParams: {
limit: "0"
}
}
})
.then(registered => {
registered.forEach(function (model) {
var creatorId = model.get('creatorId');
var userName = "System";
if (creatorId != null) {
return route.get('store').findRecord("user", creatorId)
.then(user => {
if (user != null) {
userName = [user.get('firstName'), user.get('lastName')].join(" ");
}
model.set("creator", userName);
});
}
model.set("creator", userName);
});
catalogItems.all = registered;
catalogItems.mine = registered.filter(each => each.get('creatorId') === currentUserId);
catalogItems.used = catalogItems.mine.filter(each => each.get('parentCollection') !== "user");
return {
images: this.get('store').findAll('image', {
reload: true,
adapterOptions: {
queryParams: {
limit: "0"
}
}
}),
tales: this.get('store').findAll('tale', {
reload: true,
adapterOptions: {
queryParams: {
sort: "created",
sortdir: "1",
limit: "0"
}
}
}),
dataRegistered: this.get('store').query('folder', {
reload: true,
adapterOptions: {
appendPath: "registered",
queryParams: {
limit: "0"
}
}
}),
catalogItems: catalogItems
};
})
.catch(e => {
console.log(e);
});
}
});
|
describe("Events", function(){
var EventTest;
var ListenTest;
var spy;
beforeEach(function(){
EventTest = Spine.Class.create();
EventTest.extend(Spine.Events);
spy = jasmine.createSpy();
});
it("can bind/trigger events", function(){
EventTest.bind("daddyo", spy);
EventTest.trigger("daddyo");
expect(spy).toHaveBeenCalled();
});
it("can listen for events on other objects", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "daddyo", spy);
EventTest.trigger("daddyo");
expect(spy).toHaveBeenCalled();
});
it("should trigger correct events", function(){
EventTest.bind("daddyo", spy);
EventTest.trigger("motherio");
expect(spy).not.toHaveBeenCalled();
});
it("can bind/trigger multiple events", function(){
EventTest.bind("house car windows", spy);
EventTest.trigger("car");
expect(spy).toHaveBeenCalled();
});
it("can listen for multiple events on other objects", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "house car windows", spy);
EventTest.trigger("car");
expect(spy).toHaveBeenCalled();
});
it("can pass data to triggered events", function(){
EventTest.bind("yoyo", spy);
EventTest.trigger("yoyo", 5, 10);
expect(spy).toHaveBeenCalledWith(5, 10);
});
it("can unbind events", function(){
EventTest.bind("daddyo", spy);
EventTest.unbind("daddyo");
EventTest.trigger("daddyo");
expect(spy).not.toHaveBeenCalled();
});
it("can unbind all events if no arguments given", function() {
EventTest.bind("yoyo daddyo", spy);
EventTest.unbind();
EventTest.trigger("yoyo");
expect(spy).not.toHaveBeenCalled();
spy.reset()
EventTest.trigger("daddyo");
expect(spy).not.toHaveBeenCalled();
});
it("can stop listening to events", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "daddyo", spy);
EventTest.trigger("daddyo");
expect(spy).toHaveBeenCalled();
spy.reset();
ListenTest.stopListening(EventTest, "daddyo");
EventTest.trigger("daddyo");
expect(spy).not.toHaveBeenCalled();
});
it("can unbind one event", function(){
EventTest.bind("house car windows", spy);
EventTest.unbind("car windows");
EventTest.trigger("car");
EventTest.trigger("windows");
expect(spy).not.toHaveBeenCalled();
EventTest.trigger("house");
expect(spy).toHaveBeenCalled();
});
it("can stopListening to one event", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "house car windows", spy)
ListenTest.stopListening(EventTest, "car windows");
EventTest.trigger("car");
EventTest.trigger("windows");
expect(spy).not.toHaveBeenCalled();
EventTest.trigger("house");
expect(spy).toHaveBeenCalled();
});
it("can stop listening to a specific callback", function(){
var noop2 = {spy2: function(){}};
spyOn(noop2, "spy2");
var spy2 = noop2.spy2;
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "keep", spy);
ListenTest.listenTo(EventTest, "keep", spy2);
//EventTest.trigger("keep");
//expect(spy).toHaveBeenCalled();
//expect(spy2).toHaveBeenCalled();
ListenTest.stopListening(EventTest, "keep", spy2);
EventTest.trigger("keep");
expect(spy).toHaveBeenCalled();
expect(spy2).not.toHaveBeenCalled();
});
it("can bind to an event only once", function(){
EventTest.one("indahouse", spy);
EventTest.trigger("indahouse");
expect(spy).toHaveBeenCalled();
spy.reset();
EventTest.trigger("indahouse");
expect(spy).not.toHaveBeenCalled();
});
it("can listen to to a event only once", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenToOnce(EventTest, 'indahouse', spy)
EventTest.trigger("indahouse");
expect(spy).toHaveBeenCalled();
spy.reset();
EventTest.trigger("indahouse");
expect(spy).not.toHaveBeenCalled();
});
it("can stopListening to a event that is being listened to once", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenToOnce(EventTest, "indahouse", spy)
ListenTest.stopListening(EventTest, "indahouse");
EventTest.trigger("indahouse");
expect(spy).not.toHaveBeenCalled();
});
it("can stopListening to all events if no arguments given", function(){
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "house", spy);
ListenTest.listenToOnce(EventTest, "indahouse", spy);
ListenTest.stopListening();
EventTest.trigger("house");
expect(spy).not.toHaveBeenCalled();
spy.reset();
EventTest.trigger("indahouse");
expect(spy).not.toHaveBeenCalled();
});
it("should allow a callback to unbind itself", function(){
var a = jasmine.createSpy("a");
var b = jasmine.createSpy("b");
var c = jasmine.createSpy("c");
b.andCallFake(function () {
EventTest.unbind("once", b);
});
EventTest.bind("once", a);
EventTest.bind("once", b);
EventTest.bind("once", c);
EventTest.trigger("once");
expect(a).toHaveBeenCalled();
expect(b).toHaveBeenCalled();
expect(c).toHaveBeenCalled();
EventTest.trigger("once");
expect(a.callCount).toBe(2);
expect(b.callCount).toBe(1);
expect(c.callCount).toBe(2);
});
it("can cancel propogation", function(){
EventTest.bind("motherio", function(){ return false; });
EventTest.bind("motherio", spy);
EventTest.trigger("motherio");
expect(spy).not.toHaveBeenCalled();
});
it("should clear events on inherited objects", function(){
EventTest.bind("yoyo", spy);
var Sub = EventTest.sub();
Sub.trigger("yoyo");
expect(spy).not.toHaveBeenCalled();
});
it("should not unbind all events if given and undefined object", function() {
EventTest.bind("daddyo", spy);
EventTest.unbind(undefined);
EventTest.trigger("daddyo");
expect(spy).toHaveBeenCalled();
});
it("should not stopListening to all events if given and undefined object", function() {
ListenTest = Spine.Class.create();
ListenTest.extend(Spine.Events);
ListenTest.listenTo(EventTest, "house", spy);
ListenTest.stopListening(undefined);
EventTest.trigger("house");
expect(spy).toHaveBeenCalled();
});
});
|
'use strict';
System.register(['aurelia-templating', 'aurelia-dependency-injection', 'aurelia-framework', '../common/attributeManager', '../common/attributes', '../element/element'], function (_export, _context) {
"use strict";
var bindable, customElement, noView, inject, computedFrom, AttributeManager, getBooleanFromAttributeValue, Ui5Element, _createClass, _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, Ui5SplitPane;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
return {
setters: [function (_aureliaTemplating) {
bindable = _aureliaTemplating.bindable;
customElement = _aureliaTemplating.customElement;
noView = _aureliaTemplating.noView;
}, function (_aureliaDependencyInjection) {
inject = _aureliaDependencyInjection.inject;
}, function (_aureliaFramework) {
computedFrom = _aureliaFramework.computedFrom;
}, function (_commonAttributeManager) {
AttributeManager = _commonAttributeManager.AttributeManager;
}, function (_commonAttributes) {
getBooleanFromAttributeValue = _commonAttributes.getBooleanFromAttributeValue;
}, function (_elementElement) {
Ui5Element = _elementElement.Ui5Element;
}],
execute: function () {
_createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
_export('Ui5SplitPane', Ui5SplitPane = (_dec = customElement('ui5-split-pane'), _dec2 = inject(Element), _dec3 = bindable(), _dec4 = bindable(), _dec5 = bindable(), _dec6 = bindable(), _dec7 = bindable(), _dec8 = bindable(), _dec9 = bindable(), _dec10 = computedFrom('_splitpane'), _dec(_class = _dec2(_class = (_class2 = function (_Ui5Element) {
_inherits(Ui5SplitPane, _Ui5Element);
function Ui5SplitPane(element) {
_classCallCheck(this, Ui5SplitPane);
var _this = _possibleConstructorReturn(this, _Ui5Element.call(this, element));
_this._splitpane = null;
_this._parent = null;
_this._relation = null;
_initDefineProp(_this, 'ui5Id', _descriptor, _this);
_initDefineProp(_this, 'ui5Class', _descriptor2, _this);
_initDefineProp(_this, 'ui5Tooltip', _descriptor3, _this);
_initDefineProp(_this, 'prevId', _descriptor4, _this);
_initDefineProp(_this, 'demandPane', _descriptor5, _this);
_initDefineProp(_this, 'requiredParentWidth', _descriptor6, _this);
_initDefineProp(_this, 'validationSuccess', _descriptor7, _this);
_initDefineProp(_this, 'validationError', _descriptor8, _this);
_initDefineProp(_this, 'parseError', _descriptor9, _this);
_initDefineProp(_this, 'formatError', _descriptor10, _this);
_initDefineProp(_this, 'modelContextChange', _descriptor11, _this);
_this.element = element;
_this.attributeManager = new AttributeManager(_this.element);
return _this;
}
Ui5SplitPane.prototype.fillProperties = function fillProperties(params) {
params.demandPane = getBooleanFromAttributeValue(this.demandPane);
params.requiredParentWidth = this.requiredParentWidth ? parseInt(this.requiredParentWidth) : 0;
_Ui5Element.prototype.fillProperties.call(this, params);
};
Ui5SplitPane.prototype.defaultFunc = function defaultFunc() {};
Ui5SplitPane.prototype.attached = function attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id) this._splitpane = new sap.ui.layout.SplitPane(this.ui5Id, params);else this._splitpane = new sap.ui.layout.SplitPane(params);
if (this.ui5Class) this._splitpane.addStyleClass(this.ui5Class);
if (this.ui5Tooltip) this._splitpane.setTooltip(this.ui5Tooltip);
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || this._parent.UIElement.sId != this._splitpane.sId) {
var prevSibling = null;
this._relation = this._parent.addChild(this._splitpane, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
} else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._splitpane, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
}
} else {
if (this._splitpane.placeAt) this._splitpane.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({ "ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
this.attributeManager.addAttributes({ "ui5-id": this._splitpane.sId });
};
Ui5SplitPane.prototype.detached = function detached() {
try {
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if (this._splitpane) this._parent.removeChildByRelation(this._splitpane, this._relation);
}
} else {
this._splitpane.destroy();
}
_Ui5Element.prototype.detached.call(this);
} catch (err) {}
};
Ui5SplitPane.prototype.addChild = function addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (var _iterator = path, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
elem = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
elem = _i.value;
}
try {
if (elem.localName == 'content') {
this._splitpane.setContent(child);return elem.localName;
}
if (elem.localName == 'tooltip') {
this._splitpane.setTooltip(child);return elem.localName;
}
if (elem.localName == 'customdata') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._splitpane.insertCustomData(child, _index);else this._splitpane.addCustomData(child, 0);return elem.localName;
}
if (elem.localName == 'layoutdata') {
this._splitpane.setLayoutData(child);return elem.localName;
}
if (elem.localName == 'dependents') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._splitpane.insertDependent(child, _index);else this._splitpane.addDependent(child, 0);return elem.localName;
}
if (elem.localName == 'dragdropconfig') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._splitpane.insertDragDropConfig(child, _index);else this._splitpane.addDragDropConfig(child, 0);return elem.localName;
}
} catch (err) {}
}
};
Ui5SplitPane.prototype.removeChildByRelation = function removeChildByRelation(child, relation) {
try {
if (relation == 'content') {
this._splitpane.destroyContent(child);
}
if (relation == 'tooltip') {
this._splitpane.destroyTooltip(child);
}
if (relation == 'customdata') {
this._splitpane.removeCustomData(child);
}
if (relation == 'layoutdata') {
this._splitpane.destroyLayoutData(child);
}
if (relation == 'dependents') {
this._splitpane.removeDependent(child);
}
if (relation == 'dragdropconfig') {
this._splitpane.removeDragDropConfig(child);
}
} catch (err) {}
};
Ui5SplitPane.prototype.demandPaneChanged = function demandPaneChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.setDemandPane(getBooleanFromAttributeValue(newValue));
}
};
Ui5SplitPane.prototype.requiredParentWidthChanged = function requiredParentWidthChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.setRequiredParentWidth(newValue);
}
};
Ui5SplitPane.prototype.validationSuccessChanged = function validationSuccessChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.attachValidationSuccess(newValue);
}
};
Ui5SplitPane.prototype.validationErrorChanged = function validationErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.attachValidationError(newValue);
}
};
Ui5SplitPane.prototype.parseErrorChanged = function parseErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.attachParseError(newValue);
}
};
Ui5SplitPane.prototype.formatErrorChanged = function formatErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.attachFormatError(newValue);
}
};
Ui5SplitPane.prototype.modelContextChangeChanged = function modelContextChangeChanged(newValue) {
if (newValue != null && newValue != undefined && this._splitpane !== null) {
this._splitpane.attachModelContextChange(newValue);
}
};
_createClass(Ui5SplitPane, [{
key: 'UIElement',
get: function get() {
return this._splitpane;
}
}]);
return Ui5SplitPane;
}(Ui5Element), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'ui5Id', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Class', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'ui5Tooltip', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'prevId', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, 'demandPane', [_dec3], {
enumerable: true,
initializer: function initializer() {
return true;
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, 'requiredParentWidth', [_dec4], {
enumerable: true,
initializer: function initializer() {
return 800;
}
}), _descriptor7 = _applyDecoratedDescriptor(_class2.prototype, 'validationSuccess', [_dec5], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor8 = _applyDecoratedDescriptor(_class2.prototype, 'validationError', [_dec6], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor9 = _applyDecoratedDescriptor(_class2.prototype, 'parseError', [_dec7], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor10 = _applyDecoratedDescriptor(_class2.prototype, 'formatError', [_dec8], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor11 = _applyDecoratedDescriptor(_class2.prototype, 'modelContextChange', [_dec9], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _applyDecoratedDescriptor(_class2.prototype, 'UIElement', [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, 'UIElement'), _class2.prototype)), _class2)) || _class) || _class));
_export('Ui5SplitPane', Ui5SplitPane);
}
};
}); |
'use strict';
// Configuring the Recipes module
angular.module('recipes').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Recipes', 'recipes', 'dropdown', '/recipes(/create)?');
Menus.addSubMenuItem('topbar', 'recipes', 'List Recipes', 'recipes');
Menus.addSubMenuItem('topbar', 'recipes', 'New Recipe', 'recipes/create');
}
]);
|
/**
* @summary theDirt
* @description handle dirty rails forms
* @version 0.0.1
* @file jquery.theDirt.js
* @author Blair Anderson (www.blairanderson.co)
* @contact www.blairandersom.co
*
* @copyright Copyright 2014 Blair Anderson
*
*/
/**
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').theDirt();
* } );
*
* @example
* // Initialisation with configuration options - in this case, Green
* $(document).ready( function {
* $('#example').theDirt( {"color": 'green'} );
* } );
*/
$(function(){
var TheDirt = function( options ){
$el = $(this);
$el.attr('data-remote', true)
debugger
// form error
$el.ajaxError(function(e, request, settings) {
var $form = $(e.currentTarget),
$textarea = $form.find('textarea');
$form.addClass('active.error');
$form.find("input[type='submit']").val('Not Saved... Try Again...');
$textarea.attr('data-start', $textarea.val() );
});
// form success
$el.bind('ajax:success', function(e, data, status, xhr){
var $form = $(e.currentTarget),
$textarea = $form.find('textarea');
$form.removeClass('active');
$form.removeClass('error');
$form.find("input[type='submit']").val('Saved');
$textarea.attr('data-start', $textarea.val() );
});
// store a copy of the current content
var $textfields = $('textarea');
for (var i = $textfields.length - 1; i >= 0; i--) {
var $textarea = $( $textfields[i] );
$textarea.attr('data-start', $textarea.val() );
};
// when anything changes on an input, change the button to 'saving...' or 'saved' whenever it should
$textfields.bind('input propertychange', function(e) {
var $textarea = $( e.currentTarget );
var $form = $textarea.closest('form');
if( $textarea.val() != $textarea.data("start") ){
$form.addClass('active');
$form.find("input[type='submit']").val('Saving...');
} else {
$form.removeClass('active');
$form.find("input[type='submit']").val('Saved');
}
});
// create a funtion to set a countdown timer to save the changes
var throttle = function throttle(f, delay){
var timer = null;
return function(){
var context = this, args = arguments;
clearTimeout(timer);
timer = window.setTimeout(function(){
f.apply(context, args);
}, delay || 3000);
};
}
// when a user starts typing, call the timer to save
$('textarea').keyup(throttle(function(e){
var $textarea = $(e.currentTarget);
if( $textarea.val() != $textarea.data("start") ){
$textarea.closest('form').submit();
}
}));
// when a suer leave a text box, save the data
$('textarea').blur(function(e) {
var $textarea = $(e.currentTarget);
if( $textarea.val() != $textarea.data("start") ){
$textarea.closest('form').submit();
}
});
};
TheDirt.version = "0.0.1";
// jQuery aliases
$.fn.TheDirt = TheDirt;
$.fn.theDirt = TheDirt;
$.fn.theDirtSettings = TheDirt.settings;
})
|
const queryparse = require('url').parse;
const domino = require('domino');
const jQuery = require('jquery');
/**
* Yttrium Router
* @type {module.Router}
*/
module.exports = class Router {
constructor(options) {
this.dom = domino.createWindow('<!DOCTYPE html>'); // new jsdom.JSDOM('<!DOCTYPE html>');
this.$ = jQuery(this.dom);
this.notFound = (options && options.notFound);
this.$ = this.$.bind(this);
this.router = this.router.bind(this);
this.routeTo = this.routeTo.bind(this);
this.send404 = this.send404.bind(this);
this.checkMethod = this.checkMethod.bind(this);
// attach the default index route to the RouterDOM
this.$('html').append('<index>');
// if a custom 404 route was specified, attach it to the DOM at no charge
if (this.notFound) this.$('index').append(`<${this.notFound}>`);
}
/**
* The main Yttrium router function
* it needs access to a jQuery instance tied to the RouterDOM
* it is meant to be used like $(server).on('request', router);
* @param server
* @param req
* @param res
* @returns {*}
*/
router(server, req, res) {
if (req && res) {
const parsedURL = queryparse(req.url, true);
const query = parsedURL.query;
const route = parsedURL.pathname
.replace(/\./g, '\\.') // paths referencing file names have to be escaped
.split('/')
.filter(r => r.length > 0);
// handle default route (index)
if (!route.length) {
return this.routeTo({ to: 'index', req, res, query });
}
route.unshift('index');
// Get the route selector
const routeTree = route.join(' > ');
if (this.$(routeTree).length) {
// full route was found
return this.routeTo({ to: routeTree, req, res, query });
}
const possibleParam = route.pop();
const paramRouteTree = route.join(' > ');
if (this.$(paramRouteTree).length && this.$(paramRouteTree).data('dynamic')) {
// a route with a dynamic parameter
// set the data-[something] with what the route had specified in data-dynamic='something'
this.$(paramRouteTree).data(this.$(paramRouteTree).data('dynamic'), possibleParam);
return this.routeTo({ to: paramRouteTree, req, res, query });
}
// route not found and not a dynamic route
this.send404(req, res);
}
return true;
}
/**
* Adds any query params to the query data object and triggers the route
* @param to
* @param req
* @param res
* @param query
*/
routeTo({ to, req, res, query }) {
// checks method and adds query params
if (this.checkMethod(to, req)) {
this.$(to)
.data('query', query)
.trigger('route', [req, res]);
} else {
this.send404(req, res);
}
}
/**
* Checks to see if method was specified on route and if so, that the request method matches
* @param route
* @param req
* @returns {boolean}
*/
checkMethod(route, req) {
// returns true if method was unspecified
// returns false if method was specified but didn't match request
// returns true if method specified and matched by request
if (this.$(route).data('method')) {
return this.$(route).data('method').toUpperCase() === req.method;
}
return true;
}
/**
* Triggers route function for the not-found route
* @param req
* @param res
*/
send404(req, res) {
// trigger a custom not-found route if there is one
if (this.notFound && this.$(`index > ${this.notFound}`)) {
this.$(this.$(`index > ${this.notFound}`)).trigger('route', [req, res]);
} else {
// otherwise, just close out with a 404
res.writeHead(404, 'Not Found');
res.end();
}
}
};
|
var NAVTREEINDEX70 =
{
"group___peripheral___registers___bits___definition.html#gae284870b7eb267d0ef7eb1f347038e1b":[2,106,0,5,0,3723],
"group___peripheral___registers___bits___definition.html#gae284870b7eb267d0ef7eb1f347038e1b":[4,0,0,1,0,23,5229],
"group___peripheral___registers___bits___definition.html#gae29556bba5b57a25104de74433d8cd31":[2,106,0,5,0,2005],
"group___peripheral___registers___bits___definition.html#gae29556bba5b57a25104de74433d8cd31":[4,0,0,1,0,23,2395],
"group___peripheral___registers___bits___definition.html#gae29d6ecd5e6c802a6214b814f6466b58":[4,0,0,1,0,23,5167],
"group___peripheral___registers___bits___definition.html#gae29d6ecd5e6c802a6214b814f6466b58":[2,106,0,5,0,3662],
"group___peripheral___registers___bits___definition.html#gae29eccc9daf15c787ebfc26af3fb3194":[4,0,0,1,0,23,2996],
"group___peripheral___registers___bits___definition.html#gae2bc0ce7ae7b0e7bad3ad51a6329dcea":[4,0,0,1,0,23,2447],
"group___peripheral___registers___bits___definition.html#gae2bc0ce7ae7b0e7bad3ad51a6329dcea":[2,106,0,5,0,2057],
"group___peripheral___registers___bits___definition.html#gae2be70f723d8e89b4566a9438a671f49":[4,0,0,1,0,23,3722],
"group___peripheral___registers___bits___definition.html#gae2c0c68bf65088e0ddeb9a1759aff3f7":[4,0,0,1,0,23,4094],
"group___peripheral___registers___bits___definition.html#gae2c0c68bf65088e0ddeb9a1759aff3f7":[2,106,0,5,0,2663],
"group___peripheral___registers___bits___definition.html#gae2ca76cb985239ed613062b1087075ab":[4,0,0,1,0,23,4991],
"group___peripheral___registers___bits___definition.html#gae2ca76cb985239ed613062b1087075ab":[2,106,0,5,0,3495],
"group___peripheral___registers___bits___definition.html#gae2d37d3e8661d7e4531eadb21e3d8d9c":[4,0,0,1,0,23,2657],
"group___peripheral___registers___bits___definition.html#gae2d37d3e8661d7e4531eadb21e3d8d9c":[2,106,0,5,0,2266],
"group___peripheral___registers___bits___definition.html#gae2da0bee4d174489ae10478531aee6ee":[2,106,0,5,0,3159],
"group___peripheral___registers___bits___definition.html#gae2da0bee4d174489ae10478531aee6ee":[4,0,0,1,0,23,4614],
"group___peripheral___registers___bits___definition.html#gae2de45b22180cee8e9b3fef000869af3":[4,0,0,1,0,23,1260],
"group___peripheral___registers___bits___definition.html#gae2de45b22180cee8e9b3fef000869af3":[2,106,0,5,0,1237],
"group___peripheral___registers___bits___definition.html#gae2ed8b32d9eb8eea251bd1dac4f34668":[4,0,0,1,0,23,4829],
"group___peripheral___registers___bits___definition.html#gae2ed8b32d9eb8eea251bd1dac4f34668":[2,106,0,5,0,3346],
"group___peripheral___registers___bits___definition.html#gae2f28920677dd99f9132ed28f7b1d5e2":[4,0,0,1,0,23,4598],
"group___peripheral___registers___bits___definition.html#gae2f28920677dd99f9132ed28f7b1d5e2":[2,106,0,5,0,3146],
"group___peripheral___registers___bits___definition.html#gae2faa0ef57b6622fc9f0171b13a51bfc":[4,0,0,1,0,23,3764],
"group___peripheral___registers___bits___definition.html#gae2fbdc1b854a54c4288402c2d3a7fca9":[2,106,0,5,0,114],
"group___peripheral___registers___bits___definition.html#gae2fbdc1b854a54c4288402c2d3a7fca9":[4,0,0,1,0,23,127],
"group___peripheral___registers___bits___definition.html#gae2fdd1ad6a4b7db36ece6145cba49ccf":[4,0,0,1,0,23,3851],
"group___peripheral___registers___bits___definition.html#gae31631eaac76ebecb059918c351ef3c9":[2,106,0,5,0,1582],
"group___peripheral___registers___bits___definition.html#gae31631eaac76ebecb059918c351ef3c9":[4,0,0,1,0,23,1611],
"group___peripheral___registers___bits___definition.html#gae325703f616d90c6c22198c288fa4f28":[4,0,0,1,0,23,5300],
"group___peripheral___registers___bits___definition.html#gae325703f616d90c6c22198c288fa4f28":[2,106,0,5,0,3794],
"group___peripheral___registers___bits___definition.html#gae3302817d057bf5fb99fd86aeb800478":[2,106,0,5,0,2141],
"group___peripheral___registers___bits___definition.html#gae3302817d057bf5fb99fd86aeb800478":[4,0,0,1,0,23,2531],
"group___peripheral___registers___bits___definition.html#gae348cc5bec6eecd8a188c3e90a9618d1":[2,106,0,5,0,1295],
"group___peripheral___registers___bits___definition.html#gae348cc5bec6eecd8a188c3e90a9618d1":[4,0,0,1,0,23,1318],
"group___peripheral___registers___bits___definition.html#gae34f5dda7a153ffd927c9cd38999f822":[2,106,0,5,0,67],
"group___peripheral___registers___bits___definition.html#gae34f5dda7a153ffd927c9cd38999f822":[4,0,0,1,0,23,80],
"group___peripheral___registers___bits___definition.html#gae35dfabd53bc335d95d330442cdfac6d":[4,0,0,1,0,23,3217],
"group___peripheral___registers___bits___definition.html#gae35dfabd53bc335d95d330442cdfac6d":[2,106,0,5,0,2480],
"group___peripheral___registers___bits___definition.html#gae37e08098d003f44eb8770a9d9bd40d0":[4,0,0,1,0,23,5484],
"group___peripheral___registers___bits___definition.html#gae37e08098d003f44eb8770a9d9bd40d0":[2,106,0,5,0,3963],
"group___peripheral___registers___bits___definition.html#gae387252f29b6f98cc1fffc4fa0719b6e":[4,0,0,1,0,23,3549],
"group___peripheral___registers___bits___definition.html#gae38aa3b76227bb8e9d8cedc31c023f63":[2,106,0,5,0,3060],
"group___peripheral___registers___bits___definition.html#gae38aa3b76227bb8e9d8cedc31c023f63":[4,0,0,1,0,23,4512],
"group___peripheral___registers___bits___definition.html#gae39e70a22e12291dfd597ab670302dcf":[4,0,0,1,0,23,2653],
"group___peripheral___registers___bits___definition.html#gae39e70a22e12291dfd597ab670302dcf":[2,106,0,5,0,2262],
"group___peripheral___registers___bits___definition.html#gae3a86c3918526efe2258ecbb34b91587":[4,0,0,1,0,23,3710],
"group___peripheral___registers___bits___definition.html#gae3d780fc1222a183071c73e62a0524a1":[4,0,0,1,0,23,1855],
"group___peripheral___registers___bits___definition.html#gae3de2080f48cc851c20d920acfd1737d":[4,0,0,1,0,23,356],
"group___peripheral___registers___bits___definition.html#gae3de2080f48cc851c20d920acfd1737d":[2,106,0,5,0,333],
"group___peripheral___registers___bits___definition.html#gae3f01cb1643b967ccea0c4bdfee8a5d2":[4,0,0,1,0,23,3753],
"group___peripheral___registers___bits___definition.html#gae3f70fc89b51ec09451071bf4bb2d5d1":[4,0,0,1,0,23,5228],
"group___peripheral___registers___bits___definition.html#gae3f70fc89b51ec09451071bf4bb2d5d1":[2,106,0,5,0,3722],
"group___peripheral___registers___bits___definition.html#gae3fd299a559b62badc881da2a5372ebc":[4,0,0,1,0,23,5326],
"group___peripheral___registers___bits___definition.html#gae3fd299a559b62badc881da2a5372ebc":[2,106,0,5,0,3820],
"group___peripheral___registers___bits___definition.html#gae403370a70f9ea2b6f9b449cafa6a91c":[4,0,0,1,0,23,1278],
"group___peripheral___registers___bits___definition.html#gae403370a70f9ea2b6f9b449cafa6a91c":[2,106,0,5,0,1255],
"group___peripheral___registers___bits___definition.html#gae4054fdf1fced195e59509a2282fd023":[4,0,0,1,0,23,1262],
"group___peripheral___registers___bits___definition.html#gae4054fdf1fced195e59509a2282fd023":[2,106,0,5,0,1239],
"group___peripheral___registers___bits___definition.html#gae4123bce64dc4f1831f992b09d6db4f2":[2,106,0,5,0,180],
"group___peripheral___registers___bits___definition.html#gae4123bce64dc4f1831f992b09d6db4f2":[4,0,0,1,0,23,193],
"group___peripheral___registers___bits___definition.html#gae4365204ebb29eb5595027a4ee9c5f0d":[4,0,0,1,0,23,341],
"group___peripheral___registers___bits___definition.html#gae4365204ebb29eb5595027a4ee9c5f0d":[2,106,0,5,0,318],
"group___peripheral___registers___bits___definition.html#gae44bae7ffc1cdebd5efbefbf679881df":[4,0,0,1,0,23,4616],
"group___peripheral___registers___bits___definition.html#gae44bae7ffc1cdebd5efbefbf679881df":[2,106,0,5,0,3161],
"group___peripheral___registers___bits___definition.html#gae44e1d120c773c9dc26f418acf3cb6de":[2,106,0,5,0,652],
"group___peripheral___registers___bits___definition.html#gae44e1d120c773c9dc26f418acf3cb6de":[4,0,0,1,0,23,675],
"group___peripheral___registers___bits___definition.html#gae45a8c814b13fa19f157364dc715c08a":[4,0,0,1,0,23,4439],
"group___peripheral___registers___bits___definition.html#gae45a8c814b13fa19f157364dc715c08a":[2,106,0,5,0,2987],
"group___peripheral___registers___bits___definition.html#gae4770cce2b4f601e88fb512f6db688ec":[4,0,0,1,0,23,5023],
"group___peripheral___registers___bits___definition.html#gae4770cce2b4f601e88fb512f6db688ec":[2,106,0,5,0,3527],
"group___peripheral___registers___bits___definition.html#gae497ffa0ef246a52e57a394fa57e616d":[2,106,0,5,0,1227],
"group___peripheral___registers___bits___definition.html#gae497ffa0ef246a52e57a394fa57e616d":[4,0,0,1,0,23,1250],
"group___peripheral___registers___bits___definition.html#gae49def2961bf528448a4fbb4aa9c9d94":[2,106,0,5,0,3016],
"group___peripheral___registers___bits___definition.html#gae49def2961bf528448a4fbb4aa9c9d94":[4,0,0,1,0,23,4468],
"group___peripheral___registers___bits___definition.html#gae4a1adc2e4e550a38649a2bfd3662680":[2,106,0,5,0,357],
"group___peripheral___registers___bits___definition.html#gae4a1adc2e4e550a38649a2bfd3662680":[4,0,0,1,0,23,380],
"group___peripheral___registers___bits___definition.html#gae4a87123ae5ff76992162152fbb4c92a":[4,0,0,1,0,23,566],
"group___peripheral___registers___bits___definition.html#gae4a87123ae5ff76992162152fbb4c92a":[2,106,0,5,0,543],
"group___peripheral___registers___bits___definition.html#gae4ccedde67989fcbaa84cae9cae4b1eb":[4,0,0,1,0,23,1020],
"group___peripheral___registers___bits___definition.html#gae4ccedde67989fcbaa84cae9cae4b1eb":[2,106,0,5,0,997],
"group___peripheral___registers___bits___definition.html#gae4e7104ce01e3a79b8f6138d87dc3684":[2,106,0,5,0,13],
"group___peripheral___registers___bits___definition.html#gae4e7104ce01e3a79b8f6138d87dc3684":[4,0,0,1,0,23,26],
"group___peripheral___registers___bits___definition.html#gae5043268b4da44b49fad35b7f94c811d":[4,0,0,1,0,23,3762],
"group___peripheral___registers___bits___definition.html#gae5088dcbaefc55d4b6693e9b1e595ed0":[4,0,0,1,0,23,3535],
"group___peripheral___registers___bits___definition.html#gae5088dcbaefc55d4b6693e9b1e595ed0":[2,106,0,5,0,2601],
"group___peripheral___registers___bits___definition.html#gae538b44aa24031a294442dc47f6849f5":[4,0,0,1,0,23,3832],
"group___peripheral___registers___bits___definition.html#gae5396ec2dbbee9d7585224fa12273598":[2,106,0,5,0,1666],
"group___peripheral___registers___bits___definition.html#gae5396ec2dbbee9d7585224fa12273598":[4,0,0,1,0,23,1950],
"group___peripheral___registers___bits___definition.html#gae53f1f88362bc9d12367842b2c41ac5f":[4,0,0,1,0,23,3007],
"group___peripheral___registers___bits___definition.html#gae543b0dd58f03c2f70bb6b3b65232863":[4,0,0,1,0,23,3870],
"group___peripheral___registers___bits___definition.html#gae5509a0f869a4c7ba34f45be4b733b23":[4,0,0,1,0,23,5398],
"group___peripheral___registers___bits___definition.html#gae5509a0f869a4c7ba34f45be4b733b23":[2,106,0,5,0,3892],
"group___peripheral___registers___bits___definition.html#gae55be7b911b4c0272543f98a0dba5f20":[2,106,0,5,0,16],
"group___peripheral___registers___bits___definition.html#gae55be7b911b4c0272543f98a0dba5f20":[4,0,0,1,0,23,29],
"group___peripheral___registers___bits___definition.html#gae56f77f869114e69525353f96004f955":[4,0,0,1,0,23,881],
"group___peripheral___registers___bits___definition.html#gae56f77f869114e69525353f96004f955":[2,106,0,5,0,858],
"group___peripheral___registers___bits___definition.html#gae570e9ba39dbe11808db929392250cf4":[2,106,0,5,0,330],
"group___peripheral___registers___bits___definition.html#gae570e9ba39dbe11808db929392250cf4":[4,0,0,1,0,23,353],
"group___peripheral___registers___bits___definition.html#gae5797a389fecf611dccd483658b822fa":[4,0,0,1,0,23,4210],
"group___peripheral___registers___bits___definition.html#gae5797a389fecf611dccd483658b822fa":[2,106,0,5,0,2776],
"group___peripheral___registers___bits___definition.html#gae58d87c9513c11593041c3d43b955e8b":[2,106,0,5,0,394],
"group___peripheral___registers___bits___definition.html#gae58d87c9513c11593041c3d43b955e8b":[4,0,0,1,0,23,417],
"group___peripheral___registers___bits___definition.html#gae597b084698f4daaa14f171448991b51":[2,106,0,5,0,1937],
"group___peripheral___registers___bits___definition.html#gae597b084698f4daaa14f171448991b51":[4,0,0,1,0,23,2327],
"group___peripheral___registers___bits___definition.html#gae5a5e1f0f1a66d607984d02b96b7fa2a":[2,106,0,5,0,1333],
"group___peripheral___registers___bits___definition.html#gae5a5e1f0f1a66d607984d02b96b7fa2a":[4,0,0,1,0,23,1356],
"group___peripheral___registers___bits___definition.html#gae5c1b8a0f2b4f79bd868bbb2b4eff617":[2,106,0,5,0,3136],
"group___peripheral___registers___bits___definition.html#gae5c1b8a0f2b4f79bd868bbb2b4eff617":[4,0,0,1,0,23,4588],
"group___peripheral___registers___bits___definition.html#gae5cb252582e6b7bd706b37447f71d6cd":[2,106,0,5,0,1084],
"group___peripheral___registers___bits___definition.html#gae5cb252582e6b7bd706b37447f71d6cd":[4,0,0,1,0,23,1107],
"group___peripheral___registers___bits___definition.html#gae5d2d461bbcd923fe3ea3ba2328233cb":[4,0,0,1,0,23,4299],
"group___peripheral___registers___bits___definition.html#gae5d2d461bbcd923fe3ea3ba2328233cb":[2,106,0,5,0,2863],
"group___peripheral___registers___bits___definition.html#gae616e53b9d961571eea4ff2df31f8399":[4,0,0,1,0,23,1108],
"group___peripheral___registers___bits___definition.html#gae616e53b9d961571eea4ff2df31f8399":[2,106,0,5,0,1085],
"group___peripheral___registers___bits___definition.html#gae61f8d54923999fffb6db381e81f2b69":[4,0,0,1,0,23,4777],
"group___peripheral___registers___bits___definition.html#gae61f8d54923999fffb6db381e81f2b69":[2,106,0,5,0,3294],
"group___peripheral___registers___bits___definition.html#gae6206d385d3b3e127b1e63be48f83a63":[4,0,0,1,0,23,3999],
"group___peripheral___registers___bits___definition.html#gae625d21947ae82cc3509b06363ad0635":[4,0,0,1,0,23,550],
"group___peripheral___registers___bits___definition.html#gae625d21947ae82cc3509b06363ad0635":[2,106,0,5,0,527],
"group___peripheral___registers___bits___definition.html#gae62678bd1dc39aae5a153e9c9b3c3f3b":[2,106,0,5,0,1467],
"group___peripheral___registers___bits___definition.html#gae62678bd1dc39aae5a153e9c9b3c3f3b":[4,0,0,1,0,23,1490],
"group___peripheral___registers___bits___definition.html#gae62885f29418cc83a57964fe631282cb":[4,0,0,1,0,23,3574],
"group___peripheral___registers___bits___definition.html#gae6398bd3e8312eea3b986ab59b80b466":[2,106,0,5,0,2812],
"group___peripheral___registers___bits___definition.html#gae6398bd3e8312eea3b986ab59b80b466":[4,0,0,1,0,23,4246],
"group___peripheral___registers___bits___definition.html#gae6417d13d2568b05676800c9eda4bdfb":[4,0,0,1,0,23,5281],
"group___peripheral___registers___bits___definition.html#gae6417d13d2568b05676800c9eda4bdfb":[2,106,0,5,0,3775],
"group___peripheral___registers___bits___definition.html#gae64182a042ceb8275c54819458b1ca9c":[4,0,0,1,0,23,1675],
"group___peripheral___registers___bits___definition.html#gae64a72dcf70ca2a6ee576a3a8c829838":[2,106,0,5,0,1974],
"group___peripheral___registers___bits___definition.html#gae64a72dcf70ca2a6ee576a3a8c829838":[4,0,0,1,0,23,2364],
"group___peripheral___registers___bits___definition.html#gae64f792b7a3401cff4d95e31d3867422":[4,0,0,1,0,23,3390],
"group___peripheral___registers___bits___definition.html#gae66a06121fc545cb8ec5a1c2ada0a138":[2,106,0,5,0,1532],
"group___peripheral___registers___bits___definition.html#gae66a06121fc545cb8ec5a1c2ada0a138":[4,0,0,1,0,23,1557],
"group___peripheral___registers___bits___definition.html#gae67a96234e062d1304a4af3afc938164":[4,0,0,1,0,23,5002],
"group___peripheral___registers___bits___definition.html#gae67a96234e062d1304a4af3afc938164":[2,106,0,5,0,3506],
"group___peripheral___registers___bits___definition.html#gae68a19a18d72f6d87c6f2b8cc8bfc6dc":[2,106,0,5,0,203],
"group___peripheral___registers___bits___definition.html#gae68a19a18d72f6d87c6f2b8cc8bfc6dc":[4,0,0,1,0,23,216],
"group___peripheral___registers___bits___definition.html#gae68ca6758cf36232dd5ac63afae97cbc":[4,0,0,1,0,23,4517],
"group___peripheral___registers___bits___definition.html#gae68ca6758cf36232dd5ac63afae97cbc":[2,106,0,5,0,3065],
"group___peripheral___registers___bits___definition.html#gae6a5be6cff1227431b8d54dffcc1ce88":[2,106,0,5,0,15],
"group___peripheral___registers___bits___definition.html#gae6a5be6cff1227431b8d54dffcc1ce88":[4,0,0,1,0,23,28],
"group___peripheral___registers___bits___definition.html#gae6b0fe571aa29ed30389f87bdbf37b46":[4,0,0,1,0,23,3410],
"group___peripheral___registers___bits___definition.html#gae6d8d2847058747ce23a648668ce4dba":[4,0,0,1,0,23,4739],
"group___peripheral___registers___bits___definition.html#gae6d8d2847058747ce23a648668ce4dba":[2,106,0,5,0,3256],
"group___peripheral___registers___bits___definition.html#gae6ec91db97da763ae1da98ef3a3f7fea":[2,106,0,5,0,433],
"group___peripheral___registers___bits___definition.html#gae6ec91db97da763ae1da98ef3a3f7fea":[4,0,0,1,0,23,456],
"group___peripheral___registers___bits___definition.html#gae70893925ea53547e9ce780c0480587b":[2,106,0,5,0,445],
"group___peripheral___registers___bits___definition.html#gae70893925ea53547e9ce780c0480587b":[4,0,0,1,0,23,468],
"group___peripheral___registers___bits___definition.html#gae729e21d590271c59c0d653300d5581c":[2,106,0,5,0,277],
"group___peripheral___registers___bits___definition.html#gae729e21d590271c59c0d653300d5581c":[4,0,0,1,0,23,290],
"group___peripheral___registers___bits___definition.html#gae72c4f34bb3ccffeef1d7cdcb7415bdc":[4,0,0,1,0,23,4276],
"group___peripheral___registers___bits___definition.html#gae72c4f34bb3ccffeef1d7cdcb7415bdc":[2,106,0,5,0,2842],
"group___peripheral___registers___bits___definition.html#gae738b22f6a8123026921a1d14f9547c0":[4,0,0,1,0,23,3963],
"group___peripheral___registers___bits___definition.html#gae7765ebf87061237afaa5995af169e52":[4,0,0,1,0,23,4166],
"group___peripheral___registers___bits___definition.html#gae7765ebf87061237afaa5995af169e52":[2,106,0,5,0,2734],
"group___peripheral___registers___bits___definition.html#gae7868643a65285fc7132f040c8950f43":[4,0,0,1,0,23,4654],
"group___peripheral___registers___bits___definition.html#gae7868643a65285fc7132f040c8950f43":[2,106,0,5,0,3171],
"group___peripheral___registers___bits___definition.html#gae78ec392640f05b20a7c6877983588ae":[2,106,0,5,0,1235],
"group___peripheral___registers___bits___definition.html#gae78ec392640f05b20a7c6877983588ae":[4,0,0,1,0,23,1258],
"group___peripheral___registers___bits___definition.html#gae7999bc46c6dbd508261b3975803e799":[2,106,0,5,0,1516],
"group___peripheral___registers___bits___definition.html#gae7999bc46c6dbd508261b3975803e799":[4,0,0,1,0,23,1541],
"group___peripheral___registers___bits___definition.html#gae7999e2ebeb1300d0cf6a59ad92c41b6":[4,0,0,1,0,23,3492],
"group___peripheral___registers___bits___definition.html#gae7ae8e338b3b42ad037e9e5b6eeb2c41":[4,0,0,1,0,23,3512],
"group___peripheral___registers___bits___definition.html#gae7b2373a2ac5150ca92566fd4663fb17":[2,106,0,5,0,1854],
"group___peripheral___registers___bits___definition.html#gae7b2373a2ac5150ca92566fd4663fb17":[4,0,0,1,0,23,2244],
"group___peripheral___registers___bits___definition.html#gae7bc1fb16d2d5b7a8d92fce5a61a038f":[2,106,0,5,0,3581],
"group___peripheral___registers___bits___definition.html#gae7bc1fb16d2d5b7a8d92fce5a61a038f":[4,0,0,1,0,23,5077],
"group___peripheral___registers___bits___definition.html#gae7d3c36f449ef1ee9ee20c5686b4e974":[4,0,0,1,0,23,94],
"group___peripheral___registers___bits___definition.html#gae7d3c36f449ef1ee9ee20c5686b4e974":[2,106,0,5,0,81],
"group___peripheral___registers___bits___definition.html#gae7de15e73395473569a447023dae53c4":[4,0,0,1,0,23,935],
"group___peripheral___registers___bits___definition.html#gae7de15e73395473569a447023dae53c4":[2,106,0,5,0,912],
"group___peripheral___registers___bits___definition.html#gae7f25e19a542791bcb97956262637e9b":[2,106,0,5,0,3810],
"group___peripheral___registers___bits___definition.html#gae7f25e19a542791bcb97956262637e9b":[4,0,0,1,0,23,5316],
"group___peripheral___registers___bits___definition.html#gae8268be8b5477f813c165e851acd41a2":[4,0,0,1,0,23,827],
"group___peripheral___registers___bits___definition.html#gae8268be8b5477f813c165e851acd41a2":[2,106,0,5,0,804],
"group___peripheral___registers___bits___definition.html#gae83dd9ce8a2c7917e278ce4755f8f43e":[4,0,0,1,0,23,449],
"group___peripheral___registers___bits___definition.html#gae83dd9ce8a2c7917e278ce4755f8f43e":[2,106,0,5,0,426],
"group___peripheral___registers___bits___definition.html#gae83fb5d62c6e6fa1c2fd06084528404e":[4,0,0,1,0,23,1621],
"group___peripheral___registers___bits___definition.html#gae849a9a49305e7d6cbdf64843f689fe8":[4,0,0,1,0,23,4584],
"group___peripheral___registers___bits___definition.html#gae849a9a49305e7d6cbdf64843f689fe8":[2,106,0,5,0,3132],
"group___peripheral___registers___bits___definition.html#gae8527cce22f69e02a08ed67a67f8e5ca":[2,106,0,5,0,1633],
"group___peripheral___registers___bits___definition.html#gae8527cce22f69e02a08ed67a67f8e5ca":[4,0,0,1,0,23,1917],
"group___peripheral___registers___bits___definition.html#gae861d74943f3c045421f9fdc8b966841":[4,0,0,1,0,23,4701],
"group___peripheral___registers___bits___definition.html#gae861d74943f3c045421f9fdc8b966841":[2,106,0,5,0,3218],
"group___peripheral___registers___bits___definition.html#gae86672dd7838e6a272ac7b90ee7a6f63":[2,106,0,5,0,1509],
"group___peripheral___registers___bits___definition.html#gae86672dd7838e6a272ac7b90ee7a6f63":[4,0,0,1,0,23,1534],
"group___peripheral___registers___bits___definition.html#gae874b1d1b15b4ada193bab411634a37a":[4,0,0,1,0,23,4996],
"group___peripheral___registers___bits___definition.html#gae874b1d1b15b4ada193bab411634a37a":[2,106,0,5,0,3500],
"group___peripheral___registers___bits___definition.html#gae87c14b75911aa0a9d0349d02d342711":[2,106,0,5,0,375],
"group___peripheral___registers___bits___definition.html#gae87c14b75911aa0a9d0349d02d342711":[4,0,0,1,0,23,398],
"group___peripheral___registers___bits___definition.html#gae87cecc544d0c1d8e778c3a598da9276":[4,0,0,1,0,23,5415],
"group___peripheral___registers___bits___definition.html#gae87cecc544d0c1d8e778c3a598da9276":[2,106,0,5,0,3905],
"group___peripheral___registers___bits___definition.html#gae8a4c3f98ccb3926fdafabb4d30f6a19":[4,0,0,1,0,23,2232],
"group___peripheral___registers___bits___definition.html#gae8a4c3f98ccb3926fdafabb4d30f6a19":[2,106,0,5,0,1842],
"group___peripheral___registers___bits___definition.html#gae8a8b42e33aef2a7bc2d41ad9d231733":[4,0,0,1,0,23,3337],
"group___peripheral___registers___bits___definition.html#gae8acbff235a15b58d1be0f065cdb5472":[4,0,0,1,0,23,3426],
"group___peripheral___registers___bits___definition.html#gae8ae4d091bb2c7148188ef430734020a":[2,106,0,5,0,3141],
"group___peripheral___registers___bits___definition.html#gae8ae4d091bb2c7148188ef430734020a":[4,0,0,1,0,23,4593],
"group___peripheral___registers___bits___definition.html#gae8b909ca659271857d9f3fcc817d8a4a":[4,0,0,1,0,23,5354],
"group___peripheral___registers___bits___definition.html#gae8b909ca659271857d9f3fcc817d8a4a":[2,106,0,5,0,3848],
"group___peripheral___registers___bits___definition.html#gae8bc946580d9e262135bec9bd61deef0":[2,106,0,5,0,2512],
"group___peripheral___registers___bits___definition.html#gae8bc946580d9e262135bec9bd61deef0":[4,0,0,1,0,23,3252],
"group___peripheral___registers___bits___definition.html#gae8c6e3cf3a4d1e9d722e820a3a0c1b6a":[4,0,0,1,0,23,746],
"group___peripheral___registers___bits___definition.html#gae8c6e3cf3a4d1e9d722e820a3a0c1b6a":[2,106,0,5,0,723],
"group___peripheral___registers___bits___definition.html#gae8d952192721dbdcea8d707d43096454":[4,0,0,1,0,23,1580],
"group___peripheral___registers___bits___definition.html#gae8d952192721dbdcea8d707d43096454":[2,106,0,5,0,1551],
"group___peripheral___registers___bits___definition.html#gae8e4fb52990f0fa3fb9bed5b74f1a589":[4,0,0,1,0,23,1975],
"group___peripheral___registers___bits___definition.html#gae8e4fb52990f0fa3fb9bed5b74f1a589":[2,106,0,5,0,1691],
"group___peripheral___registers___bits___definition.html#gae8ee1bc04de47f522a90619d57086b06":[4,0,0,1,0,23,5007],
"group___peripheral___registers___bits___definition.html#gae8ee1bc04de47f522a90619d57086b06":[2,106,0,5,0,3511],
"group___peripheral___registers___bits___definition.html#gae8fb23e47faf2dd2b69a22e36c4ea56d":[4,0,0,1,0,23,2904],
"group___peripheral___registers___bits___definition.html#gae9070c9b9eec5dea6b5c4cdbaa1d5918":[4,0,0,1,0,23,591],
"group___peripheral___registers___bits___definition.html#gae9070c9b9eec5dea6b5c4cdbaa1d5918":[2,106,0,5,0,568],
"group___peripheral___registers___bits___definition.html#gae909f90338c129e116b7d49bebfb31c5":[4,0,0,1,0,23,3381],
"group___peripheral___registers___bits___definition.html#gae910eb3d34714653d43579dcface4ead":[4,0,0,1,0,23,5011],
"group___peripheral___registers___bits___definition.html#gae910eb3d34714653d43579dcface4ead":[2,106,0,5,0,3515],
"group___peripheral___registers___bits___definition.html#gae92349731a6107e0f3a251b44a67c7ea":[4,0,0,1,0,23,4839],
"group___peripheral___registers___bits___definition.html#gae92349731a6107e0f3a251b44a67c7ea":[2,106,0,5,0,3356],
"group___peripheral___registers___bits___definition.html#gae934674f6e22a758e430f32cfc386d70":[2,106,0,5,0,1410],
"group___peripheral___registers___bits___definition.html#gae934674f6e22a758e430f32cfc386d70":[4,0,0,1,0,23,1433],
"group___peripheral___registers___bits___definition.html#gae93b86fd4c1bfcfafc42bf820c17c019":[4,0,0,1,0,23,2878],
"group___peripheral___registers___bits___definition.html#gae94612b95395eff626f5f3d7d28352dd":[4,0,0,1,0,23,4378],
"group___peripheral___registers___bits___definition.html#gae94612b95395eff626f5f3d7d28352dd":[2,106,0,5,0,2934],
"group___peripheral___registers___bits___definition.html#gae94ab55c126ff24572bbff0da5a3f360":[4,0,0,1,0,23,2855],
"group___peripheral___registers___bits___definition.html#gae94c65876a1baf0984a6f85aa836b8d0":[4,0,0,1,0,23,3815],
"group___peripheral___registers___bits___definition.html#gae956b8918d07e914a3f9861de501623f":[4,0,0,1,0,23,2902],
"group___peripheral___registers___bits___definition.html#gae96248bcf102a3c6f39f72cdcf8e4fe5":[2,106,0,5,0,1434],
"group___peripheral___registers___bits___definition.html#gae96248bcf102a3c6f39f72cdcf8e4fe5":[4,0,0,1,0,23,1457],
"group___peripheral___registers___bits___definition.html#gae965845f1e45d1f45831be60829e63bc":[4,0,0,1,0,23,1241],
"group___peripheral___registers___bits___definition.html#gae965845f1e45d1f45831be60829e63bc":[2,106,0,5,0,1218],
"group___peripheral___registers___bits___definition.html#gae968658ab837800723eafcc21af10247":[2,106,0,5,0,2937],
"group___peripheral___registers___bits___definition.html#gae968658ab837800723eafcc21af10247":[4,0,0,1,0,23,4381],
"group___peripheral___registers___bits___definition.html#gae9708e7cde70a19e8e8fa33291e1b9d5":[4,0,0,1,0,23,396],
"group___peripheral___registers___bits___definition.html#gae9708e7cde70a19e8e8fa33291e1b9d5":[2,106,0,5,0,373],
"group___peripheral___registers___bits___definition.html#gae97de172023462e5f40d4b420209809b":[4,0,0,1,0,23,742],
"group___peripheral___registers___bits___definition.html#gae97de172023462e5f40d4b420209809b":[2,106,0,5,0,719],
"group___peripheral___registers___bits___definition.html#gae97e53f3ffb5cccda1077815e464902c":[2,106,0,5,0,2015],
"group___peripheral___registers___bits___definition.html#gae97e53f3ffb5cccda1077815e464902c":[4,0,0,1,0,23,2405],
"group___peripheral___registers___bits___definition.html#gae9813cba2c5a4b58b07f9bbf6551ea00":[4,0,0,1,0,23,1537],
"group___peripheral___registers___bits___definition.html#gae9813cba2c5a4b58b07f9bbf6551ea00":[2,106,0,5,0,1512],
"group___peripheral___registers___bits___definition.html#gae991abb6f2e64443be7e39633f192aba":[2,106,0,5,0,1081],
"group___peripheral___registers___bits___definition.html#gae991abb6f2e64443be7e39633f192aba":[4,0,0,1,0,23,1104],
"group___peripheral___registers___bits___definition.html#gae993f7764c1e10e2f5022cba2a081f97":[4,0,0,1,0,23,2916],
"group___peripheral___registers___bits___definition.html#gae99763414b3c2f11fcfecb1f93eb6701":[2,106,0,5,0,2949],
"group___peripheral___registers___bits___definition.html#gae99763414b3c2f11fcfecb1f93eb6701":[4,0,0,1,0,23,4393],
"group___peripheral___registers___bits___definition.html#gae998d2cd523e6beee400d63cab203a45":[4,0,0,1,0,23,2656],
"group___peripheral___registers___bits___definition.html#gae998d2cd523e6beee400d63cab203a45":[2,106,0,5,0,2265],
"group___peripheral___registers___bits___definition.html#gae99d36b50a16c38b2006fdba4683ddd9":[2,106,0,5,0,874],
"group___peripheral___registers___bits___definition.html#gae99d36b50a16c38b2006fdba4683ddd9":[4,0,0,1,0,23,897]
};
|
'use strict';
module.exports = function(config, ircbot, utils) {
const logger = utils.logger.log;
if (!('path' in config) && !('port' in config)) {
logger('Starting without control socket, because neither path nor port were provided');
return;
}
function commandCallback(line) {
let args = line.split(' ');
let cmd = args.shift().toLowerCase();
let argsOptional = false;
let knownCmd = true;
let sendCmd = true;
switch (cmd) {
case 'quote':
cmd = 'send';
case 'send':
// no need to modify args
break;
case 'join':
args = [
args.slice(0, 2).join(' ')
];
break;
case 'part':
args.splice(1, args.length - 1, args.slice(1).join(' '));
break;
case 'say':
case 'action':
case 'notice':
args.splice(1, args.length - 1, args.slice(1).join(' '));
break;
case 'ctcp':
args.splice(2, args.length - 2, args.slice(2).join(' '));
break;
case 'whois':
args.splice(1, args.length - 1);
break;
case 'list':
argsOptional = true;
break;
case 'connect':
case 'activateFloodProtection':
argsOptional = true;
if (0 in args) {
args = [
parseInt(args[0])
];
}
break;
case 'disconnect':
if (!ircbot.conn) {
sendCmd = false;
break;
}
argsOptional = true;
const message = args.join(' ');
if (message.length) {
args = [
message
];
}
else {
args = [];
}
break;
default:
sendCmd = false;
switch (cmd) {
case 'exit':
if (ircbot.conn) {
ircbot.disconnect('Exiting by control socket request', function() {
process.exit();
});
}
else {
process.exit();
}
break;
default:
knownCmd = false;
break;
}
break;
}
if (knownCmd) {
logger('CMD: got CMD', cmd, 'ARGS', args);
if (sendCmd) {
if (args.length === 0 && !argsOptional) {
logger('CMD: not enough arguments');
return;
}
ircbot[cmd].apply(ircbot, args);
}
}
else {
logger('CMD: unknown CMD', cmd, 'ARGS', args);
}
}
const controlSocket = new utils.commandSocket.Socket(config, commandCallback);
};
|
/*global define*/
define([
'./BoundingRectangle',
'./BoundingSphere',
'./Cartesian2',
'./Cartesian3',
'./ComponentDatatype',
'./CornerType',
'./defaultValue',
'./defined',
'./DeveloperError',
'./Ellipsoid',
'./Geometry',
'./GeometryAttribute',
'./GeometryAttributes',
'./GeometryPipeline',
'./IndexDatatype',
'./Math',
'./PolygonPipeline',
'./PolylinePipeline',
'./PolylineVolumeGeometryLibrary',
'./PrimitiveType',
'./VertexFormat',
'./WindingOrder'
], function(
BoundingRectangle,
BoundingSphere,
Cartesian2,
Cartesian3,
ComponentDatatype,
CornerType,
defaultValue,
defined,
DeveloperError,
Ellipsoid,
Geometry,
GeometryAttribute,
GeometryAttributes,
GeometryPipeline,
IndexDatatype,
CesiumMath,
PolygonPipeline,
PolylinePipeline,
PolylineVolumeGeometryLibrary,
PrimitiveType,
VertexFormat,
WindingOrder) {
'use strict';
function computeAttributes(combinedPositions, shape, boundingRectangle, vertexFormat) {
var attributes = new GeometryAttributes();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute({
componentDatatype : ComponentDatatype.DOUBLE,
componentsPerAttribute : 3,
values : combinedPositions
});
}
var shapeLength = shape.length;
var vertexCount = combinedPositions.length / 3;
var length = (vertexCount - shapeLength * 2) / (shapeLength * 2);
var firstEndIndices = PolygonPipeline.triangulate(shape);
var indicesCount = (length - 1) * (shapeLength) * 6 + firstEndIndices.length * 2;
var indices = IndexDatatype.createTypedArray(vertexCount, indicesCount);
var i, j;
var ll, ul, ur, lr;
var offset = shapeLength * 2;
var index = 0;
for (i = 0; i < length - 1; i++) {
for (j = 0; j < shapeLength - 1; j++) {
ll = j * 2 + i * shapeLength * 2;
lr = ll + offset;
ul = ll + 1;
ur = ul + offset;
indices[index++] = ul;
indices[index++] = ll;
indices[index++] = ur;
indices[index++] = ur;
indices[index++] = ll;
indices[index++] = lr;
}
ll = shapeLength * 2 - 2 + i * shapeLength * 2;
ul = ll + 1;
ur = ul + offset;
lr = ll + offset;
indices[index++] = ul;
indices[index++] = ll;
indices[index++] = ur;
indices[index++] = ur;
indices[index++] = ll;
indices[index++] = lr;
}
if (vertexFormat.st || vertexFormat.tangent || vertexFormat.binormal) { // st required for tangent/binormal calculation
var st = new Float32Array(vertexCount * 2);
var lengthSt = 1 / (length - 1);
var heightSt = 1 / (boundingRectangle.height);
var heightOffset = boundingRectangle.height / 2;
var s, t;
var stindex = 0;
for (i = 0; i < length; i++) {
s = i * lengthSt;
t = heightSt * (shape[0].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
for (j = 1; j < shapeLength; j++) {
t = heightSt * (shape[j].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
st[stindex++] = s;
st[stindex++] = t;
}
t = heightSt * (shape[0].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
}
for (j = 0; j < shapeLength; j++) {
s = 0;
t = heightSt * (shape[j].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
}
for (j = 0; j < shapeLength; j++) {
s = (length - 1) * lengthSt;
t = heightSt * (shape[j].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
}
attributes.st = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 2,
values : new Float32Array(st)
});
}
var endOffset = vertexCount - shapeLength * 2;
for (i = 0; i < firstEndIndices.length; i += 3) {
var v0 = firstEndIndices[i] + endOffset;
var v1 = firstEndIndices[i + 1] + endOffset;
var v2 = firstEndIndices[i + 2] + endOffset;
indices[index++] = v0;
indices[index++] = v1;
indices[index++] = v2;
indices[index++] = v2 + shapeLength;
indices[index++] = v1 + shapeLength;
indices[index++] = v0 + shapeLength;
}
var geometry = new Geometry({
attributes : attributes,
indices : indices,
boundingSphere : BoundingSphere.fromVertices(combinedPositions),
primitiveType : PrimitiveType.TRIANGLES
});
if (vertexFormat.normal) {
geometry = GeometryPipeline.computeNormal(geometry);
}
if (vertexFormat.tangent || vertexFormat.binormal) {
geometry = GeometryPipeline.computeBinormalAndTangent(geometry);
if (!vertexFormat.tangent) {
geometry.attributes.tangent = undefined;
}
if (!vertexFormat.binormal) {
geometry.attributes.binormal = undefined;
}
if (!vertexFormat.st) {
geometry.attributes.st = undefined;
}
}
return geometry;
}
/**
* A description of a polyline with a volume (a 2D shape extruded along a polyline).
*
* @alias PolylineVolumeGeometry
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {Cartesian3[]} options.polylinePositions An array of {@link Cartesain3} positions that define the center of the polyline volume.
* @param {Cartesian2[]} options.shapePositions An array of {@link Cartesian2} positions that define the shape to be extruded along the polyline
* @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
* @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
* @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
* @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
*
* @see PolylineVolumeGeometry#createGeometry
*
* @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Polyline%20Volume.html|Cesium Sandcastle Polyline Volume Demo}
*
* @example
* function computeCircle(radius) {
* var positions = [];
* for (var i = 0; i < 360; i++) {
* var radians = Cesium.Math.toRadians(i);
* positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
* }
* return positions;
* }
*
* var volume = new Cesium.PolylineVolumeGeometry({
* vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
* polylinePositions : Cesium.Cartesian3.fromDegreesArray([
* -72.0, 40.0,
* -70.0, 35.0
* ]),
* shapePositions : computeCircle(100000.0)
* });
*/
function PolylineVolumeGeometry(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var positions = options.polylinePositions;
var shape = options.shapePositions;
//>>includeStart('debug', pragmas.debug);
if (!defined(positions)) {
throw new DeveloperError('options.polylinePositions is required.');
}
if (!defined(shape)) {
throw new DeveloperError('options.shapePositions is required.');
}
//>>includeEnd('debug');
this._positions = positions;
this._shape = shape;
this._ellipsoid = Ellipsoid.clone(defaultValue(options.ellipsoid, Ellipsoid.WGS84));
this._cornerType = defaultValue(options.cornerType, CornerType.ROUNDED);
this._vertexFormat = VertexFormat.clone(defaultValue(options.vertexFormat, VertexFormat.DEFAULT));
this._granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
this._workerName = 'createPolylineVolumeGeometry';
var numComponents = 1 + positions.length * Cartesian3.packedLength;
numComponents += 1 + shape.length * Cartesian2.packedLength;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
this.packedLength = numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 2;
}
/**
* Stores the provided instance into the provided array.
*
* @param {PolylineVolumeGeometry} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
PolylineVolumeGeometry.pack = function(value, array, startingIndex) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
//>>includeEnd('debug');
startingIndex = defaultValue(startingIndex, 0);
var i;
var positions = value._positions;
var length = positions.length;
array[startingIndex++] = length;
for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
Cartesian3.pack(positions[i], array, startingIndex);
}
var shape = value._shape;
length = shape.length;
array[startingIndex++] = length;
for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
Cartesian2.pack(shape[i], array, startingIndex);
}
Ellipsoid.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid.packedLength;
VertexFormat.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat.packedLength;
array[startingIndex++] = value._cornerType;
array[startingIndex] = value._granularity;
};
var scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
var scratchVertexFormat = new VertexFormat();
var scratchOptions = {
polylinePositions : undefined,
shapePositions : undefined,
ellipsoid : scratchEllipsoid,
vertexFormat : scratchVertexFormat,
cornerType : undefined,
granularity : undefined
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {PolylineVolumeGeometry} [result] The object into which to store the result.
* @returns {PolylineVolumeGeometry} The modified result parameter or a new PolylineVolumeGeometry instance if one was not provided.
*/
PolylineVolumeGeometry.unpack = function(array, startingIndex, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(array)) {
throw new DeveloperError('array is required');
}
//>>includeEnd('debug');
startingIndex = defaultValue(startingIndex, 0);
var i;
var length = array[startingIndex++];
var positions = new Array(length);
for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
positions[i] = Cartesian3.unpack(array, startingIndex);
}
length = array[startingIndex++];
var shape = new Array(length);
for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
shape[i] = Cartesian2.unpack(array, startingIndex);
}
var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
startingIndex += Ellipsoid.packedLength;
var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
startingIndex += VertexFormat.packedLength;
var cornerType = array[startingIndex++];
var granularity = array[startingIndex];
if (!defined(result)) {
scratchOptions.polylinePositions = positions;
scratchOptions.shapePositions = shape;
scratchOptions.cornerType = cornerType;
scratchOptions.granularity = granularity;
return new PolylineVolumeGeometry(scratchOptions);
}
result._positions = positions;
result._shape = shape;
result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
result._cornerType = cornerType;
result._granularity = granularity;
return result;
};
var brScratch = new BoundingRectangle();
/**
* Computes the geometric representation of a polyline with a volume, including its vertices, indices, and a bounding sphere.
*
* @param {PolylineVolumeGeometry} polylineVolumeGeometry A description of the polyline volume.
* @returns {Geometry|undefined} The computed vertices and indices.
*/
PolylineVolumeGeometry.createGeometry = function(polylineVolumeGeometry) {
var positions = polylineVolumeGeometry._positions;
var cleanPositions = PolylinePipeline.removeDuplicates(positions);
var shape2D = polylineVolumeGeometry._shape;
shape2D = PolylineVolumeGeometryLibrary.removeDuplicatesFromShape(shape2D);
if (cleanPositions.length < 2 || shape2D.length < 3) {
return undefined;
}
if (PolygonPipeline.computeWindingOrder2D(shape2D) === WindingOrder.CLOCKWISE) {
shape2D.reverse();
}
var boundingRectangle = BoundingRectangle.fromPoints(shape2D, brScratch);
var computedPositions = PolylineVolumeGeometryLibrary.computePositions(cleanPositions, shape2D, boundingRectangle, polylineVolumeGeometry, true);
return computeAttributes(computedPositions, shape2D, boundingRectangle, polylineVolumeGeometry._vertexFormat);
};
return PolylineVolumeGeometry;
});
|
define(['app'], function (app) {
// controller
app.controller('firstPageCtrl', function (socket,$css,$scope,$ionicModal,$http, $timeout,$ionicPopup,$state) {
// properties
socket.on('connect',function(){
//Add user called nickname
socket.emit('add user','nickname');
alert("http://chat.socket.io");
});
$scope.$on('$ionicView.afterEnter',function(){
//清空所有样式
//$css.removeAll();
});
//加载样式
//$css.add('css/WorkTask.css');
$scope.GoPage = function (target,param) {
$state.go(target,{params:param,xxx:'111',zzz:'222'});
}
});
});
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'examplemean';
var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})(); |
'use strict';
/*
* Module dependencies
*/
var _ = require('underscore');
var Mei = require('../mei');
var Goban = require('./goban');
var Player = require('./player');
var Room = require('./room');
var Stone = require('./stone');
/*
* Game model
*
* @key {Model:Goban} goban
* @key {string} turn (black/white)
*/
var Game = module.exports = Mei.Model.extend({
defaults: {
type: 'game',
turn: 'black'
},
schema: {
id: String,
type: String,
turn: String,
goban: Goban,
black: Player,
white: Player,
room: Room
}
});
/* Switch between the 2 possible values : black & white */
Game.prototype.toggleTurn = function () {
this.set('turn', this.get('turn') === 'black' ? 'white' : 'black');
};
/* Checks if stone simulation went well */
Game.prototype.canPutStone = function (stone) {
if (!this.goban()) return false;
if (!(stone instanceof Stone)) stone = new Stone(stone);
if (stone.get('color') !== this.get('turn')) return false;
return this.goban().canPutStone(stone);
};
/* Put a stone on goban, if possible */
Game.prototype.putStone = function (stone) {
var that = this;
if (!this.goban()) return false;
this.goban().off('capture');
this.goban().on('capture', function (group) {
that.get(stone.get('color')).incPrisoners(group.get('stones').size());
});
if (!(stone instanceof Stone)) stone = new Stone(stone);
if (stone.get('color') !== this.get('turn')) return false;
if (!this.goban().putStone(stone)) return false;
this.toggleTurn();
return true;
}; |
'use strict';
app.service('UserSession', function () {
this.create = function (userId, userAccessrights) {
console.log('UserSession.create: userId: %d, userAccessrights: %s ', userId, userAccessrights);
this.userId = userId;
this.userAccessrights = userAccessrights;
};
this.destroy = function () {
this.userId = null;
this.userAccessrights = null;
};
return this;
});
|
/**
* Created with IntelliJ IDEA.
* User: berkich
* Date: 6/21/13
*
* $.securityLabelRest is the global jQuery identifier to access this widget
*/
/*jslint plusplus: true */
jQuery(function ($, undefined) {
var bannerContainer = 'body';
var securityLabelName = 'securityLabel';
// var securityAggregateName = 'securityAggregate';
var securityAggregateName = 'securityLabel'; //configured for record level MAC, aggregate is same as reg label
var _Settings = {};
$.widget("swif.securityLabelRest", $.swif.securityLabel, {
//className:'swif-security',
body: $('body'),
// $security:$.noop(),
defaultLabel: ['U'],
options: {
// dialogEventId: 'securityDialog',
ajaxTimeout: 120,
baseURL: "",
restPath: "/swif/svcs/",
restURLs: {
settings: "settings",
collection: "",
query: "/query",
//find: "/find",
data: "/data",
securityLabel: "securitylabel",
//"classifications":"classifications",
// labelUser : "label/user/"
retrieveUsers: "retrieveUsers",
retrieveGroups: "retrieveGroups"
},
ajax: {
type: 'GET', contentType: 'application/json', dataType: 'json', context: this, timeout: 120 * 1000
}
},
_create: function () {
//this.element.addClass( this.className );
console.log("SWIF_REST_CREATE()");
this._super();
_Settings = this.options;
if (mil.js.swif.restPath !== undefined) {
_Settings.restPath = mil.js.swif.restPath;
}
$.securityLabelRest = this.element.data("swifSecurityLabelRest");
//this._update();
},
_destroy: function () {
console.log("SWIF_REST_DESTROY()");
return this._super();
},
//// REST private function ////
_ajax: function (url, options) {
var settings = [];
/* Workaround to resolve broken JSON returned from queries on the 'binary' collection. wms 2/28/15 */
if (url.indexOf("binary") >= 0) {
settings['dataFilter'] = function (data) {
//return (typeof data !== 'string') ? data : data.replace('<Binary Data>','"Binary Data"');
return (typeof data !== 'string') ? data : data.split('<Binary Data>').join('"Binary Data"');
}
}
$.extend(settings, _Settings.ajax, options, {
url: _Settings.baseURL + url,
timeout: this.options.ajaxTimeout * 1000
});
return $.ajax(settings).fail(function (jqXHR, textStatus, context) {
if (textStatus === 'parsererror') {
//alert('Error Sending/Receiving data: You may need to sign out and login in!');
//window.top.location.href = "/owf/j_spring_cas_security_logout";
} else {
SWIF.displayMessage('Error Sending/Receiving data: ' + textStatus, 'Server Error');
}
});
},
_ajaxGetRest: function (url, options) {
options = options || {};
$.extend(options, {type: 'GET'});
return this._ajax(_Settings.restPath + url, options);
},
_ajaxPostRest: function (url, options) {
options = options || {};
$.extend(options, {type: 'POST'});
return this._ajax(_Settings.restPath + url, options);
},
_ajaxPutRest: function (url, options) {
options = options || {};
$.extend(options, {type: 'PUT'});
return this._ajax(_Settings.restPath + url, options);
},
_ajaxDeleteRest: function (url, options) {
options = options || {};
$.extend(options, {type: 'DELETE'});
return this._ajax(_Settings.restPath + url, options);
},
getDialogLabel: function (SecurityLabel, title) {
var dfd;
//console.log('REST getDialogLabel: CALL this.getDialogLabel() ');
dfd = this._super(SecurityLabel, title);
return dfd;
},
getLabel: function () {
if ($.securityLabelBanner) {
return $.securityLabelBanner.getLabel();
}
},
setLabel: function (label) {
if ($.securityLabelBanner) {
$.securityLabelBanner.setLabel(label);
}
},
addLabel: function (label) {
if ($.securityLabelBanner) {
$.securityLabelBanner.addLabel(label);
}
},
formatLabel: function (label) {
if ($.securityLabelBanner) {
return $.securityLabelBanner.getBanner(label).text;
} else {
return "";
}
},
addRecord: function (record) {
if ($.securityLabelBanner && record && record[securityAggregateName]) {
$.securityLabelBanner.addLabel(record[securityAggregateName]);
}
},
addRecords: function (records) {
if ($.securityLabelBanner && records) {
var securityLabel = {};
for (var i = 0; i < records.length; i++) {
if (records[i] && records[i][securityAggregateName]) {
securityLabel = $.securityLabelBanner.addLabelDest(records[i][securityAggregateName], securityLabel);
}
}
$.securityLabelBanner.addLabel(securityLabel);
}
},
labelCollection: function (collectionName, collection, clear) {
var $this = this;
var dfd = $.Deferred();
if ($.securityLabelBanner) {
collection[securityLabelName] = $.securityLabelBanner.getLabel();
}
if (collection[securityLabelName] === undefined) {
collection[securityLabelName] = this.defaultLabel;
}
var routine;
if (!collection._id || !collection._id.$oid) {
routine = this.createCollection
} else {
routine = this.updateCollection
}
//id = collection._id.$oid;
$.securityLabelRest.getDialogLabel(collection[securityLabelName], collectionName).done(function (label) {
if (label) {
collection[securityLabelName] = label;
if (clear) {
$.securityLabelRest.clearLabel();
}
if ($.securityLabelBanner) {
collection[securityAggregateName] = $.securityLabelBanner.aggregateLabels(collection);
}
routine.call($this, collectionName, collection)
.fail(function (jqXHR, textStatus, context) {
//--- If the AJAX fails, don't die here. Inform the pending promise.
dfd.reject();
})
.done(function (data, textStatus, jqXHR) {
if (data && data._id) {
collection._id = {};
collection._id.$oid = data._id;
}
dfd.resolve(collectionName, collection);
});
}
});
return dfd.promise();
},
getCollection: function (collectionName, ids) {
var id;
var deferreds = [];
var url = _Settings.restURLs.collection + collectionName;
if (typeof ids === 'string') {
url += '/' + ids;
return this._ajaxGetRest(url, {context: this})
.done(function (data, textStatus, jqXHR) {
$.securityLabelRest.addRecord(data);
});
}
for (id in ids) {
if (ids.hasOwnProperty(id)) {
var uri = url + '/' + ids[id];
deferreds.push(this._ajaxGetRest(uri, {context: this}))
}
}
return $.when.apply($, deferreds)
.pipe(function (a1) {
var json = [];
if (!ids || ids.length == 0) {
return json;
}
if (!$.securityLabelRest.isArray(a1)) {
json.push(a1);
} else {
for (var i = 0; i < arguments.length; i++) {
var args = arguments[i];
var data = args[0];
var jqXHR = args[2];
if (jqXHR.status === 200 && data) {
json.push(data);
}
else {
//console.log('jqXHR.status=' + jqXHR.status + ' : ' + data);
}
}
}
return json;
})
.done(function (data) {
$.securityLabelRest.addRecords(data);
});
},
searchCollection: function (collectionName, queryString) {
var query = 'q=' + queryString.split(' ').join('+');
return $.securityLabelRest.queryCollection(collectionName, query);
},
queryCollection: function (collectionName, queryString) {
var url = _Settings.restURLs.collection + collectionName + _Settings.restURLs.query;
if (queryString) {
url += '?' + queryString;
}
return this._ajaxGetRest(url, {context: this})
.done(function (data) {
$.securityLabelRest.addRecords(data);
});
},
//Find has been disabled until we fully assess the security risks of allowing users to perform mongo queries.
/*
findCollection: function (collectionName, query) {
var url = _Settings.restURLs.collection + collectionName + _Settings.restURLs.find;
if (query) {
var stringJSON = query;
if (typeof stringJSON === 'object') {
stringJSON = JSON.stringify(stringJSON);
}
url += '?q=' + stringJSON;
//url += '?q=' + encodeURIComponent(stringJSON);
}
return this._ajaxGetRest(url, {context: this})
.done(function (data) {
$.securityLabelRest.addRecords(data);
});
},*/
createCollection: function (collectionName, collectionJSON) {
var url = _Settings.restURLs.collection + collectionName;
var stringJSON = collectionJSON;
if (typeof stringJSON === 'object') {
stringJSON = JSON.stringify(collectionJSON);
} else {
collectionJSON = $.parseJSON(collectionJSON);
}
return this._ajaxPostRest(url, {data: stringJSON, context: this})
.done(function (data) {
if (!data._id) {
alert('Create failed...');
} else {
$.securityLabelRest.addRecord(collectionJSON);
}
});
},
updateCollection: function (collectionName, id, collectionJSON) {
var url = _Settings.restURLs.collection + collectionName;
if (id != null && typeof id !== 'string') {
collectionJSON = id;
id = null;
}
if (!id) {
if (!collectionJSON._id || !collectionJSON._id.$oid) {
var dfd = $.Deferred();
dfd.reject("ID missing on update");
return dfd;
}
id = collectionJSON._id.$oid;
}
if (id) {
url += '/' + id;
}
var stringJSON = collectionJSON;
if (typeof stringJSON === 'object') {
stringJSON = JSON.stringify(collectionJSON);
} else {
collectionJSON = $.parseJSON(collectionJSON);
}
return this._ajaxPutRest(url, {data: stringJSON, context: this})
.done(function () {
$.securityLabelRest.addRecord(collectionJSON);
}
);
},
updateData: function (updatedProperties) {
var url = "data/update";
var stringJSON = updatedProperties;
if (typeof stringJSON === 'object') {
stringJSON = JSON.stringify(updatedProperties);
}
return this._ajaxPutRest(url, {data: stringJSON, context: this});
},
deleteCollection: function (collectionName, id, childCollections) {
var url = _Settings.restURLs.collection + collectionName;
if (id) {
url += '/' + id;
if (childCollections) {
var stringJSON = childCollections;
if (typeof stringJSON === 'object') {
stringJSON = JSON.stringify(stringJSON);
}
url += '?childCollections=' + stringJSON;
}
return this._ajaxDeleteRest(url, {context: this});
}
return {};
},
getData: function (ids) {
var id;
var deferreds = [];
var url = _Settings.restURLs.data;
if (typeof ids === 'string') {
url += '/' + ids;
return this._ajaxGetRest(url, {context: this})
.done(function (data) {
$.securityLabelRest.addRecord(data);
});
}
for (id in ids) {
if (ids.hasOwnProperty(id)) {
var uri = url + '/' + ids[id];
deferreds.push(this._ajaxGetRest(uri, {context: this}))
}
}
return $.when.apply($, deferreds)
.pipe(function (a1) {
var json = [];
for (var i = 0; i < arguments.length; i++) {
var args = arguments[i];
var data = args[0];
var jqXHR = args[2];
if (jqXHR.status == 200) {
json.push(data); //$.parseJSON(jqXHR.responseText));
}
else {
//console.log('jqXHR.status=' + jqXHR.status + ' : ' + data);
}
}
return json;
})
.done(function (data) {
$.securityLabelRest.addRecords(data);
});
},
createData: function (data, securityLabel) {
var url = _Settings.restURLs.data + '?' + _Settings.restURLs.securityLabel + '=' + securityLabel;
return this._ajaxPostRest(url, {
data: data,
contentType: 'multipart/form-data',
processData: false,
context: this
})
.done(function () {
$.securityLabelRest.setLabel(securityLabel);
});
},
deleteData: function (id) {
var url = _Settings.restURLs.data;
if (id) {
url += '/' + id;
return this._ajaxDeleteRest(url, {context: this});
}
return {};
},
clearLabel: function () {
if ($.securityLabelBanner) {
$.securityLabelBanner.clearLabel();
}
},
labelAll: function (obj, label) {
var k;
if (obj instanceof Object) {
obj.securityLabel = label;
for (k in obj) {
if (obj.hasOwnProperty(k)) { //make sure that the property isn't coming from the prototype
if (k != "securityLabel" && k != "_id") {
labelAll(obj[k], label);
}
}
}
}
},
labelAllNotAlreadyLabeled: function (obj, label) {
var k;
if (obj instanceof Object) {
if (!("securityLabel" in obj)) {
obj.securityLabel = label;
}
for (k in obj) {
if (obj.hasOwnProperty(k)) { //make sure that the property isn't coming from the prototype
if (k != "securityLabel" && k != "_id") {
labelAllNotAlreadyLabeled(obj[k], label);
}
}
}
}
},
labelInheritFromParentifNotLabeled: function (obj, label) {
var k;
if (obj instanceof Object) {
if (!("securityLabel" in obj)) {
obj.securityLabel = label;
}
for (k in obj) {
if (obj.hasOwnProperty(k)) { //make sure that the property isn't coming from the prototype
if (k != "securityLabel" && k != "_id") {
labelInheritFromParentifNotLabeled(obj[k], obj.securityLabel);
}
}
}
}
},
isArray: function (a) {
return Object.prototype.toString.apply(a) === '[object Array]';
},
getAllUsers: function (securityLabel) {
//TODO: filtering by security label not currently supported by backend service
var url = _Settings.restURLs.retrieveUsers;
return this._ajaxGetRest(url, {context: this});
},
getUsers: function (users, securityLabel) {
//TODO: filtering by security label not currently supported by backend service
if (!$.securityLabelRest.isArray(users) || users.length == 0) {
console.log("Invalid list of users received");
return null;
}
var url = _Settings.restURLs.retrieveUsers + "?";
for (i = 0; i < users.length; i++) {
url += "user=" + users[i] + "&";
}
url = url.substring(0, url.length - 1);
return this._ajaxGetRest(url, {context: this});
},
getGroups: function (groups, securityLabel) {
//TODO: filtering by security label not currently supported by backend service
if (!$.securityLabelRest.isArray(groups) || groups.length == 0) {
console.log("Invalid list of groups received");
return null;
}
var url = _Settings.restURLs.retrieveGroups + "?";
for (i = 0; i < groups.length; i++) {
url += "group=" + groups[i] + "&";
}
url = url.substring(0, url.length - 1);
return this._ajaxGetRest(url, {context: this});
},
lastProperty: 'The END of Widget swif.security' // Do Not move, for convenience only
});
// Create a jQuery utility pointing to our widget
// Initialize the WIDGET...........
$(bannerContainer).securityLabelRest();
});
|
'use strict';
/**
* @ngdoc function
* @name recappApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the recappApp
*/
angular.module('recappApp')
.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
var vm = this;
vm.click = function() {
console.log('Clicked');
alert('Clicked');
}
});
|
const redis = require("redis");
const _ = require("lodash");
const req = require("tiny_request");
const http = require("http");
const htmlparser = require("htmlparser2");
class RedisStorage {
constructor() {
this.client = redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PWD
})
this.listener = redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PWD
})
this._initListeners()
}
setBankData(pattern, channel, message) {
if (message === 'nbrb') {
getNBRBCurrencies().then((nbrbArray) => {
this.client.psetex(message, process.env.TTL, JSON.stringify(nbrbArray))
console.log('nbrb stored in cache')
})
}
if (message === 'other') {
getHtml().then((otherArray) => {
console.log('other stored in cache')
this.client.psetex(message, process.env.TTL, JSON.stringify(otherArray))
})
}
}
getBankData(bankKey, bankName) {
if ('nbrb' === bankKey) {
return new Promise((resolve, reject) => {
this.client.get(bankKey, (err, val) => {
if (!err && val) {
console.log('got from cache')
resolve(JSON.parse(val))
} else {
console.log('got from web')
getNBRBCurrencies().then((nbrbArray) => {
this.client.psetex(bankKey, process.env.TTL, JSON.stringify(nbrbArray))
resolve(nbrbArray)
})
}
})
})
}
if ('other' === bankKey) {
return new Promise((resolve, reject) => {
this.client.get(bankKey, (err, val) => {
if (!err && val) {
console.log('got from cache')
let foundBank = _.find(JSON.parse(val), (bank) => {
return bank.bankName === bankName
})
resolve(foundBank)
} else {
console.log('got from web')
getHtml().then((otherArray) => {
let foundBank = _.find(otherArray, (bank) => {
return bank.bankName === bankName
})
resolve(foundBank)
console.log(foundBank)
this.client.psetex(bankKey, process.env.TTL, JSON.stringify(otherArray))
})
}
})
})
}
}
getOtherBanksData(bankName) {
return this.getBankData('other', bankName)
}
getNBRBData() {
return this.getBankData('nbrb')
}
_initListeners() {
this.listener.config("SET", "notify-keyspace-events", "AKE");
this.listener.psubscribe("__keyevent@0__:expired");
this.listener.on('pmessage', (pattern, channel, message) => {
this.setBankData(pattern, channel, message)
});
}
}
module.exports = RedisStorage
const urls = ["http://www.nbrb.by/API/ExRates/Rates/145", "http://www.nbrb.by/API/ExRates/Rates/292", "http://www.nbrb.by/API/ExRates/Rates/298"];
const getNBRBCurrencies = () => {
let requests = [];
_.each(urls, (url) => {
let req = performRequest(url);
requests.push(req);
});
return Promise.all(requests).then((responses) => {
return responses;
});
};
const performRequest = (url) => {
let request = {
url: url,
json: true,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
"Connection": "keep-alive"
}
};
return new Promise((resolve, reject) => {
req.get(request, (body, response, err) => {
if (!err && response.statusCode === 200) {
resolve(body);
} else {
reject(err);
}
});
});
}
let rowTag = "";
let bankNameTag = "";
let currTag = "";
let bankData = [];
let bankDataObj;
let currencyArray = [];
let resolve, reject;
const parser = new htmlparser.Parser({
onopentag: (name, attribs) => {
if ("tr" === name) {
if (attribs['data-key']) {
bankDataObj = {};
rowTag = name;
}
}
if ("span" === name) {
if (attribs.class && attribs.class.includes("iconb")) {
bankNameTag = name;
}
}
if ("span" === name) {
if (attribs.class && attribs.class.includes("first_curr")) {
currTag = name;
}
}
},
ontext: (text) => {
if (rowTag) {
if (bankNameTag) {
bankDataObj.bankName = text
}
if (currTag && text) {
currencyArray.push(text)
}
}
},
onclosetag: (tagName) => {
if (rowTag === tagName) {
// renew all temporary values
rowTag = ""
parseValues()
bankData.push(bankDataObj)
bankDataObj = {}
currencyArray = []
}
if (bankNameTag === tagName) {
bankNameTag = ""
}
if (currTag === tagName) {
currTag = ""
}
},
onend: () => {
resolve(bankData);
}
}, { decodeEntities: true });
const parseValues = () => {
bankDataObj.usdBuy = currencyArray[0];
bankDataObj.usdSell = currencyArray[1];
bankDataObj.euroBuy = currencyArray[2];
bankDataObj.euroSell = currencyArray[3];
bankDataObj.rubBuy = currencyArray[4];
bankDataObj.rubSell = currencyArray[5];
}
const getHtml = () => {
return new Promise((res, rej) => {
http.get('http://myfin.by/currency/minsk', (response) => {
resolve = res;
reject = rej;
const statusCode = response.statusCode;
const contentType = response.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\n` +
`Status Code: ${statusCode}`);
}
if (error) {
response.resume();
return;
}
response.setEncoding('utf8');
response.pipe(parser);
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
});
} |
/*! UIkit 2.8.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
(function(addon) {
var component;
if (jQuery && jQuery.UIkit) {
component = addon(jQuery, jQuery.UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-htmleditor", ["uikit"], function(){
return component || addon(jQuery, jQuery.UIkit);
});
}
})(function($, UI) {
var editors = [];
UI.component('htmleditor', {
defaults: {
mode : 'split',
markdown : false,
autocomplete : true,
height : 500,
maxsplitsize : 1000,
markedOptions: { gfm: true, tables: true, breaks: true, pedantic: true, sanitize: false, smartLists: true, smartypants: false, langPrefix: 'lang-'},
codemirror : { mode: 'htmlmixed', tabMode: 'indent', tabsize: 4, lineWrapping: true, dragDrop: false, autoCloseTags: true, matchTags: true, autoCloseBrackets: true, matchBrackets: true, indentUnit: 4, hintOptions: {completionSingle:false} },
toolbar : [ 'bold', 'italic', 'strike', 'link', 'image', 'blockquote', 'listUl', 'listOl' ],
lblPreview : 'Preview',
lblCodeview : 'HTML',
lblMarkedview: 'Markdown'
},
init: function() {
var $this = this, tpl = UI.components.htmleditor.template;
this.CodeMirror = this.options.CodeMirror || CodeMirror;
this.buttons = {};
tpl = tpl.replace(/\{:lblPreview\}/g, this.options.lblPreview);
tpl = tpl.replace(/\{:lblCodeview\}/g, this.options.lblCodeview);
this.htmleditor = $(tpl);
this.content = this.htmleditor.find('.uk-htmleditor-content');
this.toolbar = this.htmleditor.find('.uk-htmleditor-toolbar');
this.preview = this.htmleditor.find('.uk-htmleditor-preview').children().eq(0);
this.code = this.htmleditor.find('.uk-htmleditor-code');
this.element.before(this.htmleditor).appendTo(this.code);
this.editor = this.CodeMirror.fromTextArea(this.element[0], this.options.codemirror);
this.editor.htmleditor = this;
this.editor.on('change', UI.Utils.debounce(function() { $this.render(); }, 150));
this.editor.on('change', function() { $this.editor.save(); });
this.code.find('.CodeMirror').css('height', this.options.height);
$(window).on('resize', UI.Utils.debounce(function() { $this.fit(); }, 200));
var previewContainer = $this.preview.parent(),
codeContent = this.code.find('.CodeMirror-sizer'),
codeScroll = this.code.find('.CodeMirror-scroll').on('scroll', UI.Utils.debounce(function() {
if ($this.htmleditor.attr('data-mode') == 'tab') return;
// calc position
var codeHeight = codeContent.height() - codeScroll.height(),
previewHeight = previewContainer[0].scrollHeight - previewContainer.height(),
ratio = previewHeight / codeHeight,
previewPostition = codeScroll.scrollTop() * ratio;
// apply new scroll
previewContainer.scrollTop(previewPostition);
}, 10));
this.htmleditor.on('click', '.uk-htmleditor-button-code, .uk-htmleditor-button-preview', function(e) {
e.preventDefault();
if ($this.htmleditor.attr('data-mode') == 'tab') {
$this.htmleditor.find('.uk-htmleditor-button-code, .uk-htmleditor-button-preview').removeClass('uk-active').filter(this).addClass('uk-active');
$this.activetab = $(this).hasClass('uk-htmleditor-button-code') ? 'code' : 'preview';
$this.htmleditor.attr('data-active-tab', $this.activetab);
$this.editor.refresh();
}
});
// toolbar actions
this.htmleditor.on('click', 'a[data-htmleditor-button]', function() {
if (!$this.code.is(':visible')) return;
$this.trigger('action.' + $(this).data('htmleditor-button'), [$this.editor]);
});
this.preview.parent().css('height', this.code.height());
// autocomplete
if (this.options.autocomplete && this.CodeMirror.showHint && this.CodeMirror.hint && this.CodeMirror.hint.html) {
this.editor.on('inputRead', UI.Utils.debounce(function() {
var doc = $this.editor.getDoc(), POS = doc.getCursor(), mode = $this.CodeMirror.innerMode($this.editor.getMode(), $this.editor.getTokenAt(POS).state).mode.name;
if (mode == 'xml') { //html depends on xml
var cur = $this.editor.getCursor(), token = $this.editor.getTokenAt(cur);
if (token.string.charAt(0) == '<' || token.type == 'attribute') {
$this.CodeMirror.showHint($this.editor, $this.CodeMirror.hint.html, { completeSingle: false });
}
}
}, 100));
}
this.debouncedRedraw = UI.Utils.debounce(function () { $this.redraw(); }, 5);
this.on('init', function() {
$this.redraw();
});
editors.push(this);
},
addButton: function(name, button) {
this.buttons[name] = button;
},
addButtons: function(buttons) {
$.extend(this.buttons, buttons);
},
replaceInPreview: function(regexp, callback) {
var editor = this.editor, results = [], value = editor.getValue(), offset = -1;
this.currentvalue = this.currentvalue.replace(regexp, function() {
offset = value.indexOf(arguments[0], ++offset);
var match = {
matches: arguments,
from : translateOffset(offset),
to : translateOffset(offset + arguments[0].length),
replace: function(value) {
editor.replaceRange(value, match.from, match.to);
},
inRange: function(cursor) {
if (cursor.line === match.from.line && cursor.line === match.to.line) {
return cursor.ch >= match.from.ch && cursor.ch < match.to.ch;
}
return (cursor.line === match.from.line && cursor.ch >= match.from.ch)
|| (cursor.line > match.from.line && cursor.line < match.to.line)
|| (cursor.line === match.to.line && cursor.ch < match.to.ch);
}
};
var result = callback(match);
if (result == false) {
return arguments[0];
}
results.push(match);
return result;
});
function translateOffset(offset) {
var result = editor.getValue().substring(0, offset).split('\n');
return { line: result.length - 1, ch: result[result.length - 1].length }
}
return results;
},
_buildtoolbar: function() {
if (!(this.options.toolbar && this.options.toolbar.length)) return;
var $this = this, bar = [];
this.toolbar.empty();
this.options.toolbar.forEach(function(button) {
if (!$this.buttons[button]) return;
var title = $this.buttons[button].title ? $this.buttons[button].title : button;
bar.push('<li><a data-htmleditor-button="'+button+'" title="'+title+'" data-uk-tooltip>'+$this.buttons[button].label+'</a></li>');
});
this.toolbar.html(bar.join('\n'));
},
fit: function() {
var mode = this.options.mode;
if (mode == 'split' && this.htmleditor.width() < this.options.maxsplitsize) {
mode = 'tab';
}
if (mode == 'tab') {
if (!this.activetab) {
this.activetab = 'code';
this.htmleditor.attr('data-active-tab', this.activetab);
}
this.htmleditor.find('.uk-htmleditor-button-code, .uk-htmleditor-button-preview').removeClass('uk-active')
.filter(this.activetab == 'code' ? '.uk-htmleditor-button-code' : '.uk-htmleditor-button-preview')
.addClass('uk-active');
}
this.editor.refresh();
this.preview.parent().css('height', this.code.height());
this.htmleditor.attr('data-mode', mode);
},
redraw: function() {
this._buildtoolbar();
this.render();
this.fit();
},
getMode: function() {
return this.editor.getOption('mode');
},
getCursorMode: function() {
var param = { mode: 'html'};
this.trigger('cursorMode', [param]);
return param.mode;
},
render: function() {
this.currentvalue = this.editor.getValue();
// empty code
if (!this.currentvalue) {
this.element.val('');
this.preview.html('');
return;
}
this.trigger('render', [this]);
this.trigger('renderLate', [this]);
this.preview.html(this.currentvalue);
},
addShortcut: function(name, callback) {
var map = {};
if (!$.isArray(name)) {
name = [name];
}
name.forEach(function(key) {
map[key] = callback;
});
this.editor.addKeyMap(map);
return map;
},
addShortcutAction: function(action, shortcuts) {
var editor = this;
this.addShortcut(shortcuts, function() {
editor.element.trigger('action.' + action, [editor.editor]);
});
},
replaceSelection: function(replace) {
var text = this.editor.getSelection();
if (!text.length) {
var cur = this.editor.getCursor(),
curLine = this.editor.getLine(cur.line),
start = cur.ch,
end = start;
while (end < curLine.length && /[\w$]+/.test(curLine.charAt(end))) ++end;
while (start && /[\w$]+/.test(curLine.charAt(start - 1))) --start;
var curWord = start != end && curLine.slice(start, end);
if (curWord) {
this.editor.setSelection({ line: cur.line, ch: start}, { line: cur.line, ch: end });
text = curWord;
}
}
var html = replace.replace('$1', text);
this.editor.replaceSelection(html, 'end');
this.editor.focus();
},
replaceLine: function(replace) {
var pos = this.editor.getDoc().getCursor(),
text = this.editor.getLine(pos.line),
html = replace.replace('$1', text);
this.editor.replaceRange(html , { line: pos.line, ch: 0 }, { line: pos.line, ch: text.length });
this.editor.setCursor({ line: pos.line, ch: html.length });
this.editor.focus();
},
save: function() {
this.editor.save();
}
});
UI.components.htmleditor.template = [
'<div class="uk-htmleditor uk-clearfix" data-mode="split">',
'<div class="uk-htmleditor-navbar">',
'<ul class="uk-htmleditor-navbar-nav uk-htmleditor-toolbar"></ul>',
'<div class="uk-htmleditor-navbar-flip">',
'<ul class="uk-htmleditor-navbar-nav">',
'<li class="uk-htmleditor-button-code"><a>{:lblCodeview}</a></li>',
'<li class="uk-htmleditor-button-preview"><a>{:lblPreview}</a></li>',
'<li><a data-htmleditor-button="fullscreen"><i class="uk-icon-expand"></i></a></li>',
'</ul>',
'</div>',
'</div>',
'<div class="uk-htmleditor-content">',
'<div class="uk-htmleditor-code"></div>',
'<div class="uk-htmleditor-preview"><div></div></div>',
'</div>',
'</div>'
].join('');
UI.plugin('htmleditor', 'base', {
init: function(editor) {
editor.addButtons({
fullscreen: {
title : 'Fullscreen',
label : '<i class="uk-icon-expand"></i>'
},
bold : {
title : 'Bold',
label : '<i class="uk-icon-bold"></i>'
},
italic : {
title : 'Italic',
label : '<i class="uk-icon-italic"></i>'
},
strike : {
title : 'Strikethrough',
label : '<i class="uk-icon-strikethrough"></i>'
},
blockquote : {
title : 'Blockquote',
label : '<i class="uk-icon-quote-right"></i>'
},
link : {
title : 'Link',
label : '<i class="uk-icon-link"></i>'
},
image : {
title : 'Image',
label : '<i class="uk-icon-picture-o"></i>'
},
listUl : {
title : 'Unordered List',
label : '<i class="uk-icon-list-ul"></i>'
},
listOl : {
title : 'Ordered List',
label : '<i class="uk-icon-list-ol"></i>'
}
});
addAction('bold', '<strong>$1</strong>');
addAction('italic', '<em>$1</em>');
addAction('strike', '<del>$1</del>');
addAction('blockquote', '<blockquote><p>$1</p></blockquote>', 'replaceLine');
addAction('link', '<a href="http://">$1</a>');
addAction('image', '<img src="http://" alt="$1">');
var listfn = function() {
if (editor.getCursorMode() == 'html') {
var cm = editor.editor,
pos = cm.getDoc().getCursor(true),
posend = cm.getDoc().getCursor(false);
for (var i=pos.line; i<(posend.line+1);i++) {
cm.replaceRange('<li>'+cm.getLine(i)+'</li>', { line: i, ch: 0 }, { line: i, ch: cm.getLine(i).length });
}
cm.setCursor({ line: posend.line, ch: cm.getLine(posend.line).length });
cm.focus();
}
}
editor.on('action.listUl', function() {
listfn();
});
editor.on('action.listOl', function() {
listfn();
});
editor.htmleditor.on('click', 'a[data-htmleditor-button="fullscreen"]', function() {
editor.htmleditor.toggleClass('uk-htmleditor-fullscreen');
var wrap = editor.editor.getWrapperElement();
if (editor.htmleditor.hasClass('uk-htmleditor-fullscreen')) {
editor.editor.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, width: wrap.style.width, height: wrap.style.height};
wrap.style.width = '';
wrap.style.height = editor.content.height()+'px';
document.documentElement.style.overflow = 'hidden';
} else {
document.documentElement.style.overflow = '';
var info = editor.editor.state.fullScreenRestore;
wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, info.scrollTop);
}
setTimeout(function() {
editor.fit();
UI.$win.trigger('resize');
}, 50);
});
editor.addShortcut(['Ctrl-S', 'Cmd-S'], function() { editor.element.trigger('htmleditor-save', [editor]); });
editor.addShortcutAction('bold', ['Ctrl-B', 'Cmd-B']);
function addAction(name, replace, mode) {
editor.on('action.'+name, function() {
if (editor.getCursorMode() == 'html') {
editor[mode == 'replaceLine' ? 'replaceLine' : 'replaceSelection'](replace);
}
});
}
}
});
UI.plugin('htmleditor', 'markdown', {
init: function(editor) {
var parser = editor.options.marked || marked;
if (!parser) return;
parser.setOptions(editor.options.markedOptions);
if (editor.options.markdown) {
enableMarkdown()
}
addAction('bold', '**$1**');
addAction('italic', '*$1*');
addAction('strike', '~~$1~~');
addAction('blockquote', '> $1', 'replaceLine');
addAction('link', '[$1](http://)');
addAction('image', '');
editor.on('action.listUl', function() {
if (editor.getCursorMode() == 'markdown') {
var cm = editor.editor,
pos = cm.getDoc().getCursor(true),
posend = cm.getDoc().getCursor(false);
for (var i=pos.line; i<(posend.line+1);i++) {
cm.replaceRange('* '+cm.getLine(i), { line: i, ch: 0 }, { line: i, ch: cm.getLine(i).length });
}
cm.setCursor({ line: posend.line, ch: cm.getLine(posend.line).length });
cm.focus();
}
});
editor.on('action.listOl', function() {
if (editor.getCursorMode() == 'markdown') {
var cm = editor.editor,
pos = cm.getDoc().getCursor(true),
posend = cm.getDoc().getCursor(false),
prefix = 1;
if (pos.line > 0) {
var prevline = cm.getLine(pos.line-1), matches;
if(matches = prevline.match(/^(\d+)\./)) {
prefix = Number(matches[1])+1;
}
}
for (var i=pos.line; i<(posend.line+1);i++) {
cm.replaceRange(prefix+'. '+cm.getLine(i), { line: i, ch: 0 }, { line: i, ch: cm.getLine(i).length });
prefix++;
}
cm.setCursor({ line: posend.line, ch: cm.getLine(posend.line).length });
cm.focus();
}
});
editor.on('renderLate', function() {
if (editor.editor.options.mode == 'gfm') {
editor.currentvalue = parser(editor.currentvalue);
}
});
editor.on('cursorMode', function(e, param) {
if (editor.editor.options.mode == 'gfm') {
var pos = editor.editor.getDoc().getCursor();
if (!editor.editor.getTokenAt(pos).state.base.htmlState) {
param.mode = 'markdown';
}
}
});
$.extend(editor, {
enableMarkdown: function() {
enableMarkdown()
this.render();
},
disableMarkdown: function() {
this.editor.setOption('mode', 'htmlmixed');
this.htmleditor.find('.uk-htmleditor-button-code a').html(this.options.lblCodeview);
this.render();
}
});
// switch markdown mode on event
editor.on({
enableMarkdown : function() { editor.enableMarkdown(); },
disableMarkdown : function() { editor.disableMarkdown(); }
});
function enableMarkdown() {
editor.editor.setOption('mode', 'gfm');
editor.htmleditor.find('.uk-htmleditor-button-code a').html(editor.options.lblMarkedview);
}
function addAction(name, replace, mode) {
editor.on('action.'+name, function() {
if (editor.getCursorMode() == 'markdown') {
editor[mode == 'replaceLine' ? 'replaceLine' : 'replaceSelection'](replace);
}
});
}
}
});
// init code
$(function() {
$('textarea[data-uk-htmleditor]').each(function() {
var editor = $(this), obj;
if (!editor.data('htmleditor')) {
obj = UI.htmleditor(editor, UI.Utils.options(editor.attr('data-uk-htmleditor')));
}
});
});
$(document).on("uk-check-display", function(e) {
editors.forEach(function(item) {
if(item.htmleditor.is(":visible")) item.fit();
});
});
return UI.htmleditor;
}); |
this.props.; |
var Paddle = function(){
this.height = 20,
this.width = 100,
this.colour = 'red',
this.x = canvas.width / 2,
this.y = canvas.height - 30,
this.center = function(){
return (this.x + (this.x + this.width)) / 2
}
}
Paddle.prototype.surfaceRange = function () {
var lower, upper;
lower = this.center() - (this.width / 2)
upper = this.center() + (this.width / 2)
return [lower, upper]
};
Paddle.prototype.leftBoundary = function() {
if(this.x == 0){
return false
}
return true
};
Paddle.prototype.rightBoundary = function() {
if(this.x == (canvas.width - this.width)){
return false
}
return true
};
Paddle.prototype.topSide = function () {
return this.y
};
Paddle.prototype.leftEdge = function () {
var leftCorner, leftMedium;
leftCorner = this.surfaceRange()[0];
leftMedium = leftCorner + 20;
return [leftCorner, leftMedium];
};
Paddle.prototype.rightEdge = function () {
var rightCorner, rightMedium;
rightCorner = this.surfaceRange()[1];
rightMedium = rightCorner - 20;
return [rightCorner, rightMedium];
};
|
var path = require('path'),
color = require('ansi-color').set;
var exit = require('../exit.js').exit;
exports.run = function(argv) {
var id = argv.id,
shell = color('neco_deactivate', 'bold+yellow');
console.log('run \''+shell+' command in your shell, :)');
exit.emit('success');
};
|
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
var Readable = require('stream').Readable;
var util = require('util');
function Router(){
EventEmitter.call(this);
this.routes = {};
}
util.inherits(Router, EventEmitter);
Router.format = Router.prototype.format = function(path){
path = path || '';
if (typeof path !== 'string') throw new TypeError('path must be a string!');
path = path
.replace(/^\/+/, '') // Remove prefixed slashes
.replace(/\\/g, '/') // Replaces all backslashes
.replace(/\?.*$/, ''); // Remove query string
// Appends `index.html` to the path with trailing slash
if (!path || path[path.length - 1] === '/'){
path += 'index.html';
}
return path;
};
Router.prototype.list = function(){
var routes = this.routes;
var keys = Object.keys(routes);
var arr = [];
var key;
for (var i = 0, len = keys.length; i < len; i++){
key = keys[i];
if (routes[key]) arr.push(key);
}
return arr;
};
Router.prototype.get = function(path){
if (typeof path !== 'string') throw new TypeError('path must be a string!');
var data = this.routes[this.format(path)];
if (data == null) return;
return new RouteStream(data);
};
Router.prototype.isModified = function(path){
if (typeof path !== 'string') throw new TypeError('path must be a string!');
var data = this.routes[this.format(path)];
return data ? data.modified : false;
};
Router.prototype.set = function(path, data_){
if (typeof path !== 'string') throw new TypeError('path must be a string!');
if (data_ == null) throw new TypeError('data is required!');
var data;
path = this.format(path);
if (typeof data_ === 'function'){
if (data_.length){
data = Promise.promisify(data_);
} else {
data = Promise.method(data_);
}
} else {
data = function(){
return Promise.resolve(data_);
};
}
// TODO: Maybe the stream can be reused?
// this.routes[path] = new RouteStream(data, data_.modified);
data.modified = data_.modified == null ? true : data_.modified;
this.routes[path] = data;
this.emit('update', path);
return this;
};
Router.prototype.remove = function(path){
if (typeof path !== 'string') throw new TypeError('path must be a string!');
path = this.format(path);
this.routes[path] = null;
this.emit('remove', path);
return this;
};
function RouteStream(data){
Readable.call(this, {objectMode: true});
this._data = data;
this._ended = false;
this.modified = data.modified;
}
util.inherits(RouteStream, Readable);
RouteStream.prototype._read = function(){
// Don't read it twice!
if (this._ended) return false;
this._ended = true;
var self = this;
this._data().then(function(data){
if (data instanceof Readable){
data.on('readable', function(){
var chunk;
// Start reading files...
while ((chunk = data.read()) !== null){
// Push data
self.push(chunk);
}
}).on('error', function(err){
self.emit('error', err);
}).on('end', function(){
// Don't forget to close the stream or the stream will keep reading
self.push(null);
});
} else if (data instanceof Buffer || typeof data === 'string'){
self.push(data);
self.push(null);
} else if (typeof data === 'object'){
self.push(JSON.stringify(data));
self.push(null);
} else {
self.push(null);
}
}, function(err){
self.emit('error', err);
});
};
module.exports = Router; |
var personalData = require('./personalData');
var webModel = require('./webModel');
var webModelFunctions = require('./webModelFunctions');
var robotModel = require('./robotModel');
const spawn = require('child_process').spawn;
var ipAddress = require('./ipAddress');
/*
To get the state of all relays:
switch_relay_name.sh all state
Use this to populate a list of relays in webModel,
and also get their names from
personalData.relays
*/
module.exports = class UsbRelay {
constructor() {
this.dataHolder = '';
this.busy = false;
this.script = __dirname + '/../scripts/switch_relay_name.sh';
}
findRelayName(relayNumber) {
for (let key in personalData.relays) {
if (personalData.relays.hasOwnProperty(key)) {
if (personalData.relays[key] === relayNumber) {
return key;
}
}
}
return 'empty';
}
updateAllRelayState() {
if (!this.busy) {
this.busy = true;
const process = spawn(this.script, ['all', 'state']);
process.stdout.on('data', (data) => {
if (data != '') {
this.dataHolder += data;
}
});
process.stderr.on('data', (data) => {
console.log(`UsbRelay output stderr: ${data}`);
});
process.on('close', (code) => {
if (code === null || code === 0) {
let linesArray = this.dataHolder.split('\n');
let relayStatusArray = [];
for (let i = 0; i < linesArray.length; i++) {
if (['ON', 'OFF'].indexOf(linesArray[i]) > -1) {
relayStatusArray.push(linesArray[i])
}
}
// WARNING: Relays are 1 indexed, not 0!
for (let i = 0; i < relayStatusArray.length; i++) {
let relayNumber = i + 1;
let relayState = relayStatusArray[i];
let relayName = this.findRelayName(relayNumber);
webModelFunctions.publishRelayState(relayNumber, relayState, relayName);
}
this.dataHolder = '';
} else {
console.log(`UsbRelay State collection failed with code: ${code}`);
console.log(this.dataHolder);
}
this.busy = false;
});
}
}
toggle(relayNumber) {
const relayObject = webModel.relays.find(x=> x.number === relayNumber);
if (relayObject) {
if (relayObject.relayOn) {
this.switch(relayNumber, 'off');
} else {
this.switch(relayNumber, 'on');
}
}
}
switch(relayNumber, onOrOff) {
this.busy = true;
const state = onOrOff.toLowerCase();
if (state !== 'on' && state !== 'off') {
return;
}
const process = spawn(this.script, [relayNumber, state]);
process.stderr.on('data', (data) => {
console.log(`UsbRelay output stderr: ${data}`);
});
process.on('close', (code) => {
if (code === null || code === 0) {
webModelFunctions.scrollingStatusUpdate(`Relay ${relayNumber} ${state}`);
} else {
console.log(`UsbRelay State collection failed with code: ${code}`);
}
this.busy = false;
});
}
};
|
/**
* Created by liushuo on 17/3/8.
*/
import React , {Component} from 'react';
import {AppRegistry , Text , View, StyleSheet, Dimensions, Image, TouchableOpacity} from 'react-native';
let {width} = Dimensions.get('window');
export default class BSBottomTopCommonCell extends Component{
constructor(props){
super(props);
}
render(){
return(
<View style={styles.containerStyle}>
<View style={styles.leftView}>
<Image source={{uri:this.props.leftIcon}} style={styles.leftIconStyle}/>
<Text style={styles.leftTitle}>{this.props.leftTitle}</Text>
</View>
<TouchableOpacity >
<View style={styles.rightView}>
<Text style={styles.rightTitle}>{this.props.rightTitle}</Text>
<Image source={{uri:'icon_cell_rightArrow'}} style={styles.rightIconStyle}/>
</View>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
containerStyle:{
backgroundColor:'white',
alignItems:'center',
flexDirection:'row',
justifyContent:'space-between',
width:width,
height:39,
borderBottomColor:'#e8e8e8',
borderBottomWidth:1
},
leftView:{
marginLeft:8,
flexDirection:'row',
alignItems:'center',
},
leftIconStyle:{
width:23,
height:23,
marginRight:5
},
leftTitle:{
fontSize:17,
},
rightIconStyle:{
width:8,
height:13,
marginLeft:2
},
rightTitle:{
color:'gray',
fontSize:13
},
rightView:{
marginRight:8,
flexDirection:'row',
alignItems:'center'
}
}) |
var lib = require("../");
var helper = require("./helper");
var nock = require("nock");
var InServiceNumber = lib.InServiceNumber;
describe("In Service Number", function(){
before(function(){
nock.disableNetConnect();
helper.setupGlobalOptions();
});
after(function(){
nock.cleanAll();
nock.enableNetConnect();
});
describe("#list", function(){
it("should return numbers", function(done){
helper.nock().get("/accounts/FakeAccountId/inserviceNumbers").reply(200, helper.xml.inServiceNumbers, {"Content-Type": "application/xml"});
InServiceNumber.list(helper.createClient(), {}, function(err, res){
if(err){
return done(err);
}
res.totalCount.should.eql(59);
res.telephoneNumbers.telephoneNumber[0].should.eql("8043024183");
done();
});
});
});
describe("#totals", function(){
it("should return totals", function(done){
helper.nock().get("/accounts/FakeAccountId/inserviceNumbers/totals").reply(200, helper.xml.inServiceNumbersTotals, {"Content-Type": "application/xml"});
InServiceNumber.totals(helper.createClient(), function(err, res){
if(err){
return done(err);
}
res.count.should.eql(3);
done();
});
});
});
describe("#get tn", function(){
it("should return tn result", function(done){
helper.nock().get("/accounts/FakeAccountId/inserviceNumbers/9195551212").reply(200);
InServiceNumber.get(helper.createClient(), "9195551212", function(err, res){
if(err){
return done(err);
}
done();
});
});
});
});
|
/**
Big I worker thread
**/
SOAR = {};
importScripts("/debug/soar/vector.js");
importScripts("/debug/soar/mesh.js");
importScripts("/debug/soar/noise.js");
importScripts("/debug/soar/space.js");
importScripts("/debug/soar/pattern.js");
//
// pattern/surface variables
//
var rng = SOAR.random.create();
var road = {};
var cliff = {};
var brush = {};
var rocks = {};
//
// dummy display variable for mesh creation
//
var display = {
gl: ""
};
/**
generate a random number for seeding other RNGs
used because seeding by time fails on startup--
all seeds will be the same. you need a "master"
seed RNG to drive all others.
@method seed
@return number, seed integer
**/
function seed() {
return Math.round(rng.get() * rng.modu);
}
/**
iterate over a 2D mesh with indexing
@method indexMesh
@param mesh object
@param il number, steps for first dimension
@param jl number, steps for second dimension
@param func function, callback to generate point field
@param wind boolean, winding order
@param op object, opaque data passed to function
**/
function indexMesh(mesh, il, jl, func, wind, op) {
var im = il - 1;
var jm = jl - 1;
var k = mesh.length / mesh.stride;
var i, j;
for (i = 0; i < il; i++) {
for (j = 0; j < jl; j++, k++) {
func(i / im, j / jm, op);
if (i < im && j < jm) {
if (wind) {
mesh.index(k, k + jl, k + 1, k + jl, k + jl + 1, k + 1);
} else {
mesh.index(k, k + 1, k + jl, k + jl, k + 1, k + jl + 1);
}
}
}
}
}
/**
perform startup initialization
@method init
@param data object, initialization parameters
**/
function init(data) {
// received height map from main thread; make line object
road.height = SOAR.space.makeLine(data.map.road, 6, 0.05);
// generate dummy mesh for vertex and texture coordinates
road.mesh = SOAR.mesh.create(display);
road.mesh.add(0, 3);
road.mesh.add(0, 2);
// received surface map from main thread; make surface object
var surf0 = SOAR.space.makeSurface(data.map.cliff, 10, 0.05, 0.1);
var surf1 = SOAR.space.makeSurface(data.map.cliff, 5, 0.25, 0.5);
var surf2 = SOAR.space.makeSurface(data.map.cliff, 1, 0.75, 1.5);
cliff.surface = function(y, z) {
return surf0(y, z) + surf1(y, z) + surf2(y, z);
};
cliff.mesh = SOAR.mesh.create(display);
cliff.mesh.add(0, 3);
cliff.mesh.add(0, 2);
// received RNG seed
brush.seed = data.seed.brush;
brush.mesh = SOAR.mesh.create(display);
brush.mesh.add(0, 3);
brush.mesh.add(0, 2);
rocks.seed = data.seed.rocks;
rocks.mesh = SOAR.mesh.create(display);
rocks.mesh.add(0, 3);
rocks.mesh.add(0, 2);
}
/**
generate all meshes and
hand back over to main UI
@method generate
@param p object, player position
**/
function generate(p) {
// lock the z-coordinate to integer boundaries
p.z = Math.floor(p.z);
// road is modulated xz-planar surface
road.mesh.reset();
indexMesh(road.mesh, 2, 64, function(xr, zr) {
var z = p.z + (zr - 0.5) * 16;
var y = road.height(z);
var x = cliff.surface(y, z) + (xr - 0.5);
road.mesh.set(x, y, z, xr, z);
}, false);
// cliff is modulated yz-planar surface
// split into section above path and below
cliff.mesh.reset();
indexMesh(cliff.mesh, 32, 64, function(yr, zr) {
var z = p.z + (zr - 0.5) * 16;
var y = road.height(z) + yr * 8;
var x = cliff.surface(y, z) + 0.5;
cliff.mesh.set(x, y, z, y, z);
}, false);
indexMesh(cliff.mesh, 32, 64, function(yr, zr) {
var z = p.z + (zr - 0.5) * 16;
var y = road.height(z) - yr * 8;
var x = cliff.surface(y, z) - 0.5;
cliff.mesh.set(x, y, z, y, z);
}, true);
// brush and rocks are generated in "cells"
// cells occur on integral z boundaries (z = 0, 1, 2, ...)
// and are populated using random seeds derived from z-value
brush.mesh.reset();
(function(mesh) {
var i, j, k;
var iz, x, y, z, a, r, s;
// 16 cells because path/cliff is 16 units long in z-direction
for (i = -8; i < 8; i++) {
iz = p.z + i;
// same random seed for each cell
rng.reseed(Math.abs(iz * brush.seed + 1));
// place 25 bits of brush at random positions/sizes
for (j = 0; j < 25; j++) {
s = rng.get() < 0.5 ? -1 : 1;
z = iz + rng.get(0, 1);
y = road.height(z) - 0.0025;
x = cliff.surface(y, z) + s * (0.5 - rng.get(0, 0.15));
r = rng.get(0.01, 0.1);
a = rng.get(0, Math.PI);
// each brush consists of 4 triangles
// rotated around the center point
for (k = 0; k < 4; k++) {
mesh.set(x, y, z, 0, 0);
mesh.set(x + r * Math.cos(a), y + r, z + r * Math.sin(a), -1, 1);
a = a + Math.PI * 0.5;
mesh.set(x + r * Math.cos(a), y + r, z + r * Math.sin(a), 1, 1);
}
}
}
})(brush.mesh);
rocks.mesh.reset();
(function(mesh) {
var o = SOAR.vector.create();
var i, j, k;
var iz, x, y, z, r, s;
var tx, ty;
for (i = -8; i < 8; i++) {
iz = p.z + i;
// same random seed for each cell--though not
// the same as the brush, or rocks would overlap!
rng.reseed(Math.abs(iz * rocks.seed + 2));
// twenty rocks per cell
for (j = 0; j < 20; j++) {
s = rng.get() < 0.5 ? -1 : 1;
z = iz + rng.get(0, 1);
y = road.height(z) - 0.005;
x = cliff.surface(y, z) + s * (0.5 - rng.get(0.02, 0.25));
r = rng.get(0.01, 0.03);
tx = rng.get(0, 5);
ty = rng.get(0, 5);
// each rock is an upturned half-sphere
indexMesh(mesh, 6, 6, function(xr, zr) {
o.x = 2 * (xr - 0.5);
o.z = 2 * (zr - 0.5);
o.y = (1 - o.x * o.x) * (1 - o.z * o.z);
o.norm().mul(r);
mesh.set(x + o.x, y + o.y, z + o.z, xr + tx, zr + ty);
}, false);
}
}
})(rocks.mesh);
// send mesh data back to main UI
postMessage({
cmd: "build-meshes",
cliff: cliff.mesh,
road: road.mesh,
brush: brush.mesh,
rocks: rocks.mesh
});
}
//
// message handling stub
//
this.addEventListener("message", function(e) {
switch(e.data.cmd) {
case "init":
init(e.data);
break;
case "generate":
generate(e.data.pos);
break;
}
}, false);
|
// flow-typed signature: b02d4e2bdae07acdc32a378268f654f9
// flow-typed version: <<STUB>>/babel-preset-react-optimize_v^1.0.1/flow_v0.39.0
/**
* This is an autogenerated libdef stub for:
*
* 'babel-preset-react-optimize'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-preset-react-optimize' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-preset-react-optimize/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'babel-preset-react-optimize/lib/index.js' {
declare module.exports: $Exports<'babel-preset-react-optimize/lib/index'>;
}
|
// Dependencies
import notification from './notification';
// Module definition
document.addEventListener('click', function(event) {
switch(event.target.id) {
case 'success':
case 'error':
case 'info':
case 'help':
case 'globe':
case 'fixed':
case 'loading':
notification.add('some text here', {
'type': event.target.id
});
break;
case 'remove':
notification.destroy();
break;
}
});
|
/*
Copyright (c) 2014, Pixel & Tonic, Inc.
@license http://buildwithcraft.com/license Craft License Agreement
@link http://buildwithcraft.com
*/
(function(a){Craft.EntryTypeSwitcher=Garnish.Base.extend({$form:null,$typeSelect:null,$spinner:null,$fields:null,init:function(){this.$form=a("#entry-form");this.$typeSelect=a("#entryType");this.$spinner=a('<div class="spinner hidden" style="margin-left: 5px;"/>').insertAfter(this.$typeSelect.parent());this.$fields=a("#fields");this.addListener(this.$typeSelect,"change","onTypeChange")},onTypeChange:function(e){this.$spinner.removeClass("hidden");Craft.postActionRequest("entries/switchEntryType",
this.$form.serialize(),a.proxy(function(b,d){this.$spinner.addClass("hidden");if("success"==d){Craft.cp.deselectContentTab();Craft.cp.$contentTabsContainer.html(b.tabsHtml);this.$fields.html(b.fieldsHtml);Craft.cp.initContentTabs();Craft.initUiElements(this.$fields);var c="";b.headHtml&&(c+=b.headHtml);b.footHtml&&(c+=b.footHtml);c&&a(c).appendTo(Garnish.$bod);slugGenerator.setNewSource("#title")}},this))}})})(jQuery);
//# sourceMappingURL=EntryTypeSwitcher.min.map
|
$(document).ready(function(){
var x = $(document).width();
var y = $(document).height();
var containerW = x-40;
var containerH = y-40;
//$("#myApp").width(containerW);
//$("#myApp").height(containerH);
/*var pstyle = 'background-color: #F5F6F7; border: 1px solid #dfdfdf; padding: 5px;';
$('#myLayout').w2layout({
name: 'myLayout',
panels: [
{ type: 'top', width: '100%', height: '10%', style: pstyle},
{ type: 'bottom', width: '100%', height: '10%', resizable: true, style: pstyle },
{ type: 'main', width: '80%', style: pstyle },
]
});*/
}); |
var format = require('util').format;
var debug = require('debug')('qufoxMonitor');
var MongoClient = require('mongodb').MongoClient;
var async = require('async');
var TcpSocketServer = require('./TcpSocketServer');
var Database = require('./Database');
var WebServer = require('./WebServer');
var HttpServer = require('./HttpServer');
var WebSocketServer = require('./WebSocketServer');
var mongodbUrl = 'mongodb://127.0.0.1:27017/qufoxMonitor';
var tcpServerPort = 3200;
var port = 3300;
var database = new Database(mongodbUrl);
var tcpServer = new TcpSocketServer(tcpServerPort);
var webServer = new WebServer();
var httpServer = new HttpServer(port, webServer);
var socketServer = new WebSocketServer(httpServer);
async.waterfall([
function (callback) { database.connect(callback); },
function (callback) { httpServer.listen(callback); },
function (callback) { tcpServer.listen(callback); }
],
function (err, result) {
if (err) {
debug(err);
}
else {
startProcess();
}
});
function startProcess(){
tcpServer.on('data', function (data) {
database.AddTelegram(data);
socketServer.broadcast('data', data);
});
}
// debug('Try Mongodb connect ... (' + mongodbUrl + ')');
// MongoClient.connect(mongodbUrl, function(err, db) {
// if(err) {
// debug('Mongodb connection Error - ' + err);
// process.exit(1);
// }
// debug('Mongodb connected.');
// var tcpServer = new TcpSocketServer(tcpServerPort);
// tcpServer.on('data', function (telegram){
// if (!telegram || !telegram.type || !telegram.data) {
// debug('Bad telegram format.');
// }
// else
// {
// var type = telegram.type;
// delete telegram.type;
// db.collection(type).insert(telegram, function (err, docs){
// if (err) {
// debug('collection['+type+'] insert Error - ' + err);
// }
// });
// }
// });
// });
|
const functions = require('firebase-functions');
const cors = require('cors');
const BASE = functions.config().legionassult.base;
const base = parseInt(+new Date(BASE) / 1000, 10);
const calcAssultTime = require('./utils/calcAssultTime')(base);
const corsOptions = {
origin: true,
methods: 'GET',
exposedHeaders: 'Date'
};
module.exports = function legionAssultTime() {
return functions.https.onRequest((req, res) => {
if (req.method !== 'GET') {
res.status(403).send('Forbidden!');
}
(cors(corsOptions))(req, res, () => {
/**
* api parameters
*
* start - starting time (any Date object formate)
* count - number of assult times returned
* callback - jsonp support callback function name
*/
const startFrom = (
req.query.start
? +new Date(req.query.start)
: +new Date()
) / 1000;
const count = Number(req.query.count || 5);
const assults = calcAssultTime(startFrom, count);
res
.status(200)
.set({
'Cache-Control': 'public, max-age=3600'
})
.jsonp({
start: startFrom,
count,
assults
});
});
});
};
|
/**
* Copyright (c) Microsoft. All rights reserved.
*
* 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.
*/
// Module dependencies.
var url = require('url');
var WrapTokenManager = require('./wraptokenmanager');
var Constants = require('../../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var ServiceBusConstants = Constants.ServiceBusConstants;
/**
* Creates a new Wrap object.
*
* @param {string} acsHost The access control host.
* @param {string} issuer The service bus issuer.
* @param {string} accessKey The service bus issuer password.
*/
function Wrap(acsHost, issuer, accessKey) {
this.acsHost = acsHost;
this.issuer = issuer;
this.accessKey = accessKey;
this.wrapTokenManager = new WrapTokenManager(acsHost, issuer, accessKey);
}
/**
* Signs a request with the Authentication header.
*
* @param {WebResource} The webresource to be signed.
* @return {undefined}
*/
Wrap.prototype.signRequest = function (webResource, callback) {
var parsedUrl = url.parse(webResource.uri);
parsedUrl.protocol = 'http:';
delete parsedUrl.path;
delete parsedUrl.host;
delete parsedUrl.port;
var requestUrl = url.format(parsedUrl);
this.wrapTokenManager.getAccessToken(requestUrl, function (error, accessToken) {
if (!error) {
webResource.withHeader(HeaderConstants.AUTHORIZATION,
'WRAP access_token=\"' + accessToken[ServiceBusConstants.WRAP_ACCESS_TOKEN] + '\"');
}
callback(error);
});
};
module.exports = Wrap; |
/*
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint node: true */
/*global document: true, window:true, esprima: true, testReflect: true */
var runTests;
/**
* Description
* @method getContext
* @param {} esprima
* @param {} reportCase
* @param {} reportFailure
* @return ObjectExpression
*/
function getContext(esprima, reportCase, reportFailure) {
'use strict';
var Reflect, Pattern;
// Maps Mozilla Reflect object to our Esprima parser.
Reflect = {
/**
* Description
* @method parse
* @param {} code
* @return result
*/
parse: function (code) {
var result;
reportCase(code);
try {
result = esprima.parse(code);
} catch (error) {
result = error;
}
return result;
}
};
// This is used by Reflect test suite to match a syntax tree.
/**
* Description
* @param {} obj
* @return pattern
*/
Pattern = function (obj) {
var pattern;
// Poor man's deep object cloning.
pattern = JSON.parse(JSON.stringify(obj));
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
if (obj.type && obj.type === 'Literal') {
if (obj.value instanceof RegExp) {
pattern = {
type: obj.type,
value: obj.value.toString()
};
}
}
// Special handling for branch statement because SpiderMonkey
// prefers to put the 'alternate' property before 'consequent'.
if (obj.type && obj.type === 'IfStatement') {
pattern = {
type: pattern.type,
test: pattern.test,
consequent: pattern.consequent,
alternate: pattern.alternate
};
}
// Special handling for do while statement because SpiderMonkey
// prefers to put the 'test' property before 'body'.
if (obj.type && obj.type === 'DoWhileStatement') {
pattern = {
type: pattern.type,
body: pattern.body,
test: pattern.test
};
}
/**
* Description
* @method adjustRegexLiteralAndRaw
* @param {} key
* @param {} value
* @return value
*/
function adjustRegexLiteralAndRaw(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
} else if (key === 'raw' && typeof value === "string") {
// Ignore Esprima-specific 'raw' property.
return undefined;
}
return value;
}
if (obj.type && (obj.type === 'Program')) {
/**
* Description
* @method assert
* @param {} tree
* @return
*/
pattern.assert = function (tree) {
var actual, expected;
actual = JSON.stringify(tree, adjustRegexLiteralAndRaw, 4);
expected = JSON.stringify(obj, null, 4);
if (expected !== actual) {
reportFailure(expected, actual);
}
};
}
return pattern;
};
return {
Reflect: Reflect,
Pattern: Pattern
};
}
if (typeof window !== 'undefined') {
// Run all tests in a browser environment.
/**
* Description
* @return
*/
runTests = function () {
'use strict';
var total = 0,
failures = 0;
/**
* Description
* @method setText
* @param {} el
* @param {} str
* @return
*/
function setText(el, str) {
if (typeof el.innerText === 'string') {
el.innerText = str;
} else {
el.textContent = str;
}
}
/**
* Description
* @method reportCase
* @param {} code
* @return
*/
function reportCase(code) {
var report, e;
report = document.getElementById('report');
e = document.createElement('pre');
e.setAttribute('class', 'code');
setText(e, code);
report.appendChild(e);
total += 1;
}
/**
* Description
* @method reportFailure
* @param {} expected
* @param {} actual
* @return
*/
function reportFailure(expected, actual) {
var report, e;
failures += 1;
report = document.getElementById('report');
e = document.createElement('p');
setText(e, 'Expected');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'expected');
setText(e, expected);
report.appendChild(e);
e = document.createElement('p');
setText(e, 'Actual');
report.appendChild(e);
e = document.createElement('pre');
e.setAttribute('class', 'actual');
setText(e, actual);
report.appendChild(e);
}
setText(document.getElementById('version'), esprima.version);
window.setTimeout(function () {
var tick, context = getContext(esprima, reportCase, reportFailure);
tick = new Date();
testReflect(context.Reflect, context.Pattern);
tick = (new Date()) - tick;
if (failures > 0) {
setText(document.getElementById('status'), total + ' tests. ' +
'Failures: ' + failures + '. ' + tick + ' ms');
} else {
setText(document.getElementById('status'), total + ' tests. ' +
'No failure. ' + tick + ' ms');
}
}, 513);
};
} else {
(function (global) {
'use strict';
var esprima = require('../esprima'),
tick,
total = 0,
failures = [],
header,
current,
context;
/**
* Description
* @method reportCase
* @param {} code
* @return
*/
function reportCase(code) {
total += 1;
current = code;
}
/**
* Description
* @method reportFailure
* @param {} expected
* @param {} actual
* @return
*/
function reportFailure(expected, actual) {
failures.push({
source: current,
expected: expected.toString(),
actual: actual.toString()
});
}
context = getContext(esprima, reportCase, reportFailure);
tick = new Date();
require('./reflect').testReflect(context.Reflect, context.Pattern);
tick = (new Date()) - tick;
header = total + ' tests. ' + failures.length + ' failures. ' +
tick + ' ms';
if (failures.length) {
console.error(header);
failures.forEach(function (failure) {
console.error(failure.source + ': Expected\n ' +
failure.expected.split('\n').join('\n ') +
'\nto match\n ' + failure.actual);
});
} else {
console.log(header);
}
process.exit(failures.length === 0 ? 0 : 1);
}(this));
}
/* vim: set sw=4 ts=4 et tw=80 : */
|
angular.module('dmsApp').controller('personRolesController', function($scope, $state, personRoleService, personService, documentService) {
$scope.personRoles = [];
$scope.personRole = {};
$scope.documents = [];
$scope.persons = [];
$scope.tmp = {};
$scope.loadPersonRoles = function(){
personRoleService.query(function(personRoles){
$scope.personRoles = personRoles;
});
};
$scope.createNewPersonRole = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
personRoleService.save($scope.personRole, function(){
$('#createPersonRoleModal').modal('hide');
$scope.loadPersonRoles();
$scope.personRole = {};
});
};
$scope.delete = function(id){
personRoleService.delete({id: id}, function(){
$scope.loadPersonRoles();
})
};
$scope.createNewPersonRoleDocumentRelationship = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
$scope.personRole.referes_to.push($scope.tmp.document);
$scope.tmp.document = {};
$('#createNewPersonRoleDocumentRelationshipModal').modal('hide');
};
$scope.createNewPersonRolePersonRelationship = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
$scope.personRole.is_role_of = $scope.tmp.person;
$scope.tmp = {};
$('#createNewPersonRolePersonRelationshipModal').modal('hide');
};
$scope.showPersonRoleDocumentRelationsModal = function(){
documentService.query(function(documents){
$scope.documents = documents;
});
};
$scope.showPersonRolePersonRelationsModal = function(){
personService.query(function(persons){
$scope.persons = persons;
});
};
$scope.hideUpperModal = function(){
$('#createNewPersonRoleDocumentRelationshipModal').modal('hide');
$('#createNewPersonRolePersonRelationshipModal').modal('hide');
};
//initial
$scope.loadPersonRoles();
});
angular.module('dmsApp').controller('personRoleDetailsController', function($scope, $stateParams, personRoleService, personService, documentService) {
$scope.personRole = {};
$scope.documents = [];
$scope.persons = [];
$scope.tmp = {};
$scope.loadPersonRole = function(id){
personRoleService.get({id: id}, function(personRole){
$scope.personRole = personRole;
});
};
$scope.update = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
personRoleService.update($scope.personRole, function(response){
$scope.personRole = response;
});
};
$scope.createNewPersonRoleDocumentRelationship = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
$scope.personRole.referes_to.push($scope.tmp.document);
$scope.tmp.document = {};
$('#createNewPersonRoleDocumentRelationshipModal').modal('hide');
};
$scope.createNewPersonRolePersonRelationship = function(){
if(!$scope.personRole.referes_to){
$scope.personRole.referes_to = [];
}
if(!$scope.personRole.is_role_of){
$scope.personRole.is_role_of = {};
}
$scope.personRole.is_role_of = $scope.tmp.person;
$scope.tmp = {};
$('#createNewPersonRolePersonRelationshipModal').modal('hide');
};
$scope.showPersonRoleDocumentRelationsModal = function(){
documentService.query(function(documents){
$scope.documents = documents;
});
};
$scope.showPersonRolePersonRelationsModal = function(){
personService.query(function(persons){
$scope.persons = persons;
});
};
//initial
$scope.loadPersonRole($stateParams.id);
});
|
import normaliseKeypath from 'utils/normaliseKeypath';
import resolveRef from 'shared/resolveRef';
var options = {
capture: true, // top-level calls should be intercepted
noUnwrap: true // wrapped values should NOT be unwrapped
};
export default function Ractive$get ( keypath ) {
var value;
keypath = normaliseKeypath( keypath );
value = this.viewmodel.get( keypath, options );
// Create inter-component binding, if necessary
if ( value === undefined && this.parent && !this.isolated ) {
if ( resolveRef( this, keypath, this.fragment ) ) { // creates binding as side-effect, if appropriate
value = this.viewmodel.get( keypath );
}
}
return value;
}
|
import requireDir from 'require-dir';
import Waterline from 'waterline';
const models = requireDir();
const waterline = new Waterline();
Object.keys(models).forEach((name) => {
waterline.loadCollection(models[name].default);
});
export default {
waterline,
};
|
(function ($) {
"use strict";
/**
* Hero module implementation.
*
* @author Terrific Composer
* @namespace Tc.Module
* @class Hero
* @extends Tc.Module
*/
Tc.Module.Hero = Tc.Module.extend({
/**
* Initializes the Hero module.
*
* @method init
* @return {void}
* @constructor
* @param {jQuery} $ctx the jquery context
* @param {Sandbox} sandbox the sandbox to get the resources from
* @param {Number} id the unique module id
*/
init:function ($ctx, sandbox, id) {
// call base constructor
this._super($ctx, sandbox, id);
},
/**
* Hook function to do all of your module stuff.
*
* @method on
* @param {Function} callback function
* @return void
*/
on:function (callback) {
var $ctx = this.$ctx,
self = this;
// extract the name and provide the default greeting
$('.message', $ctx).val('Hi, I am ' + $('pre', $ctx).data('name'));
// bind the submit event on the form
$('form', $ctx).bind('submit', function () {
var name = $('pre', $ctx).data('name'),
message = $('.message', $ctx).val();
// write the current message in the bubble and notify the others
self.fire('message', { name:name, message:message}, function () {
$('.bubble', $ctx).text(message);
});
return false;
});
callback();
},
/**
* Hook function to trigger your events.
*
* @method after
* @return void
*/
after:function () {
var $ctx = this.$ctx;
// trigger the first submit to write the default message in the bubble
$('form', $ctx).trigger('submit');
},
/**
* Handles the incoming messages from the other superheroes
*/
onMessage:function (data) {
var $ctx = this.$ctx;
data = data || {};
if (data.name && data.message) {
$('.bubble', $ctx).text(data.name + ' said: ' + data.message);
}
}
});
})(Tc.$);
|
var mongoose = require('mongoose'),
shortid = require('shortid'),
helpers = require('./model_helpers'),
broadcast = require('./broadcast'),
chat = require('./chat'),
skill = require('./skill'),
job = require('./job'),
project = require('./project'),
Schema = mongoose.Schema,
ObjectId = Schema.Types.ObjectId;
var user = new Schema({
_id: {
type: String,
default: shortid.generate
},
username: {
type: String,
required: true,
unique: true
},
passwordHash: {
type: String,
required: true
},
twoFactorMethod: {
type: String,
default: ""
},
name: {
type: String,
default: ""
},
avatar: {
// path to the image
type: String,
default: "/images/users/placeholder.png"
},
title: {
type: String,
default: ""
},
skillTags: [{
type: skill,
default: []
}],
bio: {
type: String,
default: ""
},
tags: [{
type: String,
default: []
}],
email: {
type: String ,
required: true
},
isVerified: {
type: Boolean,
default: false
},
timeVerified: {
type: Date
},
powerLevel: {
type: Number,
default: 0
},
url: {
type: String,
default: ""
},
// Refer to http://stackoverflow.com/questions/4677237
// for further explanation of why this is the case
followings: [{
type: ObjectId,
default: []
}],
followers: [{
type: ObjectId,
ref: 'User',
default: []
}],
numFollowers: {
type: Number,
default: 0
},
chats: [{
type: chat,
default: []
}],
messageBoard: [{
type: broadcast,
default: []
}],
blocked: [{
type: ObjectId,
ref: 'User',
default: []
}],
jobs: [{
type: String,
ref: 'Job',
default: []
}],
projects: [{
type: String,
ref: 'Project',
default: []
}],
frozen: [{
type: Boolean,
default: false
}],
times_frozen: [{
type: Number,
default: 0
}],
googleId: [{
type: String,
default: ""
}],
githubId: [{
type: String,
default: ""
}],
google: {
id: String,
token: String,
email: String,
name: String
}
}, { collection : 'users', timestamps: true });
user.statics.findByUsername =
helpers.finderForProperty("username", { findOne: true, caseInsensitive: true });
user.statics.findByName =
helpers.finderForProperty("name", { findOne: true, caseInsensitive: false });
user.statics.findByEmail =
helpers.finderForProperty("email", { findOne: true, caseInsensitive: false });
user.statics.findByJobs =
helpers.finderForProperty("jobs", { findOne: false, caseInsensitive: true });
user.statics.findByTag =
helpers.finderForProperty("tags", { findOne: false, caseInsensitive: false });
user.statics.findBySkill =
helpers.finderForProperty("skillTags", { findOne: false, caseInsensitive: false });
module.exports = mongoose.model('User', user);
|
// Compiled by ClojureScript 0.0-2322
goog.provide('clojure.browser.repl');
goog.require('cljs.core');
goog.require('clojure.browser.event');
goog.require('clojure.browser.event');
goog.require('clojure.browser.net');
goog.require('clojure.browser.net');
clojure.browser.repl.xpc_connection = cljs.core.atom.call(null,null);
clojure.browser.repl.repl_print = (function repl_print(data){var temp__4124__auto__ = cljs.core.deref.call(null,clojure.browser.repl.xpc_connection);if(cljs.core.truth_(temp__4124__auto__))
{var conn = temp__4124__auto__;return clojure.browser.net.transmit.call(null,conn,new cljs.core.Keyword(null,"print","print",1299562414),cljs.core.pr_str.call(null,data));
} else
{return null;
}
});
/**
* Process a single block of JavaScript received from the server
*/
clojure.browser.repl.evaluate_javascript = (function evaluate_javascript(conn,block){var result = (function (){try{return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"status","status",-1997798413),new cljs.core.Keyword(null,"success","success",1890645906),new cljs.core.Keyword(null,"value","value",305978217),(''+cljs.core.str.cljs$core$IFn$_invoke$arity$1(eval(block)))], null);
}catch (e10821){var e = e10821;return new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"status","status",-1997798413),new cljs.core.Keyword(null,"exception","exception",-335277064),new cljs.core.Keyword(null,"value","value",305978217),cljs.core.pr_str.call(null,e),new cljs.core.Keyword(null,"stacktrace","stacktrace",-95588394),(cljs.core.truth_(e.hasOwnProperty("stack"))?e.stack:"No stacktrace available.")], null);
}})();return cljs.core.pr_str.call(null,result);
});
clojure.browser.repl.send_result = (function send_result(connection,url,data){return clojure.browser.net.transmit.call(null,connection,url,"POST",data,null,(0));
});
/**
* Send data to be printed in the REPL. If there is an error, try again
* up to 10 times.
*/
clojure.browser.repl.send_print = (function() {
var send_print = null;
var send_print__2 = (function (url,data){return send_print.call(null,url,data,(0));
});
var send_print__3 = (function (url,data,n){var conn = clojure.browser.net.xhr_connection.call(null);clojure.browser.event.listen.call(null,conn,new cljs.core.Keyword(null,"error","error",-978969032),((function (conn){
return (function (_){if((n < (10)))
{return send_print.call(null,url,data,(n + (1)));
} else
{return console.log(("Could not send "+cljs.core.str.cljs$core$IFn$_invoke$arity$1(data)+" after "+cljs.core.str.cljs$core$IFn$_invoke$arity$1(n)+" attempts."));
}
});})(conn))
);
return clojure.browser.net.transmit.call(null,conn,url,"POST",data,null,(0));
});
send_print = function(url,data,n){
switch(arguments.length){
case 2:
return send_print__2.call(this,url,data);
case 3:
return send_print__3.call(this,url,data,n);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
send_print.cljs$core$IFn$_invoke$arity$2 = send_print__2;
send_print.cljs$core$IFn$_invoke$arity$3 = send_print__3;
return send_print;
})()
;
clojure.browser.repl.order = cljs.core.atom.call(null,(0));
clojure.browser.repl.wrap_message = (function wrap_message(t,data){return cljs.core.pr_str.call(null,new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"type","type",1174270348),t,new cljs.core.Keyword(null,"content","content",15833224),data,new cljs.core.Keyword(null,"order","order",-1254677256),cljs.core.swap_BANG_.call(null,clojure.browser.repl.order,cljs.core.inc)], null));
});
/**
* Start the REPL server connection.
*/
clojure.browser.repl.start_evaluator = (function start_evaluator(url){var temp__4124__auto__ = clojure.browser.net.xpc_connection.call(null);if(cljs.core.truth_(temp__4124__auto__))
{var repl_connection = temp__4124__auto__;var connection = clojure.browser.net.xhr_connection.call(null);clojure.browser.event.listen.call(null,connection,new cljs.core.Keyword(null,"success","success",1890645906),((function (connection,repl_connection,temp__4124__auto__){
return (function (e){return clojure.browser.net.transmit.call(null,repl_connection,new cljs.core.Keyword(null,"evaluate-javascript","evaluate-javascript",-315749780),e.currentTarget.getResponseText(cljs.core.List.EMPTY));
});})(connection,repl_connection,temp__4124__auto__))
);
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"send-result","send-result",35388249),((function (connection,repl_connection,temp__4124__auto__){
return (function (data){return clojure.browser.repl.send_result.call(null,connection,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"result","result",1415092211),data));
});})(connection,repl_connection,temp__4124__auto__))
);
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"print","print",1299562414),((function (connection,repl_connection,temp__4124__auto__){
return (function (data){return clojure.browser.repl.send_print.call(null,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"print","print",1299562414),data));
});})(connection,repl_connection,temp__4124__auto__))
);
clojure.browser.net.connect.call(null,repl_connection,cljs.core.constantly.call(null,null));
return setTimeout(((function (connection,repl_connection,temp__4124__auto__){
return (function (){return clojure.browser.repl.send_result.call(null,connection,url,clojure.browser.repl.wrap_message.call(null,new cljs.core.Keyword(null,"ready","ready",1086465795),"ready"));
});})(connection,repl_connection,temp__4124__auto__))
,(50));
} else
{return alert("No 'xpc' param provided to child iframe.");
}
});
/**
* Connects to a REPL server from an HTML document. After the
* connection is made, the REPL will evaluate forms in the context of
* the document that called this function.
*/
clojure.browser.repl.connect = (function connect(repl_server_url){var repl_connection = clojure.browser.net.xpc_connection.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"peer_uri","peer_uri",910305997),repl_server_url], null));cljs.core.swap_BANG_.call(null,clojure.browser.repl.xpc_connection,cljs.core.constantly.call(null,repl_connection));
clojure.browser.net.register_service.call(null,repl_connection,new cljs.core.Keyword(null,"evaluate-javascript","evaluate-javascript",-315749780),((function (repl_connection){
return (function (js){return clojure.browser.net.transmit.call(null,repl_connection,new cljs.core.Keyword(null,"send-result","send-result",35388249),clojure.browser.repl.evaluate_javascript.call(null,repl_connection,js));
});})(repl_connection))
);
return clojure.browser.net.connect.call(null,repl_connection,cljs.core.constantly.call(null,null),((function (repl_connection){
return (function (iframe){return iframe.style.display = "none";
});})(repl_connection))
);
});
|
// Adapted from Vue CLI v2 "init" command
const kolorist = require('kolorist')
const Metalsmith = require('metalsmith')
const Handlebars = require('handlebars')
const async = require('async')
const render = require('consolidate').handlebars.render
const path = require('path')
const multimatch = require('multimatch')
const getOptions = require('./options')
const ask = require('./ask')
const filter = require('./filter')
const logger = require('./logger')
// register handlebars helper
Handlebars.registerHelper('if_eq', function (a, b, opts) {
return a === b
? opts.fn(this)
: opts.inverse(this)
})
Handlebars.registerHelper('unless_eq', function (a, b, opts) {
return a === b
? opts.inverse(this)
: opts.fn(this)
})
/**
* Generate a template given a `src` and `dest`.
*
* @param {String} name
* @param {String} src
* @param {String} dest
* @param {Function} done
*/
module.exports = function generate (name, src, dest, done) {
const opts = getOptions(name, src)
const metalsmith = Metalsmith(path.join(src, 'template'))
const data = Object.assign(metalsmith.metadata(), {
destDirName: name,
inPlace: dest === process.cwd(),
noEscape: true
})
opts.helpers && Object.keys(opts.helpers).map(key => {
Handlebars.registerHelper(key, opts.helpers[key])
})
const helpers = { chalk: kolorist, logger }
if (opts.metalsmith && typeof opts.metalsmith.before === 'function') {
opts.metalsmith.before(metalsmith, opts, helpers)
}
metalsmith.use(askQuestions(opts.prompts))
.use(filterFiles(opts.filters))
.use(renderTemplateFiles(opts.skipInterpolation))
if (typeof opts.metalsmith === 'function') {
opts.metalsmith(metalsmith, opts, helpers)
}
else if (opts.metalsmith && typeof opts.metalsmith.after === 'function') {
opts.metalsmith.after(metalsmith, opts, helpers)
}
metalsmith.clean(false)
.source('.') // start from template root instead of `./src` which is Metalsmith's default for `source`
.destination(dest)
.build((err, files) => {
done(err)
if (typeof opts.complete === 'function') {
const helpers = { chalk: kolorist, logger, files }
opts.complete(data, helpers)
}
else {
logMessage(opts.completeMessage, data)
}
})
return data
}
/**
* Create a middleware for asking questions.
*
* @param {Object} prompts
* @return {Function}
*/
function askQuestions (prompts) {
return (files, metalsmith, done) => {
ask(prompts, metalsmith.metadata(), done)
}
}
/**
* Create a middleware for filtering files.
*
* @param {Object} filters
* @return {Function}
*/
function filterFiles (filters) {
return (files, metalsmith, done) => {
filter(files, filters, metalsmith.metadata(), done)
}
}
/**
* Template in place plugin.
*
* @param {Object} files
* @param {Metalsmith} metalsmith
* @param {Function} done
*/
function renderTemplateFiles (skipInterpolation) {
skipInterpolation = typeof skipInterpolation === 'string'
? [skipInterpolation]
: skipInterpolation
return (files, metalsmith, done) => {
const keys = Object.keys(files)
const metalsmithMetadata = metalsmith.metadata()
async.each(keys, (file, next) => {
// skipping files with skipInterpolation option
if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
return next()
}
const str = files[file].contents.toString()
// do not attempt to render files that do not have mustaches
if (!/{{([^{}]+)}}/g.test(str)) {
return next()
}
render(str, metalsmithMetadata, (err, res) => {
if (err) {
err.message = `[${file}] ${err.message}`
return next(err)
}
files[file].contents = Buffer.from(res)
next()
})
}, done)
}
}
/**
* Display template complete message.
*
* @param {String} message
* @param {Object} data
*/
function logMessage (message, data) {
if (!message) return
render(message, data, (err, res) => {
if (err) {
console.error('\n Error when rendering template complete message: ' + err.message.trim())
}
else {
console.log('\n' + res.split(/\r?\n/g).map(line => ' ' + line).join('\n'))
}
})
}
|
describe('Game service', function () {
beforeEach(angular.mock.module('sevenWonders.core.game'));
beforeEach(angular.mock.module('sevenWonders.core.model'));
beforeEach(module(function ($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
}));
beforeEach(inject(function (_UserModel_,_Game_, _Restangular_, _$q_, _$exceptionHandler_, _$httpBackend_, _Auth_) {
$q = _$q_;
deferred = $q.defer();
Restangular = _Restangular_;
$exceptionHandler = _$exceptionHandler_;
exception = _$exceptionHandler_;
$httpBackend = _$httpBackend_;
Auth = _Auth_;
Game = _Game_;
UserModel = _UserModel_;
}));
it('Should exist', function () {
expect(Game).toBeDefined();
});
describe('.getAvailableGames', function () {
var mockedgameModel = {
id: 1,
roomName: 'Jhon',
channel: 4,
type: 'Babilon',
numberPlayers: 7
};
var mockedgameModel2 = {
id: 2,
roomName: 'Snow',
channel: 4,
type: 'Ephesos',
numberPlayers: 3
};
var mockedGames = [mockedgameModel, mockedgameModel2];
it('should exist', function () {
expect(Game.getAvailableGames).toBeDefined();
});
it('should return an empty list of games', function () {
spyOn(Game, 'getAvailableGames').and.returnValue(deferred.promise);
deferred.resolve([]);
var expected = Game.getAvailableGames().$$state.value;
expect(expected).toEqual([]);
});
it('should not let return an empty list of games', function () {
spyOn(Game, 'getAvailableGames').and.returnValue(deferred.promise);
deferred.reject();
var expected = Game.getAvailableGames().$$state.value;
expect(expected).toBe(undefined);
});
});
describe('.create', function () {
var mockGame = {
gameSetting: mockGameSetting,
token: 'bla bla bla',
id: '8569235'
}
var mockGameSetting = {
maxPlayers: 5,
roomName: 'Light',
owner: 'Gonzalo'
}
it('Should exist', function () {
expect(Game.create).toBeDefined();
});
it('should return exception when trying to create an undefinde gameSetting', function () {
expect($exceptionHandler.errors).toEqual([]);
try {
Game.create(undefined);
} catch (e) {
$exceptionHandler(e);
}
expect($exceptionHandler.errors).toEqual(['gameSetting is not defined!!.']);
});
it('Should accept to create a Game', function () {
spyOn(Game, 'create').and.returnValue(deferred.promise);
deferred.resolve(mockGame);
expect(Game.create(mockGameSetting).$$state.value).toEqual(mockGame);
});
it('Should reject to create a Game', function () {
spyOn(Game, 'create').and.returnValue(deferred.promise);
deferred.reject();
expect(Game.create(mockGameSetting).$$state.value).toBe(undefined);
});
});
describe('.join', function () {
var mockedPlayer = {
id: 1
};
var player = {
id: 4,
userName: 'fpfo',
token: 896
}
it('should exist', function () {
expect(Game.join).toBeDefined();
});
it('should return exception when trying to create an undefinde gameSetting', function () {
expect(exception.errors).toEqual([]);
try {
Game.join(undefined);
} catch (e) {
exception(e);
}
expect(exception.errors).toEqual(['game is not defined!!.']);
});
it('Should reject to create a Game', function () {
spyOn(Restangular.service('games'), 'one').and.callThrough();
spyOn(Auth, 'getLoggedUser').and.returnValue(player);
$httpBackend.expectPOST('/games/1/players', mockedPlayer).respond(undefined);
var runGame = Game.join(mockedPlayer);
expect(runGame.$$state.status).toBe(0);
});
});
}); |
/*
* 存放错误记录
*/
const Sequelize = require('sequelize');
module.exports = (db) => {
return db.define('logtable', {
/* 订单价格 */
totalCost: {
type: Sequelize.DECIMAL(10, 2)
},
orderId: {
type: Sequelize.INTEGER,
unique: true
},
/*买家付款*/
buyerPay: {
type: Sequelize.DECIMAL(10, 2)
},
/*卖家收款*/
sellerGet: {
type: Sequelize.DECIMAL(10, 2)
},
/* 状态 */
status: {
type: Sequelize.INTEGER
},
/*错误类型*/
wrongStatus:{
type: Sequelize.INTEGER
},
/*infomation*/
info:{
type: Sequelize.STRING
},
/*买家卖家id,转账id*/
});
};
|
$(document).ready(function(){
$('#dataProductos').DataTable( {
dom: 'Bfrtlip',
responsive: true,
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [2,3,4,5]
}
}
],
columnDefs: [
{
targets: [0,1],
visible: false,
searchable: false
},
],
"language":
{
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
}
} );
});
|
declare module pg {
// Note: Currently There are some issues in Function overloading.
// https://github.com/facebook/flow/issues/2423
// So i temporarily remove the
// `((event: string, listener: Function) => EventEmitter );`
// from all overloading for EventEmitter.on().
// `any` types exised in this file, cause of currently `mixed` did not work well
// in Function Overloading.
// `Function` types exised in this file, cause of they come from another
// untyped npm lib.
/* Cause of <flow 0.36 did not support export type very well,
// so copy the types from pg-pool
// https://github.com/flowtype/flow-typed/issues/16
// https://github.com/facebook/flow/commit/843389f89c69516506213e298096a14867a45061
const Pool = require('pg-pool');
import type {
PgPoolConfig,
PoolConnectCallback,
DoneCallback,
PoolClient
} from 'pg-pool';
*/
// ------------- copy from 'pg-pool' ------------>>
/*
* PgPoolConfig's properties are passed unchanged to both
* the node-postgres Client constructor and the node-pool constructor
* allowing you to fully configure the behavior of both
* node-pool (https://github.com/coopernurse/node-pool)
*/
declare type PgPoolConfig = {
// node-pool ----------------
name: string,
create: Function,
destroy: Function,
max: number,
min: number,
refreshIdle: boolean,
idleTimeoutMillis: number,
connectionTimeoutMillis: number,
reapIntervalMillis: number,
returnToHead: boolean,
priorityRange: number,
validate: Function,
validateAsync: Function,
log: Function,
// node-postgres Client ------
//database user's name
user: string,
//name of database to connect
database: string,
//database user's password
password: string,
//database port
port: number,
// database host. defaults to localhost
host?: string,
// whether to try SSL/TLS to connect to server. default value: false
ssl?: boolean,
// name displayed in the pg_stat_activity view and included in CSV log entries
// default value: process.env.PGAPPNAME
application_name?: string,
// fallback value for the application_name configuration parameter
// default value: false
fallback_application_name?: string,
// max milliseconds any query using this connection will execute for before timing out in error. false=unlimited
// default value: false
statement_timeout?: boolean | number,
// pg-pool
Client: mixed,
Promise: mixed,
onCreate: Function,
};
/*
* Not extends from Client, cause some of Client's functions(ex: connect and end)
* should not be used by PoolClient (which returned from Pool.connect).
*/
declare type PoolClient = {
release(error?: mixed): void,
query:
( (query: QueryConfig|string, callback?: QueryCallback) => Query ) &
( (text: string, values: Array<any>, callback?: QueryCallback) => Query ),
on:
((event: 'drain', listener: () => void) => events$EventEmitter )&
((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter )&
((event: 'notification', listener: (message: any) => void) => events$EventEmitter )&
((event: 'notice', listener: (message: any) => void) => events$EventEmitter )&
((event: 'end', listener: () => void) => events$EventEmitter ),
}
declare type PoolConnectCallback = (error: PG_ERROR|null,
client: PoolClient|null, done: DoneCallback) => void;
declare type DoneCallback = (error?: mixed) => void;
// https://github.com/facebook/flow/blob/master/lib/node.js#L581
// on() returns a events$EventEmitter
declare class Pool extends events$EventEmitter {
constructor(options: $Shape<PgPoolConfig>, Client?: Class<Client>): void;
connect(cb?: PoolConnectCallback): Promise<PoolClient>;
take(cb?: PoolConnectCallback): Promise<PoolClient>;
end(cb?: DoneCallback): Promise<void>;
// Note: not like the pg's Client, the Pool.query return a Promise,
// not a Thenable Query which Client returned.
// And there is a flow(<0.34) issue here, when Array<mixed>,
// the overloading will not work
query:
( (query: QueryConfig|string, callback?: QueryCallback) => Promise<ResultSet> ) &
( (text: string, values: Array<any>, callback?: QueryCallback) => Promise<ResultSet>);
/* flow issue: https://github.com/facebook/flow/issues/2423
* When this fixed, this overloading can be used.
*/
/*
on:
((event: 'connect', listener: (client: PoolClient) => void) => events$EventEmitter )&
((event: 'acquire', listener: (client: PoolClient) => void) => events$EventEmitter )&
((event: "error", listener: (err: PG_ERROR) => void) => events$EventEmitter )&
((event: string, listener: Function) => events$EventEmitter);
*/
}
// <<------------- copy from 'pg-pool' ------------------------------
// error
declare type PG_ERROR = {
name: string,
length: number,
severity: string,
code: string,
detail: string|void,
hint: string|void,
position: string|void,
internalPosition: string|void,
internalQuery: string|void,
where: string|void,
schema: string|void,
table: string|void,
column: string|void,
dataType: string|void,
constraint: string|void,
file: string|void,
line: string|void,
routine: string|void
};
declare type ClientConfig = {
//database user's name
user?: string,
//name of database to connect
database?: string,
//database user's password
password?: string,
//database port
port?: number,
// database host. defaults to localhost
host?: string,
// whether to try SSL/TLS to connect to server. default value: false
ssl?: boolean,
// name displayed in the pg_stat_activity view and included in CSV log entries
// default value: process.env.PGAPPNAME
application_name?: string,
// fallback value for the application_name configuration parameter
// default value: false
fallback_application_name?: string,
}
declare type Row = {
[key: string]: mixed,
};
declare type ResultSet = {
command: string,
rowCount: number,
oid: number,
rows: Array<Row>,
};
declare type ResultBuilder = {
command: string,
rowCount: number,
oid: number,
rows: Array<Row>,
addRow: (row: Row) => void,
};
declare type QueryConfig = {
name?: string,
text: string,
values?: any[],
};
declare type QueryCallback = (err: PG_ERROR|null, result: ResultSet|void) => void;
declare type ClientConnectCallback = (err: PG_ERROR|null, client: Client|void) => void;
/*
* lib/query.js
* Query extends from EventEmitter in source code.
* but in Flow there is no multiple extends.
* And in Flow await is a `declare function $await<T>(p: Promise<T> | T): T;`
* seems can not resolve a Thenable's value type directly
* so `Query extends Promise` to make thing temporarily work.
* like this:
* const q = client.query('select * from some');
* q.on('row',cb); // Event
* const result = await q; // or await
*
* ToDo: should find a better way.
*/
declare class Query extends Promise<ResultSet> {
then<U>( onFulfill?: (value: ResultSet) => Promise<U> | U,
onReject?: (error: PG_ERROR) => Promise<U> | U
): Promise<U>;
// Because then and catch return a Promise,
// .then.catch will lose catch's type information PG_ERROR.
catch<U>( onReject?: (error: PG_ERROR) => ?Promise<U> | U ): Promise<U>;
on :
((event: 'row', listener: (row: Row, result: ResultBuilder) => void) => events$EventEmitter )&
((event: 'end', listener: (result: ResultBuilder) => void) => events$EventEmitter )&
((event: 'error', listener: (err: PG_ERROR) => void) => events$EventEmitter );
}
/*
* lib/client.js
* Note: not extends from EventEmitter, for This Type returned by on().
* Flow's EventEmitter force return a EventEmitter in on().
* ToDo: Not sure in on() if return events$EventEmitter or this will be more suitable
* return this will restrict event to given literial when chain on().on().on().
* return a events$EventEmitter will fallback to raw EventEmitter, when chains
*/
declare class Client {
constructor(config?: string | ClientConfig): void;
connect(callback?: ClientConnectCallback):void;
end(): void;
escapeLiteral(str: string): string;
escapeIdentifier(str: string): string;
query:
( (query: QueryConfig|string, callback?: QueryCallback) => Query ) &
( (text: string, values: Array<any>, callback?: QueryCallback) => Query );
on:
((event: 'drain', listener: () => void) => this )&
((event: 'error', listener: (err: PG_ERROR) => void) => this )&
((event: 'notification', listener: (message: any) => void) => this )&
((event: 'notice', listener: (message: any) => void) => this )&
((event: 'end', listener: () => void) => this );
}
/*
* require('pg-types')
*/
declare type TypeParserText = (value: string) => any;
declare type TypeParserBinary = (value: Buffer) => any;
declare type Types = {
getTypeParser:
((oid: number, format?: 'text') => TypeParserText )&
((oid: number, format: 'binary') => TypeParserBinary );
setTypeParser:
((oid: number, format?: 'text', parseFn: TypeParserText) => void )&
((oid: number, format: 'binary', parseFn: TypeParserBinary) => void)&
((oid: number, parseFn: TypeParserText) => void),
}
/*
* lib/index.js ( class PG)
*/
declare class PG extends events$EventEmitter {
types: Types;
Client: Class<Client>;
Pool: Class<Pool>;
Connection: mixed; //Connection is used internally by the Client.
constructor(client: Client): void;
native: { // native binding, have the same capability like PG
types: Types;
Client: Class<Client>;
Pool: Class<Pool>;
Connection: mixed;
};
// The end(),connect(),cancel() in PG is abandoned ?
}
// These class are not exposed by pg.
declare type PoolType = Pool;
declare type PGType = PG;
declare type QueryType = Query;
// module export, keep same structure with index.js
declare module.exports: PG;
}
|
if (Meteor.isClient) {
}
if (Meteor.isServer) {
Meteor.startup(function () {
});
}
|
/*
FILE ARCHIVED ON 0:22:26 Dec 1, 2007 AND RETRIEVED FROM THE
INTERNET ARCHIVE ON 8:41:23 Apr 5, 2015.
JAVASCRIPT APPENDED BY WAYBACK MACHINE, COPYRIGHT INTERNET ARCHIVE.
ALL OTHER CONTENT MAY ALSO BE PROTECTED BY COPYRIGHT (17 U.S.C.
SECTION 108(a)(3)).
*/
/*======================================================================*\
|| #################################################################### ||
|| # vBulletin 3.6.7 PL1
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2000-2007 Jelsoft Enterprises Ltd. All Rights Reserved. ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # /web/20071201002226/http://www.vbulletin.com | /web/20071201002226/http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/
// #############################################################################
// Initial setup
// ensure SESSIONURL exists
if (typeof(SESSIONURL) == "undefined")
{
var SESSIONURL = "";
}
// ensure vbphrase exists
if (typeof(vbphrase) == "undefined")
{
var vbphrase = new Array();
}
// Array of message editor objects
var vB_Editor = new Array();
// Ignore characters within [quote] tags in messages for length check
var ignorequotechars = false;
// Number of pagenav items dealt with so far
var pagenavcounter = 0;
// #############################################################################
// Browser detection and limitation workarounds
// Define the browser we have instead of multiple calls throughout the file
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = ((userAgent.indexOf('opera') != -1) || (typeof(window.opera) != 'undefined'));
var is_saf = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv = (userAgent.indexOf('webtv') != -1);
var is_ie = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4 = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_ie7 = ((is_ie) && (userAgent.indexOf('msie 7.') != -1));
var is_moz = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon = (userAgent.indexOf('konqueror') != -1);
var is_ns = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4 = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac = (userAgent.indexOf('mac') != -1);
// Catch possible bugs with WebTV and other older browsers
var is_regexp = (window.RegExp) ? true : false;
// Is the visiting browser compatible with AJAX?
var AJAX_Compatible = false;
// Help out old versions of IE that don't understand element.style.cursor = 'pointer'
var pointer_cursor = (is_ie ? 'hand' : 'pointer');
/**
* Workaround for heinous IE bug - add special vBlength property to all strings
* This method is applied to ALL string objects automatically
*
* @return integer
*/
String.prototype.vBlength = function()
{
return (is_ie && this.indexOf('\n') != -1) ? this.replace(/\r?\n/g, '_').length : this.length;
}
if ('1234'.substr(-2, 2) == '12') // (which would be incorrect)
{
String.prototype.substr_orig = String.prototype.substr;
/**
* Overrides IE's original String.prototype.substr to accept negative values
*
* @param integer Substring start position
* @param integer Substring length
*
* @return string
*/
String.prototype.substr = function(start, length)
{
return this.substr_orig( (start < 0 ? this.length + start : start), length);
};
}
/**
* Pop function for browsers that don't have it built in
*
* @param array Array from which to pop
*
* @return mixed null on empty, value on success
*/
function array_pop(a)
{
if (typeof a != 'object' || !a.length)
{
return null;
}
else
{
var response = a[a.length - 1];
a.length--;
return response;
}
}
if (typeof Array.prototype.shift === 'undefined')
{
Array.prototype.shift = function()
{
for(var i = 0, b = this[0], l = this.length-1; i < l; i++)
{
this[i] = this[i + 1];
}
this.length--;
return b;
};
}
/**
* Push function for browsers that don't have it built in
*
* @param array Array onto which to push
* @param mixed Value(s) to push onto - you may use multiple arguments here, eg: array_push(myArray, 1, 2, 3, 4, ...)
*
* @return integer Length of array
*/
function array_push(a, values)
{
for (var i = 1; i < arguments.length; i++)
{
a[a.length] = arguments[i];
}
return a.length;
}
/**
* Function to emulate document.getElementById
*
* @param string Object ID
*
* @return mixed null if not found, object if found
*/
function fetch_object(idname)
{
if (document.getElementById)
{
return document.getElementById(idname);
}
else if (document.all)
{
return document.all[idname];
}
else if (document.layers)
{
return document.layers[idname];
}
else
{
return null;
}
}
/**
* Function to emulate document.getElementsByTagName
*
* @param object Parent object (eg: document)
* @param string Tag type (eg: 'td')
*
* @return array
*/
function fetch_tags(parentobj, tag)
{
if (parentobj == null)
{
return new Array();
}
else if (typeof parentobj.getElementsByTagName != 'undefined')
{
return parentobj.getElementsByTagName(tag);
}
else if (parentobj.all && parentobj.all.tags)
{
return parentobj.all.tags(tag);
}
else
{
return new Array();
}
}
/**
* Function to count the number of tags in an object
*
* @param object Parent object (eg: document)
* @param string Tag type (eg: 'td')
*
* @return integer
*/
function fetch_tag_count(parentobj, tag)
{
return fetch_tags(parentobj, tag).length;
}
// #############################################################################
// Event handlers
/**
* Handles the different event models of different browsers and prevents event bubbling
*
* @param event Event object
*
* @return event
*/
function do_an_e(eventobj)
{
if (!eventobj || is_ie)
{
window.event.returnValue = false;
window.event.cancelBubble = true;
return window.event;
}
else
{
eventobj.stopPropagation();
eventobj.preventDefault();
return eventobj;
}
}
/**
* Handles the different event models of different browsers and prevents event bubbling in a lesser way than do_an_e()
*
* @param event Event object
*
* @return event
*/
function e_by_gum(eventobj)
{
if (!eventobj || is_ie)
{
window.event.cancelBubble = true;
return window.event;
}
else
{
if (eventobj.target.type == 'submit')
{
// naughty safari
eventobj.target.form.submit();
}
eventobj.stopPropagation();
return eventobj;
}
}
// #############################################################################
// Message manipulation and validation
/**
* Checks that a message is valid for submission to PHP
*
* @param string Message text
* @param mixed Either subject text (if you want to make sure it exists) or 0 if you don't care
* @param integer Minimum acceptable character limit for the message
*
* @return boolean
*/
function validatemessage(messagetext, subjecttext, minchars)
{
if (is_kon || is_saf || is_webtv)
{
// ignore less-than-capable browsers
return true;
}
else if (subjecttext.length < 1)
{
// subject not specified
alert(vbphrase['must_enter_subject']);
return false;
}
else
{
var stripped = PHP.trim(stripcode(messagetext, false, ignorequotechars));
if (stripped.length < minchars)
{
// minimum message length not met
alert(construct_phrase(vbphrase['message_too_short'], minchars));
return false;
}
else if (typeof(document.forms.vbform) != 'undefined' && typeof(document.forms.vbform.imagestamp) != 'undefined')
{
// This form has image verification enabled
document.forms.vbform.imagestamp.failed = false;
if (document.forms.vbform.imagestamp.value.length != 6)
{
alert(vbphrase['complete_image_verification']);
document.forms.vbform.imagestamp.failed = true;
document.forms.vbform.imagestamp.focus();
return false;
}
else
{
return true;
}
}
else
{
// everything seems ok
return true;
}
}
}
/**
* Strips quotes and bbcode tags from text
*
* @param string Text to manipulate
* @param boolean If true, strip <x> otherwise strip [x]
* @param boolean If true, strip all [quote]...contents...[/quote]
*
* @return string
*/
function stripcode(str, ishtml, stripquotes)
{
if (!is_regexp)
{
return str;
}
if (stripquotes)
{
var start_time = new Date().getTime();
while ((startindex = PHP.stripos(str, '[quote')) !== false)
{
if (new Date().getTime() - start_time > 2000)
{
// while loop has been running for over 2 seconds and has probably gone infinite
break;
}
if ((stopindex = PHP.stripos(str, '[/quote]')) !== false)
{
fragment = str.substr(startindex, stopindex - startindex + 8);
str = str.replace(fragment, '');
}
else
{
break;
}
str = PHP.trim(str);
}
}
if (ishtml)
{
// exempt image tags -- they need to count as characters in the string
// as the do as BB codes
str = str.replace(/<img[^>]+src="([^"]+)"[^>]*>/gi, '$1');
var html1 = new RegExp("<(\\w+)[^>]*>", 'gi');
var html2 = new RegExp("<\\/\\w+>", 'gi');
str = str.replace(html1, '');
str = str.replace(html2, '');
var html3 = new RegExp('( )', 'gi');
str = str.replace(html3, ' ');
}
else
{
var bbcode1 = new RegExp("\\[(\\w+)[^\\]]*\\]", 'gi');
var bbcode2 = new RegExp("\\[\\/(\\w+)\\]", 'gi');
str = str.replace(bbcode1, '');
str = str.replace(bbcode2, '');
}
return str;
}
// #############################################################################
// vB_PHP_Emulator class
// #############################################################################
/**
* PHP Function Emulator Class
*/
function vB_PHP_Emulator()
{
}
// =============================================================================
// vB_PHP_Emulator Methods
/**
* Find a string within a string (case insensitive)
*
* @param string Haystack
* @param string Needle
* @param integer Offset
*
* @return mixed Not found: false / Found: integer position
*/
vB_PHP_Emulator.prototype.stripos = function(haystack, needle, offset)
{
if (typeof offset == 'undefined')
{
offset = 0;
}
index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return (index == -1 ? false : index);
}
/**
* Trims leading whitespace
*
* @param string String to trim
*
* @return string
*/
vB_PHP_Emulator.prototype.ltrim = function(str)
{
return str.replace(/^\s+/g, '');
}
/**
* Trims trailing whitespace
*
* @param string String to trim
*
* @return string
*/
vB_PHP_Emulator.prototype.rtrim = function(str)
{
return str.replace(/(\s+)$/g, '');
}
/**
* Trims leading and trailing whitespace
*
* @param string String to trim
*
* @return string
*/
vB_PHP_Emulator.prototype.trim = function(str)
{
return this.ltrim(this.rtrim(str));
}
/**
* Emulation of PHP's preg_quote()
*
* @param string String to process
*
* @return string
*/
vB_PHP_Emulator.prototype.preg_quote = function(str)
{
// replace + { } ( ) [ ] | / ? ^ $ \ . = ! < > : * with backslash+character
return str.replace(/(\+|\{|\}|\(|\)|\[|\]|\||\/|\?|\^|\$|\\|\.|\=|\!|\<|\>|\:|\*)/g, "\\$1");
}
/**
* Emulates PHP's preg_match_all()... sort of
*
* @param string Haystack
* @param string Regular expression - to be inserted into RegExp(x)
*
* @return mixed Array on match, false on no match
*/
vB_PHP_Emulator.prototype.match_all = function(string, regex)
{
var gmatch = string.match(RegExp(regex, "gim"));
if (gmatch)
{
var matches = new Array();
var iregex = new RegExp(regex, "im");
for (var i = 0; i < gmatch.length; i++)
{
matches[matches.length] = gmatch[i].match(iregex);
}
return matches;
}
else
{
return false;
}
}
/**
* Emulates unhtmlspecialchars in vBulletin
*
* @param string String to process
*
* @return string
*/
vB_PHP_Emulator.prototype.unhtmlspecialchars = function(str)
{
f = new Array(/</g, />/g, /"/g, /&/g);
r = new Array('<', '>', '"', '&');
for (var i in f)
{
str = str.replace(f[i], r[i]);
}
return str;
}
/**
* Unescape CDATA from vB_AJAX_XML_Builder PHP class
*
* @param string Escaped CDATA
*
* @return string
*/
vB_PHP_Emulator.prototype.unescape_cdata = function(str)
{
var r1 = /<\=\!\=\[\=C\=D\=A\=T\=A\=\[/g;
var r2 = /\]\=\]\=>/g;
return str.replace(r1, '<![CDATA[').replace(r2, ']]>');
}
/**
* Emulates PHP's htmlspecialchars()
*
* @param string String to process
*
* @return string
*/
vB_PHP_Emulator.prototype.htmlspecialchars = function(str)
{
//var f = new Array(/&(?!#[0-9]+;)/g, /</g, />/g, /"/g);
var f = new Array(
(is_mac && is_ie ? new RegExp('&', 'g') : new RegExp('&(?!#[0-9]+;)', 'g')),
new RegExp('<', 'g'),
new RegExp('>', 'g'),
new RegExp('"', 'g')
);
var r = new Array(
'&',
'<',
'>',
'"'
);
for (var i = 0; i < f.length; i++)
{
str = str.replace(f[i], r[i]);
}
return str;
}
/**
* Searches an array for a value
*
* @param string Needle
* @param array Haystack
* @param boolean Case insensitive
*
* @return integer Not found: -1 / Found: integer index
*/
vB_PHP_Emulator.prototype.in_array = function(ineedle, haystack, caseinsensitive)
{
var needle = new String(ineedle);
if (caseinsensitive)
{
needle = needle.toLowerCase();
for (var i in haystack)
{
if (haystack[i].toLowerCase() == needle)
{
return i;
}
}
}
else
{
for (var i in haystack)
{
if (haystack[i] == needle)
{
return i;
}
}
}
return -1;
}
/**
* Emulates PHP's strpad()
*
* @param string Text to pad
* @param integer Length to pad
* @param string String with which to pad
*
* @return string
*/
vB_PHP_Emulator.prototype.str_pad = function(text, length, padstring)
{
text = new String(text);
padstring = new String(padstring);
if (text.length < length)
{
padtext = new String(padstring);
while (padtext.length < (length - text.length))
{
padtext += padstring;
}
text = padtext.substr(0, (length - text.length)) + text;
}
return text;
}
/**
* A sort of emulation of PHP's urlencode - not 100% the same, but accomplishes the same thing
*
* @param string String to encode
*
* @return string
*/
vB_PHP_Emulator.prototype.urlencode = function(text)
{
text = escape(text.toString()).replace(/\+/g, "%2B");
// this escapes 128 - 255, as JS uses the unicode code points for them.
// This causes problems with submitting text via AJAX with the UTF-8 charset.
var matches = text.match(/(%([0-9A-F]{2}))/gi);
if (matches)
{
for (var matchid = 0; matchid < matches.length; matchid++)
{
var code = matches[matchid].substring(1,3);
if (parseInt(code, 16) >= 128)
{
text = text.replace(matches[matchid], '%u00' + code);
}
}
}
// %25 gets translated to % by PHP, so if you have %25u1234,
// we see it as %u1234 and it gets translated. So make it %u0025u1234,
// which will print as %u1234!
text = text.replace('%25', '%u0025');
return text;
}
/**
* Works a bit like ucfirst, but with some extra options
*
* @param string String with which to work
* @param string Cut off string before first occurence of this string
*
* @return string
*/
vB_PHP_Emulator.prototype.ucfirst = function(str, cutoff)
{
if (typeof cutoff != 'undefined')
{
var cutpos = str.indexOf(cutoff);
if (cutpos > 0)
{
str = str.substr(0, cutpos);
}
}
str = str.split(' ');
for (var i = 0; i < str.length; i++)
{
str[i] = str[i].substr(0, 1).toUpperCase() + str[i].substr(1);
}
return str.join(' ');
}
// initialize the PHP emulator
var PHP = new vB_PHP_Emulator();
// #############################################################################
// vB_AJAX_Handler
// #############################################################################
/**
* XML Sender Class
*
* @param boolean Should connections be asyncronous?
*/
function vB_AJAX_Handler(async)
{
/**
* Should connections be asynchronous?
*
* @var boolean
*/
this.async = async ? true : false;
}
// =============================================================================
// vB_AJAX_Handler methods
/**
* Initializes the XML handler
*
* @return boolean True if handler created OK
*/
vB_AJAX_Handler.prototype.init = function()
{
if (typeof vb_disable_ajax != 'undefined' && vb_disable_ajax == 2)
{
// disable all ajax features
return false;
}
try
{
this.handler = new XMLHttpRequest();
return (this.handler.setRequestHeader ? true : false);
}
catch(e)
{
try
{
this.handler = eval("new A" + "ctiv" + "eX" + "Ob" + "ject('Micr" + "osoft.XM" + "LHTTP');");
return true;
}
catch(e)
{
return false;
}
}
}
/**
* Detects if the browser is fully compatible
*
* @return boolean
*/
vB_AJAX_Handler.prototype.is_compatible = function()
{
if (typeof vb_disable_ajax != 'undefined' && vb_disable_ajax == 2)
{
// disable all ajax features
return false;
}
if (is_ie && !is_ie4) { return true; }
else if (typeof XMLHttpRequest != 'undefined')
{
try { return XMLHttpRequest.prototype.setRequestHeader ? true : false; }
catch(e)
{
try { var tester = new XMLHttpRequest(); return tester.setRequestHeader ? true : false; }
catch(e) { return false; }
}
}
else { return false; }
}
/**
* Checks if the system is ready
*
* @return boolean False if ready
*/
vB_AJAX_Handler.prototype.not_ready = function()
{
return (this.handler.readyState && (this.handler.readyState < 4));
}
/**
* OnReadyStateChange event handler
*
* @param function
*/
vB_AJAX_Handler.prototype.onreadystatechange = function(event)
{
if (!this.handler)
{
if (!this.init())
{
return false;
}
}
if (typeof event == 'function')
{
this.handler.onreadystatechange = event;
}
else
{
alert('XML Sender OnReadyState event is not a function');
}
return false;
}
/**
* Sends data
*
* @param string Destination URL
* @param string Request Data
*
* @return mixed Return message
*/
vB_AJAX_Handler.prototype.send = function(desturl, datastream)
{
if (!this.handler)
{
if (!this.init())
{
return false;
}
}
if (!this.not_ready())
{
this.handler.open('POST', desturl, this.async);
this.handler.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.handler.send(datastream + '&s=' + fetch_sessionhash());
if (!this.async && this.handler.readyState == 4 && this.handler.status == 200)
{
return true;
}
}
return false;
}
/**
* Fetches the contents of an XML node
*
* @param object XML node
*
* @return string XML node contents
*/
vB_AJAX_Handler.prototype.fetch_data = function(xml_node)
{
if (xml_node && xml_node.firstChild && xml_node.firstChild.nodeValue)
{
return PHP.unescape_cdata(xml_node.firstChild.nodeValue);
}
else
{
return '';
}
}
// we can check this variable to see if browser is AJAX compatible
var AJAX_Compatible = vB_AJAX_Handler.prototype.is_compatible();
// #############################################################################
// vB_Hidden_Form
// #############################################################################
/**
* Form Generator Class
*
* Builds a form filled with hidden fields for invisible submit via POST
*
* @param string Script (my_target_script.php)
*/
function vB_Hidden_Form(script)
{
this.action = script;
this.variables = new Array();
}
// =============================================================================
// vB_Hidden_Form methods
/**
* Adds a hidden input field to the form object
*
* @param string Name attribute
* @param string Value attribute
*/
vB_Hidden_Form.prototype.add_variable = function(name, value)
{
this.variables[this.variables.length] = new Array(name, value);
};
/**
* Fetches all form elements inside an HTML element and performs 'add_input()' on them
*
* @param object HTML element to search
*/
vB_Hidden_Form.prototype.add_variables_from_object = function(obj)
{
var inputs = fetch_tags(obj, 'input');
for (var i = 0; i < inputs.length; i++)
{
switch (inputs[i].type)
{
case 'checkbox':
case 'radio':
if (inputs[i].checked)
{
this.add_variable(inputs[i].name, inputs[i].value);
}
break;
case 'text':
case 'hidden':
case 'password':
this.add_variable(inputs[i].name, inputs[i].value);
break;
default:
continue;
}
}
var textareas = fetch_tags(obj, 'textarea');
for (var i = 0; i < textareas.length; i++)
{
this.add_variable(textareas[i].name, textareas[i].value);
}
var selects = fetch_tags(obj, 'select');
for (var i = 0; i < selects.length; i++)
{
if (selects[i].multiple)
{
for (var j = 0; j < selects[i].options.length; j++)
{
if (selects[i].options[j].selected)
{
this.add_variable(selects[i].name, selects[i].options[j].value);
}
}
}
else
{
this.add_variable(selects[i].name, selects[i].options[selects[i].selectedIndex].value);
}
}
};
/**
* Fetches a variable value
*
* @param string Variable name
*
* @return mixed Variable value
*/
vB_Hidden_Form.prototype.fetch_variable = function(varname)
{
for (var i = 0; i < this.variables.length; i++)
{
if (this.variables[i][0] == varname)
{
return this.variables[i][1];
}
}
return null;
};
/**
* Submits the hidden form object
*/
vB_Hidden_Form.prototype.submit_form = function()
{
this.form = document.createElement('form');
this.form.method = 'post';
this.form.action = this.action;
for (var i = 0; i < this.variables.length; i++)
{
var inputobj = document.createElement('input');
inputobj.type = 'hidden';
inputobj.name = this.variables[i][0];
inputobj.value = this.variables[i][1];
this.form.appendChild(inputobj);
}
document.body.appendChild(this.form).submit();
};
/**
* Builds a URI query string from the given variables
*/
vB_Hidden_Form.prototype.build_query_string = function()
{
var query_string = '';
for (var i = 0; i < this.variables.length; i++)
{
query_string += this.variables[i][0] + '=' + PHP.urlencode(this.variables[i][1]) + '&';
}
return query_string;
}
/**
* Legacy functions for backward compatability
*/
vB_Hidden_Form.prototype.add_input = vB_Hidden_Form.prototype.add_variable;
vB_Hidden_Form.prototype.add_inputs_from_object = vB_Hidden_Form.prototype.add_variables_from_object;
// #############################################################################
// Window openers and instant messenger wrappers
/**
* Opens a generic browser window
*
* @param string URL
* @param integer Width
* @param integer Height
* @param string Optional Window ID
*/
function openWindow(url, width, height, windowid)
{
return window.open(
url,
(typeof windowid == 'undefined' ? 'vBPopup' : windowid),
'statusbar=no,menubar=no,toolbar=no,scrollbars=yes,resizable=yes'
+ (typeof width != 'undefined' ? (',width=' + width) : '') + (typeof height != 'undefined' ? (',height=' + height) : '')
);
}
/**
* Opens control panel help window
*
* @param string Script name
* @param string Action type
* @param string Option value
*
* @return window
*/
function js_open_help(scriptname, actiontype, optionval)
{
return openWindow(
'help.php?s=' + SESSIONHASH + '&do=answer&page=' + scriptname + '&pageaction=' + actiontype + '&option=' + optionval,
600, 450, 'helpwindow'
);
}
/**
* Opens a window to show a list of attachments in a thread (misc.php?do=showattachments)
*
* @param integer Thread ID
*
* @return window
*/
function attachments(threadid)
{
return openWindow(
'misc.php?' + SESSIONURL + 'do=showattachments&t=' + threadid,
480, 300
);
}
/**
* Opens a window to show a list of posters in a thread (misc.php?do=whoposted)
*
* @param integer Thread ID
*
* @return window
*/
function who(threadid)
{
return openWindow(
'misc.php?' + SESSIONURL + 'do=whoposted&t=' + threadid,
230, 300
);
}
/**
* Opens an IM Window
*
* @param string IM type
* @param integer User ID
* @param integer Width of window
* @param integer Height of window
*
* @return window
*/
function imwindow(imtype, userid, width, height)
{
return openWindow(
'sendmessage.php?' + SESSIONURL + 'do=im&type=' + imtype + '&u=' + userid,
width, height
);
}
/**
* Sends an MSN message
*
* @param string Target MSN handle
*
* @return boolean false
*/
function SendMSNMessage(name)
{
if (!is_ie)
{
alert(vbphrase['msn_functions_only_work_in_ie']);
return false;
}
else
{
MsgrObj.InstantMessage(name);
return false;
}
}
/**
* Adds an MSN Contact (requires MSN)
*
* @param string MSN handle
*
* @return boolean false
*/
function AddMSNContact(name)
{
if (!is_ie)
{
alert(vbphrase['msn_functions_only_work_in_ie']);
return false;
}
else
{
MsgrObj.AddContact(0, name);
return false;
}
}
/**
* Detects Caps-Lock when a key is pressed
*
* @param event
*
* @return boolean True if Caps-Lock is on
*/
function detect_caps_lock(e)
{
e = (e ? e : window.event);
var keycode = (e.which ? e.which : (e.keyCode ? e.keyCode : (e.charCode ? e.charCode : 0)));
var shifted = (e.shiftKey || (e.modifiers && (e.modifiers & 4)));
var ctrled = (e.ctrlKey || (e.modifiers && (e.modifiers & 2)));
// if characters are uppercase without shift, or lowercase with shift, caps-lock is on.
return (keycode >= 65 && keycode <= 90 && !shifted && !ctrled) || (keycode >= 97 && keycode <= 122 && shifted);
}
/**
* Confirms log-out request
*
* @param string Log-out confirmation message
*
* @return boolean
*/
function log_out(confirmation_message)
{
var ht = document.getElementsByTagName("html")[0];
ht.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
if (confirm(confirmation_message))
{
return true;
}
else
{
ht.style.filter = "";
return false;
}
}
// #############################################################################
// Cookie handlers
/**
* Sets a cookie
*
* @param string Cookie name
* @param string Cookie value
* @param date Cookie expiry date
*/
function set_cookie(name, value, expires)
{
document.cookie = name + '=' + escape(value) + '; path=/' + (typeof expires != 'undefined' ? '; expires=' + expires.toGMTString() : '');
}
/**
* Deletes a cookie
*
* @param string Cookie name
*/
function delete_cookie(name)
{
document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT' + '; path=/';
}
/**
* Fetches the value of a cookie
*
* @param string Cookie name
*
* @return string
*/
function fetch_cookie(name)
{
cookie_name = name + '=';
cookie_length = document.cookie.length;
cookie_begin = 0;
while (cookie_begin < cookie_length)
{
value_begin = cookie_begin + cookie_name.length;
if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
{
var value_end = document.cookie.indexOf (';', value_begin);
if (value_end == -1)
{
value_end = cookie_length;
}
return unescape(document.cookie.substring(value_begin, value_end));
}
cookie_begin = document.cookie.indexOf(' ', cookie_begin) + 1;
if (cookie_begin == 0)
{
break;
}
}
return null;
}
// #############################################################################
// Form element managers (used for 'check all' type systems
/**
* Sets all checkboxes, radio buttons or selects in a given form to a given state, with exceptions
*
* @param object Form object
* @param string Target element type (one of 'radio', 'select-one', 'checkbox')
* @param string Selected option in case of 'radio'
* @param array Array of element names to be excluded
* @param mixed Value to give to found elements
*/
function js_toggle_all(formobj, formtype, option, exclude, setto)
{
for (var i =0; i < formobj.elements.length; i++)
{
var elm = formobj.elements[i];
if (elm.type == formtype && PHP.in_array(elm.name, exclude, false) == -1)
{
switch (formtype)
{
case 'radio':
if (elm.value == option) // option == '' evaluates true when option = 0
{
elm.checked = setto;
}
break;
case 'select-one':
elm.selectedIndex = setto;
break;
default:
elm.checked = setto;
break;
}
}
}
}
/**
* Sets all <select> elements to the selectedIndex specified by the 'selectall' element
*
* @param object Form object
*/
function js_select_all(formobj)
{
exclude = new Array();
exclude[0] = 'selectall';
js_toggle_all(formobj, 'select-one', '', exclude, formobj.selectall.selectedIndex);
}
/**
* Sets all <input type="checkbox" /> elements to have the same checked status as 'allbox'
*
* @param object Form object
*/
function js_check_all(formobj)
{
exclude = new Array();
exclude[0] = 'keepattachments';
exclude[1] = 'allbox';
exclude[2] = 'removeall';
js_toggle_all(formobj, 'checkbox', '', exclude, formobj.allbox.checked);
}
/**
* Sets all <input type="radio" /> groups to have a particular option checked
*
* @param object Form object
* @param mixed Selected option
*/
function js_check_all_option(formobj, option)
{
exclude = new Array();
exclude[0] = 'useusergroup';
js_toggle_all(formobj, 'radio', option, exclude, true);
}
/**
* Alias to js_check_all
*/
function checkall(formobj) { js_check_all(formobj); }
/**
* Alias to js_check_all_option
*/
function checkall_option(formobj, option) { js_check_all_option(formobj, option); }
/**
* Resize function for CP textareas
*
* @param integer If positive, size up, otherwise size down
* @param string ID of the textarea
*
* @return boolean false
*/
function resize_textarea(to, id)
{
if (to < 0)
{
var rows = -5;
var cols = -10;
}
else
{
var rows = 5;
var cols = 10;
}
var textarea = fetch_object(id);
if (typeof textarea.orig_rows == 'undefined')
{
textarea.orig_rows = textarea.rows;
textarea.orig_cols = textarea.cols;
}
var newrows = textarea.rows + rows;
var newcols = textarea.cols + cols;
if (newrows >= textarea.orig_rows && newcols >= textarea.orig_cols)
{
textarea.rows = newrows;
textarea.cols = newcols;
}
return false;
}
// #############################################################################
// Collapsible element handlers
/**
* Toggles the collapse state of an object, and saves state to 'vbulletin_collapse' cookie
*
* @param string Unique ID for the collapse group
*
* @return boolean false
*/
function toggle_collapse(objid)
{
if (!is_regexp)
{
return false;
}
obj = fetch_object('collapseobj_' + objid);
img = fetch_object('collapseimg_' + objid);
cel = fetch_object('collapsecel_' + objid);
if (!obj)
{
// nothing to collapse!
if (img)
{
// hide the clicky image if there is one
img.style.display = 'none';
}
return false;
}
if (obj.style.display == 'none')
{
obj.style.display = '';
save_collapsed(objid, false);
if (img)
{
img_re = new RegExp("_collapsed\\.gif$");
img.src = img.src.replace(img_re, '.gif');
}
if (cel)
{
cel_re = new RegExp("^(thead|tcat)(_collapsed)$");
cel.className = cel.className.replace(cel_re, '$1');
}
}
else
{
obj.style.display = 'none';
save_collapsed(objid, true);
if (img)
{
img_re = new RegExp("\\.gif$");
img.src = img.src.replace(img_re, '_collapsed.gif');
}
if (cel)
{
cel_re = new RegExp("^(thead|tcat)$");
cel.className = cel.className.replace(cel_re, '$1_collapsed');
}
}
return false;
}
/**
* Updates vbulletin_collapse cookie with collapse preferences
*
* @param string Unique ID for the collapse group
* @param boolean Add a cookie
*/
function save_collapsed(objid, addcollapsed)
{
var collapsed = fetch_cookie('vbulletin_collapse');
var tmp = new Array();
if (collapsed != null)
{
collapsed = collapsed.split('\n');
for (var i in collapsed)
{
if (collapsed[i] != objid && collapsed[i] != '')
{
tmp[tmp.length] = collapsed[i];
}
}
}
if (addcollapsed)
{
tmp[tmp.length] = objid;
}
expires = new Date();
expires.setTime(expires.getTime() + (1000 * 86400 * 365));
set_cookie('vbulletin_collapse', tmp.join('\n'), expires);
}
// #############################################################################
// Event Handlers for PageNav menus
/**
* Class to handle pagenav events
*/
function vBpagenav()
{
}
/**
* Handles clicks on pagenav menu control objects
*/
vBpagenav.prototype.controlobj_onclick = function(e)
{
this._onclick(e);
var inputs = fetch_tags(this.menu.menuobj, 'input');
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].type == 'text')
{
inputs[i].focus();
break;
}
}
};
/**
* Submits the pagenav form... sort of
*/
vBpagenav.prototype.form_gotopage = function(e)
{
if ((pagenum = parseInt(fetch_object('pagenav_itxt').value, 10)) > 0)
{
window.location = this.addr + '&page=' + pagenum;
}
return false;
};
/**
* Handles clicks on the 'Go' button in pagenav popups
*/
vBpagenav.prototype.ibtn_onclick = function(e)
{
return this.form.gotopage();
};
/**
* Handles keypresses in the text input of pagenav popups
*/
vBpagenav.prototype.itxt_onkeypress = function(e)
{
return ((e ? e : window.event).keyCode == 13 ? this.form.gotopage() : true);
};
// #############################################################################
// DHTML Popup Menu Handling (complements vbulletin_menu.js)
/**
* Wrapper for vBmenu.register
*
* @param string Control ID
* @param boolean No image (true)
* @param boolean Does nothing any more
*/
function vbmenu_register(controlid, noimage, datefield)
{
if (typeof(vBmenu) == "object")
{
return vBmenu.register(controlid, noimage);
}
else
{
return false;
}
}
// #############################################################################
// Stuff that really doesn't fit anywhere else
/**
* Sets an element and all its children to be 'unselectable'
*
* @param object Object to be made unselectable
*/
function set_unselectable(obj)
{
if (!is_ie4 && typeof obj.tagName != 'undefined')
{
if (obj.hasChildNodes())
{
for (var i = 0; i < obj.childNodes.length; i++)
{
set_unselectable(obj.childNodes[i]);
}
}
obj.unselectable = 'on';
}
}
/**
* Fetches the sessionhash from the SESSIONURL variable
*
* @return string
*/
function fetch_sessionhash()
{
return (SESSIONURL == '' ? '' : SESSIONURL.substr(2, 32));
}
/**
* Emulates the PHP version of vBulletin's construct_phrase() sprintf wrapper
*
* @param string String containing %1$s type replacement markers
* @param string First replacement
* @param string Nth replacement
*
* @return string
*/
function construct_phrase()
{
if (!arguments || arguments.length < 1 || !is_regexp)
{
return false;
}
var args = arguments;
var str = args[0];
var re;
for (var i = 1; i < args.length; i++)
{
re = new RegExp("%" + i + "\\$s", 'gi');
str = str.replace(re, args[i]);
}
return str;
}
/**
* Handles the quick style/language options in the footer
*
* @param object Select object
* @param string Type (style or language)
*/
function switch_id(selectobj, type)
{
var id = selectobj.options[selectobj.selectedIndex].value;
if (id == '')
{
return;
}
var url = new String(window.location);
var fragment = new String('');
// get rid of fragment
url = url.split('#');
// deal with the fragment first
if (url[1])
{
fragment = '#' + url[1];
}
// deal with the main url
url = url[0];
// remove id=x& from main bit
if (url.indexOf(type + 'id=') != -1 && is_regexp)
{
re = new RegExp(type + "id=\\d+&?");
url = url.replace(re, '');
}
// add the ? to the url if needed
if (url.indexOf('?') == -1)
{
url += '?';
}
else
{
// make sure that we have a valid character to join our id bit
lastchar = url.substr(url.length - 1);
if (lastchar != '&' && lastchar != '?')
{
url += '&';
}
}
window.location = url + type + 'id=' + id + fragment;
}
/**
* Takes the 'alt' attribute for an image and attaches it to the 'title' attribute
*
* @param object Image object
*/
function img_alt_2_title(img)
{
if (!img.title && img.alt != '')
{
img.title = img.alt;
}
}
// #############################################################################
// Initialize a PostBit
/**
* This function runs all the necessary Javascript code on a PostBit
* after it has been loaded via AJAX. Don't use this method before a
* complete page load or you'll have problems.
*
* @param object Object containing postbits
*/
function PostBit_Init(obj, postid)
{
if (typeof vBmenu != 'undefined')
{
// init profile menu(s)
var divs = fetch_tags(obj, 'div');
for (var i = 0; i < divs.length; i++)
{
if (divs[i].id && divs[i].id.substr(0, 9) == 'postmenu_')
{
vBmenu.register(divs[i].id, true);
}
}
}
if (typeof vB_QuickEditor != 'undefined')
{
// init quick edit controls
vB_AJAX_QuickEdit_Init(obj);
}
if (typeof vB_QuickReply != 'undefined')
{
// init quick reply button
qr_init_buttons(obj);
}
if (typeof mq_init != 'undefined')
{
// init quick reply button
mq_init(obj);
}
if (typeof vBrep != 'undefined')
{
if (typeof postid != 'undefined' && typeof postid != 'null')
{
vbrep_register(postid);
}
}
if (typeof inlineMod != 'undefined')
{
im_init(obj);
}
}
// #############################################################################
// Main vBulletin Javascript Initialization
/**
* This function runs (almost) at the end of script loading on most vBulletin pages
*
* It sets up things like image alt->title tags, turns on the popup menu system etc.
*
* @return boolean
*/
function vBulletin_init()
{
// don't bother doing any exciting stuff for WebTV
if (is_webtv)
{
return false;
}
// set 'title' tags for image elements
var imgs = fetch_tags(document, 'img');
for (var i = 0; i < imgs.length; i++)
{
img_alt_2_title(imgs[i]);
}
// finalize popup menus
if (typeof vBmenu == 'object')
{
// close all menus on document click or resize
if (typeof(YAHOO) != "undefined")
{
YAHOO.util.Event.on(document, "click", vbmenu_hide);
YAHOO.util.Event.on(window, "resize", vbmenu_hide);
}
else if (window.attachEvent && !is_saf)
{
document.attachEvent('onclick', vbmenu_hide);
window.attachEvent('onresize', vbmenu_hide);
}
else if (document.addEventListener && !is_saf)
{
document.addEventListener('click', vbmenu_hide, false);
window.addEventListener('resize', vbmenu_hide, false);
}
else
{
window.onclick = vbmenu_hide;
window.onresize = vbmenu_hide;
}
// add popups to pagenav elements
var pagenavs = fetch_tags(document, 'td');
for (var n = 0; n < pagenavs.length; n++)
{
if (pagenavs[n].hasChildNodes() && pagenavs[n].firstChild.name && pagenavs[n].firstChild.name.indexOf('PageNav') != -1)
{
var addr = pagenavs[n].title;
pagenavs[n].title = '';
pagenavs[n].innerHTML = '';
pagenavs[n].id = 'pagenav.' + n;
var pn = vBmenu.register(pagenavs[n].id);
if (is_saf)
{
pn.controlobj._onclick = pn.controlobj.onclick;
pn.controlobj.onclick = vBpagenav.prototype.controlobj_onclick;
}
}
}
// process the pagenavs popup form
if (typeof addr != 'undefined')
{
fetch_object('pagenav_form').addr = addr;
fetch_object('pagenav_form').gotopage = vBpagenav.prototype.form_gotopage;
fetch_object('pagenav_ibtn').onclick = vBpagenav.prototype.ibtn_onclick;
fetch_object('pagenav_itxt').onkeypress = vBpagenav.prototype.itxt_onkeypress;
}
// activate the menu system
vBmenu.activate(true);
}
// the new init system
vBulletin.init();
return true;
}
// #############################################################################
// deal with Firebug console calls
if (!console)
{
var console = function() { var moo = 1 + 1; };
console.log = function(str) { var moo = 1 + 1; };
}
// #############################################################################
function vBulletin_Framework()
{
this.elements = new Array();
this.ajaxurls = new Array();
this.events = new Array();
this.regexp = "(^|[^a-z0-9_])([a-z0-9_]+)\\[([^\\]]*)\\]";
this.add_event("systemInit");
this.time = new Date();
}
vBulletin_Framework.prototype.init = function()
{
this.find_elements(document.getElementsByTagName("body")[0]);
this.events.systemInit.fire();
}
vBulletin_Framework.prototype.extend = function(subClass, baseClass)
{
function inheritance() {}
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}
vBulletin_Framework.prototype.find_elements = function(parent)
{
for (var i = 0; i < parent.childNodes.length; i++)
{
var element = parent.childNodes[i];
if (element.className)
{
var classmatch = PHP.match_all(element.className, this.regexp);
if (classmatch)
{
this.register_element(element, classmatch);
}
}
if (parent.childNodes[i].hasChildNodes())
{
this.find_elements(parent.childNodes[i]);
}
}
}
vBulletin_Framework.prototype.register_element = function(element, classmatch)
{
for (var i = 0; i < classmatch.length; i++)
{
if (!this.elements[classmatch[i][2]])
{
this.elements[classmatch[i][2]] = new Array();
}
this.elements[classmatch[i][2]][this.elements[classmatch[i][2]].length] = new Array(element, classmatch[i][3]);
}
}
vBulletin_Framework.prototype.register_ajax_urls = function(fetch, save, elements)
{
var fetch = fetch.split("?"); fetch[1] = SESSIONURL + "ajax=1&" + fetch[1].replace(/\{(\d+)(:\w+)?\}/gi, '%$1$s');
var save = save.split("?"); save[1] = SESSIONURL + "ajax=1&" + save[1].replace(/\{(\d+)(:\w+)?\}/gi, '%$1$s');
for (var i = 0; i < elements.length; i++)
{
this.ajaxurls[elements[i]] = new Array(fetch, save);
}
}
vBulletin_Framework.prototype.add_event = function(eventname)
{
this.events[eventname] = (typeof YAHOO != 'undefined' ? new YAHOO.util.CustomEvent(eventname) : new null_event());
}
vBulletin_Framework.prototype.console = function()
{
if (is_moz && console)
{
var args = new Array();
for (var i = 0; i < arguments.length; i++)
{
args[args.length] = arguments[i];
}
try
{
eval("console.log('" + args.join("','") + "');");
}
catch(e) {}
}
}
if (typeof YAHOO == 'undefined')
{
function null_event()
{
this.fire = function() {};
this.subscribe = function() {};
};
}
vBulletin = new vBulletin_Framework();
/*======================================================================*\
|| ####################################################################
|| # Downloaded: 22:20, Sat Jul 7th 2007
|| # CVS: $RCSfile$ - $Revision: 16933 $
|| ####################################################################
\*======================================================================*/
|
'use strict';
// bower install angular#~1.3 angular-route#~1.3 angular-animate#~1.3
// bower install angular#~1.4 angular-route#~1.4 angular-animate#~1.4
angular.module('mgcrea.ngStrapDocs', ['mgcrea.ngStrap', 'mgcrea.ngPlunkr', 'ngRoute', 'ngAnimate'])
.constant('version', 'v2.3.6')
.constant('ngVersion', angular.version.full)
.config(function($plunkrProvider, version) {
angular.extend($plunkrProvider.defaults, {
plunkrTitle: 'AngularStrap Example Plunkr',
plunkrTags: ['angular', 'angular-strap'],
plunkrPrivate: false,
contentHtmlUrlPrefix: 'https://rawgit.com/mgcrea/angular-strap/' + version + '/src/',
contentJsUrlPrefix: 'https://rawgit.com/mgcrea/angular-strap/' + version + '/src/'
});
})
.config(function($routeProvider, $compileProvider, $locationProvider, $sceProvider) {
// Configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(false);
// Disable strict context
$sceProvider.enabled(false);
// Disable scope debug data
$compileProvider.debugInfoEnabled(false);
})
.run(function($window, $rootScope, $location, $anchorScroll, version, ngVersion) {
$rootScope.version = version;
$rootScope.ngVersion = ngVersion;
// FastClick
$window.FastClick.attach($window.document.body);
// Support simple anchor id scrolling
var bodyElement = angular.element($window.document.body);
bodyElement.on('click', function(evt) {
var el = angular.element(evt.target);
var hash = el.attr('href');
if(!hash || hash[0] !== '#') return;
if(hash.length > 1 && hash[1] === '/') return;
if(evt.which !== 1) return;
$location.hash(hash.substr(1));
$anchorScroll();
});
// Initial $anchorScroll()
setTimeout(function() {
$anchorScroll();
}, 0);
});
|
define(function(require, exports, module) {
var useTestServer = true;
var testBaseUrl = 'http://10.0.0.9:9999/';
var releaseBaseUrl = 'https://shiliujishi.com/';
var testServiceUrls = {
'account' : testBaseUrl + 'admin/member/members.js'
};
var releaseServiceUrls = {
'account' : testBaseUrl + 'admin/member/members.js'
};
exports.ServiceUrls = {
getServiceUrlByName: function(serviceName) {
if(useTestServer) {
return testServiceUrls[ serviceName ];
} else {
return releaseServiceUrls[ serviceName ];
}
}
};
}); |
module.exports = {
conditions: [''],
name: 'SpreadElement',
rules: [
'... AssignmentExpression_In',
],
handlers: [
'$$ = new (require(\'./ast/SpreadElementNode\'))($2, { loc: this._$, yy })',
],
subRules: [
require('./AssignmentExpression_In'),
],
};
|
module.exports = { prefix: 'fal', iconName: 'sign-out', icon: [512, 512, [], "f08b", "M48 64h132c6.6 0 12 5.4 12 12v8c0 6.6-5.4 12-12 12H48c-8.8 0-16 7.2-16 16v288c0 8.8 7.2 16 16 16h132c6.6 0 12 5.4 12 12v8c0 6.6-5.4 12-12 12H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48zm279 19.5l-7.1 7.1c-4.7 4.7-4.7 12.3 0 17l132 131.4H172c-6.6 0-12 5.4-12 12v10c0 6.6 5.4 12 12 12h279.9L320 404.4c-4.7 4.7-4.7 12.3 0 17l7.1 7.1c4.7 4.7 12.3 4.7 17 0l164.5-164c4.7-4.7 4.7-12.3 0-17L344 83.5c-4.7-4.7-12.3-4.7-17 0z"] }; |
/*
* TouchPoint.js v1.0.1 - 2017-09-30
* A JavaScript library that visually shows taps/cicks on HTML prototypes
* https://github.com/jonahvsweb/touchpoint-js
*
* Copyright (c) 2017 Jonah Bitautas <jonahvsweb@gmail.com>
*
* Released under the MIT license
*/
'use strict';
var TouchPoint;
(function () {
TouchPoint = {
clickTap: 'ontouchstart' in window ? 'touchstart' : 'click',
dom: '',
styleEl: '',
color: '#FFF',
opacity: 0.8,
size: 20,
scale: 8,
tp: '',
animIds: {},
init: function init() {
var dom = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'body';
window.addEventListener('load', this.setupAnimation, false);
this.dom = document.querySelector(dom);
this.createCss('.tp-init', 'position: absolute; width: ' + this.size + 'px; height: ' + this.size + 'px; background-color: ' + this.color + '; opacity: ' + this.opacity + '; border-radius: 20px; -ms-transform: scale(0.5); -webkit-transform: scale(0.5); -moz-transform: scale(0.5); -o-transform: scale(0.5); transform: scale(0.5); -ms-transition: all 0.5s ease-out; -webkit-transition: all 0.5s ease-out; -moz-transition: all 0.5s ease-out; -o-transition: all 0.5s ease-out; transition: all 0.5s ease-out; z-index: 9999;').createCss('.tp-anim', '-ms-transform: scale(' + this.scale + '); -webkit-transform: scale(' + this.scale + '); -moz-transform: scale(' + this.scale + '); -o-transform: scale(' + this.scale + '); transform: scale(' + this.scale + '); opacity: 0;');
this.dom.addEventListener(this.clickTap, this.create, false);
},
create: function create(e) {
TouchPoint.tp = document.createElement('div');
TouchPoint.tp.setAttribute('id', 'touchpoint');
if (TouchPoint.getMobileOS() === 'iOS') {
TouchPoint.tp.style.left = e.pageX - TouchPoint.size * 0.5 + 'px';
TouchPoint.tp.style.top = e.pageY - TouchPoint.size * 0.5 + 'px';
} else if (TouchPoint.getMobileOS() === 'Android') {
TouchPoint.tp.style.left = e.touches[0].pageX - TouchPoint.size * 0.5 + 'px';
TouchPoint.tp.style.top = e.touches[0].pageY - TouchPoint.size * 0.5 + 'px';
} else if (e.touches && e.touches.length > 0) {
TouchPoint.tp.style.left = e.touches[0].pageX - TouchPoint.size * 0.5 + 'px';
TouchPoint.tp.style.top = e.touches[0].pageY - TouchPoint.size * 0.5 + 'px';
} else {
TouchPoint.tp.style.left = e.clientX - TouchPoint.size * 0.5 + 'px';
TouchPoint.tp.style.top = e.clientY - TouchPoint.size * 0.5 + 'px';
}
TouchPoint.tp.className = 'tp-init';
document.body.appendChild(TouchPoint.tp);
window.requestNextAnimationFrame(function () {
TouchPoint.tp.className += ' tp-anim';
});
TouchPoint.tp.addEventListener('transitionend', TouchPoint.gc, false);
},
gc: function gc(e) {
var currTP = document.querySelector('#touchpoint');
TouchPoint.dom.removeEventListener(TouchPoint.clickTap, TouchPoint.create, false);
if (currTP) {
e.target.removeEventListener('transitionend', TouchPoint.gc, false);
document.body.removeChild(currTP);
TouchPoint.dom.addEventListener(TouchPoint.clickTap, TouchPoint.create, false);
}
},
createCss: function createCss(name, rules) {
var head = document.head || document.getElementsByTagName('head')[0];
for (var i = 0; i < head.childNodes.length; i = i + 1) {
if (head.getElementsByTagName('style')[i].tagName.toLowerCase() === 'style') {
head.getElementsByTagName('style')[i].innerHTML += name + ' { ' + rules + ' }';
TouchPoint.styleEl = head.getElementsByTagName('style')[i];
break;
} else {
TouchPoint.styleEl = document.createElement('style');
TouchPoint.styleEl.type = 'text/css';
TouchPoint.styleEl.innerHTML = name + ' { ' + rules + ' }';
head.appendChild(TouchPoint.styleEl);
break;
}
}
return TouchPoint;
},
getMobileOS: function getMobileOS() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
return 'iOS';
} else if (userAgent.match(/Android/i)) {
return 'Android';
} else {
return 'unknown';
}
},
requestId: function requestId() {
var id = void 0;
do {
id = Math.floor(Math.random() * 1E9);
} while (id in TouchPoint.animIds);
return id;
},
setupAnimation: function setupAnimation(e) {
if (!window.requestNextAnimationFrame) {
window.requestNextAnimationFrame = function (callback, element) {
var id = TouchPoint.requestId();
TouchPoint.animIds[id] = requestAnimationFrame(function () {
TouchPoint.animIds[id] = requestAnimationFrame(function (ts) {
delete TouchPoint.animIds[id];
callback(ts);
}, element);
}, element);
return id;
};
}
if (!window.cancelNextAnimationFrame) {
window.cancelNextAnimationFrame = function (id) {
if (TouchPoint.animIds[id]) {
cancelAnimationFrame(TouchPoint.animIds[id]);
delete TouchPoint.animIds[id];
}
};
}
}
};
})();
//# sourceMappingURL=touchpoint-es5.js.map
|
import React from 'react'
import { Link } from 'react-router'
import Logon from './logon'
/**
* 本组件为欢迎页(首页)
* 由于几乎没有交互逻辑
* 因此可以不使用类的写法
*
* 实际上,ES6 的类经由 Babel 转码后
* 其实还是返回一个类似的函数
*/
const Welcome = () => (
<div className="row">
<div className="medium-8 columns">
<h1>欢迎使用 <br/> 我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符我是占位符</h1>
</div>
<div className="medium-4 columns">
<Logon/>
</div>
</div>
);
export default Welcome
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BsNavbar = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _desc, _value, _class, _descriptor;
var _aureliaFramework = require('aurelia-framework');
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var BsNavbar = exports.BsNavbar = (_class = function () {
function BsNavbar() {
_classCallCheck(this, BsNavbar);
_initDefineProp(this, 'value', _descriptor, this);
}
_createClass(BsNavbar, [{
key: 'valueChanged',
value: function valueChanged(newValue, oldValue) {}
}]);
return BsNavbar;
}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, 'value', [_aureliaFramework.bindable], {
enumerable: true,
initializer: null
})), _class); |
'use strict';
// Configuring the Pets module
angular.module('pets').run(['Menus',
function(Menus) {
// Add the pets dropdown item
Menus.addMenuItem('topbar', {
title: 'Mascotas',
state: 'pets',
type: 'dropdown'
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'pets', {
title: 'Mis mascotas',
state: 'pets.list'
});
// Add the dropdown create item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Nueva mascota',
state: 'pets.create'
});*/
Menus.addSubMenuItem('topbar', 'pets', {
title: 'Perdidas',
state: 'pets.list-missing'
});
Menus.addSubMenuItem('topbar', 'pets', {
title: 'Adopcion',
state: 'pets.list-adoption'
});
Menus.addSubMenuItem('topbar', 'pets', {
title: 'Busca Novi@s',
state: 'pets.list-dates'
});
// Add the dropdown list item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Listar Generos',
state: 'petgenres.list'
});*/
// Add the dropdown create item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Crear Genero',
state: 'petgenres.create'
});*/
// Add the dropdown list item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Listar Tipos',
state: 'pettypes.list'
});*/
// Add the dropdown create item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Crear Tipo',
state: 'pettypes.create'
});*/
// Add the dropdown list item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Listar Razas',
state: 'petbreeds.list'
});*/
// Add the dropdown create item
/*Menus.addSubMenuItem('topbar', 'pets', {
title: 'Crear Raza',
state: 'petbreeds.create'
});*/
}
]);
|
/* @ngInject */
class NavigationController {
constructor(){}
}
export default NavigationController; |
import Layer from './components/layer/layer.js'
import './css/common.css'
const App=function () {
let dom=document.getElementById('app');
let layer=new Layer()
dom.innerHTML=layer.tpl({
name:'john',
arr:['apple','xiaomi']
});
}
new App(); |
// define collections
Notifications = new Mongo.Collection('notifications')
if (Meteor.isClient) {
angular.module('notifyapp', ['angular-meteor'])
angular.module('notifyapp').controller('notificationsListController', ['$meteor', '$scope',
function ($meteor, $scope) {
$scope.notifications = $meteor.collection(Notifications)
}
])
angular.module('notifyapp').directive('addNotification',
function () {
return {
restrict: 'E',
templateUrl: 'views/add-notification.html',
controller: 'addNotificationController',
}
}
)
angular.module('notifyapp').controller('addNotificationController', ['$meteor', '$scope',
function ($meteor, $scope) {
$scope.notifications = $meteor.collection(Notifications)
$scope.add = false
$scope.$on('addNotification', function () {
$scope.add = true
})
$scope.addNotification = function (newNotification) {
$scope.notifications.push({
title: newNotification.title,
body: newNotification.body,
createdAt: new Date()
})
$scope.add = false
}
}
])
angular.module('notifyapp').directive('deleteNotification',
function () {
return {
restrict: 'E',
templateUrl: 'views/delete-notification.html',
controller: 'deleteNController'
}
}
)
angular.module('notifyapp').controller('deleteNController', ['$scope', '$meteor',
function ($scope, $meteor) {
$scope.notifications = $meteor.collection(Notifications)
$scope.delete = false
$scope.$on('deleteNotification', function (e, d) {
$scope.n = d
$scope.delete = true
})
$scope.removeN = function () {
if ($scope.n) {
$scope.notifications.remove($scope.n)
$scope.delete = false
}
}
}
])
angular.module('notifyapp').directive('fakeNotification',
function () {
return {
restrict: 'E',
templateUrl: 'views/fake-notification.html',
controller: 'fakeNotificationController'
}
}
)
angular.module('notifyapp').controller('fakeNotificationController', ['$scope', '$timeout',
function ($scope, $timeout) {
$scope.$on('showNotification', function (e, n) {
$scope.fn = n
$timeout(function () {
$scope.fn = undefined
}, 5000)
})
}
])
angular.module('notifyapp').directive('editNotification',
function () {
return {
restrict: 'E',
templateUrl: 'views/edit-notification.html',
controller: 'editNController'
}
}
)
angular.module('notifyapp').controller('editNController', ['$scope', '$meteor',
function ($scope, $meteor) {
$scope.notifications = $meteor.collection(Notifications)
$scope.edit = false
$scope.$on('editNotification', function (e, n) {
$scope.old = angular.copy(n)
$scope.en = n
$scope.edit = true
})
}
])
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:f28a6959ed09eed29c22734d75df9d0d7a85111a4cb695808bc0da5cc57318d8
size 8132
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.Select.
sap.ui.define(['jquery.sap.global', './Bar', './Dialog', './InputBase', './Popover', './SelectList', './SelectRenderer', './library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator', 'sap/ui/core/IconPool'],
function(jQuery, Bar, Dialog, InputBase, Popover, SelectList, SelectRenderer, library, Control, EnabledPropagator, IconPool) {
"use strict";
/**
* Constructor for a new Select.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given.
* @param {object} [mSettings] Initial settings for the new control.
*
* @class
* The <code>sap.m.Select</code> control provides a list of items that allows users to select an item.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.30.8
*
* @constructor
* @public
* @alias sap.m.Select
* @ui5-metamodel This control will also be described in the UI5 (legacy) design time meta model.
*/
var Select = Control.extend("sap.m.Select", /** @lends sap.m.Select.prototype */ { metadata: {
library: "sap.m",
properties: {
/**
* The name to be used in the HTML code (for example, for HTML forms that send data to the server via submit).
*/
name: { type : "string", group : "Misc", defaultValue: "" },
/**
* Indicates whether the user can change the selection.
*/
enabled: { type: "boolean", group: "Behavior", defaultValue: true },
/**
* Sets the width of the control. The default width is derived from the widest item.
* If the width defined is smaller than the widest item in the selection list, only the width of the selection field will be changed:
* the list will keep the width of its widest item.
* If the list is wider than the viewport, it is truncated and an ellipsis is displayed for each item.
* For phones, the width of the list is always the same as the viewport.<br>
*
* <b>Note:</b> This property is ignored if the <code>autoAdjustWidth</code> property is set to <code>true</code>.
*/
width: { type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "auto" },
/**
* Sets the maximum width of the control.<br>
*
* <b>Note:</b> This property is ignored if the <code>autoAdjustWidth</code> property is set to <code>true</code>.
*/
maxWidth: { type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%" },
/**
* Key of the selected item. If the key has no corresponding aggregated item, no changes will be made.<br>
* <b>Note:</b> If duplicate keys exist, the first item matching the key is selected.
* @since 1.11
*/
selectedKey: { type: "string", group: "Data", defaultValue: "" },
/**
* ID of the selected item. If the ID has no corresponding aggregated item, no changes will be made.
* @since 1.12
*/
selectedItemId: { type: "string", group: "Misc", defaultValue: "" },
/**
* The URI to the icon that will be displayed only when using the <code>IconOnly</code> type.
* @since 1.16
*/
icon: { type: "sap.ui.core.URI", group: "Appearance", defaultValue: "" },
/**
* Type of a select. Possible values <code>Default</code>, <code>IconOnly</code>.
* @since 1.16
*/
type: { type: "sap.m.SelectType", group: "Appearance", defaultValue: sap.m.SelectType.Default },
/**
* Indicates whether the width of the input field is determined by the selected item's content.
* @since 1.16
*/
autoAdjustWidth: { type: "boolean", group: "Appearance", defaultValue: false },
/**
* Sets the horizontal alignment of the text within the input field.
* @since 1.28
*/
textAlign: { type: "sap.ui.core.TextAlign", group: "Appearance", defaultValue: sap.ui.core.TextAlign.Initial },
/**
* Specifies the direction of the text within the input field with enumerated options. By default, the control inherits text direction from the DOM.
* @since 1.28
*/
textDirection: { type: "sap.ui.core.TextDirection", group: "Appearance", defaultValue: sap.ui.core.TextDirection.Inherit }
},
defaultAggregation : "items",
aggregations: {
/**
* Defines the items contained within this control.
*/
items: { type: "sap.ui.core.Item", multiple: true, singularName: "item", bindable: "bindable" },
/**
* Internal aggregation to hold the inner picker popup.
*/
picker: { type : "sap.ui.core.Control", multiple: false, visibility: "hidden" }
},
associations: {
/**
* Sets or retrieves the selected item from the aggregation named items.
*/
selectedItem: { type: "sap.ui.core.Item", multiple: false },
/**
* Association to controls / IDs which label this control (see WAI-ARIA attribute <code>aria-labelledby</code>).
* @since 1.27.0
*/
ariaLabelledBy: { type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy" }
},
events: {
/**
* This event is fired when the value in the selection field is changed in combination with one of the following actions:
* <ul>
* <li>The focus leaves the selection field</li>
* <li>The <i>Enter</i> key is pressed</li>
* <li>The item is pressed</li>
* </ul>
*/
change: {
parameters: {
/**
* The selected item.
*/
selectedItem: { type : "sap.ui.core.Item" }
}
}
}
}});
IconPool.insertFontFaceStyle();
EnabledPropagator.apply(Select.prototype, [true]);
/* =========================================================== */
/* Private methods and properties */
/* =========================================================== */
/* ----------------------------------------------------------- */
/* Private methods */
/* ----------------------------------------------------------- */
function fnHandleKeyboardNavigation(oItem) {
if (oItem) {
this.setSelection(oItem);
this.setValue(oItem.getText());
}
this.scrollToItem(oItem);
}
Select.prototype._handleFocusout = function() {
this._bFocusoutDueRendering = this._bRenderingPhase;
if (!this._bFocusoutDueRendering) {
if (this._bProcessChange) {
this._checkSelectionChange();
}
this._bProcessChange = true;
}
};
Select.prototype._checkSelectionChange = function() {
var oItem = this.getSelectedItem();
if (this._oSelectionOnFocus !== oItem) {
this.fireChange({ selectedItem: oItem });
}
};
Select.prototype._getSelectedItemText = function(vItem) {
vItem = vItem || this.getSelectedItem();
if (!vItem) {
vItem = this.getDefaultSelectedItem();
}
if (vItem) {
return vItem.getText();
}
return "";
};
Select.prototype._callMethodInControl = function(sFunctionName, aArgs) {
var oList = this.getList();
if (aArgs[0] === "items") {
if (oList) {
return SelectList.prototype[sFunctionName].apply(oList, aArgs);
}
} else {
return Control.prototype[sFunctionName].apply(this, aArgs);
}
};
/**
* Retrieves the first enabled item from the aggregation named <code>items</code>.
*
* @param {array} [aItems]
* @returns {sap.ui.core.Item | null}
* @private
*/
Select.prototype.findFirstEnabledItem = function(aItems) {
var oList = this.getList();
return oList ? oList.findFirstEnabledItem(aItems) : null;
};
/**
* Retrieves the last enabled item from the aggregation named <code>items</code>.
*
* @param {array} [aItems]
* @returns {sap.ui.core.Item | null}
* @private
*/
Select.prototype.findLastEnabledItem = function(aItems) {
var oList = this.getList();
return oList ? oList.findLastEnabledItem(aItems) : null;
};
/**
* Sets the selected item by its index.
*
* @param {int} iIndex
* @private
*/
Select.prototype.setSelectedIndex = function(iIndex, _aItems /* only for internal usage */) {
var oItem;
_aItems = _aItems || this.getItems();
// constrain the new index
iIndex = (iIndex > _aItems.length - 1) ? _aItems.length - 1 : Math.max(0, iIndex);
oItem = _aItems[iIndex];
if (oItem) {
this.setSelection(oItem);
}
};
/**
* Scrolls an item into the visual viewport.
*
* @private
*/
Select.prototype.scrollToItem = function(oItem) {
var oPicker = this.getPicker(),
oPickerDomRef = oPicker.getDomRef("cont"),
oItemDomRef = oItem && oItem.getDomRef();
if (!oPicker || !oPickerDomRef || !oItemDomRef) {
return;
}
var iPickerScrollTop = oPickerDomRef.scrollTop,
iItemOffsetTop = oItemDomRef.offsetTop,
iPickerHeight = oPickerDomRef.clientHeight,
iItemHeight = oItemDomRef.offsetHeight;
if (iPickerScrollTop > iItemOffsetTop) {
// scroll up
oPickerDomRef.scrollTop = iItemOffsetTop;
// bottom edge of item > bottom edge of viewport
} else if ((iItemOffsetTop + iItemHeight) > (iPickerScrollTop + iPickerHeight)) {
// scroll down, the item is partly below the viewport of the List
oPickerDomRef.scrollTop = Math.ceil(iItemOffsetTop + iItemHeight - iPickerHeight);
}
};
/**
* Sets the text value of the <code>Select</code> field.
*
* @param {string} sValue
* @private
*/
Select.prototype.setValue = function(sValue) {
this.$("label").text(sValue);
};
/**
* Whether the native HTML Select Element is required.
*
* @returns {boolean}
* @private
*/
Select.prototype._isRequiredSelectElement = function() {
if (this.getAutoAdjustWidth()) {
return false;
} else if (this.getWidth() === "auto") {
return true;
}
};
/**
* Handles the virtual focus of items.
*
* @param {sap.ui.core.Item | null} vItem
* @private
* @since 1.30
*/
Select.prototype._handleAriaActiveDescendant = function(vItem) {
var oDomRef = this.getDomRef(),
oItemDomRef = vItem && vItem.getDomRef(),
sActivedescendant = "aria-activedescendant";
if (!oDomRef) {
return;
}
// the aria-activedescendant attribute is set when the item is rendered
if (oItemDomRef && this.isOpen()) {
oDomRef.setAttribute(sActivedescendant, vItem.getId());
} else {
oDomRef.removeAttribute(sActivedescendant);
}
};
/**
* Gets the Select's <code>List</code>.
*
* @returns {sap.m.List}
* @private
* @since 1.22.0
*/
Select.prototype.getList = function() {
if (this.bIsDestroyed) {
return null;
}
return this._oList;
};
/**
* Called whenever the binding of the aggregation items is changed.
*
* @private
*/
Select.prototype.updateItems = function(sReason) {
SelectList.prototype.updateItems.apply(this, arguments);
// note: after the items are recreated, the selected item association
// points to the new item
this._oSelectionOnFocus = this.getSelectedItem();
};
/**
* Called when the items aggregation needs to be refreshed.<br>
*
* <b>Note:</b> This method has been overwritten to prevent <code>updateItems()</code>
* from being called when the bindings are refreshed.
* @see sap.ui.base.ManagedObject#bindAggregation
*
* @private
*/
Select.prototype.refreshItems = function() {
SelectList.prototype.refreshItems.apply(this, arguments);
};
/* ----------------------------------------------------------- */
/* Picker */
/* ----------------------------------------------------------- */
/**
* This event handler will be called before the Select Picker is opened.
*
* @private
*/
Select.prototype.onBeforeOpen = function() {
var fnPickerTypeBeforeOpen = this["_onBeforeOpen" + this.getPickerType()];
// add the active state to the Select's field
this.addStyleClass(SelectRenderer.CSS_CLASS + "Pressed");
// call the hook to add additional content to the List
this.addContent();
fnPickerTypeBeforeOpen && fnPickerTypeBeforeOpen.call(this);
};
/**
* This event handler will be called after picker popup is opened.
*
* @private
*/
Select.prototype.onAfterOpen = function() {
var oDomRef = this.getFocusDomRef(),
oItem = null;
if (!oDomRef) {
return;
}
oItem = this.getSelectedItem();
oDomRef.setAttribute("aria-expanded", "true");
// expose a parent/child contextual relationship to assistive technologies
// note: the "aria-owns" attribute is set when the list is visible and in view
oDomRef.setAttribute("aria-owns", this.getList().getId());
if (oItem) {
// note: the "aria-activedescendant" attribute is set
// when the currently active descendant is visible and in view
oDomRef.setAttribute("aria-activedescendant", oItem.getId());
}
};
/**
* This event handler will be called before the picker popup is closed.
*
* @private
*/
Select.prototype.onBeforeClose = function() {
var oDomRef = this.getFocusDomRef();
if (oDomRef) {
// note: the "aria-owns" attribute is removed when the list is not visible and in view
oDomRef.removeAttribute("aria-owns");
// the "aria-activedescendant" attribute is removed when the currently active descendant is not visible
oDomRef.removeAttribute("aria-activedescendant");
}
// remove the active state of the Select's field
this.removeStyleClass(SelectRenderer.CSS_CLASS + "Pressed");
};
/**
* This event handler will be called after the picker popup is closed.
*
* @private
*/
Select.prototype.onAfterClose = function() {
var oDomRef = this.getFocusDomRef();
if (oDomRef) {
oDomRef.setAttribute("aria-expanded", "false");
// note: the "aria-owns" attribute is removed when the list is not visible and in view
oDomRef.removeAttribute("aria-owns");
}
};
/**
* Gets the control's picker popup.
*
* @returns {sap.m.Dialog | sap.m.Popover | null} The picker instance, creating it if necessary by calling <code>createPicker()</code> method.
* @private
*/
Select.prototype.getPicker = function() {
if (this.bIsDestroyed) {
return null;
}
// initialize the control's picker
return this.createPicker(this.getPickerType());
};
/**
* Setter for property <code>_sPickerType</code>.
*
* @private
*/
Select.prototype.setPickerType = function(sPickerType) {
this._sPickerType = sPickerType;
};
/**
* Getter for property <code>_sPickerType</code>
*
* @returns {string}
* @private
*/
Select.prototype.getPickerType = function() {
return this._sPickerType;
};
/* ----------------------------------------------------------- */
/* Popover */
/* ----------------------------------------------------------- */
/**
* Creates an instance type of <code>sap.m.Popover</code>.
*
* @returns {sap.m.Popover}
* @private
*/
Select.prototype._createPopover = function() {
var that = this,
oPicker = new Popover({
showArrow: false,
showHeader: false,
placement: sap.m.PlacementType.Vertical,
offsetX: 0,
offsetY: 0,
initialFocus: this,
bounce: false
});
// detect when the scrollbar is pressed
oPicker.addEventDelegate({
ontouchstart: function(oEvent) {
var oPickerDomRef = this.getDomRef("cont");
if (oEvent.target === oPickerDomRef) {
that._bProcessChange = false;
}
}
}, oPicker);
this._decoratePopover(oPicker);
return oPicker;
};
/**
* Decorate a Popover instance by adding some private methods.
*
* @param {sap.m.Popover}
* @private
*/
Select.prototype._decoratePopover = function(oPopover) {
var that = this;
// adding additional capabilities to the Popover
oPopover._removeArrow = function() {
this._marginTop = 0;
this._marginLeft = 0;
this._marginRight = 0;
this._marginBottom = 0;
this._arrowOffset = 0;
this._offsets = ["0 0", "0 0", "0 0", "0 0"];
};
oPopover._setPosition = function() {
this._myPositions = ["begin bottom", "begin center", "begin top", "end center"];
this._atPositions = ["begin top", "end center", "begin bottom", "begin center"];
};
oPopover._setMinWidth = function(sWidth) {
this.getDomRef().style.minWidth = sWidth;
};
oPopover._setWidth = function(sWidth) {
var bAutoAdjustWidth = that.getAutoAdjustWidth(),
bIconOnly = that.getType() === "IconOnly",
oPickerDomRef = this.getDomRef();
// set the width of the content
if (sap.ui.Device.system.desktop || sap.ui.Device.system.tablet) {
if (bAutoAdjustWidth) {
oPickerDomRef.style.width = "auto";
oPickerDomRef.style.minWidth = sWidth;
}
}
if (!bIconOnly) {
// set the width of the popover
oPickerDomRef.style.minWidth = sWidth;
}
};
oPopover.open = function() {
return this.openBy(that);
};
};
/**
* Required adaptations after rendering of the Popover.
*
* @private
*/
Select.prototype._onAfterRenderingPopover = function() {
var oPopover = this.getPicker(),
sWidth = (this.$().outerWidth() / parseFloat(sap.m.BaseFontSize)) + "rem";
// remove the Popover arrow
oPopover._removeArrow();
// position adaptations
oPopover._setPosition();
// width adaptations
if (sap.ui.Device.system.phone) {
oPopover._setMinWidth("100%");
} else {
oPopover._setWidth(sWidth);
}
};
/* ----------------------------------------------------------- */
/* Dialog */
/* ----------------------------------------------------------- */
/**
* Creates an instance type of <code>sap.m.Dialog</code>.
*
* @returns {sap.m.Dialog}
* @private
*/
Select.prototype._createDialog = function() {
var CSS_CLASS = SelectRenderer.CSS_CLASS;
// initialize Dialog
var oDialog = new Dialog({
stretchOnPhone: true,
customHeader: new Bar({
contentLeft: new InputBase({
width: "100%",
editable: false
}).addStyleClass(CSS_CLASS + "Input")
}).addStyleClass(CSS_CLASS + "Bar")
});
oDialog.getAggregation("customHeader").attachBrowserEvent("tap", function() {
oDialog.close();
}, this);
return oDialog;
};
/**
* Called before the Dialog is opened.
*
* @private
*/
Select.prototype._onBeforeOpenDialog = function() {
var oInput = this.getPicker().getCustomHeader().getContentLeft()[0];
oInput.setValue(this.getSelectedItem().getText());
oInput.setTextDirection(this.getTextDirection());
oInput.setTextAlign(this.getTextAlign());
};
/* =========================================================== */
/* Lifecycle methods */
/* =========================================================== */
/**
* Initialization hook.
*
* @private
*/
Select.prototype.init = function() {
// set the picker type
this.setPickerType(sap.ui.Device.system.phone ? "Dialog" : "Popover");
// initialize composites
this.createPicker(this.getPickerType());
// selected item on focus
this._oSelectionOnFocus = null;
// to detect when the control is in the rendering phase
this._bRenderingPhase = false;
// to detect if the focusout event is triggered due a rendering
this._bFocusoutDueRendering = false;
// used to prevent the change event from firing when the user scrolls
// the picker popup (dropdown) list using the mouse
this._bProcessChange = false;
};
/**
* Required adaptations before rendering.
*
* @private
*/
Select.prototype.onBeforeRendering = function() {
// rendering phase is started
this._bRenderingPhase = true;
// note: in IE11 and Firefox 38, the focusout event is not fired when the select is removed
if (this.getFocusDomRef() === document.activeElement) {
this._handleFocusout();
}
this.synchronizeSelection();
};
/**
* Required adaptations after rendering.
*
* @private
*/
Select.prototype.onAfterRendering = function() {
// rendering phase is finished
this._bRenderingPhase = false;
};
/**
* Cleans up before destruction.
*
* @private
*/
Select.prototype.exit = function() {
this._oSelectionOnFocus = null;
};
/* =========================================================== */
/* Event handlers */
/* =========================================================== */
/**
* Handle the touch start event on the Select.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.ontouchstart = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
if (this.getEnabled() && this.isOpenArea(oEvent.target)) {
// add the active state to the Select's field
this.addStyleClass(SelectRenderer.CSS_CLASS + "Pressed");
}
};
/**
* Handle the touch end event on the Select.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.ontouchend = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
if (this.getEnabled() && (!this.isOpen() || !this.hasContent()) && this.isOpenArea(oEvent.target)) {
// remove the active state of the Select HTMLDIVElement container
this.removeStyleClass(SelectRenderer.CSS_CLASS + "Pressed");
}
};
/**
* Handle the tap event on the Select.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.ontap = function(oEvent) {
var CSS_CLASS = SelectRenderer.CSS_CLASS;
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
if (!this.getEnabled()) {
return;
}
if (this.isOpenArea(oEvent.target)) {
if (this.isOpen()) {
this.close();
this.removeStyleClass(CSS_CLASS + "Pressed");
return;
}
if (this.hasContent()) {
this.open();
}
}
if (this.isOpen()) {
// add the active state to the Select's field
this.addStyleClass(CSS_CLASS + "Pressed");
}
};
/**
* Handle the selection change event on the List.
*
* @param {sap.ui.base.Event} oControlEvent
* @private
*/
Select.prototype.onSelectionChange = function(oControlEvent) {
var oItem = oControlEvent.getParameter("selectedItem");
this.close();
this.setSelection(oItem);
this.fireChange({ selectedItem: oItem });
this.setValue(this._getSelectedItemText());
};
/* ----------------------------------------------------------- */
/* Keyboard handling */
/* ----------------------------------------------------------- */
/**
* Handle the keypress event.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onkeypress = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
if (!this.getEnabled()) {
return;
}
var oItem = this.findNextItemByFirstCharacter(String.fromCharCode(oEvent.which)); // note: jQuery oEvent.which normalizes oEvent.keyCode and oEvent.charCode
fnHandleKeyboardNavigation.call(this, oItem);
};
/**
* Handle when F4 or Alt + DOWN arrow are pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapshow = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent browser address bar to be open in ie9, when F4 is pressed
if (oEvent.which === jQuery.sap.KeyCodes.F4) {
oEvent.preventDefault();
}
this.toggleOpenState();
};
/**
* Handle when Alt + UP arrow are pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
* @function
*/
Select.prototype.onsaphide = Select.prototype.onsapshow;
/**
* Handle when escape is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapescape = function(oEvent) {
if (this.isOpen()) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
this.close();
this._checkSelectionChange();
}
};
/**
* Handle when enter is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapenter = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
this.close();
this._checkSelectionChange();
};
/**
* Handle when the spacebar key is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapspace = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when the spacebar key is pressed
oEvent.preventDefault();
if (this.isOpen()) {
this._checkSelectionChange();
}
this.toggleOpenState();
};
/**
* Handle when keyboard DOWN arrow is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapdown = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when arrow keys are pressed
oEvent.preventDefault();
var oNextSelectableItem,
aSelectableItems = this.getSelectableItems();
oNextSelectableItem = aSelectableItems[aSelectableItems.indexOf(this.getSelectedItem()) + 1];
fnHandleKeyboardNavigation.call(this, oNextSelectableItem);
};
/**
* Handle when keyboard UP arrow is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapup = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when arrow keys are pressed
oEvent.preventDefault();
var oPrevSelectableItem,
aSelectableItems = this.getSelectableItems();
oPrevSelectableItem = aSelectableItems[aSelectableItems.indexOf(this.getSelectedItem()) - 1];
fnHandleKeyboardNavigation.call(this, oPrevSelectableItem);
};
/**
* Handle Home key pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsaphome = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when Home key is pressed
oEvent.preventDefault();
var oFirstSelectableItem = this.getSelectableItems()[0];
fnHandleKeyboardNavigation.call(this, oFirstSelectableItem);
};
/**
* Handle End key pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapend = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when End key is pressed
oEvent.preventDefault();
var oLastSelectableItem = this.findLastEnabledItem(this.getSelectableItems());
fnHandleKeyboardNavigation.call(this, oLastSelectableItem);
};
/**
* Handle when page down key is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsappagedown = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when page down key is pressed
oEvent.preventDefault();
var aSelectableItems = this.getSelectableItems(),
oSelectedItem = this.getSelectedItem();
this.setSelectedIndex(aSelectableItems.indexOf(oSelectedItem) + 10, aSelectableItems);
oSelectedItem = this.getSelectedItem();
if (oSelectedItem) {
this.setValue(oSelectedItem.getText());
}
this.scrollToItem(oSelectedItem);
};
/**
* Handle when page up key is pressed.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsappageup = function(oEvent) {
// mark the event for components that needs to know if the event was handled
oEvent.setMarked();
// note: prevent document scrolling when page up key is pressed
oEvent.preventDefault();
var aSelectableItems = this.getSelectableItems(),
oSelectedItem = this.getSelectedItem();
this.setSelectedIndex(aSelectableItems.indexOf(oSelectedItem) - 10, aSelectableItems);
oSelectedItem = this.getSelectedItem();
if (oSelectedItem) {
this.setValue(oSelectedItem.getText());
}
this.scrollToItem(oSelectedItem);
};
/**
* Handle the focusin event.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onfocusin = function(oEvent) {
if (!this._bFocusoutDueRendering && !this._bProcessChange) {
this._oSelectionOnFocus = this.getSelectedItem();
}
this._bProcessChange = true;
// note: in some circumstances IE browsers focus non-focusable elements
if (oEvent.target !== this.getFocusDomRef()) { // whether an inner element is receiving the focus
// force the focus to leave the inner element and set it back to the control's root element
this.focus();
}
};
/**
* Handle the focusout event.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onfocusout = function() {
this._handleFocusout();
};
/**
* Handle the focus leave event.
*
* @param {jQuery.Event} oEvent The event object.
* @private
*/
Select.prototype.onsapfocusleave = function(oEvent) {
var oPicker = this.getAggregation("picker");
if (!oEvent.relatedControlId || !oPicker) {
return;
}
var oControl = sap.ui.getCore().byId(oEvent.relatedControlId),
oFocusDomRef = oControl && oControl.getFocusDomRef();
if (sap.ui.Device.system.desktop && jQuery.sap.containsOrEquals(oPicker.getFocusDomRef(), oFocusDomRef)) {
// force the focus to stay in the input field
this.focus();
}
};
/* =========================================================== */
/* API methods */
/* =========================================================== */
/* ----------------------------------------------------------- */
/* protected methods */
/* ----------------------------------------------------------- */
/**
* Updates and synchronizes <code>selectedItem</code> association, <code>selectedItemId</code> and <code>selectedKey</code> properties.
*
* @param {sap.ui.core.Item | null} vItem
*/
Select.prototype.setSelection = function(vItem) {
var oList = this.getList(),
sKey;
if (oList) {
oList.setSelection(vItem);
}
this.setAssociation("selectedItem", vItem, true);
this.setProperty("selectedItemId", (vItem instanceof sap.ui.core.Item) ? vItem.getId() : vItem, true);
if (typeof vItem === "string") {
vItem = sap.ui.getCore().byId(vItem);
}
sKey = vItem ? vItem.getKey() : "";
this.setProperty("selectedKey", sKey, true);
this._handleAriaActiveDescendant(vItem);
};
/**
* Determines whether the <code>selectedItem</code> association and <code>selectedKey</code> property are synchronized.
*
* @returns {boolean}
*/
Select.prototype.isSelectionSynchronized = function() {
var vItem = this.getSelectedItem();
return this.getSelectedKey() === (vItem && vItem.getKey());
};
/**
* Synchronize selected item and key.
*
* @param {sap.ui.core.Item} vItem
* @param {string} sKey
* @param {array} [aItems]
*/
Select.prototype.synchronizeSelection = function() {
SelectList.prototype.synchronizeSelection.call(this);
};
/**
* This hook method can be used to add additional content.
*
* @param {sap.m.Dialog | sap.m.Popover} [oPicker]
*/
Select.prototype.addContent = function(oPicker) {};
/**
* Creates a picker popup container where the selection should take place.
*
* @param {string} sPickerType
* @returns {sap.m.Popover | sap.m.Dialog}
* @protected
*/
Select.prototype.createPicker = function(sPickerType) {
var oPicker = this.getAggregation("picker"),
CSS_CLASS = SelectRenderer.CSS_CLASS;
if (oPicker) {
return oPicker;
}
oPicker = this["_create" + sPickerType]();
// define a parent-child relationship between the control and the picker popup
this.setAggregation("picker", oPicker, true);
// configuration
oPicker.setHorizontalScrolling(false)
.addStyleClass(CSS_CLASS + "Picker")
.addStyleClass(CSS_CLASS + "Picker-CTX")
.attachBeforeOpen(this.onBeforeOpen, this)
.attachAfterOpen(this.onAfterOpen, this)
.attachBeforeClose(this.onBeforeClose, this)
.attachAfterClose(this.onAfterClose, this)
.addEventDelegate({
onBeforeRendering: this.onBeforeRenderingPicker,
onAfterRendering: this.onAfterRenderingPicker
}, this)
.addContent(this.createList());
return oPicker;
};
/**
* Retrieves the next item from the aggregation named <code>items</code>
* whose first character match with the given <code>sChar</code>.
*
* @param {string} sChar
* @returns {sap.ui.core.Item | null}
* @since 1.26.0
*/
Select.prototype.findNextItemByFirstCharacter = function(sChar) {
var aItems = this.getItems(),
iSelectedIndex = this.getSelectedIndex(),
aItemsAfterSelection = aItems.splice(iSelectedIndex + 1, aItems.length - iSelectedIndex),
aItemsBeforeSelection = aItems.splice(0, aItems.length - 1);
aItems = aItemsAfterSelection.concat(aItemsBeforeSelection);
for (var i = 0, oItem; i < aItems.length; i++) {
oItem = aItems[i];
if (oItem.getEnabled() && !(oItem instanceof sap.ui.core.SeparatorItem) && jQuery.sap.startsWithIgnoreCase(oItem.getText(), sChar)) {
return oItem;
}
}
return null;
};
/**
* Create an instance type of <code>sap.m.SelectList</code>.
*
* @returns {sap.m.SelectList}
*/
Select.prototype.createList = function() {
// list to use inside the picker
this._oList = new SelectList({
width: "100%"
}).addEventDelegate({
ontap: function(oEvent) {
this.close();
}
}, this)
.attachSelectionChange(this.onSelectionChange, this);
return this._oList;
};
/**
* Determines whether the Select has content or not.
*
* @returns {boolean}
*/
Select.prototype.hasContent = function() {
return !!this.getItems().length;
};
/**
* This hook method is called before the control's picker popup is rendered.
*
*/
Select.prototype.onBeforeRenderingPicker = function() {
var fnOnBeforeRenderingPickerType = this["_onBeforeRendering" + this.getPickerType()];
fnOnBeforeRenderingPickerType && fnOnBeforeRenderingPickerType.call(this);
};
/**
* This hook method is called after the control's picker popup is rendered.
*
*/
Select.prototype.onAfterRenderingPicker = function() {
var fnOnAfterRenderingPickerType = this["_onAfterRendering" + this.getPickerType()];
fnOnAfterRenderingPickerType && fnOnAfterRenderingPickerType.call(this);
};
/**
* Open the control's picker popup.
*
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @protected
* @since 1.16
*/
Select.prototype.open = function() {
var oPicker = this.getPicker();
if (oPicker) {
oPicker.open();
}
return this;
};
/**
* Toggle the open state of the control's picker popup.
*
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @since 1.26
*/
Select.prototype.toggleOpenState = function() {
if (this.isOpen()) {
this.close();
} else if (this.hasContent()) {
this.open();
}
return this;
};
/**
* Gets the visible <code>items</code>.
*
* @return {sap.ui.core.Item[]}
* @since 1.22.0
*/
Select.prototype.getVisibleItems = function() {
var oList = this.getList();
return oList ? oList.getVisibleItems() : [];
};
/**
* Determines whether the provided item is selected.
*
* @param {sap.ui.core.Item} oItem
* @returns {boolean}
* @since 1.24.0
*/
Select.prototype.isItemSelected = function(oItem) {
return oItem && (oItem.getId() === this.getAssociation("selectedItem"));
};
/**
* Retrieves the index of the selected item from the aggregation named <code>items</code>.
*
* @returns {int} An integer specifying the selected index, or -1 if no item is selected.
* @since 1.26.0
*/
Select.prototype.getSelectedIndex = function() {
var oSelectedItem = this.getSelectedItem();
return oSelectedItem ? this.indexOfItem(this.getSelectedItem()) : -1;
};
/**
* Retrieves the default selected item object from the aggregation named <code>items</code>.
*
* @returns {sap.ui.core.Item | null}
* @since 1.22.0
*/
Select.prototype.getDefaultSelectedItem = function(aItems) {
return this.findFirstEnabledItem();
};
/**
* Gets the selectable items from the aggregation named <code>items</code>.
*
* @return {sap.ui.core.Item[]} An array containing the selectables items.
* @since 1.22.0
*/
Select.prototype.getSelectableItems = function() {
var oList = this.getList();
return oList ? oList.getSelectableItems() : [];
};
/**
* Gets the control's picker popup's trigger element.
*
* @returns {Element | null} Returns the element that is used as trigger to open the control's picker popup.
* @since 1.22.0
*/
Select.prototype.getOpenArea = function() {
return this.getDomRef();
};
/**
* Checks whether the provided element is the open area.
*
* @param {Element} oDomRef
* @returns {boolean}
* @since 1.22.0
*/
Select.prototype.isOpenArea = function(oDomRef) {
var oOpenAreaDomRef = this.getOpenArea();
return oOpenAreaDomRef && oOpenAreaDomRef.contains(oDomRef);
};
/**
* Retrieves an item by searching for the given property/value from the aggregation named <code>items</code>.<br>
* <b>Note: </b> If duplicate values exists, the first item matching the value is returned.
*
* @param {string} sProperty An item property.
* @param {string} sValue An item value that specifies the item to retrieve.
* @returns {sap.ui.core.Item | null} The matched item or null.
* @since 1.22.0
*/
Select.prototype.findItem = function(sProperty, sValue) {
var oList = this.getList();
return oList ? oList.findItem(sProperty, sValue) : null;
};
/**
* Clear the selection.
*
* @since 1.22.0
*/
Select.prototype.clearSelection = function() {
this.setSelection(null);
};
/**
* Handles properties' changes of items in the aggregation named <code>items</code>.
*
* @private
* @param {sap.ui.base.Event} oControlEvent
* @since 1.30
*/
Select.prototype.onItemChange = function(oControlEvent) {
var sSelectedItemId = this.getAssociation("selectedItem"),
sNewValue = oControlEvent.getParameter("newValue"),
sProperty = oControlEvent.getParameter("name");
// if the selected item has changed, synchronization is needed
if (sSelectedItemId === oControlEvent.getParameter("id")) {
switch (sProperty) {
case "text":
this.setValue(sNewValue);
break;
case "key":
this.setSelectedKey(sNewValue);
break;
// no default
}
}
};
Select.prototype.fireChange = function(mParameters) {
this._oSelectionOnFocus = mParameters.selectedItem;
return this.fireEvent("change", mParameters);
};
Select.prototype.addAggregation = function(sAggregationName, oObject, bSuppressInvalidate) {
this._callMethodInControl("addAggregation", arguments);
if (sAggregationName === "items" && !bSuppressInvalidate && !this.isInvalidateSuppressed()) {
this.invalidate(oObject);
}
return this;
};
Select.prototype.getAggregation = function() {
return this._callMethodInControl("getAggregation", arguments);
};
Select.prototype.setAssociation = function(sAssociationName, sId, bSuppressInvalidate) {
var oList = this.getList();
if (oList && (sAssociationName === "selectedItem")) {
// propagate the value of the "selectedItem" association to the list
SelectList.prototype.setAssociation.apply(oList, arguments);
}
return Control.prototype.setAssociation.apply(this, arguments);
};
Select.prototype.indexOfAggregation = function() {
return this._callMethodInControl("indexOfAggregation", arguments);
};
Select.prototype.insertAggregation = function() {
this._callMethodInControl("insertAggregation", arguments);
return this;
};
Select.prototype.removeAggregation = function() {
return this._callMethodInControl("removeAggregation", arguments);
};
Select.prototype.removeAllAggregation = function() {
return this._callMethodInControl("removeAllAggregation", arguments);
};
Select.prototype.destroyAggregation = function(sAggregationName, bSuppressInvalidate) {
this._callMethodInControl("destroyAggregation", arguments);
if (!bSuppressInvalidate && !this.isInvalidateSuppressed()) {
this.invalidate();
}
return this;
};
Select.prototype.setProperty = function(sPropertyName, oValue, bSuppressInvalidate) {
var oList = this.getList();
if ((sPropertyName === "selectedKey") || (sPropertyName === "selectedItemId")) {
// propagate the value of the "selectedKey" or "selectedItemId" properties to the list
oList && SelectList.prototype.setProperty.apply(oList, arguments);
}
return Control.prototype.setProperty.apply(this, arguments);
};
Select.prototype.removeAllAssociation = function(sAssociationName, bSuppressInvalidate) {
var oList = this.getList();
if (oList && (sAssociationName === "selectedItem")) {
SelectList.prototype.removeAllAssociation.apply(oList, arguments);
}
return Control.prototype.removeAllAssociation.apply(this, arguments);
};
Select.prototype.clone = function(sIdSuffix) {
var oSelectClone = Control.prototype.clone.apply(this, arguments),
oList = this.getList();
if (!this.isBound("items") && oList) {
for (var i = 0, aItems = oList.getItems(); i < aItems.length; i++) {
oSelectClone.addItem(aItems[i].clone());
}
oSelectClone.setSelectedIndex(this.indexOfItem(this.getSelectedItem()));
}
return oSelectClone;
};
/* ----------------------------------------------------------- */
/* public methods */
/* ----------------------------------------------------------- */
/**
* Adds an item to the aggregation named <code>items</code>.
*
* @param {sap.ui.core.Item} oItem The item to be added; if empty, nothing is added.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
*/
Select.prototype.addItem = function(oItem) {
this.addAggregation("items", oItem);
if (oItem) {
oItem.attachEvent("_change", this.onItemChange, this);
}
return this;
};
/**
* Inserts an item into the aggregation named <code>items</code>.
*
* @param {sap.ui.core.Item} oItem The item to be inserted; if empty, nothing is inserted.
* @param {int} iIndex The <code>0</code>-based index the item should be inserted at; for
* a negative value of <code>iIndex</code>, the item is inserted at position 0; for a value
* greater than the current size of the aggregation, the item is inserted at the last position.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
*/
Select.prototype.insertItem = function(oItem, iIndex) {
this.insertAggregation("items", oItem, iIndex);
if (oItem) {
oItem.attachEvent("_change", this.onItemChange, this);
}
return this;
};
Select.prototype.findAggregatedObjects = function() {
var oList = this.getList();
if (oList) {
// note: currently there is only one aggregation
return SelectList.prototype.findAggregatedObjects.apply(oList, arguments);
}
return [];
};
/**
* Gets aggregation <code>items</code>.
*
* <b>Note</b>: This is the default aggregation.
* @return {sap.ui.core.Item[]}
* @public
*/
Select.prototype.getItems = function() {
var oList = this.getList();
return oList ? oList.getItems() : [];
};
/**
* Sets association <code>selectedItem</code>.
*
* @param {string | sap.ui.core.Item | null} vItem New value for association <code>selectedItem</code>.
* If an ID of a <code>sap.ui.core.Item</code> is given, the item with this ID becomes the <code>selectedItem</code> association.
* Alternatively, a <code>sap.ui.core.Item</code> instance may be given or <code>null</code>.
* If the value of <code>null</code> is provided, the first enabled item will be selected (if any).
*
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
*/
Select.prototype.setSelectedItem = function(vItem) {
if (typeof vItem === "string") {
vItem = sap.ui.getCore().byId(vItem);
}
if (!(vItem instanceof sap.ui.core.Item) && vItem !== null) {
jQuery.sap.log.warning('Warning: setSelectedItem() "vItem" has to be an instance of sap.ui.core.Item, a valid sap.ui.core.Item id, or null on', this);
return this;
}
if (!vItem) {
vItem = this.getDefaultSelectedItem();
}
this.setSelection(vItem);
this.setValue(this._getSelectedItemText(vItem));
return this;
};
/**
* Sets property <code>selectedItemId</code>.
*
* Default value is an empty string <code>""</code> or <code>undefined</code>.
* If the provided <code>vItem</code> has a default value,
* the first enabled item will be selected (if any).
*
* @param {string | undefined} vItem New value for property <code>selectedItemId</code>.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
* @since 1.12
*/
Select.prototype.setSelectedItemId = function(vItem) {
vItem = this.validateProperty("selectedItemId", vItem);
if (!vItem) {
vItem = this.getDefaultSelectedItem();
}
this.setSelection(vItem);
this.setValue(this._getSelectedItemText());
return this;
};
/**
* Sets property <code>selectedKey</code>.
*
* Default value is an empty string <code>""</code> or <code>undefined</code>.
*
* If the provided <code>sKey</code> has a default value,
* the first enabled item will be selected (if any).
* In the case that an item has the default key value, it will be selected instead.
*
* @param {string} sKey New value for property <code>selectedKey</code>.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
* @since 1.11
*/
Select.prototype.setSelectedKey = function(sKey) {
sKey = this.validateProperty("selectedKey", sKey);
var oItem = this.getItemByKey(sKey);
if (oItem || (sKey === "")) {
// if "sKey" is an empty string "" or undefined,
// the first enabled item will be selected (if any)
if (!oItem && sKey === "") {
oItem = this.getDefaultSelectedItem();
}
this.setSelection(oItem);
this.setValue(this._getSelectedItemText(oItem));
return this;
}
return this.setProperty("selectedKey", sKey);
};
/**
* Sets property <code>textAlign</code>.
*
* Default value is a sap.ui.core.TextAlign.Initial <code>"Initial"</code>.
* If the provided <code>sValue</code> has a default value,
* the browser default is used.
*
* @param {sap.ui.core.TextAlign} sValue New value for property <code>textAlign</code>.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
* @since 1.28
*/
/**
* Sets property <code>textDirection</code>.
*
* Default value is a sap.ui.core.TextDirection.Inherit <code>"Inherit"</code>.
* If the provided <code>sValue</code> has a default value,
* the inherited direction from the DOM is used.
*
* @param {sap.ui.core.TextDirection} sValue New value for property <code>textDirection</code>.
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
* @since 1.28
*/
/**
* Gets the item from the aggregation named <code>items</code> at the given 0-based index.
*
* @param {int} iIndex Index of the item to return.
* @returns {sap.ui.core.Item | null} Item at the given index, or null if none.
* @public
* @since 1.16
*/
Select.prototype.getItemAt = function(iIndex) {
return this.getItems()[ +iIndex] || null;
};
/**
* Gets the selected item object from the aggregation named <code>items</code>.
*
* @returns {sap.ui.core.Item | null} The current target of the <code>selectedItem</code> association, or null.
* @public
*/
Select.prototype.getSelectedItem = function() {
var vSelectedItem = this.getAssociation("selectedItem");
return (vSelectedItem === null) ? null : sap.ui.getCore().byId(vSelectedItem) || null;
};
/**
* Gets the first item from the aggregation named <code>items</code>.
*
* @returns {sap.ui.core.Item | null} The first item, or null if there are no items.
* @public
* @since 1.16
*/
Select.prototype.getFirstItem = function() {
return this.getItems()[0] || null;
};
/**
* Gets the last item from the aggregation named <code>items</code>.
*
* @returns {sap.ui.core.Item | null} The last item, or null if there are no items.
* @public
* @since 1.16
*/
Select.prototype.getLastItem = function() {
var aItems = this.getItems();
return aItems[aItems.length - 1] || null;
};
/**
* Gets the enabled items from the aggregation named <code>items</code>.
*
* @param {sap.ui.core.Item[]} [aItems=getItems()] Items to filter.
* @return {sap.ui.core.Item[]} An array containing the enabled items.
* @public
* @since 1.22.0
*/
Select.prototype.getEnabledItems = function(aItems) {
var oList = this.getList();
return oList ? oList.getEnabledItems(aItems) : [];
};
/**
* Gets the item with the given key from the aggregation named <code>items</code>.<br>
* <b>Note: </b> If duplicate keys exist, the first item matching the key is returned.
*
* @param {string} sKey An item key that specifies the item to be retrieved.
* @returns {sap.ui.core.Item | null}
* @public
* @since 1.16
*/
Select.prototype.getItemByKey = function(sKey) {
var oList = this.getList();
return oList ? oList.getItemByKey(sKey) : null;
};
/**
* Removes an item from the aggregation named <code>items</code>.
*
* @param {int | string | sap.ui.core.Item} vItem The item to be removed or its index or ID.
* @returns {sap.ui.core.Item} The removed item or null.
* @public
*/
Select.prototype.removeItem = function(vItem) {
var oList = this.getList(),
oItem;
vItem = oList ? oList.removeItem(vItem) : null;
if (this.getItems().length === 0) {
this.clearSelection();
} else if (this.isItemSelected(vItem)) {
oItem = this.findFirstEnabledItem();
if (oItem) {
this.setSelection(oItem);
}
}
this.setValue(this._getSelectedItemText());
if (vItem) {
vItem.detachEvent("_change", this.onItemChange, this);
}
return vItem;
};
/**
* Removes all the items in the aggregation named <code>items</code>.
* Additionally unregisters them from the hosting UIArea and clears the selection.
*
* @returns {sap.ui.core.Item[]} An array of the removed items (might be empty).
* @public
*/
Select.prototype.removeAllItems = function() {
var oList = this.getList(),
aItems = oList ? oList.removeAllItems() : [];
// clear the selection
this.clearSelection();
if (!this.isInvalidateSuppressed()) {
this.invalidate();
}
for (var i = 0; i < aItems.length; i++) {
aItems[i].detachEvent("_change", this.onItemChange, this);
}
return aItems;
};
/**
* Destroys all the items in the aggregation named <code>items</code>.
*
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
*/
Select.prototype.destroyItems = function() {
var oList = this.getList();
if (oList) {
oList.destroyItems();
}
if (!this.isInvalidateSuppressed()) {
this.invalidate();
}
return this;
};
/**
* Indicates whether the control's picker popup is opened.
*
* @returns {boolean} Indicates whether the picker popup is currently open (this includes opening and closing animations).
* @public
* @since 1.16
*/
Select.prototype.isOpen = function() {
var oPicker = this.getAggregation("picker");
return !!(oPicker && oPicker.isOpen());
};
/**
* Closes the control's picker popup.
*
* @returns {sap.m.Select} <code>this</code> to allow method chaining.
* @public
* @since 1.16
*/
Select.prototype.close = function() {
var oPicker = this.getAggregation("picker");
if (oPicker) {
oPicker.close();
}
return this;
};
return Select;
}, /* bExport= */ true); |
import {default as bindScope} from './bind';
import {forEach, uid} from '../';
import Scope from '../scope';
const EACH_FOR = 'data-each-for';
// each="foo"
var propertyRegExp = '[a-zA-Z0-9_\\$\\.]+';
const PROPERTY_REG_EXP = new RegExp(`^${propertyRegExp}$`);
// each="foo in bar"
var eachInRegExp = `(${propertyRegExp})\\s+in\\s+(${propertyRegExp})`;
const EACH_IN_REG_EXP = new RegExp(`^${eachInRegExp}$`);
// each="i, foo in bar"
const KEY_VALUE_EACH_IN_REG_EXP = new RegExp(`^(${propertyRegExp})\\s*,\\s*${eachInRegExp}$`);
function eachValueAs(prop, callback, itemName) {
forEach(prop, val => callback({[itemName]: val}));
}
function eachKeyValueAs(prop, callback, keyName, valueName) {
forEach(prop, (value, key) => callback({
[keyName]: key,
[valueName]: value
}));
}
function bindLoop(element, scope) {
let id = uid();
let expression = element.getAttribute('each').trim();
let keyValue = KEY_VALUE_EACH_IN_REG_EXP.exec(expression);
let eachIn = EACH_IN_REG_EXP.exec(expression);
let logicLess = PROPERTY_REG_EXP.exec(expression);
let parent = element.parentElement;
let getScopeProp = name => scope[name] || [];
let empty = () => {
let elements = parent.querySelectorAll(`[${EACH_FOR}="${id}"]`);
forEach(elements, element => parent.removeChild(element));
};
let unbind = () => {};
let compile = (vars) => {
let node = element.cloneNode(true);
let childScope = new Scope(vars, scope, node);
unbind = bindScope(node, childScope);
parent.appendChild(node);
childScope.update();
};
function watch(propName, forEachValue, ...args) {
scope.watch(propName, () => {
empty();
unbind();
forEachValue.call(null, getScopeProp(propName), compile, ...args);
});
}
parent.removeChild(element);
element.setAttribute(EACH_FOR, id);
if (keyValue) {
// key, value in array
let [, keyName, valueName, propName] = keyValue;
watch(propName, eachKeyValueAs, keyName, valueName);
} else if (eachIn) {
// value in array
let [, itemName, propName] = eachIn;
watch(propName, eachValueAs, itemName);
} else if (logicLess) {
// logic less looping
watch(expression, forEach);
} else {
throw new SyntaxError(`Incorrect "each" expression: "${expression}"`);
}
}
export function bind(root, scope) {
let elements = root.querySelectorAll('[each]');
forEach(elements, (element) => bindLoop(element, scope));
}
|
// importa models/user
// import models/user
var User = require('../models/user');
// metodo proteger rotas com autenticação (token)
// method to protect routes with authentication
exports.authorize = (token, resp) => {
// .findOne() -> metodo mongoDB, procura token na BD
User.findOne({'token': token}, (error, user) => {
// em caso de erro
if (error) {
// com erro, devolve falso
resp(false);
} else if (user) {
// encontrando usuario, devolve verdadeiro
resp(true);
} else {
// nao encontrado usuario, devolve falso
resp(false);
}
});
}
// metodo para listar detalhes user autenticado
// method to list details user authenticated
exports.userData = (token, id, res) => {
// procura token BD
User.findOne({'token': token}, (error, user) => {
// em caso de erro
if (error) {
res.send(error.message);
// caso encontre usuario ...
} else if (user) {
// verifica se user.id corresponde ao da url
if (user.id === id) {
// devolve (detalhes) usuario
res.send(user);
} else {
// 403 devolve proibido (return forbidden)
res.sendStatus(403);
}
// no caso nao encontrar usuario
} else {
// devolve requisicao invalida (400)
// return invalid request (400)
res.sendStatus(400);
}
});
}
// metodo para pesquisar por id
// method for searching by id
/*
exports.userId = (req, res) => {
User.findById({_id: req.params.id}, (error, user) => {
if (error) {
res.status(400).send(error.message);
} else {
res.send(user);
}
})
}
*/
// metodo para inserir usuario, encripta senha e cria token
// method to insert user, encrypts password and creates token
exports.insert = (req, res) => {
// define propriedades obrigatorias
// define reqired fields/properties
// O nome é obrigatório | O e-mail é obrigatório | O e-mail inválido
// A senha é obrigatória
req.assert('name', 'Name is required').notEmpty();
req.assert('email', 'Email is required').notEmpty();
req.assert('email', 'Invalid email').isEmail();
req.assert('password', 'Password is required').notEmpty();
// anexa o(s) erro(s) das validacoes em 'error'
var error = req.validationErrors();
if (error) {
// em caso de existir erro, envia status '400'
// incase of error, sends status '400'
res.sendStatus(400).send(error.message);
} else {
// procura usuario pelo nome
// search user name
User.findOne({'email': req.body.email}, (error, user) => {
if (error) {
// devolve 412 - pre-condicao falhou
// returm 412 - precondition failed
res.sendStatus(412).send(error.message);
} else if (user) {
// um usuario com esse nome já existe
res.send('a user with that email already exists');
} else {
// 'user' recebe a instancia User
let user = new User();
user.name = req.body.name;
user.email = req.body.email;
// encriptar a senha
// encryp password
user.password = user.encryptPass(req.body.password);
// criar 'token'
// created 'token'
user.token = user.createToken(req.body.name, req.body.password);
user.save((error, user) => {
if (error) {
// devolve 412 - pre-condicao falhou
// returm 412 - precondition failed
res.sendStatus(412).send(error.message);
} else {
// devolve 201 - criado
// returm 201 - created
//res.sendStatus(201).send(user);
res.sendStatus(201);
}
});
}
})
}
}
// metodo autenticar usuario
// method user authentication
exports.auth = (req, res) => {
// define propriedades obrigatorias
// define reqired fields/properties
// O e-mail é obrigatório | A senha é obrigatória
req.assert('email', 'Email is required').notEmpty();
req.assert('password', 'Password is required').notEmpty();
// anexa o(s) erro(s) das validacoes em 'error'
var error = req.validationErrors();
if (error) {
// em caso de existir erro, envia status '400'
// incase of error, sends status '400'
res.sendStatus(400).send(error.message);
} else {
// .findOne() -> metodo mongoDB; procura user bd pelo nome
User.findOne({'email': req.body.email}, (error, user) => {
// em caso de erro
if (error) {
// devolve 412 - pre-condicao falhou
// returm 412 - precondition failed
//res.sendStatus(412).send(error.message);
res.send(error.message);
// caso encontre usuario ...
} else if (user) {
// confirma se a senha está correcta
if (user.validatePass(req.body.password, user.password)) {
// devolve token
// return token
res.send(user.token);
} else {
// devolve 'senha errada'
// return 'wrong password'
res.send('wrong password');
}
// caso nao encontre usuario ...
} else {
// 404 - nao encontrado
// 404 - not found
res.sendStatus(404)
// usuario nao existe
//res.send('user does not exist');
}
})
}
}
// metodo para actualizar usuario
// method user update
exports.update = (token, id, req, res) => {
// define propriedades obrigatorias
// define reqired fields/properties
// O nome é obrigatório | O e-mail é obrigatório | O e-mail inválido
// A senha é obrigatória
req.assert('name', 'Name is required').notEmpty();
req.assert('email', 'Email is required').notEmpty();
req.assert('email', 'Invalid email').isEmail();
req.assert('password', 'Password is required').notEmpty();
// anexa o(s) erro(s) das validacoes em 'error'
var error = req.validationErrors();
if (error) {
// em caso de existir erro, envia status '400'
// incase of error, sends status '400'
res.sendStatus(400).send(error.message);
} else {
// procura 'token' BD
User.findOne({'token': token}, (error, user) => {
// em caso de erro
if (error) {
// devolve descricao erro
res.send(error.message);
// caso encontre usuario ...
} else if (user) {
// verifica se user.id corresponde ao da url
if (user._id == id) {
// encriptar a senha
// encryp password
req.body.password = user.encryptPass(req.body.password);
// actualiza dados do usuario correspondente - id
User.update({_id: id}, req.body, (error, user) => {
// em caso de erro
if (error) {
// decolve 400 - requisicao invalida
// return 400 - invalid request
res.sendStatus(400).send(error.message);
// devolve 'id' usuario actualizado
} else {
// 204 - nenhum conteudo (no content)
//res.sendStatus(204).send(id);
//res.send('OK');
res.sendStatus(204);
}
})
} else {
// decolve 403 - proibido
// return 403 - forbidden
res.sendStatus(403);
}
} else {
// decolve 400 - requisicao invalida
// return 400 - invalid request
res.sendStatus(400);
}
});
}
}
// metodo para eliminar usuario
// method to delete user
exports.delete = (token, id, res) => {
// procura 'token' BD
User.findOne({'token': token}, (error, user) => {
// em caso de erro
if (error) {
// devolve descricao erro
res.send(error.message);
} else if (user) {
//console.log(user.id);
//console.log(id);
if (user.id === id) {
User.remove({_id: id}, (error, user) => {
//User.remove((error, user) => {
if (error) {
// decolve 400 - requisicao invalida
// return 400 - invalid request
res.sendStatus(400).send(error.message);
} else {
// 204 - nenhum conteudo (no content)
//res.status(204).send(id);
//res.send('OK');
res.sendStatus(204);
}
})
} else {
// decolve 403 - proibido
// return 403 - forbidden
res.sendStatus(403);
}
} else {
// decolve 400 - requisicao invalida
// return 400 - invalid request
res.sendStatus(400);
}
});
}
|
'use strict';
describe("filter", function() {
beforeEach(module("app"));
return describe("interpolate", function() {
beforeEach(module(function($provide) {
$provide.constant("VERSION", "TEST_VER"); // mock the service
}));
return it("should replace VERSION", inject(function(interpolateFilter) {
return expect(interpolateFilter("before %VERSION% after")).toEqual("before TEST_VER after");
}));
});
});
|
(function() {
var ArrMethods = {
where: function(attrs) {
var nodes = [];
_.each(this, function(model) {
nodes = nodes.concat(model.where(attrs));
});
return wrapArray(_.uniq(nodes));
}
};
var wrapArray = function(array) { return _.extend(array, ArrMethods); };
var TreeModel = Backbone.TreeModel = Backbone.Model.extend({
constructor: function tree(node) {
Backbone.Model.prototype.constructor.apply(this, arguments);
this._nodes = new this.collectionConstructor([], {
model : this.constructor
});
this._nodes.parent = this;
if(node && node.nodes) this.add(node.nodes);
},
collectionConstructor : null,
/**
* returns JSON object representing tree, account for branch changes
*/
toJSON: function() {
var jsonObj = _.clone(_.omit(this.attributes, 'nodes'));
var children = this._nodes.toJSON();
if(children.length) jsonObj.nodes = children;
return jsonObj;
},
/**
* returns descendant matching :id
*/
find: function(id) { return this.findWhere({id: id}); },
/**
* return first matched descendant
*/
findWhere: function(attrs) { return this.where(attrs, true); },
/**
* return all matched descendants
*/
where: function(attrs, first, excludeCurrentNode) {
var nodes = [], matchedNode;
// manual (non-collection method) check on the current node
if(!excludeCurrentNode && _.where([this.toJSON()], attrs)[0]) nodes.push(this);
if(first) {
// return if first/current node is a match
if(nodes[0]) return nodes[0];
// return first matched node in children collection
matchedNode = this._nodes.where(attrs, true);
if(_.isArray(matchedNode)) matchedNode = matchedNode[0];
if(matchedNode instanceof Backbone.Model) return matchedNode;
// recursive call on children nodes
for(var i=0, len=this._nodes.length; i<len; i++) {
matchedNode = this._nodes.at(i).where(attrs, true, true);
if(matchedNode) return matchedNode;
}
} else {
// add all matched children
nodes = nodes.concat(this._nodes.where(attrs));
// recursive call on children nodes
this._nodes.each(function(node) {
nodes = nodes.concat(node.where(attrs, false, true));
});
// return all matched nodes
return wrapArray(nodes);
}
},
/**
* returns true if current node is root node
*/
isRoot: function() { return this.parent() === null; },
/**
* returns the root for any node
*/
root: function() { return this.parent() && this.parent().root() || this; },
/**
* checks if current node contains argument node
*/
contains: function(node) {
if(!node || !(node.isRoot && node.parent) || node.isRoot()) return false;
var parent = node.parent();
return (parent === this) || this.contains(parent);
},
/**
* returns the parent node
*/
parent: function() { return this.collection && this.collection.parent || null; },
/**
* returns the children Backbone Collection if children nodes exist
*/
nodes: function() { return this._nodes.length && this._nodes || null; },
/**
* returns index of node relative to collection
*/
index: function() {
if(this.isRoot()) return null;
return this.collection.indexOf(this);
},
/**
* returns the node to the right
*/
next: function() {
if(this.isRoot()) return null;
var currentIndex = this.index();
if(currentIndex < this.collection.length-1) {
return this.collection.at(currentIndex+1);
} else {
return null;
}
},
/**
* returns the node to the left
*/
prev: function() {
if(this.isRoot()) return null;
var currentIndex = this.index();
if(currentIndex > 0) {
return this.collection.at(currentIndex-1);
} else {
return null;
}
},
/**
* removes current node if no attributes arguments is passed,
* otherswise remove matched nodes or first matched node
*/
remove: function(attrs, first) {
if(!attrs) {
if(this.isRoot()) return false; // can't remove root node
this.collection.remove(this);
return true;
} else {
if(first) {
this.where(attrs, true).remove();
} else {
_.each(this.where(attrs), function(node) {
if(node.collection) node.remove();
});
}
return this;
}
},
/**
* removes all children nodes
*/
empty: function() {
this._nodes.reset();
return this;
},
/**
* add child/children nodes to Backbone Collection
*/
add: function(node) {
if(node instanceof Backbone.Model && node.collection) node.collection.remove(node);
this._nodes.add.apply(this._nodes, arguments);
return this;
},
/**
* inserts a node before the current node
*/
insertBefore: function(node) {
if(!this.isRoot()) {
if(node instanceof Backbone.Model && node.collection) node.collection.remove(node);
this.parent().add(node, {at: this.index()});
}
return this;
},
/**
* inserts a node after the current node
*/
insertAfter: function(node) {
if(!this.isRoot()) {
if(node instanceof Backbone.Model && node.collection) node.collection.remove(node);
this.parent().add(node, {at: this.index()+1});
}
return this;
},
/**
* shorthand for getting/inserting nodes before
*/
before: function(nodes) {
if(nodes) return this.insertBefore(nodes);
return this.prev();
},
/**
* shorthand for getting/inserting nodes before
*/
after: function(nodes) {
if(nodes) return this.insertAfter(nodes);
return this.next();
}
});
var TreeCollection = Backbone.TreeCollection = Backbone.Collection.extend({
model: TreeModel,
where: function(attrs, opts) {
if(opts && opts.deep) {
var nodes = [];
this.each(function(model) {
nodes = nodes.concat(model.where(attrs));
});
return wrapArray(nodes);
} else {
return Backbone.Collection.prototype.where.apply(this, arguments);
}
}
});
Backbone.TreeModel.prototype.collectionConstructor = TreeCollection
}).call(this);
|
(function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)})(function(e){e.defineMode("solr",function(){function k(b){return function(a,c){for(var d=!1,g;null!=(g=a.next())&&(g!=b||d);)d=!d&&"\\"==g;d||(c.tokenize=f);return"string"}}function l(b){return function(a,c){var d="operator";"+"==b?d+=" positive":"-"==b?d+=" negative":"|"==b?a.eat(/\|/):"&"==b?a.eat(/&/):"^"==b&&(d+=
" boost");c.tokenize=f;return d}}function m(b){return function(a,c){for(var d=b;(b=a.peek())&&null!=b.match(h);)d+=a.next();c.tokenize=f;if(n.test(d))return"operator";c=d;return parseFloat(c).toString()===c?"number":":"==a.peek()?"field":"string"}}function f(b,a){var c=b.next();'"'==c?a.tokenize=k(c):p.test(c)?a.tokenize=l(c):h.test(c)&&(a.tokenize=m(c));return a.tokenize!=f?a.tokenize(b,a):null}var h=/[^\s\|!\+\-\*\?~\^&:\(\)\[\]\{\}"\\]/,p=/[\|!\+\-\*\?~\^&]/,n=/^(OR|AND|NOT|TO)$/i;return{startState:function(){return{tokenize:f}},
token:function(b,a){return b.eatSpace()?null:a.tokenize(b,a)}}});e.defineMIME("text/x-solr","solr")});
|
/*globals $,asyncTest,deepEqual,equal,expect,module,notDeepEqual,notEqual,
notStrictEqual,ok,QUnit,raises,start,stop,strictEqual,test */
var audioUrl = 'audio/the_black_atlantic_-_dandelion.mp3';
var errorUrl = 'audio/idonotexist.mp3';
asyncTest( " returns a promise object which should resolve with the audio object", 2, function() {
var promise = $.audioPromise(new Audio(audioUrl));
equal(typeof promise.done, 'function', 'typeof promise.done should be a function');
promise.done(function(audio) {
ok(audio.duration, 'audio.duration should not be NaN');
start();
});
});
asyncTest( "rejecte the promise if there is an error with the audio file", 1, function() {
var promise = $.audioPromise(new Audio(errorUrl));
promise.fail(function(audio) {
ok(true);
start();
});
});
asyncTest( "The promise should resolve if the loaddata event has alread fired", 1, function() {
var promise = $.audioPromise(new Audio(audioUrl));
promise.done(function(audio) {
var newPromise = $.audioPromise(audio);
newPromise.done(function() {
ok(true);
start();
});
});
});
asyncTest( "The promise should be rejected if the audio element has an error", 1, function() {
var promise = $.audioPromise(new Audio(errorUrl));
promise.fail(function(audio) {
var newPromise = $.audioPromise(audio);
newPromise.fail(function() {
ok(true);
start();
});
});
});
test( "audioPromise should return null if an audio element is not passed in as an argument", 1, function() {
var promise = $.audioPromise({});
equal(promise, null, 'promise should be null');
});
asyncTest( "audioPromise can be used as a jquery selector to select one element", 1, function() {
var promise = $('#test-element').audioPromise();
promise.done(function(audio) {
ok(audio.duration, 'audio.duration should not be NaN');
start();
});
});
asyncTest( "audioPromise can be used as a jquery selector on multiple elemens", 1, function() {
var promise = $('.maybe-audio').audioPromise();
promise.done(function() {
ok(true);
start();
});
});
asyncTest( "If one audio element fails to load the promise should be rejected", 1, function() {
var promise = $('.maybe-bad-audio').audioPromise();
promise.fail(function() {
ok(true);
start();
});
});
|
var searchData=
[
['findwhereattributes',['FindWhereAttributes',['../class_client_plugin_1_1_providers_1_1_identifier.html#aa316293812114130847eb77455704a97',1,'ClientPlugin::Providers::Identifier']]],
['findwhereopcodes',['FindWhereOpCodes',['../class_client_plugin_1_1_providers_1_1_identifier.html#a916ac175843a21421019092d9e198352',1,'ClientPlugin.Providers.Identifier.FindWhereOpCodes(params string[] opRegexes)'],['../class_client_plugin_1_1_providers_1_1_identifier.html#a21cfc47f8a81281cb127290c87b9fd04',1,'ClientPlugin.Providers.Identifier.FindWhereOpCodes(string opCodeRegex)']]],
['findwhereoperands',['FindWhereOperands',['../class_client_plugin_1_1_providers_1_1_identifier.html#a723398db06ee1d2ecd700a89d5eaf033',1,'ClientPlugin.Providers.Identifier.FindWhereOperands(params string[] opRegexes)'],['../class_client_plugin_1_1_providers_1_1_identifier.html#a926df3f79d4cd430ac37a178637ee126',1,'ClientPlugin.Providers.Identifier.FindWhereOperands(string operandRegex)']]]
];
|
module.exports = require('./GUI')
|
'use strict';
const bundleTypes = {
UMD_DEV: 'UMD_DEV',
UMD_PROD: 'UMD_PROD',
NODE_DEV: 'NODE_DEV',
NODE_PROD: 'NODE_PROD',
FB_WWW_DEV: 'FB_WWW_DEV',
FB_WWW_PROD: 'FB_WWW_PROD',
RN_OSS_DEV: 'RN_OSS_DEV',
RN_OSS_PROD: 'RN_OSS_PROD',
RN_FB_DEV: 'RN_FB_DEV',
RN_FB_PROD: 'RN_FB_PROD',
};
const UMD_DEV = bundleTypes.UMD_DEV;
const UMD_PROD = bundleTypes.UMD_PROD;
const NODE_DEV = bundleTypes.NODE_DEV;
const NODE_PROD = bundleTypes.NODE_PROD;
const FB_WWW_DEV = bundleTypes.FB_WWW_DEV;
const FB_WWW_PROD = bundleTypes.FB_WWW_PROD;
const RN_OSS_DEV = bundleTypes.RN_OSS_DEV;
const RN_OSS_PROD = bundleTypes.RN_OSS_PROD;
const RN_FB_DEV = bundleTypes.RN_FB_DEV;
const RN_FB_PROD = bundleTypes.RN_FB_PROD;
const moduleTypes = {
ISOMORPHIC: 'ISOMORPHIC',
RENDERER: 'RENDERER',
RENDERER_UTILS: 'RENDERER_UTILS',
RECONCILER: 'RECONCILER',
NON_FIBER_RENDERER: 'NON_FIBER_RENDERER',
};
// React
const ISOMORPHIC = moduleTypes.ISOMORPHIC;
// Individual renderers. They bundle the reconciler. (e.g. ReactDOM)
const RENDERER = moduleTypes.RENDERER;
// Helper packages that access specific renderer's internals. (e.g. TestUtils)
const RENDERER_UTILS = moduleTypes.RENDERER_UTILS;
// Standalone reconciler for third-party renderers.
const RECONCILER = moduleTypes.RECONCILER;
// Non-Fiber implementations like SSR and Shallow renderers.
const NON_FIBER_RENDERER = moduleTypes.NON_FIBER_RENDERER;
const bundles = [
/******* Isomorphic *******/
{
label: 'core',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: ISOMORPHIC,
entry: 'react',
global: 'React',
externals: [],
},
/******* React DOM *******/
{
label: 'dom-client',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: RENDERER,
entry: 'react-dom',
global: 'ReactDOM',
externals: ['react'],
},
//******* Test Utils *******/
{
label: 'dom-test-utils',
moduleType: RENDERER_UTILS,
bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
entry: 'react-dom/test-utils',
global: 'ReactTestUtils',
externals: ['react', 'react-dom'],
},
/* React DOM internals required for react-native-web (e.g., to shim native events from react-dom) */
{
label: 'dom-unstable-native-dependencies',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: RENDERER_UTILS,
entry: 'react-dom/unstable-native-dependencies',
global: 'ReactDOMUnstableNativeDependencies',
externals: ['react', 'react-dom'],
},
/******* React DOM Server *******/
{
label: 'dom-server-browser',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-dom/server.browser',
global: 'ReactDOMServer',
externals: ['react'],
},
{
label: 'dom-server-node',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: NON_FIBER_RENDERER,
entry: 'react-dom/server.node',
externals: ['react', 'stream'],
},
/******* React ART *******/
{
label: 'art',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: RENDERER,
entry: 'react-art',
global: 'ReactART',
externals: ['react'],
babel: opts =>
Object.assign({}, opts, {
// Include JSX
presets: opts.presets.concat([require.resolve('babel-preset-react')]),
}),
},
/******* React Native *******/
{
label: 'native-fb',
bundleTypes: [RN_FB_DEV, RN_FB_PROD],
moduleType: RENDERER,
entry: 'react-native-renderer',
global: 'ReactNativeRenderer',
externals: [
'ExceptionsManager',
'InitializeCore',
'Platform',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'ReactNativeViewConfigRegistry',
],
},
{
label: 'native',
bundleTypes: [RN_OSS_DEV, RN_OSS_PROD],
moduleType: RENDERER,
entry: 'react-native-renderer',
global: 'ReactNativeRenderer',
externals: [
'ExceptionsManager',
'InitializeCore',
'Platform',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'ReactNativeViewConfigRegistry',
],
},
/******* React Native Fabric *******/
{
label: 'native-fabric-fb',
bundleTypes: [RN_FB_DEV, RN_FB_PROD],
moduleType: RENDERER,
entry: 'react-native-renderer/fabric',
global: 'ReactFabric',
externals: [
'ExceptionsManager',
'InitializeCore',
'Platform',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'FabricUIManager',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'ReactNativeViewConfigRegistry',
],
},
{
label: 'native-fabric',
bundleTypes: [RN_OSS_DEV, RN_OSS_PROD],
moduleType: RENDERER,
entry: 'react-native-renderer/fabric',
global: 'ReactFabric',
externals: [
'ExceptionsManager',
'InitializeCore',
'Platform',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'FabricUIManager',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'ReactNativeViewConfigRegistry',
],
},
/******* React Test Renderer *******/
{
label: 'test',
bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: RENDERER,
entry: 'react-test-renderer',
global: 'ReactTestRenderer',
externals: ['react'],
},
{
label: 'test-shallow',
bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: NON_FIBER_RENDERER,
entry: 'react-test-renderer/shallow',
global: 'ReactShallowRenderer',
externals: ['react'],
},
/******* React Noop Renderer (used for tests) *******/
{
label: 'noop',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer',
global: 'ReactNoopRenderer',
externals: ['react', 'expect'],
// React Noop uses generators. However GCC currently
// breaks when we attempt to use them in the output.
// So we precompile them with regenerator, and include
// it as a runtime dependency of React Noop. In practice
// this isn't an issue because React Noop is only used
// in our tests. We wouldn't want to do this for any
// public package though.
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
require.resolve('babel-plugin-transform-regenerator'),
]),
}),
},
/******* React Noop Persistent Renderer (used for tests) *******/
{
label: 'noop-persistent',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer/persistent',
global: 'ReactNoopRendererPersistent',
externals: ['react', 'expect'],
// React Noop uses generators. However GCC currently
// breaks when we attempt to use them in the output.
// So we precompile them with regenerator, and include
// it as a runtime dependency of React Noop. In practice
// this isn't an issue because React Noop is only used
// in our tests. We wouldn't want to do this for any
// public package though.
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
require.resolve('babel-plugin-transform-regenerator'),
]),
}),
},
/******* React Reconciler *******/
{
label: 'react-reconciler',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-reconciler',
global: 'ReactReconciler',
externals: ['react'],
},
/******* React Persistent Reconciler *******/
{
label: 'react-reconciler-persistent',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-reconciler/persistent',
global: 'ReactPersistentReconciler',
externals: ['react'],
},
/******* Reflection *******/
{
label: 'reconciler-reflection',
moduleType: RENDERER_UTILS,
bundleTypes: [NODE_DEV, NODE_PROD],
entry: 'react-reconciler/reflection',
global: 'ReactFiberTreeReflection',
externals: [],
},
/******* React Is *******/
{
label: 'react-is',
bundleTypes: [
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
UMD_DEV,
UMD_PROD,
],
moduleType: ISOMORPHIC,
entry: 'react-is',
global: 'ReactIs',
externals: [],
},
/******* Simple Cache Provider (experimental) *******/
{
label: 'simple-cache-provider',
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD, NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'simple-cache-provider',
global: 'SimpleCacheProvider',
externals: ['react'],
},
/******* createComponentWithSubscriptions (experimental) *******/
{
label: 'create-subscription',
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'create-subscription',
global: 'createSubscription',
externals: ['react'],
},
/******* React Scheduler (experimental) *******/
{
label: 'react-scheduler',
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: ISOMORPHIC,
entry: 'react-scheduler',
global: 'ReactScheduler',
externals: [],
},
];
// Based on deep-freeze by substack (public domain)
function deepFreeze(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(function(prop) {
if (
o[prop] !== null &&
(typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
!Object.isFrozen(o[prop])
) {
deepFreeze(o[prop]);
}
});
return o;
}
// Don't accidentally mutate config as part of the build
deepFreeze(bundles);
module.exports = {
bundleTypes,
moduleTypes,
bundles,
};
|
module.exports = {
'secret': 'Secret string for encoding in the api',
'database': 'mongoDB URL'
};
|
// React Component
import React,{ Component,PropTypes } from 'react'
import { Menu, Icon } from 'xComponent'
const SubMenu = Menu.SubMenu
const Item = Menu.Item
import logo from '../img/logo.png'
import defaultUser from '../img/defaultUser.png'
export default class PortalHeaderComponent extends Component {
handleMenuClick(e){
if(e.key === 'logout')
this.props.onLogoutSucess()
}
render() {
let {prefixCls} = this.props,
menu = '导航'
return (
<header className={`${prefixCls}-header`}>
<div className={`${prefixCls}-header-logo`}>
<img height="33" src={logo} />
</div>
<div className={`${prefixCls}-header-nav`} >
<Menu
mode="horizontal"
onClick={::this.handleMenuClick}>
<Item key="a">{menu}</Item>
<Item key="b">{menu}</Item>
<Item key="c">{menu}</Item>
<SubMenu title={<span><img height="25" src={defaultUser} style={{marginRight:8}} />某某某</span>}>
<Item key="logout">注销</Item>
<Menu.Divider />
<Item key="user">个人中心</Item>
<Menu.Divider />
<Item key="about">关于</Item>
<Item key="help">帮助</Item>
</SubMenu>
</Menu>
</div>
</header>
)
}
}
|
function sum_AB_test(mode) {
var gpu = new GPU({ mode });
var f = gpu.createKernel(function(a, b) {
return (a[this.thread.x] + b[this.thread.x]);
}, {
output : [6],
mode : mode
});
QUnit.assert.ok( f !== null, "function generated test");
var a = [1, 2, 3, 5, 6, 7];
var b = [4, 5, 6, 1, 2, 3];
var res = f(a,b);
var exp = [5, 7, 9, 6, 8, 10];
for(var i = 0; i < exp.length; ++i) {
QUnit.assert.close(res[i], exp[i], 0.1, "Result arr idx: "+i);
}
}
QUnit.test( "sum_AB (auto)", function() {
sum_AB_test(null);
});
QUnit.test( "sum_AB (WebGL)", function() {
sum_AB_test("webgl");
});
QUnit.test( "sum_AB (CPU)", function() {
sum_AB_test("cpu");
});
|
import callMethod from '../callMethod'
export default async function (root, {email}, context) {
callMethod(context, 'forgotPassword', {email})
return {
success: true
}
}
|
import React,{PropTypes} from 'react';
class InputEmail extends React.Component {
constructor(props, context) {
super(props, context);
this.removeInput = this.removeInput.bind(this);
this.updateEmail = this.updateEmail.bind(this);
}
removeInput() {
this.props.deleteManagerInputs(this.props.position);
}
updateEmail(){
return this.props.updateEmailState(this.props.position);
}
isHiddenButtonRemove(){
return this.props.email === "" && this.props.oneInput;
}
isHiddenButtonAdd(){
const LIMIT_MAX_EMAILS = 5;
return this.props.position === LIMIT_MAX_EMAILS-1;
}
render(){
return (<div>
<input
className="form-control"
type="email"
value={this.props.email}
onChange={this.updateEmail()}
/>
<input type="button"
className={this.isHiddenButtonAdd() ? "btn hidden" : "btn"}
onClick={this.props.addManagerInputs} value="+"/>
<input type="button"
className={this.isHiddenButtonRemove() ? "btn hidden" : "btn"}
onClick={this.removeInput} value="-"/>
</div>);
}
}
InputEmail.propTypes = {
position: PropTypes.number.isRequired,
deleteManagerInputs: PropTypes.func.isRequired,
updateEmailState: PropTypes.func.isRequired,
addManagerInputs: PropTypes.func.isRequired,
oneInput: PropTypes.bool.isRequired,
email: PropTypes.string
};
export default InputEmail;
|
import React from 'react';
import "./styles.css";
import Section from '../Section';
const SectionDark = (props) => <Section {...props} className="SectionDark">{props.children}</Section>;
export default SectionDark
|
export default {
AF: 'Afghanistan',
EG: 'Ägypten',
AX: 'Åland',
AL: 'Albanien',
DZ: 'Algerien',
AS: 'Amerikanisch-Samoa',
VI: 'Amerikanische Jungferninseln',
AD: 'Andorra',
AO: 'Angola',
AI: 'Anguilla',
AQ: 'Antarktika',
AG: 'Antigua und Barbuda',
GQ: 'Äquatorialguinea',
AR: 'Argentinien',
AM: 'Armenien',
AW: 'Aruba',
AZ: 'Aserbaidschan',
ET: 'Äthiopien',
AU: 'Australien',
BS: 'Bahamas',
BH: 'Bahrain',
BD: 'Bangladesch',
BB: 'Barbados',
BY: 'Weißrussland',
BE: 'Belgien',
BZ: 'Belize',
BJ: 'Benin',
BM: 'Bermuda',
BT: 'Bhutan',
BO: 'Bolivien',
BQ: 'Bonaire',
BA: 'Bosnien und Herzegowina',
BW: 'Botswana',
BV: 'Bouvetinsel',
BR: 'Brasilien',
VG: 'Britische Jungferninseln',
IO: 'Britisches Territorium im Indischen Ozean',
BN: 'Brunei Darussalam',
BG: 'Bulgarien',
BF: 'Burkina Faso',
BI: 'Burundi',
CL: 'Chile',
CN: 'China',
CK: 'Cookinseln',
CR: 'Costa Rica',
CI: 'Elfenbeinküste',
CW: 'Curaçao',
DK: 'Dänemark',
DE: 'Deutschland',
DM: 'Dominica',
DO: 'Dominikanische Republik',
DJ: 'Dschibuti',
EC: 'Ecuador',
SV: 'El Salvador',
ER: 'Eritrea',
EE: 'Estland',
FK: 'Falklandinseln',
FO: 'Färöer',
FJ: 'Fidschi',
FI: 'Finnland',
FR: 'Frankreich',
GF: 'Französisch-Guayana',
PF: 'Französisch-Polynesien',
TF: 'Französische Süd- und Antarktisgebiete',
GA: 'Gabun',
GM: 'Gambia',
GE: 'Georgien',
GH: 'Ghana',
GI: 'Gibraltar',
GD: 'Grenada',
GR: 'Griechenland',
GL: 'Grönland',
GP: 'Guadeloupe',
GU: 'Guam',
GT: 'Guatemala',
GG: 'Guernsey',
GN: 'Guinea',
GW: 'Guinea-Bissau',
GY: 'Guyana',
HT: 'Haiti',
HM: 'Heard und McDonaldinseln',
HN: 'Honduras',
HK: 'Hongkong',
IN: 'Indien',
ID: 'Indonesien',
IM: 'Insel Man',
IQ: 'Irak',
IR: 'Iran',
IE: 'Irland',
IS: 'Island',
IL: 'Israel',
IT: 'Italien',
JM: 'Jamaika',
JP: 'Japan',
YE: 'Jemen',
JE: 'Jersey',
JO: 'Jordanien',
KY: 'Kaimaninseln',
KH: 'Kambodscha',
CM: 'Kamerun',
CA: 'Kanada',
CV: 'Kap Verde',
KZ: 'Kasachstan',
QA: 'Katar',
KE: 'Kenia',
KG: 'Kirgisistan',
KI: 'Kiribati',
CC: 'Kokosinseln',
CO: 'Kolumbien',
KM: 'Komoren',
CD: 'Kongo',
KP: 'Nordkorea',
KR: 'Südkorea',
HR: 'Kroatien',
CU: 'Kuba',
KW: 'Kuwait',
LA: 'Laos',
LS: 'Lesotho',
LV: 'Lettland',
LB: 'Libanon',
LR: 'Liberia',
LY: 'Libyen',
LI: 'Liechtenstein',
LT: 'Litauen',
LU: 'Luxemburg',
MO: 'Macao',
MG: 'Madagaskar',
MW: 'Malawi',
MY: 'Malaysia',
MV: 'Malediven',
ML: 'Mali',
MT: 'Malta',
MA: 'Marokko',
MH: 'Marshallinseln',
MQ: 'Martinique',
MR: 'Mauretanien',
MU: 'Mauritius',
YT: 'Mayotte',
MK: 'Mazedonien',
MX: 'Mexiko',
FM: 'Mikronesien',
MD: 'Moldawien',
MC: 'Monaco',
MN: 'Mongolei',
ME: 'Montenegro',
MS: 'Montserrat',
MZ: 'Mosambik',
MM: 'Myanmar',
NA: 'Namibia',
NR: 'Nauru',
NP: 'Nepal',
NC: 'Neukaledonien',
NZ: 'Neuseeland',
NI: 'Nicaragua',
NL: 'Niederlande',
NE: 'Niger',
NG: 'Nigeria',
NU: 'Niue',
MP: 'Nördliche Marianen',
NF: 'Norfolkinsel',
NO: 'Norwegen',
OM: 'Oman',
AT: 'Österreich',
TL: 'Osttimor',
PK: 'Pakistan',
PS: 'Staat Palästina',
PW: 'Palau',
PA: 'Panama',
PG: 'Papua-Neuguinea',
PY: 'Paraguay',
PE: 'Peru',
PH: 'Philippinen',
PN: 'Pitcairninseln',
PL: 'Polen',
PT: 'Portugal',
PR: 'Puerto Rico',
TW: 'Taiwan',
CG: 'Republik Kongo',
RE: 'Réunion',
RW: 'Ruanda',
RO: 'Rumänien',
RU: 'Russische Föderation',
BL: 'Saint-Barthélemy',
MF: 'Saint-Martin',
SB: 'Salomonen',
ZM: 'Sambia',
WS: 'Samoa',
SM: 'San Marino',
ST: 'São Tomé und Príncipe',
SA: 'Saudi-Arabien',
SE: 'Schweden',
CH: 'Schweiz',
SN: 'Senegal',
RS: 'Serbien',
SC: 'Seychellen',
SL: 'Sierra Leone',
ZW: 'Simbabwe',
SG: 'Singapur',
SX: 'Sint Maarten',
SK: 'Slowakei',
SI: 'Slowenien',
SO: 'Somalia',
ES: 'Spanien',
LK: 'Sri Lanka',
SH: 'St. Helena',
KN: 'St. Kitts und Nevis',
LC: 'St. Lucia',
PM: 'Saint-Pierre und Miquelon',
VC: 'St. Vincent und die Grenadinen',
ZA: 'Südafrika',
SD: 'Sudan',
GS: 'Südgeorgien und die Südlichen Sandwichinseln',
SS: 'Südsudan',
SR: 'Suriname',
SJ: 'Svalbard und Jan Mayen',
SZ: 'Swasiland',
SY: 'Syrien, Arabische Republik',
TJ: 'Tadschikistan',
TZ: 'Tansania, Vereinigte Republik',
TH: 'Thailand',
TG: 'Togo',
TK: 'Tokelau',
TO: 'Tonga',
TT: 'Trinidad und Tobago',
TD: 'Tschad',
CZ: 'Tschechische Republik',
TN: 'Tunesien',
TR: 'Türkei',
TM: 'Turkmenistan',
TC: 'Turks- und Caicosinseln',
TV: 'Tuvalu',
UG: 'Uganda',
UA: 'Ukraine',
HU: 'Ungarn',
UM: 'United States Minor Outlying Islands',
UY: 'Uruguay',
UZ: 'Usbekistan',
VU: 'Vanuatu',
VA: 'Vatikanstadt',
VE: 'Venezuela',
AE: 'Vereinigte Arabische Emirate',
US: 'Vereinigte Staaten von Amerika',
GB: 'Vereinigtes Königreich Großbritannien und Nordirland',
VN: 'Vietnam',
WF: 'Wallis und Futuna',
CX: 'Weihnachtsinsel',
EH: 'Westsahara',
CF: 'Zentralafrikanische Republik',
CY: 'Zypern'
};
|
var mongoose = require('mongoose');
module.exports = function (uri) {
mongoose.connect(uri);
mongoose.connection.on('connected', function () {
console.log('Mongoose! Conectado em ' + uri);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose! Desconectado de ' + uri);
});
mongoose.connection.on('error', function (erro) {
console.log('Mongoose! Erro na conexão: ' + erro);
});
process.on('SIGINT', function() {
mongoose.connection.close(function() {
console.log('Mongoose! Desconectado.');
// 0 indica que a finalização ocorreu sem erros
process.exit(0);
});
});
}
|
soku.factory('sokuService', ['$rootScope', '$http', '$routeParams',
function($rootScope, $http, $routeParams) {
var serviceBase = 'api/';
params = $routeParams;
function getGameId(){
return params.gameId;
}
return {
getPlayerTurn : function(){
return $http.get(serviceBase + 'player' + '/' + getGameId());
},
getPlayer : function(player){
return $http.get(serviceBase + 'player' + '/' + getGameId() + '/' + player);
},
isPiecePlayable : function(piece){
return $http.get(serviceBase + 'playable' + '/' + getGameId() + '/' + piece);
},
play : function(piece, tile){
return $http.get(serviceBase + 'play' + '/' + getGameId() + '/' + piece + '/' + tile);
},
getGame : function(gameId){
return $http.get(serviceBase + 'game' + '/' + gameId);
},
getGames : function(){
return $http.get(serviceBase + 'games');
},
newGame : function(){
return $http.get(serviceBase + 'game/new');
}
}
}]); |
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
clean: {
dev: ["dev/css/fonts"],
build: ["build/**/*", "!build/VERSION"],
cleanup: [".grunt/"]
},
copy: {
dev: {
expand: true,
cwd: "node_modules/bootstrap-sass/assets/fonts/bootstrap/",
src: "**",
dest: "dev/css/fonts/"
},
build: {
expand: true,
cwd: "dev",
src: ["*", "css/fonts/**", "img/**"],
dest: "build/",
filter: "isFile"
}
},
concat: {
build: {
src: [
"dev/js/jquery-3.3.1.slim.min.js",
"dev/js/spambotscare-1.0.0.js",
"node_modules/bootstrap-sass/assets/javascripts/bootstrap.js"
// "node_modules/flipclock/compiled/flipclock.js",
// "dev/js/eventsobject.js",
// "dev/js/script.js",
// "dev/js/jquery.validate.min.js",
// "dev/js/messages_de.min.js",
// "dev/js/ajaxform.js"
],
dest: ".grunt/js/<%= pkg.name %>.js"
}
},
uglify: {
options: {
banner:
'/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: ".grunt/js/<%= pkg.name %>.js",
dest: "build/js/<%= pkg.name %>.min.js"
}
},
compass: {
dev: {
options: {
bundleExec: true,
sassDir: "dev/scss",
cssDir: "dev/css"
}
},
build: {
options: {
bundleExec: true,
sassDir: "dev/scss",
cssDir: "build/css",
environment: "production"
}
}
},
filerev: {
build: {
src: [
"build/img/*.{jpg,jpeg,gif,png,webp}",
"!build/img/weltengeschichte-preview.jpg",
"!build/img/weltengeschichte-video-preview.jpg",
"build/css/*.css",
"build/js/weltengeschichte.min.js"
]
}
},
useminPrepare: {
html: "dev/teaser.html",
options: {
dest: "build"
}
},
usemin: {
html: ["build/*.html"],
css: "build/css/**.css"
},
imagemin: {
compressdev: {
files: [
{
expand: true,
cwd: "dev/img/",
src: ["**/*.{png,jpg,gif}"],
dest: "dev/img/"
}
]
}
},
json: {
main: {
src: ["dev/events.json"],
dest: "dev/js/eventsobject.js"
}
}
});
// Load the plugins
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-compass");
grunt.loadNpmTasks("grunt-usemin");
grunt.loadNpmTasks("grunt-filerev");
grunt.loadNpmTasks("grunt-newer");
grunt.loadNpmTasks("grunt-contrib-imagemin");
grunt.loadNpmTasks("grunt-json");
// Tasks.
grunt.registerTask("dev", "Set up dev environment", [
"clean:dev",
"copy:dev",
"compass:dev",
"json"
]);
grunt.registerTask("compress", "Compress images", [
"newer:imagemin:compressdev"
]);
grunt.registerTask("build", "Build the website into the build/ filder", [
"clean:build",
"copy:build",
"useminPrepare",
"json",
"concat:build",
"uglify:build",
"compass:build",
"filerev",
"usemin",
"clean:cleanup"
]);
grunt.registerTask("js", "Just update weltengeschichte.2.min.js", [
"concat:build",
"uglify:build"
]);
// grunt.registerTask('deploy', 'Deploy the website', customDeployTask);
// function customDeployTask() {
// grunt.task.run('build');
// grunt.task.run('copy:deploy');
// }
};
|
// is location refreshing currently on?
var watchingPosition = false;
// current location variable and dependency
var location = new ReactiveVar(null);
// error variable and dependency
var error = new ReactiveVar(null);
var onError = function (newError) {
error.set(newError);
};
var onPosition = function (newLocation) {
location.set(newLocation);
error.set(null);
};
var startWatchingPosition = function (options) {
if (! watchingPosition && navigator.geolocation) {
options = options || {
enableHighAccuracy: true,
maximumAge: 0,
timeout: 10000
};
navigator.geolocation.watchPosition(onPosition, onError, options);
watchingPosition = true;
}
};
// exports
/**
* @summary The namespace for all geolocation functions.
* @namespace
*/
Geolocation = {
/**
* @summary Get the current geolocation error
* @return {PositionError} The
* [position error](https://developer.mozilla.org/en-US/docs/Web/API/PositionError)
* that is currently preventing position updates.
*/
error: function (options) {
startWatchingPosition(options);
return error.get();
},
/**
* @summary Get the current location
* @return {Position | null} The
* [position](https://developer.mozilla.org/en-US/docs/Web/API/Position)
* that is reported by the device, or null if no position is available.
*/
currentLocation: function (options) {
startWatchingPosition(options);
return location.get();
},
// simple version of location; just lat and lng
/**
* @summary Get the current latitude and longitude
* @return {Object | null} An object with `lat` and `lng` properties,
* or null if no position is available.
*/
latLng: function (options) {
var loc = Geolocation.currentLocation(options);
if (loc) {
return {
lat: loc.coords.latitude,
lng: loc.coords.longitude
};
}
return null;
}
};
|
// FIXME should possibly show tooltip when dragging?
goog.provide('ol.control.ZoomSlider');
goog.require('ol');
goog.require('ol.View');
goog.require('ol.animation');
goog.require('ol.control.Control');
goog.require('ol.css');
goog.require('ol.easing');
goog.require('ol.events');
goog.require('ol.events.Event');
goog.require('ol.events.EventType');
goog.require('ol.math');
goog.require('ol.pointer.PointerEventHandler');
/**
* @classdesc
* A slider type of control for zooming.
*
* Example:
*
* map.addControl(new ol.control.ZoomSlider());
*
* @constructor
* @extends {ol.control.Control}
* @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options.
* @api stable
*/
ol.control.ZoomSlider = function(opt_options) {
var options = opt_options ? opt_options : {};
/**
* Will hold the current resolution of the view.
*
* @type {number|undefined}
* @private
*/
this.currentResolution_ = undefined;
/**
* The direction of the slider. Will be determined from actual display of the
* container and defaults to ol.control.ZoomSlider.direction.VERTICAL.
*
* @type {ol.control.ZoomSlider.direction}
* @private
*/
this.direction_ = ol.control.ZoomSlider.direction.VERTICAL;
/**
* @type {boolean}
* @private
*/
this.dragging_;
/**
* @type {!Array.<ol.EventsKey>}
* @private
*/
this.dragListenerKeys_ = [];
/**
* @type {number}
* @private
*/
this.heightLimit_ = 0;
/**
* @type {number}
* @private
*/
this.widthLimit_ = 0;
/**
* @type {number|undefined}
* @private
*/
this.previousX_;
/**
* @type {number|undefined}
* @private
*/
this.previousY_;
/**
* The calculated thumb size (border box plus margins). Set when initSlider_
* is called.
* @type {ol.Size}
* @private
*/
this.thumbSize_ = null;
/**
* Whether the slider is initialized.
* @type {boolean}
* @private
*/
this.sliderInitialized_ = false;
/**
* @type {number}
* @private
*/
this.duration_ = options.duration !== undefined ? options.duration : 200;
var className = options.className !== undefined ? options.className : 'ol-zoomslider';
var thumbElement = document.createElement('button');
thumbElement.setAttribute('type', 'button');
thumbElement.className = className + '-thumb ' + ol.css.CLASS_UNSELECTABLE;
var containerElement = document.createElement('div');
containerElement.className = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' + ol.css.CLASS_CONTROL;
containerElement.appendChild(thumbElement);
/**
* @type {ol.pointer.PointerEventHandler}
* @private
*/
this.dragger_ = new ol.pointer.PointerEventHandler(containerElement);
ol.events.listen(this.dragger_, ol.pointer.EventType.POINTERDOWN,
this.handleDraggerStart_, this);
ol.events.listen(this.dragger_, ol.pointer.EventType.POINTERMOVE,
this.handleDraggerDrag_, this);
ol.events.listen(this.dragger_, ol.pointer.EventType.POINTERUP,
this.handleDraggerEnd_, this);
ol.events.listen(containerElement, ol.events.EventType.CLICK,
this.handleContainerClick_, this);
ol.events.listen(thumbElement, ol.events.EventType.CLICK,
ol.events.Event.stopPropagation);
var render = options.render ? options.render : ol.control.ZoomSlider.render;
ol.control.Control.call(this, {
element: containerElement,
render: render
});
};
ol.inherits(ol.control.ZoomSlider, ol.control.Control);
/**
* @inheritDoc
*/
ol.control.ZoomSlider.prototype.disposeInternal = function() {
this.dragger_.dispose();
ol.control.Control.prototype.disposeInternal.call(this);
};
/**
* The enum for available directions.
*
* @enum {number}
*/
ol.control.ZoomSlider.direction = {
VERTICAL: 0,
HORIZONTAL: 1
};
/**
* @inheritDoc
*/
ol.control.ZoomSlider.prototype.setMap = function(map) {
ol.control.Control.prototype.setMap.call(this, map);
if (map) {
map.render();
}
};
/**
* Initializes the slider element. This will determine and set this controls
* direction_ and also constrain the dragging of the thumb to always be within
* the bounds of the container.
*
* @private
*/
ol.control.ZoomSlider.prototype.initSlider_ = function() {
var container = this.element;
var containerSize = {
width: container.offsetWidth, height: container.offsetHeight
};
var thumb = container.firstElementChild;
var computedStyle = ol.global.getComputedStyle(thumb);
var thumbWidth = thumb.offsetWidth +
parseFloat(computedStyle['marginRight']) +
parseFloat(computedStyle['marginLeft']);
var thumbHeight = thumb.offsetHeight +
parseFloat(computedStyle['marginTop']) +
parseFloat(computedStyle['marginBottom']);
this.thumbSize_ = [thumbWidth, thumbHeight];
if (containerSize.width > containerSize.height) {
this.direction_ = ol.control.ZoomSlider.direction.HORIZONTAL;
this.widthLimit_ = containerSize.width - thumbWidth;
} else {
this.direction_ = ol.control.ZoomSlider.direction.VERTICAL;
this.heightLimit_ = containerSize.height - thumbHeight;
}
this.sliderInitialized_ = true;
};
/**
* Update the zoomslider element.
* @param {ol.MapEvent} mapEvent Map event.
* @this {ol.control.ZoomSlider}
* @api
*/
ol.control.ZoomSlider.render = function(mapEvent) {
if (!mapEvent.frameState) {
return;
}
if (!this.sliderInitialized_) {
this.initSlider_();
}
var res = mapEvent.frameState.viewState.resolution;
if (res !== this.currentResolution_) {
this.currentResolution_ = res;
this.setThumbPosition_(res);
}
};
/**
* @param {Event} event The browser event to handle.
* @private
*/
ol.control.ZoomSlider.prototype.handleContainerClick_ = function(event) {
var map = this.getMap();
var view = map.getView();
var currentResolution = view.getResolution();
map.beforeRender(ol.animation.zoom({
resolution: /** @type {number} */ (currentResolution),
duration: this.duration_,
easing: ol.easing.easeOut
}));
var relativePosition = this.getRelativePosition_(
event.offsetX - this.thumbSize_[0] / 2,
event.offsetY - this.thumbSize_[1] / 2);
var resolution = this.getResolutionForPosition_(relativePosition);
view.setResolution(view.constrainResolution(resolution));
};
/**
* Handle dragger start events.
* @param {ol.pointer.PointerEvent} event The drag event.
* @private
*/
ol.control.ZoomSlider.prototype.handleDraggerStart_ = function(event) {
if (!this.dragging_ &&
event.originalEvent.target === this.element.firstElementChild) {
this.getMap().getView().setHint(ol.View.Hint.INTERACTING, 1);
this.previousX_ = event.clientX;
this.previousY_ = event.clientY;
this.dragging_ = true;
if (this.dragListenerKeys_.length === 0) {
var drag = this.handleDraggerDrag_;
var end = this.handleDraggerEnd_;
this.dragListenerKeys_.push(
ol.events.listen(document, ol.events.EventType.MOUSEMOVE, drag, this),
ol.events.listen(document, ol.events.EventType.TOUCHMOVE, drag, this),
ol.events.listen(document, ol.pointer.EventType.POINTERMOVE, drag, this),
ol.events.listen(document, ol.events.EventType.MOUSEUP, end, this),
ol.events.listen(document, ol.events.EventType.TOUCHEND, end, this),
ol.events.listen(document, ol.pointer.EventType.POINTERUP, end, this)
);
}
}
};
/**
* Handle dragger drag events.
*
* @param {ol.pointer.PointerEvent|Event} event The drag event.
* @private
*/
ol.control.ZoomSlider.prototype.handleDraggerDrag_ = function(event) {
if (this.dragging_) {
var element = this.element.firstElementChild;
var deltaX = event.clientX - this.previousX_ + parseInt(element.style.left, 10);
var deltaY = event.clientY - this.previousY_ + parseInt(element.style.top, 10);
var relativePosition = this.getRelativePosition_(deltaX, deltaY);
this.currentResolution_ = this.getResolutionForPosition_(relativePosition);
this.getMap().getView().setResolution(this.currentResolution_);
this.setThumbPosition_(this.currentResolution_);
this.previousX_ = event.clientX;
this.previousY_ = event.clientY;
}
};
/**
* Handle dragger end events.
* @param {ol.pointer.PointerEvent|Event} event The drag event.
* @private
*/
ol.control.ZoomSlider.prototype.handleDraggerEnd_ = function(event) {
if (this.dragging_) {
var map = this.getMap();
var view = map.getView();
view.setHint(ol.View.Hint.INTERACTING, -1);
map.beforeRender(ol.animation.zoom({
resolution: /** @type {number} */ (this.currentResolution_),
duration: this.duration_,
easing: ol.easing.easeOut
}));
var resolution = view.constrainResolution(this.currentResolution_);
view.setResolution(resolution);
this.dragging_ = false;
this.previousX_ = undefined;
this.previousY_ = undefined;
this.dragListenerKeys_.forEach(ol.events.unlistenByKey);
this.dragListenerKeys_.length = 0;
}
};
/**
* Positions the thumb inside its container according to the given resolution.
*
* @param {number} res The res.
* @private
*/
ol.control.ZoomSlider.prototype.setThumbPosition_ = function(res) {
var position = this.getPositionForResolution_(res);
var thumb = this.element.firstElementChild;
if (this.direction_ == ol.control.ZoomSlider.direction.HORIZONTAL) {
thumb.style.left = this.widthLimit_ * position + 'px';
} else {
thumb.style.top = this.heightLimit_ * position + 'px';
}
};
/**
* Calculates the relative position of the thumb given x and y offsets. The
* relative position scales from 0 to 1. The x and y offsets are assumed to be
* in pixel units within the dragger limits.
*
* @param {number} x Pixel position relative to the left of the slider.
* @param {number} y Pixel position relative to the top of the slider.
* @return {number} The relative position of the thumb.
* @private
*/
ol.control.ZoomSlider.prototype.getRelativePosition_ = function(x, y) {
var amount;
if (this.direction_ === ol.control.ZoomSlider.direction.HORIZONTAL) {
amount = x / this.widthLimit_;
} else {
amount = y / this.heightLimit_;
}
return ol.math.clamp(amount, 0, 1);
};
/**
* Calculates the corresponding resolution of the thumb given its relative
* position (where 0 is the minimum and 1 is the maximum).
*
* @param {number} position The relative position of the thumb.
* @return {number} The corresponding resolution.
* @private
*/
ol.control.ZoomSlider.prototype.getResolutionForPosition_ = function(position) {
var fn = this.getMap().getView().getResolutionForValueFunction();
return fn(1 - position);
};
/**
* Determines the relative position of the slider for the given resolution. A
* relative position of 0 corresponds to the minimum view resolution. A
* relative position of 1 corresponds to the maximum view resolution.
*
* @param {number} res The resolution.
* @return {number} The relative position value (between 0 and 1).
* @private
*/
ol.control.ZoomSlider.prototype.getPositionForResolution_ = function(res) {
var fn = this.getMap().getView().getValueForResolutionFunction();
return 1 - fn(res);
};
|
Module.register("camera", {
// Module config defaults.
defaults: {
},
start: function() {
this.sendSocketNotification("FETCH_ALL_PHOTOS");
this.photos = ['~/theia/photos/william.jpg'];
},
socketNotificationReceived: function(notification, payload) {
Log.info(this.name + " received a notification: " + notification);
if (notification === "FETCHED_PHOTOS") {
this.photos = payload.photos;
this.updateDom();
}
},
// Override dom generator.
getDom: function() {
const wrapper = document.createElement("div");
const imageContainer = document.createElement("div");
for (photo of this.photos) {
const image = document.createElement("img");
image.className = "photo";
image.src = photo.src;
imageContainer.appendChild(image);
}
// Return the wrapper to the dom.
return wrapper;
},
// Listen for camera notifcations
notificationReceived: function(notification, payload, sender) {
console.log('Camera module received notification to take a photo');
if (notification === 'TAKE_PHOTO') {
this.sendSocketNotification('TAKE_PHOTO');
}
},
});
|
import DegToRad from 'math/DegToRad.js';
import RadToDeg from 'math/RadToDeg.js';
import Wrap from 'math/Wrap.js';
import ShapeFill from 'canvas/shapes/ShapeFill.js';
import ShapeStroke from 'canvas/shapes/ShapeStroke.js';
export default function Shape (
{
x = 0,
y = 0,
width = 0,
height = width,
rotation = 0,
stroke = '',
fill = '',
strokeFirst = false,
radius = 0,
startAngle = 0,
endAngle = 360,
antiClockwise = false,
angle = 0,
anchor = undefined,
anchorX = 0,
anchorY = 0,
scale = undefined,
scaleX = 1,
scaleY = 1,
lineWidth = 1,
lineCap = 'butt',
lineJoin = 'bevel',
miterLimit = 10,
lineDashSegments = undefined,
lineDashOffset = 0,
interpolate = true,
subPixelAdjust = true,
visible = true
} = {}
) {
let shape = {
visible: visible,
// transform level values
x: x,
y: y,
rotation: rotation,
scaleX: scaleX,
scaleY: scaleY,
rotationAnchorX: anchorX,
rotationAnchorY: anchorY,
width: width,
height: height,
// Arc / Circle specific
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
antiClockwise: antiClockwise,
lineWidth: lineWidth,
lineCap: lineCap,
lineJoin: lineJoin,
miterLimit: miterLimit,
lineDashSegments: lineDashSegments,
lineDashOffset: lineDashOffset,
interpolate: interpolate,
subPixelAdjust: subPixelAdjust,
fills: [],
addFill () {
let fill = new ShapeFill(this);
this.fills.push(fill);
return fill;
},
addStroke () {
let stroke = new ShapeStroke(this);
this.fills.push(stroke);
return stroke;
},
getFill (index = 0) {
return this.fills[index];
},
lineDash (segments, offset = 0) {
this.lineDashSegments = segments;
this.lineDashOffset = offset;
},
set angle (value) {
this.rotation = DegToRad(Wrap(value, 0, 360));
},
get angle () {
return RadToDeg(this.rotation);
},
startDraw (ctx, i) {
ctx.save();
ctx.lineWidth = this.lineWidth;
ctx.lineCap = this.lineCap;
ctx.lineJoin = this.lineJoin;
ctx.miterLimit = this.miterLimit;
if (this.lineDashSegments)
{
ctx.setLineDash(this.lineDashSegments);
ctx.lineDashOffset = this.lineDashOffset;
}
// let tx = this.getRenderX(this.interpolate, i) + (this.anchor.x * -this.width);
// let ty = this.getRenderY(this.interpolate, i) + (this.anchor.y * -this.height);
// let tx = this.getRenderX(this.interpolate, i);
// let ty = this.getRenderY(this.interpolate, i);
// if (this.subPixelAdjust && this.lineWidth % 2)
// {
// tx -= 0.5;
// ty -= 0.5;
// }
this.transform.setTransform(ctx);
ctx.beginPath();
},
endDraw (ctx) {
for (let fill of this.fills)
{
fill.draw(ctx);
}
ctx.restore();
}
};
if (anchor !== undefined)
{
shape.rotationAnchorX = anchor;
shape.rotationAnchorY = anchor;
}
if (scale !== undefined)
{
shape.scaleX = scale;
shape.scaleY = scale;
}
if (radius !== 0)
{
shape.width = radius * 2;
shape.height = radius * 2;
}
// degs
if (angle !== 0)
{
shape.angle = angle;
}
if (strokeFirst)
{
if (stroke !== '')
{
let strokeFill = shape.addStroke();
strokeFill.setSolid(stroke);
}
if (fill !== '')
{
let shapeFill = shape.addFill();
shapeFill.setSolid(fill);
}
}
else
{
if (fill !== '')
{
let shapeFill = shape.addFill();
shapeFill.setSolid(fill);
}
if (stroke !== '')
{
let strokeFill = shape.addStroke();
strokeFill.setSolid(stroke);
}
}
return shape;
}
|
var Parse = require('parse').Parse,
models = require('./models'),
readline = require('readline'),
colors = require('colors');
function printTags(tags) {
var str = '\bTags'.blue.bold + ': '.grey;
for (var i = 0; i < tags.length; i++) {
if (i > 0) str += ', '.grey;
str += tags[i].green;
};
console.log(str);
}
function selectTags(bookmark) {
var promise = new Parse.Promise();
promptForTags(bookmark, function(tags) {
bookmark.set('tags', tags);
bookmark.save().then(function() {
promise.resolve(bookmark);
});
});
return promise;
}
function promptForTags(bookmark, fn) {
var knownTags = [];
var query = new Parse.Query(models.Tag);
query.find().then(function(objects) {
for (var i = 0; i < objects.length; i++) {
knownTags.push(objects[i].get('name'));
};
}, function(err) {
console.error(err.message.red);
process.exit(1);
});
function completeTags(line) {
var hits = knownTags.filter(function(knownTag) {
return knownTag.indexOf(line) === 0;
});
return [hits, line];
}
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: completeTags
});
var tags = bookmark.get('tags') || [];
console.log('Add tags, one per line, empty to finish, Tab to autocomplete, "-" to remove last');
printTags(tags);
rl.setPrompt('#'.green, 1);
rl.prompt();
rl.on('line', function(tag) {
if (tag === '-') {
tags.pop();
printTags(tags);
rl.prompt();
} else if (tag.length) {
if (tags.indexOf(tag) < 0) {
tags.push(tag);
}
printTags(tags);
rl.prompt();
} else {
rl.write('');
rl.close();
fn(tags);
}
});
}
module.exports = {
prompt: promptForTags,
selectTags: selectTags,
prettyPrint: printTags
}; |
// ==========================================================================
// Grunt Build
// ==========================================================================
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
sass: {
dev: {
options: {
style: 'expanded',
compass: true
},
files: {
'public/css/core.css': 'public/css/core.scss'
}
},
dist: {
options: {
style: 'compressed',
compass: true,
sourcemap: 'none'
},
files: {
'public/css/core.css': 'public/css/core.scss'
}
},
prototype: {
options: {
style: 'expanded',
compass: true,
require: ['breakpoint']
},
files: {
'prototype/core.css': 'prototype/core.scss'
}
}
},
jshint: {
options: {
'-W058': true,
curly: true,
eqeqeq: true,
immed: true,
latedef: false,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: false,
boss: true,
eqnull: false,
browser: true,
esnext: true,
debug: true,
globalstrict: true,
globals: {
'$': false,
'module': true,
'require': false,
'console': false,
'window': true,
'debug': true,
'log': true,
'io': true,
'process': false,
'__dirname': false,
'ZeroClipboard': false,
'chrome': true
}
},
files: ['Gruntfile.js', 'app.js', 'models/*.js', 'public/js/*.js', 'chrome/ext/*.js', 'prototype/core.js']
},
jasmine: {
pivotal: {
src: 'public/js/core.js',
options: {
vendor: ['public/js/vendor/socket.io.js', 'public/js/vendor/clipboard.min.js', 'public/js/vendor/jquery.min.js'],
helpers: ['spec/helpers/jasmine-jquery.js'],
specs: 'spec/*Spec.js',
keepRunner: true
}
}
},
preprocess: {
html : {
src : 'tmpl/index.html',
dest : 'public/index.html'
}
},
watch: {
sass: {
files: ['public/css/**/*.scss'],
tasks: ['sass:dist']
},
js: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
},
test: {
files: ['spec/**/*.js', 'tmpl/inc/*.html', 'public/js/*.js'],
tasks: ['test']
},
html: {
files: ['tmpl/**/*.html'],
tasks: ['preprocess']
},
options: {
livereload: true
},
prototype: {
files: ['prototype/core.scss'],
tasks: ['sass:prototype']
}
}
});
// Load Modules
// ----------------------------------------------------------
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-preprocess');
// Register Tasks
// ----------------------------------------------------------
// grunt.registerTask('default', ['sass:dev', 'jshint', 'preprocess', 'jasmine']);
grunt.registerTask('dev', ['sass:dev', 'jshint', 'preprocess', 'jasmine', 'watch']);
grunt.registerTask('dist', ['sass:dist', 'jshint', 'jasmine', 'preprocess']);
grunt.registerTask('proto', ['sass:prototype', 'jshint', 'watch']);
grunt.registerTask('test', ['jasmine']);
// grunt.registerTask('heroku', ['sass:dist']);
// grunt.registerTask('default', ['sass:dev']);
grunt.registerTask('default', []);
// Show Timer
// ----------------------------------------------------------
require('time-grunt')(grunt);
};
|
initSidebarItems({"enum":[["ColorMode","The color mode the encoder will use to encode the image."]],"struct":[["Encoder","A GIF encoder."]]}); |
import dva from 'dva';
import './index.css';
import { useRouterHistory } from 'dva/router';
import { createHashHistory } from 'history'
// 1. Initialize
const app = dva({
history: useRouterHistory(createHashHistory)({ queryKey: false }), // 去除 _k
});
// 2. Plugins
// app.use({});
// 3. Model
// app.model(require('./models/example'));
// 4. Router
// app.router(require('./router'));
app.router(require('./components/Example'))
// 5. Start
app.start('#root');
|
var admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert("./server/firebase-service-account.json"),
databaseURL: "https://solo-project-70874.firebaseio.com", // replace this line with your URL
});
/* This is where the magic happens. We pull the id_token off of the request,
verify it against our firebase service account private_key.
Then we add the decodedToken */
var tokenDecoder = function(req, res, next){
if (req.headers.id_token) {
admin.auth().verifyIdToken(req.headers.id_token).then(function(decodedToken) {
// Adding the decodedToken to the request so that downstream processes can use it
req.decodedToken = decodedToken;
next();
})
.catch(function(error) {
// If the id_token isn't right, you end up in this callback function
// Here we are returning a forbidden error
console.log('User token could not be verified');
res.sendStatus(403);
});
} else {
// Seems to be hit when chrome makes request for map files
// Will also be hit when user does not send back an idToken in the header
res.sendStatus(403);
}
}
module.exports = { token: tokenDecoder };
|
import {DIRECTION, EVENT} from './Constants';
import SprdRange from './SprdRange';
import Actions from './Actions';
import {eventTriggered} from './Util';
//used to handle arrow key movements
export default class SprdNavigator {
static move(props, direction, step = 1){
let {ranges, minCol, minRow, rows, cols, infiniteScroll, dontSetClickSelectedRange, onEvent} = props;
let {clickSelectedRange, dragSelectedRange, dragOriginCellRange} = SprdRange.fromImmutable(null, ranges);
let {startRow, stopRow, startCol, stopCol} = clickSelectedRange;
let previousMinCol = minCol;
let previousMinRow = minRow;
switch(direction){
case DIRECTION.UP:
if(startRow > 0) startRow -= step;
if(stopRow > 0) stopRow -= step;
if( (startRow + 1) >= 0) minRow -= step;
break;
case DIRECTION.DOWN:
startRow += step;
stopRow += step;
if(startRow >= minRow + rows) minRow += step;
break;
case DIRECTION.LEFT:
if(startCol > 0)startCol -= step;
if(stopCol > 0) stopCol -= step;
if( (startCol + 1) >= 0) minCol -= step;
break;
case DIRECTION.RIGHT:
startCol += step;
stopCol += step;
if(startCol >= minCol + cols) minCol += step;
}
minRow = Math.max(minRow, 0);
minCol = Math.max(minCol, 0);
if(!infiniteScroll && (minRow > 0 || minCol > 0)) return; //disable infinite scrolling
if(previousMinRow !== minRow || previousMinCol !== minCol){
Actions.setViewPort(minRow, minCol);
}
let newClickSelectedRange = new SprdRange(startRow, startCol, stopRow, stopCol);
if(dontSetClickSelectedRange){
Actions.setRange({
dragSelectedRange: dragSelectedRange,
dragOriginCellRange: dragOriginCellRange
});
} else {
Actions.setRange({
clickSelectedRange: newClickSelectedRange,
dragSelectedRange: dragSelectedRange,
dragOriginCellRange: dragOriginCellRange
});
}
eventTriggered(
onEvent, EVENT.MOVE, null, {oldPosition: clickSelectedRange, newPosition: newClickSelectedRange});
}
} |
const hooks = require('hooks');
hooks.before('Articles > Publish an article > 201 > application/json; charset=utf-8', (transaction) => {
transaction.request.headers.Authorization = 'Basic: YWxhZGRpbjpvcGVuc2VzYW1l';
});
|
var stack = []
, domReadyRE = /interactive|complete|loaded/
, isReady = false
function async(fn){
setTimeout(function(){
fn()
}, 0)
}
function checkStatus(){
var item
if(isReady) return
if(domReadyRE.test(document.readyState)) {
isReady = true
while(item = stack.shift()) async(item)
return
}
setTimeout(checkStatus, 10)
}
checkStatus()
module.exports = function(fn){
if(typeof fn != "function") return
if(isReady) return async(fn)
stack.push(fn)
}
|
var width = 800;
var height = 600;
var score = 0;
var lives = 3;
var time = 0;
var started = false;
//rocks and misiles (sets);
var rock_group = [];
var missile_group = [];
var explosion_group = [];
var timer = "undefined";
var asteroid_info;
var keydown = {};
var FPS = 60;
var extra_size = 40;
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / FPS);
};
})();
Number.prototype.mod = function(n) {
//console.log("overidden mod");
return ((this%n)+n)%n;
};
function onload() {
width = window.innerWidth;
height = window.innerHeight;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
// function drawStroked(text, x, y) {
ctx.font = "40px Sans-serif"
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 8;
// ctx.strokeText(text, x, y);
ctx.fillStyle = 'white';
//ctx.fillText(text, x, y);
//}
//drawStroked("37°", 50, 150);
function ImageInfo( center, size, radius, lifespan , animated) {
var self = this;
self.center = center;
self.size = size;
self.radius = typeof radius !== "undefined" ? radius : 0;
if (typeof radius !== "undefined")
self.lifespan = lifespan;
else
self.lifespan = Number.POSITIVE_INFINITY;
self.animated = typeof animated !== "undefined" ? animated : false;
self.get_center = function(){
return self.center;
};
self.get_size = function(){
return self.size;
};
self.get_radius = function(){
return self.radius;
};
self.get_lifespan = function(){
return self.lifespan;
}
self.get_animated = function() {
return self.animated;
}
}
var debris_info = new ImageInfo([320, 240], [640, 480]);
var debris_image = new Image();
debris_image.src = "./img/debris2_blue.png";
var nebula_info = new ImageInfo([400, 300], [800, 600]);
var nebula_image = new Image();
nebula_image.src = "./img/nebula_blue.png";
// splash image
var splash_info = new ImageInfo([200, 150], [400, 300]);
var splash_image = new Image();
splash_image.src = "./img/splash.png";
// ship image
var ship_info = new ImageInfo([45, 45], [90, 90], 35);
var ship_image = new Image();
ship_image.src = "./img/double_ship.png";
// missile image - shot1.png, shot2.png, shot3.png
var missile_info = new ImageInfo([5,5], [10, 10], 6, 50)
var missile_image = new Image();
missile_image.src = "./img/shot2.png";
// asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
var asteroid_info = new ImageInfo([45, 45], [90, 90], 40);
var asteroid_image = new Image();
asteroid_image.src = "./img/asteroid_blue.png";
// animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
var explosion_info = new ImageInfo([64, 64], [128, 128], 17, 24, true);
var explosion_image = new Image();
explosion_image.src = "./img/explosion_alpha.png";
/*var soundtrack = new Audio("./sound/soundtrack.mp3");
var missile_sound = new Audio("./sound/missile.mp3");
//missile_sound.set_volume(0.5)
var ship_thrust_sound = new Audio("./sound/thrust.mp3");
var explosion_sound = new Audio("./sound/explosion.mp3");*/
var soundtrack = null;
var missile_sound = null;
//missile_sound.set_volume(0.5)
var ship_thrust_sound = null;
var explosion_sound = null;
//soundtrack.play();
/*nebula_image.onload = function() {
ctx.drawImage(nebula_image, 0, 0);
};*/
// helper functions to handle transformations
var angle_to_vector = function(ang){
return [Math.cos(ang), Math.sin(ang)];
};
var dist = function(p,q) {
return Math.sqrt(Math.pow((p[0] - q[0]), 2)+Math.pow((p[1] - q[1]), 2));
};
//Ship class
function Ship( pos, vel, angle, image, info) {
var self = this;
self.pos = [pos[0] ,pos[1]];
self.vel = [vel[0],vel[1]];
self.thrust = false;
self.angle = angle;
self.angle_vel = 0;
self.image = image;
self.image_center = info.get_center();
self.image_size = info.get_size();
self.radius = info.get_radius() + extra_size/2;
self.get_pos = function(){
return self.pos;
}
self.get_radius = function() {
return self.radius;
}
self.draw = function(canvas) {
// canvas.draw_circle(self.pos, self.radius, 1, "White", "White")
if(self.thrust) {
canvas.save();
canvas.translate(self.pos[0], self.pos[1]);
canvas.rotate(self.angle);
canvas.drawImage(self.image,90, 0,self.image_size[0], self.image_size[1], -(self.image_size[0] + extra_size)/2, -(self.image_size[1] + extra_size)/2, self.image_size[0] + extra_size,self.image_size[1] + extra_size/* self.angle*/);
canvas.restore();
}
else {
canvas.save();
canvas.translate(self.pos[0], self.pos[1]);
canvas.rotate(self.angle);
canvas.drawImage(self.image,0,0,self.image_size[0], self.image_size[1], -(self.image_size[0] + extra_size)/2, -(self.image_size[1] + extra_size)/2, self.image_size[0] + extra_size,self.image_size[1] + extra_size/* self.angle*/);
canvas.restore();
}
}
self.set_angle_vel = function(vel){
self.angle_vel = vel;
}
self.set_thrust = function(th) {
self.thrust = th;
if (self.thrust) {
//ship_thrust_sound.load();
//ship_thrust_sound.play();
} else {
//ship_thrust_sound.load();
}
}
self.shoot = function(){
//global missile_group
var forward = angle_to_vector(self.angle);
var a_missile = new Sprite([self.pos[0] + self.radius * forward[0], self.pos[1] + self.radius * forward[1]], [self.vel[0] + 10 * forward[0], self.vel[1] + 10 * forward[1]], 0, 0, missile_image, missile_info, missile_sound);
missile_group.push(a_missile);
}
self.update = function(){
var c = 0.06;
self.angle += self.angle_vel;
//position update
self.pos[0] = (self.pos[0] + self.vel[0]).mod(width);
self.pos[1] = (self.pos[1] + self.vel[1]).mod(height);
console.log("position : " + self.pos);
//friction update
self.vel[0] *= (1 - c);
self.vel[1] *= (1 - c);
//get forward vector
forward = angle_to_vector(self.angle);
if (self.thrust) {
self.vel[0] += forward[0];
self.vel[1] += forward[1];
}
}
}
// Sprite class
function Sprite(pos, vel, ang, ang_vel, image, info, sound){
var self = this;
self.pos = [pos[0],pos[1]];
self.vel = [vel[0],vel[1]];
self.angle = ang;
self.angle_vel = ang_vel;
self.image = image;
self.image_center = info.get_center();
self.image_size = info.get_size();
self.radius = info.get_radius();
self.lifespan = info.get_lifespan();
self.animated = info.get_animated();
self.age = 0;
sound = typeof sound !== "undefined" ? sound : false;
if (sound){
//sound.load();
//sound.play();
}
self.get_pos = function() {
return self.pos;
}
self.get_radius = function(){
return self.radius;
}
self.collide = function(other_object){
other_object_rad = other_object.get_radius();
other_object_pos = other_object.get_pos();
min_collide_dist = other_object_rad + self.radius;
distance = dist(other_object_pos, self.pos);
if (distance <= min_collide_dist)
return true;
else
return false;
}
self.draw = function( canvas){
if (!self.animated) {
canvas.save();
canvas.translate(self.pos[0], self.pos[1]);
canvas.rotate(self.angle);
canvas.drawImage(self.image, 0,0, self.image_size[0], self.image_size[1], - self.image_size[0]/2, - self.image_size[1]/2,self.image_size[0], self.image_size[1]);
canvas.restore();
} else {
im_center = [self.image_center[0] * self.age + (self.age + 1) * self.image_center[0], self.image_center[1]]
//print im_center
canvas.drawImage(self.image, im_center[0] - self.image_size[0]/2,im_center[1] - self.image_size[1]/2, self.image_size[0], self.image_size[1], self.pos[0] - self.image_size[0]/2, self.pos[1]-self.image_size[1]/2, self.image_size[0], self.image_size[1]);
}
}
self.update = function() {
self.angle += self.angle_vel;
self.pos[0] += self.vel[0];
self.pos[1] += self.vel[1];
self.age += 1;
if (self.age >= self.lifespan)
return true;
else
return false;
}
}
// mouseclick handlers that reset UI and conditions whether splash image is drawn
function process_sprite_group(sprite_group, canvas){
for (sprite in sprite_group) {
//console.log({"sprite" : sprite_group[sprite]});
sprite_group[sprite].draw(canvas);
if (sprite_group[sprite].update()) {
sprite_group.splice(sprite, 1);
}
}
}
function group_collide(group, other_object) {
var count = 0;
for (sprite in group) {
if (group[sprite].collide(other_object)) {
var a_explosive = new Sprite(group[sprite].get_pos(), [0, 0], 0, 0, explosion_image, explosion_info);
explosion_group.push(a_explosive);
group.splice(sprite, 1);
count += 1;
}
}
return count;
}
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function group_group_collide(rocks_group, missile_group) {
var collision_count = 0;
for (missile in missile_group) {
collision_count += group_collide(rocks_group, missile_group[missile]);
}
return collision_count;
}
// timer handler that spawns a rock
function rock_spawner() {
//global rock_group;
//console.log("spawning rocks");
var rock_pos = [getRandomInt(0, width), getRandomInt(0, height)]
var rock_vel = [Math.random() * .6 - .3, Math.random() * .6 - .3]
var rock_avel = Math.random() * .2 - .1
console.log(asteroid_info);
if (rock_group.length <= 12) {
var a_rock = new Sprite(rock_pos, rock_vel, 0, rock_avel, asteroid_image, asteroid_info);
rock_group.push(a_rock);
}
}
function start(){
//global started, score, lives
if (!started) {
started = true;
score = 0;
lives = 3;
if("undefined" !== timer)
clearInterval(timer);
timer = setInterval(rock_spawner, 1000);
}
}
function keydown_handler(key) {
console.log({"key":key.keyCode});
key.preventDefault();
if (key.keyCode == 37 && keydown['37'] == null) {
my_ship.set_angle_vel(-0.15);
keydown['37'] = true;
}
if (key.keyCode == 39 && keydown['39'] == null) {
my_ship.set_angle_vel(0.15);
keydown['39'] = true;
}
if (key.keyCode == 38 && keydown['38'] == null) {
my_ship.set_thrust(true);
keydown['38'] = true;
}
if (key.keyCode == 13 && keydown['13'] == null) {
if(!started) start();
else
my_ship.shoot();
keydown['13'] = true;
}
}
function keyup_handler(key) {
key.preventDefault();
if (key.keyCode == 37 || key.keyCode == 39)
my_ship.set_angle_vel(0);
if (key.keyCode == 38)
my_ship.set_thrust(false);
keydown[key.keyCode] = null;
}
function restart_game() {
//global missile_group, rock_group, score, lives, started
missile_group = [];
rock_group = [];
started = false;
clearInterval(timer);
}
function draw(canvas){
//global time, score, lives
// animiate background
time += 1;
center = debris_info.get_center();
size = debris_info.get_size();
wtime = (time / 8) % 100;
//console.log(wtime);
canvas.drawImage(nebula_image,0,0, nebula_info.get_size()[0], nebula_info.get_size()[1], 0,0, width, height);
canvas.drawImage(debris_image,0, 0, (size[0]-2*wtime), size[1],
(10*wtime), 0, (width-2.5*wtime), height);
//canvas.drawImage(debris_image, 0, 0, size[0], size[1],
// 0, 0, width, height);
//canvas.drawImage(debris_image, [size[0]-wtime, center[1]], [2*wtime, size[1]],
// [1.25*wtime, height/2], [2.5*wtime, height]);
// draw ship
my_ship.draw(canvas);
// update and draw rocks
process_sprite_group(rock_group, canvas);
hits = group_collide(rock_group, my_ship);
lives -= hits;
// if lives are exhausted restart the game
if (lives <= 0) {
live = 0;
restart_game();
}
// update and draw missiles
process_sprite_group(missile_group,canvas);
score += group_group_collide(rock_group, missile_group);
//update and update the exposion_group
process_sprite_group(explosion_group, canvas);
// update ship
my_ship.update();
canvas.fillText("Lives", 50, 50);//, 25, "White")
canvas.fillText("Score", width - 150, 50);//, 25, "White")
canvas.fillText(lives, 50, 90);//, 25, "White")
canvas.fillText(score, width - 150, 90);//, 25, "White")
if (!started) {
canvas.drawImage(splash_image, 0, 0,
splash_info.get_size()[0], splash_info.get_size()[1], width/2 - splash_info.get_size()[0]/2, height/2 - splash_info.get_size()[1]/2,
splash_info.get_size()[0], splash_info.get_size()[1]);
}
}
var my_ship = new Ship([width / 2, height / 2], [0, 0], 0, ship_image, ship_info);
function main() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw(ctx);
window.requestAnimFrame(main);
}
main();
document.addEventListener("keydown", keydown_handler);
document.addEventListener("keyup", keyup_handler);
}
|
var _ = require('lodash');
var glob = require('glob');
var requireConfig = require('./assets/app/config');
var spawn = require('child_process').spawn;
function buildRequireConfig(options) {
'use strict';
if (options == null) {
options = {};
}
var ret = {};
_.extend(ret, requireConfig('../..'), options, {
baseUrl: 'static/app',
name: 'main',
optimize: 'none',
out: './static/app.js'
});
return ret;
}
module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-jscs');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
requirejs: {
build: {
options: buildRequireConfig({
generateSourceMaps: true,
optimize: 'none'
})
}
},
handlebars: {
options: {namespace: false, amd: true},
templates: {
files: (function () {
var templates = glob.sync('./assets/**/*.hbs');
var result = templates.reduce(function destFiles(memo, source) {
var newName = source.replace(/\.hbs$/, '.js')
.replace('./assets', './static');
memo[newName] = source;
return memo;
}, {});
return result;
}())
}
},
copy: {
app: {
src: '**/*.js',
dest: '<%= clean.app %>',
cwd: './assets/app',
expand: true
},
img: {
src: '**/*.png',
dest: '<%= clean.img %>',
cwd: './assets/images',
expand: true
}
},
clean: {
app: './static/app',
img: './static/images',
compass: './sass-cache',
karma: './karma-*',
tmp: './tmp-*.tmp'
},
compass: {
dist: {
options: {
sassDir: 'assets/style',
cssDir: 'static/style',
cacheDir: './sass-cache',
importPath: ['vendor/normalize-scss']
}
}
},
karma: {
server: {
configFile: 'config/test.js',
background: true
},
unit: {
configFile: 'config/test.js',
background: false,
singleRun: true
}
},
jshint: {
options: {jshintrc: './.jshintrc'},
grunt: {
files: {src: 'Gruntfile.js'}
},
test: {
files: {src: './test/**/*.js'}
}
},
jscs: {
src: ['Gruntfile.js', 'test/**/*.js'],
options: {config: '.jscsrc'}
},
watch: {
style: {
files: '<%= compass.dist.options.sassDir %>/**/*.scss',
tasks: ['compass'],
options: {livereload: true}
},
handlebars: {
files: './assets/**/*.hbs',
tasks: ['js'],
options: {livereload: true}
},
app: {
files: './assets/**/*.js',
tasks: ['js'],
options: {livereload: true}
},
test: {
files: './test/**/*.js',
tasks: ['test'],
options: {livereload: true}
}
}
});
grunt.registerTask('run-deck', function () {
var deck = spawn('./bin/deck');
grunt.log.writeln('Running deck with pid: ' + deck.pid);
deck.stdout.pipe(process.stdout);
deck.stderr.pipe(process.stderr);
});
grunt.registerTask('test', ['jshint', 'jscs', 'karma:unit', 'clean:karma']);
grunt.registerTask('dev', ['default']);
grunt.registerTask('style', ['compass', 'clean:compass', 'clean:tmp']);
grunt.registerTask('js', ['handlebars', 'copy', 'requirejs', 'test']);
grunt.registerTask('build', ['static', 'watch']);
grunt.registerTask('static', ['clean:app', 'style', 'js']);
grunt.registerTask('default', ['run-deck', 'karma:server', 'build']);
};
|
function solve(args) {
var rows = args[0],
matrix = [],
current,
row, col;
for (row = 0; row < rows; row += 1) {
matrix[row] = '';
current = row + 1;
for (col = 0; col < rows; col += 1) {
matrix[row] += String(current) + ' ';
current += 1;
}
matrix[row] = String(matrix[row]).trim();
console.log(matrix[row]);
}
}
solve('4'); |
import {
createStore,
applyMiddleware,
compose
} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const createStoreWithMiddleware = compose(
applyMiddleware(
thunk
)
)(createStore);
export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState,
typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f);
if (module.hot) {
module.hot.accept('../reducers', () => {
store.replaceReducer(require('../reducers'));
});
}
return store;
}
|
// Generated on 2014-05-19 using generator-angular-fullstack 1.4.2
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: {
// configurable paths
app: require('./bower.json').appPath || 'app',
dist: 'dist'
},
express: {
options: {
port: process.env.PORT || 9000
},
dev: {
options: {
script: 'server.js',
debug: true
}
},
prod: {
options: {
script: 'dist/server.js',
node_env: 'production'
}
}
},
open: {
server: {
url: 'http://localhost:<%= express.options.port %>'
}
},
watch: {
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: true
}
},
mochaTest: {
files: ['test/server/{,*/}*.js'],
tasks: ['env:test', 'mochaTest']
},
jsTest: {
files: ['test/client/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
files: [
'<%= yeoman.app %>/views/{,*//*}*.{html,jade}',
'{.tmp,<%= yeoman.app %>}/styles/{,*//*}*.css',
'{.tmp,<%= yeoman.app %>}/scripts/{,*//*}*.js',
'<%= yeoman.app %>/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
],
options: {
livereload: true
}
},
express: {
files: [
'server.js',
'lib/**/*.{js,json}'
],
tasks: ['newer:jshint:server', 'express:dev', 'wait'],
options: {
livereload: true,
nospawn: true //Without this option specified express won't be reloaded
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
server: {
options: {
jshintrc: 'lib/.jshintrc'
},
src: [ 'lib/{,*/}*.js']
},
all: [
'<%= yeoman.app %>/scripts/{,*/}*.js'
],
test: {
options: {
jshintrc: 'test/client/.jshintrc'
},
src: ['test/client/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*',
'!<%= yeoman.dist %>/Procfile'
]
}]
},
heroku: {
files: [{
dot: true,
src: [
'heroku/*',
'!heroku/.git*',
'!heroku/Procfile'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Debugging with node inspector
'node-inspector': {
custom: {
options: {
'web-host': 'localhost'
}
}
},
// Use nodemon to run server in debug mode with an initial breakpoint
nodemon: {
debug: {
script: 'server.js',
options: {
nodeArgs: ['--debug-brk'],
env: {
PORT: process.env.PORT || 9000
},
callback: function (nodemon) {
nodemon.on('log', function (event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function () {
setTimeout(function () {
require('open')('http://localhost:8080/debug?port=5858');
}, 500);
});
}
}
}
},
// Automatically inject Bower components into the app
'bower-install': {
app: {
html: '<%= yeoman.app %>/views/index.html',
ignorePath: '<%= yeoman.app %>/',
exclude: ['bootstrap-sass']
}
},
// Compiles Sass to CSS and generates necessary files if requested
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
//fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: '<%= yeoman.app %>/bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false,
raw: 'Sass::Script::Number.precision = 10\n'
},
dist: {
options: {
generatedImagesDir: '<%= yeoman.dist %>/public/images/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/public/scripts/{,*/}*.js',
'<%= yeoman.dist %>/public/styles/{,*/}*.css',
'<%= yeoman.dist %>/public/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/public/styles/fonts/*'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: ['<%= yeoman.app %>/views/index.html',
'<%= yeoman.app %>/views/index.jade'],
options: {
dest: '<%= yeoman.dist %>/public'
}
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/views/{,*/}*.html',
'<%= yeoman.dist %>/views/{,*/}*.jade'],
css: ['<%= yeoman.dist %>/public/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>/public']
}
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
options : {
cache: false
},
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/public/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/public/images'
}]
}
},
htmlmin: {
dist: {
options: {
//collapseWhitespace: true,
//collapseBooleanAttributes: true,
//removeCommentsFromCDATA: true,
//removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.app %>/views',
src: ['*.html', 'partials/**/*.html'],
dest: '<%= yeoman.dist %>/views'
}]
}
},
// Allow the use of non-minsafe AngularJS files. Automatically makes it
// minsafe compatible so Uglify does not destroy the ng references
ngmin: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/views/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>/public',
src: [
'*.{ico,png,txt}',
'.htaccess',
'bower_components/**/*',
'images/{,*/}*.{webp}',
'images/Flags/flags_iso/*/*.png',
'fonts/**/*'
]
}, {
expand: true,
dot: true,
cwd: '<%= yeoman.app %>/views',
dest: '<%= yeoman.dist %>/views',
src: '**/*.jade'
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/public/images',
src: ['generated/*']
}, {
expand: true,
dest: '<%= yeoman.dist %>',
src: [
'package.json',
'server.js',
'lib/**/*'
]
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'compass:server'
],
test: [
'compass'
],
debug: {
tasks: [
'nodemon',
'node-inspector'
],
options: {
logConcurrentOutput: true
}
},
dist: [
'compass:dist',
'imagemin',
'svgmin',
'htmlmin'
]
},
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= yeoman.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Test settings
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['test/server/**/*.js']
},
env: {
test: {
NODE_ENV: 'test'
}
}
});
// Used for delaying livereload until after server has restarted
grunt.registerTask('wait', function () {
grunt.log.ok('Waiting for server reload...');
var done = this.async();
setTimeout(function () {
grunt.log.writeln('Done waiting!');
done();
}, 500);
});
grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
this.async();
});
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'express:prod', 'open', 'express-keepalive']);
}
if (target === 'debug') {
return grunt.task.run([
'clean:server',
'bower-install',
'concurrent:server',
'autoprefixer',
'concurrent:debug'
]);
}
grunt.task.run([
'clean:server',
'bower-install',
'concurrent:server',
'autoprefixer',
'express:dev',
'open',
'watch'
]);
});
grunt.registerTask('server', function () {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve']);
});
grunt.registerTask('test', function(target) {
if (target === 'server') {
return grunt.task.run([
'env:test',
'mochaTest'
]);
}
else if (target === 'client') {
return grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer',
'karma'
]);
}
else grunt.task.run([
'test:server',
'test:client'
]);
});
grunt.registerTask('build', [
'clean:dist',
'bower-install',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngmin',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin'
]);
grunt.registerTask('heroku', function () {
grunt.log.warn('The `heroku` task has been deprecated. Use `grunt build` to build for deployment.');
grunt.task.run(['build']);
});
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
var express = require('express');
var router = express.Router();
router.use(require('./cart'));
router.use(require('./signup'));
router.use(require('./login'));
router.use(require('./share'));
router.use(require('./shop'));
module.exports = router;
|
import Ember from 'ember';
import FactoryGuy, {build, buildList} from 'ember-data-factory-guy';
import SharedAdapterBehavior from './shared-adapter-tests';
import SharedFactoryGuyTestHelperBehavior from './shared-factory-guy-test-helper-tests';
import {title, inlineSetup} from '../helpers/utility-methods';
let App = null;
let adapter = 'DS.JSONAPIAdapter';
let serializerType = '-json-api';
SharedAdapterBehavior.all(adapter, serializerType);
SharedFactoryGuyTestHelperBehavior.mockFindSideloadingTests(App, adapter, serializerType);
SharedFactoryGuyTestHelperBehavior.mockFindAllSideloadingTests(App, adapter, serializerType);
SharedFactoryGuyTestHelperBehavior.mockQueryMetaTests(App, adapter, serializerType);
SharedFactoryGuyTestHelperBehavior.mockUpdateWithErrorMessages(App, adapter, serializerType);
SharedFactoryGuyTestHelperBehavior.mockCreateReturnsAssociations(App, adapter, serializerType);
module(title(adapter, 'FactoryGuy#build get'), inlineSetup(App, serializerType));
test("returns all attributes with no key", function() {
let user = build('user');
deepEqual(user.get(), { id: 1, name: 'User1', style: 'normal' });
equal(user.get().id, 1);
equal(user.get().name, 'User1');
});
test("returns an attribute with a key", function() {
let user = build('user');
equal(user.get('id'), 1);
equal(user.get('name'), 'User1');
});
test("returns a relationship with a key", function() {
let user = build('user', 'with_company');
deepEqual(user.get('company'), { id: 1, type: 'company' });
});
module(title(adapter, 'FactoryGuy#buildList get'), inlineSetup(App, serializerType));
test("returns array of all attributes with no key", function() {
let users = buildList('user', 2);
deepEqual(users.get(), [{ id: 1, name: 'User1', style: "normal" }, { id: 2, name: 'User2', style: "normal" }]);
});
test("returns an attribute with an index and key", function() {
let users = buildList('user', 2);
deepEqual(users.get(0), { id: 1, name: 'User1', style: "normal" });
equal(users.get(0).id, 1);
deepEqual(users.get(1), { id: 2, name: 'User2', style: "normal" });
equal(users.get(1).name, 'User2');
});
test("returns a relationship with an index and key", function() {
let user = buildList('user', 2, 'with_company');
deepEqual(user.get(1).company, { id: 2, type: 'company' });
});
module(title(adapter, 'FactoryGuy#build custom'), inlineSetup(App, serializerType));
test("with traits defining model attributes", function() {
let json = build('project', 'big').data;
deepEqual(json, {
id: 1,
type: 'project',
attributes: {
title: 'Big Project',
}
});
});
test("sideloads belongsTo records which are built from fixture definition", function() {
let json = build('project', 'with_user');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Project1'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "User1",
style: "normal"
}
}
]
});
});
test("sideloads belongsTo record passed as ( prebuilt ) json", function() {
let user = build('user');
let json = build('project', { user: user });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Project1'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "User1",
style: "normal"
}
}
]
});
});
test("sideloads many belongsTo records which are built from fixture definition", function() {
let json = build('project', 'big', 'with_user');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Big Project'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "User1",
style: "normal"
}
}
]
});
});
test("with more than one trait and custom attributes", function() {
let json = build('project', 'big', 'with_user', { title: 'Crazy Project' });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Crazy Project'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "User1",
style: "normal"
}
}
]
});
});
test("with trait with custom belongsTo association object", function() {
let json = build('project', 'big', 'with_dude');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Big Project'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "Dude",
style: "normal"
}
}
]
});
});
test("using trait with attribute using FactoryGuy.belongsTo method", function() {
let json = build('project', 'with_admin');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Project1'
},
relationships: {
user: {
data: { id: 1, type: 'user' }
}
}
},
included: [
{
id: 1,
type: "user",
attributes: {
name: "Admin",
style: "super"
}
}
]
});
});
test("with attribute using sequence", function() {
let json = build('project', 'with_title_sequence');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'project',
attributes: {
title: 'Project1'
}
}
});
});
test("sideloads hasMany records built from fixture definition", function() {
let json = build('user', 'with_projects');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
},
relationships: {
projects: {
data: [
{ id: 1, type: 'project' },
{ id: 2, type: 'project' }
]
}
}
},
included: [
{
id: 1,
type: "project",
attributes: {
title: "Project1"
}
},
{
id: 2,
type: "project",
attributes: {
title: "Project2"
}
}
]
});
});
test("sideloads hasMany records passed as prebuilt ( buildList ) attribute", function() {
let projects = buildList('project', 2);
let json = build('user', { projects: projects });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
},
relationships: {
projects: {
data: [
{ id: 1, type: 'project' },
{ id: 2, type: 'project' }
]
}
}
},
included: [
{
id: 1,
type: "project",
attributes: {
title: "Project1"
}
},
{
id: 2,
type: "project",
attributes: {
title: "Project2"
}
}
]
});
});
test("sideloads hasMany records passed as prebuilt ( array of build ) attribute", function() {
let project1 = build('project');
let project2 = build('project');
let json = build('user', { projects: [project1, project2] });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
},
relationships: {
projects: {
data: [
{ id: 1, type: 'project' },
{ id: 2, type: 'project' }
]
}
}
},
included: [
{
id: 1,
type: "project",
attributes: {
title: "Project1"
}
},
{
id: 2,
type: "project",
attributes: {
title: "Project2"
}
}
]
});
});
test("creates default json for model", function() {
let json = build('user');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
}
}
}
);
});
test("can override default model attributes", function() {
let json = build('user', { name: 'bob' });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'bob',
style: "normal"
}
}
}
);
});
test("can have named model definition with custom attributes", function() {
let json = build('admin');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'Admin',
style: "super"
}
}
}
);
});
test("can override named model attributes", function() {
let json = build('admin', { name: 'AdminGuy' });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'AdminGuy',
style: "super"
}
}
}
);
});
test("ignores transient attributes", function() {
let json = build('property');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'property',
attributes: {
name: 'Silly property'
}
}
}
);
});
test("similar model type ids are created sequentially", function() {
let user1 = build('user');
let user2 = build('user');
let project = build('project');
equal(user1.data.id, 1);
equal(user2.data.id, 2);
equal(project.data.id, 1);
});
test("when no custom serialize keys functions exist, dasherizes attributes and relationship keys", function() {
let json = build('profile', 'with_bat_man');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'profile',
attributes: {
description: 'Text goes here',
'camel-case-description': 'textGoesHere',
'snake-case-description': 'text_goes_here',
'a-boolean-field': false
},
relationships: {
'super-hero': {
data: { id: 1, type: 'super-hero' }
}
}
},
included: [
{
id: 1,
type: "super-hero",
attributes: {
name: "BatMan",
type: "SuperHero"
}
}
]
});
});
test("using custom serialize keys function for transforming attributes and relationship keys", function() {
let serializer = FactoryGuy.store.serializerFor('application');
let savedKeyForAttributeFn = serializer.keyForAttribute;
serializer.keyForAttribute = Ember.String.underscore;
let savedKeyForRelationshipFn = serializer.keyForRelationship;
serializer.keyForRelationship = Ember.String.underscore;
let json = build('profile', 'with_bat_man');
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'profile',
attributes: {
description: 'Text goes here',
'camel_case_description': 'textGoesHere',
'snake_case_description': 'text_goes_here',
'a_boolean_field': false
},
relationships: {
'super_hero': {
data: { id: 1, type: 'super-hero' }
}
}
},
included: [
{
id: 1,
type: "super-hero",
attributes: {
name: "BatMan",
type: "SuperHero"
}
}
]
});
serializer.keyForAttribute = savedKeyForAttributeFn;
serializer.keyForRelationship = savedKeyForRelationshipFn;
});
test("serializes custom attributes types", function() {
let info = { first: 1 };
let json = build('user', { info: info });
json.unwrap();
deepEqual(json,
{
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal",
info: '{"first":1}'
}
}
}
);
});
test("with (nested json fixture) belongsTo has a hasMany association which has a belongsTo", function() {
let expectedData = {
data: {
type: "project",
id: 1,
attributes: {
title: "Project1"
},
relationships: {
user: {
data: { id: 1, type: "user" },
}
}
},
"included": [
{
type: "outfit",
id: 1,
attributes: {
name: "Outfit-1"
},
}, {
type: "big-hat",
id: 1,
attributes: {
type: "BigHat"
},
relationships: {
outfit: {
data: { id: 1, type: 'outfit' }
}
}
}, {
type: "outfit",
id: 2,
attributes: {
name: "Outfit-2"
},
}, {
type: "big-hat",
id: 2,
attributes: {
type: "BigHat"
},
relationships: {
outfit: {
data: { id: 2, type: 'outfit' }
}
}
}, {
type: "user",
id: 1,
attributes: {
name: "User1",
style: "normal"
},
relationships: {
hats: {
data: [
{ type: "big-hat", id: 1 },
{ type: "big-hat", id: 2 }
]
}
}
}
]
};
let projectJson = build('project', 'with_user_having_hats_belonging_to_outfit');
deepEqual(projectJson.data, expectedData.data);
deepEqual(projectJson.included, expectedData.included);
});
test("#add method sideloads unrelated record passed as prebuilt ( build ) json", function() {
let batMan = build('bat_man');
let buildJson = build('user').add(batMan);
buildJson.unwrap();
let expectedJson = {
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
}
},
included: [
{
id: 1,
type: "super-hero",
attributes: {
name: "BatMan",
type: "SuperHero"
}
}
]
};
deepEqual(buildJson, expectedJson);
});
test("#add method sideloads unrelated record passed as prebuilt ( buildList ) json", function() {
let batMen = buildList('bat_man', 2);
let buildJson = build('user').add(batMen);
buildJson.unwrap();
let expectedJson = {
data: {
id: 1,
type: 'user',
attributes: {
name: 'User1',
style: "normal"
}
},
included: [
{
id: 1,
type: "super-hero",
attributes: {
name: "BatMan",
type: "SuperHero"
}
},
{
id: 2,
type: "super-hero",
attributes: {
name: "BatMan",
type: "SuperHero"
}
}
]
};
deepEqual(buildJson, expectedJson);
});
// the override for primaryKey is in the helpers/utilityMethods.js
test("serializer primaryKey override", function() {
let cat = build('cat');
equal(cat.data.catId, 1);
equal(cat.data.id, 1);
});
|
/*
* grunt-srcmust
* https://github.com/derrickliu/grunt-srcmust
*
* Copyright (c) 2014 derrickliu
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
rev: {
files: {
src: ['release/js/contact/main.js','release/css/contact.css']
}
},
srcmust: {
options: {
type: 'rename'
},
contact: {
options: {
cssdir: 'release/css/',
jsdir: 'release/js/contact/',
imagesdir: 'release/css/images/'
},
files: [
{
src: 'pim/contact.jsp'
}
]
},
sms: {
options: {
cssdir: 'release/css/',
jsdir: 'release/js/sms/',
imagesdir: 'release/css/images/'
},
files: [
{
src: 'pim/sms.jsp'
}
]
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-rev');
grunt.loadNpmTasks('grunt-srcmust');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['rev', 'srcmust']);
// By default, lint and run all tests.
grunt.registerTask('default', ['rev', 'srcmust']);
};
|
/**
* angular-strap
* @version v2.2.1 - 2015-11-27
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes (olivier@mg-crea.com)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.helpers.debounce', [])
// @source jashkenas/underscore
// @url https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L693
.factory('debounce', ["$timeout", function($timeout) {
return function(func, wait, immediate) {
var timeout = null;
return function() {
var context = this,
args = arguments,
callNow = immediate && !timeout;
if(timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(function later() {
timeout = null;
if(!immediate) {
func.apply(context, args);
}
}, wait, false);
if(callNow) {
func.apply(context, args);
}
return timeout;
};
};
}])
// @source jashkenas/underscore
// @url https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L661
.factory('throttle', ["$timeout", function($timeout) {
return function(func, wait, options) {
var timeout = null;
options || (options = {});
return function() {
var context = this,
args = arguments;
if(!timeout) {
if(options.leading !== false) {
func.apply(context, args);
}
timeout = $timeout(function later() {
timeout = null;
if(options.trailing !== false) {
func.apply(context, args);
}
}, wait, false);
}
};
};
}]);
|
"use strict";
module.exports = {
rules: {
// The following rules can be used in some cases. See the README for more
// information. (These are marked with `0` instead of `"off"` so that a
// script can distinguish them.)
curly: 0,
"max-len": 0,
"no-mixed-operators": 0,
quotes: 0,
// The rest are rules that you never need to enable when using Prettier.
"array-bracket-spacing": "off",
"arrow-parens": "off",
"arrow-spacing": "off",
"block-spacing": "off",
"brace-style": "off",
"comma-dangle": "off",
"comma-spacing": "off",
"comma-style": "off",
"computed-property-spacing": "off",
"dot-location": "off",
"eol-last": "off",
"func-call-spacing": "off",
"generator-star": "off",
"generator-star-spacing": "off",
indent: "off",
"jsx-quotes": "off",
"key-spacing": "off",
"keyword-spacing": "off",
"multiline-ternary": "off",
"newline-per-chained-call": "off",
"new-parens": "off",
"no-arrow-condition": "off",
"no-comma-dangle": "off",
"no-confusing-arrow": "off",
"no-extra-parens": "off",
"no-extra-semi": "off",
"no-mixed-spaces-and-tabs": "off",
"no-multi-spaces": "off",
"no-multiple-empty-lines": "off",
"no-reserved-keys": "off",
"no-space-before-semi": "off",
"no-spaced-func": "off",
"no-trailing-spaces": "off",
"no-whitespace-before-property": "off",
"no-wrap-func": "off",
"nonblock-statement-body-position": "off",
"object-curly-newline": "off",
"object-curly-spacing": "off",
"object-property-newline": "off",
"one-var-declaration-per-line": "off",
"operator-linebreak": "off",
"padded-blocks": "off",
"quote-props": "off",
"rest-spread-spacing": "off",
semi: "off",
"semi-spacing": "off",
"space-after-function-name": "off",
"space-after-keywords": "off",
"space-before-blocks": "off",
"space-before-function-paren": "off",
"space-before-function-parentheses": "off",
"space-before-keywords": "off",
"space-in-brackets": "off",
"space-in-parens": "off",
"space-infix-ops": "off",
"space-return-throw-case": "off",
"space-unary-ops": "off",
"space-unary-word-ops": "off",
"template-curly-spacing": "off",
"template-tag-spacing": "off",
"unicode-bom": "off",
"wrap-iife": "off",
"wrap-regex": "off",
"yield-star-spacing": "off"
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.