text
stringlengths 2
6.14k
|
|---|
/* http://keith-wood.name/datepick.html
Urdu localisation for jQuery Datepicker.
Mansoor Munib -- mansoormunib@gmail.com <http://www.mansoor.co.nr/mansoor.html>
Thanks to Habib Ahmed, ObaidUllah Anwar. */
(function($) {
$.datepick.regionalOptions.ur = {
monthNames: ['جنوری','فروری','مارچ','اپریل','مئی','جون',
'جولائی','اگست','ستمبر','اکتوبر','نومبر','دسمبر'],
monthNamesShort: ['1','2','3','4','5','6',
'7','8','9','10','11','12'],
dayNames: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dayNamesShort: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dayNamesMin: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dateFormat: 'dd/mm/yyyy', firstDay: 0,
renderer: $.datepick.defaultRenderer,
prevText: '<گذشتہ', prevStatus: 'ماه گذشتہ',
prevJumpText: '<<', prevJumpStatus: 'برس گذشتہ',
nextText: 'آئندہ>', nextStatus: 'ماه آئندہ',
nextJumpText: '>>', nextJumpStatus: 'برس آئندہ',
currentText: 'رواں', currentStatus: 'ماه رواں',
todayText: 'آج', todayStatus: 'آج',
clearText: 'حذف تاريخ', clearStatus: 'کریں حذف تاریخ',
closeText: 'کریں بند', closeStatus: 'کیلئے کرنے بند',
yearStatus: 'برس تبدیلی', monthStatus: 'ماه تبدیلی',
weekText: 'ہفتہ', weekStatus: 'ہفتہ',
dayStatus: 'انتخاب D, M d', defaultStatus: 'کریں منتخب تاريخ',
isRTL: true
};
$.datepick.setDefaults($.datepick.regionalOptions.ur);
})(jQuery);
|
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.Breakpoint = function(id, url, sourceID, lineNumber, columnNumber, condition, enabled)
{
this.id = id;
this.url = url;
this.sourceID = sourceID;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.condition = condition;
this.enabled = enabled;
this.locations = [];
}
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v6.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("./context/context");
var context_2 = require("./context/context");
var TemplateService = (function () {
function TemplateService() {
this.templateCache = {};
this.waitingCallbacks = {};
}
// returns the template if it is loaded, or null if it is not loaded
// but will call the callback when it is loaded
TemplateService.prototype.getTemplate = function (url, callback) {
var templateFromCache = this.templateCache[url];
if (templateFromCache) {
return templateFromCache;
}
var callbackList = this.waitingCallbacks[url];
var that = this;
if (!callbackList) {
// first time this was called, so need a new list for callbacks
callbackList = [];
this.waitingCallbacks[url] = callbackList;
// and also need to do the http request
var client = new XMLHttpRequest();
client.onload = function () {
that.handleHttpResult(this, url);
};
client.open("GET", url);
client.send();
}
// add this callback
if (callback) {
callbackList.push(callback);
}
// caller needs to wait for template to load, so return null
return null;
};
TemplateService.prototype.handleHttpResult = function (httpResult, url) {
if (httpResult.status !== 200 || httpResult.response === null) {
console.warn('Unable to get template error ' + httpResult.status + ' - ' + url);
return;
}
// response success, so process it
// in IE9 the response is in - responseText
this.templateCache[url] = httpResult.response || httpResult.responseText;
// inform all listeners that this is now in the cache
var callbacks = this.waitingCallbacks[url];
for (var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
// we could pass the callback the response, however we know the client of this code
// is the cell renderer, and it passes the 'cellRefresh' method in as the callback
// which doesn't take any parameters.
callback();
}
if (this.$scope) {
var that = this;
setTimeout(function () {
that.$scope.$apply();
}, 0);
}
};
__decorate([
context_2.Autowired('$scope'),
__metadata('design:type', Object)
], TemplateService.prototype, "$scope", void 0);
TemplateService = __decorate([
context_1.Bean('templateService'),
__metadata('design:paramtypes', [])
], TemplateService);
return TemplateService;
})();
exports.TemplateService = TemplateService;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.0-alpha.4
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var utils_1 = require("../utils");
var context_1 = require("../context/context");
var cellRendererFactory_1 = require("./cellRendererFactory");
/** Class to use a cellRenderer. */
var CellRendererService = (function () {
function CellRendererService() {
}
/** Uses a cellRenderer, and returns the cellRenderer object if it is a class implementing ICellRenderer.
* @cellRendererKey: The cellRenderer to use. Can be: a) a class that we call 'new' on b) a function we call
* or c) a string that we use to look up the cellRenderer.
* @params: The params to pass to the cell renderer if it's a function or a class.
* @eTarget: The DOM element we will put the results of the html element into *
* @return: If options a, it returns the created class instance */
CellRendererService.prototype.useCellRenderer = function (cellRendererKey, eTarget, params) {
var cellRenderer = this.lookUpCellRenderer(cellRendererKey);
if (utils_1.Utils.missing(cellRenderer)) {
// this is a bug in users config, they specified a cellRenderer that doesn't exist,
// the factory already printed to console, so here we just skip
return;
}
var resultFromRenderer;
var iCellRendererInstance = null;
this.checkForDeprecatedItems(cellRenderer);
// we check if the class has the 'getGui' method to know if it's a component
var rendererIsAComponent = this.doesImplementICellRenderer(cellRenderer);
// if it's a component, we create and initialise it
if (rendererIsAComponent) {
var CellRendererClass = cellRenderer;
iCellRendererInstance = new CellRendererClass();
this.context.wireBean(iCellRendererInstance);
if (iCellRendererInstance.init) {
iCellRendererInstance.init(params);
}
resultFromRenderer = iCellRendererInstance.getGui();
}
else {
// otherwise it's a function, so we just use it
var cellRendererFunc = cellRenderer;
resultFromRenderer = cellRendererFunc(params);
}
if (resultFromRenderer === null || resultFromRenderer === '') {
return;
}
if (utils_1.Utils.isNodeOrElement(resultFromRenderer)) {
// a dom node or element was returned, so add child
eTarget.appendChild(resultFromRenderer);
}
else {
// otherwise assume it was html, so just insert
eTarget.innerHTML = resultFromRenderer;
}
return iCellRendererInstance;
};
CellRendererService.prototype.checkForDeprecatedItems = function (cellRenderer) {
if (cellRenderer && cellRenderer.renderer) {
console.warn('ag-grid: colDef.cellRenderer should not be an object, it should be a string, function or class. this ' +
'changed in v4.1.x, please check the documentation on Cell Rendering, or if you are doing grouping, look at the grouping examples.');
}
};
CellRendererService.prototype.doesImplementICellRenderer = function (cellRenderer) {
// see if the class has a prototype that defines a getGui method. this is very rough,
// but javascript doesn't have types, so is the only way!
return cellRenderer.prototype && 'getGui' in cellRenderer.prototype;
};
CellRendererService.prototype.lookUpCellRenderer = function (cellRendererKey) {
if (typeof cellRendererKey === 'string') {
return this.cellRendererFactory.getCellRenderer(cellRendererKey);
}
else {
return cellRendererKey;
}
};
__decorate([
context_1.Autowired('cellRendererFactory'),
__metadata('design:type', cellRendererFactory_1.CellRendererFactory)
], CellRendererService.prototype, "cellRendererFactory", void 0);
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], CellRendererService.prototype, "context", void 0);
CellRendererService = __decorate([
context_1.Bean('cellRendererService'),
__metadata('design:paramtypes', [])
], CellRendererService);
return CellRendererService;
})();
exports.CellRendererService = CellRendererService;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.2.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("../../context/context");
var context_2 = require("../../context/context");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var filterManager_1 = require("../../filter/filterManager");
var FilterStage = (function () {
function FilterStage() {
}
FilterStage.prototype.execute = function (rowNode) {
var filterActive;
if (this.gridOptionsWrapper.isEnableServerSideFilter()) {
filterActive = false;
}
else {
filterActive = this.filterManager.isAnyFilterPresent();
}
this.recursivelyFilter(rowNode, filterActive);
};
FilterStage.prototype.recursivelyFilter = function (rowNode, filterActive) {
var _this = this;
// recursively get all children that are groups to also filter
rowNode.childrenAfterGroup.forEach(function (child) {
if (child.group) {
_this.recursivelyFilter(child, filterActive);
}
});
// result of filter for this node
var filterResult;
if (filterActive) {
filterResult = [];
rowNode.childrenAfterGroup.forEach(function (childNode) {
if (childNode.group) {
// a group is included in the result if it has any children of it's own.
// by this stage, the child groups are already filtered
if (childNode.childrenAfterFilter.length > 0) {
filterResult.push(childNode);
}
}
else {
// a leaf level node is included if it passes the filter
if (_this.filterManager.doesRowPassFilter(childNode)) {
filterResult.push(childNode);
}
}
});
}
else {
// if not filtering, the result is the original list
filterResult = rowNode.childrenAfterGroup;
}
rowNode.childrenAfterFilter = filterResult;
this.setAllChildrenCount(rowNode);
};
FilterStage.prototype.setAllChildrenCount = function (rowNode) {
var allChildrenCount = 0;
rowNode.childrenAfterFilter.forEach(function (child) {
if (child.group) {
allChildrenCount += child.allChildrenCount;
}
else {
allChildrenCount++;
}
});
rowNode.allChildrenCount = allChildrenCount;
};
__decorate([
context_2.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], FilterStage.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_2.Autowired('filterManager'),
__metadata('design:type', filterManager_1.FilterManager)
], FilterStage.prototype, "filterManager", void 0);
FilterStage = __decorate([
context_1.Bean('filterStage'),
__metadata('design:paramtypes', [])
], FilterStage);
return FilterStage;
})();
exports.FilterStage = FilterStage;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
gTestsubsuite = 'LexicalConventions';
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var gridRole = {
abstract: false,
accessibleNameRequired: true,
baseConcepts: [{
module: 'HTML',
concept: {
name: 'table',
attributes: [{
name: 'role',
value: 'grid'
}]
}
}],
childrenPresentational: false,
nameFrom: ['author'],
props: {
'aria-level': null,
'aria-multiselectable': null,
'aria-readonly': null
},
relatedConcepts: [],
requireContextRole: [],
requiredOwnedElements: [['rowgroup', 'row'], ['row']],
requiredProps: {},
superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'table']]
};
exports.default = gridRole;
|
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
|
Ext.grid.RowExpander = function(config){
Ext.apply(this, config);
this.addEvents({
beforeexpand : true,
expand: true,
beforecollapse: true,
collapse: true
});
Ext.grid.RowExpander.superclass.constructor.call(this);
if(this.tpl){
if(typeof this.tpl == 'string'){
this.tpl = new Ext.Template(this.tpl);
}
this.tpl.compile();
}
this.state = {};
this.bodyContent = {};
};
Ext.extend(Ext.grid.RowExpander, Ext.util.Observable, {
header: "",
width: 20,
sortable: false,
fixed:true,
menuDisabled:true,
dataIndex: '',
id: 'expander',
lazyRender : true,
enableCaching: true,
getRowClass : function(record, rowIndex, p, ds){
p.cols = p.cols-1;
var content = this.bodyContent[record.id];
if(!content && !this.lazyRender){
content = this.getBodyContent(record, rowIndex);
}
if(content){
p.body = content;
}
return this.state[record.id] ? 'x-grid3-row-expanded' : 'x-grid3-row-collapsed';
},
init : function(grid){
this.grid = grid;
var view = grid.getView();
view.getRowClass = this.getRowClass.createDelegate(this);
view.enableRowBody = true;
grid.on('render', function(){
view.mainBody.on('mousedown', this.onMouseDown, this);
}, this);
},
getBodyContent : function(record, index){
if(!this.enableCaching){
return this.tpl.apply(record.data);
}
var content = this.bodyContent[record.id];
if(!content){
content = this.tpl.apply(record.data);
this.bodyContent[record.id] = content;
}
return content;
},
onMouseDown : function(e, t){
if(t.className == 'x-grid3-row-expander'){
e.stopEvent();
var row = e.getTarget('.x-grid3-row');
this.toggleRow(row);
}
},
renderer : function(v, p, record){
p.cellAttr = 'rowspan="2"';
return '<div class="x-grid3-row-expander"> </div>';
},
beforeExpand : function(record, body, rowIndex){
if(this.fireEvent('beforeexpand', this, record, body, rowIndex) !== false){
if(this.tpl && this.lazyRender){
body.innerHTML = this.getBodyContent(record, rowIndex);
}
return true;
}else{
return false;
}
},
toggleRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
this[Ext.fly(row).hasClass('x-grid3-row-collapsed') ? 'expandRow' : 'collapseRow'](row);
},
expandRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.DomQuery.selectNode('tr:nth(2) div.x-grid3-row-body', row);
if(this.beforeExpand(record, body, row.rowIndex)){
this.state[record.id] = true;
Ext.fly(row).replaceClass('x-grid3-row-collapsed', 'x-grid3-row-expanded');
this.fireEvent('expand', this, record, body, row.rowIndex);
}
},
collapseRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.fly(row).child('tr:nth(1) div.x-grid3-row-body', true);
if(this.fireEvent('beforecollapse', this, record, body, row.rowIndex) !== false){
this.state[record.id] = false;
Ext.fly(row).replaceClass('x-grid3-row-expanded', 'x-grid3-row-collapsed');
this.fireEvent('collapse', this, record, body, row.rowIndex);
}
}
});
|
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
angular.module('mm.addons.qbehaviour_deferredcbm')
/**
* Deferred CBM behaviour handler.
*
* @module mm.addons.qbehaviour_deferredcbm
* @ngdoc service
* @name $mmaQbehaviourDeferredCBMHandler
*/
.factory('$mmaQbehaviourDeferredCBMHandler', function($mmQuestionHelper, $mmaQbehaviourDeferredFeedbackHandler, $mmQuestion) {
var self = {};
/**
* Determine a question state based on its answer(s).
*
* @param {String} component Component the question belongs to.
* @param {Number} attemptId Attempt ID the question belongs to.
* @param {Object} question The question.
* @param {String} [siteId] Site ID. If not defined, current site.
* @return {Promise} Promise resolved with the state or false if cannot determine state.
*/
self.determineQuestionState = function(component, attemptId, question, siteId) {
// Depends on deferredfeedback.
return $mmaQbehaviourDeferredFeedbackHandler.determineQuestionState(
component, attemptId, question, siteId, self.isCompleteResponse, self.isSameResponse);
};
/**
* Check if a response is complete.
*
* @param {Object} question Question.
* @param {Object} answers Answers.
* @return {Mixed} True if complete, false if not complete, -1 if cannot determine.
*/
self.isCompleteResponse = function(question, answers) {
var complete = $mmQuestion.isCompleteResponse(question, answers);
if (complete && complete != -1) {
// Answer is complete, check the user answered CBM too.
return !!answers['-certainty'];
}
return complete;
};
/**
* Check if a response is complete.
*
* @param {Object} question Question.
* @param {Object} prevAnswers Previous answers.
* @param {Object} prevBasicAnswers Previous "basic" answers (without sequencecheck, certainty, ...).
* @param {Object} newAnswers New answers.
* @param {Object} newBasicAnswers New "basic" answers (without sequencecheck, certainty, ...).
* @return {Boolean} True if complete, false if not complete.
*/
self.isSameResponse = function(question, prevAnswers, prevBasicAnswers, newAnswers, newBasicAnswers) {
var same = $mmQuestion.isSameResponse(question, prevBasicAnswers, newBasicAnswers);
if (same) {
// Same response, check the CBM is the same too.
return prevAnswers['-certainty'] == newAnswers['-certainty'];
}
return same;
};
/**
* Whether or not the module is enabled for the site.
*
* @return {Boolean}
*/
self.isEnabled = function() {
return true;
};
/**
* Handle a question.
*
* @param {Object} question The question.
* @return {String[]} Directive to render the certainty options if required, undefined otherwise.
*/
self.handleQuestion = function(question) {
if ($mmQuestionHelper.extractQbehaviourCBM(question)) {
return ['mma-qbehaviour-deferred-cbm'];
}
};
return self;
});
|
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Repository for payment subsystem.
*
* @module core_payment/repository
* @copyright 2020 Shamim Rezaie <shamim@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import Ajax from 'core/ajax';
/**
* @typedef {Object} PaymentGateway A Payment Gateway
* @property {string} shortname
* @property {string} name
* @property {string} description
*/
/**
* Returns the list of gateways that can process payments in the given currency.
*
* @method getAvailableGateways
* @param {string} component
* @param {string} paymentArea
* @param {number} itemId
* @returns {Promise<PaymentGateway[]>}
*/
export const getAvailableGateways = (component, paymentArea, itemId) => {
const request = {
methodname: 'core_payment_get_available_gateways',
args: {
component,
paymentarea: paymentArea,
itemid: itemId,
}
};
return Ajax.call([request])[0];
};
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"priek\u0161pusdien\u0101",
"p\u0113cpusdien\u0101"
],
"DAY": [
"sv\u0113tdiena",
"pirmdiena",
"otrdiena",
"tre\u0161diena",
"ceturtdiena",
"piektdiena",
"sestdiena"
],
"MONTH": [
"janv\u0101ris",
"febru\u0101ris",
"marts",
"apr\u012blis",
"maijs",
"j\u016bnijs",
"j\u016blijs",
"augusts",
"septembris",
"oktobris",
"novembris",
"decembris"
],
"SHORTDAY": [
"Sv",
"Pr",
"Ot",
"Tr",
"Ce",
"Pk",
"Se"
],
"SHORTMONTH": [
"janv.",
"febr.",
"marts",
"apr.",
"maijs",
"j\u016bn.",
"j\u016bl.",
"aug.",
"sept.",
"okt.",
"nov.",
"dec."
],
"fullDate": "EEEE, y. 'gada' d. MMMM",
"longDate": "y. 'gada' d. MMMM",
"medium": "y. 'gada' d. MMM HH:mm:ss",
"mediumDate": "y. 'gada' d. MMM",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "lv-lv",
"pluralCat": function (n, opt_precision) { var vf = getVF(n, opt_precision); if (n % 10 == 0 || n % 100 >= 11 && n % 100 <= 19 || vf.v == 2 && vf.f % 100 >= 11 && vf.f % 100 <= 19) { return PLURAL_CATEGORY.ZERO; } if (n % 10 == 1 && n % 100 != 11 || vf.v == 2 && vf.f % 10 == 1 && vf.f % 100 != 11 || vf.v != 2 && vf.f % 10 == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.query_reports["Customer Acquisition and Loyalty"] = {
"filters": [
{
"fieldname":"company",
"label": __("Company"),
"fieldtype": "Link",
"options": "Company",
"default": frappe.defaults.get_user_default("Company"),
"reqd": 1
},
{
"fieldname":"from_date",
"label": __("From Date"),
"fieldtype": "Date",
"default": frappe.defaults.get_user_default("year_start_date"),
"reqd": 1
},
{
"fieldname":"to_date",
"label": __("To Date"),
"fieldtype": "Date",
"default": frappe.defaults.get_user_default("year_end_date"),
"reqd": 1
},
]
}
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("language","fa",{button:"تعیین زبان",remove:"حذف زبان"});
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --expose-debug-as debug --allow-natives-syntax
// Test debug events when we only listen to uncaught exceptions, the Promise
// throws, and a catch handler is installed right before throwing.
// We expect no debug event to be triggered.
Debug = debug.Debug;
var p = new Promise(function(resolve, reject) {
resolve();
});
var q = p.chain(
function() {
q.catch(function(e) {
assertEquals("caught", e.message);
});
throw new Error("caught");
});
function listener(event, exec_state, event_data, data) {
try {
assertTrue(event != Debug.DebugEvent.Exception);
} catch (e) {
%AbortJS(e + "\n" + e.stack);
}
}
Debug.setBreakOnUncaughtException();
Debug.setListener(listener);
|
// Karma configuration
// Generated on Fri Nov 08 2013 09:25:16 GMT-0600 (Central Standard Time)
var util = require('../lib/grunt/utils.js');
var grunt = require('grunt');
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
// note that the karmangular setup from util.createKarmangularConfig seems
// to take precedence over this, but we can't remove this because then
// the karmangular task doesn't appear to run. So includes the features/**/test, but
// they don't get run if you've used the --fast or --core options
files: [
'bower_components/jquery/jquery.min.js',
'lib/test/jquery.simulate.js',
'bower_components/lodash/dist/lodash.min.js',
'src/js/core/bootstrap.js',
'src/js/**/*.js',
'src/features/**/js/**/*.js',
'test/unit/**/*.spec.js',
'src/features/**/test/**/*.spec.js',
'dist/release/ui-grid.css',
'.tmp/template.js' //templates
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['dots', 'coverage'],
preprocessors: {
// Cover source files but ignore any .spec.js files. Thanks goodness I found the pattern here: https://github.com/karma-runner/karma/pull/834#issuecomment-35626132
'src/**/!(*.spec)+(.js)': ['coverage']
},
coverageReporter: {
type: 'lcov',
dir: 'coverage',
subdir: '.'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 2,
browserNoActivityTimeout: 45000, // 20000,
sauceLabs: {
username: 'nggrid',
startConnect: false,
testName: 'ui-grid unit tests'
},
// For more browsers on Sauce Labs see:
// https://saucelabs.com/docs/platforms/webdriver
customLaunchers: util.customLaunchers()
});
// TODO(c0bra): remove once SauceLabs supports websockets.
// This speeds up the capturing a bit, as browsers don't even try to use websocket. -- (thanks vojta)
if (process.env.TRAVIS) {
config.logLevel = config.LOG_INFO;
config.browserNoActivityTimeout = 120000; // NOTE: from angular.js, for socket.io buffer
config.reporters = ['dots', 'coverage'];
var buildLabel = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
// config.transports = ['websocket', 'xhr-polling'];
config.sauceLabs.build = buildLabel;
config.sauceLabs.startConnect = false;
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
config.transports = ['xhr-polling'];
// Debug logging into a file, that we print out at the end of the build.
config.loggers.push({
type: 'file',
filename: process.env.LOGS_DIR + '/' + ('karma.log')
});
// NOTE: From angular.js project, only applies to SauceLabs -- (thanks Vojta again)
// Allocating a browser can take pretty long (eg. if we are out of capacity and need to wait
// for another build to finish) and so the `captureTimeout` typically kills
// an in-queue-pending request, which makes no sense.
config.captureTimeout = 0;
}
if (grunt.option('browsers')) {
var bs = grunt.option('browsers').split(/,/).map(function(b) { return b.trim(); });
config.browsers = bs;
}
};
|
/*
Project: angular-gantt v1.2.7 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
'use strict';
angular.module('gantt.drawtask', ['gantt']).directive('ganttDrawTask', ['$document', 'ganttMouseOffset', 'moment', function(document, mouseOffset, moment) {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?',
moveThreshold: '=?',
taskModelFactory: '=taskFactory'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
if (scope.enabled === undefined) {
scope.enabled = true;
}
if (scope.moveThreshold === undefined) {
scope.moveThreshold = 0;
}
api.directives.on.new(scope, function(directiveName, directiveScope, element) {
if (directiveName === 'ganttRow') {
var addNewTask = function(x) {
var startDate = api.core.getDateByPosition(x, true);
var endDate = moment(startDate);
var taskModel = scope.taskModelFactory();
taskModel.from = startDate;
taskModel.to = endDate;
var task = directiveScope.row.addTask(taskModel);
task.isResizing = true;
task.updatePosAndSize();
directiveScope.row.updateVisibleTasks();
directiveScope.row.$scope.$digest();
};
var deferDrawing = function(startX) {
var moveTrigger = function(evt) {
var currentX = mouseOffset.getOffset(evt).x;
if (Math.abs(startX - currentX) >= scope.moveThreshold) {
element.off('mousemove', moveTrigger);
addNewTask(startX);
}
};
element.on('mousemove', moveTrigger);
document.one('mouseup', function() {
element.off('mousemove', moveTrigger);
});
};
var drawHandler = function(evt) {
var evtTarget = (evt.target ? evt.target : evt.srcElement);
var enabled = angular.isFunction(scope.enabled) ? scope.enabled(evt): scope.enabled;
if (enabled && evtTarget.className.indexOf('gantt-row') > -1) {
var x = mouseOffset.getOffset(evt).x;
if (scope.moveThreshold === 0) {
addNewTask(x, x);
} else {
deferDrawing(x);
}
}
};
element.on('mousedown', drawHandler);
directiveScope.drawTaskHandler = drawHandler;
}
});
api.directives.on.destroy(scope, function(directiveName, directiveScope, element) {
if (directiveName === 'ganttRow') {
element.off('mousedown', directiveScope.drawTaskHandler);
delete directiveScope.drawTaskHandler;
}
});
}
};
}]);
}());
angular.module('gantt.drawtask.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-drawtask-plugin.js.map
|
// TinyMCE helper, checks to see if TinyMCE editors in the given form are dirty
// Support for UMD: https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
// This allows for tools such as Browserify to compose the components together into a single HTTP request.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
// Create a new object, with an isDirty method
var tinymce = {
ignoreAnchorSelector: '.mceEditor a,.mceMenu a',
isDirty: function (form) {
var isDirty = false;
if (formHasTinyMCE(form)) {
//..alert('in finder');
// Search for all tinymce elements inside the given form
$(form).find(':tinymce').each(function () {
$.DirtyForms.dirtylog('Checking node ' + $(this).attr('id'));
if ($(this).tinymce().isDirty()) {
isDirty = true;
$.DirtyForms.dirtylog('Node was totally dirty.');
// Return false to break out of the .each() function
return false;
}
});
}
return isDirty;
},
setClean: function (form) {
if (formHasTinyMCE(form)) {
// Search for all tinymce elements inside the given form
$(form).find(':tinymce').each(function () {
if ($(this).tinymce().isDirty()) {
$.DirtyForms.dirtylog('Resetting isDirty on node ' + $(this).attr('id'));
$(this).tinymce().isNotDirty = 1; //Force not dirty state
}
});
}
}
};
// Fix: tinymce throws an error if the selector doesn't match anything
// (such as when there are no textareas on the current page)
var formHasTinyMCE = function (form) {
try {
return $(form).find(':tinymce').length > 0;
}
catch (e) {
return false;
}
};
// Push the new object onto the helpers array
$.DirtyForms.helpers.push(tinymce);
// Create a pre refire binding to trigger the tinymce save
//$(document).bind('beforeRefire.dirtyforms', function(){
// This is no longer needed, but kept here to remind me.
// tinyMCE.triggerSave();
//});
}));
|
/**
* @fileoverview A rule to disallow negated left operands of the `in` operator
* @author Michael Ficarra
* @deprecated in ESLint v3.3.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow negating the left operand in `in` expressions",
category: "Possible Errors",
recommended: true,
replacedBy: ["no-unsafe-negation"]
},
deprecated: true,
schema: []
},
create(context) {
return {
BinaryExpression(node) {
if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") {
context.report({ node, message: "The 'in' expression's left operand is negated." });
}
}
};
}
};
|
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.nl = jQuery.extend(window.ParsleyConfig.i18n.nl || {}, {
defaultMessage: "Deze waarde lijkt onjuist.",
type: {
email: "Dit lijkt geen geldig e-mail adres te zijn.",
url: "Dit lijkt geen geldige URL te zijn.",
number: "Deze waarde moet een nummer zijn.",
integer: "Deze waarde moet een nummer zijn.",
digits: "Deze waarde moet numeriek zijn.",
alphanum: "Deze waarde moet alfanumeriek zijn."
},
notblank: "Deze waarde mag niet leeg zijn.",
required: "Dit veld is verplicht.",
pattern: "Deze waarde lijkt onjuist te zijn.",
min: "Deze waarde mag niet lager zijn dan %s.",
max: "Deze waarde mag niet groter zijn dan %s.",
range: "Deze waarde moet tussen %s en %s liggen.",
minlength: "Deze tekst is te kort. Deze moet uit minimaal %s karakters bestaan.",
maxlength: "Deze waarde is te lang. Deze mag maximaal %s karakters lang zijn.",
length: "Deze waarde moet tussen %s en %s karakters lang zijn.",
equalto: "Deze waardes moeten identiek zijn."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('nl', window.ParsleyConfig.i18n.nl, true);
|
//! moment.js locale configuration
//! locale : Luxembourgish [lb]
//! author : mweimerskirch : https://github.com/mweimerskirch
//! author : David Raison : https://github.com/kwisatz
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
function processRelativeTime(number, withoutSuffix, key, isFuture) {
var format = {
'm': ['eng Minutt', 'enger Minutt'],
'h': ['eng Stonn', 'enger Stonn'],
'd': ['een Dag', 'engem Dag'],
'M': ['ee Mount', 'engem Mount'],
'y': ['ee Joer', 'engem Joer']
};
return withoutSuffix ? format[key][0] : format[key][1];
}
function processFutureTime(string) {
var number = string.substr(0, string.indexOf(' '));
if (eifelerRegelAppliesToNumber(number)) {
return 'a ' + string;
}
return 'an ' + string;
}
function processPastTime(string) {
var number = string.substr(0, string.indexOf(' '));
if (eifelerRegelAppliesToNumber(number)) {
return 'viru ' + string;
}
return 'virun ' + string;
}
/**
* Returns true if the word before the given number loses the '-n' ending.
* e.g. 'an 10 Deeg' but 'a 5 Deeg'
*
* @param number {integer}
* @returns {boolean}
*/
function eifelerRegelAppliesToNumber(number) {
number = parseInt(number, 10);
if (isNaN(number)) {
return false;
}
if (number < 0) {
// Negative Number --> always true
return true;
} else if (number < 10) {
// Only 1 digit
if (4 <= number && number <= 7) {
return true;
}
return false;
} else if (number < 100) {
// 2 digits
var lastDigit = number % 10, firstDigit = number / 10;
if (lastDigit === 0) {
return eifelerRegelAppliesToNumber(firstDigit);
}
return eifelerRegelAppliesToNumber(lastDigit);
} else if (number < 10000) {
// 3 or 4 digits --> recursively check first digit
while (number >= 10) {
number = number / 10;
}
return eifelerRegelAppliesToNumber(number);
} else {
// Anything larger than 4 digits: recursively check first n-3 digits
number = number / 1000;
return eifelerRegelAppliesToNumber(number);
}
}
var lb = moment.defineLocale('lb', {
months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
monthsParseExact : true,
weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'),
weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'),
weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'),
weekdaysParseExact : true,
longDateFormat: {
LT: 'H:mm [Auer]',
LTS: 'H:mm:ss [Auer]',
L: 'DD.MM.YYYY',
LL: 'D. MMMM YYYY',
LLL: 'D. MMMM YYYY H:mm [Auer]',
LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]'
},
calendar: {
sameDay: '[Haut um] LT',
sameElse: 'L',
nextDay: '[Muer um] LT',
nextWeek: 'dddd [um] LT',
lastDay: '[Gëschter um] LT',
lastWeek: function () {
// Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule
switch (this.day()) {
case 2:
case 4:
return '[Leschten] dddd [um] LT';
default:
return '[Leschte] dddd [um] LT';
}
}
},
relativeTime : {
future : processFutureTime,
past : processPastTime,
s : 'e puer Sekonnen',
ss : '%d Sekonnen',
m : processRelativeTime,
mm : '%d Minutten',
h : processRelativeTime,
hh : '%d Stonnen',
d : processRelativeTime,
dd : '%d Deeg',
M : processRelativeTime,
MM : '%d Méint',
y : processRelativeTime,
yy : '%d Joer'
},
dayOfMonthOrdinalParse: /\d{1,2}\./,
ordinal: '%d.',
week: {
dow: 1, // Monday is the first day of the week.
doy: 4 // The week that contains Jan 4th is the first week of the year.
}
});
return lb;
})));
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'radio', function( editor )
{
return {
title : editor.lang.checkboxAndRadio.radioTitle,
minWidth : 350,
minHeight : 140,
onShow : function()
{
delete this.radioButton;
var element = this.getParentEditor().getSelection().getSelectedElement();
if ( element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'radio' )
{
this.radioButton = element;
this.setupContent( element );
}
},
onOk : function()
{
var editor,
element = this.radioButton,
isInsertMode = !element;
if ( isInsertMode )
{
editor = this.getParentEditor();
element = editor.document.createElement( 'input' );
element.setAttribute( 'type', 'radio' );
}
if ( isInsertMode )
editor.insertElement( element );
this.commitContent( { element : element } );
},
contents : [
{
id : 'info',
label : editor.lang.checkboxAndRadio.radioTitle,
title : editor.lang.checkboxAndRadio.radioTitle,
elements : [
{
id : 'name',
type : 'text',
label : editor.lang.common.name,
'default' : '',
accessKey : 'N',
setup : function( element )
{
this.setValue(
element.data( 'cke-saved-name' ) ||
element.getAttribute( 'name' ) ||
'' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.data( 'cke-saved-name', this.getValue() );
else
{
element.data( 'cke-saved-name', false );
element.removeAttribute( 'name' );
}
}
},
{
id : 'value',
type : 'text',
label : editor.lang.checkboxAndRadio.value,
'default' : '',
accessKey : 'V',
setup : function( element )
{
this.setValue( element.getAttribute( 'value' ) || '' );
},
commit : function( data )
{
var element = data.element;
if ( this.getValue() )
element.setAttribute( 'value', this.getValue() );
else
element.removeAttribute( 'value' );
}
},
{
id : 'checked',
type : 'checkbox',
label : editor.lang.checkboxAndRadio.selected,
'default' : '',
accessKey : 'S',
value : "checked",
setup : function( element )
{
this.setValue( element.getAttribute( 'checked' ) );
},
commit : function( data )
{
var element = data.element;
if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) )
{
if ( this.getValue() )
element.setAttribute( 'checked', 'checked' );
else
element.removeAttribute( 'checked' );
}
else
{
var isElementChecked = element.getAttribute( 'checked' );
var isChecked = !!this.getValue();
if ( isElementChecked != isChecked )
{
var replace = CKEDITOR.dom.element.createFromHtml( '<input type="radio"'
+ ( isChecked ? ' checked="checked"' : '' )
+ '></input>', editor.document );
element.copyAttributes( replace, { type : 1, checked : 1 } );
replace.replace( element );
editor.getSelection().selectElement( replace );
data.element = replace;
}
}
}
}
]
}
]
};
});
|
module.exports = function (obj, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var space = opts.space || '';
if (typeof space === 'number') space = Array(space+1).join(' ');
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var replacer = opts.replacer || function(key, value) { return value; };
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (parent, key, node, level) {
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
var colonSeparator = space ? ': ' : ':';
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
node = replacer.call(parent, key, node);
if (node === undefined) {
return;
}
if (typeof node !== 'object' || node === null) {
return JSON.stringify(node);
}
if (isArray(node)) {
var out = [];
for (var i = 0; i < node.length; i++) {
var item = stringify(node, i, node[i], level+1) || JSON.stringify(null);
out.push(indent + space + item);
}
return '[' + out.join(',') + indent + ']';
}
else {
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
else seen.push(node);
var keys = objectKeys(node).sort(cmp && cmp(node));
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node, key, node[key], level+1);
if(!value) continue;
var keyValue = JSON.stringify(key)
+ colonSeparator
+ value;
;
out.push(indent + space + keyValue);
}
seen.splice(seen.indexOf(node), 1);
return '{' + out.join(',') + indent + '}';
}
})({ '': obj }, '', obj, 0);
};
var isArray = Array.isArray || function (x) {
return {}.toString.call(x) === '[object Array]';
};
var objectKeys = Object.keys || function (obj) {
var has = Object.prototype.hasOwnProperty || function () { return true };
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
|
describe("module:ng.directive:ngList", function() {
beforeEach(function() {
browser.get("./examples/example-ngList-directive/index.html");
});
var listInput = element(by.model('names'));
var names = element(by.binding('{{names}}'));
var valid = element(by.binding('myForm.namesInput.$valid'));
var error = element(by.css('span.error'));
it('should initialize to model', function() {
expect(names.getText()).toContain('["igor","misko","vojta"]');
expect(valid.getText()).toContain('true');
expect(error.getCssValue('display')).toBe('none');
});
it('should be invalid if empty', function() {
listInput.clear();
listInput.sendKeys('');
expect(names.getText()).toContain('');
expect(valid.getText()).toContain('false');
expect(error.getCssValue('display')).not.toBe('none'); });
});
|
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
var test = require('tape');
var binary = require('thrift/binary');
var cases = {
"Should read signed byte": function(assert){
assert.equal(1, binary.readByte(0x01));
assert.equal(-1, binary.readByte(0xFF));
assert.equal(127, binary.readByte(0x7F));
assert.equal(-128, binary.readByte(0x80));
assert.end();
},
"Should write byte": function(assert){
//Protocol simply writes to the buffer. Nothing to test.. yet.
assert.ok(true);
assert.end();
},
"Should read I16": function(assert) {
assert.equal(0, binary.readI16([0x00, 0x00]));
assert.equal(1, binary.readI16([0x00, 0x01]));
assert.equal(-1, binary.readI16([0xff, 0xff]));
// Min I16
assert.equal(-32768, binary.readI16([0x80, 0x00]));
// Max I16
assert.equal(32767, binary.readI16([0x7f, 0xff]));
assert.end();
},
"Should write I16": function(assert) {
assert.deepEqual([0x00, 0x00], binary.writeI16([], 0));
assert.deepEqual([0x00, 0x01], binary.writeI16([], 1));
assert.deepEqual([0xff, 0xff], binary.writeI16([], -1));
// Min I16
assert.deepEqual([0x80, 0x00], binary.writeI16([], -32768));
// Max I16
assert.deepEqual([0x7f, 0xff], binary.writeI16([], 32767));
assert.end();
},
"Should read I32": function(assert) {
assert.equal(0, binary.readI32([0x00, 0x00, 0x00, 0x00]));
assert.equal(1, binary.readI32([0x00, 0x00, 0x00, 0x01]));
assert.equal(-1, binary.readI32([0xff, 0xff, 0xff, 0xff]));
// Min I32
assert.equal(-2147483648, binary.readI32([0x80, 0x00, 0x00, 0x00]));
// Max I32
assert.equal(2147483647, binary.readI32([0x7f, 0xff, 0xff, 0xff]));
assert.end();
},
"Should write I32": function(assert) {
assert.deepEqual([0x00, 0x00, 0x00, 0x00], binary.writeI32([], 0));
assert.deepEqual([0x00, 0x00, 0x00, 0x01], binary.writeI32([], 1));
assert.deepEqual([0xff, 0xff, 0xff, 0xff], binary.writeI32([], -1));
// Min I32
assert.deepEqual([0x80, 0x00, 0x00, 0x00], binary.writeI32([], -2147483648));
// Max I32
assert.deepEqual([0x7f, 0xff, 0xff, 0xff], binary.writeI32([], 2147483647));
assert.end();
},
"Should read doubles": function(assert) {
assert.equal(0, binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(0, binary.readDouble([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(1, binary.readDouble([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(2, binary.readDouble([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(-2, binary.readDouble([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(Math.PI, binary.readDouble([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]))
assert.equal(Infinity, binary.readDouble([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.equal(-Infinity, binary.readDouble([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
assert.ok(isNaN(binary.readDouble([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])))
assert.equal(1/3, binary.readDouble([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]))
// Min subnormal positive double
assert.equal(4.9406564584124654e-324, binary.readDouble([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]))
// Min normal positive double
assert.equal(2.2250738585072014e-308, binary.readDouble([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
// Max positive double
assert.equal(1.7976931348623157e308, binary.readDouble([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]))
assert.end();
},
"Should write doubles": function(assert) {
assert.deepEqual([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 0));
assert.deepEqual([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 1));
assert.deepEqual([0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 2));
assert.deepEqual([0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], -2));
assert.deepEqual([0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18], binary.writeDouble([], Math.PI));
assert.deepEqual([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], Infinity));
assert.deepEqual([0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], -Infinity));
assert.deepEqual([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], NaN));
assert.deepEqual([0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55], binary.writeDouble([], 1/3));
// Min subnormal positive double
assert.deepEqual([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], binary.writeDouble([], 4.9406564584124654e-324));
// Min normal positive double
assert.deepEqual([0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], binary.writeDouble([], 2.2250738585072014e-308));
// Max positive double
assert.deepEqual([0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], binary.writeDouble([], 1.7976931348623157e308));
assert.end();
}
};
Object.keys(cases).forEach(function(caseName) {
test(caseName, cases[caseName]);
});
|
// $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $
/**
* Wysiwyg API integration helper function.
*/
function imceImageBrowser(field_name, url, type, win) {
// TinyMCE.
if (win !== 'undefined') {
win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1');
}
}
/**
* CKeditor integration.
*/
var imceCkeditSendTo = function (file, win) {
var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href);
if (parts && parts.length > 1) {
CKEDITOR.tools.callFunction(parts[1], file.url);
win.close();
}
else {
throw 'CKEditorFuncNum parameter not found or invalid: ' + win.location.href;
}
};
|
var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
B_CRLF = new Buffer('\r\n');
function Dicer(cfg) {
if (!(this instanceof Dicer))
return new Dicer(cfg);
WritableStream.call(this, cfg);
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string'))
throw new TypeError('Boundary required');
if (typeof cfg.boundary === 'string')
this.setBoundary(cfg.boundary);
else
this._bparser = undefined;
this._headerFirst = cfg.headerFirst;
var self = this;
this._dashes = 0;
this._parts = 0;
this._finished = false;
this._isPreamble = true;
this._justMatched = false;
this._firstWrite = true;
this._inHeader = true;
this._part = undefined;
this._cb = undefined;
this._partOpts = (typeof cfg.partHwm === 'number'
? { highWaterMark: cfg.partHwm }
: {});
this._pause = false;
this._hparser = new HeaderParser(cfg);
this._hparser.on('header', function(header) {
self._inHeader = false;
self._part.emit('header', header);
});
}
inherits(Dicer, WritableStream);
Dicer.prototype._write = function(data, encoding, cb) {
var self = this;
if (this._headerFirst && this._isPreamble) {
if (!this._part) {
this._part = new PartStream(this._partOpts);
this.emit('preamble', this._part);
}
var r = this._hparser.push(data);
if (!this._inHeader && r !== undefined && r < data.length)
data = data.slice(r);
else
return cb();
}
// allows for "easier" testing
if (this._firstWrite) {
this._bparser.push(B_CRLF);
this._firstWrite = false;
}
this._bparser.push(data);
if (this._pause)
this._cb = cb;
else
cb();
};
Dicer.prototype.reset = function() {
this._part = undefined;
this._bparser = undefined;
this._hparser = undefined;
};
Dicer.prototype.setBoundary = function(boundary) {
var self = this;
this._bparser = new StreamSearch('\r\n--' + boundary);
this._bparser.on('info', function(isMatch, data, start, end) {
self._oninfo(isMatch, data, start, end);
});
};
Dicer.prototype._oninfo = function(isMatch, data, start, end) {
var buf, self = this, i = 0, r, shouldWriteMore = true;
if (!this._part && this._justMatched && data) {
while (this._dashes < 2 && (start + i) < end) {
if (data[start + i] === 45) {
++i;
++this._dashes;
} else {
if (this._dashes)
buf = B_ONEDASH;
this._dashes = 0;
break;
}
}
if (this._dashes === 2) {
if ((start + i) < end && this._events.trailer)
this.emit('trailer', data.slice(start + i, end));
this.reset();
this._finished = true;
//process.nextTick(function() { self.emit('end'); });
}
if (this._dashes)
return;
}
if (this._justMatched)
this._justMatched = false;
if (!this._part) {
this._part = new PartStream(this._partOpts);
this._part._read = function(n) {
if (!self._pause)
return;
self._pause = false;
if (self._cb) {
var cb = self._cb;
self._cb = undefined;
cb();
}
};
this.emit(this._isPreamble ? 'preamble' : 'part', this._part);
if (!this._isPreamble)
this._inHeader = true;
}
if (data && start < end) {
if (this._isPreamble || !this._inHeader) {
if (buf)
shouldWriteMore = this._part.push(buf);
shouldWriteMore = this._part.push(data.slice(start, end));
if (!shouldWriteMore)
this._pause = true;
} else if (!this._isPreamble && this._inHeader) {
if (buf)
this._hparser.push(buf);
r = this._hparser.push(data.slice(start, end));
if (!this._inHeader && r !== undefined && r < end)
this._oninfo(false, data, start + r, end);
}
}
if (isMatch) {
this._hparser.reset();
if (this._isPreamble)
this._isPreamble = false;
else {
++this._parts;
this._part.on('end', function() {
if (--self._parts === 0 && self._finished) {
self._finished = false;
self.emit('end');
}
});
}
this._part.push(null);
this._part = undefined;
this._justMatched = true;
this._dashes = 0;
}
};
module.exports = Dicer;
|
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level2/events/dispatchEvent01";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
//
function setUpPage() {
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "hc_staff");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
/**
*
A null reference is passed to EventTarget.dispatchEvent(), should raise implementation
or platform exception.
* @author Curt Arnold
* @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent
* @see http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-17189187
*/
function dispatchEvent01() {
var success;
if(checkInitialization(builder, "dispatchEvent01") != null) return;
var doc;
var target;
var evt = null;
var preventDefault;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
{
success = false;
try {
preventDefault = doc.dispatchEvent(evt);
} catch (ex) {
success = true;
}
assertTrue("throw_ImplException", success);
}
}
function runTest() {
dispatchEvent01();
}
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'hu', {
toolbar: 'Új oldal'
});
|
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
|
/*
* bootstrap-table - v1.11.0 - 2016-07-02
* https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2016 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.fn.bootstrapTable.locales["ko-KR"]={formatLoadingMessage:function(){return"데이터를 불러오는 중입니다..."},formatRecordsPerPage:function(a){return"페이지 당 "+a+"개 데이터 출력"},formatShowingRows:function(a,b,c){return"전체 "+c+"개 중 "+a+"~"+b+"번째 데이터 출력,"},formatSearch:function(){return"검색"},formatNoMatches:function(){return"조회된 데이터가 없습니다."},formatRefresh:function(){return"새로 고침"},formatToggle:function(){return"전환"},formatColumns:function(){return"컬럼 필터링"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["ko-KR"])}(jQuery);
|
/* */
require("../../modules/js.array.statics");
module.exports = require("../../modules/$").core.Array.filter;
|
var parent = require('../../es/reflect');
module.exports = parent;
|
var a: [] = [];
var a: [Foo<T>] = [foo];
var a: [number] = [123];
var a: [number, string] = [123, "duck"];
|
var test = require('tape');
var oldToNew = require('../index').oldToNew;
var newToOld = require('../index').newToOld;
test('plugin mappings exist', function(t) {
t.plan(2);
t.equal('cordova-plugin-device', oldToNew['org.apache.cordova.device']);
t.equal('org.apache.cordova.device', newToOld['cordova-plugin-device']);
})
|
/*!
* Qoopido.js library v3.4.3, 2014-6-11
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*//*!
* Qoopido.js library
*
* version: 3.4.3
* date: 2014-6-11
* author: Dirk Lueth <info@qoopido.com>
* website: https://github.com/dlueth/qoopido.js
*
* Copyright (c) 2014 Dirk Lueth
*
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*/
!function(t){window.qoopido.register("support/element/canvas/todataurl",t,["../../../support","../canvas"])}(function(t,e,n,o,a,s,r){"use strict";var c=t.support;return c.addTest("/element/canvas/todataurl",function(e){t["support/element/canvas"]().then(function(){var t=c.pool?c.pool.obtain("canvas"):s.createElement("canvas");t.toDataURL!==r?e.resolve():e.reject(),t.dispose&&t.dispose()},function(){e.reject()}).done()})});
|
var a = {
echo(c) {
return c;
}
};
assert.strictEqual(a.echo(1), 1);
|
/**
* @file
* This file contains most of the code for the configuration page.
*/
// Create the drupal ShareThis object for clean code and namespacing:
var drupal_st = {
// These are handlerd for updating the widget pic class.
multiW: function() {
jQuery(".st_widgetPic").addClass("st_multi");
},
classicW: function() {
jQuery(".st_widgetPic").removeClass("st_multi");
},
// These are the handlers for updating the button pic class (stbc = sharethisbuttonclass).
smallChicklet: function () {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_");
},
largeChicklet: function () {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_large");
},
hcount: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_hcount");
},
vcount: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_vcount");
},
button: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_button");
},
// This is a helper function for updating button pictures.
removeButtonClasses: function() {
var toRemove = jQuery("#stb_sprite");
toRemove.removeClass("stbc_");
toRemove.removeClass("stbc_large");
toRemove.removeClass("stbc_hcount");
toRemove.removeClass("stbc_vcount");
toRemove.removeClass("stbc_button");
},
//Write helper functions for saving:
getWidget: function () {
return jQuery(".st_widgetPic").hasClass("st_multiW") ? '5x': '4x';
},
getButtons: function () {
var selectedButton = 'large';
var buttonButtons = jQuery(".st_wIm");
buttonButtons.each(function () {
if (jQuery(this).hasClass("st_select")) {
selectedButton = jQuery(this).attr("id").substring(3);
}
});
console.log(selectedButton);
return selectedButton;
},
setupServiceText: function () {
jQuery("#edit-sharethis-service-option").css({display:"none"});
},
// Function to add various events to our html form elements
addEvents: function() {
jQuery("#edit-sharethis-widget-option-st-multi").click(drupal_st.multiW);
jQuery("#edit-sharethis-widget-option-st-direct").click(drupal_st.classicW);
jQuery("#edit-sharethis-button-option-stbc-").click(drupal_st.smallChicklet);
jQuery("#edit-sharethis-button-option-stbc-large").click(drupal_st.largeChicklet);
jQuery("#edit-sharethis-button-option-stbc-hcount").click(drupal_st.hcount);
jQuery("#edit-sharethis-button-option-stbc-vcount").click(drupal_st.vcount);
jQuery("#edit-sharethis-button-option-stbc-button").click(drupal_st.button);
jQuery(".st_formButtonSave").click(drupal_st.updateOptions);
},
serviceCallback: function() {
var services = stlib_picker.getServices("myPicker");
var outputString = "";
for(i=0;i<services.length;i++) {
outputString += "\"" + _all_services[services[i]].title + ":"
outputString += services[i] + "\","
}
outputString = outputString.substring(0, outputString.length-1);
jQuery("#edit-sharethis-service-option").attr("value", outputString);
}
};
//After the page is loaded, we want to add events to dynamically created elements.
jQuery(document).ready(drupal_st.addEvents);
//After it's all done, hide the text field for the service picker so that no one messes up the data.
jQuery(document).ready(drupal_st.setupServiceText);
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleDependencyTemplateAsRequireId {
apply(dep, source, outputOptions, requestShortener) {
if(!dep.range) return;
const comment = outputOptions.pathinfo ?
`/*! ${requestShortener.shorten(dep.request)} */ ` : "";
let content;
if(dep.module)
content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`;
else
content = require("./WebpackMissingModule").module(dep.request);
source.replace(dep.range[0], dep.range[1] - 1, content);
}
}
module.exports = ModuleDependencyTemplateAsRequireId;
|
/**
* @author alteredq / http://alteredqualia.com/
*
* AudioObject
*
* - 3d spatialized sound with Doppler-shift effect
*
* - uses Audio API (currently supported in WebKit-based browsers)
* https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
*
* - based on Doppler effect demo from Chromium
* http://chromium.googlecode.com/svn/trunk/samples/audio/doppler.html
*
* - parameters
*
* - listener
* dopplerFactor // A constant used to determine the amount of pitch shift to use when rendering a doppler effect.
* speedOfSound // The speed of sound used for calculating doppler shift. The default value is 343.3 meters / second.
*
* - panner
* refDistance // A reference distance for reducing volume as source move further from the listener.
* maxDistance // The maximum distance between source and listener, after which the volume will not be reduced any further.
* rolloffFactor // Describes how quickly the volume is reduced as source moves away from listener.
* coneInnerAngle // An angle inside of which there will be no volume reduction.
* coneOuterAngle // An angle outside of which the volume will be reduced to a constant value of coneOuterGain.
* coneOuterGain // Amount of volume reduction outside of the coneOuterAngle.
*/
THREE.AudioObject = function ( url, volume, playbackRate, loop ) {
THREE.Object3D.call( this );
if ( playbackRate === undefined ) playbackRate = 1;
if ( volume === undefined ) volume = 1;
if ( loop === undefined ) loop = true;
if ( ! this.context ) {
try {
THREE.AudioObject.prototype.context = new webkitAudioContext();
} catch ( error ) {
console.warn( "THREE.AudioObject: webkitAudioContext not found" );
return this;
}
}
this.directionalSource = false;
this.listener = this.context.listener;
this.panner = this.context.createPanner();
this.source = this.context.createBufferSource();
this.masterGainNode = this.context.createGainNode();
this.dryGainNode = this.context.createGainNode();
// Setup initial gains
this.masterGainNode.gain.value = volume;
this.dryGainNode.gain.value = 3.0;
// Connect dry mix
this.source.connect( this.panner );
this.panner.connect( this.dryGainNode );
this.dryGainNode.connect( this.masterGainNode );
// Connect master gain
this.masterGainNode.connect( this.context.destination );
// Set source parameters and load sound
this.source.playbackRate.value = playbackRate;
this.source.loop = loop;
loadBufferAndPlay( url );
// private properties
var soundPosition = new THREE.Vector3(),
cameraPosition = new THREE.Vector3(),
oldSoundPosition = new THREE.Vector3(),
oldCameraPosition = new THREE.Vector3(),
soundDelta = new THREE.Vector3(),
cameraDelta = new THREE.Vector3(),
soundFront = new THREE.Vector3(),
cameraFront = new THREE.Vector3(),
soundUp = new THREE.Vector3(),
cameraUp = new THREE.Vector3();
var _this = this;
// API
this.setVolume = function ( volume ) {
this.masterGainNode.gain.value = volume;
};
this.update = function ( camera ) {
oldSoundPosition.copy( soundPosition );
oldCameraPosition.copy( cameraPosition );
soundPosition.setFromMatrixPosition( this.matrixWorld );
cameraPosition.setFromMatrixPosition( camera.matrixWorld );
soundDelta.subVectors( soundPosition, oldSoundPosition );
cameraDelta.subVectors( cameraPosition, oldCameraPosition );
cameraUp.copy( camera.up );
cameraFront.set( 0, 0, -1 );
cameraFront.transformDirection( camera.matrixWorld );
this.listener.setPosition( cameraPosition.x, cameraPosition.y, cameraPosition.z );
this.listener.setVelocity( cameraDelta.x, cameraDelta.y, cameraDelta.z );
this.listener.setOrientation( cameraFront.x, cameraFront.y, cameraFront.z, cameraUp.x, cameraUp.y, cameraUp.z );
this.panner.setPosition( soundPosition.x, soundPosition.y, soundPosition.z );
this.panner.setVelocity( soundDelta.x, soundDelta.y, soundDelta.z );
if ( this.directionalSource ) {
soundFront.set( 0, 0, -1 );
soundFront.transformDirection( this.matrixWorld );
soundUp.copy( this.up );
this.panner.setOrientation( soundFront.x, soundFront.y, soundFront.z, soundUp.x, soundUp.y, soundUp.z );
}
};
function loadBufferAndPlay( url ) {
// Load asynchronously
var request = new XMLHttpRequest();
request.open( "GET", url, true );
request.responseType = "arraybuffer";
request.onload = function() {
_this.source.buffer = _this.context.createBuffer( request.response, true );
_this.source.noteOn( 0 );
}
request.send();
}
};
THREE.AudioObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.AudioObject.prototype.constructor = THREE.AudioObject;
THREE.AudioObject.prototype.context = null;
THREE.AudioObject.prototype.type = null;
|
import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
export default get;
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var stdin = require('get-stdin');
var pkg = require('./package.json');
var stripIndent = require('./');
var argv = process.argv.slice(2);
var input = argv[0];
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Usage',
' strip-indent <file>',
' echo <string> | strip-indent',
'',
' Example',
' echo \'\\tunicorn\\n\\t\\tcake\' | strip-indent',
' unicorn',
' \tcake'
].join('\n'));
}
function init(data) {
console.log(stripIndent(data));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
if (process.stdin.isTTY) {
if (!input) {
help();
return;
}
init(fs.readFileSync(input, 'utf8'));
} else {
stdin(init);
}
|
/*!
{
"name": "ES5 String.prototype.contains",
"property": "contains",
"authors": ["Robert Kowalski"],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 `String.prototype.contains` per specification.
*/
define(['Modernizr', 'is'], function(Modernizr, is) {
Modernizr.addTest('contains', is(String.prototype.contains, 'function'));
});
|
var baseForRight = require('./_baseForRight'),
keys = require('./keys');
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
module.exports = baseForOwnRight;
|
$(function () {
'use strict';
module('affix plugin')
test('should be defined on jquery object', function () {
ok($(document.body).affix, 'affix method is defined')
})
module('affix', {
setup: function () {
// Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode
$.fn.bootstrapAffix = $.fn.affix.noConflict()
},
teardown: function () {
$.fn.affix = $.fn.bootstrapAffix
delete $.fn.bootstrapAffix
}
})
test('should provide no conflict', function () {
strictEqual($.fn.affix, undefined, 'affix was set back to undefined (org value)')
})
test('should return jquery collection containing the element', function () {
var $el = $('<div/>')
var $affix = $el.bootstrapAffix()
ok($affix instanceof $, 'returns jquery collection')
strictEqual($affix[0], $el[0], 'collection contains element')
})
test('should exit early if element is not visible', function () {
var $affix = $('<div style="display: none"/>').bootstrapAffix()
$affix.data('bs.affix').checkPosition()
ok(!$affix.hasClass('affix'), 'affix class was not added')
})
test('should trigger affixed event after affix', function () {
stop()
var templateHTML = '<div id="affixTarget">'
+ '<ul>'
+ '<li>Please affix</li>'
+ '<li>And unaffix</li>'
+ '</ul>'
+ '</div>'
+ '<div id="affixAfter" style="height: 20000px; display: block;"/>'
$(templateHTML).appendTo(document.body)
$('#affixTarget').bootstrapAffix({
offset: $('#affixTarget ul').position()
})
$('#affixTarget')
.on('affix.bs.affix', function () {
ok(true, 'affix event fired')
}).on('affixed.bs.affix', function () {
ok(true, 'affixed event fired')
$('#affixTarget, #affixAfter').remove()
start()
})
setTimeout(function () {
window.scrollTo(0, document.body.scrollHeight)
setTimeout(function () {
window.scroll(0, 0)
}, 16) // for testing in a browser
}, 0)
})
})
|
require('../modules/es6.object.to-string');
require('../modules/web.dom.iterable');
require('../modules/es6.weak-map');
module.exports = require('../modules/$.core').WeakMap;
|
import mod1770 from './mod1770';
var value=mod1770+1;
export default value;
|
$().ready(function () {
var $likeDislikeTripButton = $('#likeDislikeTripButton'),
$likesCount = $('#likesCount'),
ajaxAFT = $('#ajaxAFT input[name="__RequestVerificationToken"]:first').val();
$likeDislikeTripButton.on('click', function () {
var $this = $(this),
valueAsString = $this.attr('data-value'),
value = false
if (valueAsString == 'like') {
value = true;
}
$.ajax({
type: "POST",
url: '/TripAjax/LikeDislikeTrip',
data: {
__RequestVerificationToken: ajaxAFT,
tripId: tripId,
value: value
},
success: function (response) {
if (response.Status) {
if (value) {
addDislikeButton();
} else {
addLikeButton();
}
updateLikeCounts(response.Data);
toastr.success("You have successfully " + valueAsString + " this trip.");
} else {
if (response.ErrorMessage) {
toastr.error(response.ErrorMessage);
} else {
toastr.error("Unable to " + valueAsString + " this trip.");
}
}
}
})
});
function updateLikeCounts(likesCount) {
$likesCount.text(likesCount);
}
function addDislikeButton() {
$likeDislikeTripButton.removeClass('likeButton');
$likeDislikeTripButton.addClass('dislikeButton');
$likeDislikeTripButton.attr('data-value', 'dislike');
}
function addLikeButton() {
$likeDislikeTripButton.removeClass('dislikeButton');
$likeDislikeTripButton.addClass('likeButton');
$likeDislikeTripButton.attr('data-value', 'like');
}
})
|
import CDGPlayer from './CDGPlayer'
export default CDGPlayer
|
var structdbs_1_1i_1_1_r1 =
[
[ "nodes", "structdbs_1_1i_1_1_r1.html#a249eb273e89b4e1a053dea78ec1f2a3c", null ]
];
|
'use strict';
import React, { Component, PropTypes } from 'react';
class Package extends Component {
static propTypes = {
children: PropTypes.node,
billItems: PropTypes.object
}
render() {
const { billItems } = this.props;
const { subscriptions } = this.props.billItems.package;
const packages = subscriptions.map((val, key) =>
<tr key={key}>
<td>{val.name}</td>
<td>{val.type}</td>
<td>{val.cost}</td>
</tr>
);
return (
<section>
<h1>Latest Bill</h1>
<h3>Package</h3>
<table>
<thead>
<tr>
<th>Subscription</th>
<th>Type</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{packages}
</tbody>
</table>
<p><strong>Sub Total</strong> {billItems.package.total}</p>
{this.props.children}
</section>
);
}
}
export default Package;
|
'use strict';
require('nightingale-app-console');
var _pool = require('koack/pool');
var _pool2 = _interopRequireDefault(_pool);
var _server = require('koack/server');
var _server2 = _interopRequireDefault(_server);
var _memory = require('koack/storages/memory');
var _memory2 = _interopRequireDefault(_memory);
var _interactiveMessages = require('koack/interactive-messages');
var _interactiveMessages2 = _interopRequireDefault(_interactiveMessages);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pool = new _pool2.default({
size: 100,
path: require.resolve('./bot')
});
const server = new _server2.default({
pool,
scopes: ['bot'],
slackClient: _config2.default.slackClient,
storage: (0, _memory2.default)()
});
server.proxy = true;
server.use((0, _interactiveMessages2.default)({
pool,
token: _config2.default.verificationToken
}));
server.listen({ port: process.env.PORT || 3000 });
//# sourceMappingURL=index.js.map
|
// External modules
var del = require('del');
var critical = require('critical').stream;
// Import config
var config = require('./_config');
// Html module
module.exports = function(gulp, livereload) {
gulp.task('html', function() {
return gulp.src(config.html)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('html--deploy', function() {
return gulp.src(config.html)
.pipe(critical({
base: 'dist/',
inline: true,
css: ['dist/app.css']
}))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function() {
return gulp.src(config.images)
.pipe(gulp.dest('dist/images'))
.pipe(livereload());
});
gulp.task('assets', function() {
return gulp.src(config.assets)
.pipe(gulp.dest('dist/assets'))
.pipe(livereload());
});
gulp.task('fixtures', function() {
return gulp.src(config.fixtures)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('clean-html-tmp', function () {
return del(['dist/tmp-**']);
});
gulp.task('clean-dist', function () {
return del(['dist/**']);
});
};
|
/** @license ISC License (c) copyright 2017 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
const Pair = require('../core/types').proxy('Pair')
const isFoldable = require('../core/isFoldable')
const isSameType = require('../core/isSameType')
const isString = require('../core/isString')
function foldPairs(acc, pair) {
if(!isSameType(Pair, pair)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
const key = pair.fst()
const value = pair.snd()
if(!isString(key)) {
throw new TypeError('fromPairs: String required for fst of every Pair')
}
return value !== undefined
? Object.assign(acc, { [key]: value })
: acc
}
/** fromPairs :: Foldable f => f (Pair String a) -> Object */
function fromPairs(xs) {
if(!isFoldable(xs)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
return xs.reduce(foldPairs, {})
}
module.exports = fromPairs
|
var fs = require('fs');
var tapOut = require('tap-out');
var through = require('through2');
var duplexer = require('duplexer');
var format = require('chalk');
var prettyMs = require('pretty-ms');
var _ = require('lodash');
var repeat = require('repeat-string');
var symbols = require('./lib/utils/symbols');
var lTrimList = require('./lib/utils/l-trim-list');
module.exports = function (spec) {
spec = spec || {};
// TODO: document
var OUTPUT_PADDING = spec.padding || ' ';
var output = through();
var parser = tapOut();
var stream = duplexer(parser, output);
var startTime = new Date().getTime();
output.push('\n');
parser.on('test', function (test) {
output.push('\n' + pad(test.name) + '\n\n');
});
// Passing assertions
parser.on('pass', function (assertion) {
var glyph = format.green(symbols.ok);
var name = format.dim(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
});
// Failing assertions
parser.on('fail', function (assertion) {
var glyph = format.red(symbols.err);
var name = format.red.bold(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
stream.failed = true;
});
// All done
parser.on('output', function (results) {
output.push('\n\n');
if (results.fail.length > 0) {
output.push(formatErrors(results));
output.push('\n');
}
output.push(formatTotals(results));
output.push('\n\n\n');
});
// Utils
function formatErrors (results) {
var failCount = results.fail.length;
var past = (failCount === 1) ? 'was' : 'were';
var plural = (failCount === 1) ? 'failure' : 'failures';
var out = '\n' + pad(format.red.bold('Failed Tests:') + ' There ' + past + ' ' + format.red.bold(failCount) + ' ' + plural + '\n');
out += formatFailedAssertions(results);
return out;
}
function formatTotals (results) {
return _.filter([
pad('total: ' + results.asserts.length),
pad(format.green('passing: ' + results.pass.length)),
results.fail.length > 0 ? pad(format.red('failing: ' + results.fail.length)) : null,
pad('duration: ' + prettyMs(new Date().getTime() - startTime)) // TODO: actually calculate this
], _.identity).join('\n');
}
function formatFailedAssertions (results) {
var out = '';
var groupedAssertions = _.groupBy(results.fail, function (assertion) {
return assertion.test;
});
_.each(groupedAssertions, function (assertions, testNumber) {
// Wrie failed assertion's test name
var test = _.find(results.tests, {number: parseInt(testNumber)});
out += '\n' + pad(' ' + test.name + '\n\n');
// Write failed assertion
_.each(assertions, function (assertion) {
out += pad(' ' + format.red(symbols.err) + ' ' + format.red(assertion.name)) + '\n';
out += formatFailedAssertionDetail(assertion) + '\n';
});
});
return out;
}
function formatFailedAssertionDetail (assertion) {
var out = '';
var filepath = assertion.error.at.file;
var contents = fs.readFileSync(filepath).toString().split('\n');
var line = contents[assertion.error.at.line - 1];
var previousLine = contents[assertion.error.at.line - 2];
var nextLine = contents[assertion.error.at.line];
var lineNumber = parseInt(assertion.error.at.line);
var previousLineNumber = parseInt(assertion.error.at.line) - 1;
var nextLineNumber = parseInt(assertion.error.at.line) + 1;
var lines = lTrimList([
line,
previousLine,
nextLine
]);
var atCharacterPadding = parseInt(assertion.error.at.character) + parseInt(lineNumber.toString().length) + 2;
out += pad(' ' + format.dim(filepath)) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('v') + "\n");
out += pad(' ' + format.dim(previousLineNumber + '. ' + lines[1])) + '\n';
out += pad(' ' + lineNumber + '. ' + lines[0]) + '\n';
out += pad(' ' + format.dim(nextLineNumber + '. ' + lines[2])) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('^') + "\n");
return out;
}
function pad (str) {
return OUTPUT_PADDING + str;
}
return stream;
};
|
/*jshint esnext: true */
let plugins;
export default class DevicePlugin {
constructor(_plugins) {
plugins = _plugins;
plugins.registerCommand('Device', 'getDeviceInfo', this.getDeviceInfo);
}
getDeviceInfo(sender) {
return {
platform: sender.device.preset.platform,
version: sender.device.preset.platformVersion,
uuid: sender.device.uuid,
model: sender.device.preset.model
};
}
}
DevicePlugin.$inject = ['plugins'];
|
/**
* Created by larus on 15/2/9.
*/
angular.module('myApp').directive('taginput', function () {
return {
restrict: 'E',
template: '<input name="{{name}}" class="tagsinput tagsinput-primary" ng-value="values" />',
replace: true,
scope: {
tags: '=',
name: '@',
id: '@'
},
link: function ($scope, element, attrs) {
$scope.name = attrs.name;
$scope.id = attrs.id;
$scope.$watch('tags', function (value) {
if (!value)
value = [];
$scope.values = value;
element.tagsInput(value.toString());
});
element.tagsInput({
onAddTag: function (value) {
$scope.values.push(value);
$scope.$apply(function () {
$scope.tags = $scope.values;
});
}
});
},
controller: function ($scope) {
}
}
});
|
/* eslint-disable consistent-this */
var cscript = require('../lib/cscript.js')
describe('cscript', function() {
var mockFs, mockExecFile
it('must be initialized', function() {
(function() {
cscript.path()
}).should.throw('must initialize first')
})
it('if cscript.exe is successfully spawned then no more checks are conducted', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['cscript.exe'].args[0].should.eql('cscript.exe')
done()
})
})
it('initializes only once', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(0)
done()
})
})
})
it('if cscript.exe fails to execute, try to run "where cscript.exe"', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['where cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].err = new Error()
mockExecFile['cscript.exe'].err.code = 'ENOENT'
mockExecFile['where cscript.exe'].stdout = '123'
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(1)
cscript.path().should.eql('123')
done()
})
})
beforeEach(function() {
mockFs = {
err: null,
calls: 0,
stat: function(name, cb) {
this.calls++
var self = this
setImmediate(function() {
cb(self.err, {})
})
},
}
mockExecFile = function(command, args, options, callback) {
if (!mockExecFile[command]) {
throw new Error('unexpected command ' + command)
}
mockExecFile[command].args = arguments
mockExecFile[command].calls++
if (typeof args === 'function') {
callback = args
args = undefined
options = undefined
}
if (typeof options === 'function') {
callback = options
args = undefined
options = undefined
}
if (typeof callback !== 'function') {
throw new Error('missing callback')
}
setImmediate(function() {
callback(mockExecFile[command].err, mockExecFile[command].stdout, mockExecFile[command].stderr)
})
}
mockExecFile['cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
mockExecFile['where cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
cscript._mock(mockFs, mockExecFile, false)
})
afterEach(function() {
cscript._mockReset()
})
})
|
var SpecHelper = function(){};
|
var add = function( part ){
this._value.push(part);
}
var resolved = function( is ){
if( undefined === is ) return this._resolved;
this._resolved = !!is;
return this._resolved;
}
var getValue = function(){
return this._value;
}
var setValue = function( value ){
this._value = value;
}
var Wildcard = function(){
_oop(this,"Espresso/Bag/Resolver/Wildcard");
this._value = [];
this._resolved = false;
this._parent;
}
Wildcard.prototype.add = add;
Wildcard.prototype.resolved = resolved;
Wildcard.prototype.getValue = getValue;
Wildcard.prototype.setValue = setValue;
module.exports = Wildcard;
|
// var knexConfig = require('../knexfile')
// var knex = require('knex')(knexConfig[process.env.NODE_ENV || "development"])
var knex = require('./knexOrigin')
module.exports = {
createEvent: (eventObj, cb) => {
knex('events').insert(eventObj)
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
},
getEventById: (eventId, cb) => {
knex.select().where("id", eventId).table("events")
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
},
getEventsByHostId: (userId, cb) => {
knex('hosts').select()
.join('events', 'hosts.eventId', '=', 'events.id')
.where('hosts.userId', userId)
.then( (data) => cb(null, data) )
.catch( (err) => cb(err) )
},
getEventsByGuestId: (userId, cb) => {
knex('guests').select()
.join('events', 'guests.eventId', '=', 'events.id')
.where('guests.userId', userId)
.then( (data) => cb(null, data) )
.catch( (err) => cb(err) )
},
updateEvent: (eventId, eventChanges, cb) => {
knex('events').update(eventChanges).where('id', eventId)
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
}
}
|
(function ($) {
"use strict";
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false
, init: function () {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
submitButton.addEventListener("click", function () {
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function () {
// Show submit button here and/or inform user to click it.
});
}
};
})(jQuery);
|
// @flow
/* eslint-disable */
import {
periodic,
now,
merge,
never,
newStream,
propagateEventTask
} from '@most/core'
import {disposeBoth, disposeWith} from '@most/disposable'
import {newDefaultScheduler, asap} from '@most/scheduler'
import M from '../m'
import tree from './element'
import type {Pith} from '../vtree/rvnode'
import Counter1 from '../piths/counter1'
import Counter2 from '../piths/counter2'
const elm = document.getElementById('root-node')
if (!elm) throw new Error()
const count = () =>
M.of(periodic(1000))
.scan(a => a + 1, 0)
.skip(1)
.map(i => 'h' + i)
.take(10)
.continueWith(count)
.valueOf()
const ring = pith => pith // (put, on) => pith({...put}, on)
const rez = tree(elm)(Test())
const disposable = M.of(rez).$.run(
{
event: (t, e) => {},
end: t => {},
error: (t, err) => {}
},
newDefaultScheduler()
)
setTimeout(disposable.dispose.bind(disposable), 20000)
function Test() {
return ring((put, on) => {
function f(vnode, cb) {
if (f.patchedNodes.has(vnode)) return
const listener = () => console.log('patch', vnode)
vnode.node.addEventListener('click', listener)
console.log('addEventListener')
f.patchedNodes.set(vnode, () => {
console.log('removeEventListener')
vnode.node.removeEventListener('click', listener)
})
}
f.patchedNodes = new Map()
put.put(
newStream((sink, scheduler) => {
console.log('sink')
return disposeBoth(
asap(propagateEventTask(f, sink), scheduler),
disposeWith(() => {
f.patchedNodes.forEach(d => d())
f.patchedNodes.clear()
}, null)
)
})
)
// put.text('text')
put.node('div')(put => {
put.node('button', {on: {click: 'a'}})(put => put.text('a'))
put.node('button', {on: {click: 'b'}})(put => put.text('b'))
put.node('button', {on: {click: 'o'}})(put => put.text('o'))
})
put.node('h4')(put => put.text(count()))
put.node('div', {}, 'key')(
M.of(on)
.filter(x => typeof x.action === 'string')
.map(x => {
if (x.action === 'a') return Counter1(0)
if (x.action === 'b') return Counter1(1)
return Counter2(1)
})
.startWith(put => put.node('h1')(put => put.text('select')))
.tap(pith => console.timeStamp(pith.toString()))
.valueOf()
)
})
}
function C(): Pith {
return (put, on) => {
put.node('button', {on: {click: 'A'}})(put => {
put.text('A')
})
put.text(
M.of(on)
.map(x => x.action)
.startWith('')
.valueOf()
)
}
}
|
var socket; //socket.io (live engine)
//Variable is set by server later on
var position = {
x: 1,
y: 1
};
var heading; // direction of player
var nameSize = 18; // size of the name label
//Variable is set by server later on
var worldDimensions = {
x: 1,
y: 1
};
var inPlay = false; //whether you have started playing
var currFrameNum = 0;
var prevTimeOfFrame = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
//Load the skins into the array
for (var path in playerImageOptions) {
playerImages.push(loadImage("sprites/players/" + playerImageOptions[path]))
}
imageMode(CENTER)
}
//receive world dimensions from the server
function setWorldDimensions(wd) {
worldDimensions = wd;
}
//reload the page when you die
function iDied() {
location.reload();
}
//draw the grid background
function drawGrid(sqrWidth, border) {
strokeWeight(border);
stroke(25);
for (var x = 0; x < worldDimensions.x - 1; x += (sqrWidth + border)) {
line(x, 0, x, worldDimensions.y);
}
for (var y = 0; y < worldDimensions.y - 1; y += (sqrWidth + border)) {
line(0, y, worldDimensions.x, y);
}
}
//Display the world
function worldUpdate(bodies) {
background(30);
displayBodies(bodies);
}
function displayBodies(bodies) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
//Check if the body is a player
if (body.label === 'player') {
//Draw the player image
if (body.socketID === socket.id) {
translate(-body.position.x + width / 2, -body.position.y + height / 2);
break;
}
}
}
drawGrid(60, 20);
//Loop through all the bodies in the world
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
//Check if the body is a player
if (body.label === 'player') {
//Draw the player image
push();
translate(body.position.x, body.position.y);
rotate(body.angle);
image(playerImages[body.skinID], 0, 0);
pop();
//Write number of bullets if it is the current player
var bodyColor = color(body.render.fillStyle);
fill(color(255 - red(bodyColor), 255 - green(bodyColor), 255 - blue(bodyColor)));
textSize(nameSize);
text(body.numOfBullets, body.position.x - textWidth(body.numOfBullets) / 2, body.position.y - 60)
text(body.name, body.position.x - textWidth(body.name) / 2, body.position.y)
//Draw the health bar
var barSize = body.maxHealth / 2;
fill(255, 0, 0);
rect(body.position.x - barSize / 2, body.position.y - 45, barSize, 10);
fill(0, 255, 0);
rect(body.position.x - barSize / 2, body.position.y - 45, barSize * body.health / body.maxHealth, 10)
} else {
//Draw shape from its vertices
strokeWeight(body.render.lineWidth);
fill(body.render.fillStyle);
stroke(body.render.strokeStyle);
var vertices;
push();
if (typeof(body.vertices) === 'string') {
translate(body.position.x, body.position.y);
rotate(body.angle);
vertices = objectVertices[body.vertices];
} else {
vertices = body.vertices
}
beginShape();
for (var j = 0; j < vertices.length; j++) {
var v = vertices[j];
vertex(v.x, v.y);
}
endShape(CLOSE);
pop();
}
}
}
function draw() {
if (inPlay) {
heading = {
x: (mouseX - width / 2),
y: (mouseY - height / 2)
};
heading = getUnitVector(heading);
socket.emit('heading', heading)
} else {
var padding = 0;
var imageSize = (width - padding * (playerImages.length - 1)) / playerImages.length;
for (var i = 0; i < playerImages.length; i++) {
push();
translate(i * (imageSize + padding) + imageSize / 2, imageSize / 2);
rotate(Math.PI / 2);
image(playerImages[i], 0, 0, imageSize, imageSize);
pop();
}
}
}
function getUnitVector(v) {
var scale = Math.sqrt(v.x * v.x + v.y * v.y);
if (scale !== 0) {
v.x = v.x / scale;
v.y = v.y / scale
}
return v;
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight)
}
function keyReleased() {
if (key === ' ') {
socket.emit('newBullet')
}
if (key === 'B') {
var bombParams = getBombParams();
try {
if ((bombParams.bullets > 0)) {
socket.emit('newBomb', bombParams.bullets, bombParams.trigger, bombParams.visible)
}
} catch (e) {
}
}
if (key === 'S' && inPlay) {
toggleBombSelector();
}
}
|
// Thai
jQuery.timeago.settings.strings = {
prefixAgo : null,
prefixFromNow: null,
suffixAgo : "ที่แล้ว",
suffixFromNow: "จากตอนนี้",
seconds : "น้อยกว่าหนึ่งนาที",
minute : "ประมาณหนึ่งนาที",
minutes : "%d นาที",
hour : "ประมาณหนึ่งชั่วโมง",
hours : "ประมาณ %d ชั่วโมง",
day : "หนึ่งวัน",
days : "%d วัน",
month : "ประมาณหนึ่งเดือน",
months : "%d เดือน",
year : "ประมาณหนึ่งปี",
years : "%d ปี",
wordSeparator: "",
numbers : []
};
|
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-handler.js'
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const name = Name.toLowerCase();
function AboutHandler() {}
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) {
let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newChannel("chrome://" + name + "/content/about.html", null, null);
channel.originalURI = uri;
return channel;
},
getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler])
// vim: set fdm=marker sw=4 ts=4 et:
|
export default Ember.ObjectController.extend({
actions: {
cancel: function() {
this.transitionToRoute('books');
}
}
});
|
////////////////////////////////////////////////
/* Provided Code - Please Don't Edit */
////////////////////////////////////////////////
'use strict';
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.")
return prompt();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
} else if (randomNumber < 0.66) {
return "paper";
} else {
return "scissors";
}
}
////////////////////////////////////////////////
/* Write Your Code Below */
////////////////////////////////////////////////
function getPlayerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `getInput()`.
return move || getInput();
}
function getComputerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
return move || randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
// Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
// Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
// The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
if (playerMove === computerMove){
winner = 'tie';
} else if(playerMove === 'rock' && computerMove === 'scissors'){
winner = 'player';
} else if(playerMove === 'scissors' && computerMove === 'rock'){
winner = 'computer';
} else if(playerMove === 'paper' && computerMove === 'rock'){
winner = 'player';
} else if(playerMove === 'rock' && computerMove === 'paper'){
winner = 'computer';
} else if(playerMove === 'paper' && computerMove === 'scissors'){
winner = 'computer';
} else if(playerMove === 'scissors' && computerMove === 'paper'){
winner = 'player';
}
return winner;
}
function playToFive() {
console.log("Let's play Rock, Paper, Scissors");
var playerWins = 0;
var computerWins = 0;
// Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
/* YOUR CODE HERE */
while (playerWins < 5 && computerWins < 5) {
var playerMove = getPlayerMove();
var computerMove = getComputerMove();
var winner = getWinner(playerMove,computerMove);
if (winner === 'player') {
playerWins += 1;
} else if ( winner === 'computer') {
computerWins += 1;
} else { playerWins += 0;
computerWins += 0;
console.log("It's a tie!")
}
console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
console.log('The score is currently ' + playerWins + ' to ' + computerWins);
}
if (playerWins > computerWins) {
console.log('Player won! Congrats!')
}
else {
console.log('Computer won....Game Over!')
}
}
//call function
playToFive();
|
var express = require('express'),
server = express();
server.use('/', express.static(__dirname + '/public'));
server.use('/shaders', express.static(__dirname + '/lessons/shaders'));
server.use('/assets', express.static(__dirname + '/lessons/assets'));
server.listen(9000);
console.log('Listening on port 9000');
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
name: { type: String, required: true },
position: { type: String },
marketValue: { type: Number },
jerseyNumber: { type: Number },
dateOfBirth: { type: Date },
contractedUntil: { type: Date },
club_id: { type: Schema.Types.ObjectId, ref: 'Club' },
nation_name: { type: String, ref: 'Nation' },
attributes: {
physical: {
Acceleration: { type: Number },
Agility: { type: Number },
Balance: { type: Number },
JumpingReach: { type: Number },
NaturalFitness: { type: Number },
Pace: { type: Number },
Stamina: { type: Number },
Strength: { type: Number },
GoalkeeperRating:{ type: Number }
},
mental: {
Aggression: { type: Number },
Anticipation: { type: Number },
Bravery: { type: Number },
Composure: { type: Number },
Concentration: { type: Number },
Decision: { type: Number },
Determination: { type: Number },
Flair: { type: Number },
Leadership: { type: Number },
OfftheBall: { type: Number },
Positioning: { type: Number },
Teamwork: { type: Number },
Vision: { type: Number },
WorkRate:{ type: Number }
},
technical: {
Crossing: { type: Number },
Dribbling: { type: Number },
Finishing: { type: Number },
FirstTouch: { type: Number },
FreeKickTaking: { type: Number },
Heading: { type: Number },
LongShots: { type: Number },
LongThrows: { type: Number },
Marking: { type: Number },
Passing: { type: Number },
PenaltyTaking: { type: Number },
Tackling: { type: Number },
Technique:{ type: Number }
}
}
})
module.exports = mongoose.model('Player', schema);
|
"use strict";
const filterable = require("@lerna/filter-options");
/**
* @see https://github.com/yargs/yargs/blob/master/docs/advanced.md#providing-a-command-module
*/
exports.command = "bootstrap";
exports.describe = "Link local packages together and install remaining package dependencies";
exports.builder = yargs => {
yargs
.example(
"$0 bootstrap -- --no-optional",
"# execute `npm install --no-optional` in bootstrapped packages"
)
.parserConfiguration({
"populate--": true,
})
.options({
hoist: {
group: "Command Options:",
describe: "Install external dependencies matching [glob] to the repo root",
defaultDescription: "'**'",
},
nohoist: {
group: "Command Options:",
describe: "Don't hoist external dependencies matching [glob] to the repo root",
type: "string",
requiresArg: true,
},
mutex: {
hidden: true,
// untyped and hidden on purpose
},
"ignore-prepublish": {
group: "Command Options:",
describe: "Don't run prepublish lifecycle scripts in bootstrapped packages.",
type: "boolean",
},
"ignore-scripts": {
group: "Command Options:",
describe: "Don't run _any_ lifecycle scripts in bootstrapped packages",
type: "boolean",
},
"npm-client": {
group: "Command Options:",
describe: "Executable used to install dependencies (npm, yarn, pnpm, ...)",
type: "string",
requiresArg: true,
},
registry: {
group: "Command Options:",
describe: "Use the specified registry for all npm client operations.",
type: "string",
requiresArg: true,
},
strict: {
group: "Command Options:",
describe: "Don't allow warnings when hoisting as it causes longer bootstrap times and other issues.",
type: "boolean",
},
"use-workspaces": {
group: "Command Options:",
describe: "Enable integration with Yarn workspaces.",
type: "boolean",
},
"force-local": {
group: "Command Options:",
describe: "Force local sibling links regardless of version range match",
type: "boolean",
},
contents: {
group: "Command Options:",
describe: "Subdirectory to use as the source of any links. Must apply to ALL packages.",
type: "string",
defaultDescription: ".",
},
});
return filterable(yargs);
};
exports.handler = function handler(argv) {
return require(".")(argv);
};
|
if ( true ) import { a as x } from "./abc";
if ( false ) import { b as y } from "./abc";
if ( true ) export function outer() {
import { a as ay } from "./abc";
import { b as bee } from "./abc";
import { c as see } from "./abc";
return [ ay, bee, see ];
}
if ( false ) export { x } from "./foo";
x; // Stay as x
y; // Stay as y
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
maxWidth: '450px'
},
container: {
marginTop: '10px'
},
}
class Login extends Component {
constructor(props) {
super(props)
this.state = {
username: "",
password: "",
isLoading: false
}
}
handleUserChange(e) {
this.setState({
user: e.target.value
});
}
handlePasswordChange(e) {
this.setState({
password: e.target.value
});
}
toggleLoading() {
this.setState({
isLoading: !this.state.isLoading
});
}
handleSubmit() {
this.toggleLoading();
this.props.login(this.state.user, this.state.password,(err,data)=>{
if(err) {
this.toggleLoading();
alert(data.msg);
} else {
this.props.history.push("/dashboard");
}
});
}
handleKeyPress = (e) =>
{
console.log('Key pressed.');
if(e.key === 'Enter')
{
this.handleSubmit();
}
}
componentWillMount() {
document.title = "Login";
}
renderLogin() {
return (
<div style={styles.loginForm}>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={styles.segment}>
<Segment raised onKeyPress={this.handleKeyPress}>
<Header as='h2' color='teal' textAlign='center'>
Log-in to your account
</Header>
<Input
onChange={this.handleUserChange.bind(this)}
value={this.state.user}
fluid
icon='user'
iconPosition='left'
placeholder='Enter your username' />
<br />
<Input
onChange={this.handlePasswordChange.bind(this)}
value={this.state.password}
fluid
type='password'
icon='lock'
iconPosition='left'
placeholder='Enter your password' />
<Container textAlign='right' style={styles.container}>
<Button animated loading={this.state.isLoading} color='teal' onClick={this.handleSubmit.bind(this)}>
<Button.Content visible>Login</Button.Content>
<Button.Content hidden>
<Icon name='right arrow'/>
</Button.Content>
</Button>
</Container>
</Segment>
</Grid.Column>
</Grid>
</div>
)
}
render() {
return (
<div style={styles.loginForm}>
{this.renderLogin()}
</div>
)
}
}
function mapStateToProps({ auth }) {
return { auth }
}
export default connect(mapStateToProps, actions)(Login);
|
const jsonfile = require('jsonfile')
const stats = require("stats-lite");
const commandLineArgs = require("command-line-args");
const mqtt = require("mqtt");
const stringify = require("csv-stringify");
const fs = require("fs");
const client = mqtt.connect("mqtt://127.0.0.1:1883");
const options = commandLineArgs([
{ name: "sub_qos", type: Number },
{ name: "file", type: String, multiple: false, defaultOption: true }
]);
if (!options.file || options.sub_qos === undefined) {
console.error("You must specify --sub_qos and provide file for dump!");
process.exit(1)
}
let devices = {};
client.on("connect", () => {
client.subscribe("qos_testing/#", {
qos: options.sub_qos
});
});
client.on("message", (topic, message) => {
const device = topic.split("/")[1];
const i = parseInt(message.toString());
const ts = process.hrtime();
if(!devices[device]) {
devices[device] = {
last_i: i,
last_timestamp: ts,
messages: [ [Date.now(), i] ],
intervals: [],
seen: [],
duplicates: [],
out_of_order: []
}
} else {
let diff = process.hrtime(devices[device].last_timestamp);
diff = diff[0]*1000 + diff[1]/1000000.0;
devices[device].intervals.push(diff);
if (devices[device].seen.indexOf(i) > -1) {
devices[device].duplicates.push([Date.now(), i]);
} else if (devices[device].last_i >= i) {
devices[device].out_of_order.push([Date.now(), i]);
}
devices[device].last_i = i;
devices[device].seen.push(i);
devices[device].last_timestamp = ts;
devices[device].messages.push([Date.now(), i]);
}
});
setInterval(function() {
Object.keys(devices).forEach((device) => {
let d = devices[device];
let last_1k = d.intervals.slice(Math.max(0, d.intervals.length - 1000));
console.log("=====");
console.log("Status for device #" + device + " (stats for last 1k msgs)");
console.log("Msgs rcvd:", d.messages.length);
console.log("i:", d.last_i);
console.log("Mean interval:", stats.mean(last_1k));
console.log("stddev interval:", stats.stdev(last_1k));
console.log("95th percentile interval:", stats.percentile(last_1k, 0.95));
console.log("max interval:", Math.max(...last_1k));
console.log("number of duplicates:", d.duplicates.length);
console.log("number of out_of_order:", d.out_of_order.length);
});
}, 2000);
function dump(reason, add) {
console.log("Dumping state to " + options.file + ".json and " + options.file + "_intervals.csv");
jsonfile.writeFileSync(options.file + ".json", devices);
stringify([].concat.apply([], Object.keys(devices).map((device) => {
return devices[device].intervals.map((int) => {
return [device, int];
});
})), (err, out) => {
console.log(err);
fs.writeFileSync(options.file + "_intervals.csv", out);
console.log("Try running octave-cli --eval=\"hist(csvread('"+options.file+"_intervals.csv')(:,2), 25)\" --persist");
if(reason) {
console.log("Quiting because:", reason);
if(reason == "EXCEPTION") {
console.log(add);
}
process.exit();
}
});
}
process.on("SIGINT", dump.bind(null, "SIGINT"));
process.on("SIGHUP", dump.bind(null, false));
process.on("uncaughtException", dump.bind(null, "EXCEPTION"));
|
version https://git-lfs.github.com/spec/v1
oid sha256:7532f5b4891e60d75d6a1d91f80921a3ad8b96ba88a746f05948fc6c6f5a9772
size 137987
|
import style from './style';
const s = Object.create(style);
s.root = {
fontFamily: 'helvetica, sans-serif',
fontWeight: '300',
fontSize: '16px',
letterSpacing: '0.025em',
padding: '3vh 0 12vh 0',
width: '500px',
// use responsive max-width to simulate padding/margin to allow
// space for vertical scroll bar without creating horizontal scroll bar
// (if there is padding, the window will scroll horizontally to show the padding)
maxWidth: 'calc(100vw - 40px)',
// center based on vw to prevent content jump when vertical scroll bar show/hide
// note: vw/vh include the width of scroll bars. Note that centering using margin auto
// or % (which doesn't include scroll bars, so changes when scroll bars shown) causes a page jump
position: 'relative',
left: '50vw',
WebkitTransform: 'translate(-50%, 0)',
MozTransform: 'translate(-50%, 0)',
msTransform: 'translate(-50%, 0)',
OTransform: 'translate(-50%, 0)',
transform: 'translate(-50%, 0)',
WebkitTextSizeAdjust: 'none',
MozTextSizeAdjust: 'none',
msTextSizeAdjust: 'none',
textSizeAdjust: 'none',
};
s.title = {
fontSize: '20px',
marginBottom: '0.5vh',
};
s.repoLink = {
fontSize: '14px',
};
s.breadcrumbs = {
margin: '3vh 0',
};
s.creditLine = {
color: '#A0A0A0',
fontSize: '14px',
marginTop: '50px',
};
s.App = {
textAlign: 'center',
backgroundColor: '#F7F0F0',
};
s.Appheader = {
backgroundColor: '#18A999',
height: 'auto',
padding: '20px',
color: '#484349',
};
s.button = {
backgroundColor: '#18a999',
borderRadius: '10px',
color: '#F7F0F0',
display: 'inline-block',
marginBottom: '5px',
padding: '10px 10px',
textDecoration: 'none',
};
s.Links = {
paddingTop: '20px',
};
s.Icons = {
paddingLeft: '5px',
paddingRight: '5px',
color: '#484349',
};
export default s;
|
'use strict';
module.exports = {
SET_COUNTRY: function(state, value) {
state.countryCode = value;
},
SET_PERIOD: function(state, value) {
state.period = value;
}
};
|
var app = angular.module('Zespol', []);
//Filtr umożliwiający wstawienie scope jako link url
app.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}]);
app.controller('MusicCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/music.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.mysrctest = "http://tolmax.type.pl/uploads/music/01.Rehab.mp3";
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
//Filtr zamieniajacy podłogi na spacje dla bezpieczenstwa bazy danych mtitle przechowuje nazwy z podłogami
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i].replace(/_/g, " ");
txt += c;
}
return txt;
};
});
/////////
app.controller('VideoCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/video.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
app.controller('PhotosCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/photos.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
|
'use strict';
/* istanbul ignore next */
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('hashes', {
h1: {
allowNull: false,
primaryKey: true,
type: Sequelize.STRING(128),
},
s2: {
allowNull: false,
type: Sequelize.STRING(64),
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('hashes');
},
};
|
import React from 'react';
import { assert } from 'chai';
import {
createMount,
createShallow,
describeConformance,
getClasses,
} from '@material-ui/core/test-utils';
import DialogTitle from './DialogTitle';
describe('<DialogTitle />', () => {
let mount;
let shallow;
let classes;
before(() => {
mount = createMount({ strict: true });
shallow = createShallow({ dive: true });
classes = getClasses(<DialogTitle>foo</DialogTitle>);
});
after(() => {
mount.cleanUp();
});
describeConformance(<DialogTitle>foo</DialogTitle>, () => ({
classes,
inheritComponent: 'div',
mount,
refInstanceof: window.HTMLDivElement,
skip: ['componentProp'],
}));
it('should render JSX children', () => {
const children = <p className="test">Hello</p>;
const wrapper = shallow(<DialogTitle disableTypography>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).equals(children), true);
});
it('should render string children as given string', () => {
const children = 'Hello';
const wrapper = shallow(<DialogTitle>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).props().children, children);
});
});
|
var a = require('./a');
exports.value = 3;
|
export function threePointSecondDerivative(previous, current, next, uniformDistance) {
return (next - 2 * current + previous) / (uniformDistance * uniformDistance);
}
|
function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
}
if (typeof value === 'boolean') {
return '__q_bool|' + (value ? '1' : '0')
}
if (typeof value === 'string') {
return '__q_strn|' + value
}
if (typeof value === 'function') {
return '__q_strn|' + value.toString()
}
if (value === Object(value)) {
return '__q_objt|' + JSON.stringify(value)
}
// hmm, we don't know what to do with it,
// so just return it as is
return value
}
function decode (value) {
let type, length, source
length = value.length
if (length < 10) {
// then it wasn't encoded by us
return value
}
type = value.substr(0, 8)
source = value.substring(9)
switch (type) {
case '__q_date':
return new Date(source)
case '__q_expr':
return new RegExp(source)
case '__q_numb':
return Number(source)
case '__q_bool':
return Boolean(source === '1')
case '__q_strn':
return '' + source
case '__q_objt':
return JSON.parse(source)
default:
// hmm, we reached here, we don't know the type,
// then it means it wasn't encoded by us, so just
// return whatever value it is
return value
}
}
function generateFunctions (fn) {
return {
local: fn('local'),
session: fn('session')
}
}
let
hasStorageItem = generateFunctions(
(type) => (key) => window[type + 'Storage'].getItem(key) !== null
),
getStorageLength = generateFunctions(
(type) => () => window[type + 'Storage'].length
),
getStorageItem = generateFunctions((type) => {
let
hasFn = hasStorageItem[type],
storage = window[type + 'Storage']
return (key) => {
if (hasFn(key)) {
return decode(storage.getItem(key))
}
return null
}
}),
getStorageAtIndex = generateFunctions((type) => {
let
lengthFn = getStorageLength[type],
getItemFn = getStorageItem[type],
storage = window[type + 'Storage']
return (index) => {
if (index < lengthFn()) {
return getItemFn(storage.key(index))
}
}
}),
getAllStorageItems = generateFunctions((type) => {
let
lengthFn = getStorageLength[type],
storage = window[type + 'Storage'],
getItemFn = getStorageItem[type]
return () => {
let
result = {},
key,
length = lengthFn()
for (let i = 0; i < length; i++) {
key = storage.key(i)
result[key] = getItemFn(key)
}
return result
}
}),
setStorageItem = generateFunctions((type) => {
let storage = window[type + 'Storage']
return (key, value) => { storage.setItem(key, encode(value)) }
}),
removeStorageItem = generateFunctions((type) => {
let storage = window[type + 'Storage']
return (key) => { storage.removeItem(key) }
}),
clearStorage = generateFunctions((type) => {
let storage = window[type + 'Storage']
return () => { storage.clear() }
}),
storageIsEmpty = generateFunctions((type) => {
let getLengthFn = getStorageLength[type]
return () => getLengthFn() === 0
})
export var LocalStorage = {
has: hasStorageItem.local,
get: {
length: getStorageLength.local,
item: getStorageItem.local,
index: getStorageAtIndex.local,
all: getAllStorageItems.local
},
set: setStorageItem.local,
remove: removeStorageItem.local,
clear: clearStorage.local,
isEmpty: storageIsEmpty.local
}
export var SessionStorage = { // eslint-disable-line one-var
has: hasStorageItem.session,
get: {
length: getStorageLength.session,
item: getStorageItem.session,
index: getStorageAtIndex.session,
all: getAllStorageItems.session
},
set: setStorageItem.session,
remove: removeStorageItem.session,
clear: clearStorage.session,
isEmpty: storageIsEmpty.session
}
|
import { themr } from 'react-css-themr';
import { PAGER } from '../identifiers.js';
import { pagerFactory } from './pager.js';
import Page from './page.js';
import theme from './theme.scss';
const Pager = pagerFactory(Page);
const ThemedPager = themr(PAGER, theme)(Pager);
export default ThemedPager;
export { ThemedPager as Pager };
|
import {LEAGUE_BY_SUMMONER_FULL, LEAGUE_BY_SUMMONER, LEAGUE_BY_TEAM_FULL, LEAGUE_BY_TEAM, CHALLENGER_LEAGUE} from '../Constants';
export const League = {
getBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER_FULL
});
},
getEntriesBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER
});
},
getByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM_FULL
});
},
getEntriesByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM
});
},
getChallenger(type, options) {
return Object.assign({}, options, {
uri: CHALLENGER_LEAGUE,
query: {
type: type || 'RANKED_SOLO_5x5'
}
});
}
};
|
import { combineReducers } from 'redux';
import todos from './todos';
import filter from './filter';
import editing from './editing';
const rootReducer = combineReducers({
todos,
filter,
editing,
});
export default rootReducer;
|
'use strict';
var User = require('./user.model.js');
var config = require('../config');
var request = require('request');
var jwt = require('jwt-simple');
var authUtils = require('./authUtils');
exports.authenticate = function (req, res) {
var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';
var peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
var params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: config.GOOGLE_SECRET,
redirect_uri: req.body.redirectUri,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
request.post(accessTokenUrl, { json: true, form: params }, function(err, response, token) {
var accessToken = token.access_token;
var headers = { Authorization: 'Bearer ' + accessToken };
// Step 2. Retrieve profile information about the current user.
request.get({ url: peopleApiUrl, headers: headers, json: true }, function(err, response, profile) {
// Step 3a. Link user accounts.
if (req.headers.authorization) {
User.findOne({ google: profile.sub }, function(err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'There is already a Google account that belongs to you' });
}
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, config.TOKEN_SECRET);
User.findById(payload.sub, function(err, user) {
if (!user) {
return res.status(400).send({ message: 'User not found' });
}
user.google = profile.sub;
user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200');
user.displayName = user.displayName || profile.name;
user.save(function() {
var token = authUtils.createJWT(user);
res.send({ token: token });
});
});
});
} else {
// Step 3b. Create a new user account or return an existing one.
User.findOne({ google: profile.sub }, function(err, existingUser) {
if (existingUser) {
return res.send({ token: authUtils.createJWT(existingUser) });
}
var user = new User();
user.google = profile.sub;
user.picture = profile.picture.replace('sz=50', 'sz=200');
user.displayName = profile.name;
user.save(function(err) {
var token = authUtils.createJWT(user);
res.send({ token: token });
});
});
}
});
});
}
|
import ExtendableError from 'es6-error';
import Client from '../../api/client.js';
export class CoverArtArchiveError extends ExtendableError {
constructor(message, response) {
super(message);
this.response = response;
}
}
export default class CoverArtArchiveClient extends Client {
constructor({
baseURL = process.env.COVER_ART_ARCHIVE_BASE_URL ||
'http://coverartarchive.org/',
limit = 10,
period = 1000,
...options
} = {}) {
super({ baseURL, limit, period, ...options });
}
/**
* Sinfully attempt to parse HTML responses for the error message.
*/
parseErrorMessage(err) {
if (err.name === 'HTTPError') {
const { body } = err.response;
if (typeof body === 'string' && body.startsWith('<!')) {
const heading = /<h1>([^<]+)<\/h1>/i.exec(body);
const message = /<p>([^<]+)<\/p>/i.exec(body);
return new CoverArtArchiveError(
`${heading ? heading[1] + ': ' : ''}${message ? message[1] : ''}`,
err.response
);
}
}
return super.parseErrorMessage(err);
}
images(entityType, mbid) {
return this.get(`${entityType}/${mbid}`, { resolveBodyOnly: true });
}
async imageURL(entityType, mbid, typeOrID = 'front', size) {
let url = `${entityType}/${mbid}/${typeOrID}`;
if (size != null) {
url += `-${size}`;
}
const response = await this.get(url, {
method: 'HEAD',
followRedirect: false,
});
return response.headers.location;
}
}
|
export const listComponent = new Component({
element: "#list",
render: (data) => html`
<li>
<h3>${ data }</h3>
</li>`
})
|
import React, {Component, PropTypes} from 'react';
import {Tree, Menu, Icon} from 'antd';
const TreeNode = Tree.TreeNode;
import Animate from 'rc-animate';
import './OrganizationTreeComponent.scss';
export default class OrganizationTreeComponent extends Component
{
static PropTypes =
{
checkable: PropTypes.bool,
orgs: PropTypes.array,
checkedKeys: PropTypes.array,
setCheckedKeys: PropTypes.func,
setParentId: PropTypes.func,
}
static defaultProps =
{
checkedKeys: []
};
constructor(props)
{
super(props);
}
onCheck = (checkedKeys, info) =>
{
const setCheckedKeys = this.props.setCheckedKeys;
if(setCheckedKeys)
{
setCheckedKeys(checkedKeys);
}
}
onSelect = (selectedKeys, info) =>
{
const setParentId = this.props.setParentId;
if(setParentId)
{
const parentId = selectedKeys[0];
setParentId(parentId);
}
}
genTreeNodes(orgs)
{
return orgs.map((org) =>
{
if(org.children && org.children.length)
{
return(
<TreeNode key={org.id} title={org.organizationName}>
{
this.genTreeNodes(org.children)
}
</TreeNode>
);
}
else
{
return(
<TreeNode key={org.id} title={org.organizationName} />
);
}
});
}
render()
{
const orgs = this.props.orgs;
const checkedKeys = this.props.checkedKeys;
return(
<Tree className='orgTree' showLine defaultExpandAll defaultCheckedKeys={checkedKeys} checkable={this.props.checkable} onSelect={this.onSelect} onCheck={this.onCheck}>
{ orgs ? this.genTreeNodes(orgs) : ''}
</Tree>
);
}
}
|
/**
* Created by liumengjun on 2016-04-11.
* 注: 不用于微信端, 微信端自行处理
*/
function showLoading(msg) {
var $loadingDialog = $('#mLoadingDialog');
var $loadingText = $("#mLoadingText");
$loadingText.html(msg ? msg : "");
$loadingDialog.show();
}
function hideLoading() {
$('#mLoadingDialog').hide();
}
var DEFAULT_ERR_MSG = '请求失败, 请稍后重试, 或联系管理员!';
function _malaAjax0(method, url, data, success, dataType, error, loadingMsg) {
if ($.isFunction(data)) {
loadingMsg = error;
error = dataType;
dataType = success;
success = data;
data = undefined;
}
if ($.isFunction(dataType)) {
loadingMsg = error;
error = dataType;
dataType = undefined;
}
showLoading(loadingMsg);
return $.ajax({
url: url,
type: method,
dataType: dataType,
data: data,
success: function (result, textStatus, jqXHR) {
if (typeof(success) === 'function') {
success(result, textStatus, jqXHR);
}
hideLoading();
},
error: function (jqXHR, errorType, errorDesc) {
if (typeof(error) === 'function') {
error(jqXHR, errorType, errorDesc);
}
hideLoading();
}
});
}
function malaAjaxPost(url, data, success, dataType, error, loadingMsg) {
return _malaAjax0('post', url, data, success, dataType, error, loadingMsg);
}
function malaAjaxGet(url, data, success, dataType, error, loadingMsg) {
return _malaAjax0('get', url, data, success, dataType, error, loadingMsg);
}
|
exports.init = function (app) {
var data = [{
name: 'C',
desc: 'old program language',
history: getFakeHistory()
}, {
name: 'Java',
desc: 'large language!',
history: getFakeHistory()
}, {
name: 'C#',
desc: 'Microsoft create it',
history: getFakeHistory()
}, {
name: 'JavaScript',
desc: 'the web language',
history: getFakeHistory()
}]
app.get('/itemList', function(req, res) {
res.send(JSON.stringify(data))
})
app.get('/item/:name', function (req, res) {
var item = data.find(item => item.name === req.params.name)
if (item) {
res.type('json')
res.send(JSON.stringify(item))
} else {
res.status(404).end()
}
})
app.post('/item/:name', function(req, res) {
var item = data.find(item => item.name === req.params.name)
if (item) {
saveItem(item, JSON.parse(res.body))
}
})
app.put('/item/:name', function(req, res) {
var item = findItem(data, req.params.name)
if (item) {
res.status(403).end()
} else {
try {
item = JSON.parse(req.body)
} catch(e) {
console.log('parse req body fail: ' + req.body)
item = {
name: req.params.name
}
}
item.history = getFakeHistory()
data.push(item)
res.send(JSON.stringify(item))
}
})
app.delete('/item/:name', function(req, res) {
var i = data.findIndex(item => item.name === req.params.name)
if (i > -1) {
var item = data.splice(i, 1)
res.send(JSON.stringify(item))
} else {
res.status(404).end()
}
})
}
function findItem(items, name) {
return items && items.find(item => item.name === name)
}
function saveItem(item, data) {
for (let k of data) {
item[k] = data[k]
}
}
function getFakeHistory() {
var nodes = []
if (dice()) nodes.push({name: '1990', desc: 'aaa'})
if (dice()) nodes.push({name: '1991', desc: 'bbb'})
if (dice()) nodes.push({name: '1992', desc: 'ccc'})
if (dice()) nodes.push({name: '1993', desc: 'ddd'})
if (dice()) nodes.push({name: '1994', desc: 'eee'})
if (dice()) nodes.push({name: '1995', desc: 'fff'})
if (dice()) nodes.push({name: '1996', desc: 'ggg'})
if (dice()) nodes.push({name: '1997', desc: 'hhh'})
if (dice()) nodes.push({name: '1998', desc: 'jjj'})
if (dice()) nodes.push({name: '1999', desc: 'kkk'})
if (dice()) nodes.push({name: '2000', desc: 'lll'})
return nodes
}
function dice() {
return Math.random() > 0.5
}
|
var _logFunction = new $NavCogLogFunction();
$(document).ready(function() {
document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile);
});
function $NavCogLogFunction() {
var logLocations = [];
function loadFile(e) {
logLocations = [];
var file = this.files[0];
if (file) {
var fr = new FileReader();
fr.addEventListener("load", function(e) {
parseLogData(fr.result);
});
fr.readAsText(file);
}
}
function parseLogData(text) {
text.split("\n").forEach(function(line, i) {
if (line) {
var params = line.match(/(.*?) (.*?) (.*?) (.*)/);
if (params && params.length == 5) {
var msgs = params[4].split(",");
var obj;
switch (msgs[0]) {
case "FoundCurrentLocation":
obj = {
"edge" : msgs[3],
"x" : msgs[4],
"y" : msgs[5],
"knndist" : msgs[6]
};
break;
case "CurrentPosition":
obj = {
"dist" : msgs[1],
"edge" : msgs[3],
"x" : msgs[4],
"y" : msgs[5],
"knndist" : msgs[6]
};
break;
}
if (obj) {
obj.event = msgs[0];
obj.timestamp = params[1] + " " + params[2];
// console.log(JSON.stringify(obj));
logLocations.push(obj);
}
}
}
});
}
function renderLayer(layer) {
for ( var edgeID in layer.edges) {
drawMarkers(layer.edges[edgeID]);
}
}
function drawMarkers(edge) {
for (var i = 0; i < logLocations.length; i++) {
var log = logLocations[i];
if (log.edge == edge.id) {
var marker = logLocations[i].marker;
if (!marker) {
var node1 = _currentLayer.nodes[edge.node1], node2 = _currentLayer.nodes[edge.node2];
var info1 = node1.infoFromEdges[edge.id], info2 = node2.infoFromEdges[edge.id]
// console.log(log);
// console.log(edge);
// console.log(node1);
// console.log(node1.lat + "," + node1.lng);
// console.log(node2.lat + "," + node2.lng);
// console.log(info1.x + "," + info1.y);
// console.log(info2.x + "," + info2.y);
var ratio = (log.y - info1.y) / (info2.y - info1.y);
var lat = node1.lat + (node2.lat - node1.lat) * ratio;
var lng = node1.lng + (node2.lng - node1.lng) * ratio;
// console.log(ratio + "," + lat + "," + lng);
var title = log.timestamp.substr(17, 2); // i + 1;
var hover = (log.event == "CurrentPosition" ? "Navigation position" : "Current location");
hover += "\n" + log.timestamp;
if (!isNaN(log.dist)) {
hover += "\ndistance: " + log.dist;
}
hover += "\n";
hover += "\npos.x: " + log.x + "\npos.y: " + log.y + "\npos.knndist: " + log.knndist;
hover += "\nnormalized dist: " + ((log.knndist - edge.minKnnDist) / (edge.maxKnnDist - edge.minKnnDist));
hover += "\n";
hover += "\nedge.id: " + edge.id;
hover += "\nedge.minKnnDist: " + edge.minKnnDist;
hover += "\nedge.maxKnnDist: " + edge.maxKnnDist;
hover += "\n";
hover += "\nnode1.id: " + node1.id;
hover += "\nnode1.knnDistThres: " + node1.knnDistThres;
hover += "\nnode1.posDistThres: " + node1.posDistThres;
hover += "\n";
hover += "\nnode2.id: " + node2.id;
hover += "\nnode2.knnDistThres: " + node2.knnDistThres;
hover += "\nnode2.posDistThres: " + node2.posDistThres;
console.log("\n-------- " + hover)
var options = {
position : new google.maps.LatLng(lat, lng),
draggable : false,
raiseOnDrag : false,
labelContent : title,
labelClass : "labels",
title : hover,
labelAnchor : new google.maps.Point(10.5, 35)
};
if (log.event == "CurrentPosition") {
options.icon = {
size : new google.maps.Size(25, 25),
anchor : new google.maps.Point(12.5, 12.5),
url : "./img/round-blue.png"
};
options.shape = {
coords : [ 12.5, 12.5, 25 ],
type : "circle",
};
options.labelAnchor = new google.maps.Point(10.5, 6.25);
}
logLocations[i].marker = marker = new MarkerWithLabel(options);
}
marker.setMap(_map);
}
}
}
$editor.on("derender", function(e, layer) {
for (var i = 0; i < logLocations.length; i++) {
var marker = logLocations[i].marker;
if (marker) {
marker.setMap(null);
}
}
});
return {
"loadFile" : loadFile,
"renderLayer" : renderLayer
};
}
|
{
unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset);
}
|
'use strict';
var Backbone = require('backbone');
var User = require('./User');
var AdminView = require('./AdminView');
window.app.on('start', function () {
var self = this;
var Users = Backbone.Collection.extend({
model: User,
url: window.URL_PREFIX + '/admin/users'
});
var users = self.users = new Users();
self.showAdmin = function () {
users.fetch().then(function () {
self.rootView.main.show(new AdminView({
collection: users
}));
});
};
});
|
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
radius = 20;
var circles = d3.range(324).map(function(i) {
return {
x: (i % 25) * (radius + 1) * 2,
y: Math.floor(i / 25) * (radius + 1) * 2
};
});
var simulation = d3.forceSimulation(circles)
.force("collide", d3.forceCollide(radius + 1).iterations(4))
.on("tick", drawCircles);
d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function drawCircles() {
context.clearRect(0, 0, width, height);
context.save();
context.beginPath();
circles.forEach(drawCircle);
context.fill();
context.strokeStyle = "#fff";
context.stroke();
}
function drawCircle(d) {
context.moveTo(d.x + radius, d.y);
context.arc(d.x, d.y, radius, 0, 2 * Math.PI);
}
function dragsubject() {
return simulation.find(d3.event.x, d3.event.y, radius);
}
function dragstarted() {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}
function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}
function dragended() {
if (!d3.event.active) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
|
/*
* simple sliding menu using jQuery and Interface - http://www.getintothis.com
*
* note: this library depends on jquery (http://www.jquery.com) and
* interface (http://interface.eyecon.ro)
*
* Copyright (c) 2006 Ramin Bozorgzadeh
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LECENSE.txt) linceses.
*/
jQuery.fn.rb_menu = function(options) {
var self = this;
self.options = {
// transitions: easein, easeout, easeboth, bouncein, bounceout,
// bounceboth, elasticin, elasticout, elasticboth
transition: 'bounceout',
// trigger events: mouseover, mousedown, mouseup, click, dblclick
triggerEvent: 'mouseover',
// number of ms to delay before hiding menu (on page load)
loadHideDelay : 1000,
// number of ms to delay before hiding menu (on mouseout)
blurHideDelay: 500,
// number of ms for transition effect
effectDuration: 1000,
// hide the menu when the page loads
hideOnLoad: true,
// automatically hide menu when mouse leaves area
autoHide: true
}
// make sure to check if options are given!
if(options) {
jQuery.extend(self.options, options);
}
return this.each(function() {
var menu = jQuery(this).find('.rb_menu');
var toggle = jQuery(this).find('.rb_toggle span');
// add 'hover' class to trigger for css styling
toggle.hover( function() {
jQuery(this).addClass('hover');
}, function() {
jQuery(this).removeClass('hover');
});
if(self.options.hideOnLoad) {
if(self.options.loadHideDelay <= 0) {
menu.hide();
self.closed = true;
self.unbind();
} else {
// let's hide the menu when the page is loading
// after {loadHideDelay} milliseconds
setTimeout( function() {
menu.hideMenu();
}, self.options.loadHideDelay);
}
}
// bind event defined by {triggerEvent} to the trigger
// to open and close the menu
toggle.bind(self.options.triggerEvent, function() {
// if the trigger event is click or dblclick, we want
// to close the menu if its open
if((self.options.triggerEvent == 'click' || self.options.triggerEvent == 'dblclick') && !self.closed) {
menu.hideMenu();
} else {
menu.showMenu();
}
});
menu.hideMenu = function() {
if(this.css('display') == 'block' && !self.closed) {
this.SlideOutLeft(
self.options.effectDuration,
function() {
self.closed = true;
self.unbind();
},
self.options.transition
);
}
}
menu.showMenu = function() {
if(this.css('display') == 'none' && self.closed) {
this.SlideInLeft(
self.options.effectDuration,
function() {
self.closed = false;
if(self.options.autoHide) {
self.hover(function() {
clearTimeout(self.timeout);
}, function() {
self.timeout = setTimeout( function() {
menu.hideMenu();
}, self.options.blurHideDelay);
});
}
},
self.options.transition
);
}
}
});
};
|
import DS from 'ember-data';
import DomainResource from 'ember-fhir/models/domain-resource';
const { attr, belongsTo, hasMany } = DS;
export default DomainResource.extend({
identifier: hasMany('identifier', { async: true }),
basedOn: hasMany('reference', { async: true }),
status: attr('string'),
category: belongsTo('codeable-concept', { async: false }),
code: belongsTo('codeable-concept', { async: false }),
subject: belongsTo('reference', { async: false }),
context: belongsTo('reference', { async: false }),
effectiveDateTime: attr('date'),
effectivePeriod: belongsTo('period', { async: false }),
issued: attr('string'),
performer: hasMany('diagnostic-report-performer', { async: true }),
specimen: hasMany('reference', { async: true }),
result: hasMany('reference', { async: true }),
imagingStudy: hasMany('reference', { async: true }),
image: hasMany('diagnostic-report-image', { async: true }),
conclusion: attr('string'),
codedDiagnosis: hasMany('codeable-concept', { async: true }),
presentedForm: hasMany('attachment', { async: true })
});
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.19-2-13
description: >
Array.prototype.map - applied to the Array-like object when
'length' is inherited accessor property without a get function
includes: [runTestCase.js]
---*/
function testcase() {
function callbackfn(val, idx, obj) {
return val > 10;
}
var proto = {};
Object.defineProperty(proto, "length", {
set: function () { },
configurable: true
});
var Con = function () { };
Con.prototype = proto;
var child = new Con();
child[0] = 11;
child[1] = 12;
var testResult = Array.prototype.map.call(child, callbackfn);
return 0 === testResult.length;
}
runTestCase(testcase);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.