code
stringlengths
2
1.05M
/** * Created by ndyumin on 20.03.2017. */ const {store} = require('../src/'); const sum = (x, y) => x + y; const mult = (x, y) => x * y; const compose = (f, d) => (...args) => f(d(...args)); xtest('basic transaction', () => { /** 0 (init) | 0 >>(branch)>> 0 +2 (2) -> +2 (2) | *3 (6) +2 (4) -> +2 (8) | *3 (24) 24 <<(merge)<< +1 (25) */ const mainState = jest.fn(); const transaction = jest.fn(); const state = store(0); state.subscribe(mainState); const t = state.branch(true); t.store().subscribe(transaction); const stateEvent = state.createEvent(sum); const transactionEvent = t.store().createEvent(mult); stateEvent(2); transactionEvent(3); stateEvent(2); transactionEvent(3); t.merge(); stateEvent(1); expect(mainState.mock.calls.length).toBe(6); expect(mainState.mock.calls).toEqual([ [ 0 ], [ 2 ], [ 4 ], [ 24 ], [ 25 ] ]); expect(transaction.mock.calls.length).toBe(5); expect(transaction.mock.calls).toEqual([ [ 0 ], [ 2 ], [ 6 ], [ 8 ], [ 24 ] ]); }); xtest('test 2 transactions', () => { /** 0 0 0 +2(2) -> +2(2) -> +2(2) | *3(6) | +2(4) -> +2(8) -> +2(4) | | *4(16) 8 <<< | 16 <<< */ const clb0 = jest.fn(); const clb1 = jest.fn(); const clb2 = jest.fn(); const state = store(0); state.subscribe(clb0); const t = state.branch(); const t2 = state.branch(); t.store().subscribe(clb1); t2.store().subscribe(clb2); const stateEvent = state.createEvent(sum); const transactionEvent = t.store().createEvent(mult); const transaction2Event = t2.store().createEvent(mult); stateEvent(2); transactionEvent(3) ; stateEvent(2); transaction2Event(4) ; t.merge(); t2.merge(); // console.log(clb1.mock.calls); // console.log(clb2.mock.calls); expect(clb0.mock.calls.length).toBe(5); expect(clb0.mock.calls).toEqual([ [ 0 ], [ 2 ], [ 4 ], [ 8 ], [ 16 ] ]); expect(clb1.mock.calls.length).toBe(4); expect(clb1.mock.calls).toEqual([ [ 0 ], [ 2 ], [ 6 ], [ 8 ] ]); expect(clb2.mock.calls.length).toBe(5); expect(clb2.mock.calls).toEqual([ [ 0 ], [ 2 ], [ 4 ], [ 16 ], [ 16 ] ]); });
module.exports = function (grunt) { grunt.initConfig({ connect: { server: { options: { port: 9001, base: 'public/' } } }, watch: { project: { files: ['public/**/*.js', 'public/**/*.html', 'public/**/*.json', 'public/**/*.css', 'public/*.html'], options: { livereload: true } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['connect', 'watch']); };
{ t.$options.props; for (var n in e) t[n] = null == e[n] ? g : h(e[n], t); }
import { Notifications } from '../../../app/notifications'; import { Subscriptions } from '../../../app/models'; import { msgStream } from '../../../app/lib/server/lib/msgStream'; import { fields } from '.'; Subscriptions.on('change', ({ clientAction, id, data }) => { switch (clientAction) { case 'inserted': case 'updated': // Override data cuz we do not publish all fields data = Subscriptions.findOneById(id, { fields }); break; case 'removed': data = Subscriptions.trashFindOneById(id, { fields: { u: 1, rid: 1 } }); // emit a removed event on msg stream to remove the user's stream-room-messages subscription when the user is removed from room msgStream.__emit(data.u._id, clientAction, data); break; } Notifications.streamUser.__emit(data.u._id, clientAction, data); Notifications.notifyUserInThisInstance( data.u._id, 'subscriptions-changed', clientAction, data, ); });
import path from 'path'; import readGlob from './readGlob'; export default async function listExtensions({ cwd = process.cwd(), filterNodeModules = true, showFile = true, } = []) { const files = await readGlob('**/*', { cwd, dot: true, nodir: true }); return files.reduce((result, item) => { if (!filterNodeModules || (!/node_modules/.test(item) && !/.git\//.test(item))) { const ext = path.extname(item); const entry = (ext === '') ? path.basename(item) : `*${ext}`; if (result.indexOf(entry) === -1) { if (showFile) { console.log(`"${entry}": ${item}`); } result.push(entry); } } return result; }, []); }
/** * Created by feng on 16/12/9. */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ListView, AlertIOS, TouchableOpacity, Image, } from 'react-native'; var Carousel = require('./04-Carousel'); var Newsdetails = require('./NewsDetails'); var IMHome = React.createClass({ getDefaultProps(){ return{ url: "http://c.m.163.com/nc/article/list/T1467284926140/0-20.html", imkey:"T1467284926140", topurl:"http://data.live.126.net/livechannel/previewlist.json", } }, getInitialState(){ return{ headerArray: [], dataSource: new ListView.DataSource({ rowHasChanged:(r1,r2) => r1 !== r2 }), } }, render(){ return( <View style={{backgroundColor:'white'}}> <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} renderHeader={this.renderHeader} /> </View> ); }, componentDidMount(){ this.requestForMainData(); this.requestForTopData(); }, requestForMainData(){ fetch(this.props.url) .then(response => response.json()) .then((result) => { // AlertIOS.alert("主体数据获取成功"); var jsonData = result[this.props.imkey]; var resultArray = []; for (var i=0;i<jsonData.length;i++){ var data = jsonData[i]; resultArray.push(data) } this.setState({ dataSource: this.state.dataSource.cloneWithRows(resultArray), }); // console.log(resultArray); }) .catch((error) => { // AlertIOS.alert("主体数据获取失败") }) }, requestForTopData(){ fetch(this.props.topurl) .then(response => response.json()) .then(result => { // AlertIOS.alert("头部数据获取成功"); var topData = result["top"]; var resultArray = []; for (var i=0;i<topData.length;i++){ resultArray.push(topData[i]) } this.setState({ headerArray: resultArray, }); }) .catch(error =>{ // AlertIOS.alert("头部数据获取失败") }) }, renderRow(rowData){ return( <TouchableOpacity onPress={() => { this.pushToNewsDetail(rowData) }} > <View style={styles.container}> <Image style={styles.left_iconImage} source={{uri: rowData.imgsrc}} /> <View style={styles.right_textView}> <Text style={styles.titleText}> {rowData.title} </Text> <Text style={styles.detailText}> {rowData.digest} </Text> <Text style={styles.followText}> {rowData.replyCount+'跟帖'} </Text> </View> </View> </TouchableOpacity> ) }, renderHeader(){ // console.log(this.state.headerArray); if(this.state.headerArray == 0){return} return( <Carousel headerArray = {this.state.headerArray}/> ) }, pushToNewsDetail(rowData){ this.props.navigator.push({ component: Newsdetails, title: rowData.title, passProps: {rowData}, }) } }); const styles = StyleSheet.create({ container: { flexDirection: 'row', // backgroundColor:'white', borderBottomWidth: 0.5, borderBottomColor: '#e8e8e8', justifyContent: 'center', padding: 20, }, left_iconImage:{ width: 90, height: 90, }, right_textView:{ // justifyContent: 'center', width: 260, // height: 90, marginLeft: 8, }, titleText:{ // backgroundColor: 'red', fontSize: 16, marginTop: 0, }, detailText:{ // backgroundColor: 'green', fontSize: 10, marginTop: 10, color:'gray', height: 50, }, followText: { // backgroundColor: 'blue', position: 'absolute', right: 10, bottom: -15, borderWidth: 0.5, borderColor: 'lightgray', padding: 3, borderRadius: 5, }, }); module.exports = IMHome;
import { serializable, identifier } from 'serializr'; import { BaseDomainStore, DomainModel } from '../../../src'; class ExampleAdvancedUserModel extends DomainModel { @serializable(identifier()) id; @serializable name; } class ExampleUserService { fetchAll() { return fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()); } fetchOne(id) { // Emulate failure from backend if (this.emulateFail) { this.emulateFail = false; return Promise.reject('ERROR FETCH ONE'); } return fetch(`https://jsonplaceholder.typicode.com/users/${id}`) .then((response) => { this.emulateFail = true; return response.json(); }); } } class ExampleAdvancedUserStore extends BaseDomainStore { static service = new ExampleUserService(); static modelSchema = ExampleAdvancedUserModel; storeDidFetchAll({ response }) { // Emulate not standard response const customResponse = { data: response }; return customResponse.data; } storeDidFetchOne({ response }) { // Emulate not standard response const customResponse = { data: response }; return customResponse.data; } storeFetchAllFailed(error) { console.warn('My custom fetch all global error handler', error); } storeFetchOneFailed(error) { console.warn('My custom fetch one global error handler', error); } } export default new ExampleAdvancedUserStore();
import { graphqlQuery } from '../graphql'; export default server => { server.post('/api/graphql', (schema, request) => { const batches = JSON.parse(request.requestBody); return Promise.all( batches.map(({ query, variables }) => graphqlQuery(query, variables, schema)), ); }); };
const Conflict = require('../../../build/server/game/conflict.js'); const Player = require('../../../build/server/game/player.js'); const DrawCard = require('../../../build/server/game/drawcard.js'); describe('Conflict', function() { beforeEach(function() { this.gameSpy = jasmine.createSpyObj('game', ['applyGameAction', 'on', 'raiseEvent', 'reapplyStateDependentEffects', 'getFrameworkContext']); this.gameSpy.applyGameAction.and.callFake((type, card, handler) => { handler(card); }); this.effectEngineSpy = jasmine.createSpyObj('effectEngine', ['checkEffects']); this.gameSpy.effectEngine = this.effectEngineSpy; this.attackingPlayer = new Player('1', { username: 'Player 1', settings: {} }, true, this.gameSpy); this.defendingPlayer = new Player('2', { username: 'Player 2', settings: {} }, true, this.gameSpy); this.attackerCard = new DrawCard(this.attackingPlayer, {}); spyOn(this.attackerCard, 'getSkill').and.returnValue(5); this.defenderCard = new DrawCard(this.defendingPlayer, {}); spyOn(this.defenderCard, 'getSkill').and.returnValue(3); spyOn(this.attackerCard, 'canParticipateAsAttacker').and.returnValue(true); spyOn(this.defenderCard, 'canParticipateAsDefender').and.returnValue(true); this.conflict = new Conflict(this.gameSpy, this.attackingPlayer, this.defendingPlayer, 'military'); this.conflict.addAttackers([this.attackerCard]); this.conflict.addDefenders([this.defenderCard]); this.conflict.calculateSkill(); }); describe('removeFromConflict()', function() { describe('when the card is an attacker', function() { beforeEach(function() { this.conflict.removeFromConflict(this.attackerCard); }); it('should remove the card from the attacker list', function() { expect(this.conflict.attackers).not.toContain(this.attackerCard); }); }); describe('when the card is a defender', function() { beforeEach(function() { this.conflict.removeFromConflict(this.defenderCard); }); it('should remove the card from the defender list', function() { expect(this.conflict.defenders).not.toContain(this.defenderCard); }); }); describe('when the card is not in the conflict', function() { beforeEach(function() { this.conflict.removeFromConflict(new DrawCard(this.attackingPlayer, {})); }); it('should not modify the participating cards', function() { expect(this.conflict.attackers).toContain(this.attackerCard); expect(this.conflict.defenders).toContain(this.defenderCard); }); it('should not modify conflict skills', function() { expect(this.conflict.attackerSkill).toBe(5); expect(this.conflict.defenderSkill).toBe(3); }); }); }); });
require('./html'); require('./scripts'); require('./server'); require('./styles'); require('./watch'); var gulp = require('gulp'); gulp.task('frontend', ['frontend:scripts', 'frontend:styles', 'frontend:html']);
System.register([],function(e,t){"use strict";var n;t&&t.id;return{setters:[],execute:function(){n=function(){function e(e){this.scene=e}return e}(),e("SceneBuilder",n)}}}); //# sourceMappingURL=SceneBuilder.js.map
function new_category() { name = $('#new_category_name').val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $("input[name=csrfmiddlewaretoken]").val()); } }); $.ajax({ type: "POST", url: "/recipes/new_category/", data: { name: name }, success: function(data) { $('#new_category_name').val(''); $('#sort_container').html(data); }, error: function(data) { alert(gettext('Error!')); } }); } function delete_category(id) { if (confirm(gettext("Are you sure to delete?"))) { $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $("input[name=csrfmiddlewaretoken]").val()); } }); $.ajax({ type: "POST", url: "/recipes/delete_category/", data: { id: id }, success: function(data) { $('#sort_container').html(data); }, error: function(data) { alert(gettext('Error!')); } }); } } function save_category() { var order = [] $('#sort_items li').each(function(i) { id = $(this).attr('id'); name = $('#' + id + ' input').val(); if (id) { order.push(id + ':' + name); } }); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $("input[name=csrfmiddlewaretoken]").val()); } }); $.ajax({ type: "POST", url: "/recipes/save_category/", data: { order: order }, success: function(data) { toast(gettext("Saved successfully.")); }, error: function(data) { alert(gettext('Error!')); } }); } $(function() { if ($("#sort_items").length) { $("#sort_items").sortable({containment: "#sort_container"}); $("#sort_items").disableSelection(); } });
(function() { angular .module('beercalc') .config(config); function config($stateProvider, $urlRouterProvider) { var profileState = { url: '/profile', templateUrl: '/views/profile-view.html', controller: "ProfileController", controllerAs: "profileControll", title: 'Perfil' }, optionsState = { url: '/options', templateUrl: '/views/options-view.html', controller: "OptionsController", controllerAs: "optionsControll", title: 'Configurações' }, billsState = { url: '/bills', templateUrl: '/views/bills-view.html', controller: "BillsController", controllerAs: "billsControll", title: 'Contas' }, homeState = { url: '/home', templateUrl: '/views/home-view.html', controller: "NavigationController", controllerAs: "navController", title: 'Inicio' }, recomendationsState = { url: '/social', templateUrl: '/views/social-view.html', controller: "SocialController", controllerAs: "socialControll", title: 'Recomendações' }, helpState = { url: '/help', templateUrl: '/views/help-view.html', controller: "HelpController", controllerAs: "helpControll", title: 'Ajuda' }, optionsAboutState = { url: '/about', templateUrl: '/views/options.about-view.html', title: 'Sobre' }; $urlRouterProvider.otherwise('/home'); $stateProvider.state('options', optionsState); $stateProvider.state('profile', profileState); $stateProvider.state('bills', billsState); $stateProvider.state('home', homeState); $stateProvider.state('recomendations', recomendationsState); $stateProvider.state('help', helpState); $stateProvider.state('about', optionsAboutState); } })();
/* * Copyright (c) 2014-2018 MKLab. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ // Toolbar Button var $button = $("<a id='toolbar-merge-generalizations' href='#' title='Merge Generalizations'></a>") /** * Return generalization views of a given view. */ function getGeneralizations (selected) { var edges = app.repository.getEdgeViewsOf(selected) var results = edges.filter(function (e) { return (e instanceof type.UMLGeneralizationView) && (e.head === selected) }) return results } /** * Merge generalizations */ function handleMerge () { // Get a selected view var views = app.selections.getSelectedViews() if (views.length < 1) { app.toast.info('Nothing selected.') return } // Get specialization views var selected = views[0] var generalizations = getGeneralizations(selected) if (generalizations.length < 1) { app.toast.info('No generalizations to merge.') return } // Compute coordinates for generalizations var sorted = generalizations.map(function (e) { return e.tail.top }).sort() var topLine = sorted.length > 0 ? sorted[0] : undefined var x = Math.round((selected.left + selected.getRight()) / 2) var y1 = Math.round(selected.getBottom()) var y2 = Math.round((topLine + selected.getBottom() + 15) / 2) // Make a command and execute var builder = app.repository.getOperationBuilder() builder.begin('merge generalizations') generalizations.forEach(function (view) { if (view.lineStyle !== type.EdgeView.LS_RECTILINEAR) { builder.fieldAssign(view, 'lineStyle', type.EdgeView.LS_RECTILINEAR) } var node = view.tail var _x = Math.round((node.left + node.getRight() / 2)) var _y = Math.round(node.top) var ps = new type.Points() ps.add(new type.Point(_x, _y)) ps.add(new type.Point(_x, y2)) ps.add(new type.Point(x, y2)) ps.add(new type.Point(x, y1)) builder.fieldAssign(view, 'points', ps.__write()) }) builder.end() app.repository.doOperation(builder.getOperation()) } function init () { // Toolbar Button $('#toolbar .buttons').append($button) $button.click(function () { app.commands.execute('merge-generalizations:merge') }) app.commands.register('merge-generalizations:merge', handleMerge) } exports.init = init
import { dev, prod } from './config/webpack/'; import { argv } from 'yargs'; let wpConfig; switch (argv.env) { case 'prod': case 'production': { wpConfig = prod; break; } case 'st': case 'stage': { // TODO break; } default: { wpConfig = dev; } } export default wpConfig;
const limit = require('./limit'); /** * @kind function * @name series * @memberof times * @param {Number} n * @param {Function} iteratee * @returns {Promise} */ module.exports = (count, fn, opts) => limit(count, 1, fn, opts);
(function () { 'use strict'; var app = angular.module('Fablab'); app.controller('AccountingUserController', function ($scope, UserService,$routeParams, $rootScope,$location, $log) { $scope.selected = {user: undefined}; $scope.showRole = $rootScope.hasAnyRole('PAYMENT_MANAGE'); $scope.minDate = moment().subtract(App.CONFIG.ACCOUNTING_EDIT_HISTORY_LIMIT, 'days').format('YYYY-MM-DD'); $scope.loadUser = function (userId) { UserService.get(userId, function (data) { $scope.selected.user = data; }); }; $scope.onSelectUser = function (user) { $location.path('accounting/user-account/' + user.id); $log.info(user); }; UserService.list(function (data) { $log.info("reload user"); $scope.users = data; if ($routeParams.id) { for (var k in data) { if (data[k].id === $routeParams.id) { $scope.onSelectUser(data[k]); break; } } } }); $scope.updateUser = function () { if ($routeParams.id) { $scope.loadUser($routeParams.id); } }; $scope.updateUser(); }); }()); app.controller('AccountingUserEditController', function ($scope, $routeParams, $controller) { $controller('AccountingUserController', {$scope: $scope}); $scope.loadUser($routeParams.id); } );
var request = require("request"); var sentiment = require("sentiment"); var qs = require("querystring"); var async = require("async"); module.exports = function(a, b) { var query, cb; if("function" === typeof a) { cb = a; } else if("function" === typeof b) { query = a; cb = b; } request({ uri: "http://search.twitter.com/search.json?" + qs.stringify({ q: query && query !== "" ? query.toString() : ":) OR :(", lang: "en" }), json: true }, function(err, res, data) { if(err || !data || !data.results) return cb(err, false); var results = data.results; var length = results.length; var yeps = 0; var nopes = 0; async.forEach(results, function(result, next) { sentiment(result.text, function(err, result) { if(result.score < 1) nopes++; else yeps++; next(err); }); }, function(err) { if(err) return cb(err, false); cb(null, yeps >= nopes); }); }); };
define(function(require, exports, module) { var $ = require('$'); var _ = require('underscore'); var Backbone = require('backbone'); var eventBus = require('app-core').Eventbus; require('select2'); var componentSelect = Backbone.View.extend({ manage : true, prefix : 'app-common/src/tpl/component/', template : 'component-select.html', initialize : function(options) { this.options = options; eventBus.off('component-select:renderSelect:' + options["component_id"]); eventBus.on('component-select:renderSelect:' + options["component_id"], this.renderSelect, this); }, renderSelect: function() { console.log(">>>>>>>>>>>>>>>>>>>>>>in renderSelect"); var type = this.options["component_type"]; // Fetch component_id var component_id = this.options["component_id"]; var multiple = this.options["multiple"]; var container_id = this.options["container_id"]; var _select = this.$el.find('select'); // If component_id is not null, then set id to this select if (component_id) { _select.attr("id", component_id); } // If component_id is not null, then set id to this select if (multiple && multiple === 'multiple') _select.attr("multiple", "multiple"); // If container_id is not null, then append this select to its container if(!container_id) container_id = component_id + '-container'; var select_container = '#' + container_id; // Remove existing multi selector if ($(select_container).children()) $(select_container).children('select').remove(); this.$el.appendTo(select_container); //TODO: refactor to use switch if (!type || type === 'SELECT2') this.makeSelect2(_select); else if (type === 'MULTI_SELECT') this.makeMultiSelect(_select); }, // Select2 makeSelect2 : function(select) { // Set CSS select.attr('class', 'select2'); // Setup CSS for this select element select.select2({ width : '100%', placeholder : "Please select", allowClear : true }); }, makeMultiSelect : function(select) { // Set CSS select.attr('class', 'searchable'); // Setup CSS for this select element select.multiSelect({ selectableOptgroup : true, selectableHeader : "<input type='text' class='form-control search-input' autocomplete='off' placeholder='Filter String'>", selectionHeader : "<input type='text' class='form-control search-input' autocomplete='off' placeholder='Filter String'>", afterInit : function(ms) { var that = this, $selectableSearch = that.$selectableUl.prev(), $selectionSearch = that.$selectionUl.prev(), selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)', selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected'; that.qs1 = $selectableSearch.quicksearch(selectableSearchString).on('keydown', function(e) { if (e.which === 40) { that.$selectableUl.focus(); return false; } }); that.qs2 = $selectionSearch.quicksearch(selectionSearchString).on('keydown', function(e) { if (e.which == 40) { that.$selectionUl.focus(); return false; } }); }, afterSelect : function() { this.qs1.cache(); this.qs2.cache(); }, afterDeselect : function() { this.qs1.cache(); this.qs2.cache(); } }); // Set default options console.log(this.options.selected); select.multiSelect('select', this.options.selected); }, serialize : function() { return { options : _.clone(this.options) }; } }); module.exports = componentSelect; });
#!/usr/bin/env node // Using optimist determine engine, test files, and command files var optimist = require('optimist'), argv = optimist ['default']('engine', 'vows') ['default']('dir', 'test') .boolean('no-hints') ['default']('no-hints', false) .argv; // Set up fallbacks for testFiles and commandFiles var engine = argv.engine, dir = argv.dir, testGlob = argv['test-files'] || dir + '/*.{test,tests}.{js,json}', commandGlob = argv['command-files'] || dir + '/*.' + engine + '.js'; // Expand test and command file paths via glob var glob = require('glob'), testFiles = glob.sync(testGlob), commandFiles = glob.sync(commandGlob); // Load in lib and create a new sculptor var Sculptor = require(__dirname + '/../lib/sculptor'), options = {'hints': !argv['no-hints']}, engineSculptor = new Sculptor(engine, options); // Register the test and command files testFiles.forEach(function (testFile) { var tests = require(process.cwd() + '/' + testFile); engineSculptor.addTests(tests); }); commandFiles.forEach(function (commandFile) { var commands = require(process.cwd() + '/' + commandFile); engineSculptor.addCommands(commands); }); // Export/run the tests engineSculptor['export'](module); // TODO: Export/run the tests -- this might be different depending on engines // TODO: We might want to start handling engines as done in consolidate.js
// --------- This code has been automatically generated !!! 2017-01-16T16:52:14.069Z "use strict"; require("requirish")._(module); /** * @module opcua.address_space.types */ var assert = require("better-assert"); var util = require("util"); var _ = require("underscore"); var makeNodeId = require("lib/datamodel/nodeid").makeNodeId; var schema_helpers = require("lib/misc/factories_schema_helpers"); var extract_all_fields = schema_helpers.extract_all_fields; var resolve_schema_field_types = schema_helpers.resolve_schema_field_types; var initialize_field = schema_helpers.initialize_field; var initialize_field_array = schema_helpers.initialize_field_array; var check_options_correctness_against_schema = schema_helpers.check_options_correctness_against_schema; var _defaultTypeMap = require("lib/misc/factories_builtin_types")._defaultTypeMap; var ec = require("lib/misc/encode_decode"); var encodeArray = ec.encodeArray; var decodeArray = ec.decodeArray; var makeExpandedNodeId = ec.makeExpandedNodeId; var generate_new_id = require("lib/misc/factories").generate_new_id; var _enumerations = require("lib/misc/factories_enumerations")._private._enumerations; var schema = require("../schemas/39394884f696ff0bf66bacc9a8032cc074e0158e/ServerDiagnosticsSummary_schema").ServerDiagnosticsSummary_Schema; var BaseUAObject = require("lib/misc/factories_baseobject").BaseUAObject; /** * * @class ServerDiagnosticsSummary * @constructor * @extends BaseUAObject * @param options {Object} * @param [options.serverViewCount] {UInt32} * @param [options.currentSessionCount] {UInt32} * @param [options.cumulatedSessionCount] {UInt32} * @param [options.securityRejectedSessionCount] {UInt32} * @param [options.rejectedSessionCount] {UInt32} * @param [options.sessionTimeoutCount] {UInt32} * @param [options.sessionAbortCount] {UInt32} * @param [options.currentSubscriptionCount] {UInt32} * @param [options.cumulatedSubscriptionCount] {UInt32} * @param [options.publishingIntervalCount] {UInt32} * @param [options.securityRejectedRequestsCount] {UInt32} * @param [options.rejectedRequestsCount] {UInt32} */ function ServerDiagnosticsSummary(options) { options = options || {}; /* istanbul ignore next */ if (schema_helpers.doDebug) { check_options_correctness_against_schema(this,schema,options); } var self = this; assert(this instanceof BaseUAObject); // ' keyword "new" is required for constructor call') resolve_schema_field_types(schema); BaseUAObject.call(this,options); /** * * @property serverViewCount * @type {UInt32} */ self.serverViewCount = initialize_field(schema.fields[0], options.serverViewCount); /** * * @property currentSessionCount * @type {UInt32} */ self.currentSessionCount = initialize_field(schema.fields[1], options.currentSessionCount); /** * * @property cumulatedSessionCount * @type {UInt32} */ self.cumulatedSessionCount = initialize_field(schema.fields[2], options.cumulatedSessionCount); /** * * @property securityRejectedSessionCount * @type {UInt32} */ self.securityRejectedSessionCount = initialize_field(schema.fields[3], options.securityRejectedSessionCount); /** * * @property rejectedSessionCount * @type {UInt32} */ self.rejectedSessionCount = initialize_field(schema.fields[4], options.rejectedSessionCount); /** * * @property sessionTimeoutCount * @type {UInt32} */ self.sessionTimeoutCount = initialize_field(schema.fields[5], options.sessionTimeoutCount); /** * * @property sessionAbortCount * @type {UInt32} */ self.sessionAbortCount = initialize_field(schema.fields[6], options.sessionAbortCount); /** * * @property currentSubscriptionCount * @type {UInt32} */ self.currentSubscriptionCount = initialize_field(schema.fields[7], options.currentSubscriptionCount); /** * * @property cumulatedSubscriptionCount * @type {UInt32} */ self.cumulatedSubscriptionCount = initialize_field(schema.fields[8], options.cumulatedSubscriptionCount); /** * * @property publishingIntervalCount * @type {UInt32} */ self.publishingIntervalCount = initialize_field(schema.fields[9], options.publishingIntervalCount); /** * * @property securityRejectedRequestsCount * @type {UInt32} */ self.securityRejectedRequestsCount = initialize_field(schema.fields[10], options.securityRejectedRequestsCount); /** * * @property rejectedRequestsCount * @type {UInt32} */ self.rejectedRequestsCount = initialize_field(schema.fields[11], options.rejectedRequestsCount); // Object.preventExtensions(self); } util.inherits(ServerDiagnosticsSummary,BaseUAObject); ServerDiagnosticsSummary.prototype.encodingDefaultBinary = makeExpandedNodeId(861,0); ServerDiagnosticsSummary.prototype._schema = schema; var encode_UInt32 = _defaultTypeMap.UInt32.encode; var decode_UInt32 = _defaultTypeMap.UInt32.decode; /** * encode the object into a binary stream * @method encode * * @param stream {BinaryStream} */ ServerDiagnosticsSummary.prototype.encode = function(stream,options) { // call base class implementation first BaseUAObject.prototype.encode.call(this,stream,options); encode_UInt32(this.serverViewCount,stream); encode_UInt32(this.currentSessionCount,stream); encode_UInt32(this.cumulatedSessionCount,stream); encode_UInt32(this.securityRejectedSessionCount,stream); encode_UInt32(this.rejectedSessionCount,stream); encode_UInt32(this.sessionTimeoutCount,stream); encode_UInt32(this.sessionAbortCount,stream); encode_UInt32(this.currentSubscriptionCount,stream); encode_UInt32(this.cumulatedSubscriptionCount,stream); encode_UInt32(this.publishingIntervalCount,stream); encode_UInt32(this.securityRejectedRequestsCount,stream); encode_UInt32(this.rejectedRequestsCount,stream); }; /** * decode the object from a binary stream * @method decode * * @param stream {BinaryStream} * @param [option] {object} */ ServerDiagnosticsSummary.prototype.decode = function(stream,options) { // call base class implementation first BaseUAObject.prototype.decode.call(this,stream,options); this.serverViewCount = decode_UInt32(stream,options); this.currentSessionCount = decode_UInt32(stream,options); this.cumulatedSessionCount = decode_UInt32(stream,options); this.securityRejectedSessionCount = decode_UInt32(stream,options); this.rejectedSessionCount = decode_UInt32(stream,options); this.sessionTimeoutCount = decode_UInt32(stream,options); this.sessionAbortCount = decode_UInt32(stream,options); this.currentSubscriptionCount = decode_UInt32(stream,options); this.cumulatedSubscriptionCount = decode_UInt32(stream,options); this.publishingIntervalCount = decode_UInt32(stream,options); this.securityRejectedRequestsCount = decode_UInt32(stream,options); this.rejectedRequestsCount = decode_UInt32(stream,options); }; ServerDiagnosticsSummary.possibleFields = [ "serverViewCount", "currentSessionCount", "cumulatedSessionCount", "securityRejectedSessionCount", "rejectedSessionCount", "sessionTimeoutCount", "sessionAbortCount", "currentSubscriptionCount", "cumulatedSubscriptionCount", "publishingIntervalCount", "securityRejectedRequestsCount", "rejectedRequestsCount" ]; exports.ServerDiagnosticsSummary = ServerDiagnosticsSummary; var register_class_definition = require("lib/misc/factories_factories").register_class_definition; register_class_definition("ServerDiagnosticsSummary",ServerDiagnosticsSummary);
import React, { Component } from 'react' import PropTypes from 'prop-types' import { getSelectValue } from './utils' class ValueGroup extends Component { render() { const { clearInputOnSelect, getLabel, inputValue, isFocused, labelKey, options, placeholder, showInput, showValuesWhileFocused, value, valueComponent, valueKey, valueGroupRenderer, valueRenderer } = this.props const defaultRenderer = () => { const option = getSelectValue({ value, valueKey, options }) const ValueComponent = valueComponent return ( <ValueComponent getLabel={getLabel} labelKey={labelKey} option={option} value={value} valueKey={valueKey} valueRenderer={valueRenderer} /> ) } const ValueRenderer = valueGroupRenderer || defaultRenderer if (showInput && inputValue && !showValuesWhileFocused) { return null } const { valueGroupRenderer: _valueGroupRenderer, placeholder: _placeholder, ...rendererProps } = this.props // Don't include group headers or select all in the count let newValue = value if (Array.isArray(newValue)) { newValue = value.filter((val) => !val.options) rendererProps.value = newValue } const showValue = Array.isArray(newValue) ? newValue.length : newValue const renderer = (clearInputOnSelect && showValue) || (showValuesWhileFocused && isFocused) ? ( <ValueRenderer {...rendererProps} /> ) : ( <span className="crane-select-placeholder">{placeholder}</span> ) return showValuesWhileFocused ? ( renderer ) : ( <div className="crane-select-value-group">{renderer}</div> ) } } ValueGroup.propTypes = { clearInputOnSelect: PropTypes.bool, getLabel: PropTypes.func.isRequired, inputValue: PropTypes.string, isFocused: PropTypes.bool.isRequired, labelKey: PropTypes.string, options: PropTypes.array.isRequired, onMouseDown: PropTypes.func, placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object]), showInput: PropTypes.bool, showValuesWhileFocused: PropTypes.bool, value: PropTypes.oneOfType([ PropTypes.array, PropTypes.number, PropTypes.object, PropTypes.string ]), valueComponent: PropTypes.func, valueKey: PropTypes.string.isRequired, valueGroupRenderer: PropTypes.func, valueRenderer: PropTypes.func } ValueGroup.defaultProps = { clearInputOnSelect: true, inputValue: '', labelKey: '', onMouseDown: null, placeholder: '', showInput: false, showValuesWhileFocused: false, value: null, valueComponent: null, valueGroupRenderer: null, valueRenderer: null } export default ValueGroup
import hammerhead from './deps/hammerhead'; import testCafeCore from './deps/testcafe-core'; import testCafeUI from './deps/testcafe-ui'; import cursor from './cursor'; var browserUtils = hammerhead.utils.browser; var Promise = hammerhead.Promise; var nativeMethods = hammerhead.nativeMethods; var positionUtils = testCafeCore.positionUtils; var domUtils = testCafeCore.domUtils; function getElementFromPoint (x, y, underTopShadowUIElement) { var topElement = null; return testCafeUI.hide(underTopShadowUIElement) .then(() => { topElement = positionUtils.getElementFromPoint(x, y); return testCafeUI.show(underTopShadowUIElement); }) .then(() => topElement); } function ensureImageMap (imgElement, areaElement) { var mapElement = domUtils.closest(areaElement, 'map'); return mapElement && mapElement.name === imgElement.useMap.substring(1) ? areaElement : imgElement; } function findElementOrNonEmptyChildFromPoint (x, y, element) { var topElement = positionUtils.getElementFromPoint(x, y); var isNonEmptyChild = domUtils.containsElement(element, topElement) && nativeMethods.nodeTextContentGetter.call(topElement).length; if (topElement && topElement === element || isNonEmptyChild) return topElement; return null; } function correctTopElementByExpectedElement (topElement, expectedElement) { var expectedElementDefined = expectedElement && domUtils.isDomElement(expectedElement); if (!expectedElementDefined || !topElement || topElement === expectedElement) return topElement; var isTREFElement = domUtils.getTagName(expectedElement) === 'tref'; // NOTE: 'document.elementFromPoint' can't find these types of elements if (isTREFElement) return expectedElement; // NOTE: T299665 - Incorrect click automation for images with an associated map element in Firefox // All browsers return the <area> element from document.getElementFromPoint, but // Firefox returns the <img> element. We should accomplish this for Firefox as well. var isImageMapArea = domUtils.getTagName(expectedElement) === 'area' && domUtils.isImgElement(topElement); if (browserUtils.isFirefox && isImageMapArea) return ensureImageMap(topElement, expectedElement); // NOTE: try to find a multi-line link by its rectangle (T163678) var isLinkOrChildExpected = domUtils.isAnchorElement(expectedElement) || domUtils.getParents(expectedElement, 'a').length; var isTopElementChildOfLink = isLinkOrChildExpected && domUtils.containsElement(expectedElement, topElement) && nativeMethods.nodeTextContentGetter.call(topElement).length; var shouldSearchForMultilineLink = isLinkOrChildExpected && !isTopElementChildOfLink && nativeMethods.nodeTextContentGetter.call(expectedElement).length; if (!shouldSearchForMultilineLink) return topElement; var linkRect = expectedElement.getBoundingClientRect(); return findElementOrNonEmptyChildFromPoint(linkRect.right - 1, linkRect.top + 1, expectedElement) || findElementOrNonEmptyChildFromPoint(linkRect.left + 1, linkRect.bottom - 1, expectedElement) || topElement; } export function fromPoint (x, y, expectedElement) { var isInIframe = window !== window.top; var foundElement = null; return getElementFromPoint(x, y) .then(topElement => { foundElement = topElement; // NOTE: when trying to get an element by elementFromPoint in iframe and the target // element is under any of shadow-ui elements, you will get null (only in IE). // In this case, you should hide a top window's shadow-ui root to obtain an element. var resChain = Promise.resolve(topElement); if (!foundElement && isInIframe && x > 0 && y > 0) { resChain = resChain .then(() => getElementFromPoint(x, y, true)) .then(element => { foundElement = element; return element; }); } return resChain .then(element => correctTopElementByExpectedElement(element, expectedElement)) .then(correctedElement => { return { element: correctedElement, corrected: correctedElement !== foundElement }; }); }); } export function underCursor () { var cursorPosition = cursor.position; return fromPoint(cursorPosition.x, cursorPosition.y).then(({ element }) => element); }
var ObjectID = require('mongodb').ObjectID; var DBRef = require('mongodb').DBRef; var EventProxy = require('eventproxy'); var EventEmitter = require('events').EventEmitter; var us = require('underscore'); var fs = require('fs'); var path = require('path'); var db = require('./db'); var ERR = require('../errorcode'); var U = require('../util'); var config = require('../config'); exports.create = function(params, callback){ var doc = { path: params.path, md5: params.md5, size: Number(params.size), type: Number(params.type) || 0, mimes: params.mimes, ref: 0, createTime: Date.now(), updateTime: Date.now() }; db.resource.insert(doc, function(err, result){ callback(err, doc); }); }; exports.delete = function(query, callback){ db.resource.findAndRemove(query, [], callback); }; exports.getResource = function(query, callback){ db.resource.findOne(query, callback); }; exports.updateRef = function(resId, value, callback){ db.resource.findAndModify({ _id: resId }, [], { $inc: { ref: value } }, { 'new': true }, function(err, doc){ if(doc && doc.ref <= 0){ // 引用为0了, 删除文件 console.log('>>>resource ref=0, delete it: ' + doc._id); // 还要删除具体文件 // 还要生成的 PDF 和 SWF 没有删除 var filename = path.join(config.FILE_SAVE_ROOT, config.FILE_SAVE_DIR, doc.path); if(fs.existsSync(filename)){ fs.unlinkSync(filename); console.log('>>>unlink ' + filename); } if(fs.existsSync(filename + '.pdf')){ fs.unlinkSync(filename + '.pdf'); console.log('>>>unlink ' + filename + '.pdf'); } if(fs.existsSync(filename + '.swf')){ fs.unlinkSync(filename + '.swf'); console.log('>>>unlink ' + filename + '.swf'); } db.resource.findAndRemove({ _id: doc._id }, [], callback); }else{ callback(err, doc); } }); };
; $(function() { "use strict"; $('#section-link').on('singletap', function() { //all parameters except *url* are optional axemas.goto({'url':'www/section.html', 'title':'Section' /* 'stackMaintainedElements': 1000, */ /* 'stackPopElements':0, */ /* 'toggleSidebarIcon': 'slide_icon' */ }); }); $('#js-call-native-link').on('singletap', function() { axemas.call('open-sidebar-from-native', {}, function (data) { axemas.dialog("FATTO, Risposta: " + JSON.stringify(data)); }); }); $('#native-call-js-link').on('singletap', function() { axemas.call('send-device-name-from-native-to-js'); }); $('#native-section-link').on('singletap', function() { axemas.call('push-native-section'); }); $('#scroll-top-link').on('singletap', function() { $('html, body').animate({scrollTop : 0},800); }); // Registered method to be called from Native axemas.register("display-device-model", function(payload, cb){ axemas.dialog('Native response', "Some information on the device:\n- " + payload.name + "\n- " + payload.other, ['Close']); cb({ message: "message from JS in callback!" }); }); });
/*globals jscolor, i18nDefaultQuery */ import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; const TempSettings = new Mongo.Collection(null); RocketChat.TempSettings = TempSettings; const getDefaultSetting = function(settingId) { return RocketChat.settings.collectionPrivate.findOne({ _id: settingId }); }; const setFieldValue = function(settingId, value, type, editor) { const input = $('.page-settings').find(`[name="${ settingId }"]`); switch (type) { case 'boolean': $('.page-settings').find(`[name="${ settingId }"][value="${ Number(value) }"]`).prop('checked', true).change(); break; case 'code': input.next()[0].CodeMirror.setValue(value); break; case 'color': editor = value && value[0] === '#' ? 'color' : 'expression'; input.parents('.horizontal').find('select[name="color-editor"]').val(editor).change(); input.val(value).change(); break; case 'roomPick': const selectedRooms = Template.instance().selectedRooms.get(); selectedRooms[settingId] = value; Template.instance().selectedRooms.set(selectedRooms); TempSettings.update({ _id: settingId }, { $set: { value, changed: JSON.stringify(RocketChat.settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value) } }); break; default: input.val(value).change(); } }; Template.admin.onCreated(function() { if (RocketChat.settings.cachedCollectionPrivate == null) { RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ name: 'private-settings', eventType: 'onLogged', useCache: false }); RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection; RocketChat.settings.cachedCollectionPrivate.init(); } this.selectedRooms = new ReactiveVar({}); RocketChat.settings.collectionPrivate.find().observe({ added: (data) => { const selectedRooms = this.selectedRooms.get(); if (data.type === 'roomPick') { selectedRooms[data._id] = data.value; this.selectedRooms.set(selectedRooms); } TempSettings.insert(data); }, changed: (data) => { const selectedRooms = this.selectedRooms.get(); if (data.type === 'roomPick') { selectedRooms[data._id] = data.value; this.selectedRooms.set(selectedRooms); } TempSettings.update(data._id, data); }, removed: (data) => { const selectedRooms = this.selectedRooms.get(); if (data.type === 'roomPick') { delete selectedRooms[data._id]; this.selectedRooms.set(selectedRooms); } TempSettings.remove(data._id); } }); }); Template.admin.onDestroyed(function() { TempSettings.remove({}); }); Template.admin.helpers({ languages() { const languages = TAPi18n.getLanguages(); const result = Object.entries(languages) .map(([ key, language ]) => ({ ...language, key: key.toLowerCase() })) .sort((a, b) => a.key - b.key); result.unshift({ 'name': 'Default', 'en': 'Default', 'key': '' }); return result; }, isAppLanguage(key) { const languageKey = RocketChat.settings.get('Language'); return typeof languageKey === 'string' && languageKey.toLowerCase() === key; }, group() { const groupId = FlowRouter.getParam('group'); const group = RocketChat.settings.collectionPrivate.findOne({ _id: groupId, type: 'group' }); if (!group) { return; } const settings = RocketChat.settings.collectionPrivate.find({ group: groupId }, { sort: { section: 1, sorter: 1, i18nLabel: 1 }}).fetch(); const sections = {}; Object.keys(settings).forEach(key => { const setting = settings[key]; if (setting.i18nDefaultQuery != null) { if (_.isString(setting.i18nDefaultQuery)) { i18nDefaultQuery = JSON.parse(setting.i18nDefaultQuery); } else { i18nDefaultQuery = setting.i18nDefaultQuery; } if (!_.isArray(i18nDefaultQuery)) { i18nDefaultQuery = [i18nDefaultQuery]; } Object.keys(i18nDefaultQuery).forEach(key => { const item = i18nDefaultQuery[key]; if (RocketChat.settings.collectionPrivate.findOne(item) != null) { setting.value = TAPi18n.__(`${ setting._id }_Default`); } }); } const settingSection = setting.section || ''; if (sections[settingSection] == null) { sections[settingSection] = []; } sections[settingSection].push(setting); }); group.sections = Object.keys(sections).map(key =>{ const value = sections[key]; return { section: key, settings: value }; }); return group; }, i18nDefaultValue() { return TAPi18n.__(`${ this._id }_Default`); }, isDisabled() { let enableQuery; if (this.blocked) { return { disabled: 'disabled' }; } if (this.enableQuery == null) { return {}; } if (_.isString(this.enableQuery)) { enableQuery = JSON.parse(this.enableQuery); } else { enableQuery = this.enableQuery; } if (!_.isArray(enableQuery)) { enableQuery = [enableQuery]; } let found = 0; Object.keys(enableQuery).forEach(key =>{ const item = enableQuery[key]; if (TempSettings.findOne(item) != null) { found++; } }); if (found === enableQuery.length) { return {}; } else { return { disabled: 'disabled' }; } }, isReadonly() { if (this.readonly === true) { return { readonly: 'readonly' }; } }, canAutocomplete() { if (this.autocomplete === false) { return { autocomplete: 'off' }; } }, hasChanges(section) { const group = FlowRouter.getParam('group'); const query = { group, changed: true }; if (section != null) { if (section === '') { query.$or = [ { section: '' }, { section: { $exists: false } } ]; } else { query.section = section; } } return TempSettings.find(query).count() > 0; }, isSettingChanged(id) { return TempSettings.findOne({ _id: id }, { fields: { changed: 1 } }).changed; }, translateSection(section) { if (section.indexOf(':') > -1) { return section; } return t(section); }, label() { const label = this.i18nLabel || this._id; if (label) { return TAPi18n.__(label); } }, description() { let description; if (this.i18nDescription) { description = TAPi18n.__(this.i18nDescription); } if ((description != null) && description !== this.i18nDescription) { return description; } }, sectionIsCustomOAuth(section) { return /^Custom OAuth:\s.+/.test(section); }, callbackURL(section) { const id = s.strRight(section, 'Custom OAuth: ').toLowerCase(); return Meteor.absoluteUrl(`_oauth/${ id }`); }, relativeUrl(url) { return Meteor.absoluteUrl(url); }, selectedOption(_id, val) { const option = RocketChat.settings.collectionPrivate.findOne({ _id }); return option && option.value === val; }, random() { return Random.id(); }, getEditorOptions(readOnly = false) { return { lineNumbers: true, mode: this.code || 'javascript', gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'], foldGutter: true, matchBrackets: true, autoCloseBrackets: true, matchTags: true, showTrailingSpace: true, highlightSelectionMatches: true, readOnly }; }, setEditorOnBlur(_id) { Meteor.defer(function() { if (!$(`.code-mirror-box[data-editor-id="${ _id }"] .CodeMirror`)[0]) { return; } const codeMirror = $(`.code-mirror-box[data-editor-id="${ _id }"] .CodeMirror`)[0].CodeMirror; if (codeMirror.changeAdded === true) { return; } const onChange = function() { const value = codeMirror.getValue(); TempSettings.update({ _id }, { $set: { value, changed: RocketChat.settings.collectionPrivate.findOne(_id).value !== value }}); }; const onChangeDelayed = _.debounce(onChange, 500); codeMirror.on('change', onChangeDelayed); codeMirror.changeAdded = true; }); }, assetAccept(fileConstraints) { if (fileConstraints.extensions && fileConstraints.extensions.length) { return `.${ fileConstraints.extensions.join(', .') }`; } }, autocompleteRoom() { return { limit: 10, //inputDelay: 300 rules: [ { //@TODO maybe change this 'collection' and/or template collection: 'CachedChannelList', subscription: 'channelAndPrivateAutocomplete', field: 'name', template: Template.roomSearch, noMatchTemplate: Template.roomSearchEmpty, matchAll: true, selector(match) { return { name: match }; }, sort: 'name' } ] }; }, selectedRooms() { return Template.instance().selectedRooms.get()[this._id] || []; }, getColorVariable(color) { return color.replace(/theme-color-/, '@'); }, showResetButton() { const setting = TempSettings.findOne({ _id: this._id }, { fields: { value: 1, packageValue: 1 }}); return this.type !== 'asset' && setting.value !== setting.packageValue && !this.blocked; } }); Template.admin.events({ 'change .input-monitor, keyup .input-monitor': _.throttle(function(e) { let value = s.trim($(e.target).val()); switch (this.type) { case 'int': value = parseInt(value); break; case 'boolean': value = value === '1'; break; case 'color': $(e.target).siblings('.colorpicker-swatch').css('background-color', value); } TempSettings.update({ _id: this._id }, { $set: { value, changed: RocketChat.settings.collectionPrivate.findOne(this._id).value !== value } }); }, 500), 'change select[name=color-editor]'(e) { const value = s.trim($(e.target).val()); TempSettings.update({ _id: this._id }, { $set: { editor: value }}); RocketChat.settings.collectionPrivate.update({ _id: this._id }, { $set: { editor: value }}); }, 'click .rc-header__section-button .discard'() { const group = FlowRouter.getParam('group'); const query = { group, changed: true }; const settings = TempSettings.find(query, { fields: { _id: 1, value: 1, packageValue: 1 }}).fetch(); settings.forEach(function(setting) { const oldSetting = RocketChat.settings.collectionPrivate.findOne({ _id: setting._id }, { fields: { value: 1, type: 1, editor: 1 }}); setFieldValue(setting._id, oldSetting.value, oldSetting.type, oldSetting.editor); }); }, 'click .reset-setting'(e) { e.preventDefault(); let settingId = $(e.target).data('setting'); if (typeof settingId === 'undefined') { settingId = $(e.target).parent().data('setting'); } const defaultValue = getDefaultSetting(settingId); setFieldValue(settingId, defaultValue.packageValue, defaultValue.type, defaultValue.editor); }, 'click .reset-group'(e) { let settings; e.preventDefault(); const group = FlowRouter.getParam('group'); const section = $(e.target).data('section'); if (section === '') { settings = TempSettings.find({ group, section: { $exists: false }}, { fields: { _id: 1 }}).fetch(); } else { settings = TempSettings.find({ group, section }, { fields: { _id: 1 }}).fetch(); } settings.forEach(function(setting) { const defaultValue = getDefaultSetting(setting._id); setFieldValue(setting._id, defaultValue.packageValue, defaultValue.type, defaultValue.editor); TempSettings.update({_id: setting._id }, { $set: { value: defaultValue.packageValue, changed: RocketChat.settings.collectionPrivate.findOne(setting._id).value !== defaultValue.packageValue } }); }); }, 'click .rc-header__section-button .save'() { const group = FlowRouter.getParam('group'); const query = { group, changed: true }; const settings = TempSettings.find(query, { fields: { _id: 1, value: 1, editor: 1 }}).fetch(); if (!_.isEmpty(settings)) { RocketChat.settings.batchSet(settings, function(err) { if (err) { return handleError(err); } TempSettings.update({ changed: true }, { $unset: { changed: 1 }}); toastr.success(TAPi18n.__('Settings_updated')); }); } }, 'click .rc-header__section-button .refresh-clients'() { Meteor.call('refreshClients', function() { toastr.success(TAPi18n.__('Clients_will_refresh_in_a_few_seconds')); }); }, 'click .rc-header__section-button .add-custom-oauth'() { const config = { title: TAPi18n.__('Add_custom_oauth'), text: TAPi18n.__('Give_a_unique_name_for_the_custom_oauth'), type: 'input', showCancelButton: true, closeOnConfirm: true, inputPlaceholder: TAPi18n.__('Custom_oauth_unique_name') }; modal.open(config, function(inputValue) { if (inputValue === false) { return false; } if (inputValue === '') { modal.showInputError(TAPi18n.__('Name_cant_be_empty')); return false; } Meteor.call('addOAuthService', inputValue, function(err) { if (err) { handleError(err); } }); }); }, 'click .rc-header__section-button .refresh-oauth'() { toastr.info(TAPi18n.__('Refreshing')); return Meteor.call('refreshOAuthService', function(err) { if (err) { return handleError(err); } else { return toastr.success(TAPi18n.__('Done')); } }); }, 'click .rc-header__section-button .remove-custom-oauth'() { const name = this.section.replace('Custom OAuth: ', ''); const config = { title: TAPi18n.__('Are_you_sure'), type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: TAPi18n.__('Yes_delete_it'), cancelButtonText: TAPi18n.__('Cancel'), closeOnConfirm: true }; modal.open(config, function() { Meteor.call('removeOAuthService', name); }); }, 'click .delete-asset'() { Meteor.call('unsetAsset', this.asset); }, 'change input[type=file]'(ev) { const e = ev.originalEvent || ev; let files = e.target.files; if (!files || files.length === 0) { if (e.dataTransfer && e.dataTransfer.files) { files = e.dataTransfer.files; } else { files = []; } } Object.keys(files).forEach(key => { const blob = files[key]; toastr.info(TAPi18n.__('Uploading_file')); const reader = new FileReader(); reader.readAsBinaryString(blob); reader.onloadend = () => { return Meteor.call('setAsset', reader.result, blob.type, this.asset, function(err) { if (err != null) { handleError(err); console.log(err); return; } return toastr.success(TAPi18n.__('File_uploaded')); }); }; }); }, 'click .expand'(e) { $(e.currentTarget).closest('.section').removeClass('section-collapsed'); $(e.currentTarget).closest('button').removeClass('expand').addClass('collapse').find('span').text(TAPi18n.__('Collapse')); $('.CodeMirror').each(function(index, codeMirror) { codeMirror.CodeMirror.refresh(); }); }, 'click .collapse'(e) { $(e.currentTarget).closest('.section').addClass('section-collapsed'); $(e.currentTarget).closest('button').addClass('expand').removeClass('collapse').find('span').text(TAPi18n.__('Expand')); }, 'click button.action'() { if (this.type !== 'action') { return; } Meteor.call(this.value, function(err, data) { if (err != null) { err.details = _.extend(err.details || {}, { errorTitle: 'Error' }); handleError(err); return; } const args = [data.message].concat(data.params); toastr.success(TAPi18n.__.apply(TAPi18n, args), TAPi18n.__('Success')); }); }, 'click .button-fullscreen'() { const codeMirrorBox = $(`.code-mirror-box[data-editor-id="${ this._id }"]`); codeMirrorBox.addClass('code-mirror-box-fullscreen content-background-color'); codeMirrorBox.find('.CodeMirror')[0].CodeMirror.refresh(); }, 'click .button-restore'() { const codeMirrorBox = $(`.code-mirror-box[data-editor-id="${ this._id }"]`); codeMirrorBox.removeClass('code-mirror-box-fullscreen content-background-color'); codeMirrorBox.find('.CodeMirror')[0].CodeMirror.refresh(); }, 'autocompleteselect .autocomplete'(event, instance, doc) { const selectedRooms = instance.selectedRooms.get(); selectedRooms[this.id] = (selectedRooms[this.id] || []).concat(doc); instance.selectedRooms.set(selectedRooms); const value = selectedRooms[this.id]; TempSettings.update({ _id: this.id }, { $set: { value }}); event.currentTarget.value = ''; event.currentTarget.focus(); }, 'click .remove-room'(event, instance) { const docId = this._id; const settingId = event.currentTarget.getAttribute('data-setting'); const selectedRooms = instance.selectedRooms.get(); selectedRooms[settingId] = _.reject(selectedRooms[settingId] || [], function(setting) { return setting._id === docId; }); instance.selectedRooms.set(selectedRooms); const value = selectedRooms[settingId]; TempSettings.update({ _id: settingId }, { $set: { value } }); } }); Template.admin.onRendered(function() { Tracker.afterFlush(function() { SideNav.setFlex('adminFlex'); SideNav.openFlex(); }); Tracker.autorun(function() { const hasColor = TempSettings.find({ group: FlowRouter.getParam('group'), type: 'color' }, { fields: { _id: 1, editor: 1 }}).fetch().length; if (hasColor) { Meteor.setTimeout(function() { $('.colorpicker-input').each(function(index, el) { if (!el._jscLinkedInstance) { new jscolor(el); //eslint-disable-line } }); }, 400); } }); });
import { PropTypes } from 'react'; import { control } from 'leaflet'; import MapControl from './MapControl'; export default class ZoomControl extends MapControl { static propTypes = { imperial: PropTypes.bool, maxWidth: PropTypes.number, metric: PropTypes.bool, updateWhenIdle: PropTypes.bool, }; componentWillMount() { this.leafletElement = control.scale(this.props); } }
'use strict' const path = require('path') const ExtractTextPlugin = require('extract-text-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const webpack = require('webpack') const autoprefixer = require('autoprefixer') let isDev = process.env.NODE_ENV === 'development' //设置css modules的模块名更可读,由于我们使用了sass,所以只需要模块话根类名就行了。如果设置了modules参数会默认全局使用模块化类名,没有设置则可以通过:local(className){} 手动指定 const baseCssLoader = 'css?souceMap&modules&importLoaders=1&localIdentName=[local]__[hash:base64:5]!postcss-loader!sass-loader?souceMap' let cssLoader = ExtractTextPlugin.extract('style', baseCssLoader) let debug = false let devtool = '#source-map' let appEntry = './src/pref/app.jsx' let buildPlugins = [ //生成html上的模块的hash值,但是只包括当前打包的模块,不支持dll文件,不过由于它默认支持ejs模版,因此我们可以通过模版实现。 new HtmlWebpackPlugin({ baseDir: 'app/browser/pref', filename: '../index.html', template: 'src/pref/index.ejs', hash: true, excludeChunks: [] }), ] let devPlugins = [] let plugins = buildPlugins if (isDev) { debug = true devtool = '#inline-source-map' cssLoader = 'style!' + baseCssLoader plugins = devPlugins appEntry = [ 'react-hot-loader/patch', ].concat([appEntry]) } const baseDir = './app/browser/pref' module.exports = { // 需要打包的文件配置 entry: { app: appEntry, //通过key value的形式配置了需要打包的文件, }, debug: debug, devtool: devtool, // 输出文件配置 output: { path: `${baseDir}/dist`, // 输出的目录,我们是配置为当前目录下的dist目录 publicPath: 'dist/', // 发布后的服务器或cdn上的路径, 配置这个后webpack-dev-server会自动将html中引用的部署路径自动路由到本地的开发路径上 filename: '[name].bundle.js', // 输出的文件名,[name]就是entry的key }, // 模块加载器 module: { loaders: [ // 加载器数组 { test: /\.(png|jpg|jpeg|gif|ttf|eot|woff|woff2|svg)(?:\?.*?){0,1}$/, // 用来匹配文件的正则 // 加载器的名称,此处为url-loader,`?`后面可以添加loader的参数, // 具体得参考loader的github主页。 loader: 'url?limit=10000&name=files/[name].[ext]?[hash]', }, { test: /\.(css|scss)$/, // 使用ExtractTextPlugin,将样式抽出到单独的文件中, // webpack默认是构建html的style标签; 多个loader可以通过!连接起来, // 相当于管道一样,最后面的loader先传入文件,然后再传出给前面的loader loader: cssLoader, }, { test: /\.json$/, loader: 'json', }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel', // loader也可以使用使用数组进行配置, loaders:['babel','...'] // 参数可以用querystring: 'babel?presets[]=es2015&presets[]=react' // 或query字段: loader: 'babel', query: {presets: ['es2015', 'react']} // 或参数传json: // 'babel?{presets:["es2015", "react"]}' }, { test: /\.jsx$/, exclude: /(node_modules|bower_components)/, loaders: ["babel"] }, ], }, "babel": { "presets": [ "electron", // uglifyjs can't handle es6 syntx // "es2015", // "stage-0", "react" ], "plugins": [ "transform-runtime", "transform-flow-strip-types", "transform-decorators-legacy", // "transform-class-properties" ] }, // postcss-loader 的配置,这里我们主要是使用autoprefixer postcss: [autoprefixer({ browsers: ['last 2 version', 'Explorer >= 9'] })], resolve: { extensions: ['', '.jsx', '.js'] }, externals: [{ }], // webpack 插件配置 plugins: [ // 抽取样式到单独的 文件中,文件名称则为[name].css new ExtractTextPlugin('[name].bundle.css'), // 定义变量,这些变量会在build的时候执行,可以给不同的命令传入不同的env, // 这样就能实现服务端与本地的配置不同了。 new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'), // 直接替换,所以需要 JSON.stringify 加上引号 }, }), // 将文件打包为后通过manifest.json在require时判断是否包含,这样比起common trunk plugin // 就彻底不需要每次编译分析第三方库了,节省了编译时间 new webpack.DllReferencePlugin({ context: __dirname, manifest: require(`${baseDir}/dist/dll/vendor-manifest.json`) }), ].concat(plugins), target: 'electron-renderer', // webpack-dev-server配置 // http://webpack.github.io/docs/webpack-dev-server.html#api devServer: { contentBase: baseDir, //serve 的html的路径 hot: true, inline: true }, }
angular.module('app', ['ngRoute', 'templates']) .config(function ($routeProvider, $locationProvider) { $routeProvider.when('/', { templateUrl: 'home.html', controller: 'HomeCtrl' }); $locationProvider.html5Mode(true); }) .config(function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element(document.querySelector('meta[name=csrf-token]')).attr('content'); });
'use strict'; // rem :: Number -> Number -> Number ! module.exports = function rem(x) { return function(y) { if (y === 0) { throw new Error('Cannot divide by zero'); } else { return x % y; } }; };
#!/usr/bin/env node /** * wordpos.js * * * Usage: * wordpos -p <noun|verb|adj|adv|all> <get|is|lookup> <stdin|words*> * * Copyright (c) 2012 mooster@42at.com * https://github.com/moos/wordpos * * Released under MIT license */ var program = require('commander'), _ = require('underscore')._, pos = 'noun verb adj adv all'.split(' '); program .version('0.1.0') .usage('[options] <command> word ...') // .option('-p, --pos <pos>', 'Get specific POS [noun|verb|adj|adv]', function(val){ // val = String(val).toLowerCase(); // return _.include(pos, val) && val; // }, 'all') .option('-a, --adj', 'Get adjectives') .option('-r, --adv', 'Get adverbs') .option('-n, --noun', 'Get nouns') .option('-v, --verb', 'Get verbs') .option('-b, --brief', 'brief (un-vebose)') .option('-c, --column', 'column output') .option('-F, --full', 'full definition object') .option('-j, --json', 'full definition as JSON') .option('-f, --file', 'input file') //.parse(process.argv); program.command('get') .description('get pos from -f <file> or <stdin>') .action(exec); 00 && program.command('is') .description('is word a particular pos') .action(exec); program.command('lookup') .description('lookup word') .action(exec); program.command('*') .action(function(){ return console.log(program.helpInformation()); }); var WordPos = require('../src/wordpos'), fs = require('fs'), util = require('util'), results = {}, cmd; program.parse(process.argv); function exec(){ var args = _.initial(arguments); cmd = _.last(arguments).name; // console.log('executing %s', cmd, args) if (program.file) { fs.readFile(program.file, 'utf8', function(err, data){ if (err) return console.log(err); run(data); }); } else if (args.length){ run(args.join(' ')); } else { read_stdin(run); } } function read_stdin(callback) { var data = ''; process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { //process.stdout.write('data: ' + chunk); var c = chunk.charCodeAt(0); if (c == 4 || c == 26) // ^c ^d return process.stdin.emit('end') && process.stdin.pause(); data += chunk; }); process.stdin.on('end', function () { callback(data); }); } function optToFn() { var cmds = {noun:'Noun', verb:'Verb', adj:'Adjective', adv:'Adverb'}, fns = _.reject(cmds, function(fn, opt) { return !program[opt] }); if (!fns.length) fns = _.values(cmds); //default to all return fns; } function run(data) { var wordpos = new WordPos(), // fns = program.pos == 'all' ? cmds : [cmds[program.pos]], fns = optToFn(), plural = (cmd=='get' ? 's':''), collect = _.after(data.length, _.bind(output,null,fn)), results = {}; data = wordpos.parse(data); _(fns).each(function(fn){ var method = cmd + fn + plural; // console.log(fn, plural, method, fns); if (cmd=='get') { wordpos[method](data, _.bind(output,null,fn)); } else { data.forEach(function(word){ wordpos[method](word, function(result){ if (result && cmd != 'lookup' || result.length) { results[word] = result; } collect(results); }); }); } }); } function output(what, results) { // console.log(what, cmd , results); // return var sep = program.column ? '\n' : ' ', str = !program.brief ? util.format('# %s %d:\n', what, _(results).size()) : ''; // console.log(str + (results.length && results.join(sep) || results) + '\n'); console.log(str + print(results) + '\n'); } function print(results) { var sep = program.column ? '\n' : ' '; switch (cmd) { case 'is': return _.keys(results).join(sep); // return _.reduce(results, function(memo, v, k){ // return memo + k +" "+ v +"\n"; // }, ''); case 'lookup': if (program.json) { return util.format('%j',results); } else if (program.full) { return util.inspect(results,false,10); return JSON.stringify(results); } return _.reduce(results, function(memo, v, k){ return (v.length && (memo + k +"\n"+ print_def(v) +"\n") ) || ''; }, ''); case 'get': return results.join(sep); } function print_def(defs) { if (program.full) { return JSON.stringify(defs); } else { return _.reduce(defs, function(memo, v, k){ return memo + util.format(' %s: %s\n', v.pos, v.gloss); },''); } } }
'use strict'; /* jasmine specs for controllers go here */ describe('PhoneCat controllers', function() { describe('PhoneListCtrl', function(){ var scope, ctrl; beforeEach(module('phonecatApp')); beforeEach(inject(function($controller) { scope = {}; ctrl = $controller('PhoneListCtrl', {$scope:scope}); })); it('should set the default value of orderProp model', function() { expect(scope.orderProp).toBe('age'); }); }); });
var smtApp = angular.module('smtApp', ['ui.bootstrap', 'ui.calendar', 'angularMoment','angular-timeline','chart.js','ngAnimate','ui.router']); smtApp.controller('MainController', ['$scope', '$log', function ($scope, $log) { $scope.test = "smtApp" }])
var React = require('react'); var Agenda = require('../global/agenda.js'); var SbspOverview = React.createClass({ render: function(){ return ( <div className=""> <div className="main-padding margin-30"> <div className="component-title-box"> <h5 className="center-align"> Tasks Overview </h5> </div> <div className="row"> <table className=" tasks-table bordered responsive-table"> <thead> <tr> <th data-field="id">Description</th> <th data-field="name">Time</th> <th data-field="price">Priority</th> <th data-field="price">Status</th> </tr> </thead> <tbody> <tr> <td>Completion SW Build</td> <td>5 days</td> <td>Medium</td> <td>In Progress</td> </tr> <tr> <td>Build in East London</td> <td>3 days</td> <td>Low</td> <td>Pending</td> </tr> <tr> <td>Site visit for new project</td> <td>1 days</td> <td>Low</td> <td>Completed</td> </tr> </tbody> </table> </div> <div className="component-title-box"> <h5 className="center-align"> Files Uploaded </h5> </div> <div className="row"> <div className="col s12 l4"> <ul className="collection with-header"> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> </ul> </div> <div className="col s12 l4"> <ul className="collection with-header"> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> </ul> </div> <div className="col s12 l4"> <ul className="collection with-header"> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> <li className="collection-item "><div>Alvin<a href="#!" className="secondary-content"><i className="material-icons darkest-text-color">file_download</i></a></div></li> </ul> </div> </div> </div> <Agenda /> </div> ); } }); module.exports = SbspOverview;
(function() { function hideInfo(el, info) { return function() { var caption = el.querySelector('figcaption'); info.className = ""; caption.className = ""; caption.onclick = null; info.onclick = showInfo(el, info); }; } function showInfo(el, info) { return function() { var caption = el.querySelector('figcaption'); info.className = "active"; caption.className = "active"; info.onclick = null; caption.onclick = hideInfo(el, info); }; } function handleInfo(el) { var span = document.createElement('span'), infoBubble = document.createTextNode("🛈"); span.appendChild(infoBubble); span.onclick = showInfo(el, span); el.appendChild(span); } function initialize() { document.querySelectorAll('.captioned').forEach(handleInfo); } this.Figure = { init: initialize }; }).call(window);
//@todo: document? module.exports = [ 'auth', 'logins', 'pull', 'push', 'sites' ];
import keycode from 'keycode'; function scrollTo(el) { const rect = el.getBoundingClientRect(); const { innerWidth, innerHeight, pageYOffset, pageXOffset } = window; const top = rect.bottom + pageYOffset; const left = rect.right + pageXOffset; const x = left < pageXOffset || innerWidth + pageXOffset < left ? left - innerWidth / 2 : pageXOffset; const y = top < pageYOffset || innerHeight + pageYOffset < top ? top - innerHeight / 2 : pageYOffset; //window.scrollTo(x, y); console.log('x, y', x, y); } const EnterScrollWindow = () => { return { onKeyDown(e, data, state) { if (!window || keycode(e.which) !== 'enter') { return; } if (false) { e.preventDefault(); const block = state.blocks.get(0); const el = document.querySelector(`[data-key="${block.key}"]`); scrollTo(el); } }, }; }; export default EnterScrollWindow;
function goto_link1(){location.href="http://mp.weixin.qq.com/s?__biz=MzI3MDA4NjAxNQ==&mid=400490584&idx=1&sn=7e3bb395148a1f9a3675c63108a29266&scene=4#wechat_redirect"}function goto_link2(){location.href="http://mp.weixin.qq.com/s?__biz=MzI3MDA4NjAxNQ==&mid=400724251&idx=1&sn=d1a03a31daf29a04f03e60d8389cda93&scene=4#wechat_redirect"}$(function(){$(".flexslider").flexslider({directionNav:!0,pauseOnAction:!1}),setTimeout(adjust_height($(".slides li"),2.2),50),$(window).resize(adjust_height($(".slides li"),2.2));var e=$("#type").val();1==e?($(".nav_one").removeClass("active"),$(".series").addClass("active")):2==e?($(".nav_one").removeClass("active"),$(".scenery").addClass("active")):3==e&&($(".nav_one").removeClass("active"),$(".theme").addClass("active"))});
module.exports = { globals: { __DEV__: true, __IS_VERTIGO__: false }, automock: false, unmockedModulePathPatterns: [ '<rootDir>/node_modules/prop-types', '<rootDir>/node_modules/create-react-class', '<rootDir>/node_modules/react', '<rootDir>/node_modules/react-dom', '<rootDir>/node_modules/react-addons-test-utils', '<rootDir>/node_modules/fbjs', '<rootDir>/node_modules/numeral', '<rootDir>/node_modules/i18next-client', '<rootDir>/node_modules/focus-core' ], testPathIgnorePatterns: ['/node_modules/', 'fixture.js', '.history', '.localhistory', 'test-focus.jsx'], transformIgnorePatterns: ['/node_modules(?!\/focus-core)/'] }
/* * Character Count Plugin - jQuery plugin * Dynamic character count for text areas and input fields * written by Alen Grakalic * http://cssglobe.com/ * * * Updated to work with Twitter Bootstrap 2.0 styles by Shawn Crigger <@svizion> * http://blog.s-vizion.com * Mar-13-2011 * * Copyright (c) 2009 Alen Grakalic (http://cssglobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * Built for jQuery library * http://jquery.com * * */ (function($) { $.fn.charCount = function(options){ // default configuration properties var defaults = { allowed: 140, warning: 25, css: 'help-inline', counterElement: 'span', cssWarning: '', cssExceeded: 'error', counterText: '' }; var options = $.extend(defaults, options); function calculate(obj){ var count = $(obj).val().length; var available = options.allowed - count; if(available <= options.warning && available >= 0){ //Since the error/warning field is actually in the first div, we jump 2 parent classes up to find it. $(obj).next().parent().parent().addClass(options.cssWarning); } else { $(obj).next().parent().parent().removeClass(options.cssWarning); } if(available < 0){ $(obj).next().parent().parent().addClass(options.cssExceeded); } else { $(obj).next().parent().parent().removeClass(options.cssExceeded); } $(obj).next().html(options.counterText + available); }; this.each(function() { $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>'); calculate(this); $(this).keyup(function(){calculate(this)}); $(this).change(function(){calculate(this)}); }); }; })(jQuery);
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), less: { development: { files: { "public/css/style.css": "public/css/style.less" } } }, watch: { scripts: { files: ['public/css/*.less'], tasks: ['less'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.registerTask('default', ['less']); };
var searchData= [ ['matcher',['matcher',['../class_entitas_1_1_group.html#ae48b92ee4d75ca6ec41d1e1187e3b1a2',1,'Entitas::Group']]] ];
var searchData= [ ['main_184',['main',['../_ninja_8cpp.html#a0ddf1224851353fc92bfbff6f499fa97',1,'Ninja.cpp']]], ['makeempty_185',['makeEmpty',['../class_binary_heap.html#ae1d3eb2f5b4fdddcd0d4f0eda4a74ebe',1,'BinaryHeap::makeEmpty()'],['../class_binary_heap___four_ints.html#a5205fb4581fad5ba22013cc77af56670',1,'BinaryHeap_FourInts::makeEmpty()'],['../class_binary_heap___int_key___two_ints.html#afc1db8650e6d9410f3924d48061c4c5e',1,'BinaryHeap_IntKey_TwoInts::makeEmpty()'],['../class_binary_heap___two_ints.html#a81fe1d180e77658e1473317fc7a85fa3',1,'BinaryHeap_TwoInts::makeEmpty()']]], ['maxlevels_186',['maxLevels',['../class_array_heap_ext_mem.html#a59b5c9dc112754fd0b53716cece2c622',1,'ArrayHeapExtMem']]], ['maxmemory_187',['maxMemory',['../class_tree_builder_ext_mem.html#ad79f6b9e37659d5bf70c3718e21c2947',1,'TreeBuilderExtMem']]], ['mem_188',['mem',['../class_array_heap_ext_mem.html#a8b43317321928c37b4d477519a94e3b9',1,'ArrayHeapExtMem']]], ['memd_189',['memD',['../class_tree_builder_ext_mem.html#a6d04c7dd74f24b8741169d7bd4fcb18d',1,'TreeBuilderExtMem']]], ['memdsize_190',['memDSize',['../class_tree_builder_ext_mem.html#ab6952a3aa94a0d3f43955ac582b6478f',1,'TreeBuilderExtMem']]], ['method_191',['method',['../class_tree_builder_manager.html#a4c1a65ed414d8317911abe3d4f704bf6',1,'TreeBuilderManager']]], ['mindeltasum_192',['minDeltaSum',['../class_candidate_heap.html#a3e0ded6c95d83781ede17dca33c4aa3a',1,'CandidateHeap']]] ];
define(['jquery', 'GenomeClassifierTrainingSet', 'base/js/namespace', 'narrativeMocks'], ( $, GenomeClassifierTrainingSet, Jupyter, Mocks ) => { 'use strict'; describe('The GenomeClassifierTrainingSet widget', () => { let $div = null; beforeEach(() => { jasmine.Ajax.install(); const AUTH_TOKEN = 'fakeAuthToken'; Mocks.setAuthToken(AUTH_TOKEN); Jupyter.narrative = { getAuthToken: () => AUTH_TOKEN, }; $div = $('<div>'); }); afterEach(() => { Mocks.clearAuthToken(); Jupyter.narrative = null; jasmine.Ajax.uninstall(); $div.remove(); }); it('Should properly render data', (done) => { const trainingsetdata = { classes: ['P', 'N'], classification_data: [ { evidence_types: ['another', 'some', 'list'], genome_classification: 'N', genome_id: 'my_genome_id', genome_name: 'Acetivibrio_ethanolgignens', genome_ref: '35279/3/1', references: ['some', 'list'], }, { evidence_types: ['another', 'some', 'list'], genome_classification: 'P', genome_id: 'my_genome_id', genome_name: 'Aggregatibacter_actinomycetemcomitans_serotype_b_str._SCC4092', genome_ref: '35279/4/1', references: ['some', 'list'], }, { evidence_types: ['another', 'some', 'list'], genome_classification: 'N', genome_id: 'my_genome_id', genome_name: 'Afipia_felis_ATCC_53690', genome_ref: '35279/5/1', references: ['some', 'list'], }, ], classification_type: 'my_classification_type', description: 'my_description', name: 'my_name', number_of_classes: 2, number_of_genomes: 3, }; jasmine.Ajax.stubRequest('https://ci.kbase.us/services/ws').andReturn({ status: 200, statusText: 'success', contentType: 'application/json', responseHeaders: '', responseText: JSON.stringify({ version: '1.1', result: [ { data: [{ data: trainingsetdata }], }, ], }), }); const w = new GenomeClassifierTrainingSet($div, { upas: { upas: ['fake'] } }); w.trainingSetData = trainingsetdata; w.render(); ['Overview', 'Training Set'].forEach((str) => { expect($div.html()).toContain(str); }); // more complex structure matching const tabs = $div.find('.tabbable'); expect(tabs).not.toBeNull(); const tabsContent = $div.find('.tab-pane'); expect(tabsContent.length).toEqual(2); ['Training Set Name', 'my_name', 'Number of genomes', '3'].forEach((str) => { expect($(tabsContent[0]).html()).toContain(str); }); expect($(tabsContent[1]).html()).toContain('Acetivibrio_ethanolgignens'); expect($(tabsContent[1]).html()).not.toContain('<table>'); done(); }); }); });
'use strict' const Promise = require('bluebird') const { RESTv2 } = require('../../index') const _isEmpty = require('lodash/isEmpty') const { args: { apiKey, apiSecret }, debug, debugTable, readline } = require('../util/setup') async function execute () { const rest = new RESTv2({ apiKey, apiSecret, transform: true }) const filterByMarket = false const allPositions = await rest.positions() const positions = _isEmpty(filterByMarket) ? allPositions : allPositions.filter(({ symbol }) => symbol === filterByMarket) if (positions.length === 0) { debug('no positions match filter') return } debug( 'found %d open positions on market(s) %s\n', positions.length, positions.map(({ symbol }) => symbol).join(',') ) debugTable({ headers: ['Symbol', 'Status', 'Amount', 'Base Price', 'P/L'], rows: positions.map(p => ([ p.symbol, p.status, p.amount, p.basePrice, p.pl ])) }) const confirm = await readline.questionAsync( '> Are you sure you want to claim the position(s) listed above? ' ) if (confirm.toLowerCase()[0] !== 'y') { return } debug('') debug('claiming positions...') await Promise.all(positions.map(p => p.claim(rest))) debug('done!') readline.close() } execute()
/** * exec * @dependency : jquery fes.vendor.js fes.util.js fes.app.js * */ (function($){ // datepicker if ( $('.datepicker').length ) FES.datepicker(); // gnb if ( $('.gnb').length ) FES.gnb(); // buttonToggler if ( $('.buttonToggler').length ) FES.buttonToggler(); // tooltip if ( $('.tooltipTrigger').length ) FES.tooltip(); // toTop if ( $('.toTop').length ) FES.toTop(); // editMode if ( $('.tabType2.divide6').length ) FES.editMode(); // Window Load $(window).load(function() { // navBottom if ( $('.navBottomDesigner').length ) FES.navBottom(); }); })(jQuery);
/* ========================================================================== * ./config/helmet.js * * Helmet Config * ========================================================================== */ export function updateHelmetProps(url, title, description) { return { title, meta: [ { name: 'description', content: description }, { itemprop: 'description', content: description }, // Twitter { name: 'twitter:title', content: title }, { name: 'twitter:description', content: description }, // Facebook { property: 'og:url', content: url }, { property: 'og:title', content: title }, { property: 'og:description', content: description }, ] }; } export const HelmetBaseConfig = { title: 'Christian Le', meta: [ { name: 'description', content: 'Christian Le | Software Engineer and Photographer | GitHub: cle1994 | Berkeley Computer Science' }, { name: 'author', content: 'Christian Le (cle1994)' }, { itemprop: 'name', content: 'Christian Le (cle1994)' }, { itemprop: 'description', content: 'Christian Le | Software Engineer and Photographer | GitHub: cle1994 | Berkeley Computer Science' }, { itemprop: 'image', content: '/favicon/apple-icon-180x180.png' }, // Twitter { name: 'twitter:card', content: 'summary' }, { name: 'twitter:site', content: '@christianle94' }, { name: 'twitter:title', content: 'Christian Le' }, { name: 'twitter:description', content: 'Christian Le | Software Engineer and Photographer | GitHub: cle1994 | Berkeley Computer Science' }, { name: 'twitter:image:src', content: '/favicon/apple-icon-180x180.png' }, // Facebook/Open Graph { property: 'og:url', content: 'http://christianle.com' }, { property: 'og:title', content: 'Christian Le' }, { property: 'og:description', content: 'Christian Le | Software Engineer and Photographer | GitHub: cle1994 | Berkeley Computer Science' }, { property: 'og:site_name', content: 'Christian Le' }, { property: 'og:image', content: 'http://christianle.com/favicon/facebook.png' }, { property: 'og:type', content: 'website' } ] };
// Generated by CoffeeScript 1.6.2 (function() { var Configuration, Daemon, Installer, usage, util, _ref; _ref = require(".."), Daemon = _ref.Daemon, Configuration = _ref.Configuration, Installer = _ref.Installer; util = require("util"); process.title = "power"; usage = function() { console.error("usage: power [--print-config | --install-local | --install-system [--dry-run]]"); return process.exit(-1); }; Configuration.getUserConfiguration(function(err, configuration) { var arg, createInstaller, daemon, dryRun, installer, key, printConfig, shellEscape, underscore, value, _i, _len, _ref1, _ref2, _results; if (err) { throw err; } printConfig = false; createInstaller = null; dryRun = false; _ref1 = process.argv.slice(2); for (_i = 0, _len = _ref1.length; _i < _len; _i++) { arg = _ref1[_i]; if (arg === "--print-config") { printConfig = true; } else if (arg === "--install-local") { createInstaller = Installer.getLocalInstaller; } else if (arg === "--install-system") { createInstaller = Installer.getSystemInstaller; } else if (arg === "--dry-run") { dryRun = true; } else { usage(); } } if (dryRun && !createInstaller) { return usage(); } else if (printConfig) { underscore = function(string) { return string.replace(/(.)([A-Z])/g, function(match, left, right) { return left + "_" + right.toLowerCase(); }); }; shellEscape = function(string) { return "'" + string.toString().replace(/'/g, "'\\''") + "'"; }; _ref2 = configuration.toJSON(); _results = []; for (key in _ref2) { value = _ref2[key]; _results.push(util.puts("POWER_" + underscore(key).toUpperCase() + "=" + shellEscape(value))); } return _results; } else if (createInstaller) { installer = createInstaller(configuration); if (dryRun) { return installer.needsRootPrivileges(function(needsRoot) { var exitCode; exitCode = needsRoot ? 1 : 0; return installer.getStaleFiles(function(files) { var file, _j, _len1; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; util.puts(file.path); } return process.exit(exitCode); }); }); } else { return installer.install(function(err) { if (err) { throw err; } }); } } else { daemon = new Daemon(configuration); daemon.on("restart", function() { return process.exit(); }); return daemon.start(); } }); }).call(this);
var model = { icons : { defalt: { label: 'map-icon-map-pin', icon: { path: MAP_PIN, fillColor: '#1998F7', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, home: { label: 'map-icon-map-pin', icon: { path: MAP_PIN, fillColor: '#1998F7', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, glocery: { label: 'map-icon-grocery-or-supermarket', icon: { path: SQUARE, fillColor: '#00CCBB', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, cafe: { label: 'map-icon-cafe', icon: { path: ROUTE, fillColor: '#B3897B', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, stadium: { label: 'map-icon-stadium', icon: { path: SQUARE_ROUNDED, fillColor: '#65A844', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, market: { label: 'map-icon-florist', icon: { path: SQUARE_ROUNDED, fillColor: '#DB4437', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } }, food: { label: 'map-icon-restaurant', icon: { path: SHIELD, fillColor: '#D01F4D', fillOpacity: 1, strokeColor: '', strokeWeight: 0 } } }, locations: [ {name: 'Home', latitude: 37.3986234 , longitude: -121.94488590000003 , type: "home", visit: true}, {name: 'Safeway', latitude: 37.394634, longitude: -121.94767999999999, type: 'glocery', visit: true}, {name: 'Walmart', latitude: 37.39000850000001, longitude: -121.98550219999998, type:'glocery', visit: true}, {name: 'Sprouts Farmers Market', latitude: 37.3667316, longitude: -122.0308412, type: 'glocery', visit: true}, {name: 'Philz Coffee', latitude: 37.39000850000001, longitude: -122.03171250000003, type:'cafe', visit: true}, {name: 'Sunnyvale Library', latitude: 37.37189800000001, longitude: -122.03891699999997, type: 'lib', visit: true}, {name: 'Levi\'s Stadium', latitude: 37.402317, longitude: -121.96899539999998, type: 'stadium', visit: true}, {name: 'San Jose Flea Market', latitude: 37.368936, longitude: -121.8789875, type: 'market', visit: false}, {name: 'Bar Crudo', latitude: 37.77568309999999, longitude: -122.4382114, type: 'food', visit: false} ], zoom: 10, center: {latitude: 37.3986234 , longitude: -121.94488590000003} }
require('../sass/auth.scss'); require('jquery'); require('bootstrap-sass/assets/javascripts/bootstrap.js'); require('jquery-validation'); require('js-cookie'); require('bootstrap-switch'); var Login = function () { var $loginForm = jQuery('.login-form'); var $passwordReminderForm = jQuery('.forget-form'); var $registrationForm = jQuery('.register-form'); var handleLogin = function () { $loginForm.validate({ errorElement: 'span', // default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { email: { required: true }, password: { required: true }, remember: { required: false } }, messages: { email: { required: "Email is required." }, password: { required: "Password is required." } }, /** * Displays error alert on form submit */ invalidHandler: function (/* event, validator */) { $('.alert-danger', $loginForm).show(); }, /** * Hightlight error inputs * @param element */ highlight: function (element) { $(element).closest('.form-group').addClass('has-error'); // Set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { error.insertAfter(element.closest('.input-icon')); }, submitHandler: function (form) { form.submit(); } }); $('.login-form input').keypress(function (e) { if (e.which == 13) { if ($loginForm.validate().form()) { $loginForm.submit(); } return false; } }); }; var handleForgetPassword = function () { $passwordReminderForm.validate({ errorElement: 'span', //default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { email: { required: true, email: true } }, messages: { email: { required: "Email is required." } }, invalidHandler: function (event, validator) { //display error alert on form submit }, highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group').addClass('has-error'); // set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { error.insertAfter(element.closest('.input-icon')); }, submitHandler: function (form) { form.submit(); } }); $('.forget-form input').keypress(function (e) { if (e.which == 13) { if ($passwordReminderForm.validate().form()) { $passwordReminderForm.submit(); } return false; } }); }; var handleRegister = function () { $registrationForm.validate({ errorElement: 'span', //default input error message container errorClass: 'help-block', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { email: { required: true, email: true }, password: { required: true }, password_confirmation: { equalTo: "#register_password" }, tnc: { required: true } }, messages: { // custom messages for radio buttons and checkboxes tnc: { required: "Please accept TNC first." } }, invalidHandler: function (event, validator) { //display error alert on form submit }, highlight: function (element) { // hightlight error inputs $(element) .closest('.form-group').addClass('has-error'); // set error class to the control group }, success: function (label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement: function (error, element) { if (element.attr("name") == "tnc") { // insert checkbox errors after the container error.insertAfter($('#register_tnc_error')); } else if (element.closest('.input-icon').size() === 1) { error.insertAfter(element.closest('.input-icon')); } else { error.insertAfter(element); } }, submitHandler: function (form) { form[0].submit(); } }); $('.register-form input').keypress(function (e) { if (e.which == 13) { if ($registrationForm.validate().form()) { $registrationForm.submit(); } return false; } }); }; return { /* |---------------------------------------------- | Main function to initiate the module |---------------------------------------------- */ init: function () { handleLogin(); handleForgetPassword(); handleRegister(); } }; }(); jQuery(document).ready(function () { Login.init(); });
ModuleTemplates = { shortEvent: { "name": "Feedback", "number": 1, "eventId": "XXX", "startTime": "YYY", "endTime": "ZZZ", "wizard": { "steps": [ { "stepName": "Profil", "stepTemplate": { "url": "client/components/wizard/templates/multiple-questions.html", "config": { "questions": [ { "propertyName": "interview", "question": "Må en medarbejder fra Erhvervsakademi Aarhus kontakte dig senere for at gennemføre et kort interview?", "answers": [ "Ja", "Nej" ] }, { "propertyName": "alder", "question": "Alder", "answers": [ "-20", "21-30", "31-40", "41-50", "51-60", "61-" ] }, { "propertyName": "koen", "question": "Køn", "answers": [ "mand", "kvinde" ] }, { "propertyName": "anciennitet", "question": "Hvor længe har du været ansat på din nuværende arbejdsplads?", "answers": [ "Op til 1 år", "Fra 1 år til 3 år", "Fra 3 år til 5 år", "Fra 5 år til 8 år", "Mere end 8 år" ] } ], "mandatory": true } } }, { "stepName": "m1q2", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvad var din generelle holdning til teambuilding før dagens forløb?", "propertyName": "m1q2", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "Overvejende positiv", "negativeText": "Overvejende negativ", "smiley": false } } }, { "stepName": "m1q3", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad har du lært nogle af dine kollegaer bedre at kende i dag?", "propertyName": "m1q3", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q4", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad tror du, at du vil opleve et bedre samarbejde på din arbejdsplads efter dagens forløb?", "propertyName": "m1q4", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q5", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad er du tilfreds med den måde I løste dagens udfordringer?", "propertyName": "m1q5", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q6", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad kan dele af dagens aktiviteter overføres til udfordringer på din arbejdsplads?", "propertyName": "m1q6", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q7", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad oplevede du i dag at der var en eller flere der tog ledelse?", "propertyName": "m1q7", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q8", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "I hvor høj grad er du tilfreds med jeres engagement i dagens forløb?", "propertyName": "m1q8", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "I meget høj grad", "negativeText": "I meget lav grad", "smiley": false } } }, { "stepName": "m1q9", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvordan er din holdning til jeres samarbejde i dag?", "propertyName": "m1q9", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "Overvejende positiv", "negativeText": "Overvejende negativ", "smiley": false } } }, { "stepName": "m1q10", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvordan er din holdning til din egen indsats i dag?", "propertyName": "m1q10", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "Ovejvejende positiv", "negativeText": "Overvejende negativ", "smiley": false } } }, { "stepName": "m1q11", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Efter dagens forløb hvad er din generelle vurdering af dagen?", "propertyName": "m1q11", "minValue": 1, "maxValue": 7, "step": 1, "defaultValue": 1, "mandatory": true, "positiveText": "Overvejende positiv", "negativeText": "Overvejende negativ", "smiley": false } } }, { "stepName": "m1q12", "stepTemplate": { "url": "client/components/wizard/templates/text-input.html", "config": { "question": "Hvad har været det bedste ved dagens forløb og hvorfor?", "propertyName": "m1q12", "mandatory": false } } } ] } }, longEventBefore: { "name": "Før", "number": 1, "eventId": "XXX", "startTime": "YYY", "endTime": "ZZZ", "wizard": { "steps": [ { "stepName": "m1q1", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Arbejder du normalt alene eller i et team?", "propertyName": ",m1q1", "minValue": 1, "maxValue": 5, "step": 1, "defaultValue": 3, "mandatory": true, "positiveText": "Næsten altid i et team", "negativeText": "Næsten altid alene", "smiley": false } } }, { "stepName": "m1q2", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q2", "question": "Jobprofil", "answers": [ "Ledelsesansvar for mere end 5 personer", "Ledelsesansvar for 1 til 5 personer", "Ingen ledelsesansvar" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q3", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvad er din generelle holdning til teambuilding?", "propertyName": "m1q3", "minValue": 1, "maxValue": 5, "step": 1, "defaultValue": 3, "mandatory": true, "positiveText": "positiv", "negativeText": "negativ", "smiley": true } } }, { "stepName": "m1q4", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q4", "question": "På din arbejdsplads er I åbne om jeres svagheder?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q5", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q5", "question": "På din arbejdsplads er I gode til at give hinanden en undskyldning?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q6", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q6", "question": "På din arbejdsplads er I åbne og oprigtige over for hinanden?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q7", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q7", "question": "På din arbejdsplads hjælper I hinanden og søger input vedrørende hinandens arbejdsområder?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q8", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q8", "question": "På din arbejdsplads fremfører folk deres meninger, også selvom det medfører risiko for uenighed?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q9", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q9", "question": "Under møder bliver alle meninger og holdninger inddraget?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q10", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q10", "question": "Når der opstår en konflikt i afdelingen, håndteres den med det samme.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q11", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q11", "question": "På team/afdelingsmøder diskuteres de vigtigste og vanskelige problemstillinger.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q12", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q12", "question": "Min afdeling/teamet er klar over vores overordnede retning og prioriteter.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q13", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q13", "question": "Afdelings/teammøder afslutter diskussioner med klare og specifikke løsninger og handlingspunkter.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q14", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q14", "question": "Efter møder forlader alle møderne fulde af tillid og alle bakker op om de beslutninger der er truffet.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q15", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q15", "question": "Folk i min afdeling bakker op om de trufne beslutninger, også selvom de ikke er enige som udgangspunkt.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q16", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q16", "question": "På min arbejdsplads giver vi hinanden spontan, konstruktiv feedback.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q17", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q17", "question": "Vi sikrer, at alle føler et pres og at der er en forventning om at alle præsterer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q18", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q18", "question": "Vi konfronterer kollegaer med problemer inden for deres respektive ansvarsområder.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q19", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q19", "question": "Kollegaerne stiller spørgsmål til hinanden om deres aktuelle tilgang og metoder.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q20", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q20", "question": "Teamet/arbejdsgruppen sætter teamets succes over individuelle præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q21", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q21", "question": "Vi er villige til at bringe ofre på egne områder for teamets/afdelings skyld.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q22", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q22", "question": "Hvis vi ikke når vores fælles mål, tager alle et personligt ansvar for at forbedre afdelingens/teamets præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m1q23", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m1q23", "question": "Vi er hurtige til at fremhæve andres bidrag og præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } } ] } }, longEventDuring: { "name": "Under", "number": 2, "eventId": "XXX", "startTime": "YYY", "endTime": "ZZZ", "wizard": { "steps": [ { "stepName": "m2q1", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvad er din generelle holdning til teambuilding?", "propertyName": "m2q1", "minValue": 1, "maxValue": 5, "defaultValue": 3, "step": 1, "mandatory": true, "positiveText": "positiv", "negativeText": "negativ", "smiley": true } } }, { "stepName": "m2q2", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q2", "question": "Teammedlemmerne var åbne og oprigtige over for hinanden.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q3", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q3", "question": "Teammedlemmerne indrømmede deres svagheder over for teamet.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q4", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q4", "question": "Når der opstod konflikt, håndterede teamet dem med det samme, før teamet gik videre til næste aktivitet.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q5", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q5", "question": "Teammedlemmerne spurgte ind til de andres holdninger og meninger under aktiviteterne.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q6", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q6", "question": "Teamet afslutter diskussioner med klare og specifikke løsninger og handlingspunkter.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q7", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q7", "question": "Alle bakkede op om teamets beslutning, også selvom de ikke var 100% enig.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q8", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q8", "question": "Alle oplevede et pres fra teamet og der var en forventning om at alle præsenterede.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q9", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q9", "question": "Alle gav hinanden spontan og konstruktiv feedback.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q10", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q10", "question": "Teammedlemmerne var villige til at bringe ofre på egne områder for teamets skyld.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m2q11", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m2q11", "question": "Hvis teamet ikke kunne nå de fælles mål, tog det enkelte teammedlem personligt ansvar for at forbedre teamets præsentation.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } } ] } }, longEventAfter: { "name": "Efter", "number": 3, "eventId": "XXX", "startTime": "YYY", "endTime": "ZZZ", "wizard": { "steps": [ { "stepName": "m3q1", "stepTemplate": { "url": "client/components/wizard/templates/slider.html", "config": { "question": "Hvad er din generelle holdning til teambuilding?", "propertyName": "m3q1", "minValue": 1, "maxValue": 5, "step": 1, "defaultValue": 3, "mandatory": true, "positiveText": "positiv", "negativeText": "negativ", "smiley": true } } }, { "stepName": "m3q2", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q2", "question": "På din arbejdsplads er I åbne om jeres svagheder?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q3", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q3", "question": "På din arbejdsplads er I gode til at give hinanden en undskyldning?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q4", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q4", "question": "På din arbejdsplads er I åbne og oprigtige over for hinanden?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q5", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q5", "question": "På din arbejdsplads hjælper I hinanden og søger input vedrørende hinandens arbejdsområder?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q6", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q6", "question": "På din arbejdsplads fremfører folk deres meninger, også selvom det medfører risiko for uenighed?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q7", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q7", "question": "Under møder bliver alle meninger og holdninger inddraget?", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q8", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q8", "question": "Når der opstår en konflikt i afdelingen, håndteres den med det samme.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q9", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q9", "question": "På team/afdelingsmøder diskuteres de vigtigste og vanskelige problemstillinger.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q10", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q10", "question": "Min afdeling/teamet er klar over vores overordnede retning og prioriteter.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q11", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q11", "question": "Afdelings/teammøder afslutter diskussioner med klare og specifikke løsninger og handlingspunkter.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q12", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q12", "question": "Efter møder forlader alle møderne fulde af tillid og alle bakker op om de beslutninger der er truffet.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q13", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q13", "question": "Folk i min afdeling bakker op om de trufne beslutninger, også selvom de ikke er enige som udgangspunkt.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q14", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q14", "question": "På min arbejdsplads giver vi hinanden spontan, konstruktiv feedback.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q15", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q15", "question": "Vi sikrer, at alle føler et pres og at der er en forventning om at alle præsterer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q16", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q16", "question": "Vi konfronterer kollegaer med problemer inden for deres respektive ansvarsområder.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q17", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q17", "question": "Kollegaerne stiller spørgsmål til hinanden om deres aktuelle tilgang og metoder.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q18", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q18", "question": "Teamet/arbejdsgruppen sætter teamets succes over individuelle præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q19", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q19", "question": "Vi er villige til at bringe ofre på egne områder for teamets/afdelings skyld.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q20", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q20", "question": "Hvis vi ikke når vores fælles mål, tager alle et personligt ansvar for at forbedre afdelingens/teamets præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } }, { "stepName": "m3q21", "stepTemplate": { "url": "client/components/wizard/templates/single-question.html", "config": { "propertyName": "m3q21", "question": "Vi er hurtige til at fremhæve andres bidrag og præsentationer.", "answers": [ "Næsten aldrig", "Sjældent", "Nogle gange", "Som regel", "Næsten altid" ], "mandatory": true, "multipleChoice": false } } } ] } } };
/* global malarkey:false, moment:false */ import { config } from './index.config'; import { xConfig } from './xconfig.config'; import { xSites } from './sites.config'; import { xCurrency } from './sites.config'; import { xDecimals } from './sites.config'; import { xGetDeals } from './sites.config'; import { xSearch } from './sites.config'; import { routerConfig } from './index.route'; import { runBlock } from './index.run'; import { MainController } from './main/main.controller'; import { HomeController } from './main/home.controller'; import { DealsController } from './main/deals.controller'; import { SearchController } from './main/search.controller'; import { GithubContributorService } from '../app/components/githubContributor/githubContributor.service'; import { WebDevTecService } from '../app/components/webDevTec/webDevTec.service'; import { NavbarDirective } from '../app/components/navbar/navbar.directive'; import { MalarkeyDirective } from '../app/components/malarkey/malarkey.directive'; angular.module('ixigrab', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ui.bootstrap', 'toastr','rzModule']) .constant('malarkey', malarkey) .constant('moment', moment) .constant('xConfig', xConfig) .constant('xSites', xSites) .constant('xCurrency', xCurrency) .constant('xDecimals', xDecimals) .constant('xGetDeals', xGetDeals) .constant('xSearch', xSearch) .config(config) .config(routerConfig) .run(runBlock) .service('githubContributor', GithubContributorService) .service('webDevTec', WebDevTecService) .controller('MainController', MainController) .controller('HomeController', HomeController) .controller('DealsController', DealsController) .controller('SearchController', SearchController) .directive('acmeNavbar', NavbarDirective) .directive('acmeMalarkey', MalarkeyDirective);
import {stripIndent} from 'common-tags' import FlexSchemaError from '../Error'; import type from './type'; export const preprocessSchemaDefault = ({schema, builtinDataTypes}) => { switch(type(schema.default)) { case 'undefined': case 'function': case schema.type: break; default: if(builtinDataTypes.includes(schema.type)) { throw new FlexSchemaError({ message: `Schema's optional field "default" must be either the same type as the schema or a function that evaluates to that type.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } } }; export const preprocessSchemaIf = ({schema}) => { switch(type(schema.ifCondition)) { case 'undefined': schema.ifCondition = () => () => true; break; case 'function': break; default: throw new FlexSchemaError({ message: `Schema's optional field "if" must be a function that evaluates to a function that evaluates to a boolean.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } }; export const preprocessSchemaProcess = ({schema}) => { switch(type(schema.process)) { case 'undefined': schema.process = true; break; case 'boolean': case 'function': break; default: throw new FlexSchemaError({ message: `Schema's optional field "process" must be either boolean or a function that evaluates to boolean.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } }; export const preprocessSchemaOptional = ({schema}) => { switch(type(schema.optional)) { case 'undefined': schema.optional = false; break; case 'boolean': case 'function': break; default: throw new FlexSchemaError({ message: `Schema's optional field "optional" must be either boolean or a function that evaluates to boolean.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } }; export const preprocessSchemaNullable = ({schema}) => { switch(type(schema.nullable)) { case 'undefined': schema.nullable = false; break; case 'boolean': case 'function': break; default: throw new FlexSchemaError({ message: `Schema's optional field "nullable" must be either boolean or a function that evaluates to boolean.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } }; const preprocessSchemaActions = ({schema, name}) => { switch(type(schema[name])) { case 'undefined': return schema[name] = []; case 'array': let validated = true; for(const item of schema[name]) { const itemType = type(item); if(itemType !== 'function' && itemType !== 'string' && !itemType) { validated = false; break; } } if(validated) { return; } } throw new FlexSchemaError({ message: stripIndent` Schema's optional field "${name}" must be an array of functions or names of methods that are exposed on the schema type class or a function returning such an array `, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); }; export const preprocessSchemaProcessors = ({schema}) => { preprocessSchemaActions({ schema, name: 'preprocessors' }); preprocessSchemaActions({ schema, name: 'postprocessors' }); }; export const preprocessSchemaValidators = ({schema}) => { preprocessSchemaActions({ schema, name: 'prevalidators' }); preprocessSchemaActions({ schema, name: 'postvalidators' }); }; export const preprocessSchemaOneOf = ({schema}) => { switch(type(schema.oneOf)) { case 'undefined': schema.oneOf = []; break; case 'array': for(const acceptableValue of schema.oneOf) { if(typeof acceptableValue !== schema.type || acceptableValue === null) { throw new FlexSchemaError({ message: `Schema's optional field "oneOf" contains values that don't match the schema type. Empty array allows everything. null shouldn't be used inside oneOf. For nullable values, set "nulalble" field to true.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } } break; case 'function': break; default: throw new FlexSchemaError({ message: `Schema's optional field "oneOf" must be an array of values matching the type or a function evaluating to such an array.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } }; export const preprocessSchemaMetadata = ({schema}) => { switch(type(schema.metadata)) { case 'undefined': schema.metadata = {}; break; case 'function': break; default: if(type(schema.metadata) !== 'object') { throw new FlexSchemaError({ message: `Schema's optional field "metadata" must be an object.`, code: FlexSchemaError.CODES.BAD_SCHEMA, details: { schema } }); } } };
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define("require exports ../../../../core/tsSupport/assignHelper ../../../../core/tsSupport/generatorHelper ../../../../core/tsSupport/awaiterHelper ../../../../Color ../../../../symbols ../../../../core/compilerUtils ../../../../core/Error ../../../../core/maybe ../../../../core/promiseUtils ../../../../intl/date ../../heuristics/outline ../../statistics/classBreaks ../../statistics/summaryStatistics ../../support/utils ../../../support/numberUtils ../../../support/pointCloud/PointSizeSplatAlgorithm ../../../../views/support/colorUtils".split(" "), function(N,h,A,p,q,B,g,r,C,t,D,u,E,v,F,m,w,G,H){function n(a,b){return new C(a,b)}function x(a,b,c){var d,e,l;(b=(d={statistics:a,isDate:b},d.statistics))||(b={});var f,k;null==b.min?d.isDate?(k=y(),f=k[0],k=k[1]):(f=0,k=100):b.min===b.max&&(d.isDate?(k=y(b.min),f=k[0],k=k[1]):0>b.min?(f=2*b.min,k=0):0<b.min?(f=0,k=2*b.min):(f=0,k=100));d=null!=f?f:b.min;b=null!=k?k:b.max;null!=f||null!=k?(e=d,l=b):!c||null!=a.avg&&a.stddev||(e=a.min,l=a.max);return null!=e?[e,l]:null}function y(a){var b=("number"=== typeof a?new Date(a):new Date).getUTCFullYear(),c=Date.UTC(b,0,1,12,0,0,0),b=Date.UTC(b,11,31,12,0,0,0);"number"===typeof a&&(a<c&&(c=a),a>b&&(b=a));return[c,b]}function I(a){var b=a.layer;return a.fields.filter(function(a){return!b.getField(a)})}function J(a){var b=a.layer;return a.fields.filter(function(a){a=b.getFieldUsageInfo(a);return!a||!a.supportsRenderer})}Object.defineProperty(h,"__esModule",{value:!0});var z=/^(\d+(\.\d+)?)\s*(%)$/i,K=[0,0,0,.4],L=["hours","minutes","seconds"],M=[].concat(m.defaultBasemapGroups.light).concat(m.defaultBasemapGroups.dark); h.formatDate=function(a,b,c){if("string"===typeof a){if((b=c.getField(a))&&"date"===b.type)return b.alias||b.name}else if("number"===typeof a||a instanceof Date)return b=-1<L.indexOf(b)?"short-date-short-time":"short-date",u.formatDate(a,u.convertDateFormatToIntlOptions(b));return a};h.createError=n;h.getDefaultDataRange=x;h.createColors=function(a,b){for(var c=[],d=a.length,e=0;e<b;e++)c.push(new B(a[e%d]));return c};h.createStopValues=function(a,b){void 0===b&&(b=!0);var c=a.avg,d=c-a.stddev,e= c+a.stddev;d<a.min&&(d=a.min);e>a.max&&(e=a.max);b&&(c=d+(e-d)/2);a=w.round([d,e],{strictBounds:!0});d=a[0];e=a[1];a=[d,d+(c-d)/2,c,c+(e-c)/2,e];return w.round(a,{strictBounds:!0})};h.getSymbolSizeFromScheme=function(a,b,c){switch(b){case "point":case "multipoint":return c?"noDataSize"in a?a.noDataSize:null:"size"in a?a.size:null;case "polyline":return c?"noDataWidth"in a?a.noDataWidth:null:"width"in a?a.width:null;case "polygon":return"size"in a?a.size:null;case "mesh":break;default:r.neverReached(b)}}; h.getSymbolOutlineFromScheme=function(a,b,c){switch(b){case "point":case "multipoint":case "polygon":if(!("outline"in a))return null;a={color:a.outline.color,width:a.outline.width};null!=c&&a.color&&(b=a.color.clone(),b.a=c,a.color=b);return a;case "polyline":case "mesh":break;default:r.neverReached(b)}};h.createSymbol=function(a,b){var c=b.type,d=b.size,e=b.color,l=b.outline,f;switch(a){case "point":case "multipoint":"2d"===c?f=new g.SimpleMarkerSymbol({color:e,size:d,outline:{color:l.color,width:l.width}}): "3d-flat"===c?f=new g.PointSymbol3D({symbolLayers:[new g.IconSymbol3DLayer({size:d,resource:{primitive:"circle"},material:{color:e},outline:{color:l.color,size:l.width}})]}):-1<c.indexOf("3d-volumetric")&&(a="3d-volumetric-uniform"===c,e=new g.ObjectSymbol3DLayer({height:d,resource:{primitive:a?"sphere":"cylinder"},material:{color:e}}),a||(e.width=b.widthAndDepth,e.depth=b.widthAndDepth),f=new g.PointSymbol3D({symbolLayers:[e]}));break;case "polyline":"2d"===c?f=new g.SimpleLineSymbol({color:e,width:d}): "3d-flat"===c?f=new g.LineSymbol3D({symbolLayers:[new g.LineSymbol3DLayer({size:d,material:{color:e}})]}):"3d-volumetric"===c&&(f=new g.LineSymbol3D({symbolLayers:[new g.PathSymbol3DLayer({size:d,material:{color:e}})]}));break;case "polygon":"2d"===c?f=new g.SimpleFillSymbol({color:e,outline:{color:l.color,width:l.width}}):"3d-flat"===c?f=new g.PolygonSymbol3D({symbolLayers:[new g.FillSymbol3DLayer({material:{color:e},outline:{color:l.color,size:l.width}})]}):"3d-volumetric"===c&&(f=new g.PolygonSymbol3D({symbolLayers:[new g.ExtrudeSymbol3DLayer({size:d, material:{color:e}})]}));break;case "mesh":d=b.meshInfo&&b.meshInfo.edgesType,f=new g.MeshSymbol3D({symbolLayers:[new g.FillSymbol3DLayer({material:{color:e,colorMixMode:b.meshInfo&&b.meshInfo.colorMixMode},edges:null==d||"none"===d?null:{type:d,color:K}})]})}return f};h.verifyBasicFieldValidity=function(a,b,c){var d=I({layer:a,fields:b});if(d.length)return n(c,"Unknown fields: "+d.join(", ")+". You can only use fields defined in the layer schema");a=J({layer:a,fields:b});if(a.length)return n(c,"Unsupported fields: "+ a.join(", ")+". You can only use fields that are accessible to the renderer i.e. FieldUsageInfo.supportsRenderer must be true")};h.getClassBreaks=function(a,b){return q(this,void 0,void 0,function(){var c,d,e,l,f,k,h;return p(this,function(g){switch(g.label){case 0:return c={layer:a.layer,view:a.view,signal:a.signal},[4,D.all([v(a),b?E(c):null])];case 1:return d=g.sent(),e=d[0],l=d[1],(f=x({min:e.minValue,max:e.maxValue,avg:null,stddev:null},!1,!1))?[4,v(A({},a,{classificationMethod:"equal-interval", numClasses:1,analyzeData:!1,minValue:f[0],maxValue:f[1],normalizationTotal:f[0]+f[1]}))]:[3,3];case 2:return h=g.sent(),[3,4];case 3:h=e,g.label=4;case 4:return k=h,[2,{result:k,defaultValuesUsed:!!f,outlineResult:l}]}})})};h.getSummaryStatistics=function(a){return F(a)};h.getSizeRangeForAxis=function(a,b){var c=a.minSize;a=a.maxSize;"height"===b&&(c=((a-c)/2+c)/4.6,a*=2);return{minSize:c,maxSize:a}};h.isValidPointSize=function(a){return z.test(a)};h.getPointSizeAlgorithm=function(a){a=a.match(z); var b=Number(a[1]);if("%"===a[3])return new G.default({scaleFactor:b/100})};h.updateAgeRendererAuthoringInfoVV=function(a,b,c,d){a.startTime=b instanceof Date?b.getTime():b;a.endTime=c instanceof Date?c.getTime():c;a.units=d;a.field="string"===typeof b?b:"string"===typeof c?c:null};h.getBasemapInfo=function(a,b){return q(this,void 0,void 0,function(){var c,d,e;return p(this,function(g){switch(g.label){case 0:d=c=null;if(!a&&!b)return[2,{basemapId:c,basemapTheme:d}];!a&&b&&(a=b&&b.get("map.basemap")); a&&(c=m.getBasemapId(a,M,!1))&&(e=m.getBasemapGroup(c),t.isSome(e)&&(d=e));return c||!b?[3,2]:[4,H.getBackgroundColorTheme(b)];case 1:d=g.sent(),t.isSome(d)&&(c="dark"===d?"dark-gray":"gray"),g.label=2;case 2:return[2,{basemapId:c,basemapTheme:d}]}})})}});
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define(["require","exports","dojo/i18n!../nls/Directions","../../../intl","../../../moment"],function(q,d,g,e,p){function f(a){return"esriNAUSeconds"===a||"esriNAUMinutes"===a||"esriNAUHours"===a||"esriNAUDays"===a}function l(a,b,c){var d=f(b),e=f(c);b=d?h(a,b):k(a,b);return d===e?e?m(b,c):n(b,c):a}function h(a,b,c){a=a||0;switch(b){case "esriNAUSeconds":a/=Math.pow(60,c?-1:1);break;case "esriNAUHours":a*=Math.pow(60,c?-1:1);break;case "esriNAUDays":a*=Math.pow(1440,c?-1:1)}return a}function m(a, b){return h(a,b,!0)}function k(a,b,c){a=a||0;switch((b||"").replace("esriNAU","esri")){case "esriInches":a*=Math.pow(.0254,c?-1:1);break;case "esriFeet":a*=Math.pow(.3048,c?-1:1);break;case "esriYards":a*=Math.pow(.9144,c?-1:1);break;case "esriMiles":a*=Math.pow(1609.344,c?-1:1);break;case "esriNauticalMiles":a*=Math.pow(1851.995396854,c?-1:1);break;case "esriMillimeters":a/=Math.pow(1E3,c?-1:1);break;case "esriCentimeters":a/=Math.pow(100,c?-1:1);break;case "esriKilometers":a*=Math.pow(1E3,c?-1: 1);break;case "esriDecimeters":a/=Math.pow(10,c?-1:1)}return a}function n(a,b){return k(a,b,!0)}Object.defineProperty(d,"__esModule",{value:!0});d.useSpatiallyLocalTime=function(a,b){return!(!a._associatedStop||!b||-22091616E5===a.get("attributes.ETA"))};d.toSpatiallyLocalTimeString=function(a,b,c){var d=new Date(b),f=new Date(d.getTime()+6E4*d.getTimezoneOffset()),d=e.formatDate(f,{hour:"2-digits",minute:"2-digits",hour12:!1});return a?(b=(b-a)/1E3/60/60,a=Math.floor(b),c=60*(b-a),b=e.formatNumber(a, {minimumIntegerDigits:2}),c=e.formatNumber(c,{minimumIntegerDigits:2}),d+" "+g.gmt+(0>a?"":"+")+b+c):c?e.formatDate(f,{hour:"numeric",minute:"numeric"}):d};d.isTimeUnits=f;d.convertCostValue=l;d.toMinutes=h;d.fromMinutes=m;d.toMeters=k;d.fromMeters=n;d.isFirstStop=function(a){a=a&&a.attributes||{};return null===(a.ArriveCurbApproach||null)&&null!==(a.DepartCurbApproach||null)};d.isMiddleStop=function(a){a=a&&a.attributes||{};return null!==(a.ArriveCurbApproach||null)&&null!==(a.DepartCurbApproach|| null)};d.isLastStop=function(a){a=a&&a.attributes||{};return null!==(a.ArriveCurbApproach||null)&&null===(a.DepartCurbApproach||null)};d.isWaypoint=function(a){return a&&a.get("attributes.isWaypoint")};d.isStopLocated=function(a){a=a&&a.get("attributes.Status");return!a||6===a};d.getAssociatedStop=function(a){return a._associatedStop};d.formatTime=function(a,b){void 0===b&&(b={});b=b.unit;b=p.duration(Math.round(a),void 0===b?"minutes":b);a=b.asHours();b=b.asMilliseconds();a=1>a?e.formatDate(b,{minute:"numeric"})+ "m":Math.floor(a)+":"+e.formatDate(b,{minute:"2-digit"})+"h";return a};d.formatDistance=function(a,b){void 0===b&&(b={});var c=b.toUnits;a=l(a,b.fromUnits,c);if(!a)return"";c=(b=g.units[c])?b.abbr:c.replace("esri","").toLowerCase();return e.substitute(g.distanceTemplate,{distance:a,units:c},{format:{distance:{type:"number",intlOptions:{minimumFractionDigits:2,maximumFractionDigits:2}}}})}});
import Ember from 'ember'; import config from './config/environment'; const { Router: EmberRouter } = Ember; const Router = EmberRouter.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.route('ember-data-test'); }); export default Router;
/* * AppReducer * * The reducer takes care of our data. Using actions, we can change our * application state. * To add a new action, add it to the switch statement in the reducer function * * Example: * case YOUR_ACTION_CONSTANT: * return state.set('yourStateVariable', true); */ import { fromJS } from 'immutable'; import { LOAD_PLAYLISTS_SUCCESS, LOAD_PLAYLISTS_ERROR, TOGGLE_SELECTED_PLAYLIST, LOAD_GENRES_SUCCESS, SUBMIT_SMARTFORM, SMARTLIST_CREATED, } from './constants'; // The initial state of the App const initialState = fromJS({ loading: false, error: false, playlists: null, genres: null, smartForm: null, activeSmartList: null, }); function appReducer(state = initialState, action) { switch (action.type) { case LOAD_PLAYLISTS_SUCCESS: return state .set('playlists', action.playlists.items) .set('loading', false); case LOAD_PLAYLISTS_ERROR: return state .set('error', action.error) .set('loading', false); case TOGGLE_SELECTED_PLAYLIST: const playlists = state.get('playlists'); if (action.toggleState) { playlists[action.index].selected = true; } else { playlists[action.index].selected = false; } return state .set('playlists', playlists); case LOAD_GENRES_SUCCESS: return state .set('genres', action.genres); case SUBMIT_SMARTFORM: return state .set('smartForm', action.smartForm); case SMARTLIST_CREATED: return state .set('activeSmartList', action.smartList); default: return state; } } export default appReducer;
const processChuck = require('./lib/processChunk') module.exports = processChuck
import { merge } from 'ramda' import client from './client' import validate from './validations' import postback from './postback' import resources from './resources' export default merge({ client, validate, postback, }, resources)
'use strict'; // Customers controller var custumersApp = angular.module('customers'); custumersApp.controller('CustomersController', ['$scope', '$stateParams', 'Authentication', 'Customers', '$modal', '$log', function($scope, $stateParams, Authentication, Customers , $modal, $log) { // Authenticate the user this.authentication = Authentication; // Find a list of Customers this.customers = Customers.query(); // modal for the controller // Open a modal window to Update a single customer record this.modalCreate = function (size) { var modalInstance = $modal.open({ templateUrl: 'modules/customers/views/create-customer.client.view.html', controller: function ($scope, $modalInstance) { $scope.ok = function () { if (!$scope.createCustomerForm.$invalid){ $modalInstance.close(); } else { $log.info('form not valid '); } }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }, size: size }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; // modal for the controller // Open a modal window to Update a single customer record this.modalUpdate = function (size, selectedCustomer) { var modalInstance = $modal.open({ templateUrl: 'modules/customers/views/edit-customer.client.view.html', controller: function ($scope, $modalInstance, customer) { $scope.customer = customer; $scope.ok = function () { if (!$scope.updateCustomer.$invalid){ $modalInstance.close($scope.customer); } else { $log.info('form not valid '); } }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }, size: size, resolve: { customer: function () { return selectedCustomer; } } }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; // Remove existing Customer this.remove = function(customer) { if ( customer ) { customer.$remove(); for (var i in this.customers) { if (this.customers [i] === customer) { this.customers.splice(i, 1); } } } else { this.customer.$remove(function() { }); } }; } ]); custumersApp.controller('CustomersCreateController', ['$scope', 'Customers', 'Notify', function($scope, Customers, Notify) { // Create new Customer this.create = function() { // Create new Customer object var customer = new Customers ({ firstName: this.firstName, surname: this.surname, suburb: this.suburb, country: this.country, referred: this.referred, industry: this.industry, email: this.email, phone: this.phone, channel: this.channel }); // Redirect after save customer.$save(function(response) { Notify.sendMsg('NewCustomer', {'id': response._id}); // Clear form fields $scope.firstName = ''; $scope.surname = ''; $scope.suburb = ''; $scope.country = ''; $scope.referred = ''; $scope.industry = ''; $scope.email = ''; $scope.phone = ''; $scope.channel = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; } ]); custumersApp.controller('CustomersUpdateController', ['$scope', 'Customers', function($scope, Customers) { $scope.channelOptions = [ {id: 1, item: 'Facebook' }, {id: 2, item: 'Twitter' }, {id: 3, item: 'Email' }, ]; // Update existing Customer this.update = function(updatedCustomer) { var customer = updatedCustomer; customer.$update(function() { }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; } ]); custumersApp.directive('customerList', ['Customers', 'Notify', function(Customers, Notify){ return { restrict: 'E', transclude: true, templateUrl: 'modules/customers/views/customer-list-template.html', link: function(scope, element, attrs){ //when a new customer is added, update the customer list Notify.getMsg('NewCustomer', function(event, data) { //we need to requeries scope.customersCtrl.customers = Customers.query(); }); } }; }]);
const bcrypt = require('bcrypt') const roleAdmin = GConfig.role.admin const saltRounds = 12 /** * Mongoose schema */ const encryptPassword = function (password) { let salt = bcrypt.genSaltSync(saltRounds) return bcrypt.hashSync(password, salt) } const UserBaseInfoSchema = new GSchema({ username: { type: String, unique: true, trim: true}, // 由于微信登录等第三方登录,所以注册时可以不填写 mobilePhone: { type: String, unique: true, sparse: true}, email: { type: String, unique: true, lowercase: true, trim: true, sparse: true }, password: { type: String, required: true, default: '20170101', set : encryptPassword}, roles : [{ type: GSchema.Types.ObjectId, ref: 'UserRole' }], firstName: { type: String, trim: true}, lastName: { type: String, trim: true }, fullName: { type: String, trim: true}, nickname: {type: String}, gender: {type: Number, min: 1, max: 10}, birthday: { year : {type : Number, min : 1800, max : 9999}, month : {type : Number, min : 1, max : 12}, day : {type : Number, min : 1, max : 31} }, marriage: {type: Number, min: 1, max: 10}, // 1未婚,2已婚,3离婚,4二婚,5二离 avatar: {type: String}, idGithub: {type: String }, idWeChatOpenID: {type: String}, idWeChatUnionID: {type: String}, idQQ: {type: String}, idWeibo: {type: String} }, { toObject: { virtuals: true }, toJSON: { virtuals: true }, timestamps: true }) /** * Mongoose schema index */ // UserBaseInfoSchema.index({username: 1}) /** * Mongoose plugin */ // UserSchema.plugin(mongooseTimestamps) /** * Add your * - pre-save hooks * - validations * - virtuals */ UserBaseInfoSchema.virtual('isAdmin').get(function () { let isPassed = false this.roles.forEach( (role )=> { if (role && role._id && role._id.equals( GMongoose.Types.ObjectId(roleAdmin)) ) { isPassed = true } }) return isPassed }) /** * Mongoose Schema Statics * * http://mongoosejs.com/docs/guide.html * */ const field = { common : "-__v -updatedAt -password" } UserBaseInfoSchema.statics.findAll = function(query){ return UserBaseInfo.find(query).select(field.common).populate('roles').exec() } UserBaseInfoSchema.statics.find1 = function(query){ return UserBaseInfo.findOne(query).select(field.common).populate('roles').exec() } UserBaseInfoSchema.statics.find1Lean = function(query){ return UserBaseInfo.findOne(query).lean().select(field.common).populate('roles').exec() } UserBaseInfoSchema.statics.find1ById = function(id){ return UserBaseInfo.findById(id).select(field.common).populate('roles').exec() } /** * Mongoose Schema Instance Methods * * Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods too. * * http://mongoosejs.com/docs/guide.html */ UserBaseInfoSchema.methods.comparePasswordSync = function (password) { return bcrypt.compareSync(password, this.password) } UserBaseInfoSchema.methods.comparePassword = function (password) { return bcrypt.compare(password, this.password) } UserBaseInfoSchema.methods.comparePasswordCB = function (password, callback) { bcrypt.compare(password, this.password, function (err, isMatch) { if (err) { return callback(err) } callback(null, isMatch) }) } UserBaseInfoSchema.methods.encryptPassword = encryptPassword /** * Register Model */ const UserBaseInfo = GMongoose.model("UserBaseInfo", UserBaseInfoSchema) module.exports = UserBaseInfo
const fs = require('fs') function render( page ) { return new Promise(( resolve, reject ) => { let viewUrl = `./view/${page}` fs.readFile(viewUrl, "binary", ( err, data ) => { if ( err ) { reject( err ) } else { resolve( data ) } }) }) } module.exports = render
import React from 'react'; import PropTypes from 'prop-types'; // Components import VizzWysiwyg from '@vizzuality/wysiwyg'; import FormElement from './FormElement'; class Wysiwyg extends FormElement { constructor(props) { super(props); if (typeof window === 'undefined') { return; } this.state = { id: Date.now(), value: this.props.properties.default, valid: null, error: [], }; } /** * UI EVENTS * - triggerChange */ triggerChange(value) { this.setState({ value }, () => { // Validate this.triggerValidate(); if (this.props.onChange) { const stringifiedValue = JSON.stringify(value); this.props.onChange(stringifiedValue); } }); } setValue(value) { this.setState({ id: Date.now(), value, }); } getValue() { const { value } = this.state; try { return JSON.parse(value); } catch (e) { return null; } } render() { return ( <VizzWysiwyg id={this.state.id} items={this.getValue()} blocks={this.props.properties.blocks} onChange={this.triggerChange} onUploadImage={this.props.properties.onUploadImage} /> ); } } Wysiwyg.propTypes = { properties: PropTypes.object.isRequired, onChange: PropTypes.func, }; export default Wysiwyg;
System.register(['angular2/core', 'angular2/router', '../search-service/search.service', '../../scroll/scroll.service', '../../pager/pager.component', '../search-form/search-form.component', '../../avatar-component/avatar.component'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, router_1, search_service_1, scroll_service_1, pager_component_1, search_form_component_1, avatar_component_1; var FIRST_PAGE, SearchResultsComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (router_1_1) { router_1 = router_1_1; }, function (search_service_1_1) { search_service_1 = search_service_1_1; }, function (scroll_service_1_1) { scroll_service_1 = scroll_service_1_1; }, function (pager_component_1_1) { pager_component_1 = pager_component_1_1; }, function (search_form_component_1_1) { search_form_component_1 = search_form_component_1_1; }, function (avatar_component_1_1) { avatar_component_1 = avatar_component_1_1; }], execute: function() { FIRST_PAGE = 1; SearchResultsComponent = (function () { function SearchResultsComponent(_searchService, _scroll, _routeParams, _router) { this._searchService = _searchService; this._scroll = _scroll; this._routeParams = _routeParams; this._router = _router; this.result = []; this.submitted = false; this.itemsPerPage = 30; } SearchResultsComponent.prototype.onSearchSubmit = function (login) { this.query = login; this._router.navigate(['SearchResults', { login: login, page: FIRST_PAGE }]); }; SearchResultsComponent.prototype.onSearchResults = function (res) { this.result = res.items; this.totalCount = res.total_count; }; SearchResultsComponent.prototype.showDetails = function (user) { console.log('result>', user); }; SearchResultsComponent.prototype.onNewPage = function (newPage) { this._router.navigate(['SearchResults', { login: this.query, page: newPage }]); }; SearchResultsComponent.prototype._requestFactory = function (login) { var _this = this; return function (page) { _this._scroll.scrollTop(); _this._searchService.getUsers(login, page) .subscribe(function (users) { _this.error = null; _this.onSearchResults(users.json()); _this.submitted = true; }, function (err) { var message = err.json().message; console.error('[GH Cli Error]: %s', message); _this.result = []; _this.error = message; _this.submitted = true; }); }; }; SearchResultsComponent.prototype.ngOnInit = function () { this.query = this._routeParams.get('login'); this.currentPage = parseInt(this._routeParams.get('page')) || FIRST_PAGE; if (this.query !== null) { this._pagerHandler = this._requestFactory(this.query); this._pagerHandler(this.currentPage); } }; SearchResultsComponent.prototype._isFirstPage = function (n) { return n === FIRST_PAGE; }; SearchResultsComponent = __decorate([ core_1.Component({ selector: 'div.search-results', templateUrl: 'app/search/search-results/search-results.component.html', directives: [search_form_component_1.SearchFormComponent, pager_component_1.PagerComponent, router_1.ROUTER_DIRECTIVES, avatar_component_1.AvatarComponent], providers: [search_service_1.SearchService] }), __metadata('design:paramtypes', [search_service_1.SearchService, scroll_service_1.ScrollService, router_1.RouteParams, router_1.Router]) ], SearchResultsComponent); return SearchResultsComponent; }()); exports_1("SearchResultsComponent", SearchResultsComponent); } } }); //# sourceMappingURL=search-results.component.js.map
import { NativeModules } from 'react-native'; const client_id = process.env.SPOTIFY_CLIENT_ID; const client_secret = process.env.SPOTIFY_CLIENT_SECRET; const redirect_uri = process.env.SPOTIFY_REDIRECT_URI; //Assign our module from NativeModules and assign it to a variable const SpotifyAuth = NativeModules.SpotifyAuth; class yourComponent extends Component { //Some code ... someMethod(){ //You need this to Auth a user, without it you cant use any method! SpotifyAuth.setClientID(client_id, redirect_uri, ['streaming'], (error)=>{ if(error){ //handle error } else { //handle success } }); } }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-5-b-3 description: Object.defineProperties - 'descObj' is a boolean (8.10.5 step 1) includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; try { Object.defineProperties(obj, { prop: true }); return false; } catch (e) { return e instanceof TypeError && !obj.hasOwnProperty("prop"); } } runTestCase(testcase);
/* Copyright (c) 2009, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.8.0r4 */ /** * The Slider component is a UI control that enables the user to adjust * values in a finite range along one or two axes. Typically, the Slider * control is used in a web application as a rich, visual replacement * for an input box that takes a number as input. The Slider control can * also easily accommodate a second dimension, providing x,y output for * a selection point chosen from a rectangular region. * * @module slider * @title Slider Widget * @namespace YAHOO.widget * @requires yahoo,dom,dragdrop,event * @optional animation */ (function () { var getXY = YAHOO.util.Dom.getXY, Event = YAHOO.util.Event, _AS = Array.prototype.slice; /** * A DragDrop implementation that can be used as a background for a * slider. It takes a reference to the thumb instance * so it can delegate some of the events to it. The goal is to make the * thumb jump to the location on the background when the background is * clicked. * * @class Slider * @extends YAHOO.util.DragDrop * @uses YAHOO.util.EventProvider * @constructor * @param {String} id The id of the element linked to this instance * @param {String} sGroup The group of related DragDrop items * @param {SliderThumb} oThumb The thumb for this slider * @param {String} sType The type of slider (horiz, vert, region) */ function Slider(sElementId, sGroup, oThumb, sType) { Slider.ANIM_AVAIL = (!YAHOO.lang.isUndefined(YAHOO.util.Anim)); if (sElementId) { this.init(sElementId, sGroup, true); this.initSlider(sType); this.initThumb(oThumb); } } YAHOO.lang.augmentObject(Slider,{ /** * Factory method for creating a horizontal slider * @method YAHOO.widget.Slider.getHorizSlider * @static * @param {String} sBGElId the id of the slider's background element * @param {String} sHandleElId the id of the thumb element * @param {int} iLeft the number of pixels the element can move left * @param {int} iRight the number of pixels the element can move right * @param {int} iTickSize optional parameter for specifying that the element * should move a certain number pixels at a time. * @return {Slider} a horizontal slider control */ getHorizSlider : function (sBGElId, sHandleElId, iLeft, iRight, iTickSize) { return new Slider(sBGElId, sBGElId, new YAHOO.widget.SliderThumb(sHandleElId, sBGElId, iLeft, iRight, 0, 0, iTickSize), "horiz"); }, /** * Factory method for creating a vertical slider * @method YAHOO.widget.Slider.getVertSlider * @static * @param {String} sBGElId the id of the slider's background element * @param {String} sHandleElId the id of the thumb element * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize optional parameter for specifying that the element * should move a certain number pixels at a time. * @return {Slider} a vertical slider control */ getVertSlider : function (sBGElId, sHandleElId, iUp, iDown, iTickSize) { return new Slider(sBGElId, sBGElId, new YAHOO.widget.SliderThumb(sHandleElId, sBGElId, 0, 0, iUp, iDown, iTickSize), "vert"); }, /** * Factory method for creating a slider region like the one in the color * picker example * @method YAHOO.widget.Slider.getSliderRegion * @static * @param {String} sBGElId the id of the slider's background element * @param {String} sHandleElId the id of the thumb element * @param {int} iLeft the number of pixels the element can move left * @param {int} iRight the number of pixels the element can move right * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize optional parameter for specifying that the element * should move a certain number pixels at a time. * @return {Slider} a slider region control */ getSliderRegion : function (sBGElId, sHandleElId, iLeft, iRight, iUp, iDown, iTickSize) { return new Slider(sBGElId, sBGElId, new YAHOO.widget.SliderThumb(sHandleElId, sBGElId, iLeft, iRight, iUp, iDown, iTickSize), "region"); }, /** * Constant for valueChangeSource, indicating that the user clicked or * dragged the slider to change the value. * @property Slider.SOURCE_UI_EVENT * @final * @static * @default 1 */ SOURCE_UI_EVENT : 1, /** * Constant for valueChangeSource, indicating that the value was altered * by a programmatic call to setValue/setRegionValue. * @property Slider.SOURCE_SET_VALUE * @final * @static * @default 2 */ SOURCE_SET_VALUE : 2, /** * Constant for valueChangeSource, indicating that the value was altered * by hitting any of the supported keyboard characters. * @property Slider.SOURCE_KEY_EVENT * @final * @static * @default 2 */ SOURCE_KEY_EVENT : 3, /** * By default, animation is available if the animation utility is detected. * @property Slider.ANIM_AVAIL * @static * @type boolean */ ANIM_AVAIL : false },true); YAHOO.extend(Slider, YAHOO.util.DragDrop, { /** * Tracks the state of the mouse button to aid in when events are fired. * * @property _mouseDown * @type boolean * @default false * @private */ _mouseDown : false, /** * Override the default setting of dragOnly to true. * @property dragOnly * @type boolean * @default true */ dragOnly : true, /** * Initializes the slider. Executed in the constructor * @method initSlider * @param {string} sType the type of slider (horiz, vert, region) */ initSlider: function(sType) { /** * The type of the slider (horiz, vert, region) * @property type * @type string */ this.type = sType; //this.removeInvalidHandleType("A"); this.logger = new YAHOO.widget.LogWriter(this.toString()); /** * Event the fires when the value of the control changes. If * the control is animated the event will fire every point * along the way. * @event change * @param {int} newOffset|x the new offset for normal sliders, or the new * x offset for region sliders * @param {int} y the number of pixels the thumb has moved on the y axis * (region sliders only) */ this.createEvent("change", this); /** * Event that fires at the beginning of a slider thumb move. * @event slideStart */ this.createEvent("slideStart", this); /** * Event that fires at the end of a slider thumb move * @event slideEnd */ this.createEvent("slideEnd", this); /** * Overrides the isTarget property in YAHOO.util.DragDrop * @property isTarget * @private */ this.isTarget = false; /** * Flag that determines if the thumb will animate when moved * @property animate * @type boolean */ this.animate = Slider.ANIM_AVAIL; /** * Set to false to disable a background click thumb move * @property backgroundEnabled * @type boolean */ this.backgroundEnabled = true; /** * Adjustment factor for tick animation, the more ticks, the * faster the animation (by default) * @property tickPause * @type int */ this.tickPause = 40; /** * Enables the arrow, home and end keys, defaults to true. * @property enableKeys * @type boolean */ this.enableKeys = true; /** * Specifies the number of pixels the arrow keys will move the slider. * Default is 20. * @property keyIncrement * @type int */ this.keyIncrement = 20; /** * moveComplete is set to true when the slider has moved to its final * destination. For animated slider, this value can be checked in * the onChange handler to make it possible to execute logic only * when the move is complete rather than at all points along the way. * Deprecated because this flag is only useful when the background is * clicked and the slider is animated. If the user drags the thumb, * the flag is updated when the drag is over ... the final onDrag event * fires before the mouseup the ends the drag, so the implementer will * never see it. * * @property moveComplete * @type Boolean * @deprecated use the slideEnd event instead */ this.moveComplete = true; /** * If animation is configured, specifies the length of the animation * in seconds. * @property animationDuration * @type int * @default 0.2 */ this.animationDuration = 0.2; /** * Constant for valueChangeSource, indicating that the user clicked or * dragged the slider to change the value. * @property SOURCE_UI_EVENT * @final * @default 1 * @deprecated use static Slider.SOURCE_UI_EVENT */ this.SOURCE_UI_EVENT = 1; /** * Constant for valueChangeSource, indicating that the value was altered * by a programmatic call to setValue/setRegionValue. * @property SOURCE_SET_VALUE * @final * @default 2 * @deprecated use static Slider.SOURCE_SET_VALUE */ this.SOURCE_SET_VALUE = 2; /** * When the slider value changes, this property is set to identify where * the update came from. This will be either 1, meaning the slider was * clicked or dragged, or 2, meaning that it was set via a setValue() call. * This can be used within event handlers to apply some of the logic only * when dealing with one source or another. * @property valueChangeSource * @type int * @since 2.3.0 */ this.valueChangeSource = 0; /** * Indicates whether or not events will be supressed for the current * slide operation * @property _silent * @type boolean * @private */ this._silent = false; /** * Saved offset used to protect against NaN problems when slider is * set to display:none * @property lastOffset * @type [int, int] */ this.lastOffset = [0,0]; }, /** * Initializes the slider's thumb. Executed in the constructor. * @method initThumb * @param {YAHOO.widget.SliderThumb} t the slider thumb */ initThumb: function(t) { var self = this; /** * A YAHOO.widget.SliderThumb instance that we will use to * reposition the thumb when the background is clicked * @property thumb * @type YAHOO.widget.SliderThumb */ this.thumb = t; t.cacheBetweenDrags = true; if (t._isHoriz && t.xTicks && t.xTicks.length) { this.tickPause = Math.round(360 / t.xTicks.length); } else if (t.yTicks && t.yTicks.length) { this.tickPause = Math.round(360 / t.yTicks.length); } this.logger.log("tickPause: " + this.tickPause); // delegate thumb methods t.onAvailable = function() { return self.setStartSliderState(); }; t.onMouseDown = function () { self._mouseDown = true; self.logger.log('thumb mousedown'); return self.focus(); }; t.startDrag = function() { self.logger.log('thumb startDrag'); self._slideStart(); }; t.onDrag = function() { self.logger.log('thumb drag'); self.fireEvents(true); }; t.onMouseUp = function() { self.thumbMouseUp(); }; }, /** * Executed when the slider element is available * @method onAvailable */ onAvailable: function() { this._bindKeyEvents(); }, /** * Sets up the listeners for keydown and key press events. * * @method _bindKeyEvents * @protected */ _bindKeyEvents : function () { Event.on(this.id, "keydown", this.handleKeyDown, this, true); Event.on(this.id, "keypress", this.handleKeyPress, this, true); }, /** * Executed when a keypress event happens with the control focused. * Prevents the default behavior for navigation keys. The actual * logic for moving the slider thumb in response to a key event * happens in handleKeyDown. * @param {Event} e the keypress event */ handleKeyPress: function(e) { if (this.enableKeys) { var kc = Event.getCharCode(e); switch (kc) { case 0x25: // left case 0x26: // up case 0x27: // right case 0x28: // down case 0x24: // home case 0x23: // end Event.preventDefault(e); break; default: } } }, /** * Executed when a keydown event happens with the control focused. * Updates the slider value and display when the keypress is an * arrow key, home, or end as long as enableKeys is set to true. * @param {Event} e the keydown event */ handleKeyDown: function(e) { if (this.enableKeys) { var kc = Event.getCharCode(e), t = this.thumb, h = this.getXValue(), v = this.getYValue(), changeValue = true; switch (kc) { // left case 0x25: h -= this.keyIncrement; break; // up case 0x26: v -= this.keyIncrement; break; // right case 0x27: h += this.keyIncrement; break; // down case 0x28: v += this.keyIncrement; break; // home case 0x24: h = t.leftConstraint; v = t.topConstraint; break; // end case 0x23: h = t.rightConstraint; v = t.bottomConstraint; break; default: changeValue = false; } if (changeValue) { if (t._isRegion) { this._setRegionValue(Slider.SOURCE_KEY_EVENT, h, v, true); } else { this._setValue(Slider.SOURCE_KEY_EVENT, (t._isHoriz ? h : v), true); } Event.stopEvent(e); } } }, /** * Initialization that sets up the value offsets once the elements are ready * @method setStartSliderState */ setStartSliderState: function() { this.logger.log("Fixing state"); this.setThumbCenterPoint(); /** * The basline position of the background element, used * to determine if the background has moved since the last * operation. * @property baselinePos * @type [int, int] */ this.baselinePos = getXY(this.getEl()); this.thumb.startOffset = this.thumb.getOffsetFromParent(this.baselinePos); if (this.thumb._isRegion) { if (this.deferredSetRegionValue) { this._setRegionValue.apply(this, this.deferredSetRegionValue); this.deferredSetRegionValue = null; } else { this.setRegionValue(0, 0, true, true, true); } } else { if (this.deferredSetValue) { this._setValue.apply(this, this.deferredSetValue); this.deferredSetValue = null; } else { this.setValue(0, true, true, true); } } }, /** * When the thumb is available, we cache the centerpoint of the element so * we can position the element correctly when the background is clicked * @method setThumbCenterPoint */ setThumbCenterPoint: function() { var el = this.thumb.getEl(); if (el) { /** * The center of the slider element is stored so we can * place it in the correct position when the background is clicked. * @property thumbCenterPoint * @type {"x": int, "y": int} */ this.thumbCenterPoint = { x: parseInt(el.offsetWidth/2, 10), y: parseInt(el.offsetHeight/2, 10) }; } }, /** * Locks the slider, overrides YAHOO.util.DragDrop * @method lock */ lock: function() { this.logger.log("locking"); this.thumb.lock(); this.locked = true; }, /** * Unlocks the slider, overrides YAHOO.util.DragDrop * @method unlock */ unlock: function() { this.logger.log("unlocking"); this.thumb.unlock(); this.locked = false; }, /** * Handles mouseup event on the thumb * @method thumbMouseUp * @private */ thumbMouseUp: function() { this._mouseDown = false; this.logger.log("thumb mouseup"); if (!this.isLocked()) { this.endMove(); } }, onMouseUp: function() { this._mouseDown = false; this.logger.log("background mouseup"); if (this.backgroundEnabled && !this.isLocked()) { this.endMove(); } }, /** * Returns a reference to this slider's thumb * @method getThumb * @return {SliderThumb} this slider's thumb */ getThumb: function() { return this.thumb; }, /** * Try to focus the element when clicked so we can add * accessibility features * @method focus * @private */ focus: function() { this.logger.log("focus"); this.valueChangeSource = Slider.SOURCE_UI_EVENT; // Focus the background element if possible var el = this.getEl(); if (el.focus) { try { el.focus(); } catch(e) { // Prevent permission denied unhandled exception in FF that can // happen when setting focus while another element is handling // the blur. @TODO this is still writing to the error log // (unhandled error) in FF1.5 with strict error checking on. } } this.verifyOffset(); return !this.isLocked(); }, /** * Event that fires when the value of the slider has changed * @method onChange * @param {int} firstOffset the number of pixels the thumb has moved * from its start position. Normal horizontal and vertical sliders will only * have the firstOffset. Regions will have both, the first is the horizontal * offset, the second the vertical. * @param {int} secondOffset the y offset for region sliders * @deprecated use instance.subscribe("change") instead */ onChange: function (firstOffset, secondOffset) { /* override me */ this.logger.log("onChange: " + firstOffset + ", " + secondOffset); }, /** * Event that fires when the at the beginning of the slider thumb move * @method onSlideStart * @deprecated use instance.subscribe("slideStart") instead */ onSlideStart: function () { /* override me */ this.logger.log("onSlideStart"); }, /** * Event that fires at the end of a slider thumb move * @method onSliderEnd * @deprecated use instance.subscribe("slideEnd") instead */ onSlideEnd: function () { /* override me */ this.logger.log("onSlideEnd"); }, /** * Returns the slider's thumb offset from the start position * @method getValue * @return {int} the current value */ getValue: function () { return this.thumb.getValue(); }, /** * Returns the slider's thumb X offset from the start position * @method getXValue * @return {int} the current horizontal offset */ getXValue: function () { return this.thumb.getXValue(); }, /** * Returns the slider's thumb Y offset from the start position * @method getYValue * @return {int} the current vertical offset */ getYValue: function () { return this.thumb.getYValue(); }, /** * Provides a way to set the value of the slider in code. * * @method setValue * @param {int} newOffset the number of pixels the thumb should be * positioned away from the initial start point * @param {boolean} skipAnim set to true to disable the animation * for this move action (but not others). * @param {boolean} force ignore the locked setting and set value anyway * @param {boolean} silent when true, do not fire events * @return {boolean} true if the move was performed, false if it failed */ setValue: function() { var args = _AS.call(arguments); args.unshift(Slider.SOURCE_SET_VALUE); return this._setValue.apply(this,args); }, /** * Worker function to execute the value set operation. Accepts type of * set operation in addition to the usual setValue params. * * @method _setValue * @param source {int} what triggered the set (e.g. Slider.SOURCE_SET_VALUE) * @param {int} newOffset the number of pixels the thumb should be * positioned away from the initial start point * @param {boolean} skipAnim set to true to disable the animation * for this move action (but not others). * @param {boolean} force ignore the locked setting and set value anyway * @param {boolean} silent when true, do not fire events * @return {boolean} true if the move was performed, false if it failed * @protected */ _setValue: function(source, newOffset, skipAnim, force, silent) { var t = this.thumb, newX, newY; if (!t.available) { this.logger.log("defer setValue until after onAvailble"); this.deferredSetValue = arguments; return false; } if (this.isLocked() && !force) { this.logger.log("Can't set the value, the control is locked"); return false; } if ( isNaN(newOffset) ) { this.logger.log("setValue, Illegal argument: " + newOffset); return false; } if (t._isRegion) { this.logger.log("Call to setValue for region Slider ignored. Use setRegionValue","warn"); return false; } this.logger.log("setValue " + newOffset); this._silent = silent; this.valueChangeSource = source || Slider.SOURCE_SET_VALUE; t.lastOffset = [newOffset, newOffset]; this.verifyOffset(); this._slideStart(); if (t._isHoriz) { newX = t.initPageX + newOffset + this.thumbCenterPoint.x; this.moveThumb(newX, t.initPageY, skipAnim); } else { newY = t.initPageY + newOffset + this.thumbCenterPoint.y; this.moveThumb(t.initPageX, newY, skipAnim); } return true; }, /** * Provides a way to set the value of the region slider in code. * @method setRegionValue * @param {int} newOffset the number of pixels the thumb should be * positioned away from the initial start point (x axis for region) * @param {int} newOffset2 the number of pixels the thumb should be * positioned away from the initial start point (y axis for region) * @param {boolean} skipAnim set to true to disable the animation * for this move action (but not others). * @param {boolean} force ignore the locked setting and set value anyway * @param {boolean} silent when true, do not fire events * @return {boolean} true if the move was performed, false if it failed */ setRegionValue : function () { var args = _AS.call(arguments); args.unshift(Slider.SOURCE_SET_VALUE); return this._setRegionValue.apply(this,args); }, /** * Worker function to execute the value set operation. Accepts type of * set operation in addition to the usual setValue params. * * @method _setRegionValue * @param source {int} what triggered the set (e.g. Slider.SOURCE_SET_VALUE) * @param {int} newOffset the number of pixels the thumb should be * positioned away from the initial start point (x axis for region) * @param {int} newOffset2 the number of pixels the thumb should be * positioned away from the initial start point (y axis for region) * @param {boolean} skipAnim set to true to disable the animation * for this move action (but not others). * @param {boolean} force ignore the locked setting and set value anyway * @param {boolean} silent when true, do not fire events * @return {boolean} true if the move was performed, false if it failed * @protected */ _setRegionValue: function(source, newOffset, newOffset2, skipAnim, force, silent) { var t = this.thumb, newX, newY; if (!t.available) { this.logger.log("defer setRegionValue until after onAvailble"); this.deferredSetRegionValue = arguments; return false; } if (this.isLocked() && !force) { this.logger.log("Can't set the value, the control is locked"); return false; } if ( isNaN(newOffset) ) { this.logger.log("setRegionValue, Illegal argument: " + newOffset); return false; } if (!t._isRegion) { this.logger.log("Call to setRegionValue for non-region Slider ignored. Use setValue","warn"); return false; } this._silent = silent; this.valueChangeSource = source || Slider.SOURCE_SET_VALUE; t.lastOffset = [newOffset, newOffset2]; this.verifyOffset(); this._slideStart(); newX = t.initPageX + newOffset + this.thumbCenterPoint.x; newY = t.initPageY + newOffset2 + this.thumbCenterPoint.y; this.moveThumb(newX, newY, skipAnim); return true; }, /** * Checks the background position element position. If it has moved from the * baseline position, the constraints for the thumb are reset * @method verifyOffset * @return {boolean} True if the offset is the same as the baseline. */ verifyOffset: function() { var xy = getXY(this.getEl()), t = this.thumb; if (!this.thumbCenterPoint || !this.thumbCenterPoint.x) { this.setThumbCenterPoint(); } if (xy) { this.logger.log("newPos: " + xy); if (xy[0] != this.baselinePos[0] || xy[1] != this.baselinePos[1]) { this.logger.log("background moved, resetting constraints"); // Reset background this.setInitPosition(); this.baselinePos = xy; // Reset thumb t.initPageX = this.initPageX + t.startOffset[0]; t.initPageY = this.initPageY + t.startOffset[1]; t.deltaSetXY = null; this.resetThumbConstraints(); return false; } } return true; }, /** * Move the associated slider moved to a timeout to try to get around the * mousedown stealing moz does when I move the slider element between the * cursor and the background during the mouseup event * @method moveThumb * @param {int} x the X coordinate of the click * @param {int} y the Y coordinate of the click * @param {boolean} skipAnim don't animate if the move happend onDrag * @param {boolean} midMove set to true if this is not terminating * the slider movement * @private */ moveThumb: function(x, y, skipAnim, midMove) { var t = this.thumb, self = this, p,_p,anim; if (!t.available) { this.logger.log("thumb is not available yet, aborting move"); return; } this.logger.log("move thumb, x: " + x + ", y: " + y); t.setDelta(this.thumbCenterPoint.x, this.thumbCenterPoint.y); _p = t.getTargetCoord(x, y); p = [Math.round(_p.x), Math.round(_p.y)]; if (this.animate && t._graduated && !skipAnim) { this.logger.log("graduated"); this.lock(); // cache the current thumb pos this.curCoord = getXY(this.thumb.getEl()); this.curCoord = [Math.round(this.curCoord[0]), Math.round(this.curCoord[1])]; setTimeout( function() { self.moveOneTick(p); }, this.tickPause ); } else if (this.animate && Slider.ANIM_AVAIL && !skipAnim) { this.logger.log("animating to " + p); this.lock(); anim = new YAHOO.util.Motion( t.id, { points: { to: p } }, this.animationDuration, YAHOO.util.Easing.easeOut ); anim.onComplete.subscribe( function() { self.logger.log("Animation completed _mouseDown:" + self._mouseDown); self.unlock(); if (!self._mouseDown) { self.endMove(); } }); anim.animate(); } else { t.setDragElPos(x, y); if (!midMove && !this._mouseDown) { this.endMove(); } } }, _slideStart: function() { if (!this._sliding) { if (!this._silent) { this.onSlideStart(); this.fireEvent("slideStart"); } this._sliding = true; this.moveComplete = false; // for backward compatibility. Deprecated } }, _slideEnd: function() { if (this._sliding) { // Reset state before firing slideEnd var silent = this._silent; this._sliding = false; this.moveComplete = true; // for backward compatibility. Deprecated this._silent = false; if (!silent) { this.onSlideEnd(); this.fireEvent("slideEnd"); } } }, /** * Move the slider one tick mark towards its final coordinate. Used * for the animation when tick marks are defined * @method moveOneTick * @param {int[]} the destination coordinate * @private */ moveOneTick: function(finalCoord) { var t = this.thumb, self = this, nextCoord = null, tmpX, tmpY; if (t._isRegion) { nextCoord = this._getNextX(this.curCoord, finalCoord); tmpX = (nextCoord !== null) ? nextCoord[0] : this.curCoord[0]; nextCoord = this._getNextY(this.curCoord, finalCoord); tmpY = (nextCoord !== null) ? nextCoord[1] : this.curCoord[1]; nextCoord = tmpX !== this.curCoord[0] || tmpY !== this.curCoord[1] ? [ tmpX, tmpY ] : null; } else if (t._isHoriz) { nextCoord = this._getNextX(this.curCoord, finalCoord); } else { nextCoord = this._getNextY(this.curCoord, finalCoord); } this.logger.log("moveOneTick: " + " finalCoord: " + finalCoord + " this.curCoord: " + this.curCoord + " nextCoord: " + nextCoord); if (nextCoord) { // cache the position this.curCoord = nextCoord; // move to the next coord this.thumb.alignElWithMouse(t.getEl(), nextCoord[0] + this.thumbCenterPoint.x, nextCoord[1] + this.thumbCenterPoint.y); // check if we are in the final position, if not make a recursive call if (!(nextCoord[0] == finalCoord[0] && nextCoord[1] == finalCoord[1])) { setTimeout(function() { self.moveOneTick(finalCoord); }, this.tickPause); } else { this.unlock(); if (!this._mouseDown) { this.endMove(); } } } else { this.unlock(); if (!this._mouseDown) { this.endMove(); } } }, /** * Returns the next X tick value based on the current coord and the target coord. * @method _getNextX * @private */ _getNextX: function(curCoord, finalCoord) { this.logger.log("getNextX: " + curCoord + ", " + finalCoord); var t = this.thumb, thresh, tmp = [], nextCoord = null; if (curCoord[0] > finalCoord[0]) { thresh = t.tickSize - this.thumbCenterPoint.x; tmp = t.getTargetCoord( curCoord[0] - thresh, curCoord[1] ); nextCoord = [tmp.x, tmp.y]; } else if (curCoord[0] < finalCoord[0]) { thresh = t.tickSize + this.thumbCenterPoint.x; tmp = t.getTargetCoord( curCoord[0] + thresh, curCoord[1] ); nextCoord = [tmp.x, tmp.y]; } else { // equal, do nothing } return nextCoord; }, /** * Returns the next Y tick value based on the current coord and the target coord. * @method _getNextY * @private */ _getNextY: function(curCoord, finalCoord) { var t = this.thumb, thresh, tmp = [], nextCoord = null; if (curCoord[1] > finalCoord[1]) { thresh = t.tickSize - this.thumbCenterPoint.y; tmp = t.getTargetCoord( curCoord[0], curCoord[1] - thresh ); nextCoord = [tmp.x, tmp.y]; } else if (curCoord[1] < finalCoord[1]) { thresh = t.tickSize + this.thumbCenterPoint.y; tmp = t.getTargetCoord( curCoord[0], curCoord[1] + thresh ); nextCoord = [tmp.x, tmp.y]; } else { // equal, do nothing } return nextCoord; }, /** * Resets the constraints before moving the thumb. * @method b4MouseDown * @private */ b4MouseDown: function(e) { if (!this.backgroundEnabled) { return false; } this.thumb.autoOffset(); this.baselinePos = []; }, /** * Handles the mousedown event for the slider background * @method onMouseDown * @private */ onMouseDown: function(e) { if (!this.backgroundEnabled || this.isLocked()) { return false; } this._mouseDown = true; var x = Event.getPageX(e), y = Event.getPageY(e); this.logger.log("bg mousedown: " + x + "," + y); this.focus(); this._slideStart(); this.moveThumb(x, y); }, /** * Handles the onDrag event for the slider background * @method onDrag * @private */ onDrag: function(e) { this.logger.log("background drag"); if (this.backgroundEnabled && !this.isLocked()) { var x = Event.getPageX(e), y = Event.getPageY(e); this.moveThumb(x, y, true, true); this.fireEvents(); } }, /** * Fired when the slider movement ends * @method endMove * @private */ endMove: function () { this.logger.log("endMove"); this.unlock(); this.fireEvents(); this._slideEnd(); }, /** * Resets the X and Y contraints for the thumb. Used in lieu of the thumb * instance's inherited resetConstraints because some logic was not * applicable. * @method resetThumbConstraints * @protected */ resetThumbConstraints: function () { var t = this.thumb; t.setXConstraint(t.leftConstraint, t.rightConstraint, t.xTickSize); t.setYConstraint(t.topConstraint, t.bottomConstraint, t.xTickSize); }, /** * Fires the change event if the value has been changed. Ignored if we are in * the middle of an animation as the event will fire when the animation is * complete * @method fireEvents * @param {boolean} thumbEvent set to true if this event is fired from an event * that occurred on the thumb. If it is, the state of the * thumb dd object should be correct. Otherwise, the event * originated on the background, so the thumb state needs to * be refreshed before proceeding. * @private */ fireEvents: function (thumbEvent) { var t = this.thumb, newX, newY, newVal; if (!thumbEvent) { t.cachePosition(); } if (! this.isLocked()) { if (t._isRegion) { newX = t.getXValue(); newY = t.getYValue(); if (newX != this.previousX || newY != this.previousY) { if (!this._silent) { this.onChange(newX, newY); this.fireEvent("change", { x: newX, y: newY }); } } this.previousX = newX; this.previousY = newY; } else { newVal = t.getValue(); if (newVal != this.previousVal) { this.logger.log("Firing onchange: " + newVal); if (!this._silent) { this.onChange( newVal ); this.fireEvent("change", newVal); } } this.previousVal = newVal; } } }, /** * Slider toString * @method toString * @return {string} string representation of the instance */ toString: function () { return ("Slider (" + this.type +") " + this.id); } }); YAHOO.lang.augmentProto(Slider, YAHOO.util.EventProvider); YAHOO.widget.Slider = Slider; })(); /** * A drag and drop implementation to be used as the thumb of a slider. * @class SliderThumb * @extends YAHOO.util.DD * @constructor * @param {String} id the id of the slider html element * @param {String} sGroup the group of related DragDrop items * @param {int} iLeft the number of pixels the element can move left * @param {int} iRight the number of pixels the element can move right * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize optional parameter for specifying that the element * should move a certain number pixels at a time. */ YAHOO.widget.SliderThumb = function(id, sGroup, iLeft, iRight, iUp, iDown, iTickSize) { if (id) { YAHOO.widget.SliderThumb.superclass.constructor.call(this, id, sGroup); /** * The id of the thumbs parent HTML element (the slider background * element). * @property parentElId * @type string */ this.parentElId = sGroup; } this.logger = new YAHOO.widget.LogWriter(this.toString()); /** * Overrides the isTarget property in YAHOO.util.DragDrop * @property isTarget * @private */ this.isTarget = false; /** * The tick size for this slider * @property tickSize * @type int * @private */ this.tickSize = iTickSize; /** * Informs the drag and drop util that the offsets should remain when * resetting the constraints. This preserves the slider value when * the constraints are reset * @property maintainOffset * @type boolean * @private */ this.maintainOffset = true; this.initSlider(iLeft, iRight, iUp, iDown, iTickSize); /** * Turns off the autoscroll feature in drag and drop * @property scroll * @private */ this.scroll = false; }; YAHOO.extend(YAHOO.widget.SliderThumb, YAHOO.util.DD, { /** * The (X and Y) difference between the thumb location and its parent * (the slider background) when the control is instantiated. * @property startOffset * @type [int, int] */ startOffset: null, /** * Override the default setting of dragOnly to true. * @property dragOnly * @type boolean * @default true */ dragOnly : true, /** * Flag used to figure out if this is a horizontal or vertical slider * @property _isHoriz * @type boolean * @private */ _isHoriz: false, /** * Cache the last value so we can check for change * @property _prevVal * @type int * @private */ _prevVal: 0, /** * The slider is _graduated if there is a tick interval defined * @property _graduated * @type boolean * @private */ _graduated: false, /** * Returns the difference between the location of the thumb and its parent. * @method getOffsetFromParent * @param {[int, int]} parentPos Optionally accepts the position of the parent * @type [int, int] */ getOffsetFromParent0: function(parentPos) { var myPos = YAHOO.util.Dom.getXY(this.getEl()), ppos = parentPos || YAHOO.util.Dom.getXY(this.parentElId); return [ (myPos[0] - ppos[0]), (myPos[1] - ppos[1]) ]; }, getOffsetFromParent: function(parentPos) { var el = this.getEl(), newOffset, myPos,ppos,l,t,deltaX,deltaY,newLeft,newTop; if (!this.deltaOffset) { myPos = YAHOO.util.Dom.getXY(el); ppos = parentPos || YAHOO.util.Dom.getXY(this.parentElId); newOffset = [ (myPos[0] - ppos[0]), (myPos[1] - ppos[1]) ]; l = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); t = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); deltaX = l - newOffset[0]; deltaY = t - newOffset[1]; if (isNaN(deltaX) || isNaN(deltaY)) { this.logger.log("element does not have a position style def yet"); } else { this.deltaOffset = [deltaX, deltaY]; } } else { newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); newOffset = [newLeft + this.deltaOffset[0], newTop + this.deltaOffset[1]]; } return newOffset; }, /** * Set up the slider, must be called in the constructor of all subclasses * @method initSlider * @param {int} iLeft the number of pixels the element can move left * @param {int} iRight the number of pixels the element can move right * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize the width of the tick interval. */ initSlider: function (iLeft, iRight, iUp, iDown, iTickSize) { this.initLeft = iLeft; this.initRight = iRight; this.initUp = iUp; this.initDown = iDown; this.setXConstraint(iLeft, iRight, iTickSize); this.setYConstraint(iUp, iDown, iTickSize); if (iTickSize && iTickSize > 1) { this._graduated = true; } this._isHoriz = (iLeft || iRight); this._isVert = (iUp || iDown); this._isRegion = (this._isHoriz && this._isVert); }, /** * Clear's the slider's ticks * @method clearTicks */ clearTicks: function () { YAHOO.widget.SliderThumb.superclass.clearTicks.call(this); this.tickSize = 0; this._graduated = false; }, /** * Gets the current offset from the element's start position in * pixels. * @method getValue * @return {int} the number of pixels (positive or negative) the * slider has moved from the start position. */ getValue: function () { return (this._isHoriz) ? this.getXValue() : this.getYValue(); }, /** * Gets the current X offset from the element's start position in * pixels. * @method getXValue * @return {int} the number of pixels (positive or negative) the * slider has moved horizontally from the start position. */ getXValue: function () { if (!this.available) { return 0; } var newOffset = this.getOffsetFromParent(); if (YAHOO.lang.isNumber(newOffset[0])) { this.lastOffset = newOffset; return (newOffset[0] - this.startOffset[0]); } else { this.logger.log("can't get offset, using old value: " + this.lastOffset[0]); return (this.lastOffset[0] - this.startOffset[0]); } }, /** * Gets the current Y offset from the element's start position in * pixels. * @method getYValue * @return {int} the number of pixels (positive or negative) the * slider has moved vertically from the start position. */ getYValue: function () { if (!this.available) { return 0; } var newOffset = this.getOffsetFromParent(); if (YAHOO.lang.isNumber(newOffset[1])) { this.lastOffset = newOffset; return (newOffset[1] - this.startOffset[1]); } else { this.logger.log("can't get offset, using old value: " + this.lastOffset[1]); return (this.lastOffset[1] - this.startOffset[1]); } }, /** * Thumb toString * @method toString * @return {string} string representation of the instance */ toString: function () { return "SliderThumb " + this.id; }, /** * The onchange event for the handle/thumb is delegated to the YAHOO.widget.Slider * instance it belongs to. * @method onChange * @private */ onChange: function (x, y) { } }); /** * A slider with two thumbs, one that represents the min value and * the other the max. Actually a composition of two sliders, both with * the same background. The constraints for each slider are adjusted * dynamically so that the min value of the max slider is equal or greater * to the current value of the min slider, and the max value of the min * slider is the current value of the max slider. * Constructor assumes both thumbs are positioned absolutely at the 0 mark on * the background. * * @namespace YAHOO.widget * @class DualSlider * @uses YAHOO.util.EventProvider * @constructor * @param {Slider} minSlider The Slider instance used for the min value thumb * @param {Slider} maxSlider The Slider instance used for the max value thumb * @param {int} range The number of pixels the thumbs may move within * @param {Array} initVals (optional) [min,max] Initial thumb placement */ (function () { var Event = YAHOO.util.Event, YW = YAHOO.widget; function DualSlider(minSlider, maxSlider, range, initVals) { var self = this, ready = { min : false, max : false }, minThumbOnMouseDown, maxThumbOnMouseDown; /** * A slider instance that keeps track of the lower value of the range. * <strong>read only</strong> * @property minSlider * @type Slider */ this.minSlider = minSlider; /** * A slider instance that keeps track of the upper value of the range. * <strong>read only</strong> * @property maxSlider * @type Slider */ this.maxSlider = maxSlider; /** * The currently active slider (min or max). <strong>read only</strong> * @property activeSlider * @type Slider */ this.activeSlider = minSlider; /** * Is the DualSlider oriented horizontally or vertically? * <strong>read only</strong> * @property isHoriz * @type boolean */ this.isHoriz = minSlider.thumb._isHoriz; //FIXME: this is horrible minThumbOnMouseDown = this.minSlider.thumb.onMouseDown; maxThumbOnMouseDown = this.maxSlider.thumb.onMouseDown; this.minSlider.thumb.onMouseDown = function() { self.activeSlider = self.minSlider; minThumbOnMouseDown.apply(this,arguments); }; this.maxSlider.thumb.onMouseDown = function () { self.activeSlider = self.maxSlider; maxThumbOnMouseDown.apply(this,arguments); }; this.minSlider.thumb.onAvailable = function () { minSlider.setStartSliderState(); ready.min = true; if (ready.max) { self.fireEvent('ready',self); } }; this.maxSlider.thumb.onAvailable = function () { maxSlider.setStartSliderState(); ready.max = true; if (ready.min) { self.fireEvent('ready',self); } }; // dispatch mousedowns to the active slider minSlider.onMouseDown = maxSlider.onMouseDown = function(e) { return this.backgroundEnabled && self._handleMouseDown(e); }; // Fix the drag behavior so that only the active slider // follows the drag minSlider.onDrag = maxSlider.onDrag = function(e) { self._handleDrag(e); }; // Likely only the minSlider's onMouseUp will be executed, but both are // overridden just to be safe minSlider.onMouseUp = maxSlider.onMouseUp = function (e) { self._handleMouseUp(e); }; // Replace the _bindKeyEvents for the minSlider and remove that for the // maxSlider since they share the same bg element. minSlider._bindKeyEvents = function () { self._bindKeyEvents(this); }; maxSlider._bindKeyEvents = function () {}; // The core events for each slider are handled so we can expose a single // event for when the event happens on either slider minSlider.subscribe("change", this._handleMinChange, minSlider, this); minSlider.subscribe("slideStart", this._handleSlideStart, minSlider, this); minSlider.subscribe("slideEnd", this._handleSlideEnd, minSlider, this); maxSlider.subscribe("change", this._handleMaxChange, maxSlider, this); maxSlider.subscribe("slideStart", this._handleSlideStart, maxSlider, this); maxSlider.subscribe("slideEnd", this._handleSlideEnd, maxSlider, this); /** * Event that fires when the slider is finished setting up * @event ready * @param {DualSlider} dualslider the DualSlider instance */ this.createEvent("ready", this); /** * Event that fires when either the min or max value changes * @event change * @param {DualSlider} dualslider the DualSlider instance */ this.createEvent("change", this); /** * Event that fires when one of the thumbs begins to move * @event slideStart * @param {Slider} activeSlider the moving slider */ this.createEvent("slideStart", this); /** * Event that fires when one of the thumbs finishes moving * @event slideEnd * @param {Slider} activeSlider the moving slider */ this.createEvent("slideEnd", this); // Validate initial values initVals = YAHOO.lang.isArray(initVals) ? initVals : [0,range]; initVals[0] = Math.min(Math.max(parseInt(initVals[0],10)|0,0),range); initVals[1] = Math.max(Math.min(parseInt(initVals[1],10)|0,range),0); // Swap initVals if min > max if (initVals[0] > initVals[1]) { initVals.splice(0,2,initVals[1],initVals[0]); } this.minVal = initVals[0]; this.maxVal = initVals[1]; // Set values so initial assignment when the slider thumbs are ready will // use these values this.minSlider.setValue(this.minVal,true,true,true); this.maxSlider.setValue(this.maxVal,true,true,true); YAHOO.log("Setting initial values " + this.minVal + ", " + this.maxVal,"info","DualSlider"); } DualSlider.prototype = { /** * The current value of the min thumb. <strong>read only</strong>. * @property minVal * @type int */ minVal : -1, /** * The current value of the max thumb. <strong>read only</strong>. * @property maxVal * @type int */ maxVal : -1, /** * Pixel distance to maintain between thumbs. * @property minRange * @type int * @default 0 */ minRange : 0, /** * Executed when one of the sliders fires the slideStart event * @method _handleSlideStart * @private */ _handleSlideStart: function(data, slider) { this.fireEvent("slideStart", slider); }, /** * Executed when one of the sliders fires the slideEnd event * @method _handleSlideEnd * @private */ _handleSlideEnd: function(data, slider) { this.fireEvent("slideEnd", slider); }, /** * Overrides the onDrag method for both sliders * @method _handleDrag * @private */ _handleDrag: function(e) { YW.Slider.prototype.onDrag.call(this.activeSlider, e); }, /** * Executed when the min slider fires the change event * @method _handleMinChange * @private */ _handleMinChange: function() { this.activeSlider = this.minSlider; this.updateValue(); }, /** * Executed when the max slider fires the change event * @method _handleMaxChange * @private */ _handleMaxChange: function() { this.activeSlider = this.maxSlider; this.updateValue(); }, /** * Set up the listeners for the keydown and keypress events. * * @method _bindKeyEvents * @protected */ _bindKeyEvents : function (slider) { Event.on(slider.id,'keydown', this._handleKeyDown, this,true); Event.on(slider.id,'keypress',this._handleKeyPress,this,true); }, /** * Delegate event handling to the active Slider. See Slider.handleKeyDown. * * @method _handleKeyDown * @param e {Event} the mousedown DOM event * @protected */ _handleKeyDown : function (e) { this.activeSlider.handleKeyDown.apply(this.activeSlider,arguments); }, /** * Delegate event handling to the active Slider. See Slider.handleKeyPress. * * @method _handleKeyPress * @param e {Event} the mousedown DOM event * @protected */ _handleKeyPress : function (e) { this.activeSlider.handleKeyPress.apply(this.activeSlider,arguments); }, /** * Sets the min and max thumbs to new values. * @method setValues * @param min {int} Pixel offset to assign to the min thumb * @param max {int} Pixel offset to assign to the max thumb * @param skipAnim {boolean} (optional) Set to true to skip thumb animation. * Default false * @param force {boolean} (optional) ignore the locked setting and set * value anyway. Default false * @param silent {boolean} (optional) Set to true to skip firing change * events. Default false */ setValues : function (min, max, skipAnim, force, silent) { var mins = this.minSlider, maxs = this.maxSlider, mint = mins.thumb, maxt = maxs.thumb, self = this, done = { min : false, max : false }; // Clear constraints to prevent animated thumbs from prematurely // stopping when hitting a constraint that's moving with the other // thumb. if (mint._isHoriz) { mint.setXConstraint(mint.leftConstraint,maxt.rightConstraint,mint.tickSize); maxt.setXConstraint(mint.leftConstraint,maxt.rightConstraint,maxt.tickSize); } else { mint.setYConstraint(mint.topConstraint,maxt.bottomConstraint,mint.tickSize); maxt.setYConstraint(mint.topConstraint,maxt.bottomConstraint,maxt.tickSize); } // Set up one-time slideEnd callbacks to call updateValue when both // thumbs have been set this._oneTimeCallback(mins,'slideEnd',function () { done.min = true; if (done.max) { self.updateValue(silent); // Clean the slider's slideEnd events on a timeout since this // will be executed from inside the event's fire setTimeout(function () { self._cleanEvent(mins,'slideEnd'); self._cleanEvent(maxs,'slideEnd'); },0); } }); this._oneTimeCallback(maxs,'slideEnd',function () { done.max = true; if (done.min) { self.updateValue(silent); // Clean both sliders' slideEnd events on a timeout since this // will be executed from inside one of the event's fire setTimeout(function () { self._cleanEvent(mins,'slideEnd'); self._cleanEvent(maxs,'slideEnd'); },0); } }); // Must emit Slider slideEnd event to propagate to updateValue mins.setValue(min,skipAnim,force,false); maxs.setValue(max,skipAnim,force,false); }, /** * Set the min thumb position to a new value. * @method setMinValue * @param min {int} Pixel offset for min thumb * @param skipAnim {boolean} (optional) Set to true to skip thumb animation. * Default false * @param force {boolean} (optional) ignore the locked setting and set * value anyway. Default false * @param silent {boolean} (optional) Set to true to skip firing change * events. Default false */ setMinValue : function (min, skipAnim, force, silent) { var mins = this.minSlider, self = this; this.activeSlider = mins; // Use a one-time event callback to delay the updateValue call // until after the slide operation is done self = this; this._oneTimeCallback(mins,'slideEnd',function () { self.updateValue(silent); // Clean the slideEnd event on a timeout since this // will be executed from inside the event's fire setTimeout(function () { self._cleanEvent(mins,'slideEnd'); }, 0); }); mins.setValue(min, skipAnim, force); }, /** * Set the max thumb position to a new value. * @method setMaxValue * @param max {int} Pixel offset for max thumb * @param skipAnim {boolean} (optional) Set to true to skip thumb animation. * Default false * @param force {boolean} (optional) ignore the locked setting and set * value anyway. Default false * @param silent {boolean} (optional) Set to true to skip firing change * events. Default false */ setMaxValue : function (max, skipAnim, force, silent) { var maxs = this.maxSlider, self = this; this.activeSlider = maxs; // Use a one-time event callback to delay the updateValue call // until after the slide operation is done this._oneTimeCallback(maxs,'slideEnd',function () { self.updateValue(silent); // Clean the slideEnd event on a timeout since this // will be executed from inside the event's fire setTimeout(function () { self._cleanEvent(maxs,'slideEnd'); }, 0); }); maxs.setValue(max, skipAnim, force); }, /** * Executed when one of the sliders is moved * @method updateValue * @param silent {boolean} (optional) Set to true to skip firing change * events. Default false * @private */ updateValue: function(silent) { var min = this.minSlider.getValue(), max = this.maxSlider.getValue(), changed = false, mint,maxt,dim,minConstraint,maxConstraint,thumbInnerWidth; if (min != this.minVal || max != this.maxVal) { changed = true; mint = this.minSlider.thumb; maxt = this.maxSlider.thumb; dim = this.isHoriz ? 'x' : 'y'; thumbInnerWidth = this.minSlider.thumbCenterPoint[dim] + this.maxSlider.thumbCenterPoint[dim]; // Establish barriers within the respective other thumb's edge, less // the minRange. Limit to the Slider's range in the case of // negative minRanges. minConstraint = Math.max(max-thumbInnerWidth-this.minRange,0); maxConstraint = Math.min(-min-thumbInnerWidth-this.minRange,0); if (this.isHoriz) { minConstraint = Math.min(minConstraint,maxt.rightConstraint); mint.setXConstraint(mint.leftConstraint,minConstraint, mint.tickSize); maxt.setXConstraint(maxConstraint,maxt.rightConstraint, maxt.tickSize); } else { minConstraint = Math.min(minConstraint,maxt.bottomConstraint); mint.setYConstraint(mint.leftConstraint,minConstraint, mint.tickSize); maxt.setYConstraint(maxConstraint,maxt.bottomConstraint, maxt.tickSize); } } this.minVal = min; this.maxVal = max; if (changed && !silent) { this.fireEvent("change", this); } }, /** * A background click will move the slider thumb nearest to the click. * Override if you need different behavior. * @method selectActiveSlider * @param e {Event} the mousedown event * @private */ selectActiveSlider: function(e) { var min = this.minSlider, max = this.maxSlider, minLocked = min.isLocked() || !min.backgroundEnabled, maxLocked = max.isLocked() || !min.backgroundEnabled, Ev = YAHOO.util.Event, d; if (minLocked || maxLocked) { this.activeSlider = minLocked ? max : min; } else { if (this.isHoriz) { d = Ev.getPageX(e)-min.thumb.initPageX-min.thumbCenterPoint.x; } else { d = Ev.getPageY(e)-min.thumb.initPageY-min.thumbCenterPoint.y; } this.activeSlider = d*2 > max.getValue()+min.getValue() ? max : min; } }, /** * Delegates the onMouseDown to the appropriate Slider * * @method _handleMouseDown * @param e {Event} mouseup event * @protected */ _handleMouseDown: function(e) { if (!e._handled && !this.minSlider._sliding && !this.maxSlider._sliding) { e._handled = true; this.selectActiveSlider(e); return YW.Slider.prototype.onMouseDown.call(this.activeSlider, e); } else { return false; } }, /** * Delegates the onMouseUp to the active Slider * * @method _handleMouseUp * @param e {Event} mouseup event * @protected */ _handleMouseUp : function (e) { YW.Slider.prototype.onMouseUp.apply( this.activeSlider, arguments); }, /** * Schedule an event callback that will execute once, then unsubscribe * itself. * @method _oneTimeCallback * @param o {EventProvider} Object to attach the event to * @param evt {string} Name of the event * @param fn {Function} function to execute once * @private */ _oneTimeCallback : function (o,evt,fn) { var sub = function () { // Unsubscribe myself o.unsubscribe(evt, sub); // Pass the event handler arguments to the one time callback fn.apply({},arguments); }; o.subscribe(evt,sub); }, /** * Clean up the slideEnd event subscribers array, since each one-time * callback will be replaced in the event's subscribers property with * null. This will cause memory bloat and loss of performance. * @method _cleanEvent * @param o {EventProvider} object housing the CustomEvent * @param evt {string} name of the CustomEvent * @private */ _cleanEvent : function (o,evt) { var ce,i,len,j,subs,newSubs; if (o.__yui_events && o.events[evt]) { for (i = o.__yui_events.length; i >= 0; --i) { if (o.__yui_events[i].type === evt) { ce = o.__yui_events[i]; break; } } if (ce) { subs = ce.subscribers; newSubs = []; j = 0; for (i = 0, len = subs.length; i < len; ++i) { if (subs[i]) { newSubs[j++] = subs[i]; } } ce.subscribers = newSubs; } } } }; YAHOO.lang.augmentProto(DualSlider, YAHOO.util.EventProvider); /** * Factory method for creating a horizontal dual-thumb slider * @for YAHOO.widget.Slider * @method YAHOO.widget.Slider.getHorizDualSlider * @static * @param {String} bg the id of the slider's background element * @param {String} minthumb the id of the min thumb * @param {String} maxthumb the id of the thumb thumb * @param {int} range the number of pixels the thumbs can move within * @param {int} iTickSize (optional) the element should move this many pixels * at a time * @param {Array} initVals (optional) [min,max] Initial thumb placement * @return {DualSlider} a horizontal dual-thumb slider control */ YW.Slider.getHorizDualSlider = function (bg, minthumb, maxthumb, range, iTickSize, initVals) { var mint = new YW.SliderThumb(minthumb, bg, 0, range, 0, 0, iTickSize), maxt = new YW.SliderThumb(maxthumb, bg, 0, range, 0, 0, iTickSize); return new DualSlider( new YW.Slider(bg, bg, mint, "horiz"), new YW.Slider(bg, bg, maxt, "horiz"), range, initVals); }; /** * Factory method for creating a vertical dual-thumb slider. * @for YAHOO.widget.Slider * @method YAHOO.widget.Slider.getVertDualSlider * @static * @param {String} bg the id of the slider's background element * @param {String} minthumb the id of the min thumb * @param {String} maxthumb the id of the thumb thumb * @param {int} range the number of pixels the thumbs can move within * @param {int} iTickSize (optional) the element should move this many pixels * at a time * @param {Array} initVals (optional) [min,max] Initial thumb placement * @return {DualSlider} a vertical dual-thumb slider control */ YW.Slider.getVertDualSlider = function (bg, minthumb, maxthumb, range, iTickSize, initVals) { var mint = new YW.SliderThumb(minthumb, bg, 0, 0, 0, range, iTickSize), maxt = new YW.SliderThumb(maxthumb, bg, 0, 0, 0, range, iTickSize); return new YW.DualSlider( new YW.Slider(bg, bg, mint, "vert"), new YW.Slider(bg, bg, maxt, "vert"), range, initVals); }; YAHOO.widget.DualSlider = DualSlider; })(); YAHOO.register("slider", YAHOO.widget.Slider, {version: "2.8.0r4", build: "2446"});
/** * @overview datejs * @version 1.0.0-beta-2014-03-25 * @author Gregory Wild-Smith <gregory@wild-smith.com> * @copyright 2014 Gregory Wild-Smith * @license MIT * @homepage https://github.com/abritinthebay/datejs */ /* 2014 Gregory Wild-Smith @license MIT @homepage https://github.com/abritinthebay/datejs 2014 Gregory Wild-Smith @license MIT @homepage https://github.com/abritinthebay/datejs */ Date.CultureStrings=Date.CultureStrings||{}; Date.CultureStrings["es-PA"]={name:"es-PA",englishName:"Spanish (Panama)",nativeName:"Espa\u00f1ol (Panam\u00e1)",Sunday:"domingo",Monday:"lunes",Tuesday:"martes",Wednesday:"mi\u00e9rcoles",Thursday:"jueves",Friday:"viernes",Saturday:"s\u00e1bado",Sun:"dom",Mon:"lun",Tue:"mar",Wed:"mi\u00e9",Thu:"jue",Fri:"vie",Sat:"s\u00e1b",Su:"do",Mo:"lu",Tu:"ma",We:"mi",Th:"ju",Fr:"vi",Sa:"s\u00e1",S_Sun_Initial:"d",M_Mon_Initial:"l",T_Tue_Initial:"m",W_Wed_Initial:"m",T_Thu_Initial:"j",F_Fri_Initial:"v",S_Sat_Initial:"s", January:"enero",February:"febrero",March:"marzo",April:"abril",May:"mayo",June:"junio",July:"julio",August:"agosto",September:"septiembre",October:"octubre",November:"noviembre",December:"diciembre",Jan_Abbr:"ene",Feb_Abbr:"feb",Mar_Abbr:"mar",Apr_Abbr:"abr",May_Abbr:"may",Jun_Abbr:"jun",Jul_Abbr:"jul",Aug_Abbr:"ago",Sep_Abbr:"sep",Oct_Abbr:"oct",Nov_Abbr:"nov",Dec_Abbr:"dic",AM:"a.m.",PM:"p.m.",firstDayOfWeek:0,twoDigitYearMax:2029,mdy:"mdy","M/d/yyyy":"MM/dd/yyyy","dddd, MMMM dd, yyyy":"dddd, dd' de 'MMMM' de 'yyyy", "h:mm tt":"hh:mm tt","h:mm:ss tt":"hh:mm:ss tt","dddd, MMMM dd, yyyy h:mm:ss tt":"dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt","yyyy-MM-ddTHH:mm:ss":"yyyy-MM-ddTHH:mm:ss","yyyy-MM-dd HH:mm:ssZ":"yyyy-MM-dd HH:mm:ssZ","ddd, dd MMM yyyy HH:mm:ss":"ddd, dd MMM yyyy HH:mm:ss","MMMM dd":"dd MMMM","MMMM, yyyy":"MMMM' de 'yyyy","/jan(uary)?/":"ene(ro)?","/feb(ruary)?/":"feb(rero)?","/mar(ch)?/":"mar(zo)?","/apr(il)?/":"abr(il)?","/may/":"may(o)?","/jun(e)?/":"jun(io)?","/jul(y)?/":"jul(io)?","/aug(ust)?/":"ago(sto)?", "/sep(t(ember)?)?/":"sep(tiembre)?","/oct(ober)?/":"oct(ubre)?","/nov(ember)?/":"nov(iembre)?","/dec(ember)?/":"dic(iembre)?","/^su(n(day)?)?/":"^do(m(ingo)?)?","/^mo(n(day)?)?/":"^lu(n(es)?)?","/^tu(e(s(day)?)?)?/":"^ma(r(tes)?)?","/^we(d(nesday)?)?/":"^mi(\u00e9(rcoles)?)?","/^th(u(r(s(day)?)?)?)?/":"^ju(e(ves)?)?","/^fr(i(day)?)?/":"^vi(e(rnes)?)?","/^sa(t(urday)?)?/":"^s\u00e1(b(ado)?)?","/^next/":"^next","/^last|past|prev(ious)?/":"^last|past|prev(ious)?","/^(\\+|aft(er)?|from|hence)/":"^(\\+|aft(er)?|from|hence)", "/^(\\-|bef(ore)?|ago)/":"^(\\-|bef(ore)?|ago)","/^yes(terday)?/":"^yes(terday)?","/^t(od(ay)?)?/":"^t(od(ay)?)?","/^tom(orrow)?/":"^tom(orrow)?","/^n(ow)?/":"^n(ow)?","/^ms|milli(second)?s?/":"^ms|milli(second)?s?","/^sec(ond)?s?/":"^sec(ond)?s?","/^mn|min(ute)?s?/":"^mn|min(ute)?s?","/^h(our)?s?/":"^h(our)?s?","/^w(eek)?s?/":"^w(eek)?s?","/^m(onth)?s?/":"^m(onth)?s?","/^d(ay)?s?/":"^d(ay)?s?","/^y(ear)?s?/":"^y(ear)?s?","/^(a|p)/":"^(a|p)","/^(a\\.?m?\\.?|p\\.?m?\\.?)/":"^(a\\.?m?\\.?|p\\.?m?\\.?)", "/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/":"^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)","/^\\s*(st|nd|rd|th)/":"^\\s*(st|nd|rd|th)","/^\\s*(\\:|a(?!u|p)|p)/":"^\\s*(\\:|a(?!u|p)|p)",LINT:"LINT",TOT:"TOT",CHAST:"CHAST",NZST:"NZST",NFT:"NFT",SBT:"SBT",AEST:"AEST",ACST:"ACST",JST:"JST",CWST:"CWST",CT:"CT",ICT:"ICT",MMT:"MMT",BIOT:"BST",NPT:"NPT",IST:"IST",PKT:"PKT",AFT:"AFT",MSK:"MSK",IRST:"IRST",FET:"FET",EET:"EET", CET:"CET",UTC:"UTC",GMT:"GMT",CVT:"CVT",GST:"GST",BRT:"BRT",NST:"NST",AST:"AST",EST:"EST",CST:"CST",MST:"MST",PST:"PST",AKST:"AKST",MIT:"MIT",HST:"HST",SST:"SST",BIT:"BIT",CHADT:"CHADT",NZDT:"NZDT",AEDT:"AEDT",ACDT:"ACDT",AZST:"AZST",IRDT:"IRDT",EEST:"EEST",CEST:"CEST",BST:"BST",PMDT:"PMDT",ADT:"ADT",NDT:"NDT",EDT:"EDT",CDT:"CDT",MDT:"MDT",PDT:"PDT",AKDT:"AKDT",HADT:"HADT"};Date.CultureStrings.lang="es-PA"; (function(){var f=Date,g=Date.CultureStrings?Date.CultureStrings.lang:null,c={},a=function(a,e){var b,h,f,m=e?e:g;if(Date.CultureStrings&&Date.CultureStrings[m]&&Date.CultureStrings[m][a])b=Date.CultureStrings[m][a];else switch(a){case "name":b="en-US";break;case "englishName":b="English (United States)";break;case "nativeName":b="English (United States)";break;case "twoDigitYearMax":b=2049;break;case "firstDayOfWeek":b=0;break;default:if(b=a,h=a.split("_"),f=h.length,1<f&&"/"!==a.charAt(0)&&(f=h[f- 1].toLowerCase(),"initial"===f||"abbr"===f))b=h[0]}"/"===a.charAt(0)&&(b=Date.CultureStrings&&Date.CultureStrings[m]&&Date.CultureStrings[m][a]?RegExp(Date.CultureStrings[m][a],"i"):RegExp(a.replace(RegExp("/","g"),""),"i"));c[a]=a;return b},b=function(a){a=Date.Config.i18n+a+".js";var e=document.getElementsByTagName("head")[0]||document.documentElement,b=document.createElement("script");b.src=a;var h={done:function(){}};b.onload=b.onreadystatechange=function(){this.readyState&&"loaded"!==this.readyState&& "complete"!==this.readyState||(done=!0,h.done(),e.removeChild(b))};setTimeout(function(){e.insertBefore(b,e.firstChild)},0);return{done:function(a){h.done=function(){a&&a()}}}},e=function(){var e={name:a("name"),englishName:a("englishName"),nativeName:a("nativeName"),dayNames:[a("Sunday"),a("Monday"),a("Tuesday"),a("Wednesday"),a("Thursday"),a("Friday"),a("Saturday")],abbreviatedDayNames:[a("Sun"),a("Mon"),a("Tue"),a("Wed"),a("Thu"),a("Fri"),a("Sat")],shortestDayNames:[a("Su"),a("Mo"),a("Tu"),a("We"), a("Th"),a("Fr"),a("Sa")],firstLetterDayNames:[a("S_Sun_Initial"),a("M_Mon_Initial"),a("T_Tues_Initial"),a("W_Wed_Initial"),a("T_Thu_Initial"),a("F_Fri_Initial"),a("S_Sat_Initial")],monthNames:[a("January"),a("February"),a("March"),a("April"),a("May"),a("June"),a("July"),a("August"),a("September"),a("October"),a("November"),a("December")],abbreviatedMonthNames:[a("Jan_Abbr"),a("Feb_Abbr"),a("Mar_Abbr"),a("Apr_Abbr"),a("May_Abbr"),a("Jun_Abbr"),a("Jul_Abbr"),a("Aug_Abbr"),a("Sep_Abbr"),a("Oct_Abbr"), a("Nov_Abbr"),a("Dec_Abbr")],amDesignator:a("AM"),pmDesignator:a("PM"),firstDayOfWeek:a("firstDayOfWeek"),twoDigitYearMax:a("twoDigitYearMax"),dateElementOrder:a("mdy"),formatPatterns:{shortDate:a("M/d/yyyy"),longDate:a("dddd, MMMM dd, yyyy"),shortTime:a("h:mm tt"),longTime:a("h:mm:ss tt"),fullDateTime:a("dddd, MMMM dd, yyyy h:mm:ss tt"),sortableDateTime:a("yyyy-MM-ddTHH:mm:ss"),universalSortableDateTime:a("yyyy-MM-dd HH:mm:ssZ"),rfc1123:a("ddd, dd MMM yyyy HH:mm:ss"),monthDay:a("MMMM dd"),yearMonth:a("MMMM, yyyy")}, regexPatterns:{inTheMorning:a("/( in the )(morn(ing)?)\\b/"),thisMorning:a("/(this )(morn(ing)?)\\b/"),amThisMorning:a("/(\b\\d(am)? )(this )(morn(ing)?)/"),inTheEvening:a("/( in the )(even(ing)?)\\b/"),thisEvening:a("/(this )(even(ing)?)\\b/"),pmThisEvening:a("/(\b\\d(pm)? )(this )(even(ing)?)/"),jan:a("/jan(uary)?/"),feb:a("/feb(ruary)?/"),mar:a("/mar(ch)?/"),apr:a("/apr(il)?/"),may:a("/may/"),jun:a("/jun(e)?/"),jul:a("/jul(y)?/"),aug:a("/aug(ust)?/"),sep:a("/sep(t(ember)?)?/"),oct:a("/oct(ober)?/"), nov:a("/nov(ember)?/"),dec:a("/dec(ember)?/"),sun:a("/^su(n(day)?)?/"),mon:a("/^mo(n(day)?)?/"),tue:a("/^tu(e(s(day)?)?)?/"),wed:a("/^we(d(nesday)?)?/"),thu:a("/^th(u(r(s(day)?)?)?)?/"),fri:a("/fr(i(day)?)?/"),sat:a("/^sa(t(urday)?)?/"),future:a("/^next/"),past:a("/last|past|prev(ious)?/"),add:a("/^(\\+|aft(er)?|from|hence)/"),subtract:a("/^(\\-|bef(ore)?|ago)/"),yesterday:a("/^yes(terday)?/"),today:a("/^t(od(ay)?)?/"),tomorrow:a("/^tom(orrow)?/"),now:a("/^n(ow)?/"),millisecond:a("/^ms|milli(second)?s?/"), second:a("/^sec(ond)?s?/"),minute:a("/^mn|min(ute)?s?/"),hour:a("/^h(our)?s?/"),week:a("/^w(eek)?s?/"),month:a("/^m(onth)?s?/"),day:a("/^d(ay)?s?/"),year:a("/^y(ear)?s?/"),shortMeridian:a("/^(a|p)/"),longMeridian:a("/^(a\\.?m?\\.?|p\\.?m?\\.?)/"),timezone:a("/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/"),ordinalSuffix:a("/^\\s*(st|nd|rd|th)/"),timeContext:a("/^\\s*(\\:|a(?!u|p)|p)/")},timezones:[],abbreviatedTimeZoneDST:{},abbreviatedTimeZoneStandard:{}};e.abbreviatedTimeZoneDST[a("CHADT")]= "+1345";e.abbreviatedTimeZoneDST[a("NZDT")]="+1300";e.abbreviatedTimeZoneDST[a("AEDT")]="+1100";e.abbreviatedTimeZoneDST[a("ACDT")]="+1030";e.abbreviatedTimeZoneDST[a("AZST")]="+0500";e.abbreviatedTimeZoneDST[a("IRDT")]="+0430";e.abbreviatedTimeZoneDST[a("EEST")]="+0300";e.abbreviatedTimeZoneDST[a("CEST")]="+0200";e.abbreviatedTimeZoneDST[a("BST")]="+0100";e.abbreviatedTimeZoneDST[a("PMDT")]="-0200";e.abbreviatedTimeZoneDST[a("ADT")]="-0300";e.abbreviatedTimeZoneDST[a("NDT")]="-0230";e.abbreviatedTimeZoneDST[a("EDT")]= "-0400";e.abbreviatedTimeZoneDST[a("CDT")]="-0500";e.abbreviatedTimeZoneDST[a("MDT")]="-0600";e.abbreviatedTimeZoneDST[a("PDT")]="-0700";e.abbreviatedTimeZoneDST[a("AKDT")]="-0800";e.abbreviatedTimeZoneDST[a("HADT")]="-0900";e.abbreviatedTimeZoneStandard[a("LINT")]="+1400";e.abbreviatedTimeZoneStandard[a("TOT")]="+1300";e.abbreviatedTimeZoneStandard[a("CHAST")]="+1245";e.abbreviatedTimeZoneStandard[a("NZST")]="+1200";e.abbreviatedTimeZoneStandard[a("NFT")]="+1130";e.abbreviatedTimeZoneStandard[a("SBT")]= "+1100";e.abbreviatedTimeZoneStandard[a("AEST")]="+1000";e.abbreviatedTimeZoneStandard[a("ACST")]="+0930";e.abbreviatedTimeZoneStandard[a("JST")]="+0900";e.abbreviatedTimeZoneStandard[a("CWST")]="+0845";e.abbreviatedTimeZoneStandard[a("CT")]="+0800";e.abbreviatedTimeZoneStandard[a("ICT")]="+0700";e.abbreviatedTimeZoneStandard[a("MMT")]="+0630";e.abbreviatedTimeZoneStandard[a("BST")]="+0600";e.abbreviatedTimeZoneStandard[a("NPT")]="+0545";e.abbreviatedTimeZoneStandard[a("IST")]="+0530";e.abbreviatedTimeZoneStandard[a("PKT")]= "+0500";e.abbreviatedTimeZoneStandard[a("AFT")]="+0430";e.abbreviatedTimeZoneStandard[a("MSK")]="+0400";e.abbreviatedTimeZoneStandard[a("IRST")]="+0330";e.abbreviatedTimeZoneStandard[a("FET")]="+0300";e.abbreviatedTimeZoneStandard[a("EET")]="+0200";e.abbreviatedTimeZoneStandard[a("CET")]="+0100";e.abbreviatedTimeZoneStandard[a("GMT")]="+0000";e.abbreviatedTimeZoneStandard[a("UTC")]="+0000";e.abbreviatedTimeZoneStandard[a("CVT")]="-0100";e.abbreviatedTimeZoneStandard[a("GST")]="-0200";e.abbreviatedTimeZoneStandard[a("BRT")]= "-0300";e.abbreviatedTimeZoneStandard[a("NST")]="-0330";e.abbreviatedTimeZoneStandard[a("AST")]="-0400";e.abbreviatedTimeZoneStandard[a("EST")]="-0500";e.abbreviatedTimeZoneStandard[a("CST")]="-0600";e.abbreviatedTimeZoneStandard[a("MST")]="-0700";e.abbreviatedTimeZoneStandard[a("PST")]="-0800";e.abbreviatedTimeZoneStandard[a("AKST")]="-0900";e.abbreviatedTimeZoneStandard[a("MIT")]="-0930";e.abbreviatedTimeZoneStandard[a("HST")]="-1000";e.abbreviatedTimeZoneStandard[a("SST")]="-1100";e.abbreviatedTimeZoneStandard[a("BIT")]= "-1200";for(var d in e.abbreviatedTimeZoneStandard)e.abbreviatedTimeZoneStandard.hasOwnProperty(d)&&e.timezones.push({name:d,offset:e.abbreviatedTimeZoneStandard[d]});for(d in e.abbreviatedTimeZoneDST)e.abbreviatedTimeZoneDST.hasOwnProperty(d)&&e.timezones.push({name:d,offset:e.abbreviatedTimeZoneDST[d],dst:!0});return e};f.i18n={__:function(e,d){return a(e,d)},currentLanguage:function(){return g||"en-US"},setLanguage:function(a,d){if(d||"en-US"===a||Date.CultureStrings&&Date.CultureStrings[a])g= a,Date.CultureStrings.lang=a,Date.CultureInfo=e();else if(!Date.CultureStrings||!Date.CultureStrings[a])if("undefined"!==typeof exports&&this.exports!==exports)try{require("../i18n/"+a+".js"),g=a,Date.CultureStrings.lang=a,Date.CultureInfo=e()}catch(c){throw Error("The DateJS IETF language tag '"+a+"' could not be loaded by Node. It likely does not exist.");}else Date.Config&&Date.Config.i18n?b(a).done(function(){g=a;Date.CultureStrings.lang=a;Date.CultureInfo=e()}):Date.console.error("The DateJS IETF language tag '"+ a+"' is not available and has not been loaded.")},getLoggedKeys:function(){return c},updateCultureInfo:function(){Date.CultureInfo=e()}};f.i18n.updateCultureInfo()})(); (function(){var f=Date,g=f.prototype,c=function(a,b){b||(b=2);return("000"+a).slice(-1*b)};f.console="undefined"!==typeof window&&"undefined"!==typeof window.console&&"undefined"!==typeof window.console.log?console:{log:function(){},error:function(){}};f.Config={};f.initOverloads=function(){f.now?f._now||(f._now=f.now):f._now=function(){return(new Date).getTime()};f.now=function(a){return a?f.present():f._now()};g.toISOString||(g.toISOString=function(){return this.getUTCFullYear()+"-"+c(this.getUTCMonth()+ 1)+"-"+c(this.getUTCDate())+"T"+c(this.getUTCHours())+":"+c(this.getUTCMinutes())+":"+c(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1E3).toFixed(3)).slice(2,5)+"Z"});void 0===g._toString&&(g._toString=g.toString)};f.initOverloads();g.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this};g.setTimeToNow=function(){var a=new Date;this.setHours(a.getHours());this.setMinutes(a.getMinutes());this.setSeconds(a.getSeconds());this.setMilliseconds(a.getMilliseconds()); return this};f.today=function(){return(new Date).clearTime()};f.present=function(){return new Date};f.compare=function(a,b){if(isNaN(a)||isNaN(b))throw Error(a+" - "+b);if(a instanceof Date&&b instanceof Date)return a<b?-1:a>b?1:0;throw new TypeError(a+" - "+b);};f.equals=function(a,b){return 0===a.compareTo(b)};f.getDayName=function(a){return Date.CultureInfo.dayNames[a]};f.getDayNumberFromName=function(a){var b=Date.CultureInfo.dayNames,d=Date.CultureInfo.abbreviatedDayNames,c=Date.CultureInfo.shortestDayNames; a=a.toLowerCase();for(var h=0;h<b.length;h++)if(b[h].toLowerCase()===a||d[h].toLowerCase()===a||c[h].toLowerCase()===a)return h;return-1};f.getMonthNumberFromName=function(a){var b=Date.CultureInfo.monthNames,d=Date.CultureInfo.abbreviatedMonthNames;a=a.toLowerCase();for(var c=0;c<b.length;c++)if(b[c].toLowerCase()===a||d[c].toLowerCase()===a)return c;return-1};f.getMonthName=function(a){return Date.CultureInfo.monthNames[a]};f.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};f.getDaysInMonth= function(a,b){!b&&f.validateMonth(a)&&(b=a,a=Date.today().getFullYear());return[31,f.isLeapYear(a)?29:28,31,30,31,30,31,31,30,31,30,31][b]};f.getTimezoneAbbreviation=function(a,b){var d,c=b?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard;for(d in c)if(c.hasOwnProperty(d)&&c[d]===a)return d;return null};f.getTimezoneOffset=function(a,b){var d,c=[],h=Date.CultureInfo.timezones;a||(a=(new Date).getTimezone());for(d=0;d<h.length;d++)h[d].name===a.toUpperCase()&&c.push(d); if(!h[c[0]])return null;if(1!==c.length&&b)for(d=0;d<c.length;d++){if(h[c[d]].dst)return h[c[d]].offset}else return h[c[0]].offset};f.getQuarter=function(a){a=a||new Date;return[1,2,3,4][Math.floor(a.getMonth()/3)]};f.getDaysLeftInQuarter=function(a){a=a||new Date;var b=new Date(a);b.setMonth(b.getMonth()+3-b.getMonth()%3,0);return Math.floor((b-a)/864E5)};g.clone=function(){return new Date(this.getTime())};g.compareTo=function(a){return Date.compare(this,a)};g.equals=function(a){return Date.equals(this, void 0!==a?a:new Date)};g.between=function(a,b){return this.getTime()>=a.getTime()&&this.getTime()<=b.getTime()};g.isAfter=function(a){return 1===this.compareTo(a||new Date)};g.isBefore=function(a){return-1===this.compareTo(a||new Date)};g.isToday=g.isSameDay=function(a){return this.clone().clearTime().equals((a||new Date).clone().clearTime())};g.addMilliseconds=function(a){if(!a)return this;this.setTime(this.getTime()+1*a);return this};g.addSeconds=function(a){return a?this.addMilliseconds(1E3*a): this};g.addMinutes=function(a){return a?this.addMilliseconds(6E4*a):this};g.addHours=function(a){return a?this.addMilliseconds(36E5*a):this};g.addDays=function(a){if(!a)return this;this.setDate(this.getDate()+1*a);return this};g.addWeekdays=function(a){if(!a)return this;var b=this.getDay(),d=Math.ceil(Math.abs(a)/7);(0===b||6===b)&&0<a&&(this.next().monday(),this.addDays(-1));if(0>a){for(;0>a;)this.addDays(-1),b=this.getDay(),0!==b&&6!==b&&a++;return this}if(5<a||6-b<=a)a+=2*d;return this.addDays(a)}; g.addWeeks=function(a){return a?this.addDays(7*a):this};g.addMonths=function(a){if(!a)return this;var b=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+1*a);this.setDate(Math.min(b,f.getDaysInMonth(this.getFullYear(),this.getMonth())));return this};g.addQuarters=function(a){return a?this.addMonths(3*a):this};g.addYears=function(a){return a?this.addMonths(12*a):this};g.add=function(a){if("number"===typeof a)return this._orient=a,this;a.day&&0!==a.day-this.getDate()&&this.setDate(a.day); a.milliseconds&&this.addMilliseconds(a.milliseconds);a.seconds&&this.addSeconds(a.seconds);a.minutes&&this.addMinutes(a.minutes);a.hours&&this.addHours(a.hours);a.weeks&&this.addWeeks(a.weeks);a.months&&this.addMonths(a.months);a.years&&this.addYears(a.years);a.days&&this.addDays(a.days);return this};g.getWeek=function(a){var b=new Date(this.valueOf());a?(b.addMinutes(b.getTimezoneOffset()),a=b.clone()):a=this;a=(a.getDay()+6)%7;b.setDate(b.getDate()-a+3);a=b.valueOf();b.setMonth(0,1);4!==b.getDay()&& b.setMonth(0,1+(4-b.getDay()+7)%7);return 1+Math.ceil((a-b)/6048E5)};g.getISOWeek=function(){return c(this.getWeek(!0))};g.setWeek=function(a){return 0===a-this.getWeek()?1!==this.getDay()?this.moveToDayOfWeek(1,1<this.getDay()?-1:1):this:this.moveToDayOfWeek(1,1<this.getDay()?-1:1).addWeeks(a-this.getWeek())};g.setQuarter=function(a){a=Math.abs(3*(a-1)+1);return this.setMonth(a,1)};g.getQuarter=function(){return Date.getQuarter(this)};g.getDaysLeftInQuarter=function(){return Date.getDaysLeftInQuarter(this)}; var a=function(a,b,d,c){if("undefined"===typeof a)return!1;if("number"!==typeof a)throw new TypeError(a+" is not a Number.");return a<b||a>d?!1:!0};f.validateMillisecond=function(e){return a(e,0,999,"millisecond")};f.validateSecond=function(e){return a(e,0,59,"second")};f.validateMinute=function(e){return a(e,0,59,"minute")};f.validateHour=function(e){return a(e,0,23,"hour")};f.validateDay=function(e,b,d){return a(e,1,f.getDaysInMonth(b,d),"day")};f.validateWeek=function(e){return a(e,0,53,"week")}; f.validateMonth=function(e){return a(e,0,11,"month")};f.validateYear=function(e){return a(e,-271822,275760,"year")};g.set=function(a){f.validateMillisecond(a.millisecond)&&this.addMilliseconds(a.millisecond-this.getMilliseconds());f.validateSecond(a.second)&&this.addSeconds(a.second-this.getSeconds());f.validateMinute(a.minute)&&this.addMinutes(a.minute-this.getMinutes());f.validateHour(a.hour)&&this.addHours(a.hour-this.getHours());f.validateMonth(a.month)&&this.addMonths(a.month-this.getMonth()); f.validateYear(a.year)&&this.addYears(a.year-this.getFullYear());f.validateDay(a.day,this.getFullYear(),this.getMonth())&&this.addDays(a.day-this.getDate());a.timezone&&this.setTimezone(a.timezone);a.timezoneOffset&&this.setTimezoneOffset(a.timezoneOffset);a.week&&f.validateWeek(a.week)&&this.setWeek(a.week);return this};g.moveToFirstDayOfMonth=function(){return this.set({day:1})};g.moveToLastDayOfMonth=function(){return this.set({day:f.getDaysInMonth(this.getFullYear(),this.getMonth())})};g.moveToNthOccurrence= function(a,b){if("Weekday"===a){if(0<b)this.moveToFirstDayOfMonth(),this.is().weekday()&&(b-=1);else if(0>b)this.moveToLastDayOfMonth(),this.is().weekday()&&(b+=1);else return this;return this.addWeekdays(b)}var d=0;if(0<b)d=b-1;else if(-1===b)return this.moveToLastDayOfMonth(),this.getDay()!==a&&this.moveToDayOfWeek(a,-1),this;return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(a,1).addWeeks(d)};g.moveToDayOfWeek=function(a,b){var d=(a-this.getDay()+7*(b||1))%7;return this.addDays(0=== d?d+7*(b||1):d)};g.moveToMonth=function(a,b){var d=(a-this.getMonth()+12*(b||1))%12;return this.addMonths(0===d?d+12*(b||1):d)};g.getOrdinate=function(){var a=this.getDate();return b(a)};g.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/864E5)+1};g.getTimezone=function(){return f.getTimezoneAbbreviation(this.getUTCOffset(),this.isDaylightSavingTime())};g.setTimezoneOffset=function(a){var b=this.getTimezoneOffset();return(a=-6*Number(a)/10)|| 0===a?this.addMinutes(a-b):this};g.setTimezone=function(a){return this.setTimezoneOffset(f.getTimezoneOffset(a))};g.hasDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset()};g.isDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==this.getTimezoneOffset()};g.getUTCOffset=function(a){a=-10*(a||this.getTimezoneOffset())/6;if(0>a)return a=(a-1E4).toString(),a.charAt(0)+ a.substr(2);a=(a+1E4).toString();return"+"+a.substr(1)};g.getElapsed=function(a){return(a||new Date)-this};var b=function(a){switch(1*a){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}};g.toString=function(a,f){var d=this;if(!f&&a&&1===a.length){var g,h=Date.CultureInfo.formatPatterns;d.t=d.toString;switch(a){case "d":return d.t(h.shortDate);case "D":return d.t(h.longDate);case "F":return d.t(h.fullDateTime);case "m":return d.t(h.monthDay); case "r":case "R":return g=d.clone().addMinutes(d.getTimezoneOffset()),g.toString(h.rfc1123)+" GMT";case "s":return d.t(h.sortableDateTime);case "t":return d.t(h.shortTime);case "T":return d.t(h.longTime);case "u":return g=d.clone().addMinutes(d.getTimezoneOffset()),g.toString(h.universalSortableDateTime);case "y":return d.t(h.yearMonth)}}return a?a.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g,function(a){if("\\"===a.charAt(0))return a.replace("\\",""); d.h=d.getHours;switch(a){case "hh":return c(13>d.h()?0===d.h()?12:d.h():d.h()-12);case "h":return 13>d.h()?0===d.h()?12:d.h():d.h()-12;case "HH":return c(d.h());case "H":return d.h();case "mm":return c(d.getMinutes());case "m":return d.getMinutes();case "ss":return c(d.getSeconds());case "s":return d.getSeconds();case "yyyy":return c(d.getFullYear(),4);case "yy":return c(d.getFullYear());case "dddd":return Date.CultureInfo.dayNames[d.getDay()];case "ddd":return Date.CultureInfo.abbreviatedDayNames[d.getDay()]; case "dd":return c(d.getDate());case "d":return d.getDate();case "MMMM":return Date.CultureInfo.monthNames[d.getMonth()];case "MMM":return Date.CultureInfo.abbreviatedMonthNames[d.getMonth()];case "MM":return c(d.getMonth()+1);case "M":return d.getMonth()+1;case "t":return 12>d.h()?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case "tt":return 12>d.h()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case "S":return b(d.getDate());case "W":return d.getWeek(); case "WW":return d.getISOWeek();case "Q":return"Q"+d.getQuarter();case "q":return String(d.getQuarter());default:return a}}).replace(/\[|\]/g,""):this._toString()}})(); (function(){Date.Parsing={Exception:function(a){this.message="Parse error at '"+a.substring(0,10)+" ...'"}};var f=Date.Parsing,g=[0,31,59,90,120,151,181,212,243,273,304,334],c=[0,31,60,91,121,152,182,213,244,274,305,335];f.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};f.processTimeObject=function(a){var b,e;b=new Date;e=f.isLeapYear(a.year)?c:g;a.hours=a.hours?a.hours:0;a.minutes=a.minutes?a.minutes:0;a.seconds=a.seconds?a.seconds:0;a.milliseconds=a.milliseconds?a.milliseconds:0;a.year|| (a.year=b.getFullYear());if(a.month||!a.week&&!a.dayOfYear)a.month=a.month?a.month:0,a.day=a.day?a.day:1,a.dayOfYear=e[a.month]+a.day;else for(a.dayOfYear||(a.weekDay=a.weekDay||0===a.weekDay?a.weekDay:1,b=new Date(a.year,0,4),b=0===b.getDay()?7:b.getDay(),a.dayOfYear=7*a.week+(0===a.weekDay?7:a.weekDay)-(b+3)),b=0;b<=e.length;b++)if(a.dayOfYear<e[b]||b===e.length){a.day=a.day?a.day:a.dayOfYear-e[b-1];break}else a.month=b;e=new Date(a.year,a.month,a.day,a.hours,a.minutes,a.seconds,a.milliseconds); a.zone&&("Z"===a.zone.toUpperCase()||0===a.zone_hours&&0===a.zone_minutes?b=-e.getTimezoneOffset():(b=60*a.zone_hours+(a.zone_minutes?a.zone_minutes:0),"+"===a.zone_sign&&(b*=-1),b-=e.getTimezoneOffset()),e.setMinutes(e.getMinutes()+b));return e};f.ISO={regex:/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/, parse:function(a){a=a.match(this.regex);if(!a||!a.length)return null;var b={year:a[1]?Number(a[1]):a[1],month:a[5]?Number(a[5])-1:a[5],day:a[7]?Number(a[7]):a[7],week:a[8]?Number(a[8]):a[8],weekDay:a[9]?7===Math.abs(Number(a[9]))?0:Math.abs(Number(a[9])):a[9],dayOfYear:a[10]?Number(a[10]):a[10],hours:a[15]?Number(a[15]):a[15],minutes:a[16]?Number(a[16].replace(":","")):a[16],seconds:a[19]?Math.floor(Number(a[19].replace(":","").replace(",","."))):a[19],milliseconds:a[20]?1E3*Number(a[20].replace(",", ".")):a[20],zone:a[21],zone_sign:a[22],zone_hours:a[23]&&"undefined"!==typeof a[23]?Number(a[23]):a[23],zone_minutes:a[24]&&"undefined"!==typeof a[23]?Number(a[24]):a[24]};a[18]&&((a[18]=60*Number(a[18].replace(",",".")),b.minutes)?b.seconds||(b.seconds=a[18]):b.minutes=a[18]);return b.year&&(b.year||b.month||b.day||b.week||b.dayOfYear)?f.processTimeObject(b):null}};f.Numeric={isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},regex:/\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i, parse:function(a){var b,e={},c=Date.CultureInfo.dateElementOrder.split("");if(!this.isNumeric(a)||"+"===a[0]&&"-"===a[0])return null;if(5>a.length)return e.year=a,f.processTimeObject(e);a=a.match(this.regex);if(!a||!a.length)return null;for(b=0;b<c.length;b++)switch(c[b]){case "d":e.day=a[b+1];break;case "m":e.month=a[b+1]-1;break;case "y":e.year=a[b+1]}return f.processTimeObject(e)}};f.Normalizer={parse:function(a){var b=Date.CultureInfo.regexPatterns,e=Date.i18n.__;a=a.replace(b.jan.source,"January"); a=a.replace(b.feb,"February");a=a.replace(b.mar,"March");a=a.replace(b.apr,"April");a=a.replace(b.may,"May");a=a.replace(b.jun,"June");a=a.replace(b.jul,"July");a=a.replace(b.aug,"August");a=a.replace(b.sep,"September");a=a.replace(b.oct,"October");a=a.replace(b.nov,"November");a=a.replace(b.dec,"December");a=a.replace(b.tomorrow,Date.today().addDays(1).toString("d"));a=a.replace(b.yesterday,Date.today().addDays(-1).toString("d"));a=a.replace(/\bat\b/gi,"");a=a.replace(/\s{2,}/," ");a=a.replace(RegExp("(\\b\\d\\d?("+ e("AM")+"|"+e("PM")+")? )("+b.tomorrow.source.slice(1)+")","i"),function(a,b,e,d,c){return Date.today().addDays(1).toString("d")+" "+b});a=a.replace(RegExp("(("+b.past.source+")\\s("+b.mon.source+"))"),Date.today().last().monday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.tue.source+"))"),Date.today().last().tuesday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.wed.source+"))"),Date.today().last().wednesday().toString("d"));a=a.replace(RegExp("(("+b.past.source+ ")\\s("+b.thu.source+"))"),Date.today().last().thursday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.fri.source+"))"),Date.today().last().friday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.sat.source+"))"),Date.today().last().saturday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.sun.source+"))"),Date.today().last().sunday().toString("d"));a=a.replace(b.amThisMorning,function(a,b){return b});a=a.replace(b.inTheMorning,"am");a=a.replace(b.thisMorning, "9am");a=a.replace(b.amThisEvening,function(a,b){return b});a=a.replace(b.inTheEvening,"pm");a=a.replace(b.thisEvening,"7pm");try{var c=a.split(/([\s\-\.\,\/\x27]+)/);3===c.length&&f.Numeric.isNumeric(c[0])&&f.Numeric.isNumeric(c[2])&&4<=c[2].length&&"d"===Date.CultureInfo.dateElementOrder[0]&&(a="1/"+c[0]+"/"+c[2])}catch(d){}return a}}})(); (function(){for(var f=Date.Parsing,g=f.Operators={rtoken:function(a){return function(b){var d=b.match(a);if(d)return[d[0],b.substring(d[0].length)];throw new f.Exception(b);}},token:function(a){return function(a){return g.rtoken(RegExp("^s*"+a+"s*"))(a)}},stoken:function(a){return g.rtoken(RegExp("^"+a))},until:function(a){return function(b){for(var d=[],c=null;b.length;){try{c=a.call(this,b)}catch(h){d.push(c[0]);b=c[1];continue}break}return[d,b]}},many:function(a){return function(b){for(var d=[], c=null;b.length;){try{c=a.call(this,b)}catch(h){break}d.push(c[0]);b=c[1]}return[d,b]}},optional:function(a){return function(b){var d=null;try{d=a.call(this,b)}catch(c){return[null,b]}return[d[0],d[1]]}},not:function(a){return function(b){try{a.call(this,b)}catch(d){return[null,b]}throw new f.Exception(b);}},ignore:function(a){return a?function(b){var d=null,d=a.call(this,b);return[null,d[1]]}:null},product:function(){for(var a=arguments[0],b=Array.prototype.slice.call(arguments,1),d=[],c=0;c<a.length;c++)d.push(g.each(a[c], b));return d},cache:function(a){var b={},d=null;return function(c){try{d=b[c]=b[c]||a.call(this,c)}catch(h){d=b[c]=h}if(d instanceof f.Exception)throw d;return d}},any:function(){var a=arguments;return function(b){for(var d=null,c=0;c<a.length;c++)if(null!=a[c]){try{d=a[c].call(this,b)}catch(h){d=null}if(d)return d}throw new f.Exception(b);}},each:function(){var a=arguments;return function(b){for(var d=[],c=null,h=0;h<a.length;h++)if(null!=a[h]){try{c=a[h].call(this,b)}catch(g){throw new f.Exception(b); }d.push(c[0]);b=c[1]}return[d,b]}},all:function(){var a=a;return a.each(a.optional(arguments))},sequence:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return 1==a.length?a[0]:function(c){for(var h=null,g=null,m=[],n=0;n<a.length;n++){try{h=a[n].call(this,c)}catch(p){break}m.push(h[0]);try{g=b.call(this,h[1])}catch(s){g=null;break}c=g[1]}if(!h)throw new f.Exception(c);if(g)throw new f.Exception(g[1]);if(d)try{h=d.call(this,h[1])}catch(t){throw new f.Exception(h[1]);}return[m,h?h[1]:c]}},between:function(a, b,d){d=d||a;var c=g.each(g.ignore(a),b,g.ignore(d));return function(a){a=c.call(this,a);return[[a[0][0],r[0][2]],a[1]]}},list:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return a instanceof Array?g.each(g.product(a.slice(0,-1),g.ignore(b)),a.slice(-1),g.ignore(d)):g.each(g.many(g.each(a,g.ignore(b))),px,g.ignore(d))},set:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return function(c){for(var h=null,k=h=null,m=null,n=[[],c],p=!1,s=0;s<a.length;s++){h=k=null;p=1==a.length;try{h=a[s].call(this, c)}catch(t){continue}m=[[h[0]],h[1]];if(0<h[1].length&&!p)try{k=b.call(this,h[1])}catch(u){p=!0}else p=!0;p||0!==k[1].length||(p=!0);if(!p){h=[];for(p=0;p<a.length;p++)s!=p&&h.push(a[p]);h=g.set(h,b).call(this,k[1]);0<h[0].length&&(m[0]=m[0].concat(h[0]),m[1]=h[1])}m[1].length<n[1].length&&(n=m);if(0===n[1].length)break}if(0===n[0].length)return n;if(d){try{k=d.call(this,n[1])}catch(v){throw new f.Exception(n[1]);}n[1]=k[1]}return n}},forward:function(a,b){return function(d){return a[b].call(this, d)}},replace:function(a,b){return function(d){d=a.call(this,d);return[b,d[1]]}},process:function(a,b){return function(d){d=a.call(this,d);return[b.call(this,d[0]),d[1]]}},min:function(a,b){return function(d){var c=b.call(this,d);if(c[0].length<a)throw new f.Exception(d);return c}}},c=function(a){return function(){var b=null,d=[],c;1<arguments.length?b=Array.prototype.slice.call(arguments):arguments[0]instanceof Array&&(b=arguments[0]);if(b){if(c=b.shift(),0<c.length)return b.unshift(c[void 0]),d.push(a.apply(null, b)),b.shift(),d}else return a.apply(null,arguments)}},a="optional not ignore cache".split(/\s/),b=0;b<a.length;b++)g[a[b]]=c(g[a[b]]);c=function(a){return function(){return arguments[0]instanceof Array?a.apply(null,arguments[0]):a.apply(null,arguments)}};a="each any all".split(/\s/);for(b=0;b<a.length;b++)g[a[b]]=c(g[a[b]])})(); (function(){var f=Date,g=function(a){for(var b=[],c=0;c<a.length;c++)a[c]instanceof Array?b=b.concat(g(a[c])):a[c]&&b.push(a[c]);return b};f.Grammar={};f.Translator={hour:function(a){return function(){this.hour=Number(a)}},minute:function(a){return function(){this.minute=Number(a)}},second:function(a){return function(){this.second=Number(a)}},secondAndMillisecond:function(a){return function(){var b=a.match(/^([0-5][0-9])\.([0-9]{1,3})/);this.second=Number(b[1]);this.millisecond=Number(b[2])}},meridian:function(a){return function(){this.meridian= a.slice(0,1).toLowerCase()}},timezone:function(a){return function(){var b=a.replace(/[^\d\+\-]/g,"");b.length?this.timezoneOffset=Number(b):this.timezone=a.toLowerCase()}},day:function(a){var b=a[0];return function(){this.day=Number(b.match(/\d+/)[0]);if(1>this.day)throw"invalid day";}},month:function(a){return function(){this.month=3===a.length?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(a)/4:Number(a)-1;if(0>this.month)throw"invalid month";}},year:function(a){return function(){var b= Number(a);this.year=2<a.length?b:b+(b+2E3<Date.CultureInfo.twoDigitYearMax?2E3:1900)}},rday:function(a){return function(){switch(a){case "yesterday":this.days=-1;break;case "tomorrow":this.days=1;break;case "today":this.days=0;break;case "now":this.days=0,this.now=!0}}},finishExact:function(a){a=a instanceof Array?a:[a];for(var b=0;b<a.length;b++)a[b]&&a[b].call(this);a=new Date;!this.hour&&!this.minute||this.month||this.year||this.day||(this.day=a.getDate());this.year||(this.year=a.getFullYear()); this.month||0===this.month||(this.month=a.getMonth());this.day||(this.day=1);this.hour||(this.hour=0);this.minute||(this.minute=0);this.second||(this.second=0);this.millisecond||(this.millisecond=0);if(this.meridian&&(this.hour||0===this.hour)){if("a"==this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"==this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"==this.meridian&&12>this.hour?this.hour+=12: "a"==this.meridian&&12==this.hour&&(this.hour=0)}if(this.day>f.getDaysInMonth(this.year,this.month))throw new RangeError(this.day+" is not a valid value for days.");a=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);100>this.year&&a.setFullYear(this.year);this.timezone?a.set({timezone:this.timezone}):this.timezoneOffset&&a.set({timezoneOffset:this.timezoneOffset});return a},finish:function(a){a=a instanceof Array?g(a):[a];if(0===a.length)return null;for(var b= 0;b<a.length;b++)"function"==typeof a[b]&&a[b].call(this);a=f.today();if(!this.now||this.unit||this.operator)this.now&&(a=new Date);else return new Date;var b=!!(this.days&&null!==this.days||this.orient||this.operator),c,d,e;e="past"==this.orient||"subtract"==this.operator?-1:1;this.now||-1=="hour minute second".indexOf(this.unit)||a.setTimeToNow();this.month&&"week"==this.unit&&(this.value=this.month+1,delete this.month,delete this.day);!this.month&&0!==this.month||-1=="year day hour minute second".indexOf(this.unit)|| (this.value||(this.value=this.month+1),this.month=null,b=!0);b||!this.weekday||this.day||this.days||(c=Date[this.weekday](),this.day=c.getDate(),this.month||(this.month=c.getMonth()),this.year=c.getFullYear());b&&this.weekday&&"month"!=this.unit&&"week"!=this.unit&&(this.unit="day",c=f.getDayNumberFromName(this.weekday)-a.getDay(),d=7,this.days=c?(c+e*d)%d:e*d);this.month&&"day"==this.unit&&this.operator&&(this.value||(this.value=this.month+1),this.month=null);null!=this.value&&null!=this.month&& null!=this.year&&(this.day=1*this.value);this.month&&!this.day&&this.value&&(a.set({day:1*this.value}),b||(this.day=1*this.value));this.month||!this.value||"month"!=this.unit||this.now||(this.month=this.value,b=!0);b&&(this.month||0===this.month)&&"year"!=this.unit&&(this.unit="month",c=this.month-a.getMonth(),d=12,this.months=c?(c+e*d)%d:e*d,this.month=null);this.unit||(this.unit="day");if(!this.value&&this.operator&&null!==this.operator&&this[this.unit+"s"]&&null!==this[this.unit+"s"])this[this.unit+ "s"]=this[this.unit+"s"]+("add"==this.operator?1:-1)+(this.value||0)*e;else if(null==this[this.unit+"s"]||null!=this.operator)this.value||(this.value=1),this[this.unit+"s"]=this.value*e;if(this.meridian&&(this.hour||0===this.hour)){if("a"==this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"==this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"==this.meridian&&12>this.hour?this.hour+=12:"a"==this.meridian&& 12==this.hour&&(this.hour=0)}!this.weekday||"week"===this.unit||this.day||this.days||(c=Date[this.weekday](),this.day=c.getDate(),c.getMonth()!==a.getMonth()&&(this.month=c.getMonth()));!this.month&&0!==this.month||this.day||(this.day=1);if(!this.orient&&!this.operator&&"week"==this.unit&&this.value&&!this.day&&!this.month)return Date.today().setWeek(this.value);if("week"==this.unit&&this.weeks&&!this.day&&!this.month)return a=Date[this.weekday?this.weekday:"today"]().addWeeks(this.weeks),this.now&& a.setTimeToNow(),a;b&&this.timezone&&this.day&&this.days&&(this.day=this.days);return b?a.add(this):a.set(this)}};var c=f.Parsing.Operators,a=f.Grammar,b=f.Translator,e;a.datePartDelimiter=c.rtoken(/^([\s\-\.\,\/\x27]+)/);a.timePartDelimiter=c.stoken(":");a.whiteSpace=c.rtoken(/^\s*/);a.generalDelimiter=c.rtoken(/^(([\s\,]|at|@|on)+)/);var q={};a.ctoken=function(a){var b=q[a];if(!b){for(var b=Date.CultureInfo.regexPatterns,d=a.split(/\s+/),e=[],f=0;f<d.length;f++)e.push(c.replace(c.rtoken(b[d[f]]), d[f]));b=q[a]=c.any.apply(null,e)}return b};a.ctoken2=function(a){return c.rtoken(Date.CultureInfo.regexPatterns[a])};a.h=c.cache(c.process(c.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),b.hour));a.hh=c.cache(c.process(c.rtoken(/^(0[0-9]|1[0-2])/),b.hour));a.H=c.cache(c.process(c.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),b.hour));a.HH=c.cache(c.process(c.rtoken(/^([0-1][0-9]|2[0-3])/),b.hour));a.m=c.cache(c.process(c.rtoken(/^([0-5][0-9]|[0-9])/),b.minute));a.mm=c.cache(c.process(c.rtoken(/^[0-5][0-9]/),b.minute)); a.s=c.cache(c.process(c.rtoken(/^([0-5][0-9]|[0-9])/),b.second));a.ss=c.cache(c.process(c.rtoken(/^[0-5][0-9]/),b.second));a["ss.s"]=c.cache(c.process(c.rtoken(/^[0-5][0-9]\.[0-9]{1,3}/),b.secondAndMillisecond));a.hms=c.cache(c.sequence([a.H,a.m,a.s],a.timePartDelimiter));a.t=c.cache(c.process(a.ctoken2("shortMeridian"),b.meridian));a.tt=c.cache(c.process(a.ctoken2("longMeridian"),b.meridian));a.z=c.cache(c.process(c.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),b.timezone));a.zz=c.cache(c.process(c.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/), b.timezone));a.zzz=c.cache(c.process(a.ctoken2("timezone"),b.timezone));a.timeSuffix=c.each(c.ignore(a.whiteSpace),c.set([a.tt,a.zzz]));a.time=c.each(c.optional(c.ignore(c.stoken("T"))),a.hms,a.timeSuffix);a.d=c.cache(c.process(c.each(c.rtoken(/^([0-2]\d|3[0-1]|\d)/),c.optional(a.ctoken2("ordinalSuffix"))),b.day));a.dd=c.cache(c.process(c.each(c.rtoken(/^([0-2]\d|3[0-1])/),c.optional(a.ctoken2("ordinalSuffix"))),b.day));a.ddd=a.dddd=c.cache(c.process(a.ctoken("sun mon tue wed thu fri sat"),function(a){return function(){this.weekday= a}}));a.M=c.cache(c.process(c.rtoken(/^(1[0-2]|0\d|\d)/),b.month));a.MM=c.cache(c.process(c.rtoken(/^(1[0-2]|0\d)/),b.month));a.MMM=a.MMMM=c.cache(c.process(a.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),b.month));a.y=c.cache(c.process(c.rtoken(/^(\d\d?)/),b.year));a.yy=c.cache(c.process(c.rtoken(/^(\d\d)/),b.year));a.yyy=c.cache(c.process(c.rtoken(/^(\d\d?\d?\d?)/),b.year));a.yyyy=c.cache(c.process(c.rtoken(/^(\d\d\d\d)/),b.year));e=function(){return c.each(c.any.apply(null,arguments), c.not(a.ctoken2("timeContext")))};a.day=e(a.d,a.dd);a.month=e(a.M,a.MMM);a.year=e(a.yyyy,a.yy);a.orientation=c.process(a.ctoken("past future"),function(a){return function(){this.orient=a}});a.operator=c.process(a.ctoken("add subtract"),function(a){return function(){this.operator=a}});a.rday=c.process(a.ctoken("yesterday tomorrow today now"),b.rday);a.unit=c.process(a.ctoken("second minute hour day week month year"),function(a){return function(){this.unit=a}});a.value=c.process(c.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/), function(a){return function(){this.value=a.replace(/\D/g,"")}});a.expression=c.set([a.rday,a.operator,a.value,a.unit,a.orientation,a.ddd,a.MMM]);e=function(){return c.set(arguments,a.datePartDelimiter)};a.mdy=e(a.ddd,a.month,a.day,a.year);a.ymd=e(a.ddd,a.year,a.month,a.day);a.dmy=e(a.ddd,a.day,a.month,a.year);a.date=function(b){return(a[Date.CultureInfo.dateElementOrder]||a.mdy).call(this,b)};a.format=c.process(c.many(c.any(c.process(c.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/), function(b){if(a[b])return a[b];throw f.Parsing.Exception(b);}),c.process(c.rtoken(/^[^dMyhHmstz]+/),function(a){return c.ignore(c.stoken(a))}))),function(a){return c.process(c.each.apply(null,a),b.finishExact)});var d={},l=function(b){d[b]=d[b]||a.format(b)[0];return d[b]};a.allformats=function(a){var b=[];if(a instanceof Array)for(var c=0;c<a.length;c++)b.push(l(a[c]));else b.push(l(a));return b};a.formats=function(a){if(a instanceof Array){for(var b=[],d=0;d<a.length;d++)b.push(l(a[d]));return c.any.apply(null, b)}return l(a)};a._formats=a.formats('"yyyy-MM-ddTHH:mm:ssZ";yyyy-MM-ddTHH:mm:ss.sz;yyyy-MM-ddTHH:mm:ssZ;yyyy-MM-ddTHH:mm:ssz;yyyy-MM-ddTHH:mm:ss;yyyy-MM-ddTHH:mmZ;yyyy-MM-ddTHH:mmz;yyyy-MM-ddTHH:mm;ddd, MMM dd, yyyy H:mm:ss tt;ddd MMM d yyyy HH:mm:ss zzz;MMddyyyy;ddMMyyyy;Mddyyyy;ddMyyyy;Mdyyyy;dMyyyy;yyyy;Mdyy;dMyy;d'.split(";"));a._start=c.process(c.set([a.date,a.time,a.expression],a.generalDelimiter,a.whiteSpace),b.finish);a.start=function(b){try{var c=a._formats.call({},b);if(0===c[1].length)return c}catch(d){}return a._start.call({}, b)};f._parse||(f._parse=f.parse);f.parse=function(a){var b,c,d=null;if(!a)return null;if(a instanceof Date)return a.clone();4<=a.length&&"0"!==a.charAt(0)&&"+"!==a.charAt(0)&&"-"!==a.charAt(0)&&(b=f.Parsing.ISO.parse(a)||f.Parsing.Numeric.parse(a));if(b instanceof Date&&!isNaN(b.getTime()))return b;a=(b=a.match(/\b(\d+)(?:st|nd|rd|th)\b/))&&2===b.length?a.replace(b[0],b[1]):a;a=f.Parsing.Normalizer.parse(a);try{d=f.Grammar.start.call({},a.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"))}catch(e){return null}b= 0===d[1].length?d[0]:null;if(null!==b)return b;try{return(c=Date._parse(a))||0===c?new Date(c):null}catch(g){return null}};Date.getParseFunction=function(a){var b=Date.Grammar.allformats(a);return function(a){for(var c=null,d=0;d<b.length;d++){try{c=b[d].call({},a)}catch(e){continue}if(0===c[1].length)return c[0]}return null}};f.parseExact=function(a,b){return f.getParseFunction(b)(a)}})(); (function(){var f=Date,g=f.prototype,c=Number.prototype;g._orient=1;g._nth=null;g._is=!1;g._same=!1;g._isSecond=!1;c._dateElement="days";g.next=function(){this._move=!0;this._orient=1;return this};f.next=function(){return f.today().next()};g.last=g.prev=g.previous=function(){this._move=!0;this._orient=-1;return this};f.last=f.prev=f.previous=function(){return f.today().last()};g.is=function(){this._is=!0;return this};g.same=function(){this._same=!0;this._isSecond=!1;return this};g.today=function(){return this.same().day()}; g.weekday=function(){return this._nth?l("Weekday").call(this):this._move?this.addWeekdays(this._orient):this._is?(this._is=!1,!this.is().sat()&&!this.is().sun()):!1};g.weekend=function(){return this._is?(this._is=!1,this.is().sat()||this.is().sun()):!1};g.at=function(a){return"string"===typeof a?f.parse(this.toString("d")+" "+a):this.set(a)};c.fromNow=c.after=function(a){var b={};b[this._dateElement]=this;return(a?a.clone():new Date).add(b)};c.ago=c.before=function(a){var b={};b["s"!==this._dateElement[this._dateElement.length- 1]?this._dateElement+"s":this._dateElement]=-1*this;return(a?a.clone():new Date).add(b)};var a="sunday monday tuesday wednesday thursday friday saturday".split(/\s/),b="january february march april may june july august september october november december".split(/\s/),e="Millisecond Second Minute Hour Day Week Month Year Quarter Weekday".split(/\s/),q="Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter".split(/\s/),d="final first second third fourth fifth".split(/\s/);g.toObject=function(){for(var a= {},b=0;b<e.length;b++)this["get"+q[b]]&&(a[e[b].toLowerCase()]=this["get"+q[b]]());return a};f.fromObject=function(a){a.week=null;return Date.today().set(a)};for(var l=function(a){return function(){if(this._is)return this._is=!1,this.getDay()===a;this._move&&(this._move=null);if(null!==this._nth){this._isSecond&&this.addSeconds(-1*this._orient);this._isSecond=!1;var b=this._nth;this._nth=null;var c=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(a,b);if(this>c)throw new RangeError(f.getDayName(a)+ " does not occur "+b+" times in the month of "+f.getMonthName(c.getMonth())+" "+c.getFullYear()+".");return this}return this.moveToDayOfWeek(a,this._orient)}},h=function(a){return function(){var b=f.today(),c=a-b.getDay();0===a&&1===Date.CultureInfo.firstDayOfWeek&&0!==b.getDay()&&(c+=7);return b.addDays(c)}},k=0;k<a.length;k++)f[a[k].toUpperCase()]=f[a[k].toUpperCase().substring(0,3)]=k,f[a[k]]=f[a[k].substring(0,3)]=h(k),g[a[k]]=g[a[k].substring(0,3)]=l(k);a=function(a){return function(){return this._is? (this._is=!1,this.getMonth()===a):this.moveToMonth(a,this._orient)}};h=function(a){return function(){return f.today().set({month:a,day:1})}};for(k=0;k<b.length;k++)f[b[k].toUpperCase()]=f[b[k].toUpperCase().substring(0,3)]=k,f[b[k]]=f[b[k].substring(0,3)]=h(k),g[b[k]]=g[b[k].substring(0,3)]=a(k);a=function(a){return function(b){if(this._isSecond)return this._isSecond=!1,this;if(this._same){this._same=this._is=!1;var c=this.toObject();b=(b||new Date).toObject();for(var d="",f=a.toLowerCase(),f="s"=== f[f.length-1]?f.substring(0,f.length-1):f,g=e.length-1;-1<g;g--){d=e[g].toLowerCase();if(c[d]!==b[d])return!1;if(f===d)break}return!0}"s"!==a.substring(a.length-1)&&(a+="s");this._move&&(this._move=null);return this["add"+a](this._orient)}};h=function(a){return function(){this._dateElement=a;return this}};for(k=0;k<e.length;k++)b=e[k].toLowerCase(),"weekday"!==b&&(g[b]=g[b+"s"]=a(e[k]),c[b]=c[b+"s"]=h(b+"s"));g._ss=a("Second");c=function(a){return function(b){if(this._same)return this._ss(b);if(b|| 0===b)return this.moveToNthOccurrence(b,a);this._nth=a;return 2!==a||void 0!==b&&null!==b?this:(this._isSecond=!0,this.addSeconds(this._orient))}};for(b=0;b<d.length;b++)g[d[b]]=0===b?c(-1):c(b)})(); (function(){var f=Date,g=f.prototype,c=[],a=function(a,c){c||(c=2);return("000"+a).slice(-1*c)};f.normalizeFormat=function(a){return a};f.strftime=function(a,c){return(new Date(1E3*c)).$format(a)};f.strtotime=function(a){a=f.parse(a);a.addMinutes(-1*a.getTimezoneOffset());return Math.round(f.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())/1E3)};g.$format=function(b){var e=this,g,d=function(a,b){c.push(a);return e.toString(a, b)};return b?b.replace(/(%|\\)?.|%%/g,function(b){if("\\"===b.charAt(0)||"%%"===b.substring(0,2))return b.replace("\\","").replace("%%","%");switch(b){case "d":case "%d":return d("dd");case "D":case "%a":return d("ddd");case "j":case "%e":return d("d",!0);case "l":case "%A":return d("dddd");case "N":case "%u":return e.getDay()+1;case "S":return d("S");case "w":case "%w":return e.getDay();case "z":return e.getOrdinalNumber();case "%j":return a(e.getOrdinalNumber(),3);case "%U":b=e.clone().set({month:0, day:1}).addDays(-1).moveToDayOfWeek(0);var h=e.clone().addDays(1).moveToDayOfWeek(0,-1);return h<b?"00":a((h.getOrdinalNumber()-b.getOrdinalNumber())/7+1);case "W":case "%V":return e.getISOWeek();case "%W":return a(e.getWeek());case "F":case "%B":return d("MMMM");case "m":case "%m":return d("MM");case "M":case "%b":case "%h":return d("MMM");case "n":return d("M");case "t":return f.getDaysInMonth(e.getFullYear(),e.getMonth());case "L":return f.isLeapYear(e.getFullYear())?1:0;case "o":case "%G":return e.setWeek(e.getISOWeek()).toString("yyyy"); case "%g":return e.$format("%G").slice(-2);case "Y":case "%Y":return d("yyyy");case "y":case "%y":return d("yy");case "a":case "%p":return d("tt").toLowerCase();case "A":return d("tt").toUpperCase();case "g":case "%I":return d("h");case "G":return d("H");case "h":return d("hh");case "H":case "%H":return d("HH");case "i":case "%M":return d("mm");case "s":case "%S":return d("ss");case "u":return a(e.getMilliseconds(),3);case "I":return e.isDaylightSavingTime()?1:0;case "O":return e.getUTCOffset();case "P":return g= e.getUTCOffset(),g.substring(0,g.length-2)+":"+g.substring(g.length-2);case "e":case "T":case "%z":case "%Z":return e.getTimezone();case "Z":return-60*e.getTimezoneOffset();case "B":return b=new Date,Math.floor((3600*b.getHours()+60*b.getMinutes()+b.getSeconds()+60*(b.getTimezoneOffset()+60))/86.4);case "c":return e.toISOString().replace(/\"/g,"");case "U":return f.strtotime("now");case "%c":return d("d")+" "+d("t");case "%C":return Math.floor(e.getFullYear()/100+1);case "%D":return d("MM/dd/yy"); case "%n":return"\\n";case "%t":return"\\t";case "%r":return d("hh:mm tt");case "%R":return d("H:mm");case "%T":return d("H:mm:ss");case "%x":return d("d");case "%X":return d("t");default:return c.push(b),b}}):this._toString()};g.format||(g.format=g.$format)})(); var TimeSpan=function(f,g,c,a,b){for(var e="days hours minutes seconds milliseconds".split(/\s+/),q=function(a){return function(){return this[a]}},d=function(a){return function(b){this[a]=b;return this}},l=0;l<e.length;l++){var h=e[l],k=h.slice(0,1).toUpperCase()+h.slice(1);TimeSpan.prototype[h]=0;TimeSpan.prototype["get"+k]=q(h);TimeSpan.prototype["set"+k]=d(h)}4===arguments.length?(this.setDays(f),this.setHours(g),this.setMinutes(c),this.setSeconds(a)):5===arguments.length?(this.setDays(f),this.setHours(g), this.setMinutes(c),this.setSeconds(a),this.setMilliseconds(b)):1===arguments.length&&"number"===typeof f&&(e=0>f?-1:1,this.setMilliseconds(Math.abs(f)),this.setDays(Math.floor(this.getMilliseconds()/864E5)*e),this.setMilliseconds(this.getMilliseconds()%864E5),this.setHours(Math.floor(this.getMilliseconds()/36E5)*e),this.setMilliseconds(this.getMilliseconds()%36E5),this.setMinutes(Math.floor(this.getMilliseconds()/6E4)*e),this.setMilliseconds(this.getMilliseconds()%6E4),this.setSeconds(Math.floor(this.getMilliseconds()/ 1E3)*e),this.setMilliseconds(this.getMilliseconds()%1E3),this.setMilliseconds(this.getMilliseconds()*e));this.getTotalMilliseconds=function(){return 864E5*this.getDays()+36E5*this.getHours()+6E4*this.getMinutes()+1E3*this.getSeconds()};this.compareTo=function(a){var b=new Date(1970,1,1,this.getHours(),this.getMinutes(),this.getSeconds());a=null===a?new Date(1970,1,1,0,0,0):new Date(1970,1,1,a.getHours(),a.getMinutes(),a.getSeconds());return b<a?-1:b>a?1:0};this.equals=function(a){return 0===this.compareTo(a)}; this.add=function(a){return null===a?this:this.addSeconds(a.getTotalMilliseconds()/1E3)};this.subtract=function(a){return null===a?this:this.addSeconds(-a.getTotalMilliseconds()/1E3)};this.addDays=function(a){return new TimeSpan(this.getTotalMilliseconds()+864E5*a)};this.addHours=function(a){return new TimeSpan(this.getTotalMilliseconds()+36E5*a)};this.addMinutes=function(a){return new TimeSpan(this.getTotalMilliseconds()+6E4*a)};this.addSeconds=function(a){return new TimeSpan(this.getTotalMilliseconds()+ 1E3*a)};this.addMilliseconds=function(a){return new TimeSpan(this.getTotalMilliseconds()+a)};this.get12HourHour=function(){return 12<this.getHours()?this.getHours()-12:0===this.getHours()?12:this.getHours()};this.getDesignator=function(){return 12>this.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator};this.toString=function(a){this._toString=function(){return null!==this.getDays()&&0<this.getDays()?this.getDays()+"."+this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds()): this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds())};this.p=function(a){return 2>a.toString().length?"0"+a:a};var b=this;return a?a.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,function(a){switch(a){case "d":return b.getDays();case "dd":return b.p(b.getDays());case "H":return b.getHours();case "HH":return b.p(b.getHours());case "h":return b.get12HourHour();case "hh":return b.p(b.get12HourHour());case "m":return b.getMinutes();case "mm":return b.p(b.getMinutes());case "s":return b.getSeconds(); case "ss":return b.p(b.getSeconds());case "t":return(12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator).substring(0,1);case "tt":return 12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator}}):this._toString()};return this};Date.prototype.getTimeOfDay=function(){return new TimeSpan(0,this.getHours(),this.getMinutes(),this.getSeconds(),this.getMilliseconds())}; var TimePeriod=function(f,g,c,a,b,e,q){for(var d="years months days hours minutes seconds milliseconds".split(/\s+/),l=function(a){return function(){return this[a]}},h=function(a){return function(b){this[a]=b;return this}},k=0;k<d.length;k++){var m=d[k],n=m.slice(0,1).toUpperCase()+m.slice(1);TimePeriod.prototype[m]=0;TimePeriod.prototype["get"+n]=l(m);TimePeriod.prototype["set"+n]=h(m)}if(7===arguments.length)this.years=f,this.months=g,this.setDays(c),this.setHours(a),this.setMinutes(b),this.setSeconds(e), this.setMilliseconds(q);else if(2===arguments.length&&arguments[0]instanceof Date&&arguments[1]instanceof Date){d=f.clone();l=g.clone();h=d.clone();k=d>l?-1:1;this.years=l.getFullYear()-d.getFullYear();h.addYears(this.years);1===k?h>l&&0!==this.years&&this.years--:h<l&&0!==this.years&&this.years++;d.addYears(this.years);if(1===k)for(;d<l&&d.clone().addMonths(1)<=l;)d.addMonths(1),this.months++;else for(;d>l&&d.clone().addDays(-d.getDaysInMonth())>l;)d.addMonths(-1),this.months--;d=l-d;0!==d&&(d=new TimeSpan(d), this.setDays(d.getDays()),this.setHours(d.getHours()),this.setMinutes(d.getMinutes()),this.setSeconds(d.getSeconds()),this.setMilliseconds(d.getMilliseconds()))}return this};
'use strict'; const PipelineAggregationBase = require('./pipeline-aggregation-base'); const ES_REF_URL = 'https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-extended-stats-bucket-aggregation.html'; /** * A sibling pipeline aggregation which calculates a variety of stats across * all bucket of a specified metric in a sibling aggregation. The specified * metric must be numeric and the sibling aggregation must be a multi-bucket * aggregation. * * [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-extended-stats-bucket-aggregation.html) * * @example * const reqBody = esb.requestBodySearch() * .agg( * esb.dateHistogramAggregation('sales_per_month', 'date') * .interval('month') * .agg(esb.sumAggregation('sales', 'price')) * ) * .agg( * // Calculates extended stats for monthly sales * esb.extendedStatsBucketAggregation( * 'stats_monthly_sales', * 'sales_per_month>sales' * ) * ) * .size(0); * * @param {string} name The name which will be used to refer to this aggregation. * @param {string=} bucketsPath The relative path of metric to aggregate over * * @extends PipelineAggregationBase */ class ExtendedStatsBucketAggregation extends PipelineAggregationBase { // eslint-disable-next-line require-jsdoc constructor(name, bucketsPath) { super(name, 'extended_stats_bucket', ES_REF_URL, bucketsPath); } /** * Sets the number of standard deviations above/below the mean to display. * Optional. * * @param {number} sigma Default is 2. * @returns {ExtendedStatsBucketAggregation} returns `this` so that calls can be chained */ sigma(sigma) { this._aggsDef.sigma = sigma; return this; } } module.exports = ExtendedStatsBucketAggregation;
/* eslint no-use-before-define: ["error", "nofunc"] */ import React from 'react' import { useLocalObservable } from 'mobx-react' export { createMobxManager, getMobxManager } const Global = { managerInstances: {}, } /** * @param {string} [storeId] * Can be used to identify the needed store * in case more than one store is managed * @param {function} initCallback * Function that returns the initial state of the store * * @returns {object} * Returns a manager instance which especially contains * the method "getProviderComponentAndValue()" */ function createMobxManager(storeId, initCallback) { const MobxStoreManager = _hoistClassDefinition() const manager = Global.managerInstances[storeId] if (manager == null) { Global.managerInstances[storeId] = new MobxStoreManager(storeId, initCallback) return Global.managerInstances[storeId] } manager._reset(initCallback) return manager } /** * @param {string} [storeId] * Can be used to identify the needed store * in case more than one store is managed * * @returns {object|null} * Manager instance if createMobxManager() was used before; or * Null */ function getMobxManager(storeId) { return Global.managerInstances[storeId] || null } function _hoistClassDefinition() { class MobxStoreManager { constructor(storeId, initCallback) { this._id = storeId this._initCallback = initCallback this._initialized = false this._reactContext = null this._ReactContextProvider = null this._mobxStore = null } getId() { return this._id } _initIfNeeded() { if (this._initialized) { return this } this._reactContext = React.createContext(null) this._ReactContextProvider = this._reactContext.Provider this._mobxStore = useLocalObservable(this._initCallback) this._initialized = true return this } _reset(initCallback) { if (this._initCallback === initCallback) { return this } this._initCallback = initCallback if (this._initialized) { this._mobxStore = useLocalObservable(this._initCallback) return this } this._initIfNeeded() return this } getProviderComponentAndValue() { this._initIfNeeded() const result = { Provider: this._ReactContextProvider, value: this._mobxStore, } return result } getContextHook() { this._initIfNeeded() return React.useContext(this._reactContext) } } return MobxStoreManager }
export function getUintSize(value) { // If size is n, the total bit space is 7 * n space. // Don't support >32bit integers for now. if (value < 0) return 5; if (value < (1 << 7)) return 1; if (value < (1 << 14)) return 2; if (value < (1 << 21)) return 3; if (value < (1 << 28)) return 4; /* for (let i = 1; i <= 4; ++i) { if (value < (1 << (i * 7))) return i; } */ // Actually, 5 bits mode completely drops first byte. return 5; } export function getUintVar(dataBuffer) { let firstByte = dataBuffer.getUint8BE(); let sizeByte = firstByte; let size = 1; while (size <= 5) { if ((sizeByte & 0x80) === 0) break; sizeByte = sizeByte << 1; size++; } // Done! decode the bytes. let output = 0; let remainingSize = size - 1; firstByte = firstByte & (0xFF >> size); // Handle 32bit specially :/ if (remainingSize < 4) { output = firstByte << (remainingSize << 3); } while (remainingSize >= 4) { remainingSize -= 4; output |= dataBuffer.getUint32BE() << (remainingSize << 3); } if (remainingSize >= 2) { remainingSize -= 2; output |= dataBuffer.getUint16BE() << (remainingSize << 3); } if (remainingSize >= 1) { remainingSize -= 1; output |= dataBuffer.getUint8BE() << (remainingSize << 3); } return output; } export function setUintVar(value, dataBuffer) { // Determine the size of value first. let size = getUintSize(value); // Write the first byte - Include the size information too. let sizeByte = (0xFE00 >> size) & 0xFF; let remainingSize = size - 1; // Handle 32bit specially :/ if (remainingSize < 4) { dataBuffer.setUint8BE((value >>> (remainingSize << 3)) | sizeByte); } else { dataBuffer.setUint8BE(sizeByte); } while (remainingSize >= 4) { remainingSize -= 4; dataBuffer.setUint32BE(value >>> (remainingSize << 3)); } if (remainingSize >= 2) { remainingSize -= 2; dataBuffer.setUint16BE((value >>> (remainingSize << 3)) & 0xFFFF); } if (remainingSize >= 1) { remainingSize -= 1; dataBuffer.setUint8BE((value >>> (remainingSize << 3)) & 0xFF); } }
import { spring } from 'react-motion'; export default (gateStatus) => (prevStyles) => [ { width: spring( gateStatus ? prevStyles[0].width > 1 ? prevStyles[0].width * 0.5 : 0 : prevStyles[0].width < 47 ? prevStyles[0].width + 10 : 50 ), }, { width: spring( gateStatus ? prevStyles[1].width > 1 ? prevStyles[1].width * 0.5 : 0 : prevStyles[1].width < 47 ? prevStyles[1].width + 10 : 50 ), }, { width: spring(100 - prevStyles[1].width) }, ];
// @flow import R from 'ramda'; import { createInMonthSelectors, createUpToMonthSelectors, beginningOfMonth, sumOfAmounts } from './utils'; import {arraySelector} from 'hw-react-shared'; import type {Transaction} from '../entities/Transaction'; import {TransactionResource} from '../entities/Transaction'; import {createSelector} from 'reselect'; const dateAmountSort = R.sortWith([R.descend(R.prop('date')), R.ascend(R.prop('amount'))]); export const getSortedTransactions = createSelector( arraySelector(TransactionResource), (transactions: Transaction[]) => dateAmountSort(transactions) ); export const transactionsInMonth = createInMonthSelectors( arraySelector(TransactionResource), (t: Transaction) => beginningOfMonth(t.date) ); export const transactionsUpToMonth = createUpToMonthSelectors( arraySelector(TransactionResource), (t: Transaction) => beginningOfMonth(t.date) ); export const getToBeBudgetedSumInSelectedMonth = createSelector( transactionsInMonth.selected, (transactions: Transaction[]) => sumOfAmounts(transactions.filter(t => t.type === 'to_be_budgeted')) ); export const getToBeBudgetedSumUpToSelectedMonth = createSelector( transactionsUpToMonth.selected, (transactions: Transaction[]) => sumOfAmounts(transactions.filter(t => t.type === 'to_be_budgeted')) ); /** * Flattens a series of transactions to an array of [date, category_uuid, amount] including both transactions and subtransactions. */ export const flattenTransactions = (transactions: Transaction[]) => transactions .filter(t => t.category_uuid) .map(t => ({date: t.date, category_uuid: t.category_uuid, amount: t.amount || 0})) .concat( ...transactions.map(t => t.subtransactions .filter(st => st.category_uuid) .map(st => ({date: t.date, category_uuid: st.category_uuid, amount: st.amount || 0})) ) ); export const selectSelectedMonthActivityByCategoryId = createSelector( transactionsInMonth.selected, (transactions: Transaction[]) => { const reduceToAmountSumBy = R.reduceBy((acc, record) => acc + record.amount, 0); const sumByCategoryId = reduceToAmountSumBy(R.prop('category_uuid')); return sumByCategoryId(flattenTransactions(transactions)); } );
import validator from 'validator'; function normalizeValidation(validation) { if (validation.value) return validation; return { key: true, value: validation }; } function runValidation(key, validation, value) { if (validation == null) return null; // currently only supports: // is, isURL, isEmail, len, notEmpty, notIn let args = normalizeValidation(validation); switch (key) { case 'is': if (!validator.matches(value, args.value)) return args.key; break; case 'isURL': if (!validator.isURL(value) && !validator.isNull(value)) return args.key; break; case 'isEmail': if (!validator.isEmail(value) && !validator.isNull(value)) return args.key; break; case 'len': const [min, max] = args.value; if (!validator.isLength(value, min, max)) return args.key; break; case 'notEmpty': if (validator.isNull(value)) return args.key; break; case 'notIn': if (validator.isIn(value, args.value)) return args.key; if (typeof value === 'string' && validator.isIn(value.toLowerCase(), args.value)) return args.key; break; } return null; } // Run validations from the data export default function validate(data, schema) { if (schema == null) return {}; let errors = {}; for (let key in schema) { let validation = schema[key]; let value = data[key]; for (let check in validation) { const result = runValidation(check, validation[check], value); if (result !== null) { errors[key] = result; } } } return errors; } // Run validation, return only one error. export function validateSingle(data, schema) { let result = validate(data, schema); for (let key in result) { if (result[key] !== false) return result[key]; } return null; }
var bi = require('./bi'); var util = require('./util'); var CHAR = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19, 'K': 20, 'L': 21, 'M': 22, 'N': 23, 'O': 24, 'P': 25, 'Q': 26, 'R': 27, 'S': 28, 'T': 29, 'U': 30, 'V': 31, 'W': 32, 'X': 33, 'Y': 34, 'Z': 35, }; var CHARS = Object.keys(CHAR); function calculateSum(value) { var sum = 0; for (var i = value.length - 1; i >= 0; i--) { var d = CHAR[value[i]]; if (d === undefined || (i < 9 && d > 9)) { return false; } if (i % 2 === 0) { d *= 2; if (d > 9) { d -= 9; } } sum += d; } return sum % 10; } /** * Generate a random Citizen's Card (Cartão do Cidadão) Document Number. * * @returns {string} A valid document number including alpha-numeric version and check digit. */ function generate() { var number = bi.generate(); // random 2 char document version number += util.getRandomElement(CHARS); number += util.getRandomElement(CHARS); number += (10 - calculateSum(number)) % 10; return number; } /** * Validate a given Citizen's Card (Cartão do Cidadão) Document Number. * * @param {string} number - the document number to validate. * * @returns {boolean} True if the given document number is valid. */ function validate(number) { if (typeof number !== 'string' || number.length !== 12) { return false; } return calculateSum(number) === 0; } module.exports = { validate: validate, generate: generate };
jQuery(document).ready(function($){ function initSlider() { /* галерея speakers */ $('.speakers__gallery').slick({ infinite: false, dots: false, arrows: true, slidesToShow: 3, slidesToScroll: 1, // centerMode: true, centerPadding: '0', responsive: [ { breakpoint: 919, settings: { slidesToShow: 2 } }, { breakpoint: 767, settings: { slidesToShow: 1 } } ] }); } initSlider(); $('.speakers__link--open').click(function(e){ e.preventDefault(); $('.speakers__gallery').slick('unslick'); $(this).hide(); $(this).closest('.speakers__link-wrapper').find('.speakers__link--close').show(); }); $('.speakers__link--close').click(function(e){ e.preventDefault(); initSlider(); $(this).hide(); $(this).closest('.speakers__link-wrapper').find('.speakers__link--open').show(); }); /* Fixed menu */ var nav = $('.nav'); var navTopCoord = nav.offset().top; var navHeight = $(".nav").outerHeight(true); $(window).scroll(function () { if ($(this).scrollTop() >= navTopCoord ) { $(nav).addClass('nav--fixed'); $('main').css("padding-top", navHeight + "px"); } else { $('main').css("padding-top", 0); $(nav).removeClass('nav--fixed'); } }); /* плавный скролл */ $('.nav__list a[href^="#"], .nav__dropdown-list a[href^="#"]').click(function(e){ e.preventDefault(); var el = $(this).attr('href'); $('body, html').animate({ scrollTop: ($(el).offset().top - navHeight )}, 500); $('.nav__dropdown-list').hide(); $('.nav__list').find('.nav__item--menu').removeClass('nav__item--menu-bg'); return false; }); /* Popup programme */ $('.culture-block, .address-head__btn, .address__map-img').click( function(e){ e.preventDefault(); $('body').css({"overflow":"hidden"}); $('.overlay').show(); $( $(this.hash) ) .show() .animate({opacity: 1}, 200); }); /* Close the modal window */ $('.overlay__bg, .popup__close').click( function(e){ e.preventDefault(); $('body').css({"overflow":"auto"}); $(this).closest('.overlay').find('.popup') .animate({opacity: 0}, 200, function(){ $(this).hide(); $('.overlay').fadeOut(400); } ); }); /* календарь */ if ( $('#calendar1').length ){ rome(calendar1, { weekStart: 1 }); } if ( $('#calendar2').length ){ rome(calendar2, { weekStart: 1 }); } /* карта в popup */ var myMap; ymaps.ready(function () { myMap = new ymaps.Map("YMapsID", { center: [59.931896, 30.251621], zoom: 15 }); var myPlacemark = new ymaps.Placemark([59.931896, 30.251621], {}, { iconLayout: 'default#image', iconImageHref: 'img/pointer.png', iconImageOffset: [-50, -90], iconImageSize: [209, 90], }); myMap.geoObjects.add(myPlacemark); }); $('.nav__item--menu a').click(function(e) { e.preventDefault(); $(this).closest('.nav__item--menu').toggleClass('nav__item--menu-bg'); $(this).closest('.nav').find('.nav__dropdown-list').slideToggle(); }); if ($(window).width() < 768) { $('.forum-block__img').each(function(){ $(this).appendTo($(this).closest('.forum-block__text')); }); } // $(window).resize(function(){ // if ($(window).width() > 768) { // $('.nav__list').show(); // $('.nav__hamburger').hide(); // } else { // $('.nav__list').hide(); // $('.nav__hamburger').show(); // } // }); // $(document).mouseup(function (e){ // var div = $(".header__map"); // if (!div.is(e.target) && div.has(e.target).length === 0) { // div.hide(); // } // }); });
'use strict'; var CodeRED = require('../../CodeREDConfig'); module.exports = { db: { uri: CodeRED.development.RED_DB, }, log: { // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny' format: 'combined', // Stream defaults to process.stdout // Uncomment to enable logging to a log on the file system options: { stream: 'access.log' } }, assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', // 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', 'public/lib/bootstrap-material-design/dist/css/material.min.css', 'public/lib/font-awesome/css/font-awesome.min.css' ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: ['public/dist/application.min.css','public/less/modules.css'], js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
import { createStore, applyMiddleware, compose } from 'redux'; import { routerMiddleware } from 'react-router-redux'; import thunk from 'redux-thunk'; // import { createLogger } from 'redux-logger'; import rootReducer from '../reducers'; import { isClient, isDebug } from '../../config/app'; /* * @param {Object} initial state to bootstrap our stores with for server-side rendering * @param {History Object} a history object. We use `createMemoryHistory` for server-side rendering, * while using browserHistory for client-side * rendering. */ export default function configureStore(history) { // Installs hooks that always keep react-router and redux store in sync const middleware = [thunk, routerMiddleware(history)]; let store; if (isClient && isDebug) { // middleware.push(createLogger()); store = createStore(rootReducer, compose( applyMiddleware(...middleware), typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f )); } else { store = createStore(rootReducer, compose(applyMiddleware(...middleware), f => f)); } if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('reducers', () => { const nextReducer = require('../reducers'); store.replaceReducer(nextReducer); }); } return store; }
'use strict'; var node_website_copier = require('../lib/node-website-copier.js'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports['awesome'] = { setUp: function(done) { // setup here done(); }, 'no args': function(test) { test.expect(1); // tests here test.equal(node_website_copier.awesome(), 'awesome', 'should be awesome.'); test.done(); }, };
const x = async ( // some comment a) => { return foo(await a); }; function foo(a) { return a; }
import Gist from './Gist'; import GistAddForm from './GistAddForm'; var GistBox = React.createClass({ getInitialState: function() { return { gists: [] }; }, //this means our main object addGist: function (username) { var url = `https://api.github.com/users/${username}/gists` $.get(url, function(result) { //this is in a call back function // console.log(this); var username = result[0].owner.login; var url = result[0].html_url; var gists = this.state.gists.concat({username, url}); this.setState({ gists }) //console.log(result); }.bind(this)); }, render: function() { var newGist = function(gist) { return <Gist username={gist.username} url={gist.url} /> }; return ( <div> <h1>GistBox</h1> <GistAddForm onAdd={this.addGist} /> { this.state.gists.map(newGist) } </div> ); } }); export default GistBox;
'use strict'; /** * Module dependencies. */ var url = require('url'); var sfMoviesLogic = require('sf-movies-logic'); /** * Controller Action for GET. */ module.exports.get = function(req, res, next) { var query = url.parse(req.url, true).query.q; sfMoviesLogic.search(query, function(err, data) { next.ifError(err); res.json(data.splice(0, 10)); return next(); }); };
/** @module ember @submodule ember-metal */ // BEGIN IMPORTS import Ember from 'ember-metal/core'; import isEnabled, { FEATURES } from 'ember-metal/features'; import merge from 'ember-metal/merge'; import { instrument, reset as instrumentationReset, subscribe as instrumentationSubscribe, unsubscribe as instrumentationUnsubscribe } from 'ember-metal/instrumentation'; import { EMPTY_META, GUID_KEY, META_DESC, apply, applyStr, canInvoke, generateGuid, getMeta, guidFor, inspect, makeArray, meta, metaPath, setMeta, deprecatedTryCatchFinally, tryInvoke, uuid, wrap } from 'ember-metal/utils'; import EmberError from 'ember-metal/error'; import Cache from 'ember-metal/cache'; import Logger from 'ember-metal/logger'; import { _getPath, get, getWithDefault, normalizeTuple } from 'ember-metal/property_get'; import { accumulateListeners, addListener, hasListeners, listenersFor, on, removeListener, sendEvent, suspendListener, suspendListeners, watchedEvents } from 'ember-metal/events'; import ObserverSet from 'ember-metal/observer_set'; import { beginPropertyChanges, changeProperties, endPropertyChanges, overrideChains, propertyDidChange, propertyWillChange } from 'ember-metal/property_events'; import { defineProperty } from 'ember-metal/properties'; import { set, trySet } from 'ember-metal/property_set'; import { Map, MapWithDefault, OrderedSet } from 'ember-metal/map'; import getProperties from 'ember-metal/get_properties'; import setProperties from 'ember-metal/set_properties'; import { watchKey, unwatchKey } from 'ember-metal/watch_key'; import { ChainNode, finishChains, flushPendingChains, removeChainWatcher } from 'ember-metal/chains'; import { watchPath, unwatchPath } from 'ember-metal/watch_path'; import { destroy, isWatching, rewatch, unwatch, watch } from 'ember-metal/watching'; import expandProperties from 'ember-metal/expand_properties'; import { ComputedProperty, computed, cacheFor } from 'ember-metal/computed'; import alias from 'ember-metal/alias'; import { empty, notEmpty, none, not, bool, match, equal, gt, gte, lt, lte, oneWay as computedOneWay, readOnly, defaultTo, deprecatingAlias, and, or, any, collect } from 'ember-metal/computed_macros'; computed.empty = empty; computed.notEmpty = notEmpty; computed.none = none; computed.not = not; computed.bool = bool; computed.match = match; computed.equal = equal; computed.gt = gt; computed.gte = gte; computed.lt = lt; computed.lte = lte; computed.alias = alias; computed.oneWay = computedOneWay; computed.reads = computedOneWay; computed.readOnly = readOnly; computed.defaultTo = defaultTo; computed.deprecatingAlias = deprecatingAlias; computed.and = and; computed.or = or; computed.any = any; computed.collect = collect; import { _suspendBeforeObserver, _suspendBeforeObservers, _suspendObserver, _suspendObservers, addBeforeObserver, addObserver, beforeObserversFor, observersFor, removeBeforeObserver, removeObserver } from 'ember-metal/observer'; import { IS_BINDING, Mixin, aliasMethod, beforeObserver, immediateObserver, mixin, observer, required } from 'ember-metal/mixin'; import { Binding, bind, isGlobalPath, oneWay } from 'ember-metal/binding'; import run from 'ember-metal/run_loop'; import Libraries from 'ember-metal/libraries'; import isNone from 'ember-metal/is_none'; import isEmpty from 'ember-metal/is_empty'; import isBlank from 'ember-metal/is_blank'; import isPresent from 'ember-metal/is_present'; import Backburner from 'backburner'; import { isStream, subscribe, unsubscribe, read, readHash, readArray, scanArray, scanHash, concat, chain } from 'ember-metal/streams/utils'; import Stream from 'ember-metal/streams/stream'; // END IMPORTS // BEGIN EXPORTS var EmberInstrumentation = Ember.Instrumentation = {}; EmberInstrumentation.instrument = instrument; EmberInstrumentation.subscribe = instrumentationSubscribe; EmberInstrumentation.unsubscribe = instrumentationUnsubscribe; EmberInstrumentation.reset = instrumentationReset; Ember.instrument = instrument; Ember.subscribe = instrumentationSubscribe; Ember._Cache = Cache; Ember.generateGuid = generateGuid; Ember.GUID_KEY = GUID_KEY; Ember.platform = { defineProperty: true, hasPropertyAccessors: true }; Ember.Error = EmberError; Ember.guidFor = guidFor; Ember.META_DESC = META_DESC; Ember.EMPTY_META = EMPTY_META; Ember.meta = meta; Ember.getMeta = getMeta; Ember.setMeta = setMeta; Ember.metaPath = metaPath; Ember.inspect = inspect; Ember.tryCatchFinally = deprecatedTryCatchFinally; Ember.makeArray = makeArray; Ember.canInvoke = canInvoke; Ember.tryInvoke = tryInvoke; Ember.wrap = wrap; Ember.apply = apply; Ember.applyStr = applyStr; Ember.uuid = uuid; Ember.Logger = Logger; Ember.get = get; Ember.getWithDefault = getWithDefault; Ember.normalizeTuple = normalizeTuple; Ember._getPath = _getPath; Ember.on = on; Ember.addListener = addListener; Ember.removeListener = removeListener; Ember._suspendListener = suspendListener; Ember._suspendListeners = suspendListeners; Ember.sendEvent = sendEvent; Ember.hasListeners = hasListeners; Ember.watchedEvents = watchedEvents; Ember.listenersFor = listenersFor; Ember.accumulateListeners = accumulateListeners; Ember._ObserverSet = ObserverSet; Ember.propertyWillChange = propertyWillChange; Ember.propertyDidChange = propertyDidChange; Ember.overrideChains = overrideChains; Ember.beginPropertyChanges = beginPropertyChanges; Ember.endPropertyChanges = endPropertyChanges; Ember.changeProperties = changeProperties; Ember.defineProperty = defineProperty; Ember.set = set; Ember.trySet = trySet; Ember.OrderedSet = OrderedSet; Ember.Map = Map; Ember.MapWithDefault = MapWithDefault; Ember.getProperties = getProperties; Ember.setProperties = setProperties; Ember.watchKey = watchKey; Ember.unwatchKey = unwatchKey; Ember.flushPendingChains = flushPendingChains; Ember.removeChainWatcher = removeChainWatcher; Ember._ChainNode = ChainNode; Ember.finishChains = finishChains; Ember.watchPath = watchPath; Ember.unwatchPath = unwatchPath; Ember.watch = watch; Ember.isWatching = isWatching; Ember.unwatch = unwatch; Ember.rewatch = rewatch; Ember.destroy = destroy; Ember.expandProperties = expandProperties; Ember.ComputedProperty = ComputedProperty; Ember.computed = computed; Ember.cacheFor = cacheFor; Ember.addObserver = addObserver; Ember.observersFor = observersFor; Ember.removeObserver = removeObserver; Ember.addBeforeObserver = addBeforeObserver; Ember._suspendBeforeObserver = _suspendBeforeObserver; Ember._suspendBeforeObservers = _suspendBeforeObservers; Ember._suspendObserver = _suspendObserver; Ember._suspendObservers = _suspendObservers; Ember.beforeObserversFor = beforeObserversFor; Ember.removeBeforeObserver = removeBeforeObserver; Ember.IS_BINDING = IS_BINDING; Ember.required = required; Ember.aliasMethod = aliasMethod; Ember.observer = observer; Ember.immediateObserver = immediateObserver; Ember.beforeObserver = beforeObserver; Ember.mixin = mixin; Ember.Mixin = Mixin; Ember.oneWay = oneWay; Ember.bind = bind; Ember.Binding = Binding; Ember.isGlobalPath = isGlobalPath; Ember.run = run; /** @class Backburner @for Ember @private */ Ember.Backburner = Backburner; // this is the new go forward, once Ember Data updates to using `_Backburner` we // can remove the non-underscored version. Ember._Backburner = Backburner; Ember.libraries = new Libraries(); Ember.libraries.registerCoreLibrary('Ember', Ember.VERSION); Ember.isNone = isNone; Ember.isEmpty = isEmpty; Ember.isBlank = isBlank; Ember.isPresent = isPresent; Ember.merge = merge; if (isEnabled('ember-metal-stream')) { Ember.stream = { Stream: Stream, isStream: isStream, subscribe: subscribe, unsubscribe: unsubscribe, read: read, readHash: readHash, readArray: readArray, scanArray: scanArray, scanHash: scanHash, concat: concat, chain: chain }; } Ember.FEATURES = FEATURES; Ember.FEATURES.isEnabled = isEnabled; /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. ```javascript Ember.onerror = function(error) { Em.$.ajax('/report-error', 'POST', { stack: error.stack, otherInformation: 'whatever app state you want to provide' }); }; ``` Internally, `Ember.onerror` is used as Backburner's error handler. @event onerror @for Ember @param {Exception} error the error object @public */ Ember.onerror = null; // END EXPORTS // do this for side-effects of updating Ember.assert, warn, etc when // ember-debug is present if (Ember.__loader.registry['ember-debug']) { requireModule('ember-debug'); } Ember.create = Ember.deprecateFunc('Ember.create is deprecated in-favour of Object.create', Object.create); Ember.keys = Ember.deprecateFunc('Ember.keys is deprecated in-favour of Object.keys', Object.keys); export default Ember;
import Masking from "../../../src/js/components/masking"; test('should have component defined', () => { expect(Masking).toBeDefined(); });
var author = React.createClass({ render: function() { var style = this.props.avatar_url ? { backgroundImage: `url(${this.props.avatar_url})` } : {}; return !this.props.login ? null : <div className="author" style={style}> {this.props.login} </div> } }); module.exports = author;
'use strict'; const testRule = require('stylelint-test-rule-ava'); const rule = require('..'); const messages = rule.messages; const ruleName = rule.ruleName; testRule(rule, { ruleName, config: [true], accept: [{ code: ':root { --foo-bar: 1px; }', }, { code: ':rOoT { --foo-bar: 1px; }', }, { code: ':ROOT { --foo-bar: 1px; }', }, { code: 'a { color: pink; }', }, { code: 'a { -webkit-transform: 1px; }', }], reject: [{ code: 'a { --foo-bar: 1px; }', message: messages.rejected, }, { code: 'a { color: pink; -webkit-transform: 1px; --foo-bar: 1px; }', message: messages.rejected, }, { code: ':root, a { --foo-bar: 1px; }', message: messages.rejected, }, { code: ':root a { --foo-bar: 1px; }', message: messages.rejected, }, { code: ':rOoT a { --foo-bar: 1px; }', message: messages.rejected, }, { code: ':ROOT a { --foo-bar: 1px; }', message: messages.rejected, }], });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Type is a standardization of the various JSON Schema types. It removes the concept // of a "null" type, and introduces Unions and an explicit Any type. The Any type is // part of the JSON Schema spec, but it isn't an explicit type. var Type; (function (Type) { Type[Type["ANY"] = 0] = "ANY"; Type[Type["STRING"] = 1] = "STRING"; Type[Type["BOOLEAN"] = 2] = "BOOLEAN"; Type[Type["INTEGER"] = 3] = "INTEGER"; Type[Type["NUMBER"] = 4] = "NUMBER"; Type[Type["OBJECT"] = 5] = "OBJECT"; Type[Type["ARRAY"] = 6] = "ARRAY"; Type[Type["UNION"] = 7] = "UNION"; })(Type = exports.Type || (exports.Type = {})); function toType(t) { switch (t) { case 'string': return Type.STRING; case 'integer': return Type.INTEGER; case 'number': return Type.NUMBER; case 'boolean': return Type.BOOLEAN; case 'object': return Type.OBJECT; case 'array': return Type.ARRAY; case 'null': return Type.ANY; default: throw new Error(`Unsupported type: ${t}`); } } // getPropertiesSchema extracts the Schema for `.properties` from an // event schema. function getPropertiesSchema(event) { let properties = undefined; // Events should always be a type="object" at the root, anything // else would not match on a Segment analytics event. if (event.type === Type.OBJECT) { const propertiesSchema = event.properties.find((schema) => schema.name === 'properties'); // The schema representing `.properties` in the Segement analytics // event should also always be an object. if (propertiesSchema && propertiesSchema.type === Type.OBJECT) { properties = propertiesSchema; } } return Object.assign({ // If `.properties` doesn't exist in the user-supplied JSON Schema, // default to an empty object schema as a sane default. type: Type.OBJECT, properties: [] }, (properties || {}), { isRequired: properties ? !!properties.isRequired : false, isNullable: false, // Use the event's name and description when generating an interface // to represent these properties. name: event.name, description: event.description }); } exports.getPropertiesSchema = getPropertiesSchema; // parse transforms a JSON Schema into a standardized Schema. function parse(raw, name, isRequired) { // TODO: validate that the raw JSON Schema is a valid JSON Schema before attempting to parse it. // Parse the relevant fields from the JSON Schema based on the type. const typeSpecificFields = parseTypeSpecificFields(raw, getType(raw)); const schema = Object.assign({ name: name || raw.title || '' }, typeSpecificFields); if (raw.description) { schema.description = raw.description; } if (isRequired) { schema.isRequired = true; } if (isNullable(raw)) { schema.isNullable = true; } return schema; } exports.parse = parse; // parseTypeSpecificFields extracts the relevant fields from the raw JSON Schema, // interpreting the schema based on the provided Type. function parseTypeSpecificFields(raw, type) { if (type === Type.OBJECT) { const fields = { type, properties: [] }; const requiredFields = new Set(raw.required || []); for (var entry of Object.entries(raw.properties || {})) { const [property, propertySchema] = entry; if (typeof propertySchema !== 'boolean') { const isRequired = requiredFields.has(property); fields.properties.push(parse(propertySchema, property, isRequired)); } } return fields; } else if (type === Type.ARRAY) { const fields = { type, items: { type: Type.ANY } }; if (typeof raw.items !== 'boolean' && raw.items !== undefined) { // `items` can be a single schemas, or an array of schemas, so standardize on an array. let definitions = raw.items instanceof Array ? raw.items : [raw.items]; // Convert from JSONSchema7Definition -> JSONSchema7 const schemas = definitions.filter(def => typeof def !== 'boolean'); if (schemas.length === 1) { const schema = schemas[0]; fields.items = parseTypeSpecificFields(schema, getType(schema)); } else if (schemas.length > 1) { fields.items = { type: Type.UNION, types: schemas.map(schema => parseTypeSpecificFields(schema, getType(schema))), }; } } return fields; } else if (type === Type.UNION) { const fields = { type, types: [] }; for (var val of getRawTypes(raw).values()) { // For codegen purposes, we don't consider "null" as a type, so remove it. if (val === 'null') { continue; } fields.types.push(parseTypeSpecificFields(raw, toType(val))); } if (raw.enum) { fields.enum = getEnum(raw); } return fields; } else { const fields = { type }; // TODO: Per above comment, consider filtering the enum values to just the matching type (string, boolean, etc.). if (raw.enum) { fields.enum = getEnum(raw); } // Handle the special case of `type: "null"`. In this case, only the value "null" // is allowed, so treat this as a single-value enum. const rawTypes = getRawTypes(raw); if (rawTypes.has('null') && rawTypes.size === 1) { fields.enum = [null]; } return fields; } } // getRawTypes returns the types for a given raw JSON Schema. These correspond // with the standard JSON Schema types (null, string, etc.) function getRawTypes(raw) { // JSON Schema's `type` field is either an array or a string -- standardize it into an array. const rawTypes = new Set(); if (typeof raw.type === 'string') { rawTypes.add(raw.type); } else if (raw.type instanceof Array) { raw.type.forEach(t => rawTypes.add(t)); } return rawTypes; } // getType parses the raw types from a JSON Schema and returns the standardized Type. function getType(raw) { const rawTypes = getRawTypes(raw); // For codegen purposes, we don't consider "null" as a type, so remove it. rawTypes.delete('null'); let type = Type.ANY; if (rawTypes.size === 1) { type = toType(rawTypes.values().next().value); } else if (rawTypes.size >= 1) { type = Type.UNION; } return type; } // isNullable returns true if `null` is a valid value for this JSON Schema. function isNullable(raw) { const typeAllowsNull = getRawTypes(raw).has('null') || getType(raw) === Type.ANY; const enumAllowsNull = !raw.enum || raw.enum.includes(null); return typeAllowsNull && enumAllowsNull; } // getEnum parses the enum, if specified function getEnum(raw) { if (!raw.enum) { return undefined; } const enm = raw.enum.filter(val => ['boolean', 'number', 'string'].includes(typeof val) || val === null); return enm; } //# sourceMappingURL=ast.js.map
var TorsoView = require('torso/modules/View'), galleryTemplate = require('./portfolioGalleryTemplate.hbs'); portfolioPageHeaderView = require('./portfolioPageHeaderView'); /** * Gallery View * * @class GalleryView */ module.exports = TorsoView.extend({ tagName: 'main', className: 'portfolio-page-content', id: 'main-content', moduleNamespace: 'Beiyi Wu', template: galleryTemplate, /** * @method initialize * @override */ initialize: function() { portfolioPageHeaderView.updateHeaderIcon({ icon: 'icon-pictures' }); } });
var _ = { tpl: function (str, dict) { for (var i in dict) { str = str.replace(new RegExp('\\{\\{' + i + '\\}\\}', 'g'), dict[i]) } return str }, log: function () { console.log.apply(console, arguments) }, nodes: function (str) { var div = document.createElement('div') div.innerHTML = str var fragment = document.createDocumentFragment() var nodes = div.childNodes while (nodes[0]) { fragment.appendChild(nodes[0]) } return fragment }, node: function (str) { return this.nodes(str).childNodes[0] }, hasClass: function (ele, cls) { return ele.className && ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }, addClass: function (ele, cls) { if (!this.hasClass(ele, cls)) { ele.className += " " + cls; } }, removeClass: function (ele, cls) { if (this.hasClass(ele, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' '); } }, on: function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, off: function (element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } }, parent: function (elem, cond, self) { if (!self) { elem = elem.parentNode } while (elem) { if (cond(elem)) { return elem } elem = elem.parentNode } }, child: function (elem, cond, self) { var childNodes = elem.childNodes var node, result var i = 0 self && (i = -1) for(; i < childNodes.length; i++){ node = childNodes[i] || elem result = null try{ result = cond(node) }catch (e){} if(result){ return node } } } } module.exports = _
angular.module('GooglePickerExample', ['lk-google-picker']) .config(['lkGoogleSettingsProvider', function(lkGoogleSettingsProvider) { // Configure the API credentials here lkGoogleSettingsProvider.configure({ apiKey : 'AIzaSyAEu079vZFFeuFjpfWOrcmw2uGxISgmWwI', clientId : '20787361493-372fi66o31k7t4t2ha3nvj5j36blm417.apps.googleusercontent.com' }); }]) .filter('getExtension', function() { return function(url) { return url.split('.').pop(); }; }) .controller('ExampleCtrl', ['$scope', 'lkGoogleSettings', function($scope, lkGoogleSettings) { $scope.files = []; $scope.languages = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, { code: 'ja', name: '日本語' }, { code: 'ko', name: '한국' }, ] // Check for the current language depending on lkGoogleSettings.locale $scope.initialize = function() { angular.forEach($scope.languages, function(language, index) { if (lkGoogleSettings.locale === language.code) { $scope.selectedLocale = $scope.languages[index]; } }); } // Define the locale to use $scope.changeLocale = function(locale) { lkGoogleSettings.locale = locale.code; } }]);
import form from './Form.xml'; import TopComponent from '../TopComponent/TopComponent'; import BackButton from '../BackButton/BackButton'; import UserService from '../../services/UserService/UserService'; import Transport from '../../modules/Transport/Transport'; import Validation from '../../modules/Validator/index'; import router from '../../modules/Router/Router'; import './Form.scss'; export default class FormView extends TopComponent { constructor(data) { super('div', {class: 'form-box'}, data); this.errors = {}; } render() { this._innerHTML(form(this.getData())); if (this.getData().back) { const backButton = new BackButton(); const formEnd = this.getElement().querySelector('.form-box__end'); formEnd.appendChild(backButton.getElement()); } this._validation(); return this.getElement(); } _errorOutput(formElements, errorsElements) { formElements.forEach(element => { if (this.errors[element.name]) { errorsElements[element.name].innerHTML = this.errors[element.name]; element.classList.add('input-error'); errorsElements[element.name].classList.add('active'); } else { element.classList.remove('input-error'); errorsElements[element.name].classList.remove('active'); errorsElements[element.name].innerHTML = ''; } }); } _resetErrors(formElements) { this.errors = {}; formElements.forEach(element => { element.addEventListener('focus', () => { element.classList.remove('input-error'); }, false); }); } _isValid() { let valid = true; Object.values(this.errors).forEach(error => { if (error) { valid = false; } }); return valid; } _validation() { const main = this.getElement(); const errors = main.getElementsByClassName('error'); const formElements = [...main.getElementsByClassName(this.getData().fields[0].class)]; const submitButton = main.getElementsByClassName(this.getData().buttons[0].class)[0]; this._resetErrors(formElements); const submit = () => { const values = {}; formElements.forEach(element => { values[element.name] = element; }); this.errors = Validation(values, this.errors); this._errorOutput(formElements, errors); if (this._isValid()) { this._submit(); } }; submitButton.addMultiEvents('click touchend', submit); this.getElement().addEventListener('keydown', e => { if (e.keyCode === 13) { submit(); } }); formElements.forEach(element => { element.addEventListener('blur', () => { const values = {}; values[element.name] = element; if (element.name === 'repeatPassword') { values.password = formElements.find(element => element.name === 'password'); } this.errors = Validation(values, this.errors); this._errorOutput([element], errors); }); }); } _submit() { const form = document.forms[this.getData().name]; const url = `/${this.getData().name}`; const fields = form.elements; const data = Object.assign(...Object.values(fields) .map(field => { return field.name !== 'repeatPassword' ? { [field.name]: field.value } : {}; })); if (this.getData().method === 'post') { Transport.post(url, data) .then(response => { UserService.user = response; const route = router.getRoute(''); if (!route.getView()) { route.createView(); } route.getView().rerender(); router.go('/'); }) .catch(async response => { if (!response.json) { console.log(response); return; } const json = await response.json(); const main = this.getElement(); const formError = main.getElementsByClassName('serverError')[0]; formError.name = 'formError'; this.errors.formError = json.message; this._errorOutput([formError], main.getElementsByClassName('error')); this.errors = []; }); } } }
{ ...for idx i in Array(10) { if i > 5 { {[i]: i} } else { {[i]: i} } } }
RAD.view('view.contributors', RAD.Blanks.View.extend({ url: RAD.application.basePath + 'scripts/views/contributors/contributors.html', onInitialize: function () { this.model = RAD.model('contributors'); } }));
/* * The MIT License (MIT) * * Copyright (c) 2016-2017 The Regents of the University of California * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * @author Jim Robinson */ var hic = (function (hic) { var defaultPixelSize, defaultState; var maxPixelSize = 100; var DEFAULT_ANNOTATION_COLOR = "rgb(22, 129, 198)"; var datasetCache = {}; var genomeCache = {}; // mock igv browser objects for igv.js compatibility function createIGV($hic_container) { igv.browser = { constants: {defaultColor: "rgb(0,0,150)"} } igv.trackMenuItemList = hic.trackMenuItemListReplacement; igv.trackMenuItem = hic.trackMenuItemReplacement; // Popover object -- singleton shared by all components igv.popover = new igv.Popover($hic_container); // igv.popover.presentTrackGearMenu = hic.popoverPresentTrackGearMenuReplacement; // ColorPicker object -- singleton shared by all components igv.colorPicker = new igv.ColorPicker($hic_container, undefined); igv.colorPicker.hide(); // Dialog object -- singleton shared by all components igv.dialog = new igv.Dialog($hic_container, igv.Dialog.dialogConstructor); igv.dialog.hide(); // Data Range Dialog object -- singleton shared by all components igv.dataRangeDialog = new igv.DataRangeDialog($hic_container); igv.dataRangeDialog.hide(); } function destringifyTracks(trackString) { var trackTokens = trackString.split("|||"), configList = []; trackTokens.forEach(function (track) { var tokens = track.split("|"), url = tokens[0], name = tokens[1], dataRangeString = tokens[2], color = tokens[3], config = {url: url}; if (name) config.name = name; if (dataRangeString) { var r = dataRangeString.split("-"); config.min = parseFloat(r[0]); config.max = parseFloat(r[1]) } if (color) config.color = color; configList.push(config); }); return configList; } hic.createBrowser = function ($hic_container, config) { var browser; setDefaults(config); var href = config.href || window.location.href, hicUrl = gup(href, "hicUrl"), name = gup(href, "name"), stateString = gup(href, "state"), colorScale = gup(href, "colorScale"), trackString = gup(href, "tracks"), selectedGene = gup(href, "selectedGene"), nvi = gup(href, "nvi"); defaultPixelSize = 1; defaultState = new hic.State(1, 1, 0, 0, 0, defaultPixelSize, "NONE"); if (hicUrl) { config.url = decodeURIComponent(hicUrl); } if (name) { config.name = decodeURIComponent(name); } if (stateString) { stateString = decodeURIComponent(stateString); config.state = hic.destringifyState(stateString); } if (colorScale) { config.colorScale = parseFloat(colorScale); } if (trackString) { trackString = decodeURIComponent(trackString); config.tracks = destringifyTracks(trackString); } if (selectedGene) { igv.FeatureTrack.selectedGene = selectedGene; } config.nvi = nvi; createIGV($hic_container); browser = new hic.Browser($hic_container, config); return browser; }; hic.Browser = function ($app_container, config) { var $root; //TODO -- remove this global reference !!!! hic.browser = this; this.config = config; this.eventBus = new hic.EventBus(); this.id = _.uniqueId('browser_'); this.trackRenderers = []; $root = $('<div class="hic-root unselect">'); var navbarHeight = 96; // TODO fix me if (config.showHicContactMapLabel === false) { navbarHeight = 60; } if (config.width) { $root.css("width", String(config.width)); } if (config.height) { $root.css("height", String(config.height + navbarHeight)); } $app_container.append($root); this.layoutController = new hic.LayoutController(this, $root); this.hideCrosshairs(); this.state = config.state ? config.state : defaultState.clone(); if (config.colorScale && !isNaN(config.colorScale)) { this.contactMatrixView.colorScale.high = config.colorScale; this.contactMatrixView.computeColorScale = false; } if (config.url) { this.loadHicFile(config); } this.eventBus.subscribe("LocusChange", this); this.eventBus.subscribe("DragStopped", this); this.eventBus.subscribe("MapLoad", this); this.eventBus.subscribe("ColorScale", this); this.eventBus.subscribe("NormalizationChange", this); }; hic.Browser.prototype.updateHref = function (event) { var href = window.location.href, nviString, trackString; if (event && event.type === "MapLoad") { href = replaceURIParameter("hicUrl", this.url, href); if (this.name) { href = replaceURIParameter("name", this.name, href); } } href = replaceURIParameter("state", (this.state.stringify()), href); href = replaceURIParameter("colorScale", "" + this.contactMatrixView.colorScale.high, href); if (igv.FeatureTrack.selectedGene) { href = replaceURIParameter("selectedGene", igv.FeatureTrack.selectedGene, href); } nviString = getNviString(this.dataset, this.state); if (nviString) { href = replaceURIParameter("nvi", nviString, href); } if (this.trackRenderers && this.trackRenderers.length > 0) { trackString = ""; this.trackRenderers.forEach(function (trackRenderer) { var track = trackRenderer.x.track, config = track.config, url = config.url, name = track.name, dataRange = track.dataRange, color = track.color; if (typeof url === "string") { if (trackString.length > 0) trackString += "|||"; trackString += url; trackString += "|" + (name ? name : ""); trackString += "|" + (dataRange ? (dataRange.min + "-" + dataRange.max) : ""); trackString += "|" + (color ? color : ""); } }); if (trackString.length > 0) { href = replaceURIParameter("tracks", trackString, href); } } if (this.config.updateHref === false) { console.log(href); } else { window.history.replaceState("", "juicebox", href); } }; hic.Browser.prototype.updateCrosshairs = function (coords) { this.contactMatrixView.$x_guide.css({top: coords.y, left: 0}); this.layoutController.$y_tracks.find("div[id$='x-track-guide']").css({top: coords.y, left: 0}); this.contactMatrixView.$y_guide.css({top: 0, left: coords.x}); this.layoutController.$x_tracks.find("div[id$='y-track-guide']").css({top: 0, left: coords.x}); }; hic.Browser.prototype.hideCrosshairs = function () { _.each([this.contactMatrixView.$x_guide, this.contactMatrixView.$y_guide, this.layoutController.$x_tracks.find("div[id$='y-track-guide']"), this.layoutController.$y_tracks.find("div[id$='x-track-guide']")], function ($e) { $e.hide(); }); }; hic.Browser.prototype.showCrosshairs = function () { _.each([this.contactMatrixView.$x_guide, this.contactMatrixView.$y_guide, this.layoutController.$x_tracks.find("div[id$='y-track-guide']"), this.layoutController.$y_tracks.find("div[id$='x-track-guide']")], function ($e) { $e.show(); }); }; hic.Browser.prototype.genomicState = function () { var gs, bpResolution; bpResolution = this.dataset.bpResolutions[this.state.zoom]; gs = {}; gs.bpp = bpResolution / this.state.pixelSize; gs.chromosome = {x: this.dataset.chromosomes[this.state.chr1], y: this.dataset.chromosomes[this.state.chr2]}; gs.startBP = {x: this.state.x * bpResolution, y: this.state.y * bpResolution}; gs.endBP = { x: gs.startBP.x + gs.bpp * this.contactMatrixView.getViewDimensions().width, y: gs.startBP.y + gs.bpp * this.contactMatrixView.getViewDimensions().height }; return gs; }; hic.Browser.prototype.getColorScale = function () { var cs = this.contactMatrixView.colorScale; return cs; }; hic.Browser.prototype.updateColorScale = function (high) { this.contactMatrixView.colorScale.high = high; this.contactMatrixView.imageTileCache = {}; this.contactMatrixView.update(); this.updateHref(); }; hic.Browser.prototype.loadTrack = function (trackConfigurations) { var self = this, promises; promises = []; _.each(trackConfigurations, function (config) { igv.inferTrackTypes(config); if ("annotation" === config.type && config.color === undefined) { config.color = DEFAULT_ANNOTATION_COLOR; } config.height = self.layoutController.track_height; promises.push(loadIGVTrack(config)); // X track promises.push(loadIGVTrack(config)); // Y track }); Promise .all(promises) .then(function (tracks) { var trackXYPairs = [], index; for (index = 0; index < tracks.length; index += 2) { trackXYPairs.push({x: tracks[index], y: tracks[index + 1]}); } self.addTrackXYPairs(trackXYPairs); }) .catch(function (error) { console.log(error.message); alert(error.message); }); }; function loadIGVTrack(config) { return new Promise(function (fulfill, reject) { var newTrack; newTrack = igv.createTrackWithConfiguration(config); if (undefined === newTrack) { reject(new Error('Could not create track')); } else if (typeof newTrack.getFileHeader === "function") { newTrack .getFileHeader() .then(function (header) { fulfill(newTrack); }) .catch(reject); } else { fulfill(newTrack); } }); }; hic.Browser.prototype.addTrackXYPairs = function (trackXYPairs) { this.eventBus.post(hic.Event("TrackLoad", {trackXYPairs: trackXYPairs})); }; hic.Browser.prototype.renderTracks = function (doSyncCanvas) { var list; if (_.size(this.trackRenderers) > 0) { // append each x-y track pair into a single list for Promise'ing list = []; _.each(this.trackRenderers, function (xy) { // sync canvas size with container div if needed _.each(xy, function (r) { if (true === doSyncCanvas) { r.syncCanvas(); } }); // concatenate Promises list.push(xy.x.promiseToRepaint()); list.push(xy.y.promiseToRepaint()); }); // Execute list of async Promises serially, waiting for // completion of one before executing the next. Promise .all(list) .then(function (strings) { // console.log(strings.join('\n')); }) .catch(function (error) { console.log(error.message) }); } }; hic.Browser.prototype.renderTrackXY = function (trackXY) { var list; // append each x-y track pair into a single list for Promise'ing list = []; list.push(trackXY.x.promiseToRepaint()); list.push(trackXY.y.promiseToRepaint()); Promise .all(list) .then(function (strings) { // console.log(strings.join('\n')); }) .catch(function (error) { console.log(error.message) }); }; hic.Browser.prototype.loadHicFile = function (config) { var self = this, str; if (!config.url) { console.log("No .hic url specified"); return; } if (this.url !== undefined) { // Unload previous map, important for memory management unloadDataset(this.url, this); this.dataset = undefined; this.contactMatrixView.dataset = undefined; } this.url = config.url; this.name = config.name; str = 'Contact Map: ' + config.name; this.$contactMaplabel.text(str); // $('#hic-nav-bar-contact-map-label').text(str); this.layoutController.removeAllTrackXYPairs(); self.contactMatrixView.clearCaches(); self.contactMatrixView.startSpinner(); getDataset(config, this) .then(function (dataset) { var previousGenomeId = self.genome ? self.genome.id : undefined; self.dataset = dataset; self.genome = new hic.Genome(self.dataset.genomeId, self.dataset.chromosomes); igv.browser.genome = self.genome; if (config.state) { self.setState(config.state); } else { self.setState(defaultState.clone()); self.contactMatrixView.computeColorScale = true; } self.contactMatrixView.setDataset(dataset); if (self.genome.id !== previousGenomeId) { self.eventBus.post(hic.Event("GenomeChange", self.genome.id)); } if (config.colorScale) { self.getColorScale().high = config.colorScale; } if (config.tracks) { self.loadTrack(config.tracks); } if (config.nvi) { var nviArray = decodeURIComponent(config.nvi).split("|"); dataset.initNormVectorIdx(self.state, decodeURIComponent(config.nvi)); } self.eventBus.post(hic.Event("MapLoad", dataset)); // Load norm vector index in the background dataset.hicReader.readNormVectorIndex(dataset) .then(function (ignore) { self.eventBus.post(hic.Event("NormVectorIndexLoad", dataset)); }) .catch(function (error) { console.log(error); }); }) .catch(function (error) { self.contactMatrixView.stopSpinner(); console.log(error); }); }; /** * Return a promise to load a dataset * @param config * @param browser */ function getDataset(config, browser) { var url = config.url, obj = datasetCache[url]; if (obj !== undefined) { obj.references.add(browser); // Reference counting Promise.resolve(obj.dataset); } else { return new Promise(function (fulfill, reject) { var hicReader = new hic.HiCReader(config); hicReader.loadDataset() .then(function (dataset) { var obj = { dataset: dataset, references: new Set() } obj.references.add(browser); datasetCache[url] = obj; fulfill(dataset); }) .catch(reject) }); } } function unloadDataset(url, browser) { var obj = datasetCache[url]; if (obj !== undefined) { obj.references.delete(browser); if (obj.references.size === 0) { datasetCache[url] = undefined; } } } function findDefaultZoom(bpResolutions, defaultPixelSize, chrLength) { var viewDimensions = this.contactMatrixView.getViewDimensions(), d = Math.max(viewDimensions.width, viewDimensions.height), nBins = d / defaultPixelSize, z; for (z = bpResolutions.length - 1; z >= 0; z--) { if (chrLength / bpResolutions[z] <= nBins) { return z; } } return 0; } hic.Browser.prototype.parseGotoInput = function (string) { var self = this, loci = string.split(' '), xLocus, yLocus; if (loci.length === 1) { xLocus = self.parseLocusString(loci[0]); yLocus = xLocus; } else { xLocus = self.parseLocusString(loci[0]); yLocus = self.parseLocusString(loci[1]); if (yLocus === undefined) yLocus = xLocus; } if (xLocus === undefined) { // Try a gene name search. hic.geneSearch(this.genome.id, loci[0].trim()) .then(function (result) { if (result) { igv.FeatureTrack.selectedGene = loci[0].trim(); xLocus = self.parseLocusString(result); yLocus = xLocus; self.state.selectedGene = loci[0].trim(); self.goto(xLocus.chr, xLocus.start, xLocus.end, yLocus.chr, yLocus.start, yLocus.end, 5000); } else { alert('No feature found with name "' + loci[0] + '"'); } }) .catch(function (error) { alert(error); console.log(error); }); } else { if (xLocus.wholeChr && yLocus.wholeChr) { self.setChromosomes(xLocus.chr, yLocus.chr); } else { self.goto(xLocus.chr, xLocus.start, xLocus.end, yLocus.chr, yLocus.start, yLocus.end, 200); } } } hic.Browser.prototype.findMatchingZoomIndex = function (targetResolution, resolutionArray) { var z; for (z = resolutionArray.length - 1; z > 0; z--) { if (resolutionArray[z] >= targetResolution) { return z; } } return 0; }; hic.Browser.prototype.parseLocusString = function (locus) { var self = this, parts, chrName, extent, succeeded, chromosomeNames, locusObject = {}, numeric; parts = locus.trim().split(':'); chromosomeNames = _.map(self.dataset.chromosomes, function (chr) { return chr.name; }); chrName = this.genome.getChromosomeName(parts[0]); if (!_.contains(chromosomeNames, chrName)) { return undefined; } else { locusObject.chr = _.indexOf(chromosomeNames, chrName); } if (parts.length === 1) { // Chromosome name only locusObject.start = 0; locusObject.end = this.dataset.chromosomes[locusObject.chr].size; locusObject.wholeChr = true; } else { extent = parts[1].split("-"); if (extent.length !== 2) { return undefined; } else { numeric = extent[0].replace(/\,/g, ''); locusObject.start = isNaN(numeric) ? undefined : parseInt(numeric, 10) - 1; numeric = extent[1].replace(/\,/g, ''); locusObject.end = isNaN(numeric) ? undefined : parseInt(numeric, 10); } } return locusObject; }; hic.Browser.prototype.setZoom = function (zoom) { this.contactMatrixView.clearCaches(); this.contactMatrixView.computeColorScale = true; // Shift x,y to maintain center, if possible var bpResolutions = this.dataset.bpResolutions, currentResolution = bpResolutions[this.state.zoom], viewDimensions = this.contactMatrixView.getViewDimensions(), xCenter = this.state.x + viewDimensions.width / (2 * this.state.pixelSize), // center in bins yCenter = this.state.y + viewDimensions.height / (2 * this.state.pixelSize), // center in bins newResolution = bpResolutions[zoom], newXCenter = xCenter * (currentResolution / newResolution), newYCenter = yCenter * (currentResolution / newResolution), newPixelSize = Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, zoom)); this.state.zoom = zoom; this.state.x = Math.max(0, newXCenter - viewDimensions.width / (2 * newPixelSize)); this.state.y = Math.max(0, newYCenter - viewDimensions.height / (2 * newPixelSize)); this.state.pixelSize = newPixelSize; this.clamp(); this.eventBus.post(hic.Event("LocusChange", this.state)); }; hic.Browser.prototype.updateLayout = function () { this.state.pixelSize = Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom)); this.clamp(); this.renderTracks(true); this.contactMatrixView.clearCaches(); this.contactMatrixView.update(); }; hic.Browser.prototype.setChromosomes = function (chr1, chr2) { this.state.chr1 = Math.min(chr1, chr2); this.state.chr2 = Math.max(chr1, chr2); this.state.zoom = 0; this.state.x = 0; this.state.y = 0; this.state.pixelSize = Math.min(maxPixelSize, Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom))); this.contactMatrixView.computeColorScale = true; this.eventBus.post(hic.Event("LocusChange", this.state)); }; hic.Browser.prototype.updateLayout = function () { this.state.pixelSize = Math.max(defaultPixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom)); this.clamp(); this.renderTracks(true); this.layoutController.xAxisRuler.update(); this.layoutController.yAxisRuler.update(); this.contactMatrixView.clearCaches(); this.contactMatrixView.update(); }; function minPixelSize(chr1, chr2, zoom) { var viewDimensions = this.contactMatrixView.getViewDimensions(), chr1Length = this.dataset.chromosomes[chr1].size, chr2Length = this.dataset.chromosomes[chr2].size, binSize = this.dataset.bpResolutions[zoom], nBins1 = chr1Length / binSize, nBins2 = chr2Length / binSize; // Crude test for "whole genome" var isWholeGenome = this.dataset.chromosomes[chr1].name === "All"; if (isWholeGenome) { nBins1 *= 1000; nBins2 *= 1000; } return Math.min(viewDimensions.width / nBins1, viewDimensions.height / nBins2); // return Math.min(viewDimensions.width * (binSize / chr1Length), viewDimensions.height * (binSize / chr2Length)); } hic.Browser.prototype.update = function () { this.eventBus.post(hic.Event("LocusChange", this.state)); }; /** * Set the matrix state. Used ot restore state from a bookmark * @param state browser state */ hic.Browser.prototype.setState = function (state) { this.state = state; // Possibly adjust pixel size this.state.pixelSize = Math.max(state.pixelSize, minPixelSize.call(this, this.state.chr1, this.state.chr2, this.state.zoom)); this.eventBus.post(hic.Event("LocusChange", this.state)); }; hic.Browser.prototype.setNormalization = function (normalization) { this.state.normalization = normalization; this.contactMatrixView.computeColorScale = true; this.eventBus.post(hic.Event("NormalizationChange", this.state.normalization)) }; hic.Browser.prototype.shiftPixels = function (dx, dy) { this.state.x += dx; this.state.y += dy; this.clamp(); var locusChangeEvent = hic.Event("LocusChange", this.state); locusChangeEvent.dragging = true; this.eventBus.post(locusChangeEvent); }; hic.Browser.prototype.goto = function (chr1, bpX, bpXMax, chr2, bpY, bpYMax, minResolution) { var xCenter, yCenter, targetResolution, viewDimensions = this.contactMatrixView.getViewDimensions(), viewWidth = viewDimensions.width, maxExtent; if (minResolution === undefined) minResolution = 200; targetResolution = Math.max((bpXMax - bpX) / viewDimensions.width, (bpYMax - bpY) / viewDimensions.height); if (targetResolution < minResolution) { maxExtent = viewWidth * minResolution; xCenter = (bpX + bpXMax) / 2; yCenter = (bpY + bpYMax) / 2; bpX = Math.max(xCenter - maxExtent / 2); bpY = Math.max(0, yCenter - maxExtent / 2); targetResolution = minResolution; } var bpResolutions = this.dataset.bpResolutions, newZoom = this.findMatchingZoomIndex(targetResolution, bpResolutions), newResolution = bpResolutions[newZoom], newPixelSize = Math.max(1, newResolution / targetResolution), newXBin = bpX / newResolution, newYBin = bpY / newResolution; this.state.chr1 = chr1; this.state.chr2 = chr2; this.state.zoom = newZoom; this.state.x = newXBin; this.state.y = newYBin; this.state.pixelSize = newPixelSize; this.contactMatrixView.clearCaches(); this.contactMatrixView.computeColorScale = true; this.eventBus.post(hic.Event("LocusChange", this.state)); }; hic.Browser.prototype.clamp = function () { var viewDimensions = this.contactMatrixView.getViewDimensions(), chr1Length = this.dataset.chromosomes[this.state.chr1].size, chr2Length = this.dataset.chromosomes[this.state.chr2].size, binSize = this.dataset.bpResolutions[this.state.zoom], maxX = (chr1Length / binSize) - (viewDimensions.width / this.state.pixelSize), maxY = (chr2Length / binSize) - (viewDimensions.height / this.state.pixelSize); // Negative maxX, maxY indicates pixelSize is not enough to fill view. In this case we clamp x, y to 0,0 maxX = Math.max(0, maxX); maxY = Math.max(0, maxY); this.state.x = Math.min(Math.max(0, this.state.x), maxX); this.state.y = Math.min(Math.max(0, this.state.y), maxY); }; hic.Browser.prototype.receiveEvent = function (event) { if (event.dragging) return; this.updateHref(event); }; hic.Browser.prototype.resolution = function () { return this.dataset.bpResolutions[this.state.zoom]; }; function gup(href, name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(href); if (results == null) return undefined; else return results[1]; } function replaceURIParameter(key, newValue, href) { var oldValue = gup(href, key); if (oldValue) { href = href.replace(key + "=" + oldValue, key + "=" + encodeURIComponent(newValue)); } else { var delim = href.includes("?") ? "&" : "?"; href += delim + key + "=" + encodeURIComponent(newValue); } return href; } hic.State = function (chr1, chr2, zoom, x, y, pixelSize) { this.chr1 = chr1; this.chr2 = chr2; this.zoom = zoom; this.x = x; this.y = y; this.pixelSize = pixelSize; }; // Set default values for config properties function setDefaults(config) { if (undefined === config.gestureSupport) { config.gestureSupport = false } if (config.miniMode === true) { config.showLocusGoto = false; config.showHicContactMapLabel = false; config.showChromosomeSelector = false; config.updateHref = false; } else { if (undefined === config.updateHref) { config.updateHref = true; } if (undefined === config.showLocusGoto) { config.showLocusGoto = true; } if (undefined === config.showHicContactMapLabel) { config.showHicContactMapLabel = true; } if (undefined === config.showChromosomeSelector) { config.showChromosomeSelector = true } } } function getNviString(dataset, state) { if (state.normalization && "NONE" !== state.normalization && dataset.hicReader.normVectorIndex) { var binSize = dataset.bpResolutions[state.zoom]; var idx1 = dataset.getNormalizationVectorIdx(state.normalization, state.chr1, "BP", binSize); var nviString = String(idx1.filePosition) + "," + String(idx1.size); if (state.chr1 !== state.chr2) { var idx2 = dataset.getNormalizationVectorIdx(state.normalization, state.chr2, "BP", binSize); nviString += "|" + String(idx2.filePosition) + "," + String(idx2.size); } return nviString } else { return undefined; } } return hic; }) (hic || {});
$(document).ready(function() { var prices = document.getElementsByClassName("prc"); var qties = document.getElementsByClassName("qty"); for (var i = 0; i < prices.length; i++) { prices.item(i).addEventListener("change", updateTotal); qties.item(i).addEventListener("change", updateTotal); } updateTotal(); }); function updateTotal() { console.log("Updating total sum"); var sum = 0; var prices = document.getElementsByClassName("prc"); var qties = document.getElementsByClassName("qty"); for (var i = 0; i < prices.length; i++) { sum += prices.item(i).value * qties.item(i).value; } document.getElementsByClassName("total-sum-amount").item(0).textContent = sum.toString() + ".00"; }
'use strict'; var fs = require('fs'); // file system library to read/write files var path = require('path'); // path library to help manipulate paths var UglifyJS = require('uglify-js'); // minify library module.exports = function (skelly, callback) { // set the base directory to look for less files var dir = path.join(skelly.appRoot, skelly.javascriptsRoot); var js = {}; // find all the files in /javascripts skelly.helpers.walk(dir, function(err, files) { /* istanbul ignore if */ if (err) { skelly.intLog.error(err); callback(err); } else { var pending = files.length; files.forEach(function(file) { // minify each file, include the sourcemap in the output var result = UglifyJS.minify( fs.readFileSync(file, "utf8"), { sourceMap: { filename : file.split(skelly.appRoot)[1].split('.js')[0] + '.min.' + skelly.hash + '.js', url:file.split(skelly.appRoot)[1].split('.js')[0] + '.min.' + skelly.hash + '.js.map' } } ); // need to remove the physical path to the sourcemap result.map = result.map ? result.map.replace(skelly.appRoot,'') : /* istanbul ignore next */ ' '; // add the results (code and map) to the global js object js[file.split(dir + '/')[1].split('.js')[0] + '.min' + '.js'] = result; /* istanbul ignore else */ if (!--pending) callback(null, js); }); } }); }; // TODO: add browserify to bundle includes into a single file
$(document).ready(function () { $('#sortBMW').click(function () { $('ol li').css({"color":"red","font-size":"40px","font-family":"Baskerville Old Face"}) }) })
'use strict'; export function routes($locationProvider, $urlRouterProvider, $stateProvider) { $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); $stateProvider .state('waisygh', { url: '/', views: { 'toolbar': { template: require('./toolbar/toolbar.tpl.html') } } }) ; } export function material($mdThemingProvider, $mdIconProvider) { $mdThemingProvider.theme('default') .primaryPalette(<%= theme1 %>) .accentPalette(<%= theme2 %>, { 'default': '500' }) ; $mdIconProvider .defaultIconSet('assets/mdi.svg') ; }
export default [ { name: 'Types', examples: [ { name: 'Statistic', description: 'A statistic can display a value with a label above or below it', file: 'Statistic', }, { name: 'Statistic Group', description: 'A group of statistics', file: 'StatisticGroup', }, ], }, { name: 'Content', examples: [ { name: 'Value', description: 'A statistic can contain a numeric, icon, image, or text value', file: 'StatisticContentValue', }, { name: 'Label', description: 'A statistic can contain a label to help provide context for the presented value', file: 'StatisticContentLabel', }, ], }, { name: 'Variations', examples: [ { name: 'Horizontal Statistic', description: 'A statistic can present its measurement horizontally', file: 'StatisticHorizontal', }, { name: 'Colored', description: 'A statistic can be formatted to be different colors', file: 'StatisticColored', }, { name: 'Inverted', description: 'A statistic can be formatted to fit on a dark background', file: 'StatisticInverted', }, { name: 'Evenly Divided', description: 'A statistic group can have its items divided evenly', file: 'StatisticEvenlyDivided', }, { name: 'Floated', description: 'An statistic can sit to the left or right of other content', file: 'StatisticFloated', }, { name: 'Size', description: 'A statistic can vary in size', file: 'StatisticSize', }, ], }, ];
const emojioneOptions = { styles: { backgroundImage: 'url(images/emojione.sprites.png)' } }; export default emojioneOptions;