code
stringlengths
2
1.05M
module.exports = { prefix: 'far', iconName: 'arrow-alt-square-up', icon: [448, 512, [], "f353", "M244 384h-40c-6.6 0-12-5.4-12-12V256h-67c-10.7 0-16-12.9-8.5-20.5l99-99c4.7-4.7 12.3-4.7 17 0l99 99c7.6 7.6 2.2 20.5-8.5 20.5h-67v116c0 6.6-5.4 12-12 12zM448 80v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V80c0-26.5 21.5-48 48-48h352c26.5 0 48 21.5 48 48zm-48 346V86c0-3.3-2.7-6-6-6H54c-3.3 0-6 2.7-6 6v340c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"] };
import React, { Component } from "react"; import formatter from "../formatter"; const labelStyle = { fg: "magenta", bold: true }; class RequestBreakdown extends Component { scroll(amount) { // nope } render() { const { respTime, sqlTime, renderingTime } = this.props.data; return ( <box top={0} height="100%-2" left={0} width="100%-2"> <box top={1} height={1} left={0} width={19} content=" Response Time : " style={labelStyle} /> <box top={1} height={1} left={19} width="100%-19" content={formatter.ms(respTime)} /> <box top={2} height={1} left={0} width={29} content=" ===========================" /> <box top={3} height={1} left={0} width={19} content=" SQL Time : " style={labelStyle} /> <box top={3} height={1} left={19} width="100%-19" content={formatter.ms(sqlTime)} /> <box top={4} height={1} left={0} width={19} content=" Rendering Time : " style={labelStyle} /> <box top={4} height={1} left={19} width="100%-19" content={formatter.ms(renderingTime)} /> <box top={5} height={1} left={0} width={19} content=" Others : " style={labelStyle} /> <box top={5} height={1} left={19} width="100%-19" content={formatter.ms(respTime - sqlTime - renderingTime)} /> </box> ); } } export default RequestBreakdown;
const DrawCard = require('../../drawcard.js'); const { CardTypes } = require('../../Constants'); class AsakoTsuki extends DrawCard { setupCardAbilities(ability) { this.reaction({ title: 'Honor a scholar character', when: { onClaimRing: event => event.conflict && event.conflict.hasElement('water') }, target: { cardType: CardTypes.Character, cardCondition: card => card.hasTrait('scholar'), gameAction: ability.actions.honor() } }); } } AsakoTsuki.id = 'asako-tsuki'; module.exports = AsakoTsuki;
import DndStatus from 'ringcentral-integration/modules/Presence/dndStatus'; import i18n from './i18n'; export function getPresenceStatusName( presenceStatus, dndStatus, currentLocale, ) { if (dndStatus === DndStatus.doNotAcceptAnyCalls) { return i18n.getString(dndStatus, currentLocale); } return i18n.getString(presenceStatus, currentLocale); }
"use strict"; const bunyan = require("bunyan") , bformat = require("bunyan-format") , config = require("config") ; const log_level = process.env.LOG_LEVEL || (config.has('app.log_level') ? config.get('app.log_level') : "info"); const formatOut = bformat({ outputMode: "short" , }) , logger = bunyan.createLogger({ name: "pepp", streams: [ { level: log_level, stream: formatOut }/*, { level: 'info', // log ERROR and above to a file path: './output/test.log' }*/ ] }); module.exports = logger;
module.exports = function(grunt) { grunt.initConfig({ // insert the bower files in your index.html wiredep: { target: { src: 'index.html' } } }); grunt.loadNpmTasks('grunt-wiredep'); grunt.registerTask('default', ['wiredep']); };
const test = require('tape') const MinHeap = require('./MinHeap') test('find returns null in empty heap', assert => { const heap = new MinHeap() assert.equal(heap.findMin(), null) assert.end() }) test('length is 0 in empty heap', assert => { const heap = new MinHeap() assert.equal(heap.length, 0) assert.end() }) test('length is updated when items added', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(10) assert.equal(heap.length, 3) assert.end() }) test('length is updated when items removed', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(10) heap.extractMin() heap.extractMin() assert.equal(heap.length, 1) assert.end() }) test('min item is replaced with given item', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(3) assert.equal(heap.findMin(), 1) assert.equal(heap.length, 3) heap.replace(4) assert.equal(heap.findMin(), 2) assert.equal(heap.length, 3) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 3) assert.equal(heap.extractMin(), 4) assert.end() }) test('find returns min item from heap', assert => { const heap = new MinHeap() heap.insert(3) heap.insert(1) heap.insert(10) assert.equal(heap.length, 3) assert.equal(heap.findMin(), 1) assert.equal(heap.length, 3) assert.end() }) test('extract returns min item from heap', assert => { const heap = new MinHeap() heap.insert(9) heap.insert(8) heap.insert(7) heap.insert(6) heap.insert(5) heap.insert(4) heap.insert(3) heap.insert(2) heap.insert(2) heap.insert(2) heap.insert(1) assert.equal(heap.extractMin(), 1) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 3) assert.equal(heap.extractMin(), 4) assert.equal(heap.extractMin(), 5) assert.equal(heap.extractMin(), 6) assert.equal(heap.extractMin(), 7) assert.equal(heap.extractMin(), 8) assert.equal(heap.extractMin(), 9) assert.equal(heap.extractMin(), null) assert.equal(heap.extractMin(), null) assert.end() }) test('heap can be iterated', assert => { const heap = new MinHeap() heap.insert(5) heap.insert(0) heap.insert(3) heap.insert(2) heap.insert(4) heap.insert(1) assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5]) assert.end() }) test('heap is created from given array', assert => { const input = [5, 6, 3, 1, 2, 0, 4] const heap = new MinHeap(input) assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5, 6]) assert.deepEqual(input, [5, 6, 3, 1, 2, 0, 4]) // input data should not be modified assert.end() }) test('sort random data with heap', assert => { const input = [] for (let i = 0; i < 1e5; i++) { const item = Math.floor(Math.random() * 1e4) input.push(item) } const heap = new MinHeap(input) assert.deepEqual([...heap], input.sort((a, b) => a - b)) assert.end() })
let fs = require('fs'); let path = require('path'); let moviesData = require('../config/database'); module.exports = (req, res) => { if(req.headers.statusheader === "Full") { fs.readFile("./views/status.html", (err, data) => { if(err) { console.log(err); res.writeHead(404); res.write('404 Not Found'); res.end(); } res.writeHead(200, { 'Content-Type': 'text/html' }); let imagesCount = moviesData.getMovies().length; data = data.toString().replace('{content}', `There are currently ${imagesCount} images.`); res.write(data); res.end(); }) } else { return true; } }
/* --- AUTOGENERATED FILE ----------------------------- * If you make changes to this file delete this comment. * Otherwise the file may be overwritten in the future. * --------------------------------------------------- */ const { mergeLocMatchGroups } = require('../lib/matching/utils'); const { regexMatchLocs } = require('../lib/matching/regexMatch'); const allSetSrc = { type: 'website', url: 'https://resources.allsetlearning.com/chinese/grammar/ASGTYJ3E', name: 'AllSet Chinese Grammar Wiki', }; module.exports = { id: 'budanErqie', structures: [ 'Subj. + 不但 + Adj. / Verb, 而且 + Adj. / Verb', 'Subj. + 不但 + Adj. / Verb, 而且 + Adj. / Verb', '不但 + Subj. 1 + Adj. / Verb, 而且 + Subj. 2 + Adj. / Verb', ], description: '"不但⋯⋯,而且⋯⋯" (bùdàn..., érqiě...) is a very commonly used pattern that indicates "not only, ... but also...."', sources: [allSetSrc], match: sentence => mergeLocMatchGroups([regexMatchLocs(sentence.text, /(不但)[^而且]+(而且)/)]), examples: [ { zh: '这种菜不但好吃,而且有营养。', en: 'This kind of vegetable is not only delicious, but nutritious as well.', src: allSetSrc, }, { zh: '她不但聪明,而且很努力。', en: 'She is not only smart, but also very hard-working.', src: allSetSrc, }, { zh: '他不但做完了,而且做得非常好。', en: 'Not only did he finish, but he also did it extremely well.', src: allSetSrc, }, { zh: '我不但会做饭,而且会洗衣服。', en: 'Not only can I cook, but I can also do the laundry.', src: allSetSrc, }, { zh: '不但我会做饭,而且我妹妹也会做饭。', en: 'Not only can I cook, but my little sister can as well.', src: allSetSrc, }, ], };
/** * js-borschik-include * =================== * * Собирает *js*-файлы инклудами борщика, сохраняет в виде `?.js`. * Технология нужна, если в исходных *js*-файлах используются инклуды борщика. * * В последствии, получившийся файл `?.js` следует раскрывать с помощью технологии `borschik`. * * **Опции** * * * *String* **target** — Результирующий таргет. Обязательная опция. * * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов * (его предоставляет технология `files`). По умолчанию — `?.files`. * * *String[]* **sourceSuffixes** — суффиксы файлов, по которым строится files-таргет. По умолчанию — ['js']. * * **Пример** * * ```javascript * nodeConfig.addTechs([ * [ require('enb-borschik/techs/js-borschik-include') ], * [ require('enb-borschik/techs/borschik'), { * source: '?.js', * target: '_?.js' * } ]); * ]); * ``` */ module.exports = require('enb/lib/build-flow').create() .name('js-borschik-include') .target('target', '?.js') .useFileList(['js']) .builder(function (files) { var node = this.node; return files.map(function (file) { return '/*borschik:include:' + node.relativePath(file.fullname) + '*/'; }).join('\n'); }) .createTech();
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z" }), 'OfflinePinSharp');
import * as actions from './actions' describe('App actions', () => { it('selectTerm should create SELECT_TERM action', () => { expect(actions.selectTerm('term')).toEqual({ type: 'SELECT_TERM', term: 'term' }) }) it('startFetch should create START_FETCH action', () => { expect(actions.startFetch()).toEqual({ type: 'START_FETCH', isBusy: true }) }) it('fetchTerm calls RECEIVE_ERROR on complete lookup failure', () => { let failingLookup = (url, settings, onDone ) => { throw "Error" }; let conceptNet = { lookup: failingLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_ERROR on lookup returning error to onDone', () => { let errorLookup = (url, settings, onDone ) => { onDone("Error", null) }; let conceptNet = { lookup: errorLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_RESPONSE on lookup returning results to onDone', () => { let successLookup = (url, settings, onDone ) => { onDone(null, {'edges': []}) }; let conceptNet = { lookup: successLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_RESPONSE") }; actions.getIsA(dispatch, conceptNet, "next term"); }) })
/** * @version: 1.0.1 * @author: Dan Grossman http://www.dangrossman.info/ * @date: 2012-08-20 * @copyright: Copyright (c) 2012 Dan Grossman. All rights reserved. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0 * @website: http://www.improvely.com/ */ !function ($) { var DateRangePicker = function (element, options, cb) { var hasOptions = typeof options == 'object' var localeObject; //state this.startDate = Date.today(); this.endDate = Date.today(); this.minDate = false; this.maxDate = false; this.changed = false; this.ranges = {}; this.opens = 'right'; this.cb = function () { }; this.format = 'MM/dd/yyyy'; this.separator = ' - '; this.showWeekNumbers = false; this.buttonClasses = ['btn-primary']; this.locale = { applyLabel: 'Apply', fromLabel: 'From', toLabel: 'To', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: Date.CultureInfo.shortestDayNames, monthNames: Date.CultureInfo.monthNames, firstDay: 0 }; localeObject = this.locale; this.leftCalendar = { month: Date.today().set({ day: 1, month: this.startDate.getMonth(), year: this.startDate.getFullYear() }), calendar: Array() }; this.rightCalendar = { month: Date.today().set({ day: 1, month: this.endDate.getMonth(), year: this.endDate.getFullYear() }), calendar: Array() }; // by default, the daterangepicker element is placed at the bottom of HTML body this.parentEl = 'body'; //element that triggered the date range picker this.element = $(element); if (this.element.hasClass('pull-right')) this.opens = 'left'; if (this.element.is('input')) { this.element.on({ click: $.proxy(this.show, this), focus: $.proxy(this.show, this) }); } else { this.element.on('click', $.proxy(this.show, this)); } if (hasOptions) { if(typeof options.locale == 'object') { $.each(localeObject, function (property, value) { localeObject[property] = options.locale[property] || value; }); } } var DRPTemplate = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left"></div>' + '<div class="calendar right"></div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<div>' + '<label for="daterangepicker_start">' + this.locale.fromLabel + '</label>' + '<input class="input-mini form-control" type="text" name="daterangepicker_start" value="" disabled="disabled" />' + '</div>' + '<div>' + '<label for="daterangepicker_end">' + this.locale.toLabel + '</label>' + '<input class="input-mini form-control" type="text" name="daterangepicker_end" value="" disabled="disabled" />' + '</div>' + '<button class="btn btn-small" disabled="disabled">' + this.locale.applyLabel + '</button>' + '</div>' + '</div>' + '</div>'; this.parentEl = (hasOptions && options.parentEl && $(options.parentEl)) || $(this.parentEl); //the date range picker this.container = $(DRPTemplate).appendTo(this.parentEl); if (hasOptions) { if (typeof options.format == 'string') this.format = options.format; if (typeof options.separator == 'string') this.separator = options.separator; if (typeof options.startDate == 'string') this.startDate = Date.parse(options.startDate, this.format); if (typeof options.endDate == 'string') this.endDate = Date.parse(options.endDate, this.format); if (typeof options.minDate == 'string') this.minDate = Date.parse(options.minDate, this.format); if (typeof options.maxDate == 'string') this.maxDate = Date.parse(options.maxDate, this.format); if (typeof options.startDate == 'object') this.startDate = options.startDate; if (typeof options.endDate == 'object') this.endDate = options.endDate; if (typeof options.minDate == 'object') this.minDate = options.minDate; if (typeof options.maxDate == 'object') this.maxDate = options.maxDate; if (typeof options.ranges == 'object') { for (var range in options.ranges) { var start = options.ranges[range][0]; var end = options.ranges[range][1]; if (typeof start == 'string') start = Date.parse(start); if (typeof end == 'string') end = Date.parse(end); // If we have a min/max date set, bound this range // to it, but only if it would otherwise fall // outside of the min/max. if (this.minDate && start < this.minDate) start = this.minDate; if (this.maxDate && end > this.maxDate) end = this.maxDate; // If the end of the range is before the minimum (if min is set) OR // the start of the range is after the max (also if set) don't display this // range option. if ((this.minDate && end < this.minDate) || (this.maxDate && start > this.maxDate)) { continue; } this.ranges[range] = [start, end]; } var list = '<ul>'; for (var range in this.ranges) { list += '<li>' + range + '</li>'; } list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges').prepend(list); } // update day names order to firstDay if (typeof options.locale == 'object') { if (typeof options.locale.firstDay == 'number') { this.locale.firstDay = options.locale.firstDay; var iterator = options.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } } if (typeof options.opens == 'string') this.opens = options.opens; if (typeof options.showWeekNumbers == 'boolean') { this.showWeekNumbers = options.showWeekNumbers; } if (typeof options.buttonClasses == 'string') { this.buttonClasses = [options.buttonClasses]; } if (typeof options.buttonClasses == 'object') { this.buttonClasses = options.buttonClasses; } } //apply CSS classes to buttons var c = this.container; $.each(this.buttonClasses, function (idx, val) { c.find('button').addClass(val); }); if (this.opens == 'right') { //swap calendar positions var left = this.container.find('.calendar.left'); var right = this.container.find('.calendar.right'); left.removeClass('left').addClass('right'); right.removeClass('right').addClass('left'); } if (typeof options == 'undefined' || typeof options.ranges == 'undefined') this.container.find('.calendar').show(); if (typeof cb == 'function') this.cb = cb; this.container.addClass('opens' + this.opens); //event listeners this.container.on('mousedown', $.proxy(this.mousedown, this)); this.container.find('.calendar').on('click', '.prev', $.proxy(this.clickPrev, this)); this.container.find('.calendar').on('click', '.next', $.proxy(this.clickNext, this)); this.container.find('.ranges').on('click', 'button', $.proxy(this.clickApply, this)); this.container.find('.calendar').on('click', 'td.available', $.proxy(this.clickDate, this)); this.container.find('.calendar').on('mouseenter', 'td.available', $.proxy(this.enterDate, this)); this.container.find('.calendar').on('mouseleave', 'td.available', $.proxy(this.updateView, this)); this.container.find('.ranges').on('click', 'li', $.proxy(this.clickRange, this)); this.container.find('.ranges').on('mouseenter', 'li', $.proxy(this.enterRange, this)); this.container.find('.ranges').on('mouseleave', 'li', $.proxy(this.updateView, this)); this.element.on('keyup', $.proxy(this.updateFromControl, this)); this.updateView(); this.updateCalendars(); }; DateRangePicker.prototype = { constructor: DateRangePicker, mousedown: function (e) { e.stopPropagation(); e.preventDefault(); }, updateView: function () { this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.container.find('input[name=daterangepicker_start]').val(this.startDate.toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(this.endDate.toString(this.format)); if (this.startDate.equals(this.endDate) || this.startDate.isBefore(this.endDate)) { this.container.find('button').removeAttr('disabled'); } else { this.container.find('button').attr('disabled', 'disabled'); } }, updateFromControl: function () { if (!this.element.is('input')) return; var dateString = this.element.val().split(this.separator); var start = Date.parseExact(dateString[0], this.format); var end = Date.parseExact(dateString[1], this.format); if (start == null || end == null) return; if (end.isBefore(start)) return; this.startDate = start; this.endDate = end; this.updateView(); this.cb(this.startDate, this.endDate); this.updateCalendars(); }, notify: function () { this.updateView(); if (this.element.is('input')) { this.element.val(this.startDate.toString(this.format) + this.separator + this.endDate.toString(this.format)); } this.cb(this.startDate, this.endDate); }, move: function () { var parentOffset = { top: this.parentEl.offset().top - this.parentEl.scrollTop(), left: this.parentEl.offset().left - this.parentEl.scrollLeft() }; if (this.opens == 'left') { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left, left: 'auto' }); } else { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), left: this.element.offset().left - parentOffset.left, right: 'auto' }); } }, show: function (e) { this.container.show(); this.move(); if (e) { e.stopPropagation(); e.preventDefault(); } this.changed = false; $(document).on('mousedown', $.proxy(this.hide, this)); }, hide: function (e) { this.container.hide(); $(document).off('mousedown', this.hide); if (this.changed) { this.changed = false; this.notify(); } }, enterRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.updateView(); } else { var dates = this.ranges[label]; this.container.find('input[name=daterangepicker_start]').val(dates[0].toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(dates[1].toString(this.format)); } }, clickRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.container.find('.calendar').show(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); this.changed = true; this.container.find('.calendar').hide(); this.hide(); } }, clickPrev: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: -1 }); } else { this.rightCalendar.month.add({ months: -1 }); } this.updateCalendars(); }, clickNext: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: 1 }); } else { this.rightCalendar.month.add({ months: 1 }); } this.updateCalendars(); }, enterDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].toString(this.format)); } else { this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].toString(this.format)); } }, clickDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { startDate = this.leftCalendar.calendar[row][col]; endDate = this.endDate; } else { startDate = this.startDate; endDate = this.rightCalendar.calendar[row][col]; } cal.find('td').removeClass('active'); if (startDate.equals(endDate) || startDate.isBefore(endDate)) { $(e.target).addClass('active'); if (!startDate.equals(this.startDate) || !endDate.equals(this.endDate)) this.changed = true; this.startDate = startDate; this.endDate = endDate; } this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); }, clickApply: function (e) { this.hide(); }, updateCalendars: function () { this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.getMonth(), this.leftCalendar.month.getFullYear()); this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.getMonth(), this.rightCalendar.month.getFullYear()); this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.endDate)); this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate)); }, buildCalendar: function (month, year) { var firstDay = Date.today().set({ day: 1, month: month, year: year }); var lastMonth = firstDay.clone().add(-1).day().getMonth(); var lastYear = firstDay.clone().add(-1).day().getFullYear(); var daysInMonth = Date.getDaysInMonth(year, month); var daysInLastMonth = Date.getDaysInMonth(lastYear, lastMonth); var dayOfWeek = firstDay.getDay(); //initialize a 6 rows x 7 columns array for the calendar var calendar = Array(); for (var i = 0; i < 6; i++) { calendar[i] = Array(); } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = Date.today().set({ day: startDay, month: lastMonth, year: lastYear }); for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = curDate.clone().add(1).day()) { if (i > 0 && col % 7 == 0) { col = 0; row++; } calendar[row][col] = curDate; } return calendar; }, renderCalendar: function (calendar, selected, minDate, maxDate) { var html = '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers) html += '<th></th>'; if (!minDate || minDate < calendar[1][1]) { html += '<th class="prev available"><i class="icon-arrow-left"></i></th>'; } else { html += '<th></th>'; } html += '<th colspan="5" style="width: auto">' + this.locale.monthNames[calendar[1][1].getMonth()] + calendar[1][1].toString(" yyyy") + '</th>'; if (!maxDate || maxDate > calendar[1][1]) { html += '<th class="next available"><i class="icon-arrow-right"></i></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function (index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].getWeek() + '</td>'; for (var col = 0; col < 7; col++) { var cname = 'available '; cname += (calendar[row][col].getMonth() == calendar[1][1].getMonth()) ? '' : 'off'; // Normalise the time so the comparison won't fail selected.setHours(0,0,0,0); if ( (minDate && calendar[row][col] < minDate) || (maxDate && calendar[row][col] > maxDate)) { cname = 'off disabled'; } else if (calendar[row][col].equals(selected)) { cname += 'active'; } var title = 'r' + row + 'c' + col; html += '<td class="' + cname + '" title="' + title + '">' + calendar[row][col].getDate() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; return html; } }; $.fn.daterangepicker = function (options, cb) { this.each(function() { var el = $(this); if (!el.data('daterangepicker')) el.data('daterangepicker', new DateRangePicker(el, options, cb)); }); return this; }; } (window.jQuery);
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ "use strict"; import Poisson from "poisson-disk-sample"; import Vector from "../geometry/Vector"; import Rectangle from "../geometry/Rectangle"; import Rand from "./Rand"; /** * Creates a random distribution of points in a particular bounding box * with a particular average distance between points. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} [seed=null] If specified use a local seed for creating the point * distribution. Otherwise, use the current global seed for generation * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function random(bbox, d, seed = null) { const rng = seed ? new Rand(seed) : Rand; const nPoints = bbox.area / (d * d); let points = []; for (let i = 0; i < nPoints; i++) { points.push(rng.vector(bbox)); } return points; } /** * Creates a square grid like distribution of points in a particular bounding * box with a particular distance between points. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function square(bbox, d) { const dx = d / 2; const dy = dx; let points = []; for (let y = 0; y < bbox.height; y += d) { for (let x = 0; x < bbox.width; x += d) { points.push(new Vector(dx + x, dy + y)); } } return points; } /** * Creates a square grid like distribution of points in a particular bounding * box with a particular distance between points. The grid has also been * slightly purturbed or jittered so that the distribution is not completely * even. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} amm The ammount of jitter that has been applied to the grid * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function squareJitter(bbox, d, amm) { return square(bbox, d).map(v => Rand.jitter(v, amm)); } /** * Creates a uniform hexagonal distribution of points in a particular bounding * box with a particular distance between points. The hexagons can also be * specified to have a particular width or height as well as creating hexagons * that have "pointy" tops or "flat" tops. By default it makes flat tops. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {boolean} [flatTop=true] Create hecagons with flat tops by default. * Otherwise go with the pointy top hexagons. * @param {number} w The width of the hexagon tiles * @param {number} h The height of the hexagon tiles * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function hexagon(bbox, d, flatTop = true, w, h) { // Need to allow for the change of height and width // Running into "Uncaught Voronoi.closeCells() > this makes no sense!" const dx = d / 2; const dy = dx; let points = []; const altitude = Math.sqrt(3) / 2 * d; var N = Math.sqrt(bbox.area / (d * d)); for (let y = 0; y < N; y++) { for (let x = 0; x < N; x++) { points.push(new Vector((0.5 + x) / N * bbox.width, (0.25 + 0.5 * x % 2 + y) / N * bbox.height)); // points.push(new Vector((y % 2) * dx + x * d + dx, y * d + dy)); // Pointy Top // points.push(new Vector(x * d, (x % 2) * dx + y * d)); // Flat Top } } return points; } /** * Creates a blue noise distribution of points in a particular bounding box * with a particular average distance between points. This is done by * creating a grid system and picking a random point in each grid. This has * the effect of creating a less random distribution of points. The second * parameter m determins the spacing between points in the grid. This ensures * that no two points are in the same grid. * * @summary Create a jittered grid based random blue noise point distribution. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} [seed=null] If specified use a local seed for creating the point * distribution. Otherwise, use the current global seed for generation * @param {number} [m=0] Maximum distance away from the edge of the grid that a * point can be placed. This acts to increase the padding between points. * This makes the noise less random. This number must be smaller than d. * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function jitteredGrid(bbox, d, seed = null, m = 0) { const rng = seed ? new Rand(seed) : Rand; let points = []; let pointBox; for (let y = 0; y < bbox.height - d; y += d) { for (let x = 0; x < bbox.width - d; x += d) { // Local bbox for the point to generate in const boxPos = new Vector(x - d + m, y - d + m); pointBox = new Rectangle(boxPos, x - m, y - m); points.push(rng.vector(pointBox)); } } return points; } /** * Creates a poisson, or blue noise distribution of points in a particular * bounding box with a particular average distance between points. This is * done by using poisson disk sampling which tries to create points so that the * distance between neighbors is as close to a fixed number (the distance d) * as possible. This algorithm is implemented using the poisson dart throwing * algorithm. * * @summary Create a blue noise distribution of points using poisson disk * sampling. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * * @see {@link https://www.jasondavies.com/poisson-disc/} * @see {@link https://github.com/jeffrey-hearn/poisson-disk-sample} * @memberof PointDistribution */ export function poisson(bbox, d) { var sampler = new Poisson(bbox.width, bbox.height, d, d); var solution = sampler.sampleUntilSolution(); var points = solution.map(point => Vector.add(new Vector(point), bbox.position)); return points; } /** * Creates a blue noise distribution of points in a particular bounding box * with a particular average distance between points. This is done by using * recursive wang tiles to create this distribution of points. * * @summary Not Implemented Yet * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function recursiveWang(bbox, d) { throw "Error: Not Implemented"; } /** * Creates a circular distribution of points in a particular bounding box * with a particular average distance between points. * * @summary Not Implemented Yet * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function circular(bbox, d) { throw "Error: Not Implemented"; }
'use strict'; angular.module('refugeesApp') .controller('SettingsController', function ($scope, Principal, Auth, Language, $translate) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = copyAccount(account); }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity(true).then(function(account) { $scope.settingsAccount = copyAccount(account); }); Language.getCurrent().then(function(current) { if ($scope.settingsAccount.langKey !== current) { $translate.use($scope.settingsAccount.langKey); } }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; /** * Store the "settings account" in a separate variable, and not in the shared "account" variable. */ var copyAccount = function (account) { return { activated: account.activated, email: account.email, firstName: account.firstName, langKey: account.langKey, lastName: account.lastName, login: account.login } } });
var UTIL = require('./util'); var ShadowNode; module.exports = ShadowNode = function(patch,options){ this.shadow = options.shadow; this.native = options.native; this.elem = new patch.type(this); this.elem.props = patch.props; this.elem.props.children = patch.children; this.elem.state = this.elem.getInitialState ? this.elem.getInitialState() : {}; this.elem.componentWillMount(); this.render(); this.elem.componentDidMount(); }; var proto = ShadowNode.prototype; Object.defineProperty(proto,'parent',{ get : function(){ return this.native.parent; } }); proto.setPatch = function(patch){ var oldProps = this.elem.props; this.elem._isUpdating = true; var newProps = patch.props; newProps.children = patch.children; this.elem.componentWillRecieveProps(newProps); this.elem.props = newProps; this.elem.componentDidRecieveProps(oldProps); this.update(); }; proto.update = function(){ // This is called by set state and by props updating this.elem.componentWillUpdate(); this.render(); this.elem.componentWillUpdate(); }; proto.remove = function(){ this.elem.componentWillUnmount(); this.destroyed = true; if (this.figure){ return this.figure.remove(); } this.shadow = void 0; this.figure = void 0; this.native = void 0; this.elem.componentDidUnmount(); }; proto.render = function(){ var newPatch = this.elem.render(); var lastPatch = this.lastPatch; this.lastPatch = newPatch; if (!lastPatch && !newPatch) return; if (UTIL.isNative(newPatch)){ if (this.figure){ this.figure.remove(); this.figure = void 0; } this.native.shadowTail = this; return this.native.setPatch(newPatch); } if (UTIL.differentTypes(lastPatch,newPatch)){ if (this.figure) this.figure.remove(); this.figure = new ShadowNode(newPatch,{ shadow : this,native : this.native }); return this.figure; } if (UTIL.differentPatch(lastPatch,newPatch)){ // component will update this.figure.setPatch(newPatch); // component did update } };
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var videoWorksSchema = new Schema ({ title: { type: String }, directedBy: { type: [String] }, editedBy: { type: [String] }, cast: { type: [String] }, videoUrl: { type: String }, copyright: { type: String }, workInfo: { type: String }, coverImageUrl: { type: String }, created: { type: Date, default: Date.now } }); mongoose.model('videoWorks', videoWorksSchema);
'use strict'; module.exports = { extends: ['./index', './rules/imports', './rules/frontend', './rules/vue'].map(require.resolve).concat(['plugin:vue/recommended']), parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint', sourceType: 'module', ecmaVersion: 2017, ecmaFeatures: { jsx: true, experimentalObjectRestSpread: true, }, }, rules: { // this two doesn't work in vue 'import/no-named-as-default': 'off', 'import/no-named-as-default-member': 'off', }, };
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component { constructor(props) { super(props); } render() { return ( <div id="container" className="link_box"> <div id="itemA"></div> <div id="itemB"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/> </Link> </div> <div id="itemC"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/btn_dscoupon02.jpg" alt="dscount"/> </Link> </div> <div id="itemD"></div> <div id="itemE"> <Link to="" >ログイン</Link> </div> <div id="itemF"> <Link to="/signup">会員登録</Link> </div> <div id="itemG"> <a href="#" >マイページ{" "}▼</a> </div> <div id="itemH"> <a href="#" >お客様センター{" "}▼</a> </div> <div id="itemI"> <a href="#" > <span className="glyphicon glyphicon-shopping-cart">(0)</span> </a> </div> <div id="itemJ"> <a href="#" > <span className="glyphicon glyphicon-heart">(1)</span> </a> </div> <form id="itemK"> <div className="field"> <button className="drop-down-btn" type="button" id="search">総合検索{" "}▼</button> <input className="header-search-input" type="text" id="searchterm" placeholder=" what do you want ?" /> <button className="search-submit" type="button" id="search"> <span className="glyphicon glyphicon-search"></span> </button> </div> </form> <div id="itemL"></div> </div> ); } } export default Header;
//ButtonTable is a very very special case, because I am still not sure why it is a table :-) // alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time. // we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from AbstractTable //button field is only a data structure that is stored under buttons collection var ButtonField = function (nam, label, actionName) { this.name = nam; this.label = label; this.actionName = actionName; }; var ButtonPanel = function () { this.name = null; this.P2 = null; this.renderingOption = null; this.buttons = new Object(); //collection of buttonFields }; ButtonPanel.prototype.setData = function (dc) { var data = dc.grids[this.name]; if (data.length <= 1) { if (this.renderingOption == 'nextToEachOther') { this.P2.hideOrShowPanels([this.name], 'none'); } else { var listName = this.name + 'ButtonList'; var buttonList = this.P2.doc.getElementById(listName); //should we do the following or just say buttonList.innerHTML = '' while (buttonList.options.length) { buttonList.remove(0); } } return; } data = this.transposeIfRequired(data); //possible that it was hidden earlier.. Let us show it first this.P2.hideOrShowPanels([this.name], ''); if (this.renderingOption == 'nextToEachOther') this.enableButtons(data); else this.buildDropDown(data); }; //enable/disable buttons in a button panel based on data received from server ButtonPanel.prototype.enableButtons = function (data) { var doc = this.P2.doc; var n = data.length; if (n <= 1) return; //if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes var hasFlag = data[0].length > 1; //for convenience, get the buttons into a collection indexed by name var btnsToEnable = {}; for (var i = 1; i < n; i++) { var row = data[i]; if (hasFlag) { var flag = row[1]; if (!flag || flag == '0') continue; } btnsToEnable[row[0]] = true; } //now let us go thru each button, and hide or who it for (var btnName in this.buttons) { var ele = doc.getElementById(btnName); if (!ele) { debug('Design Error: Button panel ' + this.name + ' has not produced a DOM element with name ' + btnName); continue; } ele.style.display = btnsToEnable[btnName] ? '' : 'none'; } }; ButtonPanel.prototype.buildDropDown = function (data) { var flag; var doc = this.P2.doc; var ele = doc.getElementById(this.name + 'ButtonList'); if (!ele) { debug('DESIGN ERROR: Button Panel ' + this.name + ' has not produced a drop-down boc with name = ' + this.Name + 'ButtonList'); return; } //zap options first ele.innerHTML = ''; //that took away the first one also. Add a blank option var option = doc.createElement('option'); ele.appendChild(option); //this.buttons has all the button names defined for this panel with value = 'disabled' // i.e. this.buttons['button1'] = 'disabled'; // for the rows that are in data, mark them as enabled. var n = data.length; if (n <= 1) return; if ((n == 2) && (data[0].length > 1)) { var hasFlag = data[0].length > 1; for (var i = 0; i < data[0].length; i++) { if (hasFlag) { flag = data[1][i]; if (!flag || flag == '0') continue; } var btnName = data[0][i]; var btn = this.buttons[btnName]; if (!btn) { debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button'); continue; } option = doc.createElement('option'); option.value = btn.actionName; option.innerHTML = btn.label; ele.appendChild(option); } } else { var hasFlag = data[0].length > 1; for (var i = 1; i < n; i++) { if (hasFlag) { flag = data[i][1]; if (!flag || flag == '0') continue; } var btnName = data[i][0]; var btn = this.buttons[btnName]; if (!btn) { debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button'); continue; } option = doc.createElement('option'); option.value = btn.actionName; option.innerHTML = btn.label; ele.appendChild(option); } } }; //Standard way of getting data from server is a grid with first row as header row and rest a data rows. //But it is possible that server may send button names in first row, and optional second row as enable flag. //We detect the second case, and transpose the grid, so that a common logic can be used. ButtonPanel.prototype.transposeIfRequired = function (data) { //we need to transpose only if we have one or two rows var nbrRows = data && data.length; if (!nbrRows || nbrRows > 2) return data; var row = data[0]; var nbrCols = row.length; if (!nbrCols) return data; //We make a simple assumption, that the label for last column can not clash with the name of a button. if (!this.buttons[row[nbrCols - 1]]) return data; //we transpose the grid, with an empty header row var newData = null; if (data.length == 1) //button name only { newData = [['']]; for (var i = 0; i < nbrCols; i++) newData.push([row[i]]); } else { //button name with enable flag newData = [['', '']]; var row1 = data[1]; for (var i = 0; i < nbrCols; i++) newData.push([row[i], row1[i]]); } return newData; };
/* function Canvas(paper, props){ var props = $.extend(true, { "x" : 0, "y" : 0, "width" : "100%", "height" : "100%" }, (props || {})), _scale = 1, _translateX = 0, _translateY = 0, self = this, lx = 0, ly = 0, ox = 0, oy = 0, canvasBg = paper.rect(props.x, props.y, props.width, props.height), canvas = paper.group(), elements = [] ; var moveFnc = function(dx, dy){ lx = dx * (1 / _scale) + ox; ly = dy * (1 / _scale) + oy; self.setTranslate(lx, ly); }, startFnc = function(){ var transform = canvasBg.transform(); for(var i = 0; i < transform.length; i++){ if(transform[i][0].toLowerCase() === "t"){ ox = parseInt(transform[i][1]) * _scale; oy = parseInt(transform[i][2]) * _scale; } } }, endFnc = function(){ ox = lx; oy = ly; }, applyTransform = function(){ canvas.transform("s" + _scale + "t" + _translateX + "," + _translateY); canvasBg.transform("s" + _scale + "t" + _translateX + "," + _translateY); } ; this.add = function(el){ canvas.add(el.getObj()); elements.push(el); return this; }; this.setTranslate = function(x, y){ _translateX = x; _translateY = y; applyTransform(); return this; }; this.getTranslate = function(){ return { "x" : _translateX, "y" : _translateY }; }; this.setScale = function(s, onEachElement){ _scale = s; applyTransform(); if(onEachElement){ for(var i = 0; i < elements.length; i++){ onEachElement(elements[i], s); } } return this; }; this.getScale = function(){ return _scale; }; this.getProps = function(){ return props; }; canvasBg.attr({ "fill" : "rgba(255, 255, 0, .5)", "stroke" : "#000000", "stroke-width" : 1 }); this .setTranslate(0, 0) .setScale(1) ; canvasBg.drag(moveFnc, startFnc, endFnc); } */
/* * Copyright (c) 2014 airbug inc. http://airbug.com * * bugpack-registry may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Requires //------------------------------------------------------------------------------- var buildbug = require("buildbug"); //------------------------------------------------------------------------------- // Simplify References //------------------------------------------------------------------------------- var buildProject = buildbug.buildProject; var buildProperties = buildbug.buildProperties; var buildScript = buildbug.buildScript; var buildTarget = buildbug.buildTarget; var enableModule = buildbug.enableModule; var parallel = buildbug.parallel; var series = buildbug.series; var targetTask = buildbug.targetTask; //------------------------------------------------------------------------------- // Enable Modules //------------------------------------------------------------------------------- var aws = enableModule("aws"); var bugpack = enableModule('bugpack'); var bugunit = enableModule('bugunit'); var core = enableModule('core'); var lintbug = enableModule("lintbug"); var nodejs = enableModule('nodejs'); var uglifyjs = enableModule("uglifyjs"); //------------------------------------------------------------------------------- // Values //------------------------------------------------------------------------------- var name = "bugpack-registry"; var version = "0.1.7"; var dependencies = { bugpack: "0.2.2" }; //------------------------------------------------------------------------------- // Declare Properties //------------------------------------------------------------------------------- buildProperties({ name: name, version: version }); buildProperties({ node: { packageJson: { name: "{{name}}", version: "{{version}}", description: "Registry builder for the bugpack package loader", main: "./scripts/bugpack-registry-node.js", author: "Brian Neisler <[email protected]>", dependencies: dependencies, repository: { type: "git", url: "https://github.com/airbug/bugpack.git" }, bugs: { url: "https://github.com/airbug/bugpack/issues" }, licenses: [ { type : "MIT", url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE" } ] }, sourcePaths: [ "../buganno/libraries/buganno/js/src", "../bugcore/libraries/bugcore/js/src", "../bugfs/libraries/bugfs/js/src", "../bugmeta/libraries/bugmeta/js/src", "./libraries/bugpack-registry/js/src" ], scriptPaths: [ "../buganno/libraries/buganno/js/scripts", "./projects/bugpack-registry-node/js/scripts" ], readmePath: "./README.md", unitTest: { packageJson: { name: "{{name}}-test", version: "{{version}}", main: "./scripts/bugpack-registry-node.js", dependencies: dependencies, scripts: { test: "node ./test/scripts/bugunit-run.js" } }, sourcePaths: [ "../bugdouble/libraries/bugdouble/js/src", "../bugunit/libraries/bugunit/js/src", "../bugyarn/libraries/bugyarn/js/src" ], scriptPaths: [ "../bugunit/libraries/bugunit/js/scripts" ], testPaths: [ "../buganno/libraries/buganno/js/test", "../bugcore/libraries/bugcore/js/test", "../bugfs/libraries/bugfs/js/test", "../bugmeta/libraries/bugmeta/js/test", "./libraries/bugpack-registry/js/test" ] } }, lint: { targetPaths: [ "." ], ignorePatterns: [ ".*\\.buildbug$", ".*\\.bugunit$", ".*\\.git$", ".*node_modules$" ] } }); //------------------------------------------------------------------------------- // BuildTargets //------------------------------------------------------------------------------- // Clean BuildTarget //------------------------------------------------------------------------------- buildTarget("clean").buildFlow( targetTask("clean") ); // Local BuildTarget //------------------------------------------------------------------------------- buildTarget("local").buildFlow( series([ targetTask("clean"), targetTask('lint', { properties: { targetPaths: buildProject.getProperty("lint.targetPaths"), ignores: buildProject.getProperty("lint.ignorePatterns"), lintTasks: [ "cleanupExtraSpacingAtEndOfLines", "ensureNewLineEnding", "indentEqualSignsForPreClassVars", "orderBugpackRequires", "orderRequireAnnotations", "updateCopyright" ] } }), parallel([ series([ targetTask("createNodePackage", { properties: { packageJson: buildProject.getProperty("node.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths").concat( buildProject.getProperty("node.unitTest.sourcePaths") ), "./scripts": buildProject.getProperty("node.scriptPaths").concat( buildProject.getProperty("node.unitTest.scriptPaths") ), "./test": buildProject.getProperty("node.unitTest.testPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask("packNodePackage", { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }), targetTask('startNodeModuleTests', { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ modulePath: packedNodePackage.getFilePath() }); } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: 'public-read', encrypt: true } }); }, properties: { bucket: "{{local-bucket}}" } }) ]) ]) ]) ).makeDefault(); // Prod BuildTarget //------------------------------------------------------------------------------- buildTarget("prod").buildFlow( series([ targetTask("clean"), targetTask('lint', { properties: { targetPaths: buildProject.getProperty("lint.targetPaths"), ignores: buildProject.getProperty("lint.ignorePatterns"), lintTasks: [ "cleanupExtraSpacingAtEndOfLines", "ensureNewLineEnding", "indentEqualSignsForPreClassVars", "orderBugpackRequires", "orderRequireAnnotations", "updateCopyright" ] } }), parallel([ //Create test bugpack-registry package series([ targetTask('createNodePackage', { properties: { packageJson: buildProject.getProperty("node.unitTest.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths").concat( buildProject.getProperty("node.unitTest.sourcePaths") ), "./scripts": buildProject.getProperty("node.scriptPaths").concat( buildProject.getProperty("node.unitTest.scriptPaths") ), "./test": buildProject.getProperty("node.unitTest.testPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.unitTest.packageJson.name"), buildProject.getProperty("node.unitTest.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask('packNodePackage', { properties: { packageName: "{{node.unitTest.packageJson.name}}", packageVersion: "{{node.unitTest.packageJson.version}}" } }), targetTask('startNodeModuleTests', { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage( buildProject.getProperty("node.unitTest.packageJson.name"), buildProject.getProperty("node.unitTest.packageJson.version") ); task.updateProperties({ modulePath: packedNodePackage.getFilePath(), checkCoverage: true }); } }) ]), // Create production bugpack-registry package series([ targetTask('createNodePackage', { properties: { packageJson: buildProject.getProperty("node.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths"), "./scripts": buildProject.getProperty("node.scriptPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask('packNodePackage', { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: 'public-read', encrypt: true } }); }, properties: { bucket: "{{prod-deploy-bucket}}" } }), targetTask('npmConfigSet', { properties: { config: buildProject.getProperty("npmConfig") } }), targetTask('npmAddUser'), targetTask('publishNodePackage', { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }) ]) ]) ]) ); //------------------------------------------------------------------------------- // Build Scripts //------------------------------------------------------------------------------- buildScript({ dependencies: [ "bugcore", "bugflow", "bugfs" ], script: "./lintbug.js" });
export default function(that) { return !isNaN(that.curValue) && that.curValue%1===0; }
'use strict'; angular.module('core').controller('SidebarController', ['$scope', 'Authentication', function($scope, Authentication) { $scope.authentication = Authentication; } ]);
import superagent from 'superagent'; import config from '../config'; const { NODE_ENV } = process.env; const methods = ['get', 'post', 'put', 'patch', 'del']; function formatUrl(path) { const adjustedPath = path[0] !== '/' ? '/' + path : path; if (__SERVER__ || NODE_ENV === 'production') { return `${config.apiHost}/v1${adjustedPath}` } return '/api' + adjustedPath; } export default class ApiClient { constructor() { methods.forEach((method) => this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } // if (__SERVER__ && req.get('cookie')) { // request.set('cookie', req.get('cookie')); // } if (data) { request.send(data); } if (__CLIENT__ && window.localStorage.authToken) { request.set('authorization', window.localStorage.authToken) } request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body)); })); } /* * There's a V8 bug where, when using Babel, exporting classes with only * constructors sometimes fails. Until it's patched, this is a solution to * "ApiClient is not defined" from issue #14. * https://github.com/erikras/react-redux-universal-hot-example/issues/14 * * Relevant Babel bug (but they claim it's V8): https://phabricator.babeljs.io/T2455 * * Remove it at your own risk. */ empty() {} }
version https://git-lfs.github.com/spec/v1 oid sha256:bd24e43ef20f9f9e3c711e3d54df98d049591993ab374dbc14fbe801ba528183 size 10061
module.exports = { snowboy: { models: { file: "node_modules/snowboy/resources/snowboy.umdl", sensitivity: "0.5", hotwords: "snowboy" }, detector: { resource: "node_modules/snowboy/resources/common.res", audioGain: 2.0 } } };
var jshint = require('jshint').JSHINT, colors = require('colors'); module.exports = function(code) { var options = { devel: true, node: true, predef: ['expect', 'done'], undef: true }, isValid = jshint(code, options); if (!isValid) { var errorsByLineNumber = {}; jshint.errors.map(function(error) { errorsByLineNumber[error.line] = error.reason; }); code.split('\n').forEach(function(line, index) { var lineNumber = index + 1; if (errorsByLineNumber[lineNumber]) { line = line.yellow + '\t' + ('// ERROR: ' + errorsByLineNumber[lineNumber]).red } console.log(line); }); } return isValid; };
/** * ghostHunter - 0.4.0 * Copyright (C) 2014 Jamal Neufeld ([email protected]) * MIT Licensed * @license */ (function( $ ) { /* Include the Lunr library */ var lunr=require('./lunr.min.js'); //This is the main plugin definition $.fn.ghostHunter = function( options ) { //Here we use jQuery's extend to set default values if they weren't set by the user var opts = $.extend( {}, $.fn.ghostHunter.defaults, options ); if( opts.results ) { pluginMethods.init( this , opts ); return pluginMethods; } }; $.fn.ghostHunter.defaults = { resultsData : false, onPageLoad : true, onKeyUp : false, result_template : "<a href='{{link}}'><p><h2>{{title}}</h2><h4>{{prettyPubDate}}</h4></p></a>", info_template : "<p>Number of posts found: {{amount}}</p>", displaySearchInfo : true, zeroResultsInfo : true, before : false, onComplete : false, includepages : false, filterfields : false }; var prettyDate = function(date) { var d = new Date(date); var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear(); }; var pluginMethods = { isInit : false, init : function( target , opts ){ var that = this; this.target = target; this.results = opts.results; this.blogData = {}; this.result_template = opts.result_template; this.info_template = opts.info_template; this.zeroResultsInfo = opts.zeroResultsInfo; this.displaySearchInfo = opts.displaySearchInfo; this.before = opts.before; this.onComplete = opts.onComplete; this.includepages = opts.includepages; this.filterfields = opts.filterfields; //This is where we'll build the index for later searching. It's not a big deal to build it on every load as it takes almost no space without data this.index = lunr(function () { this.field('title', {boost: 10}) this.field('description') this.field('link') this.field('plaintext', {boost: 5}) this.field('pubDate') this.field('tag') this.ref('id') }); if ( opts.onPageLoad ) { function miam () { that.loadAPI(); } window.setTimeout(miam, 1); } else { target.focus(function(){ that.loadAPI(); }); } target.closest("form").submit(function(e){ e.preventDefault(); that.find(target.val()); }); if( opts.onKeyUp ) { target.keyup(function() { that.find(target.val()); }); } }, loadAPI : function(){ if(this.isInit) return false; /* Here we load all of the blog posts to the index. This function will not call on load to avoid unnecessary heavy operations on a page if a visitor never ends up searching anything. */ var index = this.index, blogData = this.blogData; obj = {limit: "all", include: "tags", formats:["plaintext"]}; if ( this.includepages ){ obj.filter="(page:true,page:false)"; } $.get(ghost.url.api('posts',obj)).done(function(data){ searchData = data.posts; searchData.forEach(function(arrayItem){ var tag_arr = arrayItem.tags.map(function(v) { return v.name; // `tag` object has an `name` property which is the value of tag. If you also want other info, check API and get that property }) if(arrayItem.meta_description == null) { arrayItem.meta_description = '' }; var category = tag_arr.join(", "); if (category.length < 1){ category = "undefined"; } var parsedData = { id : String(arrayItem.id), title : String(arrayItem.title), description : String(arrayItem.meta_description), plaintext : String(arrayItem.plaintext), pubDate : String(arrayItem.created_at), tag : category, featureImage : String(arrayItem.feature_image), link : String(arrayItem.url) } parsedData.prettyPubDate = prettyDate(parsedData.pubDate); var tempdate = prettyDate(parsedData.pubDate); index.add(parsedData) blogData[arrayItem.id] = { title: arrayItem.title, description: arrayItem.meta_description, pubDate: tempdate, featureImage: arrayItem.feature_image, link: arrayItem.url }; }); }); this.isInit = true; }, find : function(value){ var searchResult = this.index.search(value); var results = $(this.results); var resultsData = []; results.empty(); if(this.before) { this.before(); }; if(this.zeroResultsInfo || searchResult.length > 0) { if(this.displaySearchInfo) results.append(this.format(this.info_template,{"amount":searchResult.length})); } for (var i = 0; i < searchResult.length; i++) { var lunrref = searchResult[i].ref; var postData = this.blogData[lunrref]; results.append(this.format(this.result_template,postData)); resultsData.push(postData); } if(this.onComplete) { this.onComplete(resultsData); }; }, clear : function(){ $(this.results).empty(); this.target.val(""); }, format : function (t, d) { return t.replace(/{{([^{}]*)}}/g, function (a, b) { var r = d[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); } } })( jQuery );
import React, { PropTypes, } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; const styles = StyleSheet.create({ all: { paddingHorizontal: 10, paddingVertical: 5, }, text: { fontSize: 12, color: '#666', }, }); function ListItemTitle(props) { return ( <View style={styles.all}> <Text style={styles.text} > {props.text} </Text> </View> ); } ListItemTitle.propTypes = { text: PropTypes.string, }; ListItemTitle.defaultProps = { text: '', }; export default ListItemTitle;
import axios from 'axios'; import {getAuthInfo} from './firebase-service'; import {VIANCA, CHAN, TOPA, IBA_COLOMBIA} from './service-store'; export const ERROR_RESULT = 'ERROR'; export const RESERVED_RESULT = 'R'; export const INSUFICIENT_RESULT = 'I'; export const NOT_FOUND_RESULT = 'NF'; export function submitReserve(reserve, airlineCode) { let _this = this; let apiUrl = getAirlineUrl(airlineCode); reserve.token = getAuthInfo().idToken; return axios.post(apiUrl, reserve).then(result => { if (!result.message) { console.error("No \"message\" attribute in result: ", result) return ERROR_RESULT; } return result.message; }).catch(error => console.log(error)); } function getAirlineUrl(airlineCode) { switch (airlineCode) { case VIANCA.code: return VIANCA.submitReserveUrl; case CHAN.code: return CHAN.submitReserveUrl; case TOPA.code: return TOPA.submitReserveUrl; case IBA_COLOMBIA.code: return IBA_COLOMBIA.submitReserveUrl; default: } } export function searchForReserve(apiUrl) { let _this = this; let url = apiUrl + '?token=' + getAuthInfo().idToken; // + getToken(); return axios.get(url); } export function submitAllReserveSearch() { console.log('Fetching reserve searchs'); let viancaResult = searchForReserve(VIANCA.fetchReserves); let chanResult = searchForReserve(CHAN.fetchReserves); let topaResult = searchForReserve(TOPA.fetchReserves); let ibaResult = searchForReserve(IBA_COLOMBIA.fetchReserves); let mergedResults = axios.all([viancaResult, chanResult, topaResult, ibaResult]); return mergedResults; }
import { DESCRIPTORS, LITTLE_ENDIAN } from '../helpers/constants'; if (DESCRIPTORS) QUnit.test('Int32 conversions', assert => { const int32array = new Int32Array(1); const uint8array = new Uint8Array(int32array.buffer); const dataview = new DataView(int32array.buffer); function viewFrom(it) { return new DataView(new Uint8Array(it).buffer); } function toString(it) { return it === 0 && 1 / it === -Infinity ? '-0' : it; } const data = [ [0, 0, [0, 0, 0, 0]], [-0, 0, [0, 0, 0, 0]], [1, 1, [1, 0, 0, 0]], [-1, -1, [255, 255, 255, 255]], [1.1, 1, [1, 0, 0, 0]], [-1.1, -1, [255, 255, 255, 255]], [1.9, 1, [1, 0, 0, 0]], [-1.9, -1, [255, 255, 255, 255]], [127, 127, [127, 0, 0, 0]], [-127, -127, [129, 255, 255, 255]], [128, 128, [128, 0, 0, 0]], [-128, -128, [128, 255, 255, 255]], [255, 255, [255, 0, 0, 0]], [-255, -255, [1, 255, 255, 255]], [255.1, 255, [255, 0, 0, 0]], [255.9, 255, [255, 0, 0, 0]], [256, 256, [0, 1, 0, 0]], [32767, 32767, [255, 127, 0, 0]], [-32767, -32767, [1, 128, 255, 255]], [32768, 32768, [0, 128, 0, 0]], [-32768, -32768, [0, 128, 255, 255]], [65535, 65535, [255, 255, 0, 0]], [65536, 65536, [0, 0, 1, 0]], [65537, 65537, [1, 0, 1, 0]], [65536.54321, 65536, [0, 0, 1, 0]], [-65536.54321, -65536, [0, 0, 255, 255]], [2147483647, 2147483647, [255, 255, 255, 127]], [-2147483647, -2147483647, [1, 0, 0, 128]], [2147483648, -2147483648, [0, 0, 0, 128]], [-2147483648, -2147483648, [0, 0, 0, 128]], [2147483649, -2147483647, [1, 0, 0, 128]], [-2147483649, 2147483647, [255, 255, 255, 127]], [4294967295, -1, [255, 255, 255, 255]], [4294967296, 0, [0, 0, 0, 0]], [4294967297, 1, [1, 0, 0, 0]], [9007199254740991, -1, [255, 255, 255, 255]], [-9007199254740991, 1, [1, 0, 0, 0]], [9007199254740992, 0, [0, 0, 0, 0]], [-9007199254740992, 0, [0, 0, 0, 0]], [9007199254740994, 2, [2, 0, 0, 0]], [-9007199254740994, -2, [254, 255, 255, 255]], [Infinity, 0, [0, 0, 0, 0]], [-Infinity, 0, [0, 0, 0, 0]], [-1.7976931348623157e+308, 0, [0, 0, 0, 0]], [1.7976931348623157e+308, 0, [0, 0, 0, 0]], [5e-324, 0, [0, 0, 0, 0]], [-5e-324, 0, [0, 0, 0, 0]], [NaN, 0, [0, 0, 0, 0]], ]; for (const [value, conversion, little] of data) { const big = little.slice().reverse(); const representation = LITTLE_ENDIAN ? little : big; int32array[0] = value; assert.same(int32array[0], conversion, `Int32Array ${ toString(value) } -> ${ toString(conversion) }`); assert.arrayEqual(uint8array, representation, `Int32Array ${ toString(value) } -> [${ representation }]`); dataview.setInt32(0, value); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0), conversion, `dataview{${ big }}.getInt32(0) -> ${ toString(conversion) }`); dataview.setInt32(0, value, false); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }, false) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0, false), conversion, `dataview{${ big }}.getInt32(0, false) -> ${ toString(conversion) }`); dataview.setInt32(0, value, true); assert.arrayEqual(uint8array, little, `dataview.setInt32(0, ${ toString(value) }, true) -> [${ little }]`); assert.same(viewFrom(little).getInt32(0, true), conversion, `dataview{${ little }}.getInt32(0, true) -> ${ toString(conversion) }`); } });
/** * NOTE: We are in the process of migrating these tests to Mocha. If you are * adding a new test, consider creating a new spec file in mocha_tests/ */ var async = require('../lib/async'); if (!Function.prototype.bind) { Function.prototype.bind = function (thisArg) { var args = Array.prototype.slice.call(arguments, 1); var self = this; return function () { self.apply(thisArg, args.concat(Array.prototype.slice.call(arguments))); }; }; } function eachIterator(args, x, callback) { setTimeout(function(){ args.push(x); callback(); }, x*25); } function forEachOfIterator(args, value, key, callback) { setTimeout(function(){ args.push(key, value); callback(); }, value*25); } function mapIterator(call_order, x, callback) { setTimeout(function(){ call_order.push(x); callback(null, x*2); }, x*25); } function filterIterator(x, callback) { setTimeout(function(){ callback(x % 2); }, x*25); } function detectIterator(call_order, x, callback) { setTimeout(function(){ call_order.push(x); callback(x == 2); }, x*25); } function eachNoCallbackIterator(test, x, callback) { test.equal(x, 1); callback(); test.done(); } function forEachOfNoCallbackIterator(test, x, key, callback) { test.equal(x, 1); test.equal(key, "a"); callback(); test.done(); } function getFunctionsObject(call_order) { return { one: function(callback){ setTimeout(function(){ call_order.push(1); callback(null, 1); }, 125); }, two: function(callback){ setTimeout(function(){ call_order.push(2); callback(null, 2); }, 200); }, three: function(callback){ setTimeout(function(){ call_order.push(3); callback(null, 3,3); }, 50); } }; } function isBrowser() { return (typeof process === "undefined") || (process + "" !== "[object process]"); // browserify } exports['applyEach'] = function (test) { test.expect(5); var call_order = []; var one = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('one'); cb(null, 1); }, 100); }; var two = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('two'); cb(null, 2); }, 50); }; var three = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('three'); cb(null, 3); }, 150); }; async.applyEach([one, two, three], 5, function (err) { test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, ['two', 'one', 'three']); test.done(); }); }; exports['applyEachSeries'] = function (test) { test.expect(5); var call_order = []; var one = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('one'); cb(null, 1); }, 100); }; var two = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('two'); cb(null, 2); }, 50); }; var three = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('three'); cb(null, 3); }, 150); }; async.applyEachSeries([one, two, three], 5, function (err) { test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, ['one', 'two', 'three']); test.done(); }); }; exports['applyEach partial application'] = function (test) { test.expect(4); var call_order = []; var one = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('one'); cb(null, 1); }, 100); }; var two = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('two'); cb(null, 2); }, 50); }; var three = function (val, cb) { test.equal(val, 5); setTimeout(function () { call_order.push('three'); cb(null, 3); }, 150); }; async.applyEach([one, two, three])(5, function (err) { if (err) throw err; test.same(call_order, ['two', 'one', 'three']); test.done(); }); }; exports['seq'] = function (test) { test.expect(5); var add2 = function (n, cb) { test.equal(n, 3); setTimeout(function () { cb(null, n + 2); }, 50); }; var mul3 = function (n, cb) { test.equal(n, 5); setTimeout(function () { cb(null, n * 3); }, 15); }; var add1 = function (n, cb) { test.equal(n, 15); setTimeout(function () { cb(null, n + 1); }, 100); }; var add2mul3add1 = async.seq(add2, mul3, add1); add2mul3add1(3, function (err, result) { if (err) { return test.done(err); } test.ok(err === null, err + " passed instead of 'null'"); test.equal(result, 16); test.done(); }); }; exports['seq error'] = function (test) { test.expect(3); var testerr = new Error('test'); var add2 = function (n, cb) { test.equal(n, 3); setTimeout(function () { cb(null, n + 2); }, 50); }; var mul3 = function (n, cb) { test.equal(n, 5); setTimeout(function () { cb(testerr); }, 15); }; var add1 = function (n, cb) { test.ok(false, 'add1 should not get called'); setTimeout(function () { cb(null, n + 1); }, 100); }; var add2mul3add1 = async.seq(add2, mul3, add1); add2mul3add1(3, function (err) { test.equal(err, testerr); test.done(); }); }; exports['seq binding'] = function (test) { test.expect(4); var testcontext = {name: 'foo'}; var add2 = function (n, cb) { test.equal(this, testcontext); setTimeout(function () { cb(null, n + 2); }, 50); }; var mul3 = function (n, cb) { test.equal(this, testcontext); setTimeout(function () { cb(null, n * 3); }, 15); }; var add2mul3 = async.seq(add2, mul3); add2mul3.call(testcontext, 3, function (err, result) { if (err) { return test.done(err); } test.equal(this, testcontext); test.equal(result, 15); test.done(); }); }; exports['seq without callback'] = function (test) { test.expect(2); var testcontext = {name: 'foo'}; var add2 = function (n, cb) { test.equal(this, testcontext); setTimeout(function () { cb(null, n + 2); }, 50); }; var mul3 = function () { test.equal(this, testcontext); setTimeout(function () { test.done(); }, 15); }; var add2mul3 = async.seq(add2, mul3); add2mul3.call(testcontext, 3); }; exports['auto'] = function(test){ var callOrder = []; async.auto({ task1: ['task2', function(callback){ setTimeout(function(){ callOrder.push('task1'); callback(); }, 25); }], task2: function(callback){ setTimeout(function(){ callOrder.push('task2'); callback(); }, 50); }, task3: ['task2', function(callback){ callOrder.push('task3'); callback(); }], task4: ['task1', 'task2', function(callback){ callOrder.push('task4'); callback(); }], task5: ['task2', function(callback){ setTimeout(function(){ callOrder.push('task5'); callback(); }, 0); }], task6: ['task2', function(callback){ callOrder.push('task6'); callback(); }] }, function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(callOrder, ['task2','task6','task3','task5','task1','task4']); test.done(); }); }; exports['auto concurrency'] = function (test) { var concurrency = 2; var runningTasks = []; var makeCallback = function(taskName) { return function(callback) { runningTasks.push(taskName); setTimeout(function(){ // Each task returns the array of running tasks as results. var result = runningTasks.slice(0); runningTasks.splice(runningTasks.indexOf(taskName), 1); callback(null, result); }); }; }; async.auto({ task1: ['task2', makeCallback('task1')], task2: makeCallback('task2'), task3: ['task2', makeCallback('task3')], task4: ['task1', 'task2', makeCallback('task4')], task5: ['task2', makeCallback('task5')], task6: ['task2', makeCallback('task6')] }, concurrency, function(err, results){ Object.keys(results).forEach(function(taskName) { test.ok(results[taskName].length <= concurrency); }); test.done(); }); }; exports['auto petrify'] = function (test) { var callOrder = []; async.auto({ task1: ['task2', function (callback) { setTimeout(function () { callOrder.push('task1'); callback(); }, 100); }], task2: function (callback) { setTimeout(function () { callOrder.push('task2'); callback(); }, 200); }, task3: ['task2', function (callback) { callOrder.push('task3'); callback(); }], task4: ['task1', 'task2', function (callback) { callOrder.push('task4'); callback(); }] }, function (err) { if (err) throw err; test.same(callOrder, ['task2', 'task3', 'task1', 'task4']); test.done(); }); }; exports['auto results'] = function(test){ var callOrder = []; async.auto({ task1: ['task2', function(callback, results){ test.same(results.task2, 'task2'); setTimeout(function(){ callOrder.push('task1'); callback(null, 'task1a', 'task1b'); }, 25); }], task2: function(callback){ setTimeout(function(){ callOrder.push('task2'); callback(null, 'task2'); }, 50); }, task3: ['task2', function(callback, results){ test.same(results.task2, 'task2'); callOrder.push('task3'); callback(null); }], task4: ['task1', 'task2', function(callback, results){ test.same(results.task1, ['task1a','task1b']); test.same(results.task2, 'task2'); callOrder.push('task4'); callback(null, 'task4'); }] }, function(err, results){ test.same(callOrder, ['task2','task3','task1','task4']); test.same(results, {task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'}); test.done(); }); }; exports['auto empty object'] = function(test){ async.auto({}, function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.done(); }); }; exports['auto error'] = function(test){ test.expect(1); async.auto({ task1: function(callback){ callback('testerror'); }, task2: ['task1', function(callback){ test.ok(false, 'task2 should not be called'); callback(); }], task3: function(callback){ callback('testerror2'); } }, function(err){ test.equals(err, 'testerror'); }); setTimeout(test.done, 100); }; exports['auto no callback'] = function(test){ async.auto({ task1: function(callback){callback();}, task2: ['task1', function(callback){callback(); test.done();}] }); }; exports['auto concurrency no callback'] = function(test){ async.auto({ task1: function(callback){callback();}, task2: ['task1', function(callback){callback(); test.done();}] }, 1); }; exports['auto error should pass partial results'] = function(test) { async.auto({ task1: function(callback){ callback(false, 'result1'); }, task2: ['task1', function(callback){ callback('testerror', 'result2'); }], task3: ['task2', function(){ test.ok(false, 'task3 should not be called'); }] }, function(err, results){ test.equals(err, 'testerror'); test.equals(results.task1, 'result1'); test.equals(results.task2, 'result2'); test.done(); }); }; // Issue 24 on github: https://github.com/caolan/async/issues#issue/24 // Issue 76 on github: https://github.com/caolan/async/issues#issue/76 exports['auto removeListener has side effect on loop iterator'] = function(test) { async.auto({ task1: ['task3', function(/*callback*/) { test.done(); }], task2: ['task3', function(/*callback*/) { /* by design: DON'T call callback */ }], task3: function(callback) { callback(); } }); }; // Issue 410 on github: https://github.com/caolan/async/issues/410 exports['auto calls callback multiple times'] = function(test) { if (isBrowser()) { // node only test test.done(); return; } var finalCallCount = 0; var domain = require('domain').create(); domain.on('error', function (e) { // ignore test error if (!e._test_error) { return test.done(e); } }); domain.run(function () { async.auto({ task1: function(callback) { callback(null); }, task2: ['task1', function(callback) { callback(null); }] }, // Error throwing final callback. This should only run once function() { finalCallCount++; var e = new Error("An error"); e._test_error = true; throw e; }); }); setTimeout(function () { test.equal(finalCallCount, 1, "Final auto callback should only be called once" ); test.done(); }, 10); }; exports['auto calls callback multiple times with parallel functions'] = function(test) { test.expect(1); async.auto({ task1: function(callback) { setTimeout(callback,0,"err"); }, task2: function(callback) { setTimeout(callback,0,"err"); } }, // Error throwing final callback. This should only run once function(err) { test.equal(err, "err"); test.done(); }); }; // Issue 462 on github: https://github.com/caolan/async/issues/462 exports['auto modifying results causes final callback to run early'] = function(test) { async.auto({ task1: function(callback, results){ results.inserted = true; callback(null, 'task1'); }, task2: function(callback){ setTimeout(function(){ callback(null, 'task2'); }, 50); }, task3: function(callback){ setTimeout(function(){ callback(null, 'task3'); }, 100); } }, function(err, results){ test.equal(results.inserted, true); test.ok(results.task3, 'task3'); test.done(); }); }; // Issue 263 on github: https://github.com/caolan/async/issues/263 exports['auto prevent dead-locks due to inexistant dependencies'] = function(test) { test.throws(function () { async.auto({ task1: ['noexist', function(callback){ callback(null, 'task1'); }] }); }, Error); test.done(); }; // Issue 263 on github: https://github.com/caolan/async/issues/263 exports['auto prevent dead-locks due to cyclic dependencies'] = function(test) { test.throws(function () { async.auto({ task1: ['task2', function(callback){ callback(null, 'task1'); }], task2: ['task1', function(callback){ callback(null, 'task2'); }] }); }, Error); test.done(); }; // Issue 306 on github: https://github.com/caolan/async/issues/306 exports['retry when attempt succeeds'] = function(test) { var failed = 3; var callCount = 0; var expectedResult = 'success'; function fn(callback) { callCount++; failed--; if (!failed) callback(null, expectedResult); else callback(true); // respond with error } async.retry(fn, function(err, result){ test.ok(err === null, err + " passed instead of 'null'"); test.equal(callCount, 3, 'did not retry the correct number of times'); test.equal(result, expectedResult, 'did not return the expected result'); test.done(); }); }; exports['retry when all attempts succeeds'] = function(test) { var times = 3; var callCount = 0; var error = 'ERROR'; var erroredResult = 'RESULT'; function fn(callback) { callCount++; callback(error + callCount, erroredResult + callCount); // respond with indexed values } async.retry(times, fn, function(err, result){ test.equal(callCount, 3, "did not retry the correct number of times"); test.equal(err, error + times, "Incorrect error was returned"); test.equal(result, erroredResult + times, "Incorrect result was returned"); test.done(); }); }; exports['retry fails with invalid arguments'] = function(test) { test.throws(function() { async.retry(""); }); test.throws(function() { async.retry(); }); test.throws(function() { async.retry(function() {}, 2, function() {}); }); test.done(); }; exports['retry with interval when all attempts succeeds'] = function(test) { var times = 3; var interval = 500; var callCount = 0; var error = 'ERROR'; var erroredResult = 'RESULT'; function fn(callback) { callCount++; callback(error + callCount, erroredResult + callCount); // respond with indexed values } var start = new Date().getTime(); async.retry({ times: times, interval: interval}, fn, function(err, result){ var now = new Date().getTime(); var duration = now - start; test.ok(duration > (interval * (times -1)), 'did not include interval'); test.equal(callCount, 3, "did not retry the correct number of times"); test.equal(err, error + times, "Incorrect error was returned"); test.equal(result, erroredResult + times, "Incorrect result was returned"); test.done(); }); }; exports['retry as an embedded task'] = function(test) { var retryResult = 'RETRY'; var fooResults; var retryResults; async.auto({ foo: function(callback, results){ fooResults = results; callback(null, 'FOO'); }, retry: async.retry(function(callback, results) { retryResults = results; callback(null, retryResult); }) }, function(err, results){ test.equal(results.retry, retryResult, "Incorrect result was returned from retry function"); test.equal(fooResults, retryResults, "Incorrect results were passed to retry function"); test.done(); }); }; exports['retry as an embedded task with interval'] = function(test) { var start = new Date().getTime(); var opts = {times: 5, interval: 100}; async.auto({ foo: function(callback){ callback(null, 'FOO'); }, retry: async.retry(opts, function(callback) { callback('err'); }) }, function(){ var duration = new Date().getTime() - start; var expectedMinimumDuration = (opts.times -1) * opts.interval; test.ok(duration >= expectedMinimumDuration, "The duration should have been greater than " + expectedMinimumDuration + ", but was " + duration); test.done(); }); }; exports['waterfall'] = { 'basic': function(test){ test.expect(7); var call_order = []; async.waterfall([ function(callback){ call_order.push('fn1'); setTimeout(function(){callback(null, 'one', 'two');}, 0); }, function(arg1, arg2, callback){ call_order.push('fn2'); test.equals(arg1, 'one'); test.equals(arg2, 'two'); setTimeout(function(){callback(null, arg1, arg2, 'three');}, 25); }, function(arg1, arg2, arg3, callback){ call_order.push('fn3'); test.equals(arg1, 'one'); test.equals(arg2, 'two'); test.equals(arg3, 'three'); callback(null, 'four'); }, function(arg4, callback){ call_order.push('fn4'); test.same(call_order, ['fn1','fn2','fn3','fn4']); callback(null, 'test'); } ], function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.done(); }); }, 'empty array': function(test){ async.waterfall([], function(err){ if (err) throw err; test.done(); }); }, 'non-array': function(test){ async.waterfall({}, function(err){ test.equals(err.message, 'First argument to waterfall must be an array of functions'); test.done(); }); }, 'no callback': function(test){ async.waterfall([ function(callback){callback();}, function(callback){callback(); test.done();} ]); }, 'async': function(test){ var call_order = []; async.waterfall([ function(callback){ call_order.push(1); callback(); call_order.push(2); }, function(callback){ call_order.push(3); callback(); }, function(){ test.same(call_order, [1,2,3]); test.done(); } ]); }, 'error': function(test){ test.expect(1); async.waterfall([ function(callback){ callback('error'); }, function(callback){ test.ok(false, 'next function should not be called'); callback(); } ], function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }, 'multiple callback calls': function(test){ var call_order = []; var arr = [ function(callback){ call_order.push(1); // call the callback twice. this should call function 2 twice callback(null, 'one', 'two'); callback(null, 'one', 'two'); }, function(arg1, arg2, callback){ call_order.push(2); callback(null, arg1, arg2, 'three'); }, function(arg1, arg2, arg3, callback){ call_order.push(3); callback(null, 'four'); }, function(/*arg4*/){ call_order.push(4); arr[3] = function(){ call_order.push(4); test.same(call_order, [1,2,2,3,3,4,4]); test.done(); }; } ]; async.waterfall(arr); }, 'call in another context': function(test) { if (isBrowser()) { // node only test test.done(); return; } var vm = require('vm'); var sandbox = { async: async, test: test }; var fn = "(" + (function () { async.waterfall([function (callback) { callback(); }], function (err) { if (err) { return test.done(err); } test.done(); }); }).toString() + "())"; vm.runInNewContext(fn, sandbox); } }; exports['parallel'] = function(test){ var call_order = []; async.parallel([ function(callback){ setTimeout(function(){ call_order.push(1); callback(null, 1); }, 50); }, function(callback){ setTimeout(function(){ call_order.push(2); callback(null, 2); }, 100); }, function(callback){ setTimeout(function(){ call_order.push(3); callback(null, 3,3); }, 25); } ], function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [3,1,2]); test.same(results, [1,2,[3,3]]); test.done(); }); }; exports['parallel empty array'] = function(test){ async.parallel([], function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(results, []); test.done(); }); }; exports['parallel error'] = function(test){ async.parallel([ function(callback){ callback('error', 1); }, function(callback){ callback('error2', 2); } ], function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 100); }; exports['parallel no callback'] = function(test){ async.parallel([ function(callback){callback();}, function(callback){callback(); test.done();}, ]); }; exports['parallel object'] = function(test){ var call_order = []; async.parallel(getFunctionsObject(call_order), function(err, results){ test.equals(err, null); test.same(call_order, [3,1,2]); test.same(results, { one: 1, two: 2, three: [3,3] }); test.done(); }); }; // Issue 10 on github: https://github.com/caolan/async/issues#issue/10 exports['paralel falsy return values'] = function (test) { function taskFalse(callback) { async.nextTick(function() { callback(null, false); }); } function taskUndefined(callback) { async.nextTick(function() { callback(null, undefined); }); } function taskEmpty(callback) { async.nextTick(function() { callback(null); }); } function taskNull(callback) { async.nextTick(function() { callback(null, null); }); } async.parallel( [taskFalse, taskUndefined, taskEmpty, taskNull], function(err, results) { test.equal(results.length, 4); test.strictEqual(results[0], false); test.strictEqual(results[1], undefined); test.strictEqual(results[2], undefined); test.strictEqual(results[3], null); test.done(); } ); }; exports['parallel limit'] = function(test){ var call_order = []; async.parallelLimit([ function(callback){ setTimeout(function(){ call_order.push(1); callback(null, 1); }, 50); }, function(callback){ setTimeout(function(){ call_order.push(2); callback(null, 2); }, 100); }, function(callback){ setTimeout(function(){ call_order.push(3); callback(null, 3,3); }, 25); } ], 2, function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [1,3,2]); test.same(results, [1,2,[3,3]]); test.done(); }); }; exports['parallel limit empty array'] = function(test){ async.parallelLimit([], 2, function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(results, []); test.done(); }); }; exports['parallel limit error'] = function(test){ async.parallelLimit([ function(callback){ callback('error', 1); }, function(callback){ callback('error2', 2); } ], 1, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 100); }; exports['parallel limit no callback'] = function(test){ async.parallelLimit([ function(callback){callback();}, function(callback){callback(); test.done();}, ], 1); }; exports['parallel limit object'] = function(test){ var call_order = []; async.parallelLimit(getFunctionsObject(call_order), 2, function(err, results){ test.equals(err, null); test.same(call_order, [1,3,2]); test.same(results, { one: 1, two: 2, three: [3,3] }); test.done(); }); }; exports['parallel call in another context'] = function(test) { if (isBrowser()) { // node only test test.done(); return; } var vm = require('vm'); var sandbox = { async: async, test: test }; var fn = "(" + (function () { async.parallel([function (callback) { callback(); }], function (err) { if (err) { return test.done(err); } test.done(); }); }).toString() + "())"; vm.runInNewContext(fn, sandbox); }; exports['parallel does not continue replenishing after error'] = function (test) { var started = 0; var arr = [ funcToCall, funcToCall, funcToCall, funcToCall, funcToCall, funcToCall, funcToCall, funcToCall, funcToCall, ]; var delay = 10; var limit = 3; var maxTime = 10 * arr.length; function funcToCall(callback) { started ++; if (started === 3) { return callback(new Error ("Test Error")); } setTimeout(function(){ callback(); }, delay); } async.parallelLimit(arr, limit, function(){}); setTimeout(function(){ test.equal(started, 3); test.done(); }, maxTime); }; exports['series'] = { 'series': function(test){ var call_order = []; async.series([ function(callback){ setTimeout(function(){ call_order.push(1); callback(null, 1); }, 25); }, function(callback){ setTimeout(function(){ call_order.push(2); callback(null, 2); }, 50); }, function(callback){ setTimeout(function(){ call_order.push(3); callback(null, 3,3); }, 15); } ], function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(results, [1,2,[3,3]]); test.same(call_order, [1,2,3]); test.done(); }); }, 'empty array': function(test){ async.series([], function(err, results){ test.equals(err, null); test.same(results, []); test.done(); }); }, 'error': function(test){ test.expect(1); async.series([ function(callback){ callback('error', 1); }, function(callback){ test.ok(false, 'should not be called'); callback('error2', 2); } ], function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 100); }, 'no callback': function(test){ async.series([ function(callback){callback();}, function(callback){callback(); test.done();}, ]); }, 'object': function(test){ var call_order = []; async.series(getFunctionsObject(call_order), function(err, results){ test.equals(err, null); test.same(results, { one: 1, two: 2, three: [3,3] }); test.same(call_order, [1,2,3]); test.done(); }); }, 'call in another context': function(test) { if (isBrowser()) { // node only test test.done(); return; } var vm = require('vm'); var sandbox = { async: async, test: test }; var fn = "(" + (function () { async.series([function (callback) { callback(); }], function (err) { if (err) { return test.done(err); } test.done(); }); }).toString() + "())"; vm.runInNewContext(fn, sandbox); }, // Issue 10 on github: https://github.com/caolan/async/issues#issue/10 'falsy return values': function (test) { function taskFalse(callback) { async.nextTick(function() { callback(null, false); }); } function taskUndefined(callback) { async.nextTick(function() { callback(null, undefined); }); } function taskEmpty(callback) { async.nextTick(function() { callback(null); }); } function taskNull(callback) { async.nextTick(function() { callback(null, null); }); } async.series( [taskFalse, taskUndefined, taskEmpty, taskNull], function(err, results) { test.equal(results.length, 4); test.strictEqual(results[0], false); test.strictEqual(results[1], undefined); test.strictEqual(results[2], undefined); test.strictEqual(results[3], null); test.done(); } ); } }; exports['iterator'] = function(test){ var call_order = []; var iterator = async.iterator([ function(){call_order.push(1);}, function(arg1){ test.equals(arg1, 'arg1'); call_order.push(2); }, function(arg1, arg2){ test.equals(arg1, 'arg1'); test.equals(arg2, 'arg2'); call_order.push(3); } ]); iterator(); test.same(call_order, [1]); var iterator2 = iterator(); test.same(call_order, [1,1]); var iterator3 = iterator2('arg1'); test.same(call_order, [1,1,2]); var iterator4 = iterator3('arg1', 'arg2'); test.same(call_order, [1,1,2,3]); test.equals(iterator4, undefined); test.done(); }; exports['iterator empty array'] = function(test){ var iterator = async.iterator([]); test.equals(iterator(), undefined); test.equals(iterator.next(), undefined); test.done(); }; exports['iterator.next'] = function(test){ var call_order = []; var iterator = async.iterator([ function(){call_order.push(1);}, function(arg1){ test.equals(arg1, 'arg1'); call_order.push(2); }, function(arg1, arg2){ test.equals(arg1, 'arg1'); test.equals(arg2, 'arg2'); call_order.push(3); } ]); var fn = iterator.next(); var iterator2 = fn('arg1'); test.same(call_order, [2]); iterator2('arg1','arg2'); test.same(call_order, [2,3]); test.equals(iterator2.next(), undefined); test.done(); }; exports['each'] = function(test){ var args = []; async.each([1,3,2], eachIterator.bind(this, args), function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, [1,2,3]); test.done(); }); }; exports['each extra callback'] = function(test){ var count = 0; async.each([1,3,2], function(val, callback) { count++; callback(); test.throws(callback); if (count == 3) { test.done(); } }); }; exports['each empty array'] = function(test){ test.expect(1); async.each([], function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['each empty array, with other property on the array'] = function(test){ test.expect(1); var myArray = []; myArray.myProp = "anything"; async.each(myArray, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['each error'] = function(test){ test.expect(1); async.each([1,2,3], function(x, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }; exports['each no callback'] = function(test){ async.each([1], eachNoCallbackIterator.bind(this, test)); }; exports['forEach alias'] = function (test) { test.strictEqual(async.each, async.forEach); test.done(); }; exports['forEachOf'] = function(test){ var args = []; async.forEachOf({ a: 1, b: 2 }, forEachOfIterator.bind(this, args), function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, ["a", 1, "b", 2]); test.done(); }); }; exports['forEachOf - instant resolver'] = function(test){ test.expect(1); var args = []; async.forEachOf({ a: 1, b: 2 }, function(x, k, cb) { args.push(k, x); cb(); }, function(){ // ensures done callback isn't called before all items iterated test.same(args, ["a", 1, "b", 2]); test.done(); }); }; exports['forEachOf empty object'] = function(test){ test.expect(1); async.forEachOf({}, function(value, key, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err) { if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['forEachOf empty array'] = function(test){ test.expect(1); async.forEachOf([], function(value, key, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err) { if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['forEachOf error'] = function(test){ test.expect(1); async.forEachOf({ a: 1, b: 2 }, function(value, key, callback) { callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }; exports['forEachOf no callback'] = function(test){ async.forEachOf({ a: 1 }, forEachOfNoCallbackIterator.bind(this, test)); }; exports['eachOf alias'] = function(test){ test.equals(async.eachOf, async.forEachOf); test.done(); }; exports['forEachOf with array'] = function(test){ var args = []; async.forEachOf([ "a", "b" ], forEachOfIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, [0, "a", 1, "b"]); test.done(); }); }; exports['eachSeries'] = function(test){ var args = []; async.eachSeries([1,3,2], eachIterator.bind(this, args), function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, [1,3,2]); test.done(); }); }; exports['eachSeries empty array'] = function(test){ test.expect(1); async.eachSeries([], function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['eachSeries array modification'] = function(test) { test.expect(1); var arr = [1, 2, 3, 4]; async.eachSeries(arr, function (x, callback) { async.setImmediate(callback); }, function () { test.ok(true, 'should call callback'); }); arr.pop(); arr.splice(0, 1); setTimeout(test.done, 50); }; // bug #782. Remove in next major release exports['eachSeries single item'] = function (test) { test.expect(1); var sync = true; async.eachSeries([1], function (i, cb) { cb(null); }, function () { test.ok(sync, "callback not called on same tick"); }); sync = false; test.done(); }; // bug #782. Remove in next major release exports['eachSeries single item'] = function (test) { test.expect(1); var sync = true; async.eachSeries([1], function (i, cb) { cb(null); }, function () { test.ok(sync, "callback not called on same tick"); }); sync = false; test.done(); }; exports['eachSeries error'] = function(test){ test.expect(2); var call_order = []; async.eachSeries([1,2,3], function(x, callback){ call_order.push(x); callback('error'); }, function(err){ test.same(call_order, [1]); test.equals(err, 'error'); }); setTimeout(test.done, 50); }; exports['eachSeries no callback'] = function(test){ async.eachSeries([1], eachNoCallbackIterator.bind(this, test)); }; exports['eachLimit'] = function(test){ var args = []; var arr = [0,1,2,3,4,5,6,7,8,9]; async.eachLimit(arr, 2, function(x,callback){ setTimeout(function(){ args.push(x); callback(); }, x*5); }, function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, arr); test.done(); }); }; exports['eachLimit empty array'] = function(test){ test.expect(1); async.eachLimit([], 2, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['eachLimit limit exceeds size'] = function(test){ var args = []; var arr = [0,1,2,3,4,5,6,7,8,9]; async.eachLimit(arr, 20, eachIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, arr); test.done(); }); }; exports['eachLimit limit equal size'] = function(test){ var args = []; var arr = [0,1,2,3,4,5,6,7,8,9]; async.eachLimit(arr, 10, eachIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, arr); test.done(); }); }; exports['eachLimit zero limit'] = function(test){ test.expect(1); async.eachLimit([0,1,2,3,4,5], 0, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['eachLimit error'] = function(test){ test.expect(2); var arr = [0,1,2,3,4,5,6,7,8,9]; var call_order = []; async.eachLimit(arr, 3, function(x, callback){ call_order.push(x); if (x === 2) { callback('error'); } }, function(err){ test.same(call_order, [0,1,2]); test.equals(err, 'error'); }); setTimeout(test.done, 25); }; exports['eachLimit no callback'] = function(test){ async.eachLimit([1], 1, eachNoCallbackIterator.bind(this, test)); }; exports['eachLimit synchronous'] = function(test){ var args = []; var arr = [0,1,2]; async.eachLimit(arr, 5, function(x,callback){ args.push(x); callback(); }, function(err){ if (err) throw err; test.same(args, arr); test.done(); }); }; exports['eachLimit does not continue replenishing after error'] = function (test) { var started = 0; var arr = [0,1,2,3,4,5,6,7,8,9]; var delay = 10; var limit = 3; var maxTime = 10 * arr.length; async.eachLimit(arr, limit, function(x, callback) { started ++; if (started === 3) { return callback(new Error ("Test Error")); } setTimeout(function(){ callback(); }, delay); }, function(){}); setTimeout(function(){ test.equal(started, 3); test.done(); }, maxTime); }; exports['forEachSeries alias'] = function (test) { test.strictEqual(async.eachSeries, async.forEachSeries); test.done(); }; exports['forEachOfSeries'] = function(test){ var args = []; async.forEachOfSeries({ a: 1, b: 2 }, forEachOfIterator.bind(this, args), function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, [ "a", 1, "b", 2 ]); test.done(); }); }; exports['forEachOfSeries empty object'] = function(test){ test.expect(1); async.forEachOfSeries({}, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['forEachOfSeries error'] = function(test){ test.expect(2); var call_order = []; async.forEachOfSeries({ a: 1, b: 2 }, function(value, key, callback){ call_order.push(value, key); callback('error'); }, function(err){ test.same(call_order, [ 1, "a" ]); test.equals(err, 'error'); }); setTimeout(test.done, 50); }; exports['forEachOfSeries no callback'] = function(test){ async.forEachOfSeries({ a: 1 }, forEachOfNoCallbackIterator.bind(this, test)); }; exports['forEachOfSeries with array'] = function(test){ var args = []; async.forEachOfSeries([ "a", "b" ], forEachOfIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, [ 0, "a", 1, "b" ]); test.done(); }); }; exports['eachOfLimit alias'] = function(test){ test.equals(async.eachOfLimit, async.forEachOfLimit); test.done(); }; exports['eachOfSeries alias'] = function(test){ test.equals(async.eachOfSeries, async.forEachOfSeries); test.done(); }; exports['forEachLimit alias'] = function (test) { test.strictEqual(async.eachLimit, async.forEachLimit); test.done(); }; exports['forEachOfLimit'] = function(test){ var args = []; var obj = { a: 1, b: 2, c: 3, d: 4 }; async.forEachOfLimit(obj, 2, function(value, key, callback){ setTimeout(function(){ args.push(value, key); callback(); }, value * 5); }, function(err){ test.ok(err === null, err + " passed instead of 'null'"); test.same(args, [ 1, "a", 2, "b", 3, "c", 4, "d" ]); test.done(); }); }; exports['forEachOfLimit empty object'] = function(test){ test.expect(1); async.forEachOfLimit({}, 2, function(value, key, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['forEachOfLimit limit exceeds size'] = function(test){ var args = []; var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }; async.forEachOfLimit(obj, 10, forEachOfIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, [ "a", 1, "b", 2, "c", 3, "d", 4, "e", 5 ]); test.done(); }); }; exports['forEachOfLimit limit equal size'] = function(test){ var args = []; var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }; async.forEachOfLimit(obj, 5, forEachOfIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, [ "a", 1, "b", 2, "c", 3, "d", 4, "e", 5 ]); test.done(); }); }; exports['forEachOfLimit zero limit'] = function(test){ test.expect(1); async.forEachOfLimit({ a: 1, b: 2 }, 0, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }; exports['forEachOfLimit error'] = function(test){ test.expect(2); var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }; var call_order = []; async.forEachOfLimit(obj, 3, function(value, key, callback){ call_order.push(value, key); if (value === 2) { callback('error'); } }, function(err){ test.same(call_order, [ 1, "a", 2, "b" ]); test.equals(err, 'error'); }); setTimeout(test.done, 25); }; exports['forEachOfLimit no callback'] = function(test){ async.forEachOfLimit({ a: 1 }, 1, forEachOfNoCallbackIterator.bind(this, test)); }; exports['forEachOfLimit synchronous'] = function(test){ var args = []; var obj = { a: 1, b: 2 }; async.forEachOfLimit(obj, 5, forEachOfIterator.bind(this, args), function(err){ if (err) throw err; test.same(args, [ "a", 1, "b", 2 ]); test.done(); }); }; exports['forEachOfLimit with array'] = function(test){ var args = []; var arr = [ "a", "b" ]; async.forEachOfLimit(arr, 1, forEachOfIterator.bind(this, args), function (err) { if (err) throw err; test.same(args, [ 0, "a", 1, "b" ]); test.done(); }); }; exports['map'] = { 'basic': function(test){ var call_order = []; async.map([1,3,2], mapIterator.bind(this, call_order), function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [1,2,3]); test.same(results, [2,6,4]); test.done(); }); }, 'map original untouched': function(test){ var a = [1,2,3]; async.map(a, function(x, callback){ callback(null, x*2); }, function(err, results){ test.same(results, [2,4,6]); test.same(a, [1,2,3]); test.done(); }); }, 'map without main callback': function(test){ var a = [1,2,3]; var r = []; async.map(a, function(x, callback){ r.push(x); callback(null); if (r.length >= a.length) { test.same(r, a); test.done(); } }); }, 'map error': function(test){ test.expect(1); async.map([1,2,3], function(x, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }, 'map undefined array': function(test){ test.expect(2); async.map(undefined, function(x, callback){ callback(); }, function(err, result){ test.equals(err, null); test.same(result, []); }); setTimeout(test.done, 50); }, 'map object': function (test) { async.map({a: 1, b: 2, c: 3}, function (val, callback) { callback(null, val * 2); }, function (err, result) { if (err) throw err; test.equals(Object.prototype.toString.call(result), '[object Object]'); test.same(result, {a: 2, b: 4, c: 6}); test.done(); }); }, 'mapSeries': function(test){ var call_order = []; async.mapSeries([1,3,2], mapIterator.bind(this, call_order), function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [1,3,2]); test.same(results, [2,6,4]); test.done(); }); }, 'mapSeries error': function(test){ test.expect(1); async.mapSeries([1,2,3], function(x, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }, 'mapSeries undefined array': function(test){ test.expect(2); async.mapSeries(undefined, function(x, callback){ callback(); }, function(err, result){ test.equals(err, null); test.same(result, []); }); setTimeout(test.done, 50); }, 'mapSeries object': function (test) { async.mapSeries({a: 1, b: 2, c: 3}, function (val, callback) { callback(null, val * 2); }, function (err, result) { if (err) throw err; test.same(result, {a: 2, b: 4, c: 6}); test.done(); }); }, 'mapLimit': function(test){ var call_order = []; async.mapLimit([2,4,3], 2, mapIterator.bind(this, call_order), function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [2,4,3]); test.same(results, [4,8,6]); test.done(); }); }, 'mapLimit empty array': function(test){ test.expect(1); async.mapLimit([], 2, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }, 'mapLimit undefined array': function(test){ test.expect(2); async.mapLimit(undefined, 2, function(x, callback){ callback(); }, function(err, result){ test.equals(err, null); test.same(result, []); }); setTimeout(test.done, 50); }, 'mapLimit limit exceeds size': function(test){ var call_order = []; async.mapLimit([0,1,2,3,4,5,6,7,8,9], 20, mapIterator.bind(this, call_order), function(err, results){ test.same(call_order, [0,1,2,3,4,5,6,7,8,9]); test.same(results, [0,2,4,6,8,10,12,14,16,18]); test.done(); }); }, 'mapLimit limit equal size': function(test){ var call_order = []; async.mapLimit([0,1,2,3,4,5,6,7,8,9], 10, mapIterator.bind(this, call_order), function(err, results){ test.same(call_order, [0,1,2,3,4,5,6,7,8,9]); test.same(results, [0,2,4,6,8,10,12,14,16,18]); test.done(); }); }, 'mapLimit zero limit': function(test){ test.expect(2); async.mapLimit([0,1,2,3,4,5], 0, function(x, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err, results){ test.same(results, []); test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }, 'mapLimit error': function(test){ test.expect(2); var arr = [0,1,2,3,4,5,6,7,8,9]; var call_order = []; async.mapLimit(arr, 3, function(x, callback){ call_order.push(x); if (x === 2) { callback('error'); } }, function(err){ test.same(call_order, [0,1,2]); test.equals(err, 'error'); }); setTimeout(test.done, 25); }, 'mapLimit does not continue replenishing after error': function (test) { var started = 0; var arr = [0,1,2,3,4,5,6,7,8,9]; var delay = 10; var limit = 3; var maxTime = 10 * arr.length; async.mapLimit(arr, limit, function(x, callback) { started ++; if (started === 3) { return callback(new Error ("Test Error")); } setTimeout(function(){ callback(); }, delay); }, function(){}); setTimeout(function(){ test.equal(started, 3); test.done(); }, maxTime); } }; exports['reduce'] = function(test){ var call_order = []; async.reduce([1,2,3], 0, function(a, x, callback){ call_order.push(x); callback(null, a + x); }, function(err, result){ test.ok(err === null, err + " passed instead of 'null'"); test.equals(result, 6); test.same(call_order, [1,2,3]); test.done(); }); }; exports['reduce async with non-reference memo'] = function(test){ async.reduce([1,3,2], 0, function(a, x, callback){ setTimeout(function(){callback(null, a + x);}, Math.random()*100); }, function(err, result){ test.equals(result, 6); test.done(); }); }; exports['reduce error'] = function(test){ test.expect(1); async.reduce([1,2,3], 0, function(a, x, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }; exports['inject alias'] = function(test){ test.equals(async.inject, async.reduce); test.done(); }; exports['foldl alias'] = function(test){ test.equals(async.foldl, async.reduce); test.done(); }; exports['reduceRight'] = function(test){ var call_order = []; var a = [1,2,3]; async.reduceRight(a, 0, function(a, x, callback){ call_order.push(x); callback(null, a + x); }, function(err, result){ test.equals(result, 6); test.same(call_order, [3,2,1]); test.same(a, [1,2,3]); test.done(); }); }; exports['foldr alias'] = function(test){ test.equals(async.foldr, async.reduceRight); test.done(); }; exports['transform implictly determines memo if not provided'] = function(test){ async.transform([1,2,3], function(memo, x, v, callback){ memo.push(x + 1); callback(); }, function(err, result){ test.same(result, [2, 3, 4]); test.done(); }); }; exports['transform async with object memo'] = function(test){ test.expect(2); async.transform([1,3,2], {}, function(memo, v, k, callback){ setTimeout(function() { memo[k] = v; callback(); }); }, function(err, result) { test.equals(err, null); test.same(result, { 0: 1, 1: 3, 2: 2 }); test.done(); }); }; exports['transform iterating object'] = function(test){ test.expect(2); async.transform({a: 1, b: 3, c: 2}, function(memo, v, k, callback){ setTimeout(function() { memo[k] = v + 1; callback(); }); }, function(err, result) { test.equals(err, null); test.same(result, {a: 2, b: 4, c: 3}); test.done(); }); }; exports['transform error'] = function(test){ async.transform([1,2,3], function(a, v, k, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); test.done(); }); }; exports['filter'] = function(test){ async.filter([3,1,2], filterIterator, function(results){ test.same(results, [3,1]); test.done(); }); }; exports['filter original untouched'] = function(test){ var a = [3,1,2]; async.filter(a, function(x, callback){ callback(x % 2); }, function(results){ test.same(results, [3,1]); test.same(a, [3,1,2]); test.done(); }); }; exports['filterSeries'] = function(test){ async.filterSeries([3,1,2], filterIterator, function(results){ test.same(results, [3,1]); test.done(); }); }; exports['select alias'] = function(test){ test.equals(async.select, async.filter); test.done(); }; exports['selectSeries alias'] = function(test){ test.equals(async.selectSeries, async.filterSeries); test.done(); }; exports['reject'] = function(test){ test.expect(1); async.reject([3,1,2], filterIterator, function(results){ test.same(results, [2]); test.done(); }); }; exports['reject original untouched'] = function(test){ test.expect(2); var a = [3,1,2]; async.reject(a, function(x, callback){ callback(x % 2); }, function(results){ test.same(results, [2]); test.same(a, [3,1,2]); test.done(); }); }; exports['rejectSeries'] = function(test){ test.expect(1); async.rejectSeries([3,1,2], filterIterator, function(results){ test.same(results, [2]); test.done(); }); }; function testLimit(test, arr, limitFunc, limit, iter, done) { var args = []; limitFunc(arr, limit, function(x) { args.push(x); iter.apply(this, arguments); }, function() { test.same(args, arr); if (done) done.apply(this, arguments); else test.done(); }); } exports['rejectLimit'] = function(test) { test.expect(2); testLimit(test, [5, 4, 3, 2, 1], async.rejectLimit, 2, function(v, next) { next(v % 2); }, function(x) { test.same(x, [4, 2]); test.done(); }); }; exports['filterLimit'] = function(test) { test.expect(2); testLimit(test, [5, 4, 3, 2, 1], async.filterLimit, 2, function(v, next) { next(v % 2); }, function(x) { test.same(x, [5, 3, 1]); test.done(); }); }; exports['some true'] = function(test){ test.expect(1); async.some([3,1,2], function(x, callback){ setTimeout(function(){callback(x === 1);}, 0); }, function(result){ test.equals(result, true); test.done(); }); }; exports['some false'] = function(test){ test.expect(1); async.some([3,1,2], function(x, callback){ setTimeout(function(){callback(x === 10);}, 0); }, function(result){ test.equals(result, false); test.done(); }); }; exports['some early return'] = function(test){ test.expect(1); var call_order = []; async.some([1,2,3], function(x, callback){ setTimeout(function(){ call_order.push(x); callback(x === 1); }, x*25); }, function(){ call_order.push('callback'); }); setTimeout(function(){ test.same(call_order, [1,'callback',2,3]); test.done(); }, 100); }; exports['someLimit true'] = function(test){ async.someLimit([3,1,2], 2, function(x, callback){ setTimeout(function(){callback(x === 2);}, 0); }, function(result){ test.equals(result, true); test.done(); }); }; exports['someLimit false'] = function(test){ async.someLimit([3,1,2], 2, function(x, callback){ setTimeout(function(){callback(x === 10);}, 0); }, function(result){ test.equals(result, false); test.done(); }); }; exports['every true'] = function(test){ async.everyLimit([3,1,2], 1, function(x, callback){ setTimeout(function(){callback(x > 1);}, 0); }, function(result){ test.equals(result, true); test.done(); }); }; exports['everyLimit false'] = function(test){ async.everyLimit([3,1,2], 2, function(x, callback){ setTimeout(function(){callback(x === 2);}, 0); }, function(result){ test.equals(result, false); test.done(); }); }; exports['everyLimit short-circuit'] = function(test){ test.expect(2); var calls = 0; async.everyLimit([3,1,2], 1, function(x, callback){ calls++; callback(x === 1); }, function(result){ test.equals(result, false); test.equals(calls, 1); test.done(); }); }; exports['someLimit short-circuit'] = function(test){ test.expect(2); var calls = 0; async.someLimit([3,1,2], 1, function(x, callback){ calls++; callback(x === 1); }, function(result){ test.equals(result, true); test.equals(calls, 2); test.done(); }); }; exports['any alias'] = function(test){ test.equals(async.any, async.some); test.done(); }; exports['every true'] = function(test){ test.expect(1); async.every([1,2,3], function(x, callback){ setTimeout(function(){callback(true);}, 0); }, function(result){ test.equals(result, true); test.done(); }); }; exports['every false'] = function(test){ test.expect(1); async.every([1,2,3], function(x, callback){ setTimeout(function(){callback(x % 2);}, 0); }, function(result){ test.equals(result, false); test.done(); }); }; exports['every early return'] = function(test){ test.expect(1); var call_order = []; async.every([1,2,3], function(x, callback){ setTimeout(function(){ call_order.push(x); callback(x === 1); }, x*25); }, function(){ call_order.push('callback'); }); setTimeout(function(){ test.same(call_order, [1,2,'callback',3]); test.done(); }, 100); }; exports['all alias'] = function(test){ test.equals(async.all, async.every); test.done(); }; exports['detect'] = function(test){ test.expect(2); var call_order = []; async.detect([3,2,1], detectIterator.bind(this, call_order), function(result){ call_order.push('callback'); test.equals(result, 2); }); setTimeout(function(){ test.same(call_order, [1,2,'callback',3]); test.done(); }, 100); }; exports['detect - mulitple matches'] = function(test){ test.expect(2); var call_order = []; async.detect([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){ call_order.push('callback'); test.equals(result, 2); }); setTimeout(function(){ test.same(call_order, [1,2,'callback',2,2,3]); test.done(); }, 100); }; exports['detectSeries'] = function(test){ test.expect(2); var call_order = []; async.detectSeries([3,2,1], detectIterator.bind(this, call_order), function(result){ call_order.push('callback'); test.equals(result, 2); }); setTimeout(function(){ test.same(call_order, [3,2,'callback']); test.done(); }, 200); }; exports['detectSeries - multiple matches'] = function(test){ test.expect(2); var call_order = []; async.detectSeries([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){ call_order.push('callback'); test.equals(result, 2); }); setTimeout(function(){ test.same(call_order, [3,2,'callback']); test.done(); }, 200); }; exports['detectSeries - ensure stop'] = function (test) { test.expect(1); async.detectSeries([1, 2, 3, 4, 5], function (num, cb) { if (num > 3) throw new Error("detectSeries did not stop iterating"); cb(num === 3); }, function (result) { test.equals(result, 3); test.done(); }); }; exports['detectLimit'] = function(test){ test.expect(2); var call_order = []; async.detectLimit([3, 2, 1], 2, detectIterator.bind(this, call_order), function(result) { call_order.push('callback'); test.equals(result, 2); }); setTimeout(function() { test.same(call_order, [2, 'callback', 3]); test.done(); }, 100); }; exports['detectLimit - multiple matches'] = function(test){ test.expect(2); var call_order = []; async.detectLimit([3,2,2,1,2], 2, detectIterator.bind(this, call_order), function(result){ call_order.push('callback'); test.equals(result, 2); }); setTimeout(function(){ test.same(call_order, [2, 'callback', 3]); test.done(); }, 100); }; exports['detectLimit - ensure stop'] = function (test) { test.expect(1); async.detectLimit([1, 2, 3, 4, 5], 2, function (num, cb) { if (num > 4) throw new Error("detectLimit did not stop iterating"); cb(num === 3); }, function (result) { test.equals(result, 3); test.done(); }); }; exports['sortBy'] = function(test){ test.expect(2); async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){ setTimeout(function(){callback(null, x.a);}, 0); }, function(err, result){ test.ok(err === null, err + " passed instead of 'null'"); test.same(result, [{a:1},{a:6},{a:15}]); test.done(); }); }; exports['sortBy inverted'] = function(test){ test.expect(1); async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){ setTimeout(function(){callback(null, x.a*-1);}, 0); }, function(err, result){ test.same(result, [{a:15},{a:6},{a:1}]); test.done(); }); }; exports['sortBy error'] = function(test){ test.expect(1); var error = new Error('asdas'); async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){ async.setImmediate(function(){ callback(error); }); }, function(err){ test.equal(err, error); test.done(); }); }; exports['apply'] = function(test){ test.expect(6); var fn = function(){ test.same(Array.prototype.slice.call(arguments), [1,2,3,4]); }; async.apply(fn, 1, 2, 3, 4)(); async.apply(fn, 1, 2, 3)(4); async.apply(fn, 1, 2)(3, 4); async.apply(fn, 1)(2, 3, 4); async.apply(fn)(1, 2, 3, 4); test.equals( async.apply(function(name){return 'hello ' + name;}, 'world')(), 'hello world' ); test.done(); }; // generates tests for console functions such as async.log var console_fn_tests = function(name){ if (typeof console !== 'undefined') { exports[name] = function(test){ test.expect(5); var fn = function(arg1, callback){ test.equals(arg1, 'one'); setTimeout(function(){callback(null, 'test');}, 0); }; var fn_err = function(arg1, callback){ test.equals(arg1, 'one'); setTimeout(function(){callback('error');}, 0); }; var _console_fn = console[name]; var _error = console.error; console[name] = function(val){ test.equals(val, 'test'); test.equals(arguments.length, 1); console.error = function(val){ test.equals(val, 'error'); console[name] = _console_fn; console.error = _error; test.done(); }; async[name](fn_err, 'one'); }; async[name](fn, 'one'); }; exports[name + ' with multiple result params'] = function(test){ test.expect(1); var fn = function(callback){callback(null,'one','two','three');}; var _console_fn = console[name]; var called_with = []; console[name] = function(x){ called_with.push(x); }; async[name](fn); test.same(called_with, ['one','two','three']); console[name] = _console_fn; test.done(); }; } // browser-only test exports[name + ' without console.' + name] = function(test){ if (typeof window !== 'undefined') { var _console = window.console; window.console = undefined; var fn = function(callback){callback(null, 'val');}; var fn_err = function(callback){callback('error');}; async[name](fn); async[name](fn_err); window.console = _console; } test.done(); }; }; exports['times'] = { 'times': function(test) { test.expect(2); async.times(5, function(n, next) { next(null, n); }, function(err, results) { test.ok(err === null, err + " passed instead of 'null'"); test.same(results, [0,1,2,3,4]); test.done(); }); }, 'times 3': function(test){ test.expect(1); var args = []; async.times(3, function(n, callback){ setTimeout(function(){ args.push(n); callback(); }, n * 25); }, function(err){ if (err) throw err; test.same(args, [0,1,2]); test.done(); }); }, 'times 0': function(test){ test.expect(1); async.times(0, function(n, callback){ test.ok(false, 'iterator should not be called'); callback(); }, function(err){ if (err) throw err; test.ok(true, 'should call callback'); }); setTimeout(test.done, 25); }, 'times error': function(test){ test.expect(1); async.times(3, function(n, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }, 'timesSeries': function(test){ test.expect(2); var call_order = []; async.timesSeries(5, function(n, callback){ setTimeout(function(){ call_order.push(n); callback(null, n); }, 100 - n * 10); }, function(err, results){ test.same(call_order, [0,1,2,3,4]); test.same(results, [0,1,2,3,4]); test.done(); }); }, 'timesSeries error': function(test){ test.expect(1); async.timesSeries(5, function(n, callback){ callback('error'); }, function(err){ test.equals(err, 'error'); }); setTimeout(test.done, 50); }, 'timesLimit': function(test){ test.expect(7); var limit = 2; var running = 0; async.timesLimit(5, limit, function (i, next) { running++; test.ok(running <= limit && running > 0, running); setTimeout(function () { running--; next(null, i * 2); }, (3 - i) * 10); }, function(err, results){ test.ok(err === null, err + " passed instead of 'null'"); test.same(results, [0, 2, 4, 6, 8]); test.done(); }); } }; console_fn_tests('log'); console_fn_tests('dir'); /*console_fn_tests('info'); console_fn_tests('warn'); console_fn_tests('error');*/ exports['nextTick'] = function(test){ test.expect(1); var call_order = []; async.nextTick(function(){call_order.push('two');}); call_order.push('one'); setTimeout(function(){ test.same(call_order, ['one','two']); test.done(); }, 50); }; exports['nextTick in the browser'] = function(test){ if (!isBrowser()) { // skip this test in node return test.done(); } test.expect(1); var call_order = []; async.nextTick(function(){call_order.push('two');}); call_order.push('one'); setTimeout(function(){ test.same(call_order, ['one','two']); }, 50); setTimeout(test.done, 100); }; exports['noConflict - node only'] = function(test){ if (!isBrowser()) { // node only test test.expect(3); var fs = require('fs'); var vm = require('vm'); var filename = __dirname + '/../lib/async.js'; fs.readFile(filename, function(err, content){ if(err) return test.done(); var s = vm.createScript(content, filename); var s2 = vm.createScript( content + 'this.async2 = this.async.noConflict();', filename ); var sandbox1 = {async: 'oldvalue'}; s.runInNewContext(sandbox1); test.ok(sandbox1.async); var sandbox2 = {async: 'oldvalue'}; s2.runInNewContext(sandbox2); test.equals(sandbox2.async, 'oldvalue'); test.ok(sandbox2.async2); test.done(); }); } else test.done(); }; exports['concat'] = function(test){ test.expect(3); var call_order = []; var iterator = function (x, cb) { setTimeout(function(){ call_order.push(x); var r = []; while (x > 0) { r.push(x); x--; } cb(null, r); }, x*25); }; async.concat([1,3,2], iterator, function(err, results){ test.same(results, [1,2,1,3,2,1]); test.same(call_order, [1,2,3]); test.ok(err === null, err + " passed instead of 'null'"); test.done(); }); }; exports['concat error'] = function(test){ test.expect(1); var iterator = function (x, cb) { cb(new Error('test error')); }; async.concat([1,2,3], iterator, function(err){ test.ok(err); test.done(); }); }; exports['concatSeries'] = function(test){ test.expect(3); var call_order = []; var iterator = function (x, cb) { setTimeout(function(){ call_order.push(x); var r = []; while (x > 0) { r.push(x); x--; } cb(null, r); }, x*25); }; async.concatSeries([1,3,2], iterator, function(err, results){ test.same(results, [1,3,2,1,2,1]); test.same(call_order, [1,3,2]); test.ok(err === null, err + " passed instead of 'null'"); test.done(); }); }; exports['until'] = function (test) { test.expect(4); var call_order = []; var count = 0; async.until( function () { call_order.push(['test', count]); return (count == 5); }, function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function (err, result) { test.ok(err === null, err + " passed instead of 'null'"); test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['test', 0], ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5], ]); test.equals(count, 5); test.done(); } ); }; exports['doUntil'] = function (test) { test.expect(4); var call_order = []; var count = 0; async.doUntil( function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function () { call_order.push(['test', count]); return (count == 5); }, function (err, result) { test.ok(err === null, err + " passed instead of 'null'"); test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5] ]); test.equals(count, 5); test.done(); } ); }; exports['doUntil callback params'] = function (test) { test.expect(3); var call_order = []; var count = 0; async.doUntil( function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function (c) { call_order.push(['test', c]); return (c == 5); }, function (err, result) { if (err) throw err; test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5] ]); test.equals(count, 5); test.done(); } ); }; exports['whilst'] = function (test) { test.expect(4); var call_order = []; var count = 0; async.whilst( function () { call_order.push(['test', count]); return (count < 5); }, function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function (err, result) { test.ok(err === null, err + " passed instead of 'null'"); test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['test', 0], ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5], ]); test.equals(count, 5); test.done(); } ); }; exports['doWhilst'] = function (test) { test.expect(4); var call_order = []; var count = 0; async.doWhilst( function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function () { call_order.push(['test', count]); return (count < 5); }, function (err, result) { test.ok(err === null, err + " passed instead of 'null'"); test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5] ]); test.equals(count, 5); test.done(); } ); }; exports['doWhilst callback params'] = function (test) { test.expect(3); var call_order = []; var count = 0; async.doWhilst( function (cb) { call_order.push(['iterator', count]); count++; cb(null, count); }, function (c) { call_order.push(['test', c]); return (c < 5); }, function (err, result) { if (err) throw err; test.equals(result, 5, 'last result passed through'); test.same(call_order, [ ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5] ]); test.equals(count, 5); test.done(); } ); }; exports['doWhilst - error'] = function (test) { test.expect(1); var error = new Error('asdas'); async.doWhilst( function (cb) { cb(error); }, function () {}, function (err) { test.equal(err, error); test.done(); } ); }; exports['during'] = function (test) { var call_order = []; var count = 0; async.during( function (cb) { call_order.push(['test', count]); cb(null, count < 5); }, function (cb) { call_order.push(['iterator', count]); count++; cb(); }, function (err) { test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [ ['test', 0], ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5], ]); test.equals(count, 5); test.done(); } ); }; exports['doDuring'] = function (test) { var call_order = []; var count = 0; async.doDuring( function (cb) { call_order.push(['iterator', count]); count++; cb(); }, function (cb) { call_order.push(['test', count]); cb(null, count < 5); }, function (err) { test.ok(err === null, err + " passed instead of 'null'"); test.same(call_order, [ ['iterator', 0], ['test', 1], ['iterator', 1], ['test', 2], ['iterator', 2], ['test', 3], ['iterator', 3], ['test', 4], ['iterator', 4], ['test', 5], ]); test.equals(count, 5); test.done(); } ); }; exports['doDuring - error test'] = function (test) { test.expect(1); var error = new Error('asdas'); async.doDuring( function (cb) { cb(error); }, function () {}, function (err) { test.equal(err, error); test.done(); } ); }; exports['doDuring - error iterator'] = function (test) { test.expect(1); var error = new Error('asdas'); async.doDuring( function (cb) { cb(null); }, function (cb) { cb(error); }, function (err) { test.equal(err, error); test.done(); } ); }; exports['whilst optional callback'] = function (test) { var counter = 0; async.whilst( function () { return counter < 2; }, function (cb) { counter++; cb(); } ); test.equal(counter, 2); test.done(); }; exports['queue'] = { 'queue': function (test) { test.expect(17); var call_order = [], delays = [160,80,240,80]; // worker1: --1-4 // worker2: -2---3 // order of completion: 2,1,4,3 var q = async.queue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); callback('error', 'arg'); }, delays.splice(0,1)[0]); }, 2); q.push(1, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 1); call_order.push('callback ' + 1); }); q.push(2, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 2); call_order.push('callback ' + 2); }); q.push(3, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 3); }); q.push(4, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 4); }); test.equal(q.length(), 4); test.equal(q.concurrency, 2); q.drain = function () { test.same(call_order, [ 'process 2', 'callback 2', 'process 1', 'callback 1', 'process 4', 'callback 4', 'process 3', 'callback 3' ]); test.equal(q.concurrency, 2); test.equal(q.length(), 0); test.done(); }; }, 'default concurrency': function (test) { test.expect(17); var call_order = [], delays = [160,80,240,80]; // order of completion: 1,2,3,4 var q = async.queue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); callback('error', 'arg'); }, delays.splice(0,1)[0]); }); q.push(1, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 3); call_order.push('callback ' + 1); }); q.push(2, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 2); call_order.push('callback ' + 2); }); q.push(3, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 1); call_order.push('callback ' + 3); }); q.push(4, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 4); }); test.equal(q.length(), 4); test.equal(q.concurrency, 1); q.drain = function () { test.same(call_order, [ 'process 1', 'callback 1', 'process 2', 'callback 2', 'process 3', 'callback 3', 'process 4', 'callback 4' ]); test.equal(q.concurrency, 1); test.equal(q.length(), 0); test.done(); }; }, 'zero concurrency': function(test){ test.expect(1); test.throws(function () { async.queue(function (task, callback) { callback(null, task); }, 0); }); test.done(); }, 'error propagation': function(test){ test.expect(1); var results = []; var q = async.queue(function (task, callback) { callback(task.name === 'foo' ? new Error('fooError') : null); }, 2); q.drain = function() { test.deepEqual(results, ['bar', 'fooError']); test.done(); }; q.push({name: 'bar'}, function (err) { if(err) { results.push('barError'); return; } results.push('bar'); }); q.push({name: 'foo'}, function (err) { if(err) { results.push('fooError'); return; } results.push('foo'); }); }, // The original queue implementation allowed the concurrency to be changed only // on the same event loop during which a task was added to the queue. This // test attempts to be a more robust test. // Start with a concurrency of 1. Wait until a leter event loop and change // the concurrency to 2. Wait again for a later loop then verify the concurrency. // Repeat that one more time by chaning the concurrency to 5. 'changing concurrency': function (test) { test.expect(3); var q = async.queue(function(task, callback){ setTimeout(function(){ callback(); }, 100); }, 1); for(var i = 0; i < 50; i++){ q.push(''); } q.drain = function(){ test.done(); }; setTimeout(function(){ test.equal(q.concurrency, 1); q.concurrency = 2; setTimeout(function(){ test.equal(q.running(), 2); q.concurrency = 5; setTimeout(function(){ test.equal(q.running(), 5); }, 500); }, 500); }, 500); }, 'push without callback': function (test) { test.expect(1); var call_order = [], delays = [160,80,240,80]; // worker1: --1-4 // worker2: -2---3 // order of completion: 2,1,4,3 var q = async.queue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); callback('error', 'arg'); }, delays.splice(0,1)[0]); }, 2); q.push(1); q.push(2); q.push(3); q.push(4); setTimeout(function () { test.same(call_order, [ 'process 2', 'process 1', 'process 4', 'process 3' ]); test.done(); }, 800); }, 'push with non-function': function (test) { test.expect(1); var q = async.queue(function () {}, 1); test.throws(function () { q.push({}, 1); }); test.done(); }, 'unshift': function (test) { test.expect(1); var queue_order = []; var q = async.queue(function (task, callback) { queue_order.push(task); callback(); }, 1); q.unshift(4); q.unshift(3); q.unshift(2); q.unshift(1); setTimeout(function () { test.same(queue_order, [ 1, 2, 3, 4 ]); test.done(); }, 100); }, 'too many callbacks': function (test) { test.expect(1); var q = async.queue(function (task, callback) { callback(); test.throws(function() { callback(); }); test.done(); }, 2); q.push(1); }, 'bulk task': function (test) { test.expect(9); var call_order = [], delays = [160,80,240,80]; // worker1: --1-4 // worker2: -2---3 // order of completion: 2,1,4,3 var q = async.queue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); callback('error', task); }, delays.splice(0,1)[0]); }, 2); q.push( [1,2,3,4], function (err, arg) { test.equal(err, 'error'); call_order.push('callback ' + arg); }); test.equal(q.length(), 4); test.equal(q.concurrency, 2); setTimeout(function () { test.same(call_order, [ 'process 2', 'callback 2', 'process 1', 'callback 1', 'process 4', 'callback 4', 'process 3', 'callback 3' ]); test.equal(q.concurrency, 2); test.equal(q.length(), 0); test.done(); }, 800); }, 'idle': function(test) { test.expect(7); var q = async.queue(function (task, callback) { // Queue is busy when workers are running test.equal(q.idle(), false); callback(); }, 1); // Queue is idle before anything added test.equal(q.idle(), true); q.unshift(4); q.unshift(3); q.unshift(2); q.unshift(1); // Queue is busy when tasks added test.equal(q.idle(), false); q.drain = function() { // Queue is idle after drain test.equal(q.idle(), true); test.done(); }; }, 'pause': function(test) { test.expect(3); var call_order = [], task_timeout = 100, pause_timeout = 300, resume_timeout = 500, tasks = [ 1, 2, 3, 4, 5, 6 ], elapsed = (function () { var start = (new Date()).valueOf(); return function () { return Math.round(((new Date()).valueOf() - start) / 100) * 100; }; })(); var q = async.queue(function (task, callback) { call_order.push('process ' + task); call_order.push('timeout ' + elapsed()); callback(); }); function pushTask () { var task = tasks.shift(); if (!task) { return; } setTimeout(function () { q.push(task); pushTask(); }, task_timeout); } pushTask(); setTimeout(function () { q.pause(); test.equal(q.paused, true); }, pause_timeout); setTimeout(function () { q.resume(); test.equal(q.paused, false); }, resume_timeout); setTimeout(function () { test.same(call_order, [ 'process 1', 'timeout 100', 'process 2', 'timeout 200', 'process 3', 'timeout 500', 'process 4', 'timeout 500', 'process 5', 'timeout 500', 'process 6', 'timeout 600' ]); test.done(); }, 800); }, 'pause in worker with concurrency': function(test) { test.expect(1); var call_order = []; var q = async.queue(function (task, callback) { if (task.isLongRunning) { q.pause(); setTimeout(function () { call_order.push(task.id); q.resume(); callback(); }, 500); } else { call_order.push(task.id); callback(); } }, 10); q.push({ id: 1, isLongRunning: true}); q.push({ id: 2 }); q.push({ id: 3 }); q.push({ id: 4 }); q.push({ id: 5 }); setTimeout(function () { test.same(call_order, [1, 2, 3, 4, 5]); test.done(); }, 1000); }, 'pause with concurrency': function(test) { test.expect(4); var call_order = [], task_timeout = 100, pause_timeout = 50, resume_timeout = 300, tasks = [ 1, 2, 3, 4, 5, 6 ], elapsed = (function () { var start = (new Date()).valueOf(); return function () { return Math.round(((new Date()).valueOf() - start) / 100) * 100; }; })(); var q = async.queue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); call_order.push('timeout ' + elapsed()); callback(); }, task_timeout); }, 2); q.push(tasks); setTimeout(function () { q.pause(); test.equal(q.paused, true); }, pause_timeout); setTimeout(function () { q.resume(); test.equal(q.paused, false); }, resume_timeout); setTimeout(function () { test.equal(q.running(), 2); }, resume_timeout + 10); setTimeout(function () { test.same(call_order, [ 'process 1', 'timeout 100', 'process 2', 'timeout 100', 'process 3', 'timeout 400', 'process 4', 'timeout 400', 'process 5', 'timeout 500', 'process 6', 'timeout 500' ]); test.done(); }, 800); }, 'start paused': function (test) { test.expect(2); var q = async.queue(function (task, callback) { setTimeout(function () { callback(); }, 40); }, 2); q.pause(); q.push([1, 2, 3]); setTimeout(function () { q.resume(); }, 5); setTimeout(function () { test.equal(q.tasks.length, 1); test.equal(q.running(), 2); q.resume(); }, 15); q.drain = function () { test.done(); }; }, 'kill': function (test) { test.expect(1); var q = async.queue(function (task, callback) { setTimeout(function () { test.ok(false, "Function should never be called"); callback(); }, 300); }, 1); q.drain = function() { test.ok(false, "Function should never be called"); }; q.push(0); q.kill(); setTimeout(function() { test.equal(q.length(), 0); test.done(); }, 600); }, 'events': function(test) { test.expect(4); var calls = []; var q = async.queue(function(task, cb) { // nop calls.push('process ' + task); async.setImmediate(cb); }, 10); q.concurrency = 3; q.saturated = function() { test.ok(q.length() == 3, 'queue should be saturated now'); calls.push('saturated'); }; q.empty = function() { test.ok(q.length() === 0, 'queue should be empty now'); calls.push('empty'); }; q.drain = function() { test.ok( q.length() === 0 && q.running() === 0, 'queue should be empty now and no more workers should be running' ); calls.push('drain'); test.same(calls, [ 'saturated', 'process foo', 'process bar', 'process zoo', 'foo cb', 'process poo', 'bar cb', 'empty', 'process moo', 'zoo cb', 'poo cb', 'moo cb', 'drain' ]); test.done(); }; q.push('foo', function () {calls.push('foo cb');}); q.push('bar', function () {calls.push('bar cb');}); q.push('zoo', function () {calls.push('zoo cb');}); q.push('poo', function () {calls.push('poo cb');}); q.push('moo', function () {calls.push('moo cb');}); }, 'empty': function(test) { test.expect(2); var calls = []; var q = async.queue(function(task, cb) { // nop calls.push('process ' + task); async.setImmediate(cb); }, 3); q.drain = function() { test.ok( q.length() === 0 && q.running() === 0, 'queue should be empty now and no more workers should be running' ); calls.push('drain'); test.same(calls, [ 'drain' ]); test.done(); }; q.push([]); }, 'saturated': function (test) { test.expect(1); var saturatedCalled = false; var q = async.queue(function(task, cb) { async.setImmediate(cb); }, 2); q.saturated = function () { saturatedCalled = true; }; q.drain = function () { test.ok(saturatedCalled, "saturated not called"); test.done(); }; setTimeout(function () { q.push(['foo', 'bar', 'baz', 'moo']); }, 10); }, 'started': function(test) { test.expect(2); var q = async.queue(function(task, cb) { cb(null, task); }); test.equal(q.started, false); q.push([]); test.equal(q.started, true); test.done(); } }; exports['priorityQueue'] = { 'priorityQueue': function (test) { test.expect(17); var call_order = []; // order of completion: 2,1,4,3 var q = async.priorityQueue(function (task, callback) { call_order.push('process ' + task); callback('error', 'arg'); }, 1); q.push(1, 1.4, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 2); call_order.push('callback ' + 1); }); q.push(2, 0.2, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 3); call_order.push('callback ' + 2); }); q.push(3, 3.8, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 3); }); q.push(4, 2.9, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 1); call_order.push('callback ' + 4); }); test.equal(q.length(), 4); test.equal(q.concurrency, 1); q.drain = function () { test.same(call_order, [ 'process 2', 'callback 2', 'process 1', 'callback 1', 'process 4', 'callback 4', 'process 3', 'callback 3' ]); test.equal(q.concurrency, 1); test.equal(q.length(), 0); test.done(); }; }, 'concurrency': function (test) { test.expect(17); var call_order = [], delays = [160,80,240,80]; // worker1: --2-3 // worker2: -1---4 // order of completion: 1,2,3,4 var q = async.priorityQueue(function (task, callback) { setTimeout(function () { call_order.push('process ' + task); callback('error', 'arg'); }, delays.splice(0,1)[0]); }, 2); q.push(1, 1.4, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 2); call_order.push('callback ' + 1); }); q.push(2, 0.2, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 1); call_order.push('callback ' + 2); }); q.push(3, 3.8, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 3); }); q.push(4, 2.9, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(q.length(), 0); call_order.push('callback ' + 4); }); test.equal(q.length(), 4); test.equal(q.concurrency, 2); q.drain = function () { test.same(call_order, [ 'process 1', 'callback 1', 'process 2', 'callback 2', 'process 3', 'callback 3', 'process 4', 'callback 4' ]); test.equal(q.concurrency, 2); test.equal(q.length(), 0); test.done(); }; } }; exports['cargo'] = { 'cargo': function (test) { test.expect(19); var call_order = [], delays = [160, 160, 80]; // worker: --12--34--5- // order of completion: 1,2,3,4,5 var c = async.cargo(function (tasks, callback) { setTimeout(function () { call_order.push('process ' + tasks.join(' ')); callback('error', 'arg'); }, delays.shift()); }, 2); c.push(1, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(c.length(), 3); call_order.push('callback ' + 1); }); c.push(2, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(c.length(), 3); call_order.push('callback ' + 2); }); test.equal(c.length(), 2); // async push setTimeout(function () { c.push(3, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(c.length(), 1); call_order.push('callback ' + 3); }); }, 60); setTimeout(function () { c.push(4, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(c.length(), 1); call_order.push('callback ' + 4); }); test.equal(c.length(), 2); c.push(5, function (err, arg) { test.equal(err, 'error'); test.equal(arg, 'arg'); test.equal(c.length(), 0); call_order.push('callback ' + 5); }); }, 120); setTimeout(function () { test.same(call_order, [ 'process 1 2', 'callback 1', 'callback 2', 'process 3 4', 'callback 3', 'callback 4', 'process 5' , 'callback 5' ]); test.equal(c.length(), 0); test.done(); }, 800); }, 'without callback': function (test) { test.expect(1); var call_order = [], delays = [160,80,240,80]; // worker: --1-2---34-5- // order of completion: 1,2,3,4,5 var c = async.cargo(function (tasks, callback) { setTimeout(function () { call_order.push('process ' + tasks.join(' ')); callback('error', 'arg'); }, delays.shift()); }, 2); c.push(1); setTimeout(function () { c.push(2); }, 120); setTimeout(function () { c.push(3); c.push(4); c.push(5); }, 180); setTimeout(function () { test.same(call_order, [ 'process 1', 'process 2', 'process 3 4', 'process 5' ]); test.done(); }, 800); }, 'bulk task': function (test) { test.expect(7); var call_order = [], delays = [120,40]; // worker: -123-4- // order of completion: 1,2,3,4 var c = async.cargo(function (tasks, callback) { setTimeout(function () { call_order.push('process ' + tasks.join(' ')); callback('error', tasks.join(' ')); }, delays.shift()); }, 3); c.push( [1,2,3,4], function (err, arg) { test.equal(err, 'error'); call_order.push('callback ' + arg); }); test.equal(c.length(), 4); setTimeout(function () { test.same(call_order, [ 'process 1 2 3', 'callback 1 2 3', 'callback 1 2 3', 'callback 1 2 3', 'process 4', 'callback 4', ]); test.equal(c.length(), 0); test.done(); }, 800); }, 'drain once': function (test) { test.expect(1); var c = async.cargo(function (tasks, callback) { callback(); }, 3); var drainCounter = 0; c.drain = function () { drainCounter++; }; for(var i = 0; i < 10; i++){ c.push(i); } setTimeout(function(){ test.equal(drainCounter, 1); test.done(); }, 500); }, 'drain twice': function (test) { test.expect(1); var c = async.cargo(function (tasks, callback) { callback(); }, 3); var loadCargo = function(){ for(var i = 0; i < 10; i++){ c.push(i); } }; var drainCounter = 0; c.drain = function () { drainCounter++; }; loadCargo(); setTimeout(loadCargo, 500); setTimeout(function(){ test.equal(drainCounter, 2); test.done(); }, 1000); }, 'events': function(test) { test.expect(4); var calls = []; var q = async.cargo(function(task, cb) { // nop calls.push('process ' + task); async.setImmediate(cb); }, 1); q.concurrency = 3; q.saturated = function() { test.ok(q.length() == 3, 'cargo should be saturated now'); calls.push('saturated'); }; q.empty = function() { test.ok(q.length() === 0, 'cargo should be empty now'); calls.push('empty'); }; q.drain = function() { test.ok( q.length() === 0 && q.running() === 0, 'cargo should be empty now and no more workers should be running' ); calls.push('drain'); test.same(calls, [ 'saturated', 'process foo', 'process bar', 'process zoo', 'foo cb', 'process poo', 'bar cb', 'empty', 'process moo', 'zoo cb', 'poo cb', 'moo cb', 'drain' ]); test.done(); }; q.push('foo', function () {calls.push('foo cb');}); q.push('bar', function () {calls.push('bar cb');}); q.push('zoo', function () {calls.push('zoo cb');}); q.push('poo', function () {calls.push('poo cb');}); q.push('moo', function () {calls.push('moo cb');}); }, 'expose payload': function (test) { test.expect(5); var called_once = false; var cargo= async.cargo(function(tasks, cb) { if (!called_once) { test.equal(cargo.payload, 1); test.ok(tasks.length === 1, 'should start with payload = 1'); } else { test.equal(cargo.payload, 2); test.ok(tasks.length === 2, 'next call shold have payload = 2'); } called_once = true; setTimeout(cb, 25); }, 1); cargo.drain = function () { test.done(); }; test.equals(cargo.payload, 1); cargo.push([1, 2, 3]); setTimeout(function () { cargo.payload = 2; }, 15); } }; exports['memoize'] = { 'memoize': function (test) { test.expect(5); var call_order = []; var fn = function (arg1, arg2, callback) { async.setImmediate(function () { call_order.push(['fn', arg1, arg2]); callback(null, arg1 + arg2); }); }; var fn2 = async.memoize(fn); fn2(1, 2, function (err, result) { test.ok(err === null, err + " passed instead of 'null'"); test.equal(result, 3); fn2(1, 2, function (err, result) { test.equal(result, 3); fn2(2, 2, function (err, result) { test.equal(result, 4); test.same(call_order, [['fn',1,2], ['fn',2,2]]); test.done(); }); }); }); }, 'maintains asynchrony': function (test) { test.expect(3); var call_order = []; var fn = function (arg1, arg2, callback) { call_order.push(['fn', arg1, arg2]); async.setImmediate(function () { call_order.push(['cb', arg1, arg2]); callback(null, arg1 + arg2); }); }; var fn2 = async.memoize(fn); fn2(1, 2, function (err, result) { test.equal(result, 3); fn2(1, 2, function (err, result) { test.equal(result, 3); async.nextTick(memoize_done); call_order.push('tick3'); }); call_order.push('tick2'); }); call_order.push('tick1'); function memoize_done() { var async_call_order = [ ['fn',1,2], // initial async call 'tick1', // async caller ['cb',1,2], // async callback // ['fn',1,2], // memoized // memoized async body 'tick2', // handler for first async call // ['cb',1,2], // memoized // memoized async response body 'tick3' // handler for memoized async call ]; test.same(call_order, async_call_order); test.done(); } }, 'unmemoize': function(test) { test.expect(4); var call_order = []; var fn = function (arg1, arg2, callback) { call_order.push(['fn', arg1, arg2]); async.setImmediate(function () { callback(null, arg1 + arg2); }); }; var fn2 = async.memoize(fn); var fn3 = async.unmemoize(fn2); fn3(1, 2, function (err, result) { test.equal(result, 3); fn3(1, 2, function (err, result) { test.equal(result, 3); fn3(2, 2, function (err, result) { test.equal(result, 4); test.same(call_order, [['fn',1,2], ['fn',1,2], ['fn',2,2]]); test.done(); }); }); }); }, 'unmemoize a not memoized function': function(test) { test.expect(1); var fn = function (arg1, arg2, callback) { callback(null, arg1 + arg2); }; var fn2 = async.unmemoize(fn); fn2(1, 2, function(err, result) { test.equal(result, 3); }); test.done(); }, 'error': function (test) { test.expect(1); var testerr = new Error('test'); var fn = function (arg1, arg2, callback) { callback(testerr, arg1 + arg2); }; async.memoize(fn)(1, 2, function (err) { test.equal(err, testerr); }); test.done(); }, 'multiple calls': function (test) { test.expect(3); var fn = function (arg1, arg2, callback) { test.ok(true); setTimeout(function(){ callback(null, arg1, arg2); }, 10); }; var fn2 = async.memoize(fn); fn2(1, 2, function(err, result) { test.equal(result, 1, 2); }); fn2(1, 2, function(err, result) { test.equal(result, 1, 2); test.done(); }); }, 'custom hash function': function (test) { test.expect(2); var testerr = new Error('test'); var fn = function (arg1, arg2, callback) { callback(testerr, arg1 + arg2); }; var fn2 = async.memoize(fn, function () { return 'custom hash'; }); fn2(1, 2, function (err, result) { test.equal(result, 3); fn2(2, 2, function (err, result) { test.equal(result, 3); test.done(); }); }); }, 'manually added memo value': function (test) { test.expect(1); var fn = async.memoize(function() { test(false, "Function should never be called"); }); fn.memo["foo"] = ["bar"]; fn("foo", function(val) { test.equal(val, "bar"); test.done(); }); } }; exports['ensureAsync'] = { 'defer sync functions': function (test) { test.expect(6); var sync = true; async.ensureAsync(function (arg1, arg2, cb) { test.equal(arg1, 1); test.equal(arg2, 2); cb(null, 4, 5); })(1, 2, function (err, arg4, arg5) { test.equal(err, null); test.equal(arg4, 4); test.equal(arg5, 5); test.ok(!sync, 'callback called on same tick'); test.done(); }); sync = false; }, 'do not defer async functions': function (test) { test.expect(6); var sync = false; async.ensureAsync(function (arg1, arg2, cb) { test.equal(arg1, 1); test.equal(arg2, 2); async.setImmediate(function () { sync = true; cb(null, 4, 5); sync = false; }); })(1, 2, function (err, arg4, arg5) { test.equal(err, null); test.equal(arg4, 4); test.equal(arg5, 5); test.ok(sync, 'callback called on next tick'); test.done(); }); }, 'double wrapping': function (test) { test.expect(6); var sync = true; async.ensureAsync(async.ensureAsync(function (arg1, arg2, cb) { test.equal(arg1, 1); test.equal(arg2, 2); cb(null, 4, 5); }))(1, 2, function (err, arg4, arg5) { test.equal(err, null); test.equal(arg4, 4); test.equal(arg5, 5); test.ok(!sync, 'callback called on same tick'); test.done(); }); sync = false; } }; exports['constant'] = function (test) { test.expect(5); var f = async.constant(42, 1, 2, 3); f(function (err, value, a, b, c) { test.ok(!err); test.ok(value === 42); test.ok(a === 1); test.ok(b === 2); test.ok(c === 3); test.done(); }); }; exports['asyncify'] = { 'asyncify': function (test) { var parse = async.asyncify(JSON.parse); parse("{\"a\":1}", function (err, result) { test.ok(!err); test.ok(result.a === 1); test.done(); }); }, 'asyncify null': function (test) { var parse = async.asyncify(function() { return null; }); parse("{\"a\":1}", function (err, result) { test.ok(!err); test.ok(result === null); test.done(); }); }, 'variable numbers of arguments': function (test) { async.asyncify(function (x, y, z) { test.ok(arguments.length === 3); test.ok(x === 1); test.ok(y === 2); test.ok(z === 3); })(1, 2, 3, function () {}); test.done(); }, 'catch errors': function (test) { async.asyncify(function () { throw new Error("foo"); })(function (err) { test.ok(err); test.ok(err.message === "foo"); test.done(); }); }, 'dont catch errors in the callback': function (test) { try { async.asyncify(function () {})(function (err) { if (err) { return test.done(new Error("should not get an error here")); } throw new Error("callback error"); }); } catch (e) { test.ok(e.message === "callback error"); test.done(); } }, 'promisified': [ 'native-promise-only', 'bluebird', 'es6-promise', 'rsvp' ].reduce(function(promises, name) { if (isBrowser()) { // node only test return; } var Promise = require(name); if (typeof Promise.Promise === 'function') { Promise = Promise.Promise; } promises[name] = { 'resolve': function(test) { var promisified = function(argument) { return new Promise(function (resolve) { setTimeout(function () { resolve(argument + " resolved"); }, 15); }); }; async.asyncify(promisified)("argument", function (err, value) { if (err) { return test.done(new Error("should not get an error here")); } test.ok(value === "argument resolved"); test.done(); }); }, 'reject': function(test) { var promisified = function(argument) { return new Promise(function (resolve, reject) { reject(argument + " rejected"); }); }; async.asyncify(promisified)("argument", function (err) { test.ok(err); test.ok(err.message === "argument rejected"); test.done(); }); } }; return promises; }, {}) };
/** * Runs a webserver and socket server for visualizating interactions with TJBot */ var ip = require('ip'); var express = require("express") var config = require('./config.js') var path = require("path") var app = express(); var http = require('http'); var exports = module.exports = {}; // routes var routes = require('./routes/index'); var server = http.createServer(app).listen(config.webServerNumber, function() { var addr = server.address(); console.log('Dashboard running at : http://' + ip.address() + ':' + addr.port); }); var bodyParser = require('body-parser'); var bodyParser = require('body-parser'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()); app.set('view engine', 'pug'); app.use(express.static('public')); app.use('/', routes); var WebSocket = require('ws'); var wss = new WebSocket.Server({ server }); var clients = new Map(); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { }); clients.set(ws._socket._handle.fd, ws); //clients.push({id: ws._socket._handle.fd , client: }); // ws.send('something ......'); var hold = ws; ws.on('close', function close() { console.log("closing "); // clients.delete(ws._socket._handle.fd); }); }); var sendEvent = function(data) { console.log("Number of connectd clients", clients.size) for (var [key, client] of clients) { //console.log(key + ' = sending'); if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(data)) } else { clients.delete(key); } } } exports.sendEvent = sendEvent; exports.wss = wss
import 'webrtc-adapter/out/adapter.js'; import EventEmitter from 'events'; var configuration = { iceServers: [ {urls: "stun:stun.l.google.com:19302"}, {urls: "turn:numb.viagenie.ca", credential: "w0kkaw0kka", username: "paul.sachs%40influitive.com"} ] }; export default class FirePeer extends EventEmitter { constructor(firebaseRef, userId, isMuted, isVideoMuted){ super(); this.firebaseRef = firebaseRef; this.userRef = firebaseRef.child(userId); this.userId = userId; this.eventHandlers = {}; this.options = { audio: true, video: true }; this.connections = {}; // Stores mediastreams with the key being the id of the target peer this.mediaStreams = {}; this.isMutedRef = this.userRef.child("isMuted"); this.isVideoMutedRef = this.userRef.child("isVideoMuted"); this.offersRef = this.userRef.child("offers"); this.answersRef = this.userRef.child("answers"); this.userRef.onDisconnect().remove(); this.isMuted = isMuted; this.isVideoMuted = isVideoMuted; this.isMutedRef.set(this.isMuted); this.isVideoMutedRef.set(this.isVideoMuted); this.offersRef.on("child_added", (snapshot) => { const data = snapshot.val(); const incomingPeerId = snapshot.key(); this.acceptOffer(incomingPeerId, data).then(()=>{ // Delete the offer once accepted. this.offersRef.child(incomingPeerId).set(null); }); }); this.answersRef.on("child_added", (snapshot) => { const data = snapshot.val(); const incomingPeerId = snapshot.key(); this.handleAnswer(incomingPeerId, data).then(()=>{ // Delete the offer once accepted. this.answersRef.child(incomingPeerId).set(null); }); }); this.firebaseRef.on("child_removed", (snapshot) => { const peerId = snapshot.key(); if (this.userId == peerId) { this.handleDisconnect(); } }); this.isMutedRef.on("value", this.handleIsMuted); this.isVideoMutedRef.on("value", this.handleIsVideoMuted); } connect = (peerId) => { if (this.connections[peerId] && this.connections[peerId].signalingState != 'closed') { console.log('Could send offer, already have connection'); return; } const connection = new RTCPeerConnection(configuration); this.connections[peerId] = connection; this.onaddstream = this.handleAddStream; // place an offer on the room. const media = this.getPeerMedia(); return media.then((mediaStream)=> { connection.addStream(mediaStream); this.emit('stream_added', { stream: mediaStream, isSelf: true}); this.mediaStreams[peerId] = mediaStream; return connection.createOffer(); }).then((desc)=> { return connection.setLocalDescription(desc); }).then(() => { const desc = connection.localDescription; this.firebaseRef.child(peerId).child("offers").child(this.userId) .set(JSON.stringify(desc.sdp)); this.emit('sent_offer', peerId, desc); }).catch(this.handleError); }; disconnectFrom = (peerId) => { if(this.connections[peerId]) { this.connections[peerId].close(); } }; mute = (mute) => { this.isMutedRef.set(mute); }; muteVideo = (mute) => { this.isVideoMutedRef.set(mute); }; disconnect = () => { this.userRef.remove(); }; // Private: handleDisconnect = () => { for (let key of Object.keys(this.connections)) { this.connections[key].close(); } } getPeerMedia = () => { const media = navigator.mediaDevices.getUserMedia( { audio: !this.isMuted, video: !this.isVideoMuted} ); return media; }; handleAddStream = (event) => { this.emit('stream_added', { stream: event.stream, isSelf: false}); }; acceptOffer = (peerId, offer) => { if (this.connections[peerId] && this.connections[peerId].signalingState != 'closed') { console.log('Could not accept offer, already have connection'); return; } const connection = new RTCPeerConnection(configuration); this.connections[peerId] = connection; // place an offer on the room. const media = this.getPeerMedia(); const remote_descr = new RTCSessionDescription(); remote_descr.type = "offer"; remote_descr.sdp = JSON.parse(offer); return media.then((mediaStream)=> { connection.addStream(mediaStream); this.emit('stream_added', { stream: mediaStream, isSelf: true}); this.mediaStreams[peerId] = mediaStream; return connection.setRemoteDescription(remote_descr); }).then(()=> { return connection.createAnswer(); }).then((answer) => { return connection.setLocalDescription(answer); }).then(()=> { const answer = connection.localDescription; this.firebaseRef.child(peerId).child("answers").child(this.userId) .set(JSON.stringify(answer.sdp)); this.emit('accepted_offer', peerId, answer); }).catch(this.handleError); }; handleAnswer = (peerId, answer) => { const remote_descr = new RTCSessionDescription(); remote_descr.type = "answer"; remote_descr.sdp = JSON.parse(answer); return this.connections[peerId].setRemoteDescription(remote_descr).then(() => { this.emit('handled_answer', peerId, answer); }).catch(this.handleError); }; handleError = (error) => { console.error("FirePeer: "); console.error(error); }; handleIsMuted = (snapshot) => { this.isMuted = snapshot.val(); for (const peerId of Object.keys(this.mediaStreams)) { const stream = this.mediaStreams[peerId]; const audioTracks = stream.getAudioTracks(); for (const audioTrack of audioTracks) { audioTrack.enabled = !this.isMuted; } } this.emit("muted", this.isMuted); }; handleIsVideoMuted = (snapshot) => { this.isVideoMuted = snapshot.val(); for (const peerId of Object.keys(this.mediaStreams)) { const stream = this.mediaStreams[peerId]; const videoTracks = stream.getVideoTracks(); for (const videoTrack of videoTracks) { videoTrack.enabled = !this.isVideoMuted; } } this.emit("video_muted", this.isVideoMuted); }; logInfo = () => { for (const peerId of Object.keys(this.mediaStreams)) { const stream = this.mediaStreams[peerId]; console.log(peerId); console.log("----"); console.log("stream:"); console.log(stream); console.log("audioTracks:"); console.log(stream.getAudioTracks()); console.log("videoTracks:"); console.log(stream.getVideoTracks()); console.log("----"); } } }
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.Mars || (g.Mars = {})).React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Component for rendering data container */ var DataManagerContainer = function (_React$Component) { _inherits(DataManagerContainer, _React$Component); function DataManagerContainer(props, context) { _classCallCheck(this, DataManagerContainer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(DataManagerContainer).call(this, props, context)); _this.state = { result: {} }; _this.query = props.component.getQuery(props.variables); _this.query.on('update', _this._handleDataChanges.bind(_this)); _this._executeQuery(); return _this; } _createClass(DataManagerContainer, [{ key: '_executeQuery', value: function _executeQuery() { var _this2 = this; this._resolved = false; this.query.execute().then(function (result) { _this2._resolved = true; _this2.setState({ result: result }); }); } }, { key: '_handleDataChanges', value: function _handleDataChanges(result) { if (this._resolved) { this.setState({ result: result }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.query.stop(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.query.updateVariables(nextProps); } }, { key: 'renderLoading', value: function renderLoading() { return this.props.renderLoading(); } }, { key: 'render', value: function render() { var Component = this.props.component; // eslint-disable-line return this._resolved ? _react2.default.createElement(Component, _extends({}, this.props, this.state.result)) : this.renderLoading(); } }]); return DataManagerContainer; }(_react2.default.Component); DataManagerContainer.defaultProps = { renderLoading: function renderLoading() { return null; } }; exports.default = DataManagerContainer; },{"react":undefined}],2:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _forEach = require('fast.js/forEach'); var _forEach2 = _interopRequireDefault(_forEach); var _map2 = require('fast.js/map'); var _map3 = _interopRequireDefault(_map2); var _keys2 = require('fast.js/object/keys'); var _keys3 = _interopRequireDefault(_keys2); var _marsdb = require('marsdb'); var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _utils = require('./utils'); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * ExecutionContext is used to track changes of variables * and cursors and cleanup listeners on parent cursor changes. * It also provides a method to run a function "in context": * while function running, `ExecutionContext.getCurrentContext()` * returning the context. */ var ExecutionContext = function (_EventEmitter) { _inherits(ExecutionContext, _EventEmitter); function ExecutionContext() { var variables = arguments.length <= 0 || arguments[0] === undefined ? new Map() : arguments[0]; _classCallCheck(this, ExecutionContext); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ExecutionContext).call(this)); _this.variables = variables; _this.emitCleanup = _this.emitCleanup.bind(_this); return _this; } /** * Adds a cleanup event listener and return a funtion * for removing listener. * @param {Function} fn * @return {Function} */ _createClass(ExecutionContext, [{ key: 'addCleanupListener', value: function addCleanupListener(fn) { var _this2 = this; this.on('cleanup', fn); return function () { return _this2.removeListener('cleanup', fn); }; } /** * Emits cleanup event. Given argument indicates the source * of the event. If it is `false`, then the event will be * interprated as "went from upper context". * @param {Boolean} isRoot */ }, { key: 'emitCleanup', value: function emitCleanup() { var isRoot = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; this.emit('cleanup', isRoot); } /** * Creates a child context, that have the same map of variables. * Set context cleanup listener for propagating the event to the child. * Return child context object. * @return {ExecutionContext} */ }, { key: 'createChildContext', value: function createChildContext() { var newContext = new ExecutionContext(this.variables); var stopper = this.addCleanupListener(function (isRoot) { newContext.emitCleanup(false); if (!isRoot) { stopper(); } }); return newContext; } /** * Execute given function "in context": set the context * as globally active with saving of previous active context, * and execute a function. While function executing * `ExecutionContext.getCurrentContext()` will return the context. * At the end of the execution it puts previous context back. * @param {Function} fn */ }, { key: 'withinContext', value: function withinContext(fn) { var prevContext = ExecutionContext.getCurrentContext(); ExecutionContext.__currentContext = this; try { return fn(); } finally { ExecutionContext.__currentContext = prevContext; } } /** * By given container class get variables from * the context and merge it with given initial values * and variables mapping. Return the result of the merge. * @param {Class} containerClass * @param {OBject} initVars * @param {Object} mapVars * @return {Object} */ }, { key: 'getVariables', value: function getVariables(containerClass) { var initVars = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var mapVars = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var prepareVariables = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var contextVars = this.variables.get(containerClass); if (!contextVars) { contextVars = {}; this.variables.set(containerClass, contextVars); } for (var k in initVars) { if (contextVars[k] === undefined) { if (mapVars[k] !== undefined) { (0, _invariant2.default)(utils._isProperty(mapVars[k]), 'You can pass to a mapping only parent variables'); contextVars[k] = mapVars[k]; } else { contextVars[k] = utils._createProperty(initVars[k]); } } } if (prepareVariables && !contextVars.promise) { Object.defineProperty(contextVars, 'promise', { value: Promise.resolve(prepareVariables(contextVars)), configurable: true }); } return contextVars; } /** * Track changes of given variable and regenerate value * on change. It also listen to context cleanup event * for stop variable change listeners * @param {Property} prop * @param {Object} vars * @param {Function} valueGenerator */ }, { key: 'trackVariablesChange', value: function trackVariablesChange(prop, vars, valueGenerator) { var _this3 = this; var updater = function updater() { _this3.emitCleanup(); if (prop.promise && prop.promise.stop) { prop.promise.stop(); } var nextValue = _this3.withinContext(function () { return valueGenerator(vars); }); if (utils._isCursor(nextValue)) { _this3.trackCursorChange(prop, nextValue); prop.emitChange(); } else if (!utils._isProperty(nextValue)) { prop(nextValue); } else { // Variables tracking must be used only vhen valueGenerator // returns a Cursor or any type except Property. throw new Error('Next value can\'t be a property'); } }; var varTrackers = (0, _map3.default)((0, _keys3.default)(vars), function (k) { return vars[k].addChangeListener(updater); }); var stopper = this.addCleanupListener(function (isRoot) { if (!isRoot) { (0, _forEach2.default)(varTrackers, function (stop) { return stop(); }); stopper(); } }); } /** * Observe given cursor for changes and set new * result in given property. Also tracks context * cleanup event for stop observers * @param {Property} prop * @param {Cursor} cursor */ }, { key: 'trackCursorChange', value: function trackCursorChange(prop, cursor) { var _this4 = this; if (prop.removeCursorTracker) { prop.removeCursorTracker(); } var observer = function observer(result) { if (Array.isArray(result)) { result = (0, _map3.default)(result, function (x) { return utils._createPropertyWithContext(x, _this4); }); } prop(result); }; cursor.on('cursorChanged', this.emitCleanup); prop.promise = cursor.observe(observer); prop.removeCursorTracker = function () { cursor.removeListener('cursorChanged', _this4.emitCleanup); prop.promise.stop(); }; var stopper = this.addCleanupListener(function (isRoot) { if (!isRoot) { prop.removeCursorTracker(); stopper(); } }); } /** * Returns a current active context, set by `withinContext` * @return {ExecutionContext} */ }], [{ key: 'getCurrentContext', value: function getCurrentContext() { return ExecutionContext.__currentContext; } }]); return ExecutionContext; }(_marsdb.EventEmitter); exports.default = ExecutionContext; },{"./utils":5,"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"invariant":16,"marsdb":undefined}],3:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _keys2 = require('fast.js/object/keys'); var _keys3 = _interopRequireDefault(_keys2); var _forEach = require('fast.js/forEach'); var _forEach2 = _interopRequireDefault(_forEach); var _map2 = require('fast.js/map'); var _map3 = _interopRequireDefault(_map2); var _marsdb = require('marsdb'); var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionContext = require('./ExecutionContext'); var _ExecutionContext2 = _interopRequireDefault(_ExecutionContext); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * By given frgments object, varialbes and containerClass * creates a query executor. * It will execute each fragment of fragments object and * return a promise, that will be resolved when all fragments * is filled with data. * * Container class is an object with one static function – `getFragment`, * that must return a property function. By all properties constructed * a Promise that resolved when all `prop.promise` resolved. * * The class extends `EventEmitter`.Only one event may be emitted – `update`. * The event emitted when query data is updated. With event is arrived an object * of proprties for each fragment. */ var QueryExecutor = function (_EventEmitter) { _inherits(QueryExecutor, _EventEmitter); function QueryExecutor(fragments, initVarsOverride, containerClass, prepareVariables) { _classCallCheck(this, QueryExecutor); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(QueryExecutor).call(this)); _this.containerClass = containerClass; _this.fragmentNames = (0, _keys3.default)(fragments); _this.initVarsOverride = initVarsOverride; _this.context = new _ExecutionContext2.default(); _this.variables = _this.context.getVariables(containerClass, initVarsOverride, {}, prepareVariables); _this._handleDataChanges = (0, _marsdb.debounce)(_this._handleDataChanges.bind(_this), 1000 / 60, 5); return _this; } /** * Change a batch size of updater. * Btach size is a number of changes must be happen * in debounce interval to force execute debounced * function (update a result, in our case) * * @param {Number} batchSize * @return {CursorObservable} */ _createClass(QueryExecutor, [{ key: 'batchSize', value: function batchSize(_batchSize) { this._handleDataChanges.updateBatchSize(_batchSize); return this; } /** * Change debounce wait time of the updater * @param {Number} waitTime * @return {CursorObservable} */ }, { key: 'debounce', value: function debounce(waitTime) { this._handleDataChanges.updateWait(waitTime); return this; } /** * Execute the query and return a Promise, that resolved * when all props will be filled with data. * If query already executing it just returns a promise * for currently executing query. * @return {Promise} */ }, { key: 'execute', value: function execute() { var _this2 = this; if (!this._execution) { (function () { _this2.result = {}; _this2.context.withinContext(function () { (0, _forEach2.default)(_this2.fragmentNames, function (k) { _this2.result[k] = _this2.containerClass.getFragment(k); }); }); var updater = function updater() { _this2._execution = _this2._handleDataChanges(); }; _this2._stoppers = (0, _map3.default)(_this2.fragmentNames, function (k) { return _this2.result[k].addChangeListener(updater); }); updater(); })(); } return this._execution; } /** * Stops query executing and listening for changes. * Returns a promise resolved when query stopped. * @return {Promise} */ }, { key: 'stop', value: function stop() { var _this3 = this; (0, _invariant2.default)(this._execution, 'stop(...): query is not executing'); // Remove all update listeners synchronously to avoid // updates of old data this.removeAllListeners(); return this._execution.then(function () { (0, _forEach2.default)(_this3._stoppers, function (stop) { return stop(); }); _this3.context.emitCleanup(); _this3._execution = null; }); } /** * Update top level variables of the query by setting * values in variable props from given object. If field * exists in a given object and not exists in variables map * then it will be ignored. * @param {Object} nextProps * @return {Promise} resolved when variables updated */ }, { key: 'updateVariables', value: function updateVariables(nextProps) { var _this4 = this; (0, _invariant2.default)(this._execution, 'updateVariables(...): query is not executing'); return this._execution.then(function () { var updated = false; (0, _forEach2.default)(nextProps, function (prop, k) { if (_this4.variables[k] && _this4.variables[k]() !== prop) { _this4.variables[k](prop); updated = true; } }); return updated; }); } /** * The method is invoked when some of fragment's property is updated. * It emits an `update` event only when all `prop.promise` is resolved. */ }, { key: '_handleDataChanges', value: function _handleDataChanges() { var _this5 = this; var nextPromises = (0, _map3.default)(this.fragmentNames, function (k) { return _this5.result[k].promise; }); var resultPromise = Promise.all(nextPromises).then(function () { if (_this5._resultPromise === resultPromise) { _this5.emit('update', _this5.result); } return _this5.result; }, function (error) { _this5.emit('error', error); return _this5.result; }); this._resultPromise = resultPromise; return this._resultPromise; } }]); return QueryExecutor; }(_marsdb.EventEmitter); exports.default = QueryExecutor; },{"./ExecutionContext":2,"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"invariant":16,"marsdb":undefined}],4:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.default = createContainer; var _keys2 = require('fast.js/object/keys'); var _keys3 = _interopRequireDefault(_keys2); var _assign2 = require('fast.js/object/assign'); var _assign3 = _interopRequireDefault(_assign2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionContext = require('./ExecutionContext'); var _ExecutionContext2 = _interopRequireDefault(_ExecutionContext); var _QueryExecutor = require('./QueryExecutor'); var _QueryExecutor2 = _interopRequireDefault(_QueryExecutor); var _utils = require('./utils'); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * High-order data container creator * @param {Component} Component * @param {Object} options.fragments * @param {Object} options.initVars * @return {Component} */ function createContainer(Component, _ref) { var _ref$fragments = _ref.fragments; var fragments = _ref$fragments === undefined ? {} : _ref$fragments; var _ref$initialVariables = _ref.initialVariables; var initialVariables = _ref$initialVariables === undefined ? {} : _ref$initialVariables; var _ref$prepareVariables = _ref.prepareVariables; var prepareVariables = _ref$prepareVariables === undefined ? null : _ref$prepareVariables; var componentName = Component.displayName || Component.name; var containerName = 'Mars(' + componentName + ')'; var fragmentKeys = (0, _keys3.default)(fragments); var Container = function (_React$Component) { _inherits(Container, _React$Component); function Container() { _classCallCheck(this, Container); return _possibleConstructorReturn(this, Object.getPrototypeOf(Container).apply(this, arguments)); } _createClass(Container, [{ key: 'render', value: function render() { var variables = this.props[fragmentKeys[0]].context.getVariables(Container); return _react2.default.createElement(Component, _extends({}, this.props, { variables: variables })); } }], [{ key: 'getFragment', value: function getFragment(name, mapping) { var initVarsOverride = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var parentContext = arguments[3]; parentContext = parentContext || _ExecutionContext2.default.getCurrentContext(); (0, _invariant2.default)(parentContext, 'getFragment(...): must be invoked within some context'); var childContext = parentContext.createChildContext(); var fragment = fragments[name]; var initVars = (0, _assign3.default)({}, initialVariables, initVarsOverride); var vars = childContext.getVariables(Container, initVars, mapping, prepareVariables); (0, _invariant2.default)(typeof fragment === 'function' || (typeof fragment === 'undefined' ? 'undefined' : _typeof(fragment)) === 'object', 'getFragment(...): a fragment must be a function or an object'); if ((typeof fragment === 'undefined' ? 'undefined' : _typeof(fragment)) === 'object') { return utils._getJoinFunction(Container, fragment, vars, childContext); } else { return utils._getFragmentValue(Container, fragment, vars, childContext); } } }, { key: 'getQuery', value: function getQuery() { var initVarsOverride = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var initVars = (0, _assign3.default)({}, initialVariables, initVarsOverride); return new _QueryExecutor2.default(fragments, initVars, Container, prepareVariables); } }]); return Container; }(_react2.default.Component); Container.displayName = containerName; return Container; } },{"./ExecutionContext":2,"./QueryExecutor":3,"./utils":5,"fast.js/object/assign":12,"fast.js/object/keys":14,"invariant":16,"react":undefined}],5:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.noop = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports._isProperty = _isProperty; exports._isCursor = _isCursor; exports._getFragmentValue = _getFragmentValue; exports._getJoinFunction = _getJoinFunction; exports._createProperty = _createProperty; exports._createPropertyWithContext = _createPropertyWithContext; var _forEach = require('fast.js/forEach'); var _forEach2 = _interopRequireDefault(_forEach); var _map2 = require('fast.js/map'); var _map3 = _interopRequireDefault(_map2); var _keys2 = require('fast.js/object/keys'); var _keys3 = _interopRequireDefault(_keys2); var _marsdb = require('marsdb'); var _CursorObservable = require('marsdb/dist/CursorObservable'); var _CursorObservable2 = _interopRequireDefault(_CursorObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Internals var _propertyVersionId = 0; var noop = exports.noop = function noop() {}; // eslint-disable-line /** * Return true if given value is a property * @param {Object} val * @return {Boolean} */ function _isProperty(val) { return typeof val === 'function' && !!val.isProperty; } /** * Return true if given value is a CursorObservable * @param {OBject} val * @return {Boolean} */ function _isCursor(val) { return val instanceof _CursorObservable2.default; } /** * Return a property, that updated when value * of fragment changed or variable changed. It do nothing * if generated value is already a property (just returns * the property). * * @param {Class} containerClass * @param {Function} valueGenerator * @param {Object} vars * @param {ExecutionContext} context * @return {Property} */ function _getFragmentValue(containerClass, valueGenerator, vars, context) { var _createFragmentProp = function _createFragmentProp() { var value = context.withinContext(function () { return valueGenerator(vars); }); var prop = undefined; if (_isProperty(value)) { prop = value; } else { prop = _createPropertyWithContext(null, context); if (_isCursor(value)) { context.trackCursorChange(prop, value); } else { prop(value); } context.trackVariablesChange(prop, vars, valueGenerator); } return prop; }; if (vars.promise) { var _ret = function () { var proxyProp = _createPropertyWithContext(null, context); proxyProp.promise = vars.promise.then(function () { var fragProp = _createFragmentProp(); if (fragProp() !== null) { proxyProp.emitChange(); } proxyProp.proxyTo(fragProp); return fragProp.promise; }); return { v: proxyProp }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } else { return _createFragmentProp(); } } /** * Return a function that join the result of given joinObj. * @param {Class} containerClass * @param {Object} joinObj * @param {Object} vars * @param {ExecutionContext} context * @return {Function} */ function _getJoinFunction(containerClass, joinObj, vars, context) { var joinObjKeys = (0, _keys3.default)(joinObj); return function (doc) { var updated = arguments.length <= 1 || arguments[1] === undefined ? noop : arguments[1]; if ((typeof doc === 'undefined' ? 'undefined' : _typeof(doc)) === 'object' && doc !== null) { return (0, _map3.default)(joinObjKeys, function (k) { if (doc[k] === undefined) { var _ret2 = function () { var valueGenerator = function valueGenerator(opts) { return joinObj[k](doc, opts); }; var prop = _getFragmentValue(containerClass, valueGenerator, vars, context); doc[k] = prop; return { v: Promise.resolve(prop.promise).then(function (res) { var changeStopper = prop.addChangeListener(updated); var cleanStopper = context.addCleanupListener(function (isRoot) { if (!isRoot) { cleanStopper(); changeStopper(); } }); return res; }) }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } }); } }; } /** * Creates a getter-setter property function. * The function returns current value if called without * arguments. If first argument passed then it sets new * value and returns new value. * * On set of a new value it emits a change event. You can * listen on a change event by calling `addChangeListener` * which adds a change event handler that returns a function * for stopping listening. * * A property also have a `version` field. It's a unique value * across all active properties. A version is changed when * property have changed before emitting change event. * * @param {Mixed} initValue * @return {Property} */ function _createProperty(initValue) { var emitter = new _marsdb.EventEmitter(); var store = initValue; var proxyProp = null; var prop = function prop() { if (proxyProp) { return proxyProp.apply(null, arguments); } else { if (arguments.length > 0) { store = arguments[0]; if (arguments.length === 1) { prop.emitChange(); } } return store; } }; prop.emitChange = function () { prop.version = ++_propertyVersionId; emitter.emit('change'); }; prop.addChangeListener = function (func) { emitter.on('change', func); return function () { emitter.removeListener('change', func); }; }; prop.proxyTo = function (toProp) { proxyProp = toProp; Object.defineProperty(prop, 'version', { get: function get() { return toProp.version; }, set: function set(newValue) { return toProp.version = newValue; } }); prop.addChangeListener = toProp.addChangeListener; prop.emitChange = toProp.emitChange; (0, _forEach2.default)(emitter.listeners('change'), function (cb) { return toProp.addChangeListener(cb); }); emitter = toProp.__emitter; store = null; }; prop.version = ++_propertyVersionId; prop.isProperty = true; prop.__emitter = emitter; return prop; } /** * Create a property that holds given value and context. * @param {Mixed} value * @param {ExecutionContext} context * @return {Property} */ function _createPropertyWithContext(value, context) { var nextProp = _createProperty(value); nextProp.context = context; return nextProp; } },{"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"marsdb":undefined,"marsdb/dist/CursorObservable":undefined}],6:[function(require,module,exports){ var createContainer = require('./dist/createContainer').default; var DataManagerContainer = require('./dist/DataManagerContainer').default; module.exports = { __esModule: true, createContainer: createContainer, DataManagerContainer: DataManagerContainer }; },{"./dist/DataManagerContainer":1,"./dist/createContainer":4}],7:[function(require,module,exports){ 'use strict'; var bindInternal3 = require('../function/bindInternal3'); /** * # For Each * * A fast `.forEach()` implementation. * * @param {Array} subject The array (or array-like) to iterate over. * @param {Function} fn The visitor function. * @param {Object} thisContext The context for the visitor. */ module.exports = function fastForEach (subject, fn, thisContext) { var length = subject.length, iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn, i; for (i = 0; i < length; i++) { iterator(subject[i], i, subject); } }; },{"../function/bindInternal3":10}],8:[function(require,module,exports){ 'use strict'; var bindInternal3 = require('../function/bindInternal3'); /** * # Map * * A fast `.map()` implementation. * * @param {Array} subject The array (or array-like) to map over. * @param {Function} fn The mapper function. * @param {Object} thisContext The context for the mapper. * @return {Array} The array containing the results. */ module.exports = function fastMap (subject, fn, thisContext) { var length = subject.length, result = new Array(length), iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn, i; for (i = 0; i < length; i++) { result[i] = iterator(subject[i], i, subject); } return result; }; },{"../function/bindInternal3":10}],9:[function(require,module,exports){ 'use strict'; var forEachArray = require('./array/forEach'), forEachObject = require('./object/forEach'); /** * # ForEach * * A fast `.forEach()` implementation. * * @param {Array|Object} subject The array or object to iterate over. * @param {Function} fn The visitor function. * @param {Object} thisContext The context for the visitor. */ module.exports = function fastForEach (subject, fn, thisContext) { if (subject instanceof Array) { return forEachArray(subject, fn, thisContext); } else { return forEachObject(subject, fn, thisContext); } }; },{"./array/forEach":7,"./object/forEach":13}],10:[function(require,module,exports){ 'use strict'; /** * Internal helper to bind a function known to have 3 arguments * to a given context. */ module.exports = function bindInternal3 (func, thisContext) { return function (a, b, c) { return func.call(thisContext, a, b, c); }; }; },{}],11:[function(require,module,exports){ 'use strict'; var mapArray = require('./array/map'), mapObject = require('./object/map'); /** * # Map * * A fast `.map()` implementation. * * @param {Array|Object} subject The array or object to map over. * @param {Function} fn The mapper function. * @param {Object} thisContext The context for the mapper. * @return {Array|Object} The array or object containing the results. */ module.exports = function fastMap (subject, fn, thisContext) { if (subject instanceof Array) { return mapArray(subject, fn, thisContext); } else { return mapObject(subject, fn, thisContext); } }; },{"./array/map":8,"./object/map":15}],12:[function(require,module,exports){ 'use strict'; /** * Analogue of Object.assign(). * Copies properties from one or more source objects to * a target object. Existing keys on the target object will be overwritten. * * > Note: This differs from spec in some important ways: * > 1. Will throw if passed non-objects, including `undefined` or `null` values. * > 2. Does not support the curious Exception handling behavior, exceptions are thrown immediately. * > For more details, see: * > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign * * * * @param {Object} target The target object to copy properties to. * @param {Object} source, ... The source(s) to copy properties from. * @return {Object} The updated target object. */ module.exports = function fastAssign (target) { var totalArgs = arguments.length, source, i, totalKeys, keys, key, j; for (i = 1; i < totalArgs; i++) { source = arguments[i]; keys = Object.keys(source); totalKeys = keys.length; for (j = 0; j < totalKeys; j++) { key = keys[j]; target[key] = source[key]; } } return target; }; },{}],13:[function(require,module,exports){ 'use strict'; var bindInternal3 = require('../function/bindInternal3'); /** * # For Each * * A fast object `.forEach()` implementation. * * @param {Object} subject The object to iterate over. * @param {Function} fn The visitor function. * @param {Object} thisContext The context for the visitor. */ module.exports = function fastForEachObject (subject, fn, thisContext) { var keys = Object.keys(subject), length = keys.length, iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn, key, i; for (i = 0; i < length; i++) { key = keys[i]; iterator(subject[key], key, subject); } }; },{"../function/bindInternal3":10}],14:[function(require,module,exports){ 'use strict'; /** * Object.keys() shim for ES3 environments. * * @param {Object} obj The object to get keys for. * @return {Array} The array of keys. */ module.exports = typeof Object.keys === "function" ? Object.keys : /* istanbul ignore next */ function fastKeys (obj) { var keys = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { keys.push(key); } } return keys; }; },{}],15:[function(require,module,exports){ 'use strict'; var bindInternal3 = require('../function/bindInternal3'); /** * # Map * * A fast object `.map()` implementation. * * @param {Object} subject The object to map over. * @param {Function} fn The mapper function. * @param {Object} thisContext The context for the mapper. * @return {Object} The new object containing the results. */ module.exports = function fastMapObject (subject, fn, thisContext) { var keys = Object.keys(subject), length = keys.length, result = {}, iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn, i, key; for (i = 0; i < length; i++) { key = keys[i]; result[key] = iterator(subject[key], key, subject); } return result; }; },{"../function/bindInternal3":10}],16:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; },{}]},{},[6])(6) });
module.exports = LoadsModels const resolve = require.resolve function LoadsModels (models) { const load = models.load.bind(models) /* load( require('./create_root_portfolio.js'), { uri: resolve('./create_root_portfolio.js'), id: 'portfolios/root' } ) */ }
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'source-map', entry: [ './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], module: { preLoaders: [ { test: /\.tsx?$/, exclude: /(node_modules)/, loader: 'source-map' } ], loaders: [{ test: /\.scss$/, include: /src/, loaders: [ 'style', 'css', 'autoprefixer?browsers=last 3 versions', 'sass?outputStyle=expanded' ]},{ test: /\.tsx?$/, loaders: [ 'babel', 'ts-loader' ], include: path.join(__dirname, 'app') }] }, resolve: { extensions: ["", ".webpack.js", ".web.js", ".js", ".ts", ".tsx"] } };
window.esdocSearchIndex = [ [ "./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupaddsampledatas.js~advencedfilterargmanagercategorygroupaddsampledatas", "variable/index.html#static-variable-AdvencedFilterArgManagerCategoryGroupAddSampleDatas", "<span>AdvencedFilterArgManagerCategoryGroupAddSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupeditsampledatas.js~advencedfilterargmanagercategorygroupeditsampledatas", "variable/index.html#static-variable-AdvencedFilterArgManagerCategoryGroupEditSampleDatas", "<span>AdvencedFilterArgManagerCategoryGroupEditSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorymovesampledatas.js~advencedfilterargmanagercategorymovesampledatas", "variable/index.html#static-variable-AdvencedFilterArgManagerCategoryMoveSampleDatas", "<span>AdvencedFilterArgManagerCategoryMoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategoryremovesampledatas.js~advencedfilterargmanagercategoryremovesampledatas", "variable/index.html#static-variable-AdvencedFilterArgManagerCategoryRemoveSampleDatas", "<span>AdvencedFilterArgManagerCategoryRemoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagerreadsampledatas.js~advencedfilterargmanagerreadsampledatas", "variable/index.html#static-variable-AdvencedFilterArgManagerReadSampleDatas", "<span>AdvencedFilterArgManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/advencedfiltermanager/advencedfiltermanagerreadsampledatas.js~advencedfiltermanagerreadsampledatas", "variable/index.html#static-variable-AdvencedFilterManagerReadSampleDatas", "<span>AdvencedFilterManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js</span>", "variable" ], [ "./git/userdashboard/src/components/advencedfilterquickviewer/advencedfilterquickviewersampledatas.js~advencedfilterquickviewersampledatas", "variable/index.html#static-variable-AdvencedFilterQuickViewerSampleDatas", "<span>AdvencedFilterQuickViewerSampleDatas</span> <span class=\"search-result-import-path\">./git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/categorylistmanager/categorylistmanagerreadsampledatas.js~categorylistmanagerreadsampledatas", "variable/index.html#static-variable-CategoryListManagerReadSampleDatas", "<span>CategoryListManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerloginsampledatas.js~loginmanagerloginsampledatas", "variable/index.html#static-variable-LoginManagerLoginSampleDatas", "<span>LoginManagerLoginSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerlogoutsampledatas.js~loginmanagerlogoutsampledatas", "variable/index.html#static-variable-LoginManagerLogoutSampleDatas", "<span>LoginManagerLogoutSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js</span>", "variable" ], [ "./git/uicontentsmanager/src/components/networkswitcher/networkswitchersampledatas.js~networkswitchersampledatas", "variable/index.html#static-variable-NetworkSwitcherSampleDatas", "<span>NetworkSwitcherSampleDatas</span> <span class=\"search-result-import-path\">./git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js</span>", "variable" ], [ "./git/userdashboard/src/components/networkswitcher/networkswitchersampledatas.js~networkswitchersampledatas", "variable/index.html#static-variable-NetworkSwitcherSampleDatas", "<span>NetworkSwitcherSampleDatas</span> <span class=\"search-result-import-path\">./git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanageraddsampledatas.js~projectmanageraddsampledatas", "variable/index.html#static-variable-ProjectManagerAddSampleDatas", "<span>ProjectManagerAddSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerciuploadsampledatas.js~projectmanagerciuploadsampledatas", "variable/index.html#static-variable-ProjectManagerCiUploadSampleDatas", "<span>ProjectManagerCiUploadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerreadsampledatas.js~projectmanagerreadsampledatas", "variable/index.html#static-variable-ProjectManagerReadSampleDatas", "<span>ProjectManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerremovesampledatas.js~projectmanagerremovesampledatas", "variable/index.html#static-variable-ProjectManagerRemoveSampleDatas", "<span>ProjectManagerRemoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerthumbnailuploadsampledatas.js~projectmanagerthumbnailuploadsampledatas", "variable/index.html#static-variable-ProjectManagerThumbnailUploadSampleDatas", "<span>ProjectManagerThumbnailUploadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerclearsampledatas.js~querystatemanagerclearsampledatas", "variable/index.html#static-variable-QueryStateManagerClearSampleDatas", "<span>QueryStateManagerClearSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerreadsampledatas.js~querystatemanagerreadsampledatas", "variable/index.html#static-variable-QueryStateManagerReadSampleDatas", "<span>QueryStateManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerupdatesampledatas.js~querystatemanagerupdatesampledatas", "variable/index.html#static-variable-QueryStateManagerUpdateSampleDatas", "<span>QueryStateManagerUpdateSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerdeletesampledatas.js~usermanagerdeletesampledatas", "variable/index.html#static-variable-UserManagerDeleteSampleDatas", "<span>UserManagerDeleteSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagernewsampledatas.js~usermanagernewsampledatas", "variable/index.html#static-variable-UserManagerNewSampleDatas", "<span>UserManagerNewSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerreadsampledatas.js~usermanagerreadsampledatas", "variable/index.html#static-variable-UserManagerReadSampleDatas", "<span>UserManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js</span>", "variable" ], [ "./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerupdatesampledatas.js~usermanagerupdatesampledatas", "variable/index.html#static-variable-UserManagerUpdateSampleDatas", "<span>UserManagerUpdateSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js</span>", "variable" ], [ "builtinexternal/ecmascriptexternal.js~array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~arraybuffer", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~ArrayBuffer", "external" ], [ "builtinexternal/ecmascriptexternal.js~boolean", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Boolean", "external" ], [ "builtinexternal/ecmascriptexternal.js~dataview", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~DataView", "external" ], [ "builtinexternal/ecmascriptexternal.js~date", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Date", "external" ], [ "builtinexternal/ecmascriptexternal.js~error", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Error", "external" ], [ "builtinexternal/ecmascriptexternal.js~evalerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~EvalError", "external" ], [ "builtinexternal/ecmascriptexternal.js~float32array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Float32Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~float64array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Float64Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~function", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Function", "external" ], [ "builtinexternal/ecmascriptexternal.js~generator", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Generator", "external" ], [ "builtinexternal/ecmascriptexternal.js~generatorfunction", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~GeneratorFunction", "external" ], [ "builtinexternal/ecmascriptexternal.js~infinity", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Infinity", "external" ], [ "builtinexternal/ecmascriptexternal.js~int16array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Int16Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~int32array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Int32Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~int8array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Int8Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~internalerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~InternalError", "external" ], [ "builtinexternal/ecmascriptexternal.js~json", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~JSON", "external" ], [ "builtinexternal/ecmascriptexternal.js~map", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Map", "external" ], [ "builtinexternal/ecmascriptexternal.js~nan", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~NaN", "external" ], [ "builtinexternal/ecmascriptexternal.js~number", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Number", "external" ], [ "builtinexternal/ecmascriptexternal.js~object", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Object", "external" ], [ "builtinexternal/ecmascriptexternal.js~promise", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Promise", "external" ], [ "builtinexternal/ecmascriptexternal.js~proxy", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Proxy", "external" ], [ "builtinexternal/ecmascriptexternal.js~rangeerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~RangeError", "external" ], [ "builtinexternal/ecmascriptexternal.js~referenceerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~ReferenceError", "external" ], [ "builtinexternal/ecmascriptexternal.js~reflect", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Reflect", "external" ], [ "builtinexternal/ecmascriptexternal.js~regexp", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~RegExp", "external" ], [ "builtinexternal/ecmascriptexternal.js~set", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Set", "external" ], [ "builtinexternal/ecmascriptexternal.js~string", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~String", "external" ], [ "builtinexternal/ecmascriptexternal.js~symbol", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Symbol", "external" ], [ "builtinexternal/ecmascriptexternal.js~syntaxerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~SyntaxError", "external" ], [ "builtinexternal/ecmascriptexternal.js~typeerror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~TypeError", "external" ], [ "builtinexternal/ecmascriptexternal.js~urierror", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~URIError", "external" ], [ "builtinexternal/ecmascriptexternal.js~uint16array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Uint16Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~uint32array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Uint32Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~uint8array", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Uint8Array", "external" ], [ "builtinexternal/ecmascriptexternal.js~uint8clampedarray", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~Uint8ClampedArray", "external" ], [ "builtinexternal/ecmascriptexternal.js~weakmap", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~WeakMap", "external" ], [ "builtinexternal/ecmascriptexternal.js~weakset", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~WeakSet", "external" ], [ "builtinexternal/ecmascriptexternal.js~boolean", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~boolean", "external" ], [ "builtinexternal/ecmascriptexternal.js~function", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~function", "external" ], [ "builtinexternal/ecmascriptexternal.js~null", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~null", "external" ], [ "builtinexternal/ecmascriptexternal.js~number", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~number", "external" ], [ "builtinexternal/ecmascriptexternal.js~object", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~object", "external" ], [ "builtinexternal/ecmascriptexternal.js~string", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~string", "external" ], [ "builtinexternal/ecmascriptexternal.js~undefined", "external/index.html", "BuiltinExternal/ECMAScriptExternal.js~undefined", "external" ], [ "builtinexternal/webapiexternal.js~audiocontext", "external/index.html", "BuiltinExternal/WebAPIExternal.js~AudioContext", "external" ], [ "builtinexternal/webapiexternal.js~canvasrenderingcontext2d", "external/index.html", "BuiltinExternal/WebAPIExternal.js~CanvasRenderingContext2D", "external" ], [ "builtinexternal/webapiexternal.js~documentfragment", "external/index.html", "BuiltinExternal/WebAPIExternal.js~DocumentFragment", "external" ], [ "builtinexternal/webapiexternal.js~element", "external/index.html", "BuiltinExternal/WebAPIExternal.js~Element", "external" ], [ "builtinexternal/webapiexternal.js~event", "external/index.html", "BuiltinExternal/WebAPIExternal.js~Event", "external" ], [ "builtinexternal/webapiexternal.js~node", "external/index.html", "BuiltinExternal/WebAPIExternal.js~Node", "external" ], [ "builtinexternal/webapiexternal.js~nodelist", "external/index.html", "BuiltinExternal/WebAPIExternal.js~NodeList", "external" ], [ "builtinexternal/webapiexternal.js~xmlhttprequest", "external/index.html", "BuiltinExternal/WebAPIExternal.js~XMLHttpRequest", "external" ], [ "git/resourcecreator/src/components/widgets/cores/widget000/widget000sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget000/Widget000SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget000/Widget000SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget000typea/widget000typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget000TypeA/Widget000TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget000TypeA/Widget000TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget001/widget001sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget001/Widget001SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget001/Widget001SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget001typea/widget001typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget001TypeA/Widget001TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget001TypeA/Widget001TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget002/widget002sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget003/widget003sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget003/Widget003SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget003/Widget003SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget004/widget004sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget004/Widget004SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget004/Widget004SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget008/widget008sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget008/Widget008SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget008/Widget008SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget009/widget009sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget009/Widget009SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget009/Widget009SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget009typea/widget009typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget009TypeA/Widget009TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget009TypeA/Widget009TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget010/widget010sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget010/Widget010SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget010/Widget010SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget028/widget028sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget028/Widget028SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget028/Widget028SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget030/widget030sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget030/Widget030SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget030/Widget030SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget031/widget031sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget031/Widget031SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget031/Widget031SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget031typea/widget031typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget031TypeA/Widget031TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget031TypeA/Widget031TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget032/widget032sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget032/Widget032SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget032/Widget032SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget032typea/widget032typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget032TypeA/Widget032TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget032TypeA/Widget032TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget033/widget033sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget033/Widget033SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget033/Widget033SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget033typea/widget033typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeA/Widget033TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeA/Widget033TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget033typeb/widget033typebsampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeB/Widget033TypeBSampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeB/Widget033TypeBSampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget034/widget034sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget034/Widget034SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget034/Widget034SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget034typea/widget034typeasampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeA/Widget034TypeASampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeA/Widget034TypeASampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget034typeb/widget034typebsampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeB/Widget034TypeBSampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeB/Widget034TypeBSampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget035/widget035sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget035/Widget035SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget035/Widget035SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget040/widget040sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget040/Widget040SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget040/Widget040SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget041/widget041sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget041/Widget041SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget041/Widget041SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget042/widget042sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget042/Widget042SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget042/Widget042SampleDatas.js", "file" ], [ "git/resourcecreator/src/components/widgets/cores/widget043/widget043sampledatas.js", "file/git/resourcecreator/src/Components/Widgets/Cores/Widget043/Widget043SampleDatas.js.html", "git/resourcecreator/src/Components/Widgets/Cores/Widget043/Widget043SampleDatas.js", "file" ], [ "git/resourcecreator/src/redux/projectsampledatas.js", "file/git/resourcecreator/src/Redux/projectSampleDatas.js.html", "git/resourcecreator/src/Redux/projectSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupaddsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupeditsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorymovesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategoryremovesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/advencedfiltermanager/advencedfiltermanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/categorylistmanager/categorylistmanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerloginsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerlogoutsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanageraddsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerciuploadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerremovesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerthumbnailuploadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerclearsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerupdatesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerdeletesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagernewsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerreadsampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js", "file" ], [ "git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerupdatesampledatas.js", "file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js.html", "git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js", "file" ], [ "git/uicontentsmanager/src/components/networkswitcher/networkswitchersampledatas.js", "file/git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js.html", "git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js", "file" ], [ "git/userdashboard/src/components/advencedfilterquickviewer/advencedfilterquickviewersampledatas.js", "file/git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js.html", "git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js", "file" ], [ "git/userdashboard/src/components/detailplayer/detailplayersampledatas.js", "file/git/userdashboard/src/Components/DetailPlayer/DetailPlayerSampleDatas.js.html", "git/userdashboard/src/Components/DetailPlayer/DetailPlayerSampleDatas.js", "file" ], [ "git/userdashboard/src/components/networkswitcher/networkswitchersampledatas.js", "file/git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js.html", "git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js", "file" ] ]
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { mySyncHistoryWithStore, default as createStore } from './store/createStore' import AppContainer from './containers/AppContainer' import injectTapEventPlugin from 'react-tap-event-plugin'; // ======================================================== // Browser History Setup // ======================================================== const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // ======================================================== // Store and History Instantiation // ======================================================== // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the routerKey "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = mySyncHistoryWithStore(browserHistory, store) // ======================================================== // Developer Tools Setup // ======================================================== if (__DEBUG__) { if (window.devToolsExtension) { window.devToolsExtension.open() } } // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = (routerKey = null) => { const routes = require('./routes/index').default(store) // TODO, uncomment this before production // injectTapEventPlugin() ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, MOUNT_NODE ) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle if (__DEV__ && module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react') ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } render = () => { try { renderApp(Math.random()) } catch (error) { renderError(error) } } module.hot.accept(['./routes/index'], () => render()) } // ======================================================== // Go! // ======================================================== render()
var beep = require('../beep.js'); beep(3);
var github = require('octonode'); var _ = require('lodash'); module.exports = { name:'action', description:'A command to show recent activity for all members of your org', example:'bosco action', cmd:cmd } function cmd(bosco) { getActivity(bosco); } function getActivity(bosco) { var client = github.client(bosco.config.get('github:authToken')); client.get('/orgs/tes/members', {}, function (err, status, body) { if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); } _.each(body, function(event) { console.dir(event); showUser(bosco, event); }); }); } function showUser(bosco, user) { var client = github.client(bosco.config.get('github:authToken')); client.get('/users/' + user + '/events', {}, function (err, status, body) { if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); } _.each(body, function(event) { var data = [user, event.type, event.repo.name, event.created_at]; console.dir(data.join(', ')); }); }); }
/** * constants.js */ // TODO: update these to better colors var SHIELD_COLOR = vec4.fromValues(0.0, 0.0, 1.0, 1.0); var ARMOR_COLOR = vec4.fromValues(0.0, 1.0, 0.0, 1.0); var HULL_COLOR = vec4.fromValues(1.0, 0.0, 1.0, 1.0);
'use strict' exports.Utils = require('./utils') exports.Schemas = require('./schemas') exports.Validator = require('./validator')
// @flow import type { Action } from "../actions/types"; import type { UserState } from "../types"; const initialState: UserState = { fetching: false, fetched: false, users: [], error: null }; export default function users(state: UserState = initialState, action: Action) { switch (action.type) { case "FETCH_USERS_PENDING": return { ...state, fetching: true }; case "FETCH_USERS_FULFILLED": return { ...state, fetching: false, fetched: true, users: action.payload.data, error: null }; case "FETCH_USERS_REJECTED": return { ...state, fetching: false, error: action.payload }; default: return state; } }
var ps, acorn; function start(){ ps = new PointStream(); ps.setup(document.getElementById('canvas')); ps.pointSize(5); ps.onKeyDown = function(){ ps.println(window.key); }; ps.onRender = function(){ ps.translate(0, 0, -25); ps.clear(); ps.render(acorn); }; acorn = ps.load("../../clouds/acorn.asc"); }
$identify("org/mathdox/formulaeditor/OrbeonForms.js"); $require("org/mathdox/formulaeditor/FormulaEditor.js"); var ORBEON; $main(function(){ if (ORBEON && ORBEON.xforms && ORBEON.xforms.Document) { /** * Extend the save function of the formula editor to use the orbeon update * mechanism, see also: * http://www.orbeon.com/ops/doc/reference-xforms-2#xforms-javascript */ org.mathdox.formulaeditor.FormulaEditor = $extend(org.mathdox.formulaeditor.FormulaEditor, { save : function() { // call the parent function arguments.callee.parent.save.apply(this, arguments); // let orbeon know about the change of textarea content var textarea = this.textarea; if (textarea.id) { ORBEON.xforms.Document.setValue(textarea.id, textarea.value); } } }); /** * Override Orbeon's xformsHandleResponse method so that it initializes any * canvases that might have been added by the xforms engine. */ /* prevent an error if the xformsHandleResponse doesn't exist */ var xformsHandleResponse; var oldXformsHandleResponse; var newXformsHandleResponse; var ancientOrbeon; if (xformsHandleResponse) { oldXformsHandleResponse = xformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponseDom; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { // orbeon 3.9 oldXformsHandleResponse = ORBEON.xforms.server.AjaxServer.handleResponseDom; } else { if (org.mathdox.formulaeditor.options.ancientOrbeon !== undefined && org.mathdox.formulaeditor.options.ancientOrbeon == true) { ancientOrbeon = true; } else { ancientOrbeon = false; alert("ERROR: detected orbeon, but could not add response handler"); } } newXformsHandleResponse = function(request) { // call the overridden method if (ancientOrbeon != true ) { oldXformsHandleResponse.apply(this, arguments); } // go through all canvases in the document var canvases = document.getElementsByTagName("canvas"); for (var i=0; i<canvases.length; i++) { // initialize a FormulaEditor for each canvas var canvas = canvases[i]; if (canvas.nextSibling) { if (canvas.nextSibling.tagName.toLowerCase() == "textarea") { var FormulaEditor = org.mathdox.formulaeditor.FormulaEditor; var editor = new FormulaEditor(canvas.nextSibling, canvas); // (re-)load the contents of the textarea into the editor editor.load(); } } } }; if (xformsHandleResponse) { xformsHandleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { ORBEON.xforms.Server.handleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { ORBEON.xforms.Server.handleResponseDom = newXformsHandleResponse; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { ORBEON.xforms.server.AjaxServer.handleResponseDom = newXformsHandleResponse; } } });
function isEmpty(value) { return angular.isUndefined(value) || value === '' || value === null || value !== value; } angular.module('Aggie') .directive('ngMin', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMin, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var minValidator = function (value) { var min = scope.$eval(attr.ngMin) || 0; if (!isEmpty(value) && value < min) { ctrl.$setValidity('ngMin', false); return undefined; } else { ctrl.$setValidity('ngMin', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } }; }) .directive('ngMax', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMax, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var maxValidator = function (value) { var max = scope.$eval(attr.ngMax) || Infinity; if (!isEmpty(value) && value > max) { ctrl.$setValidity('ngMax', false); return undefined; } else { ctrl.$setValidity('ngMax', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } }; });
require( "../setup" ); var packageResource = require( "../../resource/package/resource.js" ); describe( "Package Resource", function() { var server = { checkForNew: _.noop }; describe( "when getting new package callback", function() { describe( "with matching package", function() { var config, serverMock, result; before( function() { config = { package: { project: "imatch" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).once(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); describe( "with mis-matched package", function() { var config, serverMock, result; before( function() { config = { package: { project: "lol-aint-no-such" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).never(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should not call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); } ); } );
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); var server = http.createServer(app); var chatServer = require('./chat_server'); chatServer(server); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
var resetCollection = function(collection) { collection.find().fetch().forEach(function(obj) { collection.remove({_id: obj._id}); }); }; describe('CapabilityManager', function() { var capabilityManager; beforeAll(function() { capabilityManager = new CapabilityManager(); }); it('should set initial capabilities', function() { var allCaps = capabilityManager.allCapabilities; expect(allCaps.length).toEqual(3); }); });
import _size from './_size'; export default class MapObject { constructor() { this._data = new Map(); } get size() { return _size(); } }
const express = require('express'); const app = express(); app.use(express.static('./src/')) app.listen(8000, () => { console.log('The server is running on the http://localhost:8000/......'); });
/** @jsx html */ import { html } from '../../../snabbdom-jsx'; import Type from 'union-type'; import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers'; import { KEY_ENTER } from './constants'; // model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String } const Action = Type({ SetTitle : [String], Toggle : [isBoolean], StartEdit : [], CommitEdit : [String], CancelEdit : [] }); function onInput(handler, e) { if(e.keyCode === KEY_ENTER) handler(Action.CommitEdit(e.target.value)) } const view = ({model, handler, onRemove}) => <li key={model.id} class-completed={!!model.done && !model.editing} class-editing={model.editing}> <div selector=".view"> <input selector=".toggle" type="checkbox" checked={!!model.done} on-click={ pipe(targetChecked, Action.Toggle, handler) } /> <label on-dblclick={ bind(handler, Action.StartEdit()) }>{model.title}</label> <button selector=".destroy" on-click={onRemove} /> </div> <input selector=".edit" value={model.title} on-blur={ bind(handler, Action.CancelEdit()) } on-keydown={ bind(onInput, handler) } /> </li> function init(id, title) { return { id, title, done: false, editing: false, editingValue: '' }; } function update(task, action) { return Action.case({ Toggle : done => ({...task, done}), StartEdit : () => ({...task, editing: true, editingValue: task.title}), CommitEdit : title => ({...task, title, editing: false, editingValue: ''}), CancelEdit : title => ({...task, editing: false, editingValue: ''}) }, action); } export default { view, init, update, Action }
import Route from '@ember/routing/route'; export default Route.extend({ redirect() { this._super(...arguments); this.transitionTo('examples.single-date-picker'); } });
'use strict'; var fs = require('fs'); var demand = require('must'); var sinon = require('sinon'); var WebHDFS = require('../lib/webhdfs'); var WebHDFSProxy = require('webhdfs-proxy'); var WebHDFSProxyMemoryStorage = require('webhdfs-proxy-memory'); describe('WebHDFS', function () { var path = '/files/' + Math.random(); var hdfs = WebHDFS.createClient({ user: process.env.USER, port: 45000 }); this.timeout(10000); before(function (done) { var opts = { path: '/webhdfs/v1', http: { port: 45000 } }; WebHDFSProxy.createServer(opts, WebHDFSProxyMemoryStorage, done); }); it('should make a directory', function (done) { hdfs.mkdir(path, function (err) { demand(err).be.null(); done(); }); }); it('should create and write data to a file', function (done) { hdfs.writeFile(path + '/file-1', 'random data', function (err) { demand(err).be.null(); done(); }); }); it('should append content to an existing file', function (done) { hdfs.appendFile(path + '/file-1', 'more random data', function (err) { demand(err).be.null(); done(); }); }); it('should create and stream data to a file', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2'); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); done(); }); }); it('should append stream content to an existing file', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2', true); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); done(); }); }); it('should open and read a file stream', function (done) { var remoteFileStream = hdfs.createReadStream(path + '/file-1'); var spy = sinon.spy(); var data = []; remoteFileStream.on('error', spy); remoteFileStream.on('data', function onData (chunk) { data.push(chunk); }); remoteFileStream.on('finish', function () { demand(spy.called).be.falsy(); demand(Buffer.concat(data).toString()).be.equal('random datamore random data'); done(); }); }); it('should open and read a file', function (done) { hdfs.readFile(path + '/file-1', function (err, data) { demand(err).be.null(); demand(data.toString()).be.equal('random datamore random data'); done(); }); }); it('should list directory status', function (done) { hdfs.readdir(path, function (err, files) { demand(err).be.null(); demand(files).have.length(2); demand(files[0].pathSuffix).to.eql('file-1'); demand(files[1].pathSuffix).to.eql('file-2'); demand(files[0].type).to.eql('FILE'); demand(files[1].type).to.eql('FILE'); done(); }); }); it('should change file permissions', function (done) { hdfs.chmod(path, '0777', function (err) { demand(err).be.null(); done(); }); }); it('should change file owner', function (done) { hdfs.chown(path, process.env.USER, 'supergroup', function (err) { demand(err).be.null(); done(); }); }); it('should rename file', function (done) { hdfs.rename(path+ '/file-2', path + '/bigfile', function (err) { demand(err).be.null(); done(); }); }); it('should check file existence', function (done) { hdfs.exists(path + '/bigfile', function (exists) { demand(exists).be.true(); done(); }); }); it('should stat file', function (done) { hdfs.stat(path + '/bigfile', function (err, stats) { demand(err).be.null(); demand(stats).be.object(); demand(stats.type).to.eql('FILE'); demand(stats.owner).to.eql(process.env.USER); done(); }); }); it('should create symbolic link', function (done) { hdfs.symlink(path+ '/bigfile', path + '/biggerfile', function (err) { // Pass if server doesn't support symlinks if (err && err.message.indexOf('Symlinks not supported') !== -1) { done(); } else { demand(err).be.null(); done(); } }); }); it('should delete file', function (done) { hdfs.rmdir(path+ '/file-1', function (err) { demand(err).be.null(); done(); }); }); it('should delete directory recursively', function (done) { hdfs.rmdir(path, true, function (err) { demand(err).be.null(); done(); }); }); it('should support optional opts', function (done) { var myOpts = { "user.name": "testuser" } hdfs.writeFile(path + '/file-1', 'random data', myOpts, function (err) { demand(err).be.null(); done(); }); }); }); describe('WebHDFS with requestParams', function() { var path = '/files/' + Math.random(); var hdfs = WebHDFS.createClient({ user: process.env.USER, port: 45001 }, { headers: { 'X-My-Custom-Header': 'Kerberos' } }); this.timeout(10000); before(function (done) { var opts = { path: '/webhdfs/v1', http: { port: 45001 } }; WebHDFSProxy.createServer(opts, WebHDFSProxyMemoryStorage, done); }); it('should override request() options', function (done) { var localFileStream = fs.createReadStream(__filename); var remoteFileStream = hdfs.createWriteStream(path + '/file-2'); var spy = sinon.spy(); localFileStream.pipe(remoteFileStream); remoteFileStream.on('error', spy); remoteFileStream.on('response', function(response) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Kerberos'); demand(spy.called).be.falsy(); done(); }) }); it('should pass requestParams to _sendRequest', function (done) { var req = hdfs.readdir('/'); req.on('response', function(response) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Kerberos'); done(); }); }); it('should not override explicit opts with _sendRequest', function (done) { var mostSpecificParams = { headers: { 'X-My-Custom-Header': 'Bear' } } var endpoint = hdfs._getOperationEndpoint('liststatus', '/file-2'); hdfs._sendRequest('GET', endpoint, mostSpecificParams, function(err, response, body) { var customHeader = response.req.getHeader('X-My-Custom-Header'); demand(customHeader).equal('Bear'); done(err) }); }); });
/* */ (function(process) { var serial = require('../serial'); module.exports = ReadableSerial; function ReadableSerial(list, iterator, callback) { if (!(this instanceof ReadableSerial)) { return new ReadableSerial(list, iterator, callback); } ReadableSerial.super_.call(this, {objectMode: true}); this._start(serial, list, iterator, callback); } })(require('process'));
/** * Created by li_xiaoliang on 2015/3/29. */ define(['marked','highlight'],function(marked,highlight){ return{ parsemarkdown:function(md){ var pattern=/~.*?~/g; var matches=pattern.exec(md); while(matches!=null){ var match=matches[0]; console.log(match); var bematch=match.replace(match.charAt(0),"<div>").replace(match.substr(-1),"</div>") md=md.replace(match,bematch); matches=pattern.exec(md); } marked.setOptions({ highlight: function (code) { return highlight.highlightAuto(code).value; } }); return marked(md) } } })
define(['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.VirtualRepeatNext = undefined; var _dec, _class; var VirtualRepeatNext = exports.VirtualRepeatNext = (_dec = (0, _aureliaTemplating.customAttribute)('virtual-repeat-next'), _dec(_class = function () { function VirtualRepeatNext() { } VirtualRepeatNext.prototype.attached = function attached() {}; VirtualRepeatNext.prototype.bind = function bind(bindingContext, overrideContext) { this.scope = { bindingContext: bindingContext, overrideContext: overrideContext }; }; return VirtualRepeatNext; }()) || _class); });
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5s-3 1.34-3 3 1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z" }), 'GroupAddSharp');
var extend = require('extend'); var plivo = require('plivo'); var crypto = require('crypto') var phone = require('phone'); var TelcomPlivoClient = module.exports = function(opts){ if (!(this instanceof TelcomPlivoClient)) return new TelcomPlivoClient(options); this.options = {}; extend(this.options,opts); this._client = plivo.RestAPI({ authId: this.options.sid, authToken: this.options.token }); }; TelcomPlivoClient.prototype.validateRequest = function(req,callback){ if(req.header('X-Plivo-Signature') === undefined) return callback('missing requrired header.') var params = req.body; if(req.method === 'GET'){ params = req.query; } var toSign = req._telcomRequestUrlNoQuery; var expectedSignature = create_signature(toSign, params,this.options.token); if(req.header('X-Plivo-Signature') === expectedSignature) callback(); else callback('signature does not match'); } TelcomPlivoClient.prototype.sms = function(obj,callback){ var plivoMesg = { src : phone(obj.from), dst : phone(obj.to), text : obj.body }; /* { api_id: 'xxxxxxxxx-1f9d-11e3-b44b-22000ac53995', message: 'message(s) queued', message_uuid: [ 'xxxxxxxx-1f9d-11e3-b1d3-123141013a24' ] } */ this._client.send_message(plivoMesg, function(err, ret) { if(err === 202){ err = undefined; } if(!ret) ret = {}; callback(err,ret.message_uuid[0],ret.message,ret); }); }; /* { To: '15559633214', Type: 'sms', MessageUUID: 'xxxxxxx-2465-11e3-985d-0025907b94de', From: '15557894561', Text: 'Vg\n' } { to : '', from : '', body : '', messageId : '', } */ TelcomPlivoClient.prototype._convertSmsRequest = function(params){ return { to : phone(params['To']), from : phone(params['From']), body : params['Text'], messageId : params['MessageUUID'], _clientRequest : params }; } // For verifying the plivo server signature // By Jon Keating - https://github.com/mathrawka/plivo-node function create_signature(url, params,token) { var toSign = url; Object.keys(params).sort().forEach(function(key) { toSign += key + params[key]; }); var signature = crypto .createHmac('sha1',token) .update(toSign) .digest('base64'); return signature; };
import GameEvent from './GameEvent'; import Creature from '../entities/creatures/Creature'; import Ability from '../abilities/Ability'; import Tile from '../tiles/Tile'; export default class AbilityEvent extends GameEvent { /** * @class AbilityEvent * @description Fired whenever a creature attacks */ constructor(dungeon, creature, ability, tile) { super(dungeon); if(!(creature instanceof Creature)) { throw new Error('Second parameter must be a Creature'); } else if(!(ability instanceof Ability)) { throw new Error('Third parameter must be an Ability'); } else if((tile instanceof Tile) !== ability.isTargetted()) { throw new Error('Fourth parameter must be a Tile iff ability is targetted'); } this._creature = creature; this._ability = ability; this._tile = tile; } getCreature() { return this._creature; } getAbility() { return this._ability; } getTile() { return this._tile; } getText(dungeon) { var creature = this.getCreature(); var ability = this.getAbility(); var tile = dungeon.getTile(creature); return `${creature} used ${ability}` + (tile ? ` on ${tile}` : ''); } }
//------------------------------- // ADMINISTER CODES FUNCTIONALITY //------------------------------- MFILE.administerCodes = function () { MFILE.administerCodes.handleDisplay(); MFILE.administerCodes.handleKeyboard(); } MFILE.administerCodes.handleDisplay = function () { $('#result').empty(); $('#codebox').html(MFILE.html.code_box); if (MFILE.activeCode.cstr.length === 0) { //$('#code').val('<EMPTY>'); $('#code').val(''); } else { $('#code').val(MFILE.activeCode.cstr); } $("#code").focus(function(event) { $("#topmesg").html("ESC=Back, Ins=Insert, F3=Lookup, F5=Delete, ENTER=Accept"); $("#mainarea").html(MFILE.html.change_code); }); $("#code").blur(function(event) { $('#topmesg').empty(); }); } MFILE.administerCodes.handleKeyboard = function () { // Handle function keys in Code field $("#code").keydown(function (event) { MFILE.administerCodes.processKey(event); }); $('#code').focus(); } MFILE.administerCodes.processKey = function (event) { console.log("KEYDOWN. WHICH "+event.which+", KEYCODE "+event.keyCode); // Function key handler if (event.which === 9) { // tab, shift-tab event.preventDefault(); console.log("IGNORING TAB"); return true; } else if (event.which === 27) { // ESC event.preventDefault(); MFILE.activeCode.cstr = ""; $('#code').val(''); $('#code').blur(); $('#codebox').empty(); $('#result').empty(); MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } else if (event.which === 13) { // ENTER event.preventDefault(); $('#result').empty(); MFILE.fetchCode("ACCEPT"); } else if (event.which === 45) { // Ins event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to insert code '"+MFILE.activeCode.cstr+"'"); MFILE.insertCode(); $('#result').html(MFILE.activeCode.result); } else if (event.which === 114) { // F3 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Consulting server concerning the code '"+MFILE.activeCode.cstr+"'"); MFILE.searchCode(); } else if (event.which == 116) { // F5 event.preventDefault(); MFILE.activeCode.cstr = $('#code').val(); console.log("Asking server to delete code '"+MFILE.activeCode.cstr+"'"); MFILE.fetchCode('DELETE'); $('#result').html(MFILE.activeCode.result); } } //--------------- // AJAX FUNCTIONS //--------------- MFILE.insertCode = function() { console.log("About to insert code string "+MFILE.activeCode["cstr"]); $.ajax({ url: "insertcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS") console.log(result); $("#code").val(result.mfilecodeCode); $("#result").empty(); $("#result").append("New code "+result.mfilecodeCode+" (ID "+result.mfilecodeId+") added to database.") } else { console.log("FAILURE") console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.fetchCode = function (action) { // we fetch it in order to delete it console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $.ajax({ url: "fetchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.queryResult+"'"); if (result.queryResult === "success") { MFILE.activeCode.cstr = result.mfilecodeCode; $("#code").val(MFILE.activeCode.cstr); if (action === "DELETE") { MFILE.deleteCodeConf(); } else { MFILE.state = 'MAIN_MENU'; MFILE.actOnState(); } } else { $('#result').html("FAILED: '"+result.queryResult+"'"); return false; } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCodeConf = function () { // for now, called only from fetchCode console.log("Asking for confirmation to delete "+MFILE.activeCode["cstr"]); $("#mainarea").html(MFILE.html.code_delete_conf1); $("#mainarea").append(MFILE.activeCode.cstr+"<BR>"); $("#mainarea").append(MFILE.html.code_delete_conf2); $("#yesno").focus(); console.log("Attempting to fetch code "+MFILE.activeCode["cstr"]); $("#yesno").keydown(function(event) { event.preventDefault(); logKeyPress(event); if (event.which === 89) { MFILE.deleteCode(); } MFILE.actOnState(); }); } MFILE.searchCode = function () { console.log("Attempting to search code "+MFILE.activeCode["cstr"]); $.ajax({ url: "searchcode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("AJAX POST success, result is: '"+result.result+"'"); if (result.result === "success") { if (result.values.length === 0) { $("#result").html("FAILED: 'Nothing matches'"); } else if (result.values.length === 1) { $("#result").html("SUCCESS: Code found"); MFILE.activeCode.cstr = result.values[0]; $("#code").val(MFILE.activeCode.cstr); } else { $("#mainarea").html(MFILE.html.code_search_results1); $.each(result.values, function (key, value) { $("#mainarea").append(value+" "); }); $("#mainarea").append(MFILE.html.press_any_key); $("#continue").focus(); $("#continue").keydown(function(event) { event.preventDefault(); MFILE.actOnState(); }); $("#result").html("Search found multiple matching codes. Please narrow it down."); } } else { console.log("FAILURE: "+result); $("#code").empty(); $("#result").html("FAILED: '"+result.result+"'"); } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); } MFILE.deleteCode = function() { console.log("Attempting to delete code "+MFILE.activeCode["cstr"]); $.ajax({ url: "deletecode", type: "POST", dataType: "json", data: MFILE.activeCode, success: function(result) { console.log("Query result is: '"+result.queryResult+"'"); $("#id").empty(); if (result.queryResult === "success") { console.log("SUCCESS"); console.log(result); $("#code").empty(); $("#result").empty(); $("#result").append("Code deleted"); } else { console.log("FAILURE") console.log(result); $("#result").empty(); $("#result").append("FAILED: '"+result.queryResult+"'") } }, error: function(xhr, status, error) { $("#result").html("AJAX ERROR: "+xhr.status); } }); }
/** * @fileOverview * @name aqicn.js * @author ctgnauh <[email protected]> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWebPage 的 callback * @callback module:aqicn~fetchWebPageCallback * @param {object} error - 请求错误 * @param {object} result - 页面文本 */ /** * 抓取移动版 aqicn.org 页面。 * aqicn.org 桌面版在300kb以上,而移动版则不足70kb。所以使用移动版,链接后面加 /m/ 。 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {module:aqicn~fetchWebPageCallback} callback */ fetchWebPage: function (city, callback) { 'use strict'; var options = { url: 'http://aqicn.org/city/' + city + '/m/', headers: { 'User-Agent': 'wget' } }; request.get(options, function (err, res, body) { if (err) { callback(err, ''); } else { callback(null, body); } }); }, /** * 分析 html 文件并返回指定的 AQI 值 * @param {string} body - 页面文本 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @returns {number} AQI 值 */ selectAQIText: function (body, name) { 'use strict'; var self = this; var $ = cheerio.load(body); var json; var value; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" value = self.info.species.indexOf(name); } catch (err) { return NaN; } return json.d[value].iaqi; }, /** * 分析 html 文件并返回更新时间 * @param {string} body - 页面文本 * @returns {string} ISO格式的时间 */ selectUpdateTime: function (body) { 'use strict'; var $ = cheerio.load(body); var json; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" } catch (err) { return new Date(0).toISOString(); } return json.t; }, /** * 污染等级及相关信息 * @param {number} level - AQI 级别 * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @returns {object} 由AQI级别、污染等级、对健康影响情况、建议采取的措施组成的对象 */ selectInfoText: function (level, lang) { 'use strict'; var self = this; if (level > 6 || level < 0) { level = 0; } return { value: level, name: self.info.level[level].name[lang], implication: self.info.level[level].implication[lang], statement: self.info.level[level].statement[lang] }; }, /** * 计算 AQI,这里选取 aqicn.org 采用的算法,选取 AQI 中数值最大的一个 * @param {array} aqis - 包含全部 AQI 数值的数组 * @returns {number} 最大 AQI */ calculateAQI: function (aqis) { 'use strict'; return Math.max.apply(null, aqis); }, /** * 计算空气污染等级,分级标准详见[关于空气质量与空气污染指数](http://aqicn.org/?city=&size=xlarge&aboutaqi) * @param {number} aqi - 最大 AQI * @returns {number} AQI 级别 */ calculateLevel: function (aqi) { 'use strict'; var level = 0; if (aqi >= 0 && aqi <= 50) { level = 1; } else if (aqi >= 51 && aqi <= 100) { level = 2; } else if (aqi >= 101 && aqi <= 150) { level = 3; } else if (aqi >= 151 && aqi <= 200) { level = 4; } else if (aqi >= 201 && aqi <= 300) { level = 5; } else if (aqi > 300) { level = 6; } return level; }, /** * getAQIs 的 callback * @callback module:aqicn~getAQIsCallback * @param {object} error - 请求错误 * @param {object} result - 包含全部污染物信息的对象 */ /** * 获取指定城市的全部 AQI 数值 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @param {module:aqicn~getAQIsCallback} callback */ getAQIs: function (city, lang, callback) { 'use strict'; var self = this; self.fetchWebPage(city, function (err, body) { if (err) { callback(err); } var result = {}; var aqis = []; // 城市代码 result.city = city; // 数据提供时间 result.time = self.selectUpdateTime(body); // 全部 AQI 值 self.info.species.forEach(function (name) { var aqi = self.selectAQIText(body, name); aqis.push(aqi); result[name] = aqi; }); // 主要 AQI 值 result.aqi = self.calculateAQI(aqis); // AQI 等级及其它 var level = self.calculateLevel(result.aqi); var levelInfo = self.selectInfoText(level, lang); result.level = levelInfo; callback(null, result); }); }, /** * getAQIByName 的 callback * @callback module:aqicn~getAQIByNameCallback * @param {object} error - 请求错误 * @param {object} result - 城市或地区代码与指定的 AQI */ /** * 获取指定城市的指定污染物数值 * @param {string} city - 城市或地区代码 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @param {module:aqicn~getAQIByNameCallback} callback */ getAQIByName: function (city, name, callback) { 'use strict'; var self = this; self.getAQIs(city, 'cn', function (err, res) { if (err) { callback(err); } callback(null, { city: city, value: res[name], time: res.time }); }); } };
var loadState = { preload: function() { /* Load all game assets Place your load bar, some messages. In this case of loading, only text is placed... */ var loadingLabel = game.add.text(80, 150, 'loading...', {font: '30px Courier', fill: '#fff'}); //Load your images, spritesheets, bitmaps... game.load.image('kayle', 'assets/img/kayle.png'); game.load.image('tree', 'assets/img/tree.png'); game.load.image('rock', 'assets/img/rock.png'); game.load.image('undefined', 'assets/img/undefined.png'); game.load.image('grass', 'assets/img/grass.png'); game.load.image('player', 'assets/img/player.png'); game.load.image('btn-play','assets/img/btn-play.png'); game.load.image('btn-load','assets/img/btn-play.png'); //Load your sounds, efx, music... //Example: game.load.audio('rockas', 'assets/snd/rockas.wav'); //Load your data, JSON, Querys... //Example: game.load.json('version', 'http://phaser.io/version.json'); }, create: function() { game.stage.setBackgroundColor('#DEDEDE'); game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; game.state.start('menu'); } };
'use strict'; var proxy = require('proxyquire'); var stubs = { googlemaps: jasmine.createSpyObj('googlemaps', ['staticMap']), request: jasmine.createSpy('request'), '@noCallThru': true }; describe('google-static-map', function() { var uut; describe('without auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ); }); it('should not work without a api key', function() { expect( uut ).toThrow(new Error('You must provide a google api console key')); }); it('should provide a method to set a global api key', function() { expect( uut.set ).toBeDefined(); uut = uut.set('some-key'); expect( uut ).not.toThrow( jasmine.any( Error )); }); }); describe('with auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ).set('some-key'); }); it('should get/set config options', function() { var map = uut(); var set; ['zoom', 'resolution', 'mapType', 'markers', 'style'].forEach(function( key ) { set = key + ' ' + key; expect( map.config[key] ).toEqual( map[key]() ); var chain = map[key]( set ); expect( map.config[key] ).toEqual( set ); expect( chain ).toEqual( map ); }); }); it('should relay staticMap call to googlemaps module', function() { var map = uut(); var testAddress = 'Some Address, Some Country'; var staticMapReturn = 'http://some.where'; var requestReturn = 'request-return-value'; stubs.googlemaps.staticMap.andReturn( staticMapReturn ); stubs.request.andReturn( requestReturn ); var stream = map.address( testAddress ).staticMap().done(); expect( stream ).toEqual('request-return-value'); expect( stubs.googlemaps.staticMap ).toHaveBeenCalledWith( testAddress, map.config.zoom, map.config.resolution, false, false, map.config.mapType, map.config.markers, map.config.style, map.config.paths ); expect( stubs.request ).toHaveBeenCalledWith( staticMapReturn ); }); }); });
/** * Unit tests for FoxHound * * @license MIT * * @author Steven Velozo <[email protected]> */ var Chai = require('chai'); var Expect = Chai.expect; var Assert = Chai.assert; var libFable = require('fable').new({}); var libFoxHound = require('../source/FoxHound.js'); suite ( 'FoxHound', function() { setup ( function() { } ); suite ( 'Object Sanity', function() { test ( 'initialize should build a happy little object', function() { var testFoxHound = libFoxHound.new(libFable); Expect(testFoxHound) .to.be.an('object', 'FoxHound should initialize as an object directly from the require statement.'); Expect(testFoxHound).to.have.a.property('uuid') .that.is.a('string'); Expect(testFoxHound).to.have.a.property('logLevel'); } ); test ( 'basic class parameters', function() { var testFoxHound = libFoxHound.new(libFable); Expect(testFoxHound).to.have.a.property('parameters') .that.is.a('object'); Expect(testFoxHound.parameters).to.have.a.property('scope') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('dataElements') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('filter') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('begin') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('cap') .that.is.a('boolean'); // Scope is boolean false by default. Expect(testFoxHound.parameters).to.have.a.property('sort') .that.is.a('boolean'); // Scope is boolean false by default. } ); } ); suite ( 'Basic Query Generation', function() { test ( 'generate a simple query of all data in a set', function() { // The default dialect is English. This one-liner is all-in. Expect(libFoxHound.new(libFable).setLogLevel().setScope('Widget').buildReadQuery().query.body) .to.equal('Please give me all your Widget records. Thanks.'); } ); test ( 'change the dialect', function() { var tmpQuery = libFoxHound.new(libFable).setLogLevel(5); // Give a scope for the data to come from tmpQuery.setScope('Widget'); // Expect there to not be a dialect yet Expect(tmpQuery).to.have.a.property('dialect') .that.is.a('boolean'); // Build the query tmpQuery.buildReadQuery(); // Expect implicit dialect of English to be instantiated Expect(tmpQuery.dialect.name) .to.equal('English'); // Now submit a bad dialect tmpQuery.setDialect(); // Expect implicit dialect of English to be instantiated Expect(tmpQuery.dialect.name) .to.equal('English'); // This is the query generated by the English dialect Expect(tmpQuery.query.body) .to.equal('Please give me all your Widget records. Thanks.'); // Now change to MySQL tmpQuery.setDialect('MySQL'); Expect(tmpQuery.dialect.name) .to.equal('MySQL'); // Build the query tmpQuery.buildReadQuery(); // This is the query generated by the English dialect Expect(tmpQuery.query.body) .to.equal('SELECT `Widget`.* FROM `Widget`;'); } ); } ); suite ( 'State Management', function() { test ( 'change the scope by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); tmpQuery.setScope('Widget'); Expect(tmpQuery.parameters.scope) .to.equal('Widget'); } ); test ( 'merge parameters', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); tmpQuery.mergeParameters({scope:'Fridget'}); Expect(tmpQuery.parameters.scope) .to.equal('Fridget'); } ); test ( 'clone the object', function() { // Create a query var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope).to.equal(false); // Clone it var tmpQueryCloneOne = tmpQuery.clone(); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); // Set the first queries scope tmpQuery.setScope('Widget'); Expect(tmpQuery.parameters.scope).to.equal('Widget'); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); // Now clone again var tmpQueryCloneTwo = tmpQuery.clone(); Expect(tmpQueryCloneTwo.parameters.scope).to.equal('Widget'); // Set some state on the second clone, make sure it doesn't pollute other objects tmpQueryCloneTwo.setScope('Sprocket'); Expect(tmpQuery.parameters.scope).to.equal('Widget'); Expect(tmpQueryCloneOne.parameters.scope).to.equal(false); Expect(tmpQueryCloneTwo.parameters.scope).to.equal('Sprocket'); } ); test ( 'fail to change the scope by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.scope) .to.equal(false); // Numbers are not valid scopes tmpQuery.setScope(100); Expect(tmpQuery.parameters.scope) .to.equal(false); } ); test ( 'change the cap by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.cap) .to.equal(false); tmpQuery.setCap(50); Expect(tmpQuery.parameters.cap) .to.equal(50); } ); test ( 'fail to change the cap by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.cap) .to.equal(false); tmpQuery.setCap('Disaster'); Expect(tmpQuery.parameters.cap) .to.equal(false); } ); test ( 'change the user ID', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.userID) .to.equal(0); tmpQuery.setIDUser(1); Expect(tmpQuery.parameters.userID) .to.equal(1); Expect(tmpQuery.parameters.query.IDUser) .to.equal(1); } ); test ( 'fail to change the user ID', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.userID) .to.equal(0); tmpQuery.setLogLevel(3); tmpQuery.setIDUser('Disaster'); Expect(tmpQuery.parameters.userID) .to.equal(0); } ); test ( 'change the begin by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.begin) .to.equal(false); tmpQuery.setBegin(2); Expect(tmpQuery.parameters.begin) .to.equal(2); } ); test ( 'fail to change the begin by function', function() { var tmpQuery = libFoxHound.new(libFable); Expect(tmpQuery.parameters.begin) .to.equal(false); tmpQuery.setBegin('Looming'); Expect(tmpQuery.parameters.begin) .to.equal(false); } ); test ( 'Manually set the parameters object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.parameters = {Frogs:'YES'}; Expect(tmpQuery.parameters.Frogs) .to.equal('YES'); } ); test ( 'Manually set the query object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.query = {body:'GET TO ALL DE CHOPPA RECORDS'}; Expect(tmpQuery.query.body) .to.contain('CHOPPA'); } ); test ( 'Manually set the result object', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.result = {executed:true, value:[{Name:'Wendy'},{Name:'Griffin'}]}; Expect(tmpQuery.result.executed) .to.equal(true); } ); test ( 'Set a bad dialect', function() { var tmpQuery = libFoxHound.new(libFable).setDialect('Esperanto'); Expect(tmpQuery.dialect.name) .to.equal('English'); } ); test ( 'Try to pass bad filters', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addFilter(); tmpQuery.addFilter('Name'); Expect(tmpQuery.parameters.filter) .to.equal(false); } ); test ( 'Pass many filters', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addFilter('Name', 'Smith'); tmpQuery.addFilter('City', 'Seattle'); Expect(tmpQuery.parameters.filter.length) .to.equal(2); tmpQuery.addFilter('Age', 25, '>', 'AND', 'AgeParameter'); Expect(tmpQuery.parameters.filter.length) .to.equal(3); } ); test ( 'Pass bad records', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addRecord(); Expect(tmpQuery.query.records) .to.equal(false); } ); test ( 'Pass multiple records', function() { var tmpQuery = libFoxHound.new(libFable); tmpQuery.addRecord({ID:10}); tmpQuery.addRecord({ID:100}); tmpQuery.addRecord({ID:1000}); Expect(tmpQuery.query.records.length) .to.equal(3); } ); } ); } );
const path = require( 'path' ); const pkg = require( './package.json' ); const webpack = require( 'laxar-infrastructure' ).webpack( { context: __dirname, resolve: { extensions: [ '.js', '.jsx', '.ts', '.tsx' ] }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules\/.*\/spec\//, loader: 'ts-loader' }, { test: /\.jsx?$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'babel-loader' }, { test: /\.spec.js$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'laxar-mocks/spec-loader' } ] } } ); module.exports = [ webpack.library(), webpack.browserSpec( [ `./spec/${pkg.name}.spec.js` ] ) ];
import React, { Component } from "react"; import { AppHeader, AppFooter } from "../App"; import config from "../../../config"; import { fromJS } from "immutable"; import Spinner from "react-spinner"; import { PlaylistNavBar } from "../../components/PlaylistNavBar"; export class LoadingMoment extends Component { constructor(props) { super(props); this.state = { story: null, momentId: 0, storyMomentList: [] }; } async componentDidMount() { let path = this.props.location.pathname; let storyId = path.split("/")[3]; let momentId = path.split("/")[5]; let storyMomentList = []; const response = await fetch(`${config.apiEntry}/api/stories/${storyId}`); let storyObj = await response.json(); let momentList = fromJS(storyObj.momentList); momentList.forEach((m) => storyMomentList.push(m)); this.setState({ story: storyObj, momentId: momentId, storyMomentList: storyMomentList, }); this.props.history.push(`/stories/story/${storyId}/moment/${momentId}`); } render() { return ( <div className="app-container"> <AppHeader /> <PlaylistNavBar currentStory={this.state.story} currentMomentId={this.state.momentId} moments={this.state.storyMomentList} history={this.props.history} /> <div className="text-center lead"> <p>Loading moment...</p> <Spinner /> </div> <AppFooter /> </div> ); } }
/* */ var htmlparser = require('htmlparser2'); var _ = require('lodash'); var quoteRegexp = require('regexp-quote'); module.exports = sanitizeHtml; // Ignore the _recursing flag; it's there for recursive // invocation as a guard against this exploit: // https://github.com/fb55/htmlparser2/issues/105 function sanitizeHtml(html, options, _recursing) { var result = ''; function Frame(tag, attribs) { var that = this; this.tag = tag; this.attribs = attribs || {}; this.tagPosition = result.length; this.text = ''; // Node inner text this.updateParentNodeText = function() { if (stack.length) { var parentFrame = stack[stack.length - 1]; parentFrame.text += that.text; } }; } if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap; if(options.allowedTags) { allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); } var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap; var allowedAttributesGlobMap; if(options.allowedAttributes) { allowedAttributesMap = {}; allowedAttributesGlobMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; var globRegex = []; _.each(attributes, function(name) { if(name.indexOf('*') >= 0) { globRegex.push(quoteRegexp(name).replace(/\\\*/g, '.*')); } else { allowedAttributesMap[tag][name] = true; } }); allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$'); }); } var allowedClassesMap = {}; _.each(options.allowedClasses, function(classes, tag) { // Implicitly allows the class attribute if(allowedAttributesMap) { if (!allowedAttributesMap[tag]) { allowedAttributesMap[tag] = {}; } allowedAttributesMap[tag]['class'] = true; } allowedClassesMap[tag] = {}; _.each(classes, function(name) { allowedClassesMap[tag][name] = true; }); }); var transformTagsMap = {}; _.each(options.transformTags, function(transform, tag){ if (typeof transform === 'function') { transformTagsMap[tag] = transform; } else if (typeof transform === "string") { transformTagsMap[tag] = sanitizeHtml.simpleTransform(transform); } }); var depth = 0; var stack = []; var skipMap = {}; var transformMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var frame = new Frame(name, attribs); stack.push(frame); var skip = false; if (_.has(transformTagsMap, name)) { var transformedTag = transformTagsMap[name](name, attribs); frame.attribs = attribs = transformedTag.attribs; if (name !== transformedTag.tagName) { frame.name = name = transformedTag.tagName; transformMap[depth] = transformedTag.tagName; } } if (allowedTagsMap && !_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (!allowedAttributesMap || _.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (!allowedAttributesMap || _.has(allowedAttributesMap[name], a) || (_.has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a))) { if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { delete frame.attribs[a]; return; } } if (a === 'class') { value = filterClasses(value, allowedClassesMap[name]); if (!value.length) { delete frame.attribs[a]; return; } } result += ' ' + a; if (value.length) { result += '="' + escapeHtml(value) + '"'; } } else { delete frame.attribs[a]; } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } var tag = stack[stack.length-1] && stack[stack.length-1].tag; if (_.has(nonTextTagsMap, tag)) { result += text; } else { var escaped = escapeHtml(text); if (options.textFilter) { result += options.textFilter(escaped); } else { result += escaped; } } if (stack.length) { var frame = stack[stack.length - 1]; frame.text += text; } }, onclosetag: function(name) { var frame = stack.pop(); if (!frame) { // Do not crash on bad markup return; } skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; frame.updateParentNodeText(); return; } if (transformMap[depth]) { name = transformMap[depth]; delete transformMap[depth]; } if (options.exclusiveFilter && options.exclusiveFilter(frame)) { result = result.substr(0, frame.tagPosition); return; } frame.updateParentNodeText(); if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }, { decodeEntities: true }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/g, ''); // Clobber any comments in URLs, which the browser might // interpret inside an XML data island, allowing // a javascript: URL to be snuck through href = href.replace(/<\!\-\-.*?\-\-\>/g, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(options.allowedSchemes, scheme)); } function filterClasses(classes, allowed) { if (!allowed) { // The class attribute is allowed without filtering on this tag return classes; } classes = classes.split(/\s+/); return _.filter(classes, function(c) { return _.has(allowed, c); }).join(' '); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], // URL schemes we permit allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ] }; sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) { merge = (merge === undefined) ? true : merge; newAttribs = newAttribs || {}; return function(tagName, attribs) { var attrib; if (merge) { for (attrib in newAttribs) { attribs[attrib] = newAttribs[attrib]; } } else { attribs = newAttribs; } return { tagName: newTagName, attribs: attribs }; }; };
var path = require('path'); var winston = require('winston'); var config = require('./config.js'); var util = require('./util.js'); module.exports = initLogger(); function initLogger() { var targetDir = path.join(config('workingdir'), 'log'); util.createDirectoryIfNeeded(targetDir); var winstonConfig = { transports: [ new (winston.transports.Console)({ level: 'debug' }), new (winston.transports.File)({ filename: path.join(targetDir, 'tsync.log') }) ] }; return new (winston.Logger)(winstonConfig); }
const router = require('express').Router(); const db1 = require('../db'); // GET - Get All Students Info (Admin) // response: // [] students: // account_id: uuid // user_id: uuid // first_name: string // last_name: string // hometown: string // college: string // major: string // gender: string // birthdate: date // email: string // date_created: timestamp // image_path: string // bio: string router.get('/student/all', (req, res) => { db1.any(` SELECT account_id, user_id, first_name, last_name, hometown, college, major, gender, bio, birthdate, email, date_created, image_path FROM students natural join account natural join images`) .then(function(data) { // Send All Students Information console.log('Success: Admin Get All Students Information'); res.json({students: data}) }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Associations Info (Admin) // response: // [] associations: // account_id: uuid // association_id: uuid // association_name: string // initials: string // email: string // page_link: string // image_path: string // bio: string // date_created: timestamp // room: string // building: string // city: string router.get('/association/all', (req, res) => { db1.any(` SELECT account_id, association_id, association_name, initials, page_link, image_path, email, bio, room, building, city, date_created FROM associations natural join account natural join location natural join images`) .then(function(data) { // Send All Associations Information console.log('Success: Admin Get All Associations Information'); res.json({associations: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Events Info (Admin) // response: // [] events // event_id: id // event_name: string // is_live: bool (yes/no) // registration_link: string // start_date: date // end_date: date // start_time: time // end_time: time // room: string // building: string // city: string // image_path: string // time_stamp: timestamp router.get('/event/all', (req, res) => { db1.any(` SELECT event_id, event_name, is_live, registration_link, start_date, end_date, start_time, end_time, room, building, city, image_path, time_stamp FROM events natural join images natural join location`) .then(function(data) { // Send All Events Information console.log('Success: Admin Get All Events Information'); res.json({events: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); module.exports = router;
import one from './index-loader-syntax.css'; import two from 'button.modules.css!=!./index-loader-syntax-sass.css'; // Hash should be different import three from './button.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=bar'; import four from './other.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=baz'; __export__ = [...one, ...two, ...three, ...four]; export default [...one, ...two, ...three, ...four];
var mysql = require('mysql'); function discountMember(router,connection){ var self=this; self.handleRoutes(router,connection); } //KALO...UDH SEKALI DIDISKON>>>BERARTI GABOLEH LAGI LAGI DISKON YAA TODO: discountMember.prototype.handleRoutes = function(router,connection){ router.post('/discountMember',function(req,res){ var sessionCode = req.body.sessionCode; var no_bon = req.body.no_bon; var membershipCode = req.body.membershipCode; if(sessionCode == null || sessionCode == undefined || sessionCode == ''){ res.json({"message":"err.. no params s_c rec"}); }else{ if(no_bon == null || no_bon == undefined || no_bon == ''){ res.json({"message":"err.. no params n_b rec"}); }else{ if(membershipCode == null || membershipCode == undefined || membershipCode == ''){ res.json({"message":"err.. no params m_c rec"}); }else{ var query = "select role.id_role as id_role from `session` join `user` on session.id_user=user.id_user join role on role.id_role=user.id_role where session.session_code='"+sessionCode+"'"; connection.query(query,function(err,rows){ if(err){ res.json({"message":"err.. error on session","query":query}); }else{ if(rows.length == 1){ if(rows[0].id_role == 2 || rows[0].id_role == 1){ var q012 = "select discount,no_bon from `order` where no_bon='"+no_bon+"'"; connection.query(q012,function(err,rows){ if(err){ res.json({"message":"err.. on selecting disc st1"}); }else{ if(rows.length>0){ if(rows[0].discount == null || rows[0].discount == undefined || rows[0].discount == ''){ //ambil jumlah discount dulu di membership code var q2 = "select discount from `membership` where membership_code='"+membershipCode+"'"; connection.query(q2,function(err,rows){ if(err){ res.json({"message":"err.. error selecting discount"}); }else{ if(rows.length>0){ var discount = rows[0].discount; //pending var q3 = "select jumlah_bayar from `order` where no_bon = '"+no_bon+"'"; connection.query(q3,function(err,rows){ if(err){ res.json({"message":"err.. error on selecting jumlah Bayar"}); }else{ if(rows.length>0){ var jumlahBayar = rows[0].jumlah_bayar; var afterDisc = jumlahBayar-(jumlahBayar*discount/100); var q4 = "update `order` set discount="+discount+",harga_bayar_fix="+afterDisc+",jumlah_bayar="+afterDisc+" where no_bon='"+no_bon+"'"; connection.query(q4,function(err,rows){ if(err){ res.json({"message":"err.. error on updating"}); }else{ res.json({"message":"err.. success adding discount","priceAfterDiscount":afterDisc,"discount":discount}); } }); }else{ res.json({"message":"Err.. no rows absbas","q3":q3}); } } }); }else{ res.json({"message":"err.. no rows","q2":q2}); } } }); }else{ res.json({"message":"err.. have already discounted"}); } }else{ res.json({"message":"err.. no rows on order with given n_b"}); } } }); }else{ res.json({"message":"err.. you have no authorize to do this action"}); } }else{ res.json({"message":"err... rows length not equal to 1"}); } } }); } } } }); } module.exports = discountMember;
import React from 'react'; import Home from './Home.js'; import Login from './Login.js'; import PointInTime from './PointInTime.js'; import Vispdat from './VISPDAT.js'; import Refuse from './Refuse.js'; import { Actions, Scene } from 'react-native-router-flux'; /** * Order of rendering is based on index of Child scene. * We set hideNavBar to true to prevent that ugly default * header. We can enable and style when we need to. */ export default Actions.create( <Scene key="root"> <Scene key="login" component={Login} hideNavBar={true} /> <Scene key="home" component={Home} hideNavBar={true} /> <Scene key="pointInTime" component={PointInTime} hideNavBar={true} /> <Scene key="vispdat" component={Vispdat} hideNavBar={true} /> <Scene key="refuse" component={Refuse} hideNavBar={true} /> </Scene> );
/*global Showdown*/ describe('$showdown', function () { 'use strict'; beforeEach(module('pl.itcrowd.services')); it('should be possible to inject initialized $showdown converter', inject(function ($showdown) { expect($showdown).not.toBeUndefined(); })); it('should be instance of $showdown.converter', inject(function ($showdown) { expect($showdown instanceof Showdown.converter).toBeTruthy(); })); });
define(function () { var exports = {}; /** * Hashes string with a guarantee that if you need to hash a new string * that contains already hashed string at it's start, you can pass only * added part of that string along with the hash of already computed part * and will get correctly hash as if you passed full string. * * @param {string} str * @param {number=} hash * @return {number} */ exports.hash = function (str, hash) { hash = hash || 5381; // alghorithm by Dan Bernstein var i = -1, length = str.length; while(++i < length) { hash = ((hash << 5) + hash) ^ str.charCodeAt(i); } return hash; }; var entityDecoder = document.createElement('div'); /** * Correctly decodes all hex, decimal and named entities * @param {string} text * @return {string} */ exports.decodeHtmlEntities = function(text){ return text.replace(/&(?:#(x)?(\d+)|(\w+));/g, function(match, hexFlag, decOrHex, name) { if(decOrHex) { return String.fromCharCode(parseInt(decOrHex, hexFlag ? 16 : 10)); } switch(name) { case 'lt': return '<'; case 'gt': return '>'; case 'amp': return '&'; case 'quote': return '"'; default: entityDecoder.innerHTML = '&' + name + ';'; return entityDecoder.textContent; } }); }; /** * Calculates shallow difference between two object * @param {Object} one * @param {Object} other * @return {Object} */ exports.shallowObjectDiff = function(one, other) { // since we will be calling setAttribute there is no need to // differentiate between changes and additions var set = {}, removed = [], haveChanges = false, keys = Object.keys(one), length, key, i; // first go through all keys of `one` for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(other[key] != null) { if(one[key] !== other[key]) { set[key] = other[key]; haveChanges = true; } } else { removed.push(key); haveChanges = true; } } // then add all missing from the `other` into `one` keys = Object.keys(other); for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(one[key] == null) { set[key] = other[key]; haveChanges = true; } } return haveChanges ? { set: set, removed: removed } : false; }; return exports; });
version https://git-lfs.github.com/spec/v1 oid sha256:558005fd55405d3069b06849812a921274543d712676f42ad4a8c122034c02e4 size 819
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().references('id').inTable('expenses') table.integer('position').notNullable() table.decimal('preTaxAmount').notNullable() table.decimal('taxrate').notNullable() table.text('description') table.index('expense_id') }) }) .then(() => { // this is necessary BEFORE creating the expense items because knex // drops the expenses table and then recreates it (foreign key problem). console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses') return knex.schema.table('expenses', table => { table.dropColumn('preTaxAmount') table.dropColumn('taxrate') }) }) .then(() => { console.log('Migrating ' + allExpenses.length + ' expenses to items') return Promise.all( allExpenses.map(expense => createExpenseItem(knex, expense)) ) }) } exports.down = (knex, Promise) => { return knex.schema.dropTableIfExists('expense_items') } function createExpenseItem(knex, expense) { return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
var express = require('express'); var app = express(); var path = require('path'); var session = require('express-session'); var bodyParser = require('body-parser') var fs = require('fs'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(session({ secret: 'angular_tutorial', resave: true, saveUninitialized: true, })); var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; var ObjectID = require('mongodb').ObjectID; var db = new Db('tutor', new Server("localhost", 27017, {safe: true}, {auto_reconnect: true}, {})); db.open(function(){ console.log("mongo db is opened!"); db.collection('notes', function(error, notes) { db.notes = notes; }); db.collection('sections', function(error, sections) { db.sections = sections; }); }); app.get("/notes", function(req,res) { db.notes.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.post("/notes", function(req,res) { db.notes.insert(req.body); res.end(); }); app.get("/sections", function(req,res) { db.sections.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.get("/checkUser", function(req,res) { if (req.query.user.length>2) { res.send(true); } else { res.send(false); } }); app.post("/sections/replace", function(req,resp) { // do not clear the list if (req.body.length==0) { resp.end(); } // this should be used only for reordering db.sections.remove({}, function(err, res) { if (err) console.log(err); db.sections.insert(req.body, function(err, res) { if (err) console.log("err after insert",err); resp.end(); }); }); }); app.listen(3000);
var Screen = require('./basescreen'); var Game = require('../game'); var helpScreen = new Screen('Help'); // Define our winning screen helpScreen.render = function (display) { var text = 'jsrogue help'; var border = '-------------'; var y = 0; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, border); display.drawText(0, y++, 'The villagers have been complaining of a terrible stench coming from the cave.'); display.drawText(0, y++, 'Find the source of this smell and get rid of it!'); y += 3; display.drawText(0, y++, '[h or Left Arrow] to move left'); display.drawText(0, y++, '[l or Right Arrow] to move right'); display.drawText(0, y++, '[j or Down Arrow] to move down'); display.drawText(0, y++, '[k or Up Arrow] to move up'); display.drawText(0, y++, '[,] to pick up items'); //display.drawText(0, y++, '[d] to drop items'); //display.drawText(0, y++, '[e] to eat items'); //display.drawText(0, y++, '[w] to wield items'); //display.drawText(0, y++, '[W] to wield items'); //display.drawText(0, y++, '[x] to examine items'); display.drawText(0, y++, '[i] to view and manipulate your inventory'); display.drawText(0, y++, '[;] to look around you'); display.drawText(0, y++, '[?] to show this help screen'); y += 3; text = '--- press any key to continue ---'; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); }; helpScreen.handleInput = function (inputType, inputData) { // Switch back to the play screen. this.getParentScreen().setSubScreen(undefined); }; module.exports = helpScreen;
requirejs(['helper/util'], function(util){ });
// 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: 7.6.1-4-7 description: > Allow reserved words as property names by set function within an object, verified with hasOwnProperty: while, debugger, function includes: [runTestCase.js] ---*/ function testcase() { var test0 = 0, test1 = 1, test2 = 2; var tokenCodes = { set while(value){ test0 = value; }, get while(){ return test0 }, set debugger(value){ test1 = value; }, get debugger(){ return test1; }, set function(value){ test2 = value; }, get function(){ return test2; } }; var arr = [ 'while' , 'debugger', 'function' ]; for(var p in tokenCodes) { for(var p1 in arr) { if(arr[p1] === p) { if(!tokenCodes.hasOwnProperty(arr[p1])) { return false; }; } } } return true; } runTestCase(testcase);
var View = require('ampersand-view'); var templates = require('../templates'); module.exports = View.extend({ template: templates.includes.scholarship, bindings: { 'model.field': '[role=field]', 'model.slots': '[role=slots]', 'model.holder': '[role=holder]', 'model.type': '[role=type]', 'model.link': { type: 'attribute', role: 'link', name: 'href' }, 'model.scholarshipIdUpperCase': '[role=link]', 'model.releaseDateFormated': '[role=release-date]', 'model.closeDateFormated': '[role=close-date]' } });
var toInteger = require('./toInteger'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @specs * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'done saving!' after the two async saves have completed */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } module.exports = after;
$.widget( "alexandra.panelSlider", { options: { currentView: null, // The panel currently in focus panels:[] // All panels added to the navigation system }, //The constructor of the panelSLide widget _create: function() { var tempThis=this; this.element.addClass("panelSlider"); this.options.currentView=this.options.panels[0]; $.each(this.options.panels, function(i, val){ $("#"+val).hide(); tempThis._checkLinks(val); }); $("#"+this.options.currentView).show(); }, _checkLinks: function(val){ var tempThis=this; $("#"+val+" a").click(function (event) { event.preventDefault(); event.stopPropagation(); var url = $(this).attr('href'); var urlRegex = '/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/'; var res = url.match(urlRegex); if(res==null){ var newView=$.inArray(url,tempThis.options.panels); if(newView>-1){ var curView=$.inArray(tempThis.options.currentView,tempThis.options.panels); console.log("new: "+newView+", current: "+curView); if(newView>curView) tempThis.slide(url,false); else if(newView<curView) tempThis.slide(url,true); return; } } window.location = url; }); }, //It's possible to add a panel in runtime addPanel: function(panel) { this.options.panels.push(panel); $("#"+panel).hide(); this._checkLinks(panel); }, //A panel can be removed runtime removePanel: function(panel){ for(var i=0;i<this.options.panels.length;i++){ if(this.options.panels[i]==panel){ if(panel==this.options.currentView){ $("#"+panel).hide(); this.options.currentView= i-1<0 ? this.options.panels[1] : this.options.panels[i-1]; $("#"+this.options.currentView).show(); } this.options.panels.splice(i, 1); break; } } }, //The function that actually does all the sliding //If the goingBack variable is true the sliding will happen from left to right, and vice versa slide: function(panelToShow, goingBack){ /* Making sure that only registered objects can act as panels. Might be a little to rough to make such a hard return statement. */ if($.inArray(panelToShow,this.options.panels)<0) return "Not a registered panel"; var tempThis=this; var tempCurrentView=this.options.currentView; /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide off the screen */ var currentPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper=$("<div/>"); this.element.append(currentPanel); currentPanel.append(innerWrapper); innerWrapper.append($("#"+this.options.currentView)); innerWrapper.hide("slide",{direction: goingBack ? "right" : "left"}, function(){ $("#"+tempCurrentView).hide(); tempThis.element.append($("#"+tempCurrentView)); currentPanel.remove(); }); /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide onto the screen */ var newPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper2=$("<div/>"); innerWrapper2.hide(); this.element.append(newPanel); newPanel.append(innerWrapper2); innerWrapper2.append($("#"+panelToShow)); $("#"+panelToShow).show(); innerWrapper2.show("slide",{direction: goingBack ? "left" : "right"},function(){ tempThis.element.append($("#"+panelToShow)); newPanel.remove(); }); this.options.currentView=panelToShow; } });
(function() { 'use strict'; function movieDetail(movieDetailService) { return { restrict: 'EA', replace: true, templateUrl: './src/app/movieDetail/template.html', scope: {}, controllerAs: 'vm', bindToController: true, /*jshint unused:false*/ controller: function($log, $stateParams) { var vm = this; movieDetailService.getMovie().then(function(response){ vm.movie = response.data; vm.movie.vote = (vm.movie.vote_average*10); vm.movie.genres_name = []; vm.movie.production_companies_name = []; vm.movie.production_countries_name = []; for (var i = 0; i <= vm.movie.genres.length-1; i++) { vm.movie.genres_name.push(vm.movie.genres[i].name); vm.movie.genres_name.sort(); } for (var i = 0; i <= vm.movie.production_companies.length-1; i++) { vm.movie.production_companies_name.push(vm.movie.production_companies[i].name); vm.movie.production_companies_name.sort(); } for (var i = 0; i <= vm.movie.production_countries.length-1; i++) { vm.movie.production_countries_name.push(vm.movie.production_countries[i].name); vm.movie.production_countries_name.sort(); } }); }, link: function(scope, elm, attrs) { } }; } angular.module('movieDetailDirective', ['services.movieDetail']) .directive('movieDetail', movieDetail); })();
/* See license.txt for terms of usage */ require.def("domplate/toolTip", [ "domplate/domplate", "core/lib", "core/trace" ], function(Domplate, Lib, Trace) { with (Domplate) { // ************************************************************************************************ // Globals var mouseEvents = "mousemove mouseover mousedown click mouseout"; var currentToolTip = null; // ************************************************************************************************ // Tooltip function ToolTip() { this.element = null; } ToolTip.prototype = domplate( { tag: DIV({"class": "toolTip"}, DIV() ), show: function(target, options) { if (currentToolTip) currentToolTip.hide(); this.target = target; this.addListeners(); // Render the tooltip. var body = Lib.getBody(document); this.element = this.tag.append({options: options}, body, this); // Compute coordinates and show. var box = Lib.getElementBox(this.target); this.element.style.top = box.top + box.height + "px"; this.element.style.left = box.left + box.width + "px"; this.element.style.display = "block"; currentToolTip = this; return this.element; }, hide: function() { if (!this.element) return; this.removeListeners(); // Remove UI this.element.parentNode.removeChild(this.element); currentToolTip = this.element = null; }, addListeners: function() { this.onMouseEvent = Lib.bind(this.onMouseEvent, this); // Register listeners for all mouse events. $(document).bind(mouseEvents, this.onMouseEvent, true); }, removeListeners: function() { // Remove listeners for mouse events. $(document).unbind(mouseEvents, this.onMouseEvent, this, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Listeners onMouseEvent: function(event) { var e = Lib.fixEvent(event); // If the mouse is hovering within the tooltip pass the event further to it. var ancestor = Lib.getAncestorByClass(e.target, "toolTip"); if (ancestor) return; var x = event.clientX, y = event.clientY; var box = Lib.getElementBox(this.element); if (event.type != "click" && event.type != "mousedown") box = Lib.inflateRect(box, 10, 10); // If the mouse is hovering within near neighbourhood, ignore it. if (Lib.pointInRect(box, x, y)) { Lib.cancelEvent(e); return; } // If the mouse is hovering over the target, ignore it too. if (Lib.isAncestor(e.target, this.target)) { Lib.cancelEvent(e); return; } // The mouse is hovering far away, let's destroy the the tooltip. this.hide(); Lib.cancelEvent(e); } }); // ************************************************************************************************ return ToolTip; // **********************************************************************************************// }});
import robot from 'robotjs' import sleep from 'sleep' import orifice from './fc8_orifice_map.json' var fs = require('fs') /*//set speed robot.setKeyboardDelay(150) robot.setMouseDelay(100)*/ let type = [ "Orifice", "Venturi", "Nozzle", "Fixed Geometry", "V-Cone", "Segmental Meters", "Linear Meters" ] exports.startFC8 = function(){ robot.keyTap('command') robot.typeString('FC8') sleep.msleep(500) robot.keyTap('enter') sleep.msleep(500) } exports.selectType = function(request){ robot.keyTap('tab') let i = 0 for(i=0; i<type.indexOf(request); i++){ robot.keyTap('down') } robot.keyTap('tab') robot.keyTap('enter') } exports.autoCompileGas = function(){ let i = 0 for(i=0; i<9; i++){ robot.keyTap('tab') } robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } robot.keyTap('enter') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('enter') } exports.calculation = function(object) { //select dp flow size let i = 0 if(object.method == "dp"){ robot.keyTap('enter') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.percMaxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "flow"){ robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.flow.differentialPressure) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "size"){ robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') /*for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.percMaxFlow)*/ robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.differential) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } if(object.checkVentDrainHole!="off"){ /* robot.keyTap('tab') robot.keyTap('tab') let ind = orifice.FlangeTaps.VentDrainHole.indexOf(object.ventDrainHole) let indStd = orifice.FlangeTaps.VentDrainHole.indexOf('No Vent/Drain Hole') if(ind<indStd){ for (i=0; i<indStd-ind; i++){ robot.keyTap('up') } } else { for (i=0; i<ind-indStd; i++){ robot.keyTap('down') } }*/ if(object.ventDrainHole=="FC8"){ robot.keyTap('enter') } else if (object.ventDrainHole=="userdefined"){ robot.keyTap('tab') robot.keyTap('tab') for(i=0;i<17;i++){ robot.keyTap('down') } robot.typeString(object.userDefinedDiameters) robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('enter') } for(i=0; i<2; i++){ robot.keyTap('tab', 'shift') } } } exports.printPDF = function(fileName, customer, tag){ let i=0 robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(customer) robot.keyTap('tab') robot.keyTap('tab') robot.typeString(tag) for(i=0; i<15; i++){ robot.keyTap('tab') } robot.keyTap('enter') sleep.msleep(500) robot.typeString(fileName) robot.keyTap('enter') sleep.msleep(500) } exports.existFile = function (fileName, errors) { fs.exists('../Documents/'+fileName, function(exists) { if(!exists){ errors.push(fileName) console.log(fileName, "ha presentato un errore") console.log(errors) } }); }
/** * Simple re-export of frost-detail-tabs-more-tabs in the app namespace */ export {default} from 'ember-frost-tabs/components/frost-detail-tabs-more-tabs'
'use strict'; /** * Module dependencies */ var citiesPolicy = require('../policies/cities.server.policy'), cities = require('../controllers/cities.server.controller'); module.exports = function (app) { // City collection routes app.route('/api/cities').all(citiesPolicy.isAllowed) .get(cities.list) .post(cities.create); // Single city routes app.route('/api/cities/:cityId').all(citiesPolicy.isAllowed) .get(cities.read) .put(cities.update) .delete(cities.delete); // Finish by binding the city middleware app.param('cityId', cities.cityByID); };
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof exports === "object") { factory(require("jquery")); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ET (Estonian; eesti, eesti keel) */ $.extend($.validator.messages, { required: "See väli peab olema täidetud.", maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."), minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."), rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."), email: "Palun sisestage korrektne e-maili aadress.", url: "Palun sisestage korrektne URL.", date: "Palun sisestage korrektne kuupäev.", dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).", number: "Palun sisestage korrektne number.", digits: "Palun sisestage ainult numbreid.", equalTo: "Palun sisestage sama väärtus uuesti.", range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."), max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."), min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."), creditcard: "Palun sisestage korrektne krediitkaardi number." }); }));
import { TASK_STATUS_ACTIVE, TASK_STATUS_COMPLETED } from 'modules/task/constants'; export class RouterService { constructor($state, $stateParams) { this.state = $state; this.params = $stateParams; } isActiveTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_ACTIVE}); } isCompletedTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_COMPLETED}); } isTasks() { return this.state.is('app.tasks', {filter: ''}); } toActiveTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_ACTIVE}); } toCompletedTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_COMPLETED}); } toTasks() { return this.state.go('app.tasks'); } }
module.exports = { description: 'deconflict entry points with the same name in different directories', command: 'rollup --input main.js --input sub/main.js --format esm --dir _actual --experimentalCodeSplitting' };
/** * xDo app client * * Auther: [email protected] */ var app = angular.module('app', ['ngResource']); app.controller('AppCtrl', ['$scope', function($scope) { // Parent controller for all the Ctrls $scope.appModel = {} }]); // Can define config block here or use ngRoute
/** * @module creatine.transitions **/ (function() { "use strict"; /** * A transition effect to scroll the new scene. * * ## Usage example * * var game = new tine.Game(null, { * create: function() { * var transition = new tine.transitions.Scroll(tine.TOP, null, 1000); * game.replace(new MyScene(), transition); * } * }); * * @class Scroll * @constructor * @param {Constant} [direction=creatine.LEFT] The direction. * @param {Function} [ease=createjs.Ease.linear] An easing function from * `createjs.Ease` (provided by TweenJS). * @param {Number} [time=400] The transition time in milliseconds. **/ var Scroll = function(direction, ease, time) { /** * Direction of the effect. * @property direction * @type {Constant} **/ this.direction = direction || creatine.LEFT; /** * An Easing function from createjs.Ease. * @property ease * @type {Function} **/ this.ease = ease || createjs.Ease.linear; /** * The transition time in milliseconds. * @property time * @type {Number} **/ this.time = time || 400; } var p = Scroll.prototype; /** * Initialize the transition (called by the director). * @method start * @param {Director} director The Director instance. * @param {Scene} outScene The active scene. * @param {Scene} inScene The incoming scene. * @param {Function} callback The callback function called when the * transition is done. * @protected **/ p.start = function(director, outScene, inScene, callback) { this.director = director; this.outScene = outScene; this.inScene = inScene; this.callback = callback; var w = director.stage.canvas.width; var h = director.stage.canvas.height; var dir = this.direction; this.targetX = 0; this.targetY = 0; inScene.x = 0; inScene.y = 0; switch (this.direction) { case creatine.LEFT: inScene.x = w; this.targetX = -w; break; case creatine.RIGHT: inScene.x = -w; this.targetX = w; break; case creatine.TOP: inScene.y = h; this.targetY = -h; break; case creatine.BOTTOM: inScene.y = -h; this.targetY = h; break; } var self = this; createjs.Tween.get(inScene, {override:true}) .to({x:0, y:0}, this.time, this.ease) .call(function() { self.complete(); }) createjs.Tween.get(outScene, {override:true}) .to({x:this.targetX, y:this.targetY}, this.time, this.ease) } /** * Finalize the transition (called by the director). * @method complete * @protected **/ p.complete = function() { createjs.Tween.removeTweens(this.inScene); createjs.Tween.removeTweens(this.outScene); this.inScene.x = 0; this.inScene.x = 0; this.outScene.x = 0; this.outScene.y = 0; this.callback(); } creatine.transitions.Scroll = Scroll; }());
function Test() { a = 1; console.log(a); try { console.log(b); } catch (e) { console.log("null"); } } console.log("Test1"); Test(); a = 2; b = 3; console.log("Test2"); Test(); Test.a = 4; Test.b = 4; console.log("Test3"); Test(); console.log("Test4"); console.log(Test.a); console.log(Test.b);
// All code points in the `Sc` category as per Unicode v6.3.0: [ 0x24, 0xA2, 0xA3, 0xA4, 0xA5, 0x58F, 0x60B, 0x9F2, 0x9F3, 0x9FB, 0xAF1, 0xBF9, 0xE3F, 0x17DB, 0x20A0, 0x20A1, 0x20A2, 0x20A3, 0x20A4, 0x20A5, 0x20A6, 0x20A7, 0x20A8, 0x20A9, 0x20AA, 0x20AB, 0x20AC, 0x20AD, 0x20AE, 0x20AF, 0x20B0, 0x20B1, 0x20B2, 0x20B3, 0x20B4, 0x20B5, 0x20B6, 0x20B7, 0x20B8, 0x20B9, 0x20BA, 0xA838, 0xFDFC, 0xFE69, 0xFF04, 0xFFE0, 0xFFE1, 0xFFE5, 0xFFE6 ];
var should = require('should'), supertest = require('supertest'), testUtils = require('../../../utils/index'), localUtils = require('./utils'), config = require('../../../../server/config/index'), ghost = testUtils.startGhost, request; describe('Slug API', function () { var accesstoken = '', ghostServer; before(function () { return ghost() .then(function (_ghostServer) { ghostServer = _ghostServer; request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request); }) .then(function (token) { accesstoken = token; }); }); it('should be able to get a post slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/a post title/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('a-post-title'); done(); }); }); it('should be able to get a tag slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/atag/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('atag'); done(); }); }); it('should be able to get a user slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/user/user name/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('user-name'); done(); }); }); it('should be able to get an app slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/app/cool app/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('cool-app'); done(); }); }); it('should not be able to get a slug for an unknown type', function (done) { request.get(localUtils.API.getApiQuery('slugs/unknown/who knows/')) .set('Authorization', 'Bearer ' + accesstoken) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(400) .end(function (err, res) { if (err) { return done(err); } var jsonResponse = res.body; should.exist(jsonResponse.errors); done(); }); }); });
function Grid(size) { this.size = size; this.startTiles = 2; this.cells = []; this.build(); this.playerTurn = true; } // pre-allocate these objects (for speed) Grid.prototype.indexes = []; for (var x=0; x<4; x++) { Grid.prototype.indexes.push([]); for (var y=0; y<4; y++) { Grid.prototype.indexes[x].push( {x:x, y:y} ); } } // Build a grid of the specified size Grid.prototype.build = function () { for (var x = 0; x < this.size; x++) { var row = this.cells[x] = []; for (var y = 0; y < this.size; y++) { row.push(null); } } }; // Find the first available random position Grid.prototype.randomAvailableCell = function () { var cells = this.availableCells(); if (cells.length) { return cells[Math.floor(Math.random() * cells.length)]; } }; Grid.prototype.availableCells = function () { var cells = []; var self = this; this.eachCell(function (x, y, tile) { if (!tile) { //cells.push(self.indexes[x][y]); cells.push( {x:x, y:y} ); } }); return cells; }; // Call callback for every cell Grid.prototype.eachCell = function (callback) { for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { callback(x, y, this.cells[x][y]); } } }; // Check if there are any cells available Grid.prototype.cellsAvailable = function () { return !!this.availableCells().length; }; // Check if the specified cell is taken Grid.prototype.cellAvailable = function (cell) { return !this.cellOccupied(cell); }; Grid.prototype.cellOccupied = function (cell) { return !!this.cellContent(cell); }; Grid.prototype.cellContent = function (cell) { if (this.withinBounds(cell)) { return this.cells[cell.x][cell.y]; } else { return null; } }; // Inserts a tile at its position Grid.prototype.insertTile = function (tile) { this.cells[tile.x][tile.y] = tile; }; Grid.prototype.removeTile = function (tile) { this.cells[tile.x][tile.y] = null; }; Grid.prototype.withinBounds = function (position) { return position.x >= 0 && position.x < this.size && position.y >= 0 && position.y < this.size; }; Grid.prototype.clone = function() { newGrid = new Grid(this.size); newGrid.playerTurn = this.playerTurn; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { if (this.cells[x][y]) { newGrid.insertTile(this.cells[x][y].clone()); } } } return newGrid; }; // Set up the initial tiles to start the game with Grid.prototype.addStartTiles = function () { for (var i=0; i<this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position Grid.prototype.addRandomTile = function () { if (this.cellsAvailable()) { var value = Math.random() < 0.9 ? 2 : 4; //var value = Math.random() < 0.9 ? 256 : 512; var tile = new Tile(this.randomAvailableCell(), value); this.insertTile(tile); } }; // Save all tile positions and remove merger info Grid.prototype.prepareTiles = function () { this.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation Grid.prototype.moveTile = function (tile, cell) { this.cells[tile.x][tile.y] = null; this.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; Grid.prototype.vectors = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left } // Get the vector representing the chosen direction Grid.prototype.getVector = function (direction) { // Vectors representing tile movement return this.vectors[direction]; }; // Move tiles on the grid in the specified direction // returns true if move was successful Grid.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; var score = 0; var won = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = self.indexes[x][y]; tile = self.cellContent(cell); if (tile) { //if (debug) { //console.log('tile @', x, y); //} var positions = self.findFarthestPosition(cell, vector); var next = self.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.insertTile(merged); self.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score score += merged.value; // The mighty 2048 tile if (merged.value === 2048) { won = true; } } else { //if (debug) { //console.log(cell); //console.log(tile); //} self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { self.playerTurn = false; //console.log('setting player turn to ', self.playerTurn); moved = true; // The tile moved from its original cell! } } }); }); //console.log('returning, playerturn is', self.playerTurn); //if (!moved) { //console.log('cell', cell); //console.log('tile', tile); //console.log('direction', direction); //console.log(this.toString()); //} return {moved: moved, score: score, won: won}; }; Grid.prototype.computerMove = function() { this.addRandomTile(); this.playerTurn = true; } // Build a list of positions to traverse in the right order Grid.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; Grid.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.withinBounds(cell) && this.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; Grid.prototype.movesAvailable = function () { return this.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) // returns the number of matches Grid.prototype.tileMatchesAvailable = function () { var self = this; //var matches = 0; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.cellContent(cell); if (other && other.value === tile.value) { return true; //matches++; // These two tiles can be merged } } } } } //console.log(matches); return false; //matches; }; Grid.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; }; Grid.prototype.toString = function() { string = ''; for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { if (this.cells[j][i]) { string += this.cells[j][i].value + ' '; } else { string += '_ '; } } string += '\n'; } return string; } // counts the number of isolated groups. Grid.prototype.islands = function() { var self = this; var mark = function(x, y, value) { if (x >= 0 && x <= 3 && y >= 0 && y <= 3 && self.cells[x][y] && self.cells[x][y].value == value && !self.cells[x][y].marked ) { self.cells[x][y].marked = true; for (direction in [0,1,2,3]) { var vector = self.getVector(direction); mark(x + vector.x, y + vector.y, value); } } } var islands = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y]) { this.cells[x][y].marked = false } } } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y] && !this.cells[x][y].marked) { islands++; mark(x, y , this.cells[x][y].value); } } } return islands; } /// measures how smooth the grid is (as if the values of the pieces // were interpreted as elevations). Sums of the pairwise difference // between neighboring tiles (in log space, so it represents the // number of merges that need to happen before they can merge). // Note that the pieces can be distant Grid.prototype.smoothness = function() { var smoothness = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if ( this.cellOccupied( this.indexes[x][y] )) { var value = Math.log(this.cellContent( this.indexes[x][y] ).value) / Math.log(2); for (var direction=1; direction<=2; direction++) { var vector = this.getVector(direction); var targetCell = this.findFarthestPosition(this.indexes[x][y], vector).next; if (this.cellOccupied(targetCell)) { var target = this.cellContent(targetCell); var targetValue = Math.log(target.value) / Math.log(2); smoothness -= Math.abs(value - targetValue); } } } } } return smoothness; } Grid.prototype.monotonicity = function() { var self = this; var marked = []; var queued = []; var highestValue = 0; var highestCell = {x:0, y:0}; for (var x=0; x<4; x++) { marked.push([]); queued.push([]); for (var y=0; y<4; y++) { marked[x].push(false); queued[x].push(false); if (this.cells[x][y] && this.cells[x][y].value > highestValue) { highestValue = this.cells[x][y].value; highestCell.x = x; highestCell.y = y; } } } increases = 0; cellQueue = [highestCell]; queued[highestCell.x][highestCell.y] = true; markList = [highestCell]; markAfter = 1; // only mark after all queued moves are done, as if searching in parallel var markAndScore = function(cell) { markList.push(cell); var value; if (self.cellOccupied(cell)) { value = Math.log(self.cellContent(cell).value) / Math.log(2); } else { value = 0; } for (direction in [0,1,2,3]) { var vector = self.getVector(direction); var target = { x: cell.x + vector.x, y: cell.y+vector.y } if (self.withinBounds(target) && !marked[target.x][target.y]) { if ( self.cellOccupied(target) ) { targetValue = Math.log(self.cellContent(target).value ) / Math.log(2); if ( targetValue > value ) { //console.log(cell, value, target, targetValue); increases += targetValue - value; } } if (!queued[target.x][target.y]) { cellQueue.push(target); queued[target.x][target.y] = true; } } } if (markAfter == 0) { while (markList.length > 0) { var cel = markList.pop(); marked[cel.x][cel.y] = true; } markAfter = cellQueue.length; } } while (cellQueue.length > 0) { markAfter--; markAndScore(cellQueue.shift()) } return -increases; } // measures how monotonic the grid is. This means the values of the tiles are strictly increasing // or decreasing in both the left/right and up/down directions Grid.prototype.monotonicity2 = function() { // scores for all four directions var totals = [0, 0, 0, 0]; // up/down direction for (var x=0; x<4; x++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[x][next] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:x, y:current}) ? Math.log(this.cellContent( this.indexes[x][current] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:x, y:next}) ? Math.log(this.cellContent( this.indexes[x][next] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[0] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[1] += currentValue - nextValue; } current = next; next++; } } // left/right direction for (var y=0; y<4; y++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[next][y] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:current, y:y}) ? Math.log(this.cellContent( this.indexes[current][y] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:next, y:y}) ? Math.log(this.cellContent( this.indexes[next][y] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[2] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[3] += currentValue - nextValue; } current = next; next++; } } return Math.max(totals[0], totals[1]) + Math.max(totals[2], totals[3]); } Grid.prototype.maxValue = function() { var max = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { var value = this.cellContent(this.indexes[x][y]).value; if (value > max) { max = value; } } } } return Math.log(max) / Math.log(2); } // WIP. trying to favor top-heavy distributions (force consolidation of higher value tiles) /* Grid.prototype.valueSum = function() { var valueCount = []; for (var i=0; i<11; i++) { valueCount.push(0); } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { valueCount[Math.log(this.cellContent(this.indexes[x][y]).value) / Math.log(2)]++; } } } var sum = 0; for (var i=1; i<11; i++) { sum += valueCount[i] * Math.pow(2, i) + i; } return sum; } */ // check for win Grid.prototype.isWin = function() { var self = this; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (self.cellOccupied(this.indexes[x][y])) { if (self.cellContent(this.indexes[x][y]).value == 2048) { return true; } } } } return false; } //Grid.prototype.zobristTable = {} //for //Grid.prototype.hash = function() { //}