code
stringlengths
2
1.05M
"use strict"; var config = require('../config'); var routermgr = require('../lib/routermgr'); //<--require Begin //<--require End const URLROOT = '{{currouter.urlroot}}'; const URL = {{{currouter.urlstr}}}; const HTTPTYPE = routermgr.HTTP_{{currouter.http}}; const NEEDLOGIN = {{currouter.needlogin}}; class Router_{{currouter.name}} extends routermgr.Router{ constructor() { super(HTTPTYPE, URLROOT, URL, NEEDLOGIN); } onProc(req, res, next) { super.onProc(req, res, function () { //<--onProc Begin res.resret.renderJade('views/{{currouter.name_lc}}/{{currouter.name_lc}}.jade'); res.resret.param = {}; res.resret.render(res); //<--onProc End }); } }; routermgr.singleton.addRouter(new Router_{{currouter.name}}());
'use strict'; var Color = require('../../components/color'); var heatmapHoverPoints = require('../heatmap/hover'); module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, hoverLayer, true); if(hoverData) { hoverData.forEach(function(hoverPt) { var trace = hoverPt.trace; if(trace.contours.type === 'constraint') { if(trace.fillcolor && Color.opacity(trace.fillcolor)) { hoverPt.color = Color.addOpacity(trace.fillcolor, 1); } else if(trace.contours.showlines && Color.opacity(trace.line.color)) { hoverPt.color = Color.addOpacity(trace.line.color, 1); } } }); } return hoverData; };
createTest('Nested route with the many children as a tokens, callbacks should yield historic params', { '/a': { '/:id': { '/:id': function(a, b) { shared.fired.push(location.hash, a, b); } } } }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['#/a/b/c', 'b', 'c']); this.finish(); }); }); createTest('Nested route with the first child as a token, callback should yield a param', { '/foo': { '/:id': { on: function(id) { shared.fired.push(location.hash, id); } } } }, function() { shared.fired = []; this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['#/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the first child as a regexp, callback should yield a param', { '/foo': { '/(\\w+)': { on: function(value) { shared.fired.push(location.hash, value); } } } }, function() { shared.fired = []; this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['#/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the several regular expressions, callback should yield a param', { '/a': { '/(\\w+)': { '/(\\w+)': function(a, b) { shared.fired.push(a, b); } } } }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['b', 'c']); this.finish(); }); }); createTest('Single nested route with on member containing function value', { '/a': { '/b': { on: function() { shared.fired.push(location.hash); } } } }, function() { shared.fired = []; this.navigate('/a/b', function() { deepEqual(shared.fired, ['#/a/b']); this.finish(); }); }); createTest('Single non-nested route with on member containing function value', { '/a/b': { on: function() { shared.fired.push(location.hash); } } }, function() { shared.fired = []; this.navigate('/a/b', function() { deepEqual(shared.fired, ['#/a/b']); this.finish(); }); }); createTest('Single nested route with on member containing array of function values', { '/a': { '/b': { on: [function() { shared.fired.push(location.hash); }, function() { shared.fired.push(location.hash); }] } } }, function() { shared.fired = []; this.navigate('/a/b', function() { deepEqual(shared.fired, ['#/a/b', '#/a/b']); this.finish(); }); }); createTest('method should only fire once on the route.', { '/a': { '/b': { once: function() { shared.fired++; } } } }, function() { shared.fired = 0; this.navigate('/a/b', function() { this.navigate('/a/b', function() { this.navigate('/a/b', function() { deepEqual(shared.fired, 1); this.finish(); }); }); }); }); createTest('method should only fire once on the route, multiple nesting.', { '/a': { on: function() { shared.fired++; }, once: function() { shared.fired++; } }, '/b': { on: function() { shared.fired++; }, once: function() { shared.fired++; } } }, function() { shared.fired = 0; this.navigate('/a', function() { this.navigate('/b', function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, 6); this.finish(); }); }); }); }); }); createTest('overlapping routes with tokens.', { '/a/:b/c' : function() { shared.fired.push(location.hash); }, '/a/:b/c/:d' : function() { shared.fired.push(location.hash); } }, function() { shared.fired = []; this.navigate('/a/b/c', function() { this.navigate('/a/b/c/d', function() { deepEqual(shared.fired, ['#/a/b/c', '#/a/b/c/d']); this.finish(); }); }); }); // // // // // // Recursion features // // // ---------------------------------------------------------- createTest('Nested routes with no recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c']); this.finish(); }); }); createTest('Nested routes with backward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b', 'a']); this.finish(); }); }); createTest('Breaking out of nested routes with backward recursion', { '/a': { '/:b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b']); this.finish(); }); }); createTest('Nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b', 'c']); this.finish(); }); }); createTest('Nested routes with forward recursion, single route with an after event.', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); }, after: function() { shared.fired.push('c-after'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { shared.fired = []; this.navigate('/a/b/c', function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['a', 'b', 'c', 'c-after', 'a', 'b']); this.finish(); }); }); }); createTest('Breaking out of nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { shared.fired = []; this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b']); this.finish(); }); }); // // ABOVE IS WORKING // // // // // Special Events // // ---------------------------------------------------------- createTest('All global event should fire after every route', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { '/c': { on: function a() { shared.fired.push('a'); } } }, '/d': { '/:e': { on: function a() { shared.fired.push('a'); } } } }, { after: function() { shared.fired.push('b'); } }, function() { shared.fired = []; this.navigate('/a', function() { this.navigate('/b/c', function() { this.navigate('/d/e', function() { deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a']); this.finish(); }); }); }); }); createTest('Not found.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { notfound: function() { shared.fired.push('notfound'); } }, function() { shared.fired = []; this.navigate('/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['notfound', 'notfound']); this.finish(); }); }); }); createTest('On all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { on: function() { shared.fired.push('c'); } }, function() { shared.fired = []; this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b', 'c']); this.finish(); }); }); }); createTest('After all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { after: function() { shared.fired.push('c'); } }, function() { shared.fired = []; this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b']); this.finish(); }); }); }); createTest('resource object.', { '/a': { '/b/:c': { on: 'f1' }, on: 'f2' }, '/d': { on: ['f1', 'f2'] } }, { resource: { f1: function (name){ shared.fired.push("f1-" + name); }, f2: function (name){ shared.fired.push("f2"); } } }, function() { shared.fired = []; this.navigate('/a/b/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']); this.finish(); }); }); }); createTest('argument matching should be case agnostic', { '/fooBar/:name': { on: function(name) { shared.fired.push("fooBar-" + name); } } }, function() { shared.fired = []; this.navigate('/fooBar/tesTing', function() { deepEqual(shared.fired, ['fooBar-tesTing']); this.finish(); }); }); createTest('sanity test', { '/is/:this/:sane': { on: function(a, b) { shared.fired.push('yes ' + a + ' is ' + b); } }, '/': { on: function() { shared.fired.push('is there sanity?'); } } }, function() { shared.fired = []; this.navigate('/is/there/sanity', function() { deepEqual(shared.fired, ['yes there is sanity']); this.finish(); }); }); createTest('`/` route should be navigable from the routing table', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { shared.fired = []; this.navigate('/', function root() { deepEqual(shared.fired, ['/']); this.finish(); }); }); createTest('`/` route should not override a `/:token` route', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { shared.fired = []; this.navigate('/a', function afunc() { deepEqual(shared.fired, ['/a']); this.finish(); }); }); createTest('should accept the root as a token.', { '/:a': { on: function root() { shared.fired.push(location.hash); } } }, function() { shared.fired = []; this.navigate('/a', function root() { deepEqual(shared.fired, ['#/a']); this.finish(); }); }); createTest('routes should allow wildcards.', { '/:a/b*d': { on: function() { shared.fired.push(location.hash); } } }, function() { shared.fired = []; this.navigate('/a/bcd', function root() { deepEqual(shared.fired, ['#/a/bcd']); this.finish(); }); }); createTest('functions should have |this| context of the router instance.', { '/': { on: function root() { shared.fired.push(!!this.routes); } } }, function() { shared.fired = []; this.navigate('/', function root() { deepEqual(shared.fired, [true]); this.finish(); }); }); createTest('setRoute with a single parameter should change location correctly', { '/bonk': { on: function() { shared.fired.push(window.location.hash); } } }, function() { var self = this; shared.fired = []; this.router.setRoute('/bonk'); setTimeout(function() { deepEqual(shared.fired, ['#/bonk']); self.finish(); }, 14) }); createTest('route should accept _ and . within parameters', { '/:a': { on: function root() { shared.fired.push(location.hash); } } }, function() { shared.fired = []; this.navigate('/a_complex_route.co.uk', function root() { deepEqual(shared.fired, ['#/a_complex_route.co.uk']); this.finish(); }); }); createTest('initializing with a default route should only result in one route handling', { '/': { on: function root() { if (!shared.init){ shared.init = 0; } shared.init++; } }, '/test': { on: function root() { if (!shared.test){ shared.test = 0; } shared.test++; } } }, function() { this.navigate('/test', function root() { equal(shared.init, 1); equal(shared.test, 1); this.finish(); }); }, null, '/'); createTest('changing the hash twice should call each route once', { '/hash1': { on: function root() { shared.fired.push('hash1'); } }, '/hash2': { on: function root() { shared.fired.push('hash2'); } } }, function() { shared.fired = []; this.navigate('/hash1', function(){}); this.navigate('/hash2', function(){ deepEqual(shared.fired, ['hash1', 'hash2']); this.finish(); }); } ); // This test doesn't use the createTest since createTest runs init on the router before // running the test, which is what we want to test. test('fire the correct route when initializing the router', function(){ window.location.hash = 'initial'; var fired = []; var router = new (window.Router || window.RouterAlias)({ '/initial': function(){ fired.push('/initial'); }, 'initial': function(){ fired.push('initial'); } }); router.init(); deepEqual(fired, ['/initial', 'initial']); router.destroy(); }); test('do not combine hash if convert_hash_in_init is false', function(){ window.location.hash = 'initial'; var fired = []; var initialPath = window.location.pathname; var routes = { '/initial': function(){ fired.push('/initial'); }, 'initial': function(){ fired.push('initial'); } }; routes[initialPath] = function(){ fired.push('*'); }; var router = new (window.Router || window.RouterAlias)(routes); router.configure({ html5history: true, convert_hash_in_init: false }); router.init(); deepEqual(fired, ['*']); router.destroy(); }); createTest('routes should parse query string parameters.', { '/:a/b': function() { } }, function() { this.navigate('/foo/b?x==y&z&x=2', function root() { deepEqual(this.router.getRoute(), ['foo', 'b']); deepEqual(this.router.query, {x: ['=y', '2'], z: true}); this.finish(); }); }); createTest('routes without query strings should yield no query.', { '/:a/b': function() { } }, function() { this.navigate('/foo/b', function root() { equal(this.router.query, null); this.finish(); }); });
YUI.add('dom-style-ie', function (Y, NAME) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] === AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] === 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter === 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val <= 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } }, 'patched-v3.16.0', {"requires": ["dom-style", "color-base"]});
const {Models} = require('../db'); const util = require('./util'); module.exports = router => { util.b(router, 'promos'); router.post('/promos', (req, res) => { const promoToSave = req.body; console.log(promoToSave); if (!promoToSave.id) { Models.promos.create(promoToSave).then(result => { const promo = result; Promise.all( promo.setPlatos(promoToSave.platos.map((plato) => plato.id)), promo.setProductos(promoToSave.productos.map((producto) => producto.id)) ).then(res.json(promo)); }); } else { Models.promos.upsert(promoToSave).then(() => { Models.promos.findById(promoToSave.id).then(promo => { Promise.all( promo.setPlatos(promoToSave.platos.map((plato) => plato.id)), promo.setProductos(promoToSave.productos.map((producto) => producto.id)) ).then(res.json(promo)); }); }); } }); router.get('/promos', (req, res) => { Models.promos.findAll({ include: [ { model: Models.platos }, { model: Models.productos } ] }).then(result => { res.json(result); }); }); router.get('/promos/:id', (req, res) => { Models.promos.findById(req.params.id, { include: [ { model: Models.platos }, { model: Models.productos } ] }).then(result => { res.json(result); }); }); };
"use strict"; var utils = require("../utils"); var log = require("npmlog"); function formatData(data) { return { userID: utils.formatID(data.uid.toString()), photoUrl: data.photo, indexRank: data.index_rank, name: data.text, isVerified: data.is_verified, profileUrl: data.path, category: data.category, score: data.score, }; } module.exports = function(defaultFuncs, api, ctx) { return function getUserID(name, callback) { if(!callback) { throw {error: "getUserID: need callback"}; } var form = { 'value' : name.toLowerCase(), 'viewer' : ctx.userID, 'rsp' : "search", 'context' : "search", 'path' : "/home.php", 'request_id' : utils.getGUID(), }; defaultFuncs .get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form) .then(utils.parseAndCheckLogin(ctx, defaultFuncs)) .then(function(resData) { if (resData.error) { throw resData; } var data = resData.payload.entries; if(data[0].type !== "user") { throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path}; } callback(null, data.map(formatData)); }) .catch(function(err) { log.error("getUserID", err); return callback(err); }); }; };
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.drawing.manager.Canvas"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.drawing.manager.Canvas"] = true; dojo.provide("dojox.drawing.manager.Canvas"); (function(){ dojox.drawing.manager.Canvas = dojox.drawing.util.oo.declare( // summary: // Creates a dojox.gfx.surface to be used for Drawing. Note that // The 'surface' that Drawing uses is actually a dojox.gfx.group. // This allows for more versatility. // // Called internally from a dojox.Drawing. // // Note: Surface creation is asynchrous. Connect to // onSurfaceReady in Drawing. // function(/*Object*/options){ dojo.mixin(this, options); var dim = dojo.contentBox(this.srcRefNode); this.height = this.parentHeight = dim.h; this.width = this.parentWidth = dim.w; this.domNode = dojo.create("div", {id:"canvasNode"}, this.srcRefNode); dojo.style(this.domNode, { width:this.width, height:"auto" }); dojo.setSelectable(this.domNode, false); this.id = this.id || this.util.uid("surface"); console.info("create canvas"); this.gfxSurface = dojox.gfx.createSurface(this.domNode, this.width, this.height); this.gfxSurface.whenLoaded(this, function(){ setTimeout(dojo.hitch(this, function(){ this.surfaceReady = true; if(dojo.isIE){ //this.gfxSurface.rawNode.parentNode.id = this.id; }else if(dojox.gfx.renderer == "silverlight"){ this.id = this.domNode.firstChild.id }else{ //this.gfxSurface.rawNode.id = this.id; } this.underlay = this.gfxSurface.createGroup(); this.surface = this.gfxSurface.createGroup(); this.overlay = this.gfxSurface.createGroup(); this.surface.setTransform({dx:0, dy:0,xx:1,yy:1}); this.gfxSurface.getDimensions = dojo.hitch(this.gfxSurface, "getDimensions"); if(options.callback){ options.callback(this.domNode); } }),500); }); this._mouseHandle = this.mouse.register(this); }, { // zoom: [readonly] Number // The amount the canvas is zoomed zoom:1, useScrollbars: true, baseClass:"drawingCanvas", resize: function(width, height){ // summary: // Method used to change size of canvas. Potentially // called from a container like ContentPane. May be // called directly. // this.parentWidth = width; this.parentHeight = height; this.setDimensions(width, height); }, setDimensions: function(width, height, scrollx, scrolly){ // summary: // Internal. Changes canvas size and sets scroll position. // Do not call this, use resize(). // // changing the size of the surface and setting scroll // if items are off screen var sw = this.getScrollWidth(); //+ 10; this.width = Math.max(width, this.parentWidth); this.height = Math.max(height, this.parentHeight); if(this.height>this.parentHeight){ this.width -= sw; } if(this.width>this.parentWidth){ this.height -= sw; } this.mouse.resize(this.width,this.height); this.gfxSurface.setDimensions(this.width, this.height); this.domNode.parentNode.scrollTop = scrolly || 0; this.domNode.parentNode.scrollLeft = scrollx || 0; if(this.useScrollbars){ //console.info("Set Canvas Scroll", (this.height > this.parentHeight), this.height, this.parentHeight) dojo.style(this.domNode.parentNode, { overflowY: this.height > this.parentHeight ? "scroll" : "hidden", overflowX: this.width > this.parentWidth ? "scroll" : "hidden" }); }else{ dojo.style(this.domNode.parentNode, { overflowY: "hidden", overflowX: "hidden" }); } }, setZoom: function(zoom){ // summary: // Internal. Zooms canvas in and out. this.zoom = zoom; this.surface.setTransform({xx:zoom, yy:zoom}); this.setDimensions(this.width*zoom, this.height*zoom) }, onScroll: function(){ // summary: // Event fires on scroll.NOT IMPLEMENTED }, getScrollOffset: function(){ // summary: // Get the scroll position of the canvas return { top:this.domNode.parentNode.scrollTop, left:this.domNode.parentNode.scrollLeft }; // Object }, getScrollWidth: function(){ // summary: // Special method used to detect the width (and height) // of the browser scrollbars. Becomes memoized. // var p = dojo.create('div'); p.innerHTML = '<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:0;left:-1000px;"><div style="height:100px;"></div>'; var div = p.firstChild; dojo.body().appendChild(div); var noscroll = dojo.contentBox(div).h; dojo.style(div, "overflow", "scroll"); var scrollWidth = noscroll - dojo.contentBox(div).h; dojo.destroy(div); this.getScrollWidth = function(){ return scrollWidth; }; return scrollWidth; // Object } } ); })(); }
/* jshint node:true */ 'use strict'; var Node = require('./node.js'), sys = require('sys'); /** * A processing instruction provides an opportunity for application-specific instructions to be embedded within XML * and which can be ignored by XML processors which do not support processing their instructions (outside of their * having a place in the DOM). * @name ProcessingInstruction * @type constructor * @access internal * @param Simple object * @return ProcessingInstruction */ function ProcessingInstruction(simple) { ProcessingInstruction.super_.apply(this, [simple]); } // ProcessingInstruction extends Node sys.inherits(ProcessingInstruction, Node); ProcessingInstruction.prototype.toString = function() { return '[object DOMProcessingInstruction]'; }; // Expose the ProcessingInstruction module module.exports = ProcessingInstruction;
/** * @fileoverview added by tsickle * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ goog.module('test_files.generic_fn_type.generic_fn_type'); var module = module || { id: 'test_files/generic_fn_type/generic_fn_type.ts' }; module = module; exports = {}; /** * A function type that includes a generic type argument. Unsupported by * Closure, so tsickle should emit ?. * @type {function(?): ?} */ let genericFnType = (/** * @param {T} x * @return {T} */ (x) => x); /** @type {function(new:?, ?)} */ let genericCtorFnType;
"use strict"; /* Quiz App */ /* Controllers */ // Main page controller angular.module("wuzQuizFrontendApp.controllers").controller("MainCtrl", function($scope, $stateParams, $rootScope,Session) { $scope.$on("identifyStatusChanged", function(args, payload) { console.log(payload); $scope.noticeMessage = payload; //.) }); $scope.Session = Session.getSession(); }); angular.module("wuzQuizFrontendApp.controllers").controller("NavbarCtrl",function($scope,Session,$rootScope){ $rootScope.user_id=Session.getSession().user_id; });
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var handleErrors = require('../util/handleErrors'); var config = require('../config').sass; var autoprefixer = require('gulp-autoprefixer'); gulp.task('sass', function () { return gulp.src(config.src) .pipe(sourcemaps.init()) .pipe(sass(config.settings)) .on('error', handleErrors) .pipe(sourcemaps.write()) .pipe(autoprefixer({ browsers: [ 'last 2 version' ] })) .pipe(gulp.dest(config.dest)) .pipe(browserSync.reload({ stream: true })); });
"use strict"; function MainCtrl () { } angular .module('admin.ngApp', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap']) .controller('MainCtrl', MainCtrl) .config(["$asideProvider", function($asideProvider) { angular.extend( $asideProvider.defaults,{container:"body",html:!0} ); }]); function AsideCtrl ($scope) { $scope.aside = { title:"Settings", content:"<br/>" } } angular.module("admin.ngApp") .controller("AsideCtrl", AsideCtrl); function TypeaheadCtrl ($scope, $http) { $scope.selectedContent = "Content"; $scope.selectedTags = "Tags"; $scope.selectedTitle = ""; $scope.getEntries = function(viewValue) { var args = {title: viewValue}; return $http.get('/admin/entries.json?', {params: args}).then( function(e) { return e.data.entries }); }; } angular.module("admin.ngApp") .controller("TypeaheadCtrl", TypeaheadCtrl);
/* * app.js */ var config = require('./config') // 用于生产环境 if (!config.debug) { } require('colors'); var path = require("path"); var Loader = require("loader"); var express = require("express"); var errorhandler = require('errorhandler'); var session = require('express-session'); var passport = require("passport"); // require('./middlewares/mongoose_log'); // 打印 mongodb 查询日志 require('./models'); var router = require("./router") var auth = require('./middlewares/auth'); var errorPageMiddleware = require("./middlewares/error_page"); // var proxyMiddleware = require('./middlewares/proxy'); var RedisStore = require('connect-redis')(session); // var MongoStore = require('connect-mongo')(session); var _ = require('lodash'); var csurf = require('csurf'); var compress = require('compression'); var bodyParser = require('body-parser'); var requestLog = require('./middlewares/request_log'); var errorhandler = require('errorhandler'); var renderMiddleware = require('./middlewares/render'); var logger = require("./common/logger"); var busboy = require('connect-busboy'); // 静态文件目录 var staticDir = path.join(__dirname, 'public'); var exphbs = require('express-handlebars'); var connection_string = config.db; // assets var assets = {}; if (config.mini_assets) { try { assets = require('./assets.json'); } catch (e) { console.log('You must execute `make build` before start app when mini_assets is true.'); throw e; } } var urlinfo = require('url').parse(config.host); config.hostname = urlinfo.hostname || config.host; var app = express(); // configuration in all env app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.engine('html', require('ejs-mate')); app.locals._layoutFile = 'layout.html'; app.enable('trust proxy'); // Request logger 请求时间 app.use(requestLog); if (config.debug) { // 渲染时间 app.use(renderMiddleware.render); } // 静态资源 app.use(Loader.less(__dirname)); app.use('/public', express.static(staticDir)); // 每日访问限制 app.use(require('response-time')()); app.use(bodyParser.json({limit: '1mb'})); app.use(bodyParser.urlencoded({ extended: true, limit: '1mb' })); app.use(require('method-override')()); var cookieParser = require('cookie-parser')(config.session_secret); app.use(cookieParser); app.use(compress()); var session = session({ secret: config.session_secret, store: new RedisStore({ url: connection_string }), resave: true, saveUninitialized: true, }) app.use(session); app.use(passport.initialize()); // custom middleware app.use(auth.authUser); // app.use(auth.blockUser()); if (!config.debug) { app.use(function (req, res, next) { if (req.path.indexOf('/api') === -1) { csurf()(req, res, next); return; } next(); }); app.set('view cache', true); } // set static, dynamic helpers _.extend(app.locals, { config: config, Loader: Loader, assets: assets }); app.use(errorPageMiddleware.errorPage); // _.extend(app.locals, require('./common/render_helper')); app.use(function (req, res, next) { res.locals.csrf = req.csrfToken ? req.csrfToken() : ''; next(); }); app.use(busboy({ limits: { fileSize: 10 * 1024 * 1024 // 10MB } })); app.use('/', router); // error handler if (config.debug) { app.use(errorhandler()); } else { app.use(function (err, req, res, next) { console.error('server 500 error:', err); return res.status(500).send('500 status'); }); } // 配置socket.io var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(config.port, function () { logger.log("NodeClub listening on port %d", config.port); logger.log("God bless love...."); logger.log("You can debug your app with http://" + config.host + ':' + config.port); logger.log(""); }); io.use(function(socket, next) { session(socket.handshake, {}, next); }); io.on('connection', function (socket) { socket.on('connection name',function(user){ io.sockets.emit('new user', user.name + " has joined."); }) }); module.exports = app;
'use strict'; (function() { // Sciprotos Controller Spec describe('Sciprotos Controller Tests', function() { // Initialize global variables var SciprotosController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Sciprotos controller. SciprotosController = $controller('SciprotosController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Sciproto object fetched from XHR', inject(function(Sciprotos) { // Create sample Sciproto using the Sciprotos service var sampleSciproto = new Sciprotos({ name: 'New Sciproto' }); // Create a sample Sciprotos array that includes the new Sciproto var sampleSciprotos = [sampleSciproto]; // Set GET response $httpBackend.expectGET('sciprotos').respond(sampleSciprotos); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.sciprotos).toEqualData(sampleSciprotos); })); it('$scope.findOne() should create an array with one Sciproto object fetched from XHR using a sciprotoId URL parameter', inject(function(Sciprotos) { // Define a sample Sciproto object var sampleSciproto = new Sciprotos({ name: 'New Sciproto' }); // Set the URL parameter $stateParams.sciprotoId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/sciprotos\/([0-9a-fA-F]{24})$/).respond(sampleSciproto); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.sciproto).toEqualData(sampleSciproto); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Sciprotos) { // Create a sample Sciproto object var sampleSciprotoPostData = new Sciprotos({ name: 'New Sciproto' }); // Create a sample Sciproto response var sampleSciprotoResponse = new Sciprotos({ _id: '525cf20451979dea2c000001', name: 'New Sciproto' }); // Fixture mock form input values scope.name = 'New Sciproto'; // Set POST response $httpBackend.expectPOST('sciprotos', sampleSciprotoPostData).respond(sampleSciprotoResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Sciproto was created expect($location.path()).toBe('/sciprotos/' + sampleSciprotoResponse._id); })); it('$scope.update() should update a valid Sciproto', inject(function(Sciprotos) { // Define a sample Sciproto put data var sampleSciprotoPutData = new Sciprotos({ _id: '525cf20451979dea2c000001', name: 'New Sciproto' }); // Mock Sciproto in scope scope.sciproto = sampleSciprotoPutData; // Set PUT response $httpBackend.expectPUT(/sciprotos\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/sciprotos/' + sampleSciprotoPutData._id); })); it('$scope.remove() should send a DELETE request with a valid sciprotoId and remove the Sciproto from the scope', inject(function(Sciprotos) { // Create new Sciproto object var sampleSciproto = new Sciprotos({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Sciprotos array and include the Sciproto scope.sciprotos = [sampleSciproto]; // Set expected DELETE response $httpBackend.expectDELETE(/sciprotos\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleSciproto); $httpBackend.flush(); // Test array after successful delete expect(scope.sciprotos.length).toBe(0); })); }); }());
/** * Index Template By => create-module script * @version 1.0.0 * */ export { default } from './PublicationAddToListFormContainer';
if (typeof window !== 'undefined') { window.Tracker = require('./index'); }
'use strict'; const Promise = require('bluebird'); const bcrypt = Promise.promisifyAll(require('bcrypt')); const Model = require('./model'); /** * A simple user model. Part of the schema is implicitly inherited from Model, * i.e., the primary key and the timestamps. */ class User extends Model { get childSchema () { return { email: { type: 'string', notNull: true, hidden: true, validate: (value) => value.includes('@') }, password: { type: 'string', notNull: true, hidden: true, transform: this.encryptPassword, validate: (value) => value.length >= 6 }, name: { type: 'string', notNull: true } }; } /** * Salt and hash the password with bcrypt. * * @param {String} password The password to encrypt. * @returns {Promise} Resolves to the encrypted password. */ encryptPassword (password) { return bcrypt.genSaltAsync(10).then(salt => { return bcrypt.hashAsync(password, salt); }); } } module.exports = User;
import React from 'react'; class ProgressBar extends React.Component { render() { let value = this.props.children !== null ? <div className="progress-bar-label-value">{this.props.children}</div> : null; return <div className={`progress-bar${value === null ? ' progress-bar__small' : ''}`}> <div className="progress-bar-label" style={{width: this.props.percent + '%'}}>{value}</div> </div>; } } ProgressBar.propTypes = { children: React.PropTypes.node, percent: React.PropTypes.number.isRequired }; ProgressBar.defaultProps = { children: null }; export default ProgressBar;
import {inject, bindable} from 'aurelia-framework'; import {Collections} from 'services/collections'; import {DataContext} from 'services/datacontext'; import {Character, Person} from 'models/index'; @inject(Collections, DataContext) export class Home{ heading = 'Choose a planet...'; @bindable selectedPlanet; character; mapRows = []; constructor(collections, datacontext){ this.collections = collections; this.datacontext = datacontext; this.character = new Character(); } selectedPlanetChanged(){ if (this.selectedPlanet) { this.selectedPlanet.residents.forEach(resident => { this.datacontext.getResource(resident).then(resp => { let newResident = new Person(resp.content) this.selectedPlanet.fetchedResidents.push(newResident); this.recalculateMap(); }); }); } } recalculateMap(){ if (this.selectedPlanet) { let surface = this.selectedPlanet.surface; let residents = this.selectedPlanet.fetchedResidents; let allRows = []; let returnRows = []; surface.blocks.forEach(block => { if (allRows.indexOf(block.row) === -1) { allRows.push(block.row) } }); allRows.forEach(row => { let newRow = surface.blocks.filter(block => { return block.row === row; }); returnRows.push(newRow); }); this.mapRows = returnRows; let startingPosition = surface.findStart(); this.character.moveToTile(startingPosition); let newSpot = this.getTile(this.character.x, this.character.y); newSpot.showChar(); residents.forEach(resident => { console.log(resident); if (!resident.onMap) { resident.showOnMap(this.selectedPlanet.surface); } }); } } getTile(x,y){ return this.selectedPlanet.surface.blocks.filter(block => { return block.row === x && block.column === y; })[0]; } move(dir){ let char = this.character; let oldSpot = this.getTile(char.x, char.y); oldSpot.clear(); char.move(dir); let newSpot = this.getTile(char.x, char.y); if (!newSpot.canBeMovedTo()) { newSpot = oldSpot; char.moveToTile(oldSpot); } newSpot.showChar(); } }
'use strict'; /* Controllers */ (function(module) { module.controller('ResumeCtrl', ['$timeout', '$scope', function($timeout, $scope) { }]); })(window.CtrlModule);
// Generated by IcedCoffeeScript 1.8.0-a (function() { module.exports = function() { if (this.shouldLoadScript) { coffeescript(function() { return window.minicms_component_markdown = function(prefix, form, name) { var editor, field; field = $('#field-' + form + '-' + name); console.log(name + " = " + $('#' + form + '-form').data('fields')[name]); field.data('value', $('#' + form + '-form').data('fields')[name]); editor = field.data('epiceditor'); if (editor == null) { field.data('epiceditor', true); return $(document).ready(function() { var defaultVal; defaultVal = field.data('value'); if (typeof defaultVal !== 'string') { defaultVal = ''; } return setTimeout((function() { editor = new EpicEditor({ container: 'form-input-' + form + '-' + name + '--epiceditor', basePath: '/' + prefix + '/vendor/epiceditor', clientSideStorage: false, file: { defaultContent: defaultVal }, button: { preview: true, fullscreen: false }, theme: { base: '/themes/base/epiceditor.css', preview: '/../../css/epic-preview-minicms.css', editor: '/../../css/epic-editor-minicms.css' } }); field.data('epiceditor', editor); editor.load(function() { return $(this.getElement('editor').body).bind('paste', function() { return setTimeout((function() { return editor.sanitize(); }), 1); }); }); $('#form-input-' + form + '-' + name + '--epiceditor iframe').css('visibility', 'hidden'); setTimeout((function() { $('#form-input-' + form + '-' + name + '--epiceditor iframe').css('visibility', 'visible'); return minicms_form_load(prefix, form, name); }), 250); return editor.on('update', function() { var text; text = editor.exportFile(); console.log(name + " = " + text); field.data('value', text); return minicms_form_update(prefix, form); }); }), 100); }); } }; }); } div('#field-' + this.form + '-' + this.field + '.control-group.form-component-markdown', function() { return div('.form-field-content', function() { label('.control-label', { "for": "form-input-" + this.form + "-" + this.field }, function() { return h(this.label); }); return div('.controls', function() { return div('#form-input-' + this.form + '-' + this.field + '--epiceditor.input-xlarge.fake-field', { style: "width:600px;height:" + (this.height ? this.height : 320) + "px" }, function() {}); }); }); }); return text('<script type="text/javascript">minicms_component_markdown("' + this.config.prefix.url + '", "' + this.form + '", "' + this.field + '");</script>'); }; }).call(this);
var app = angular.module('cc98.controllers') app.controller('boardSubCtrl', function ($scope, $http, $stateParams) { $scope.title = $stateParams.title; $scope.doRefresh = function () { var boardRootId = $stateParams.id; $http.get('http://api.cc98.org/board/' + boardRootId + '/subs') .success(function (newItems) { $scope.boardSubs = newItems; }) .finally(function () { $scope.$broadcast('scroll.refreshComplete'); }); }; //根据板块今日帖数的多少来确定label的颜色 $scope.labelColor = function (postCount) { if (postCount != undefined) { if (postCount == 0) return "label-default"; else if (postCount < 10) return "label-info"; else if (postCount < 50) return "label-primary"; else if (postCount < 100) return "label-success"; else if (postCount < 200) return "label-energized"; else if (postCount < 500) return "label-royal"; else if (postCount < 1000) return "label-pink"; else return "label-danger"; } } });
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Chatbubble extends React.Component { render() { if(this.props.bare) { return <g> <path d="M256,449.4c28.9,0,56.4-5.7,81.3-15.9c0.6-0.3,1.1-0.5,1.7-0.7c0.1,0,0.2,0,0.2-0.1c3.5-1.3,7.3-2,11.2-2 c4.3,0,8.4,0.8,12.1,2.4l84,30.9l-22.1-88.4c0-5.3,1.5-10.3,3.9-14.6c0,0,0,0,0,0c0.8-1.3,1.6-2.6,2.5-3.7 c20.9-31.3,33-68.5,33-108.4C464,137.9,370.9,48,256,48C141.1,48,48,137.9,48,248.7C48,359.6,141.1,449.4,256,449.4z"></path> </g>; } return <IconBase> <path d="M256,449.4c28.9,0,56.4-5.7,81.3-15.9c0.6-0.3,1.1-0.5,1.7-0.7c0.1,0,0.2,0,0.2-0.1c3.5-1.3,7.3-2,11.2-2 c4.3,0,8.4,0.8,12.1,2.4l84,30.9l-22.1-88.4c0-5.3,1.5-10.3,3.9-14.6c0,0,0,0,0,0c0.8-1.3,1.6-2.6,2.5-3.7 c20.9-31.3,33-68.5,33-108.4C464,137.9,370.9,48,256,48C141.1,48,48,137.9,48,248.7C48,359.6,141.1,449.4,256,449.4z"></path> </IconBase>; } };Chatbubble.defaultProps = {bare: false}
import html from 'bel' import Events from 'plug/core/Events' import ShowUserRolloverEvent from 'plug/events/ShowUserRolloverEvent' import users from 'plug/collections/users' import getUserClasses from 'extplug/util/getUserClasses' export default function UserBadge (uid) { const user = users.findWhere({ id: uid }) if (user) { return html` <div class="extp-UserBadge user ${getUserClasses(uid).join(' ')}" onclick=${onclick}> <div class="extp-UserBadge-img"> <div class="thumb small"> <i class="avi avi-${user.get('avatarID')}"></i> </div> </div> <span class="extp-UserBadge-name"> ${user.get('username')} </span> </div> ` } else { // TODO load user using a bulk load action const placeholder = html`<div />` return placeholder } function onclick (event) { const el = $(event.target).closest('.extp-UserBadge') Events.dispatch(new ShowUserRolloverEvent(ShowUserRolloverEvent.SHOW, user, { x: el.offset().left - 6, y: el.offset().top }, true)) } }
var geometry__rect_8h = [ [ "reduce", "namespacehryky_1_1geometry.html#a18354ece30244aa68fc3744f2cdb41fc", null ], [ "swap", "namespacehryky_1_1geometry.html#a73028b267b1f3811ebacb86acbee6742", null ] ];
/* * reqHelper.js * https://github.com/skalio/teambeamjs * * Copyright (c) 2015 Skalio GmbH * Licensed under the MIT license. * * @license */ /* global process */ 'use strict'; var Q = require('q'), fs = require('fs'), request = require('request'), https = require('https'), settings = require('./settings'), logHelper = require('./logHelper'); // setup initial session. http client "request" var session = request.defaults({jar: true}); //enable cookies var g_options = { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json, text/javascript, */*', 'Accept-Charset': 'utf-8', 'user-agent': settings.getUserAgent() }, agent: https.globalAgent, // enables SSL support json: true }; /** * Convenience function, making a HTTP GET request to the given URL. * * @param {string} url * @returns {Q.Promise} */ exports.get = function(url) { return exports.call( { url: url, method: 'get' } ); }; /** * Convenience function, making a HTTP GET request to the given URL. Once * resolved, the value of the promise will be a stream. * * @param {string} url * @param {object} options * @returns {Q.Promise} */ exports.getAsStream = function(url, options) { return exports.call( { url: url, method: 'get', stream: true, path: options.basedir, objectIdOrName: options.use_filename } ); }; /** * Convenience function, making a HTTP POST request to the given URL. The body * must be an object which will be JSON encoded. * * @param {string} url * @param {object} body * @returns {Q.Promise} */ exports.post = function(url, body) { g_options.url = url; g_options.method ='post'; g_options.body = body; var length = Buffer.byteLength(JSON.stringify(body), 'utf8'); g_options.headers['Content-Length'] = length; return exports.call(g_options); }; /** * Convenience function, making a HTTP DELETE request to the given URL. * * @param {string} url * @returns {Q.Promise} */ exports.delete = function(url) { return exports.call( { url: url, method: 'delete' } ); }; /** * Convenience function, making a HTTP PUT request to the given URL. The * given file must refer to a local file. The given token is inserted * as auth-token-header * * @param {string} url * @param {file} file * @param {string} token * @returns {Q.Promise} */ exports.putFile = function(url, file, token) { return exports.call( { url: url, method: 'put', filename: file.path, json: false, headers: { 'X-Skp-Auth': token, 'Content-length': file.size, 'Content-type': 'application/octet-stream' } } ); }; exports.call = function(options) { var promise = _makeRequest(options); promise = promise.fail(function(error) { switch (error.httpStatusCode) { case 401 : if (options.url.endsWith('/auth/login')) { // failed login attempts won't get any better when retrying throw error; } if (options.url.endsWith('/auth/logout')) { // attempting to logout a non-existing session... return Q.resolve(); } logHelper.consoleOutput('Session has timed out. Reauthenticating and retrying...'); return process.principal.login().then(function() { // retry only once return _makeRequest(options); }); // unreachable case 410 : logHelper.consoleOutput('The API has been closed, need to update client'); throw error; case 503 : var delay = 60; // in seconds logHelper.consoleOutput('Server is currently in maintenance, retrying in ' + delay + ' seconds'); return Q.delay(delay * 1000).then(function() { // retry forever return exports.call(options); }); default : throw error; } }); return promise; }; /** * Makes the HTTP request and resolves the returned promise with the result. * In the event of an unfavourable HTTP response code, the promise will be * rejected with an extended Error object. * * @param {object} options * @returns {Q.Promise} */ function _makeRequest(options) { var defer = Q.defer(); options = options || {}; options.method = options.method || "get"; var proxy = settings.getProxy(); if(typeof proxy !== "undefined") { options.proxy = proxy; } //callback function function callback(error, response, body) { if(error) { throw error; } if (response.statusCode >= 400) { defer.reject(_exceptionToError(response)); } else { if (options.method === "put" || options.stream) { defer.resolve(response); } else { defer.resolve(response.body); } } } //making request if(options.method === "put") { fs.createReadStream(options.filename).pipe(session(options, callback)); } else if(options.stream) { session(options, callback).pipe(fs.createWriteStream(options.path + "/" + options.objectIdOrName)); } else { session(options, callback); } return defer.promise; } /** * Creates an Error based on the response body format * @param {http.IncomingMessage} response * @returns {Error} */ function _exceptionToError(response) { var parts = []; if (response.body.error) { parts = [response.body.error.message].concat(response.body.error.details); } var error = new Error(parts.join(' ')); error.httpStatusCode = response.statusCode; error.code = 0; if (typeof response.body.error !== "undefined" && response.body.error.code) { error.code = response.body.error.code; } return error; } /** * Checks if a given string conforms to a email address. * @param {string} querystring * @returns Promise */ exports.validateEmail = function (querystring) { var deferred = Q.defer(); var validateEmail = settings.getBaseUrl() + "/rs/v1/validate/email?q=" + encodeURIComponent(querystring); exports.get(validateEmail) .then(function(result) { deferred.resolve(result); }); return deferred.promise; };
/* global Chart */ 'use strict'; window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; window.randomScalingFactor = function() { return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100); };
'use strict' const voucherifyClient = require('../src/index') const voucherify = voucherifyClient({ applicationId: 'c70a6f00-cf91-4756-9df5-47628850002b', clientSecretKey: '3266b9f8-e246-4f79-bdf0-833929b1380c' }) const payload = { name: 'Apple iPhone 6', metadata: { type: 'normal' }, attributes: [ 'attr_one', 'attr_two' ] } let skuId = null console.log('==== CREATE ====') voucherify.products.create(payload) .then((product) => { console.log('New Product: ', product) console.log('==== READ ====') return voucherify.products.get(product.id) .then((result) => { console.log('Result: ', result) return }) .then(() => { console.log('==== CREATE - SKU ====') const sku = { sku: 'APPLE_IPHONE_6_BLACK' } return voucherify.products.createSku(product.id, sku) .then((sku) => { console.log('Result: ', sku) console.log('==== GET - SKU ====') return voucherify.products.getSku(product.id, sku.id) .then((sku) => { console.log('Result: ', sku) console.log('==== UPDATE - SKU ====') sku.sku = 'eur' sku.price = 1000 return voucherify.products.updateSku(product.id, sku) }) }) .then((sku) => { console.log('Result: ', sku) skuId = sku.id return product }) }) }) .then((product) => { console.log('==== UPDATE ====') product.metadata = product.metadata || {} product.metadata.type = 'premium' return voucherify.products.update(product) .then((result) => { console.log('Result: ', JSON.stringify(result, null, 2)) return product }) }) .then((product) => { if (!skuId) { return product } console.log('==== DELETE - SKU ====') return voucherify.products.deleteSku(product.id, skuId) .then(() => { console.log('Checking...') return voucherify.products.getSku(product.id, skuId) .catch((err) => { console.log('Result:', err) return product }) .then((product) => { skuId = null return product }) }) }) .then((product) => { console.log('==== DELETE ====') return voucherify.products.delete(product.id) .then(() => { console.log('Checking...') return voucherify.products.get(product.id) .catch((err) => { console.log('Result:', err) }) }) }) .catch((err) => { console.error('Error: ', err, err.stack) })
"use babel"; import github from './github'; import git from './git'; module.exports = {github, git};
// Database.js module.exports = function Database(configuration) { var mongoose = require('mongoose'); var mongooseUri = process.env.MONGO_STRING || process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://' + configuration.host + configuration.database; console.log('mongooseURI = ' + mongooseUri); mongoose.connect(mongooseUri); };
var request = require('request'); var et = require('elementtree'); var prettyBytes = require('pretty-bytes'); module.exports = { list: function (folder) { console.log(''); var folders = folder.findall('folders/folder'); folders.forEach(function(folder) { if (!folder.get('deleted')) console.log('<DIR>' + '\t' + folder.get('name')); }, this); var files = folder.findall('files/file'); files.forEach(function(file) { if (!file.get('deleted')) { var currentRevision = file.find('currentRevision'); if (currentRevision) console.log(currentRevision.findtext('modified') + '\t' + prettyBytes(parseInt(currentRevision.findtext('size'), 10)) + '\t' + file.get('name')); } }); } }
import { combineReducers } from 'redux' import FiltersReducer from './FiltersReducer' import TasksReducer from './TasksReducer' module.exports = combineReducers({ tasks: TasksReducer, filters: FiltersReducer, })
module.exports = function (a, b, options) { if (a === b) { return options.fn(this); } };
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Util = require('../../Util'); var SaklientException = require('../../errors/SaklientException'); var Resource = require('./Resource'); 'use strict'; /** * アイコンの実体1つに対応し、属性の取得や操作を行うためのクラス。 * * @module saklient.cloud.resources.Icon * @class Icon * @constructor * @extends Resource */ var Icon = (function (_super) { __extends(Icon, _super); /** * @private * @constructor * @param {Client} client * @param {any} obj * @param {boolean} wrapped=false */ function Icon(client, obj, wrapped) { if (typeof wrapped === "undefined") { wrapped = false; } _super.call(this, client); /** * @member saklient.cloud.resources.Icon#n_id * @default false * @type boolean * @private */ this.n_id = false; /** * @member saklient.cloud.resources.Icon#n_scope * @default false * @type boolean * @private */ this.n_scope = false; /** * @member saklient.cloud.resources.Icon#n_name * @default false * @type boolean * @private */ this.n_name = false; /** * @member saklient.cloud.resources.Icon#n_url * @default false * @type boolean * @private */ this.n_url = false; Util.validateArgCount(arguments.length, 2); Util.validateType(client, "saklient.cloud.Client"); Util.validateType(wrapped, "boolean"); this.apiDeserialize(obj, wrapped); } /** * @private * @method _apiPath * @protected * @return {string} */ Icon.prototype._apiPath = function () { return "/icon"; }; /** * @private * @method _rootKey * @protected * @return {string} */ Icon.prototype._rootKey = function () { return "Icon"; }; /** * @private * @method _rootKeyM * @protected * @return {string} */ Icon.prototype._rootKeyM = function () { return "Icons"; }; /** * @private * @method _className * @return {string} */ Icon.prototype._className = function () { return "Icon"; }; /** * @private * @method _id * @return {string} */ Icon.prototype._id = function () { return this.get_id(); }; /** * このローカルオブジェクトに現在設定されているリソース情報をAPIに送信し、新規作成または上書き保存します。 * * @method save * @chainable * @public * @return {Icon} this */ Icon.prototype.save = function () { return (this._save()); }; /** * 最新のリソース情報を再取得します。 * * @method reload * @chainable * @public * @return {Icon} this */ Icon.prototype.reload = function () { return (this._reload()); }; /** * (This method is generated in Translator_default#buildImpl) * * @method get_id * @private * @return {string} */ Icon.prototype.get_id = function () { return this.m_id; }; Object.defineProperty(Icon.prototype, "id", { /** * ID * * @property id * @type string * @readOnly * @public */ get: function () { return this.get_id(); }, enumerable: true, configurable: true }); /** * (This method is generated in Translator_default#buildImpl) * * @method get_scope * @private * @return {string} */ Icon.prototype.get_scope = function () { return this.m_scope; }; Object.defineProperty(Icon.prototype, "scope", { /** * スコープ {{#crossLink "EScope"}}{{/crossLink}} * * @property scope * @type string * @readOnly * @public */ get: function () { return this.get_scope(); }, enumerable: true, configurable: true }); /** * (This method is generated in Translator_default#buildImpl) * * @method get_name * @private * @return {string} */ Icon.prototype.get_name = function () { return this.m_name; }; /** * (This method is generated in Translator_default#buildImpl) * * @method set_name * @private * @param {string} v * @return {string} */ Icon.prototype.set_name = function (v) { Util.validateArgCount(arguments.length, 1); Util.validateType(v, "string"); this.m_name = v; this.n_name = true; return this.m_name; }; Object.defineProperty(Icon.prototype, "name", { /** * 名前 * * @property name * @type string * @public */ get: function () { return this.get_name(); }, set: function (v) { this.set_name(v); }, enumerable: true, configurable: true }); /** * (This method is generated in Translator_default#buildImpl) * * @method get_url * @private * @return {string} */ Icon.prototype.get_url = function () { return this.m_url; }; Object.defineProperty(Icon.prototype, "url", { /** * URL * * @property url * @type string * @readOnly * @public */ get: function () { return this.get_url(); }, enumerable: true, configurable: true }); /** * (This method is generated in Translator_default#buildImpl) * * @method apiDeserializeImpl * @protected * @param {any} r */ Icon.prototype.apiDeserializeImpl = function (r) { Util.validateArgCount(arguments.length, 1); this.isNew = r == null; if (this.isNew) { r = {}; } ; this.isIncomplete = false; if (Util.existsPath(r, "ID")) { this.m_id = Util.getByPath(r, "ID") == null ? null : "" + Util.getByPath(r, "ID"); } else { this.m_id = null; this.isIncomplete = true; } ; this.n_id = false; if (Util.existsPath(r, "Scope")) { this.m_scope = Util.getByPath(r, "Scope") == null ? null : "" + Util.getByPath(r, "Scope"); } else { this.m_scope = null; this.isIncomplete = true; } ; this.n_scope = false; if (Util.existsPath(r, "Name")) { this.m_name = Util.getByPath(r, "Name") == null ? null : "" + Util.getByPath(r, "Name"); } else { this.m_name = null; this.isIncomplete = true; } ; this.n_name = false; if (Util.existsPath(r, "URL")) { this.m_url = Util.getByPath(r, "URL") == null ? null : "" + Util.getByPath(r, "URL"); } else { this.m_url = null; this.isIncomplete = true; } ; this.n_url = false; }; /** * @private * @method apiSerializeImpl * @protected * @param {boolean} withClean=false * @return {any} */ Icon.prototype.apiSerializeImpl = function (withClean) { if (typeof withClean === "undefined") { withClean = false; } Util.validateType(withClean, "boolean"); var missing = []; var ret = {}; if (withClean || this.n_id) { Util.setByPath(ret, "ID", this.m_id); } ; if (withClean || this.n_scope) { Util.setByPath(ret, "Scope", this.m_scope); } ; if (withClean || this.n_name) { Util.setByPath(ret, "Name", this.m_name); } else { if (this.isNew) { missing.push("name"); } ; } ; if (withClean || this.n_url) { Util.setByPath(ret, "URL", this.m_url); } ; if (missing.length > 0) { throw new SaklientException("required_field", "Required fields must be set before the Icon creation: " + missing.join(", ")); } ; return ret; }; return Icon; })(Resource); module.exports = Icon;
/* eslint-disable no-console */ import express from 'express' import webpackDev from './middleware/webpackDev' import webpackHot from './middleware/webpackHot' import apiProxy from './middleware/apiProxy' import serve from './middleware/serve' const app = express() app.use(webpackDev) app.use(webpackHot) /* Proxy api requests */ // TODO all -> use app.all('/api/*', apiProxy) app.use(serve) const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 3000 app.listen(port, error => error ? console.error(error) : console.info(`==> 🌎 Listening on port ${ port }. Open up http://localhost:${ port }/ in your browser.`) )
module.exports = { avgColour: require("./avg-colour"), centreColour: require("./centre-colour") };
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, (global.promisify = global.promisify || {}, global.promisify.js = factory())); }(this, (function () { 'use strict'; // >>> PUBLIC <<< var assertType = function assertType(moduleName) { return function (type, val) { var tag = Object.prototype.toString.call(val); // Match both [object Function] and [object AsyncFunction] var throwError = type === 'Function' ? typeof val !== 'function' : "[object ".concat(type, "]") !== tag; if (throwError) { throw new TypeError("".concat(moduleName, ": expected [").concat(type, "] but got ").concat(tag)); } }; }; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } // >>> PUBLIC <<< /** * A way to detect if object is native(built in) or user defined * Warning! Detection is not bulletproof and can be easily tricked. * In real word scenarios there should not be fake positives * @param {any} obj - Value to be tested is native object * @returns {boolean} - True if it's object and if it's built in JS object * @example * isNativeObject({}); \\ => false * isNativeObject(Object.prototype); \\ => true * isNativeObject(Number.prototype); \\ => true */ var isNativeObject = function isNativeObject(obj) { return !!(obj && (_typeof(obj) === 'object' || typeof obj === 'function') && Object.prototype.hasOwnProperty.call(obj, 'constructor') && typeof obj.constructor === 'function' && Function.prototype.toString.call(obj.constructor).includes('[native code]')); }; var assertType$1 = assertType('promisify'); // >>> INTERNALS <<< /** * @const {Symbol} - Symbol to be applied on promisified functions to avoid multiple promisify of same function */ var PROMISIFIED_SYMBOL = Symbol('promisified'); /** * Promisified resolver for error first callback function. * * @param {Function} fn - Error first callback function we want to promisify * @param {Object} [options] * @param {boolean} [options.multiArgs=false] - Promise will resolve with array of values if true * @returns {Function} - Promisified version of error first callback function */ var promisified = function promisified(fn, args, options) { var _this = this; return new Promise(function (resolve, reject) { args.push(function (err) { if (err) return reject(err); for (var _len = arguments.length, result = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { result[_key - 1] = arguments[_key]; } return resolve(options && options.multiArgs ? result : result[0]); }); fn.apply(_this, args); }); }; /** * Check does we need to apply promisify * * @param {Object} prop - Object property we want to test * @param {string[]} [exclude=undefined] - List of object keys not to promisify * @param {string[]} [include=undefined] - Promisify only provided keys * * @returns {boolean} */ var shouldPromisify = function shouldPromisify(prop, exclude, include) { return typeof prop === 'function' && prop[PROMISIFIED_SYMBOL] !== true && (!include || include.some(function (k) { return k === prop.name; })) && (!exclude || exclude.every(function (k) { return k !== prop.name; })); }; /** * Promisify error first callback function. * Instead of taking a callback, the returned function will return a promise * whose fate is decided by the callback behavior of the given node function * * @param {Function} fn - Error first callback function we want to promisify * @param {Object} [options] * @param {boolean} [options.multiArgs=false] - Promise will resolve with array of values if true * * @returns {Function} - Promisified version of error first callback function * * @example * const async = promisify((cb) => cb(null, 'res1')); * async().then((response) => { console.log(response) }); */ var promisify = function promisify(fn, options) { assertType$1('Function', fn); return function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return promisified.call(this, fn, args, options); }; }; /** * Promisify the entire object by going through the object's properties * and creating an async equivalent of each function on the object. * * @param {Object} obj - The object we want to promisify * @param {Object} [options] * @param {string} [options.suffix='Async'] - Suffix will be appended to original method name * @param {boolean} [options.multiArgs=false] - Promise will resolve with array of values if true * @param {boolean} [options.proto=false] - Promisify object prototype chain if true * @param {string[]} [options.exclude=undefined] - List of object keys not to promisify * @param {string[]} [options.include=undefined] - Promisify only provided keys * * @returns {Object} - Initial obj with appended promisified functions on him */ promisify.all = function (obj, options) { assertType$1('Object', obj); // Apply default options if not provided var _ref = options || {}, suffix = _ref.suffix, exclude = _ref.exclude, include = _ref.include, proto = _ref.proto; // eslint-disable-line prefer-const suffix = typeof suffix === 'string' ? suffix : 'Async'; exclude = Array.isArray(exclude) ? exclude : undefined; include = Array.isArray(include) ? include : undefined; Object.getOwnPropertyNames(obj).forEach(function (key) { if (shouldPromisify(obj[key], exclude, include)) { var asyncKey = "".concat(key).concat(suffix); while (asyncKey in obj) { // Function has already been promisified skip it if (obj[asyncKey][PROMISIFIED_SYMBOL] === true) { return; } asyncKey = "".concat(asyncKey, "Promisified"); } obj[asyncKey] = promisify(obj[key], options); obj[asyncKey][PROMISIFIED_SYMBOL] = true; } }); // Promisify object prototype if specified if (proto) { var prototype = Object.getPrototypeOf(obj); if (prototype && !isNativeObject(prototype)) { promisify.all(prototype, options); } } return obj; }; // >>> PUBLIC <<< var promisify_1 = promisify; return promisify_1; })));
describe("Propagators", function() { describe("DDPropagator", function() { it('supports DD trace headers', function() { const propagator = new lightstep.DDPropagator(); let headers = { 'x-datadog-trace-id': '100000000000456', 'x-datadog-parent-id': '100000000000123', 'x-datadog-sampling-priority': '1' } let context = propagator.extract(headers); let textMap = {}; propagator.inject(context, textMap) expect(headers).to.deep.equal(textMap); }) }) })
define([ "jquery" ], function($) { var jQuery = $.noConflict(true); jQuery.fn.setVisible = function(visible) { return visible ? this.show() : this.hide(); } return jQuery; });
var expressions = require('./expressions'), each = require('std/each'), curry = require('std/curry'), throttle = require('std/throttle'), addClass = require('fun-dom/addClass'), removeClass = require('fun-dom/removeClass'), on = require('fun-dom/on'), off = require('fun-dom/off'), arrayToObject = require('std/arrayToObject') ;(function() { if (typeof fun == 'undefined') { fun = {} } var _unique, _hooks, _hookCallbacks fun.reset = function() { _unique = 0 fun.expressions = expressions _hooks = fun.hooks = {} _hookCallbacks = {} } fun.name = function(readable) { return '_' + (readable || '') + '_' + (_unique++) } fun.expressions = expressions /* Values ********/ fun.value = function(val) { return expressions.fromJsValue(val) } fun.emit = function(parentHookName, value) { if (!value) { return } var hookName = fun.hook(fun.name(), parentHookName) value.observe(function() { _hooks[hookName].innerHTML = '' _hooks[hookName].appendChild(document.createTextNode(value)) }) } fun.set = function(value, chainStr, setValue) { if (arguments.length == 2) { setValue = chainStr chainStr = null } var chain = chainStr ? chainStr.split('.') : [] while (chain.length) { value = expressions.dereference(value, expressions.Text(chain.shift())) } value.mutate('set', [expressions.fromJsValue(setValue)]) } fun.dictSet = function(dict, prop, setValue) { dict.mutate('set', [expressions.fromJsValue(prop), expressions.fromJsValue(setValue)]) } fun.handleTemplateForLoopMutation = function(mutation, loopHookName, iterableValue, yieldFn) { var op = mutation && mutation.operator if (op == 'push') { var emitHookName = fun.name() fun.hook(emitHookName, loopHookName) var content = iterableValue.getContent(), item = content[content.length - 1] yieldFn(emitHookName, item) // TODO // } else if (op == 'pop') { // var parent = fun.hooks[loopHookName], // children = parent.childNodes // parent.removeChild(children[children.length - 1]) } else { fun.destroyHook(loopHookName) var emitHookName = fun.name() fun.hook(emitHookName, loopHookName) iterableValue.evaluate().iterate(function(item) { yieldFn(emitHookName, item) }) } } /* Hooks *******/ fun.setHook = function(name, dom) { _hooks[name] = dom } fun.hook = function(name, parentName, opts) { if (_hooks[name]) { return name } opts = opts || {} var parent = _hooks[parentName], hook = _hooks[name] = document.createElement(opts.tagName || 'hook') each(opts.attrs, function(attr) { if (attr.expand) { fun.attrExpand(name, attr.expand) } else { fun.attr(name, attr.name, attr.value) } }) if (_hookCallbacks[name]) { for (var i=0, callback; callback = _hookCallbacks[name][i]; i++) { callback(hook) } } if (!parent.childNodes.length || !opts.prepend) { parent.appendChild(hook) } else { parent.insertBefore(hook, parent.childNodes[0]) } return name } fun.destroyHook = function(hookName) { if (!_hooks[hookName]) { return } _hooks[hookName].innerHTML = '' } fun.withHook = function(hookName, callback) { if (_hooks[hookName]) { return callback(_hooks[hookName]) } else if (_hookCallbacks[hookName]) { _hookCallbacks[hookName].push(callback) } else { _hookCallbacks[hookName] = [callback] } } fun.attr = function(hookName, key, value) { if (key == 'data') { fun.reflectInput(hookName, value) return } var hook = _hooks[hookName], lastValue value.observe(function() { if (match = key.match(/^on(\w+)$/)) { if (lastValue) { off(hook, eventName, lastValue) } var eventName = match[1].toLowerCase() if (value.getType() != 'Handler') { console.warn('Event attribute', eventName, 'value is not a Handler') return } on(hook, eventName, lastValue = function(e) { e.hook = hook value.evaluate().invoke([expressions.Event(e)]) }) } else if (key == 'style') { // TODO remove old styles each(value.getContent(), function(val, key) { fun.setStyle(hook, key, val) }) } else if (key == 'class' || key == 'className') { if (lastValue) { removeClass(hook, lastValue) } addClass(hook, lastValue = value.getContent()) } else { hook.setAttribute(key, value.getContent()) } }) } fun.attrExpand = function(hookName, expandValue) { // TODO Observe the expandValue, and detect keys getting added/removed properly each(expandValue.getContent(), function(value, name) { name = _getDictionaryKeyString(name) fun.attr(hookName, name, value) }) } var _getDictionaryKeyString = function(key) { key = fun.expressions.fromLiteral(key) if (key.getType() != 'Text') { return } return key.getContent() } var skipPx = arrayToObject(['zIndex', 'z-index']) fun.setStyle = function(hook, key, value) { key = _getDictionaryKeyString(key) if (!key) { return } value = value.evaluate() var rawValue = value.toString() if ((value.getType() == 'Number' || rawValue.match(/^\d+$/)) && !skipPx[key]) { rawValue = rawValue + 'px' } if (key == 'float') { key = 'cssFloat' } hook.style[key] = rawValue } fun.reflectInput = function(hookName, property) { var input = _hooks[hookName] if (input.type == 'checkbox') { property.observe(function() { input.checked = property.getContent() ? true : false }) on(input, 'change', function() { setTimeout(function() { _doSet(property, input.checked ? fun.expressions.Yes : fun.expressions.No) }) }) } else { property.observe(function() { input.value = property.evaluate().toString() }) function update(e) { setTimeout(function() { var value = input.value if (property.getContent() === value) { return } _doSet(property, fun.expressions.Text(input.value)) input.value = value }, 0) } on(input, 'keypress', update) on(input, 'keyup', update) on(input, 'keydown', function(e) { if (e.keyCode == 86) { update(e) } // catch paste events }) } function _doSet(property, value) { if (property._type == 'dereference') { var components = property.components fun.dictSet(components.value, components.key, value) } else { fun.set(property, value) } } } /* init & export ***************/ fun.reset() if (typeof module != 'undefined') { module.exports = fun } })()
/** * Requires. */ var util = require('util'); var Directive = require('./Directive'); /** * Exports. */ module.exports = InvalidDirective; util.inherits(InvalidDirective, Directive); function InvalidDirective() { // Nothing to do. }; /** * @Override Directive.process(). */ InvalidDirective.prototype.process = function(onEndCallback) { onEndCallback(''); };
/** * Created by msav on 3/11/2017. */ var app = angular.module("dmsApp"); app.factory("documentService", function ($http, configService) { return { getTypesForCompany: function (vat) { return $http.get(configService.getConfig().host+"/document/getDocumentTypes/" + vat); } } });
'use strict'; const lexers = require('occam-lexers'); const TerminalPart = require('../../part/terminal'), EpsilonTerminalNode = require('../../../common/node/terminal/epsilon'); const { specialSymbols } = lexers, { epsilon } = specialSymbols; class EpsilonPart extends TerminalPart { parse(configuration) { const epsilonTerminalNode = new EpsilonTerminalNode(); return epsilonTerminalNode; } isEpsilonPart() { const epsilonPart = true; return epsilonPart; } asString() { const string = epsilon; /// return string; } clone() { return super.clone(EpsilonPart); } } module.exports = EpsilonPart;
const checkContext = require('./check-context'); module.exports = function () { return function (context) { checkContext(context, 'before', ['find'], 'disablePagination'); const $limit = (context.params.query || {}).$limit; if ($limit === '-1' || $limit === -1) { context.params.paginate = false; delete context.params.query.$limit; } return context; }; };
/* eslint-disable no-console */ import fs from 'fs' import crypto from 'crypto' import { resolve } from 'path' import { Dir, DEV_PATH } from '../config' import transformFiles from './transform-files' const dirs = [ resolve(Dir.dist, 'js'), resolve(Dir.dist, 'css'), ] const mapData = {} function transformer({ filename, sourcePath, destinationPath }) { const oldFilePath = resolve(sourcePath, filename) const fileContents = fs.readFileSync(oldFilePath, 'utf-8') const hash = crypto.createHash('md5').update(fileContents).digest('hex') if (filename.indexOf(hash) !== -1) { console.log(`${filename} is unchanged.`) const str = filename.split('.') str.splice(str.indexOf(hash), 1) const baseFilename = str.join('.') mapData[baseFilename] = filename return } const str = filename.split('') str.splice(filename.lastIndexOf('.'), 0, `.${hash}`) const filenameHashed = str.join('') const newFilePath = resolve(destinationPath, filenameHashed) fs.renameSync(oldFilePath, newFilePath) mapData[filename] = filenameHashed console.log(`${filename} was renamed to ${filenameHashed}`) } function hashFilenames(directories) { if (!Dir.dist) { return } console.log('Hashing filenames...\n') directories.forEach((dir) => { transformFiles(dir, {}, transformer) }) fs.writeFileSync(resolve(DEV_PATH, 'filename-map.json'), JSON.stringify(mapData), 'utf-8') console.log('\nFilenames hashed!\n') } hashFilenames(dirs)
(function () { "use strict"; angular .module("ataCashout.results") .directive("resultPanel", resultPanel) .controller("ResultPanelController", ["$scope", ResultPanelController]); function resultPanel() { return { restrict: "E", scope: { result: "=", }, controller: "ResultPanelController", templateUrl: "results/resultPanel.html" }; } function ResultPanelController($scope) { $scope.cols = { cashable: { class: function() { return "col-md-" + $scope.cols.cashable.number(); }, number: function() { return $scope.result.banked > 0 || $scope.result.lost > 0 ? 5 : 8; } }, noncashable: { class: function() { return $scope.cols.noncashable.number() > 0 ? "col-md-" + $scope.cols.noncashable.number() : null; }, number: function() { return $scope.result.banked > 0 || $scope.result.lost > 0 ? 12 - $scope.cols.cashable.number() : 0; } } }; } })();
import React from 'react'; import { NavLink } from 'react-router-dom'; const NavItem = ({ sub, toggleCollapse }) => ( <button onClick={() => { toggleCollapse(); }}> <NavLink to={sub.url} style={{display: 'block', height: '100%', textDecoration: 'none'}} > {sub.display_name} </NavLink> </button> ) export default NavItem;
var apiTester = require('./api-crud-executor.js'); apiTester({ name: 'FeatureAPI', baseurl: 'http://localhost:3000', baseapi: '/api/feature', resCacheData: [], resCacheKeys: function (response) { return {'id': response.id, 'name': response.name}; }, typeMatch: { id: {type: 'Number', required: true}, name: {type: 'String', required: true}, strategy: {type: 'String', required: false}, score: {type: 'String', required: false} }, create: function () { return [ {send: {name: 'mocha'}}, {send: {name: 'chai'}}, {send: {name: 'javascript'}}, {send: {name: 'superagent'}}, {send: {name: 'require'}} ] }, find: function () { return [ this.resCacheData[0], this.resCacheData[Math.floor(this.resCacheData.length / 2)], this.resCacheData[this.resCacheData.length - 1] ]; }, patch: function () { return { id: this.resCacheData[0].id, name: this.resCacheData[0].name, strategy: "reduce" }; }, update: function () { return { id: this.resCacheData[0].id, name: "override", strategy: "strategic" }; }, delete: function () { return this.resCacheData; } } );
define([ "jquery", "require", "./util", "./fb", "./server", "jquery.ui", "jquery.jcrop", "jquery.facedetection", "jquery.photobooth" ], function($, require) { var util = require("./util"); var fb = require("./fb"); var server = require("./server"); var jcropApi; /* store jcrop to enable image changes */ var functions = { memePicture: function() { var images = ['meme01.jpg', 'meme02.jpg', 'meme03.jpg', 'meme04.jpg']; var currentDate = new Date(); var imageNumber = Math.floor(currentDate.getSeconds()/(60/images.length)); require("./picture").updatePicture(images[imageNumber]); }, updatePicture: function(picture) { /* destroy any existing jcrop */ if (jcropApi) { jcropApi.destroy(); } /* "reset" the picture object */ $("#picture").val(picture); $(".picture-merger").html(""); var pic = $("<img id='file' alt='My Picture' name='file'/>"); pic.attr("src", "/picture/" + picture); pic.appendTo(".picture-merger") /* init square selection */ pic.faceDetection({ complete: function(img, coords) { var pos = [0, 0, 300, 300]; if (coords.length > 0) { var adj1 = (300 - coords[0].width) / 2; var adj2 = adj1 + coords[0].width; pos = [ (coords[0].x - adj1), (coords[0].y - adj1), (coords[0].x + adj2), (coords[0].y + adj2) ]; } pic.Jcrop({ allowSelect: false, aspectRatio: 1, setSelect: pos, bgColor: "black", bgOpacity: .2, onSelect: function(c) { $("#x1").val(c.x); $("#x2").val(c.x2); $("#y1").val(c.y); $("#y2").val(c.y2); $("#w").val(c.w); $("#h").val(c.h); }, onChange: function(c) { $(".jcrop-holder div div div.jcrop-tracker").css( "background", "url('" + $("#sticker").val() + "') no-repeat 0 0 / " + c.w + "px " + c.h + "px"); } }, function() { jcropApi = this; }); /* enable generate button */ $("#btn_profile").button("enable"); $("#btn_upload").button("enable"); $("#btn_take").button("enable"); $("#btn_generate").button("enable"); } }); }, takePicture: function() { var userid = $("#userid").val(); $(".picture-merger").html(""); $(".picture-merger").photobooth().on( "image", function(event, dataUrl) { server.uploadBase64Picture(dataUrl, userid, function(data) { $(".picture-merger").data("photobooth").destroy(); require("./picture").updatePicture(data.picture); }); } ).resize(500, 500); if ($(".picture-merger").data("photobooth").isSupported) { $("#btn_profile").button("disable"); $("#btn_upload").button("disable"); $("#btn_take").button("disable"); $("#btn_generate").button("disable"); } else { util.showI18nMessage("info", "take_picture_not_available"); $(".picture-merger").data("photobooth").destroy(); require("./picture").memePicture(); } } }; return functions; });
module.exports = function (grunt) { grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.initConfig({ uglify: { dev: { files: { 'app/js/app.min.js': ['app/js/app.js', 'app/js/WebSocketFactory.js', 'app/js/directives/**/*.js', 'app/js/controllers/**/*.js'] }, options: { sourceMap: true, sourceMapName: 'app/js/app.min.js.map' } } }, cssmin: { options: { sourceMap: true }, target: { files: { 'app/css/app.min.css': ['app/css/app.css'], 'app/css/app_ie9lte.min.css': ['app/css/app_ie9lte.css'] } } }, karma: { unit: { configFile: 'karma.conf.js' } } }); grunt.registerTask("default", ['uglify', 'cssmin', 'karma']) };
class NotAnnotatedClass { constructor(name) { this.name = name } print() { console.log(this.name) } } class MyLogger { /** * @injectable(logger) */ constructor() { this.prefix = "app:" } log(message) { console.log(this.prefix + message) } } class MyDebugger { /** * @injectable(debugger) * @inject(logger) */ constructor(logger) { this.logger = logger } debug(message) { this.logger.log(message) } } module.exports = { NotAnnotatedClass: NotAnnotatedClass, MyLogger: MyLogger, MyDebugger: MyDebugger }
var _ = require("lodash"); var fs = require("fs-extra"); module.exports = function(options) { options = _.extend({ file: "data.json", saveFrequency: 1, indexing: false }, options); var lastSaved = 0; //If the specified file doesn't exist, we create an empty JSON object if (!fs.existsSync(options.file)) { fs.ensureFileSync(options.file); fs.writeFileSync(options.file, "{}"); } var _data; var _indexes = {}; try { _data = JSON.parse(fs.readFileSync(options.file, { encoding: 'utf-8' })); } catch (err) { console.error("Cantrip - Not valid JSON file: " + options.file); process.exit(5); } function clone(object) { return JSON.parse(JSON.stringify(object)); }; function createIndex(pathIdentifier, data) { if (_indexes[pathIdentifier]) return; _indexes[pathIdentifier] = []; for (var i = 0; i < data.length; i++) { _indexes[pathIdentifier][data[i][options.idAttribute]] = data[i]; } } function resetIndex(pathIdentifier) { for (var key in _indexes) { if (key.indexOf(pathIdentifier) === 0) { delete _indexes[key]; } } } /** * Sync the data currently in memory to the target file */ function syncData() { if (options.saveFrequency === 0) return; lastSaved++; if (lastSaved === options.saveFrequency) { fs.writeFile(options.file, JSON.stringify(_data, null, "\t"), function(err) { if (err) { console.log(err); } }); lastSaved = 0; } } /** * Private function for getting the reference to the target node */ var _get = function(path) { path = _.filter(path.split("/"), function(string) { return string !== ""; }); var node = _data; //Loop through the data by the given paths for (var i = 0; i < path.length; i++) { //Check if we are looking up an item in an array if (_.isArray(node) && options.indexing) { //if indexing is on, create an index if it didn't exist before, and assign the reference to the node var pathIdentifier = "/" + path.slice(0, i).join("/"); if (!_indexes[pathIdentifier]) { createIndex(pathIdentifier, node); } node = _indexes[pathIdentifier][path[i]]; } else { var temp = node[path[i]]; //If we found the given key, assign the node object to its value if (temp !== undefined) { node = node[path[i]]; //If the given key doesn't exist, try the _id } else { temp = _.find(node, function(obj) { return obj[options.idAttribute] === path[i]; }); //If it's not undefined, then assign it as the value if (temp !== undefined) { node = temp; } else { return null; } } } } return node || null; }; function getParentPath(path) { return path.split("/").slice(0, -1).join("/"); } var _parent = function(path) { var parent = _get(getParentPath(path)); var err = parent === null ? new Error("Requested node doesn't exist.") : null; return parent; }; /** * Return the datastore */ return { /** * Public getter function that returns a clone of the target node */ get: function(path) { return clone(_get(path)); }, set: function(path, data, patch) { var target = _get(path); if (_.isArray(target)) { //POST var ref = clone(data); target.push(ref); //If indexing is turned on, make sure to insert the new reference if (options.indexing) { if (!_indexes[path]) { createIndex(path, target); } _indexes[path][data[options.idAttribute]] = ref; } syncData(); return clone(data); } else if (_.isObject(target)) { //PATCH if (patch) { target = _.merge(target, data, function(a, b) { if (_.isArray(a)) { return b; } }); syncData(); //Reset the matching indexes if it's turned on if (options.indexing) { resetIndex(path); } return clone(target); } else { //PUT var parent = _parent(path); var toPut = _.last(path.split("/")); if (toPut === "") { _data = clone(data); _index = {}; } else { if (_.isArray(parent)) { var item = _.find(parent, function(item) { return item[options.idAttribute] === toPut; }); //Delete all keys of the array for (var key in item) { if (key !== options.idAttribute && key !== "_modifiedDate" && key !== "_createdDate") { delete item[key]; } } item = _.merge(item, clone(data)); } else { parent[toPut] = clone(data); } } syncData(); //Reset the matching indexes if it's turned on if (options.indexing) { resetIndex(path); } return clone(target); } } else { var parent = _parent(path); parent[_.last(path.split("/"))] = data; syncData(); //Reset the matching indexes if it's turned on if (options.indexing) { resetIndex(path); } return clone(parent); } }, delete: function(path) { var key = _.last(path.split("/")); var parent = _parent(path); if (_.isArray(parent)) { var obj; if (options.indexing) { var indexKey = path.split("/").slice(0, -1).join("/"); var obj = _indexes[indexKey][key]; delete _indexes[getParentPath(path)][key]; resetIndex(path); } else { obj = _.find(parent, function(obj) { return obj[options.idAttribute] === key; }); } var index = _.indexOf(parent, obj) if (index > -1) { parent.splice(index, 1); } } else if (_.isObject(parent)) { delete parent[key]; if (options.indexing) { resetIndex(path); } } syncData(); return clone(parent); }, parent: function(path) { return clone(_parent(path)); } }; }
var React = require('react'); var KeyCode = require('./utils/key-code'); var StylePropable = require('./mixins/style-propable'); var AutoPrefix = require('./styles/auto-prefix'); var Transitions = require('./styles/transitions'); var WindowListenable = require('./mixins/window-listenable'); var Overlay = require('./overlay'); var Paper = require('./paper'); var Menu = require('./menu/menu'); var LeftNav = React.createClass({displayName: "LeftNav", mixins: [StylePropable, WindowListenable], contextTypes: { muiTheme: React.PropTypes.object }, propTypes: { className: React.PropTypes.string, docked: React.PropTypes.bool, header: React.PropTypes.element, menuItems: React.PropTypes.array.isRequired, onChange: React.PropTypes.func, onNavOpen: React.PropTypes.func, onNavClose: React.PropTypes.func, openRight: React.PropTypes.bool, selectedIndex: React.PropTypes.number }, windowListeners: { 'keyup': '_onWindowKeyUp', 'resize': '_onWindowResize' }, getDefaultProps: function() { return { docked: true }; }, getInitialState: function() { return { open: this.props.docked, maybeSwiping: false, swiping: false }; }, componentDidMount: function() { this._updateMenuHeight(); this._enableSwipeHandling(); }, componentDidUpdate: function(prevProps, prevState) { this._updateMenuHeight(); this._enableSwipeHandling(); }, componentWillUnmount: function() { this._disableSwipeHandling(); }, toggle: function() { this.setState({ open: !this.state.open }); return this; }, close: function() { this.setState({ open: false }); if (this.props.onNavClose) this.props.onNavClose(); return this; }, open: function() { this.setState({ open: true }); if (this.props.onNavOpen) this.props.onNavOpen(); return this; }, getThemePalette: function() { return this.context.muiTheme.palette; }, getTheme: function() { return this.context.muiTheme.component.leftNav; }, getStyles: function() { var x = this._getTranslateMultiplier() * (this.state.open ? 0 : this._getMaxTranslateX()) + 'px'; var styles = { root: { height: '100%', width: this.getTheme().width, position: 'fixed', zIndex: 10, left: 0, top: 0, transform: 'translate3d(' + x + ', 0, 0)', transition: !this.state.swiping && Transitions.easeOut(), backgroundColor: this.getTheme().color, overflow: 'hidden' }, menu: { overflowY: 'auto', overflowX: 'hidden', height: '100%' }, menuItem: { height: this.context.muiTheme.spacing.desktopLeftNavMenuItemHeight, lineDeight: this.context.muiTheme.spacing.desktopLeftNavMenuItemHeight }, rootWhenOpenRight: { left: 'auto', right: '0' } }; styles.menuItemLink = this.mergeAndPrefix(styles.menuItem, { display: 'block', textDecoration: 'none', color: this.getThemePalette().textColor }); styles.menuItemSubheader = this.mergeAndPrefix(styles.menuItem, { overflow: 'hidden' }); return styles; }, render: function() { var selectedIndex = this.props.selectedIndex; var overlay; var styles = this.getStyles(); if (!this.props.docked) { overlay = React.createElement(Overlay, {ref: "overlay", show: this.state.open, transitionEnabled: !this.state.swiping, onTouchTap: this._onOverlayTouchTap}); } return ( React.createElement("div", {className: this.props.className}, overlay, React.createElement(Paper, { ref: "clickAwayableElement", zDepth: 2, rounded: false, transitionEnabled: !this.state.swiping, style: this.mergeAndPrefix( styles.root, this.props.openRight && styles.rootWhenOpenRight, this.props.style)}, this.props.header, React.createElement(Menu, { ref: "menuItems", style: this.mergeAndPrefix(styles.menu), zDepth: 0, menuItems: this.props.menuItems, menuItemStyle: this.mergeAndPrefix(styles.menuItem), menuItemStyleLink: this.mergeAndPrefix(styles.menuItemLink), menuItemStyleSubheader: this.mergeAndPrefix(styles.menuItemSubheader), selectedIndex: selectedIndex, onItemClick: this._onMenuItemClick}) ) ) ); }, _updateMenuHeight: function() { if (this.props.header) { var container = React.findDOMNode(this.refs.clickAwayableElement); var menu = React.findDOMNode(this.refs.menuItems); var menuHeight = container.clientHeight - menu.offsetTop; menu.style.height = menuHeight + 'px'; } }, _onMenuItemClick: function(e, key, payload) { if (this.props.onChange && this.props.selectedIndex !== key) { this.props.onChange(e, key, payload); } if (!this.props.docked) this.close(); }, _onOverlayTouchTap: function() { this.close(); }, _onWindowKeyUp: function(e) { if (e.keyCode == KeyCode.ESC && !this.props.docked && this.state.open) { this.close(); } }, _onWindowResize: function(e) { this._updateMenuHeight(); }, _getMaxTranslateX: function() { return this.getTheme().width + 10; }, _getTranslateMultiplier: function() { return this.props.openRight ? 1 : -1; }, _enableSwipeHandling: function() { if (this.state.open && !this.props.docked) { document.body.addEventListener('touchstart', this._onBodyTouchStart); } else { this._disableSwipeHandling(); } }, _disableSwipeHandling: function() { document.body.removeEventListener('touchstart', this._onBodyTouchStart); }, _onBodyTouchStart: function(e) { var touchStartX = e.touches[0].pageX; var touchStartY = e.touches[0].pageY; this.setState({ maybeSwiping: true, touchStartX: touchStartX, touchStartY: touchStartY }); document.body.addEventListener('touchmove', this._onBodyTouchMove); document.body.addEventListener('touchend', this._onBodyTouchEnd); document.body.addEventListener('touchcancel', this._onBodyTouchEnd); }, _onBodyTouchMove: function(e) { var currentX = e.touches[0].pageX; var currentY = e.touches[0].pageY; if (this.state.swiping) { e.preventDefault(); var translateX = Math.min( Math.max( this._getTranslateMultiplier() * (currentX - this.state.swipeStartX), 0 ), this._getMaxTranslateX() ); var leftNav = React.findDOMNode(this.refs.clickAwayableElement); leftNav.style[AutoPrefix.single('transform')] = 'translate3d(' + (this._getTranslateMultiplier() * translateX) + 'px, 0, 0)'; this.refs.overlay.setOpacity(1 - translateX / this._getMaxTranslateX()); } else if (this.state.maybeSwiping) { var dXAbs = Math.abs(currentX - this.state.touchStartX); var dYAbs = Math.abs(currentY - this.state.touchStartY); // If the user has moved his thumb ten pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. var threshold = 10; if (dXAbs > threshold && dYAbs <= threshold) { this.setState({ swiping: true, swipeStartX: currentX }); } else if (dXAbs <= threshold && dYAbs > threshold) { this._onBodyTouchEnd(); } } }, _onBodyTouchEnd: function() { var shouldClose = false; if (this.state.swiping) shouldClose = true; this.setState({ maybeSwiping: false, swiping: false }); // We have to call close() after setting swiping to false, // because only then CSS transition is enabled. if (shouldClose) this.close(); document.body.removeEventListener('touchmove', this._onBodyTouchMove); document.body.removeEventListener('touchend', this._onBodyTouchEnd); document.body.removeEventListener('touchcancel', this._onBodyTouchEnd); } }); module.exports = LeftNav;
// libs import { Component } from 'react'; import 'antd/dist/antd.css'; import { connect } from 'react-redux'; import Immutable from 'seamless-immutable'; import { Table, Card, Icon, Tag, Button } from 'antd'; import ReactJson from 'react-json-view'; import { openModal } from '../actions/modal.action'; import { createSelector } from 'reselect'; import { Row, Col } from 'antd'; const ContainerTable = ({ dataSource, openModal }) => { const columns = [ { title: 'PodName', dataIndex: 'podName', key: 'podName', onFilter: (value, record) => record.podName.includes(value), sorter: (a, b) => a.podName.length - b.podName.length }, { title: 'Age', dataIndex: 'age', key: 'age' }, { title: 'Address', dataIndex: 'address', key: 'address' }, { title: 'Status', dataIndex: '', key: 'x', render: (text, record) => ( <span> <Tag color="green">{record.podName}</Tag> </span> ) }, { title: 'Terminal', dataIndex: '', rowSpan: 2, key: 'y', render: (text, record) => ( <Row type="flex" justify="left" align="middle"> <Col span={3}> <Button icon="desktop" onClick={() => openModal(record, 'docker')}> Host </Button> </Col> <Col span={1}> <span className="ant-divider"/> </Col> <Col span={3}> <Button icon="laptop" onClick={() => openModal(record)}> Pod </Button> </Col> <Col span={1}> <span className="ant-divider"/> </Col> <Col span={3}> <Button icon="code-o" onClick={() => openModal(record)}> Log </Button> </Col> <Col span={1}> <span className="ant-divider"/> </Col> <Col span={3}> <Button icon="edit" onClick={() => openModal(record)}> Describe </Button> </Col> <Col span={5}/> {/* <Tag color="green">{record.podName}</Tag>*/} </Row> ) } ]; return ( <div> <Table columns={columns} dataSource={dataSource.asMutable()} expandedRowRender={(record) => ( <Card title="Card title"> <ReactJson src={record}/> </Card> )}/> </div> ); }; const containerTable = (state) => state.containerTable.dataSource; const autoCompleteFilter = (state) => state.autoCompleteFilter.filter; const tableDataSelector = createSelector( containerTable, autoCompleteFilter, (containerTable, autoCompleteFilter) => { let returnData = containerTable; if (autoCompleteFilter != '') { returnData = containerTable.filter((row) => Object.values(row).find((f) => f.toString().includes(autoCompleteFilter)) ); } return returnData; } ); ContainerTable.propTypes = { // columns: React.PropTypes.array.isRequired, dataSource: React.PropTypes.array.isRequired }; const mapStateToProps = (state) => ({ // columns: state.containerTable.columns, dataSource: tableDataSelector(state) }); export default connect(mapStateToProps, { openModal })(ContainerTable);
'use strict'; const fs = require('fs'), Emitter = require('events').EventEmitter, emitter = new Emitter(), eventState = require('event-state'), dirTree = (path, cb) => { const buildBranch = (path, branch) => { fs.readdir(path, (err, files) => { if (err) { //Errors result in a false value in the tree. branch[path] = false; cb(err); } else { const newEvents = files.map(file => { return path + '/' + file; }); if (!state) { // If this is the first iteration, // initialize the dynamic state machine (DSM). state = emitter.required(newEvents, () => { // Allow for multiple paradigms vis-a-vis callback and promises. // resolve the promise with the completed tree.. cb(null, tree); }); } else { // Add events to the DSM for the directory's children state.add(newEvents); } // Check each file descriptor to see if it's a directory. files.forEach(file => { const filePath = path + '/' + file; fs.stat(filePath, (err, stats) => { if (err) { // Errors result in a false value in the tree branch[file] = false; emitter.emit(filePath, true); } else if (stats.isDirectory() && file[0] !== '.' && file !== 'node_modules') { // Directories are object properties on the tree. branch[file] = {}; //console.log('cur dir name', file); // Recurse into the directory. buildBranch(filePath, branch[file]); } else { const fp = filePath.replace(process.cwd(), ''); //console.log(dir, file); // If it's not a directory, it's a file. // Files get a true value in the tree. branch[file] = fp; emitter.emit(filePath, true); } }); }); } //Once we've read the directory, we can raise the event for the parent // directory and let it's children take care of themselves. emitter.emit(path, true); }); }; let tree = {}, state; return buildBranch(path, tree); }; emitter.required = eventState; module.exports = dirTree;
var socket = io.connect(SAILFISH_SERVER); socket.on('connect', function () { socket.emit('browser-connected'); }); socket.on('runners.status', function(runners) { $("#runnerContainer").empty(); if(!_.isEmpty($("#runnerContainer"))) { _.each(runners, function(runner) { if(runner.locked) { } else { } $("#runnerContainer").append('<li><a href="#" class="button disabled">'+runner.token+'</a></li>'); }); } });
import { Point } from "../lib/point.js"; import { ITextEditor } from "../lib/text-editor.js"; // This is a mock class of the ITextEditor interface export class TextEditor extends ITextEditor { constructor(lines) { super(); this._lines = lines.slice(); this._cursorPos = new Point(0, 0); this._selectionRange = null; } getCursorPosition() { return this._cursorPos; } setCursorPosition(pos) { this._cursorPos = pos; this._selectionRange = null; } getSelectionRange() { return this._selectionRange; } setSelectionRange(range) { this._cursorPos = range.end; this._selectionRange = range; } getLastRow() { return this._lines.length - 1; } acceptsTableEdit(row) { return true; } getLine(row) { return this._lines[row]; } getLines() { return this._lines.slice(); } insertLine(row, line) { this._lines.splice(row, 0, line); } deleteLine(row) { this._lines.splice(row, 1); } replaceLines(startRow, endRow, lines) { this._lines.splice(startRow, endRow - startRow, ...lines); } transact(func) { func(); } }
module.exports = { 'slogan': 'Find your next home or find your next place where you will be on yours vacations.', 'home': 'Home', 'about': 'About', 'login': 'Login', 'register': 'Register', 'publish': 'Publish', 'support': 'Support', 'contact-us': 'Contact Us', 'help': 'Help', 'privacy': 'Privacy', 'terms': 'Terms', 'follow-us': 'Follow Us', 'welcome': 'Welcome', 'language': 'Language', 'spanish': 'Spanish', 'english': 'English' }
// Load the given HTML in the iframe within the given element function view(viewer_id, html) { var iframe = $("#" + viewer_id + " iframe", top.document); var doc = iframe[0].contentWindow.document; doc.open(); doc.write(html); doc.close(); } // Create a new ACE editor in the div with the given id, and return it var ace_number = 1; function new_editor(div) { // Create a unique div for the ace editor var ace_id = "ace_" + ace_number; ace_number += 1; // Create a div for ACE to use var ace_div = $("<div></div>"); ace_div.attr("id", ace_id); ace_div.attr("class", 'ace'); ace_div.appendTo(div); // Turn it into an editor var editor = ace.edit(ace_id); // TODO: Make these bits configurable var session = editor.getSession(); session.setMode("ace/mode/html"); editor.setTheme("ace/theme/github"); editor.setShowPrintMargin(false); return editor; } // Attach a viewer with the given ID to the editor with the given ID function attach_viewer(editor, viewer_id) { // Does editor need refreshing? var need_refresh = false; // How long (in ms) to wait between refreshes, at minimum var refresh_interval = 500; // Don't refresh if changes occur in rapid succession var ignore_threshold = 200; // Track timestamp of the last change made in the editor var last_changed = new Date().getTime(); var session = editor.getSession(); session.on('change', function(e) { last_changed = new Date().getTime(); need_refresh = true; }); // At regular intervals, check for changes and refresh the view window.setInterval(function() { var now = new Date().getTime(); // If last keystroke was a while ago, and editor has changed, refresh if (now - last_changed > ignore_threshold && need_refresh) { // TODO: Generalize viewer so it can be any element, or several elements view(viewer_id, editor.getValue()); need_refresh = false; } // Otherwise, either the last change was too recent, or the // last change has already been refreshed }, refresh_interval); return false; } // Make the given div element into an ACE editor // TODO: Refactor function make_editor(div) { editor = new_editor(div); attach_viewer(editor, "viewer"); $(div + ' input[name="import_file"]').change(function() { function populate_editor(responseText, statusText, xhr, $form) { editor.setValue(responseText, -1); } $(div + " form").ajaxSubmit({success: populate_editor}); }); $(div).draggable({cancel: ".ace", containment: "#board"}); $(div).resizable(); $(div).resize(function() { editor.resize(); }); } $(document).ready(function() { make_editor("#editor"); });
"use strict"; ace.define("ace/snippets/typescript", ["require", "exports", "module"], function (e, t, n) { "use strict"; t.snippetText = undefined, t.scope = "typescript"; });
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const bootstrap = require('./bootstrap'); const product = require('../product.json'); // Avoid Monkey Patches from Application Insights bootstrap.avoidMonkeyPatchFromAppInsights(); // Enable portable support bootstrap.configurePortable(product); // Enable ASAR support bootstrap.enableASARSupport(); // Load CLI through AMD loader require('./bootstrap-amd').load('vs/code/node/cli');
// Karma configuration // Generated on 2016-09-23 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) // as well as any additional frameworks (requirejs/chai/sinon/...) frameworks: [ 'jasmine' ], // list of files / patterns to load in the browser files: [ // bower:js // endbower 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [ ], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
var hostnames = []; var tabHostnames = {}; var recipeCounters = {}; chrome.browserAction.setBadgeBackgroundColor({ color: '#000', }); chrome.tabs.query({}, function(results){ for(var i in results){ var tab = results[i]; handleBrowserAction(tab); } }); chrome.tabs.onUpdated.addListener(function(tabId, info, tab){ if( info.status === "loading" ) { recipeCounters[tabId] = 0; handleBrowserAction(tab); } }); chrome.tabs.onUpdated.addListener(function(tabId, info, tab){ if( info.url || info.status === "loading"){ var url = new URL(tab.url); var hostname = url.hostname; if( url.protocol !== "http:" && url.protocol !== "https:" ){ return; } tabHostnames[tabId] = hostname; var patterns = getPatternsForHostname(hostname); for(var i in patterns){ applyRecipe(patterns[i], tabId); } } }); function urlsMatch(pattern, url){ if(typeof pattern == "string"){ pattern = pattern.split(".").reverse(); } if(typeof url == "string"){ url.split(".").reverse(); } for (var i in pattern){ var sector1 = pattern[i]; var sector2 = url[i]; if(sector1 === "*"){ return true; } else if(sector1 === sector2){ continue; } else{ return false; } } return true; } function getPatternsForHostname(hostname){ var out = [hostname]; var sectors = hostname.split('.'); for (var i=0; i<sectors.length; i++){ var patt = [].concat.call("*", sectors.slice(i+1)).join("."); out.push(patt); } return out; } function applyRecipe(pattern, tabId){ var cssKey = "CSS_#"+pattern; var jsKey = "js_#"+pattern; chrome.storage.sync.get(cssKey, function(data){ if(data[cssKey] != null){ chrome.browserAction.setBadgeText({ text: String(++recipeCounters[tabId]), tabId: tabId, }); chrome.tabs.insertCSS(tabId, { code: String(data[cssKey]), runAt: "document_start", //allFrames: true, }); } }); chrome.storage.sync.get(jsKey, function(data){ if(data[jsKey] != null){ chrome.browserAction.setBadgeText({ text: String(++recipeCounters[tabId]), tabId: tabId, }); chrome.tabs.executeScript(tabId, { code: String(data[jsKey]), runAt: "document_start", //allFrames: true, }); } }); } function handleBrowserAction(tab){ var protocol = new URL(tab.url).protocol; if( protocol === "http:" || protocol === "https:" ){ chrome.browserAction.enable(tab.id); } else{ chrome.browserAction.disable(tab.id); } }
/* --- Made by justgoscha and licensed under MIT license --- */ var app = angular.module('autocomplete', []); app.directive('autocomplete', function() { var index = -1; return { restrict: 'E', scope: { searchParam: '=ngModel', suggestions: '=data', onType: '=onType', onSelect: '=onSelect', autocompleteRequired: '=', noAutoSort: '=noAutoSort' }, controller: ['$scope', function($scope){ // the index of the suggestions that's currently selected $scope.selectedIndex = -1; $scope.initLock = true; // set new index $scope.setIndex = function(i){ $scope.selectedIndex = parseInt(i); }; this.setIndex = function(i){ $scope.setIndex(i); $scope.$apply(); }; $scope.getIndex = function(i){ return $scope.selectedIndex; }; // watches if the parameter filter should be changed var watching = true; // autocompleting drop down on/off $scope.completing = false; // starts autocompleting on typing in something $scope.$watch('searchParam', function(newValue, oldValue){ if (oldValue === newValue || (!oldValue && $scope.initLock)) { return; } if(watching && typeof $scope.searchParam !== 'undefined' && $scope.searchParam !== null) { $scope.completing = true; $scope.searchFilter = $scope.searchParam; $scope.selectedIndex = -1; } // function thats passed to on-type attribute gets executed if($scope.onType) $scope.onType($scope.searchParam); }); // for hovering over suggestions this.preSelect = function(suggestion){ watching = false; // this line determines if it is shown // in the input field before it's selected: //$scope.searchParam = suggestion; $scope.$apply(); watching = true; }; $scope.preSelect = this.preSelect; this.preSelectOff = function(){ watching = true; }; $scope.preSelectOff = this.preSelectOff; // selecting a suggestion with RIGHT ARROW or ENTER $scope.select = function(suggestion){ if(suggestion){ $scope.searchParam = suggestion; $scope.searchFilter = suggestion; if($scope.onSelect) $scope.onSelect(suggestion); } watching = false; $scope.completing = false; setTimeout(function(){watching = true;},1000); $scope.setIndex(-1); }; }], link: function(scope, element, attrs){ console.log(scope.noAutoSort) setTimeout(function() { scope.initLock = false; scope.$apply(); }, 250); var attr = ''; // Default atts scope.attrs = { "placeholder": "start typing...", "class": "", "id": "", "inputclass": "", "inputid": "" }; for (var a in attrs) { attr = a.replace('attr', '').toLowerCase(); // add attribute overriding defaults // and preventing duplication if (a.indexOf('attr') === 0) { scope.attrs[attr] = attrs[a]; } } if (attrs.clickActivation) { element[0].onclick = function(e){ if(!scope.searchParam){ setTimeout(function() { scope.completing = true; scope.$apply(); }, 200); } if(scope.selectedIndex !== -1) { scope.select(angular.element(angular.element(this).find('li')[scope.selectedIndex]).text()); setTimeout(function () { scope.completing = false; scope.$apply(); }, 200); } }; } var key = {left: 37, up: 38, right: 39, down: 40 , enter: 13, esc: 27, tab: 9}; document.addEventListener("keydown", function(e){ var keycode = e.keyCode || e.which; switch (keycode){ case key.esc: // disable suggestions on escape scope.select(); scope.setIndex(-1); scope.$apply(); e.preventDefault(); } }, true); document.addEventListener("blur", function(e){ // disable suggestions on blur // we do a timeout to prevent hiding it before a click event is registered setTimeout(function() { scope.select(); scope.setIndex(-1); scope.$apply(); }, 150); }, true); element[0].addEventListener("keydown",function (e){ var keycode = e.keyCode || e.which; var l = angular.element(this).find('li').length; // this allows submitting forms by pressing Enter in the autocompleted field if(!scope.completing || l == 0) return; // implementation of the up and down movement in the list of suggestions switch (keycode){ case key.up: index = scope.getIndex()-1; if(index<-1){ index = l-1; } else if (index >= l ){ index = -1; scope.setIndex(index); scope.preSelectOff(); break; } scope.setIndex(index); if(index!==-1) scope.preSelect(angular.element(angular.element(this).find('li')[index]).text()); scope.$apply(); break; case key.down: index = scope.getIndex()+1; if(index<-1){ index = l-1; } else if (index >= l ){ index = -1; scope.setIndex(index); scope.preSelectOff(); scope.$apply(); break; } scope.setIndex(index); if(index!==-1) scope.preSelect(angular.element(angular.element(this).find('li')[index]).text()); break; case key.left: break; case key.right: case key.enter: case key.tab: index = scope.getIndex(); // scope.preSelectOff(); if(index !== -1) { scope.select(angular.element(angular.element(this).find('li')[index]).text()); if(keycode == key.enter) { e.preventDefault(); } } else { if(keycode == key.enter) { scope.select(); } } scope.setIndex(-1); scope.$apply(); break; case key.esc: // disable suggestions on escape scope.select(); scope.setIndex(-1); scope.$apply(); e.preventDefault(); break; default: return; } }); }, template: '\ <div class="autocomplete {{ attrs.class }}" id="{{ attrs.id }}">\ <input\ type="text"\ ng-model="searchParam"\ placeholder="{{ attrs.placeholder }}"\ class="{{ attrs.inputclass }}"\ tabindex="{{ attrs.tabindex }}"\ id="{{ attrs.inputid }}"\ name="{{ attrs.name }}"\ ng-required="{{ autocompleteRequired }}" />\ <ul ng-if="!noAutoSort" ng-show="completing && (suggestions | filter:searchFilter).length > 0">\ <li\ suggestion\ ng-repeat="suggestion in suggestions | filter:searchFilter | orderBy:\'toString()\' track by $index"\ index="{{ $index }}"\ val="{{ suggestion }}"\ ng-class="{ active: ($index === selectedIndex) }"\ ng-click="select(suggestion)"\ ng-bind-html="suggestion | highlight:searchParam"></li>\ </ul>\ <ul ng-if="noAutoSort" ng-show="completing && (suggestions | filter:searchFilter).length > 0">\ <li\ suggestion\ ng-repeat="suggestion in suggestions | filter:searchFilter track by $index"\ index="{{ $index }}"\ val="{{ suggestion }}"\ ng-class="{ active: ($index === selectedIndex) }"\ ng-click="select(suggestion)"\ ng-bind-html="suggestion | highlight:searchParam"></li>\ </ul>\ </div>' }; }); app.filter('highlight', ['$sce', function ($sce) { return function (input, searchParam) { if (typeof input === 'function') return ''; if (searchParam) { var words = '(' + searchParam.split(/\ /).join(' |') + '|' + searchParam.split(/\ /).join('|') + ')', exp = new RegExp(words, 'gi'); if (words.length) { input = input.replace(exp, "<span class=\"highlight\">$1</span>"); } } return $sce.trustAsHtml(input); }; }]); app.directive('suggestion', function(){ return { restrict: 'A', require: '^autocomplete', // ^look for controller on parents element link: function(scope, element, attrs, autoCtrl){ element.bind('mouseenter', function() { autoCtrl.preSelect(attrs.val); autoCtrl.setIndex(attrs.index); }); element.bind('mouseleave', function() { autoCtrl.preSelectOff(); }); } }; });
import { formatSha as _formatSha, safe } from 'travis/utils/helpers'; import Ember from "ember"; export default Ember.Helper.helper(function(params) { return safe(_formatSha(params[0])); });
// Easing functions var easing = require('./src/easing'); // Component transformers var inertial = require('./src/inertial'); var interpolation = require('./src/interpolation'); var transition = require('./src/transition'); var interpolate = require('./src/interpolate'); var easeFocused = require('./src/easeFocused'); var easedToggle = require('./src/easedToggle'); module.exports = { easeFocused: easeFocused, easedToggle: easedToggle, interpolate: interpolate, easing: easing, inertial: inertial, interpolation: interpolation, transition: transition }
/*jslint white: true, nomen: true */ // http://www.jslint.com/lint.html#options (function(win, doc) { // todo: bug - after resize on ios - smoke is wrong 'use strict'; /*global window, document, setTimeout, history, Image */ /*global Backbone, $, templateMaster, APP, log, Mover, _ */ win.APP = win.APP || {}; win.APP.BB = win.APP.BB || {}; APP.BB.BattleView = APP.BB.BaseView.extend({ events: { 'click .js-end-turn': 'endTurn', 'click .js-battle-menu-button': 'openMenu', 'click .js-help-button': 'showHelp', 'click .js-move-back-button': 'moveUndo', hideHouseSmoke: 'hideHouseSmoke', showHouseSmoke: 'showHouseSmoke' }, selectors: { mapImageWrapper: '.js-map-image-wrapper', mapImage: '.js-map-image', moveAreaWrapper: '.js-move-area-wrapper', moveAreaContainer: '.js-move-area-container', mainEventHandler: '.js-main-event-handler', eventHandlerWrapper: '.js-event-handler-wrapper', eventSquares: '.js-event-square', activeEventSquare: '.active-event-square', activeSquareMark: '.active-square-mark', buildingWrapper: '.js-building-wrapper', unitsWrapper: '.js-units-wrapper', unitWrapper: '.js-unit-wrapper', building: '.js-building', smokeWrapper: '.js-smoke-wrapper', viewDisable: '.js-view-disable', viewCpuDisable: '.js-view-cpu-disable', square: '.js-square', statusBar: '.js-battle-view-status-bar', styleSquareSize: '.js-style-square-size', unitInfoWrapper: '.js-unit-info-wrapper', moveBack: '.js-move-back-button', helpButton: '.js-help-button' }, squareSize: win.APP.map.squareSize, initialize: function(data) { var view = this; view.detectClickEvent(); view.$el = $(view.tmpl.battle()); if (data.fromSave) { view.info.set('difficult', data.difficult); var args = { jsMapKey: data.jsMapKey, money: 500, players: data.players, unitLimit: data.unitLimit, difficult: data.difficult, fromSave: true }; view.set('args', args); view.set('argsForRestart', data.argsForRestart); view.set('map', data.map); // see normal load view.set( 'model', new win.APP.BB.BattleModel({ view: view, args: view.get('args'), map: view.get('map'), savedData: data }) ); view.set('markActiveSquare', {}); // {x: number, y: number} view.set('infoSquareXY', {x: 0, y: 0}); // {x: number, y: number} // set sizes view.setSize(); // draw map //setTimeout(function () { view.drawMap(); //}, 50); // draw buildings view.drawBuildings(); // + // draw units view.drawUnits(); // + view.drawGraves(); // bind move area view.bindMoveArea(); view.bindEventListeners(); view.render(); view.moveBack.init({view: view}); // start game from model view.get('model').startGame(); view.proto.initialize.apply(view, arguments); return; } // get map view.set('args', data); view.set('argsForRestart', view.util.copyJSON(data)); win.APP.map.db .getMap({ jsMapKey: data.jsMapKey, type: data.type }) .then(function(map) { view.set('map', map); view.set( 'model', new win.APP.BB.BattleModel({ view: view, args: view.get('args'), map: view.get('map') }) ); view.set('markActiveSquare', {}); // {x: number, y: number} view.set('infoSquareXY', {x: 0, y: 0}); // {x: number, y: number} // set sizes view.setSize(); //draw map view.drawMap(); // draw buildings view.drawBuildings(); // draw units view.drawUnits(); // bind move area view.bindMoveArea(); view.bindEventListeners(); view.render(); view.moveBack.init({view: view}); // start game from model view.get('model').startGame(); view.proto.initialize.apply(view, arguments); }); }, moveUndo: function() { this.moveBack.moveBack(); }, moveBack: { init: function(data) { var moveBack = this, view = data.view; moveBack.view = view; moveBack.$button = view.$el.find(view.selectors.moveBack); }, pushUnit: function(unit) { var moveBack = this; moveBack.unitSavedData = unit.toJSON(); moveBack.unit = unit; if (unit.get('model').get('activePlayer').type !== 'cpu') { moveBack.showButton(); } }, moveBack: function() { var moveBack = this, view = moveBack.view, unit = moveBack.unit, xy; unit.set(moveBack.unitSavedData); xy = { x: unit.get('x'), y: unit.get('y') }; moveBack.view .moveUnitTo({ unit: unit, x: xy.x, y: xy.y }) .then(function() { moveBack.clear(); view.onClick(xy); }); }, showButton: function() { var moveBack = this; moveBack.$button.removeClass('hidden'); }, hideButton: function() { var moveBack = this; moveBack.$button.addClass('hidden'); }, clear: function() { var moveBack = this; moveBack.hideButton(); moveBack.unitSavedData = null; delete moveBack.unitSavedData; moveBack.unit = null; delete moveBack.unit; } }, restart: function() { var view = this, args = view.get('argsForRestart'); view.trigger('hide'); new view.constructor(args); }, disable: function() { this.$el.find(this.selectors.viewDisable).removeClass('hidden'); }, enable: function() { this.$el.find(this.selectors.viewDisable).addClass('hidden'); }, onClick: function(xy) { var view = this; view.markActiveSquare(xy); view.autoSetSquareInfo(); // 0 - show unit available attack (using available path) - hold or dblclick // 1 - show unit info in popup - hold or dblclick // 5 - show available path - only for player unit - click view.get('model').click(xy); }, endTurn: function() { var view = this, info = view.info; if (info.get('confirmTurn') === 'on') { view.showPopup({ popupName: 'end-turn-popup', parentView: view }); return; } view.confirmedEndTurn(); }, confirmedEndTurn: function() { var view = this; view.get('model').newTurn(); view.removeActiveSquare(); view.clearAvailableActions(); }, markActiveSquare: function(xy) { this.removeActiveSquare(); var view = this, x = xy.x, y = xy.y, util = view.util, selectors = view.selectors, squareEventHandler = util.findIn( view.$el[0], selectors.eventSquares + '[data-xy="x' + x + 'y' + y + '"]' ); if (!squareEventHandler) { squareEventHandler = view.createEventHandlerListener({ x: xy.x, y: xy.y }); } view.set('markActiveSquare', { x: x, y: y }); $(squareEventHandler).html('<div class="' + view.classNames.activeSquareMark + '">&nbsp;</div>'); view.showUnitInfo(); }, removeActiveSquare: function() { var view = this, node = view.util.findIn(view.$el[0], view.selectors.activeSquareMark); view.set('markActiveSquare', { x: null, y: null }); view.hideUnitInfo(); //return node && node.parentNode.removeChild(node); return node && $(node).remove(); }, restoreActiveSquare: function() { var view = this, markActiveSquareXy = view.get('markActiveSquare'); if (markActiveSquareXy.x === null || markActiveSquareXy.y === null) { return; } view.markActiveSquare(markActiveSquareXy); view.showUnitInfo(); }, showAvailableActions: function(actions) { var view = this, deferred = $.Deferred(); view.clearAvailableActions(); if (actions.availablePathWithTeamUnit) { view.showAvailablePathWithTeamUnit(actions.availablePathWithTeamUnit); } if (actions.confirmMoveAction) { view.showConfirmMoveAction(actions.confirmMoveAction); } if (actions.unitsUnderAttack) { view.showUnitsUnderAttack(actions.unitsUnderAttack); } if (actions.confirmAttackAction) { view.showConfirmAttackAction(actions.confirmAttackAction); } if (actions.gravesToRaise) { view.showGravesToRaise(actions.gravesToRaise); } if (actions.buildingToFix) { view.showFixBuilding(actions.buildingToFix); } if (actions.buildingToOccupy) { view.showBuildingToOccupy(actions.buildingToOccupy); } if (actions.openStore) { view.showOpenStore(actions.openStore); } if (actions.availableAttackMapWithPath) { view.showAvailableAttackMapWithPath(actions.availableAttackMapWithPath); } setTimeout(function() { deferred.resolve(); }, win.APP.info.actionTime()); return deferred.promise(); }, showAvailablePathWithTeamUnit: function(path) { path.forEach(function(xy) { this.createEventHandlerListener({ x: xy.x, y: xy.y, className: 'show-available-path' }); }, this); }, showConfirmMoveAction: function(confirmMoveAction) { this.createEventHandlerListener({ x: confirmMoveAction.x, y: confirmMoveAction.y, className: 'show-confirm-move' }); }, showUnitsUnderAttack: function(unitsUnderAttack) { unitsUnderAttack.forEach(function(xy) { this.createEventHandlerListener({ x: xy.x, y: xy.y, className: 'show-unit-under-attack' }); }, this); }, showConfirmAttackAction: function(confirmAttackAction) { this.createEventHandlerListener({ x: confirmAttackAction.x, y: confirmAttackAction.y, className: 'show-confirm-attack' }); }, showGravesToRaise: function(graves) { graves.forEach(function(xy) { this.createEventHandlerListener({ x: xy.x, y: xy.y, className: 'show-raise-skeleton' }); }, this); }, showFixBuilding: function(building) { this.createEventHandlerListener({ x: building.x, y: building.y, className: 'show-fix-building' }); }, showBuildingToOccupy: function(building) { this.createEventHandlerListener({ x: building.x, y: building.y, className: 'show-occupy-building' }); }, showOpenStore: function(xy) { this.createEventHandlerListener({ x: xy.x, y: xy.y, className: 'show-open-store' }); }, showAvailableAttackMapWithPath: function(attackSquares) { var view = this, util = view.util, el = view.$el[0], squareSelector = view.selectors.eventSquares, availableAttackClassName = 'show-available-attack'; attackSquares.forEach(function(xy) { var x = xy.x, y = xy.y, node = util.findIn(el, squareSelector + '[data-xy="x' + x + 'y' + y + '"]'); if (node) { node.classList.add(availableAttackClassName); return; } view.createEventHandlerListener({ x: x, y: y, className: availableAttackClassName }); }); }, clearAvailableActions: function() { var view = this, //util = view.util, //nodes = util.findInAll(view.$el[0], view.selectors.eventSquares), nodes = view.$el.find(view.selectors.eventSquares); //parentNode = nodes[0] && nodes[0].parentNode; nodes.remove().empty(); //nodes.forEach(function (node) { // parentNode.removeChild(node); //}); view.restoreActiveSquare(); }, updateStatusBar: function() { var view = this, util = view.util, hideSymbols = util.hideSymbols, model = view.get('model'), activePlayer = model.get('activePlayer'), unitLimit = model.get('unitLimit'), color = activePlayer.color, money = activePlayer.money, playerUnits = model.getUnitsByOwnerId(activePlayer.id), isCpu = activePlayer.type === 'cpu', obj = { color: color, unitLimit: isCpu ? hideSymbols(unitLimit, '-') : unitLimit, unitCount: isCpu ? hideSymbols(playerUnits.length, '-') : playerUnits.length, money: isCpu ? hideSymbols(money, '-') : money }, $node = view.tmpl['battle-view-status-bar'](obj), $statusBarWrapper = view.$el.find(view.selectors.statusBar); $statusBarWrapper.empty().append($node); view.autoSetSquareInfo(); }, autoSetSquareInfo: function() { var view = this, xy = view.get('markActiveSquare'), model = view.get('model'), isNotXY = typeof xy.x !== 'number' || typeof xy.y !== 'number', building, terrain, infoViewObj = {}, $el = view.$el, $node; if (isNotXY) { xy = view.get('infoSquareXY'); xy.x = xy.x || 0; xy.y = xy.y || 0; } view.set('infoSquareXY', xy); building = model.getBuildingByXY(xy); terrain = model.getTerrainByXY(xy); infoViewObj.armor = model.getArmorByXY(xy); if (building) { if (building.state === 'normal') { infoViewObj.className = 'building-' + building.type + '-' + building.color; } if (building.state === 'destroyed') { infoViewObj.className = 'building-' + building.type + '-destroyed'; } } else if (terrain) { // find terrain infoViewObj.className = 'terrain-' + terrain.terrainName; } $node = $(view.tmpl['battle-view-info-square'](infoViewObj)); $el.find('.js-status-bar-info-square-container') .remove() .empty(); $el.find('.js-status-bar-info-square-wrapper').append($node); }, bindEventListeners: function() { var device = win.APP.device; this.listenTo(device, 'resize', this.onResize); }, unbindEventListeners: function() { this.stopListening(); this.get('mover').unbindEventListeners(); }, onResize: function() { var mover = this.get('mover'); mover.detectSizes(); mover.detectEdgePositions(); mover.onResizeCheckState(); }, createEventHandlerListener: function(data) { // x, y, className var view = this, util = view.util, x = data.x, y = data.y, className = data.className || '', squareSize = view.getSquareSize(), pre = view.info.get('pre', true).css, node = doc.createElement('div'), prevNode = util.findIn(view.$el[0], view.selectors.eventSquares + '[data-xy="x' + x + 'y' + y + '"]'), wrapper; node.innerHTML = '&nbsp;'; if (prevNode) { $(prevNode) .remove() .empty(); //prevNode.parentNode.removeChild(prevNode); } node.className = ('js-square js-event-square square ' + className).trim(); node.setAttribute('data-xy', 'x' + x + 'y' + y); node.setAttribute('data-x', x); node.setAttribute('data-y', y); node.setAttribute( 'style', pre + 'transform: translate3d(' + x * squareSize + 'px, ' + y * squareSize + 'px, 0);' ); wrapper = util.findIn(view.$el[0], view.selectors.eventHandlerWrapper); wrapper.appendChild(node); return node; }, drawMap: function() { var view = this, $mapImageWrapper = view.$el.find(view.selectors.mapImageWrapper), canvas = doc.createElement('canvas'), //canvas = $mapImageWrapper.get(0), ctx = canvas.getContext('2d'), getXYFromStringXY = view.util.getXYFromStringXY, xyStr = view.util.getStringFromXY, map = view.get('map'), squareSize = view.squareSize.max, squareSizeX2, mapTiles = win.APP.mapTiles, terrains = map.terrain, angleTypes = ['road', 'water'], mapWidth = map.size.width, mapHeight = map.size.height, maxCanvasSize = win.APP.map.maxCanvasSize, args = view.get('args'), mapType = args.type, jsMapKey = args.jsMapKey; // detect skirmish and missions if (['skirmish', 'mission'].indexOf(mapType) !== -1) { $mapImageWrapper.html('&nbsp;').css('background-image', 'url(map/' + jsMapKey + '.png)'); return; } //if ( !this.info.get('isAndroid', true) ) { // for NOT android set size 24 // squareSize = 48; // see tiles image size 24 * 2 //} // adjust square size while (mapWidth * mapHeight * squareSize * squareSize * 4 >= maxCanvasSize) { squareSize -= 6; } //squareSize -= 6; squareSizeX2 = squareSize * 2; canvas.width = mapWidth * squareSizeX2; canvas.height = mapHeight * squareSizeX2; // reduce blur for ios devices ctx.webkitImageSmoothingEnabled = false; ctx.mozImageSmoothingEnabled = false; ctx.imageSmoothingEnabled = false; // future // prepare buildings _.each(terrains, function(value, xy) { var building = _.find(map.buildings, getXYFromStringXY(xy)); if (!building) { return; } if ('farm' === building.type) { terrains[xy] = 'terra-1'; } else { terrains[xy] = 'road-1'; } }); // draw main tiles _.each(terrains, function(value, xy) { xy = getXYFromStringXY(xy); ctx.drawImage( mapTiles[value].img, xy.x * squareSizeX2, xy.y * squareSizeX2, squareSizeX2, squareSizeX2 ); }); function isReal(x, y) { return x >= 0 && y >= 0 && x < mapWidth && y < mapHeight; } // draw angles road angleTypes.forEach(function(type) { _.each(terrains, function(value, xy) { if (value.indexOf(type) === -1) { return; } xy = getXYFromStringXY(xy); var x = xy.x, y = xy.y, xl = x - 1, xr = x + 1, yu = y - 1, yd = y + 1, xSquareSizeX2 = x * squareSizeX2, ySquareSizeX2 = y * squareSizeX2, xSquareSizeX2Half = xSquareSizeX2 + squareSize, ySquareSizeX2Half = ySquareSizeX2 + squareSize, terrain1Real = isReal(xl, yu) && terrains[xyStr(xl, yu)], terrain2Real = isReal(x, yu) && terrains[xyStr(x, yu)], terrain3Real = isReal(xr, yu) && terrains[xyStr(xr, yu)], terrain4Real = isReal(xl, y) && terrains[xyStr(xl, y)], terrain6Real = isReal(xr, y) && terrains[xyStr(xr, y)], terrain7Real = isReal(xl, yd) && terrains[xyStr(xl, yd)], terrain8Real = isReal(x, yd) && terrains[xyStr(x, yd)], terrain9Real = isReal(xr, yd) && terrains[xyStr(xr, yd)], terrain1 = terrain1Real || value, terrain2 = terrain2Real || value, terrain3 = terrain3Real || value, terrain4 = terrain4Real || value, terrain6 = terrain6Real || value, terrain7 = terrain7Real || value, terrain8 = terrain8Real || value, terrain9 = terrain9Real || value, // true if no bridge or no terrain type t1 = terrain1.indexOf(type) && terrain1.indexOf('bridge'), t2 = terrain2.indexOf(type) && terrain2.indexOf('bridge'), t3 = terrain3.indexOf(type) && terrain3.indexOf('bridge'), t4 = terrain4.indexOf(type) && terrain4.indexOf('bridge'), t6 = terrain6.indexOf(type) && terrain6.indexOf('bridge'), t7 = terrain7.indexOf(type) && terrain7.indexOf('bridge'), t8 = terrain8.indexOf(type) && terrain8.indexOf('bridge'), t9 = terrain9.indexOf(type) && terrain9.indexOf('bridge'); if (type === 'road') { if (!terrain2Real) { t2 = !t4 || !t6; } if (!terrain4Real) { t4 = !t2 || !t8; } if (!terrain6Real) { t6 = !t2 || !t8; } if (!terrain8Real) { t8 = !t4 || !t6; } } // draw 2, 4, 6, 8 if (t2) { // up is different type ctx.drawImage( mapTiles['a-' + type + '-2'].img, xSquareSizeX2, ySquareSizeX2, squareSizeX2, squareSize ); } if (t4) { ctx.drawImage( mapTiles['a-' + type + '-4'].img, xSquareSizeX2, ySquareSizeX2, squareSize, squareSizeX2 ); } if (t6) { ctx.drawImage( mapTiles['a-' + type + '-6'].img, xSquareSizeX2Half, ySquareSizeX2, squareSize, squareSizeX2 ); } if (t8) { ctx.drawImage( mapTiles['a-' + type + '-8'].img, xSquareSizeX2, ySquareSizeX2Half, squareSizeX2, squareSize ); } // draw 1, 3, 7, 9 - normal if (t2 && t4) { ctx.drawImage( mapTiles['a-' + type + '-1'].img, xSquareSizeX2, ySquareSizeX2, squareSize, squareSize ); } if (t2 && t6) { ctx.drawImage( mapTiles['a-' + type + '-3'].img, xSquareSizeX2Half, ySquareSizeX2, squareSize, squareSize ); } if (t4 && t8) { ctx.drawImage( mapTiles['a-' + type + '-7'].img, xSquareSizeX2, ySquareSizeX2Half, squareSize, squareSize ); } if (t6 && t8) { ctx.drawImage( mapTiles['a-' + type + '-9'].img, xSquareSizeX2Half, ySquareSizeX2Half, squareSize, squareSize ); } // draw 1, 3, 7, 9 - small if (!t2 && !t4 && t1) { ctx.drawImage( mapTiles['a-' + type + '-1-s'].img, xSquareSizeX2, ySquareSizeX2, squareSize, squareSize ); } if (!t2 && !t6 && t3) { ctx.drawImage( mapTiles['a-' + type + '-3-s'].img, xSquareSizeX2Half, ySquareSizeX2, squareSize, squareSize ); } if (!t4 && !t8 && t7) { ctx.drawImage( mapTiles['a-' + type + '-7-s'].img, xSquareSizeX2, ySquareSizeX2Half, squareSize, squareSize ); } if (!t6 && !t8 && t9) { ctx.drawImage( mapTiles['a-' + type + '-9-s'].img, xSquareSizeX2Half, ySquareSizeX2Half, squareSize, squareSize ); } // fix building }); }); $mapImageWrapper.find('img')[0].src = canvas.toDataURL(); }, drawBuildings: function() { var view = this, model = view.get('model'), info = view.info, smokeState = info.get('buildingSmoke'); model.appendBuildings(); if (smokeState === 'on') { view.showHouseSmoke(); } else { view.hideHouseSmoke(); } }, hideHouseSmoke: function() { this.$el .find(this.selectors.smokeWrapper) .remove() .empty(); }, showHouseSmoke: function() { var view = this, model = view.get('model'), buildings = model.get('buildings'), $el = view.$el, selectors = view.selectors, $eventHandleWrapper = $el.find(selectors.eventHandlerWrapper), $smokeWrapper = $('<div/>') .attr('class', 'js-smoke-wrapper smoke-wrapper') .attr('style', $eventHandleWrapper.attr('style')); view.hideHouseSmoke(); $eventHandleWrapper.after($smokeWrapper); _.each(buildings, function(building) { if (building.type === 'farm' && building.hasOwnProperty('ownerId')) { view.addSmokeToBuilding(building); } }); }, appendBuilding: function(building) { var $node = $('<div>&nbsp;</div>'), x = building.x, y = building.y, dY = building.type === 'castle' ? -1 : 0, squareSize = this.getSquareSize(), height = squareSize - squareSize * dY, pre = this.info.get('pre', true).css, $wrapper = this.$el.find(this.selectors.buildingWrapper); $node .attr('data-xy', 'x' + x + 'y' + y) .attr('data-x', x) .attr('data-y', y) .attr('data-type', building.type); $node .addClass('building') .addClass('js-building') .addClass('square'); if (building.state === 'normal') { $node.addClass('building-' + building.type + '-' + (building.color || 'gray')); } if (building.state === 'destroyed') { $node.addClass('building-' + building.type + '-destroyed'); } x = x * squareSize; y = (y + dY) * squareSize; $node.css(pre + 'transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)'); $node.css({ height: height + 'px' }); if (building.type === 'farm' && building.hasOwnProperty('ownerId')) { this.addSmokeToBuilding(building); } $wrapper.append($node); }, redrawBuilding: function(building) { var view = this, state = building.state, color = building.color || win.APP.building.defaults.color, type = building.type, x = building.x, y = building.y, $wrapper = view.$el.find(view.selectors.buildingWrapper), $buildingNode = $wrapper.find('[data-xy="x' + x + 'y' + y + '"]'); $buildingNode.attr('class', '').addClass('building js-building square'); if (state === 'normal') { $buildingNode.addClass('building-' + type + '-' + color); } if (state === 'destroyed') { $buildingNode.addClass('building-' + type + '-destroyed'); view.removeSmokeToBuilding(building); } if (type === 'farm' && building.hasOwnProperty('ownerId')) { view.addSmokeToBuilding(building); } else { view.removeSmokeToBuilding(building); } }, redrawUnit: function(unit) { var view = this, x = unit.get('x'), y = unit.get('y'), color = unit.get('color'), $unitWrapper = view.$el.find(view.selectors.unitsWrapper), allColors = win.APP.map.allColors, type = unit.get('type'), $unit = $unitWrapper.find('[data-xy="x' + x + 'y' + y + '"]'), $unitImage = $unit.find('.js-unit-image'); _.each(allColors, function(color) { $unitImage.removeClass('unit-image-' + type + '-' + color); }); $unitImage.addClass('unit-image-' + type + '-' + color); }, addSmokeToBuilding: function(building) { var x = building.x, y = building.y, pre = this.info.get('pre', true).css, squareSize = this.getSquareSize(), $wrapper = this.$el.find(this.selectors.smokeWrapper), $smokeContainer = $( '<div class="square js-square"><div class="building-smoke-mover"><div class="building-smoke">&nbsp;</div></div></div>' ); if (!$wrapper.length) { return; } $wrapper .find('[data-xy="x' + x + 'y' + y + '"]') .remove() .empty(); $smokeContainer .attr('data-xy', 'x' + x + 'y' + y) .attr('data-x', x) .attr('data-y', y); x *= squareSize; y *= squareSize; $smokeContainer.css(pre + 'transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)'); $wrapper.append($smokeContainer); }, removeSmokeToBuilding: function(building) { var x = building.x, y = building.y, $wrapper = this.$el.find(this.selectors.smokeWrapper), $smokeContainer = $wrapper.find('[data-xy="x' + x + 'y' + y + '"]'); if (!$wrapper.length) { return; } $smokeContainer.remove().empty(); }, drawUnits: function() { var model = this.get('model'); model.appendUnits(); }, drawGraves: function() { var model = this.get('model'); model.appendGraves(); }, appendUnit: function(unit) { var view = this, pre = view.info.get('pre', true).css, $unitWrapper = $('<div></div>'), squareSize = view.getSquareSize(), $unitBlock = $('<div>&nbsp;</div>'), unitInfo = unit.toJSON(), x = unitInfo.x, y = unitInfo.y, cssX = x * squareSize, cssY = y * squareSize, unitType = unit.get('type'), $unitLayerWrapper = view.$el.find(view.selectors.unitsWrapper), unitImage, animationEnd = view.info.get('animationEnd', true); $unitWrapper.css(pre + 'transform', 'translate3d(' + cssX + 'px, ' + cssY + 'px, 0)'); $unitWrapper.attr({ 'data-x': x, 'data-y': y, 'data-xy': 'x' + x + 'y' + y, 'data-unit-id': unitInfo.id }); $unitWrapper.addClass('js-square square unit-wrapper unit-wrapper-' + unitType); $unitWrapper.append($unitBlock); $unitBlock.addClass('js-unit-image unit-image unit-image-' + unitType + '-' + unitInfo.color); // health //$unitWrapper.append('<div class="js-unit-health unit-health"><div class="js-unit-health-ten unit-health-ten">&nbsp;</div><div class="js-unit-health-one unit-health-one">&nbsp;</div></div>'); // delta health //$unitWrapper.append('<div class="js-delta-unit-health delta-unit-health"><div class="js-delta-unit-health-sign delta-unit-health-sign">&nbsp;</div><div class="js-delta-unit-health-ten delta-unit-health-ten">&nbsp;</div><div class="js-delta-unit-health-one delta-unit-health-one">&nbsp;</div></div>'); // wisp aura //$unitWrapper.append('<div class="js-under-wisp-aura-image under-wisp-aura-image">&nbsp;</div>'); // poisoned //$unitWrapper.append('<div class="js-under-poison-image under-poison-image">&nbsp;</div>'); // level //$unitWrapper.append('<div class="js-unit-level unit-level">&nbsp;</div>'); // level up //$unitWrapper.append('<div class="js-unit-level-up unit-level-up">&nbsp;</div>'); // show unit appear animation unitImage = $unitWrapper.find('.unit-image'); unitImage.one(animationEnd, function() { $(this).removeClass('show-new-unit'); }); // work only one time unitImage.addClass('show-new-unit'); $unitLayerWrapper.append($unitWrapper); view.setUnitHealth({unit: unit}); view.setUnitLevel({unit: unit, doNotShowLevelUp: Boolean(unit.get('xp'))}); }, removeUnit: function(unit) { this.getUnitByUnit(unit) .remove() .empty(); }, getUnitByUnit: function(unit) { return this.$el.find(this.selectors.unitsWrapper + ' [data-unit-id="' + unit.get('id') + '"]'); }, setActiveUnit: function(unit) { this.getUnitByUnit(unit).removeClass('not-active'); }, setNotActiveUnit: function(unit) { this.getUnitByUnit(unit).addClass('not-active'); }, addGrave: function(grave) { var view = this, pre = view.info.get('pre', true).css, $graveWrapper = $('<div>&nbsp;</div>'), squareSize = view.getSquareSize(), x = grave.x, y = grave.y, cssX = x * squareSize, cssY = y * squareSize, $unitLayerWrapper = view.$el.find(view.selectors.unitsWrapper); $graveWrapper.css(pre + 'transform', 'translate3d(' + cssX + 'px, ' + cssY + 'px, 0)'); $graveWrapper.attr({ 'data-x': x, 'data-y': y, 'data-xy': 'x' + x + 'y' + y, 'data-grave-id': grave.id }); $graveWrapper.addClass('js-square square grave-wrapper'); $unitLayerWrapper.append($graveWrapper); }, removeGrave: function(grave) { var view = this, $graveWrapper = view.$el.find(view.selectors.unitsWrapper + ' [data-grave-id="' + grave.id + '"]'); $graveWrapper.remove().empty(); }, setWispAuraState: function(data) { var view = this, unit = data.unit, wispAuraState = data.wispAuraState, $unitNode = view.getUnitByUnit(unit), $wispAura; if (wispAuraState) { // do not add node if node exist $wispAura = $unitNode.find('.js-under-wisp-aura-image'); if (!$wispAura.length) { $unitNode.append('<div class="js-under-wisp-aura-image under-wisp-aura-image">&nbsp;</div>'); } } else { //remove wist aura $unitNode .find('.js-under-wisp-aura-image') .remove() .empty(); } }, setPoisonState: function(data) { var view = this, unit = data.unit, poisonCount = data.poisonCount, $unitNode = view.getUnitByUnit(unit), $poison; if (poisonCount) { // do not add node if node exist $poison = $unitNode.find('.js-under-poison-image'); if (!$poison.length) { $unitNode.append('<div class="js-under-poison-image under-poison-image">&nbsp;</div>'); } } else { $unitNode .find('.js-under-poison-image') .remove() .empty(); } }, getSquareSize: function() { return this.info.get('squareSize'); }, setSize: function() { var squareSize = this.getSquareSize() || this.squareSize.default, selectors = this.selectors, $moveAreaContainer = this.$el.find(selectors.moveAreaContainer), $mapImageWrapper = this.$el.find(selectors.mapImageWrapper), $eventHandlerWrapper = this.$el.find(selectors.eventHandlerWrapper), $squares = this.$el.find(selectors.square), $buildings = this.$el.find(selectors.building), map = this.get('map'), pre = this.info.get('pre', true).css, width = map.size.width * squareSize, height = map.size.height * squareSize, $innerBlocks = this.$el.find(selectors.moveAreaContainer + '> div'); this.info.set('squareSize', squareSize); // set container $moveAreaContainer.css({ width: width + 'px', height: height + 'px' }); // set canvas $mapImageWrapper.css({ width: width + 'px', height: height + 'px' }); // set event handler wrapper $eventHandlerWrapper.css({ width: width + 'px', height: height + 'px' }); // set .building-wrapper, units-wrapper and etc. $innerBlocks.css({ width: width + 'px', height: height + 'px' }); // set squares sizes $squares.each(function() { var $this = $(this), x = Number($this.attr('data-x')) * squareSize, y = Number($this.attr('data-y')) * squareSize; $this.css(pre + 'transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)'); }); // set buildings position $buildings.each(function() { var $this = $(this), type = $this.attr('data-type'), x = Number($this.attr('data-x')), y = Number($this.attr('data-y')), dY = type === 'castle' ? -1 : 0, nodeHeight = squareSize - squareSize * dY; x = x * squareSize; y = (y + dY) * squareSize; $this.css(pre + 'transform', 'translate3d(' + x + 'px, ' + y + 'px, 0)'); $this.css({ height: nodeHeight + 'px' }); }); this.autoSetStyleForSize(); }, autoSetStyleForSize: function() { var view = this, squareSize = view.getSquareSize(), $el = view.$el, selectors = view.selectors, $style = $el.find(selectors.styleSquareSize); $style.html( '.square-grid { background-size: ' + squareSize + 'px ' + squareSize + 'px } .square { width: ' + squareSize + 'px; height: ' + squareSize + 'px; }' ); }, bindMoveArea: function() { var moveAreaWrapper = this.$el.find(this.selectors.moveAreaWrapper), moveAreaContainer = moveAreaWrapper.find(this.selectors.moveAreaContainer), mover = new Mover({ wrapper: moveAreaWrapper, container: moveAreaContainer, onRedraw: { context: this, fn: this.onRedrawMapFromMover } }); mover.init(); this.set('mover', mover); }, onRedrawMapFromMover: function(data) { var xyzs = data.xyzs, time = xyzs.hasOwnProperty('time') ? xyzs.time : 300, scale = xyzs.scale, x = xyzs.x, y = xyzs.y, z = xyzs.z, squareSize = Math.round(this.getSquareSize() * scale), mover = this.get('mover'); squareSize = win.APP.util.getBetween(this.squareSize.min, squareSize, this.squareSize.max); this.info.set('squareSize', squareSize); this.setSize(); mover.detectSizes(); mover.detectEdgePositions(); mover.setDefaultContainerSize(); mover.setStyleByXYZS({ x: x, y: y, z: z, time: time, check: true // fix if user up two finger simultaneously }); mover.set('currentContainerXY', { // fix if user up two finger simultaneously x: x, // see mover.fixAfterResizing y: y }); }, detectClickEvent: function() { var view = this, selectors = view.selectors; $.Finger.pressDuration = 600; view.events[view.eventTypes.down + ' ' + selectors.moveAreaContainer] = 'saveDownEvent'; view.events[view.eventTypes.move + ' ' + selectors.moveAreaContainer] = 'saveMoveEvent'; view.events[view.eventTypes.up + ' ' + selectors.mainEventHandler] = 'detectClick'; view.events[view.eventTypes.dbl + ' ' + selectors.mainEventHandler] = 'detectDblClick'; view.events['press' + ' ' + selectors.mainEventHandler] = 'detectPress'; }, detectClick: function() { var view = this, downXY = view.get('downEvent'), moveXY = view.get('moveEvent'), maxDeltaMove = 10, xy; if (!downXY || !moveXY) { return; } if (Math.abs(downXY.x - moveXY.x) + Math.abs(downXY.y - moveXY.y) > maxDeltaMove) { return; } xy = view.getEventXy(); view.onClick(xy); }, detectPress: function() { var view = this, downEvent = view.get('downEvent'), moveEvent = view.get('moveEvent'), lang, model, xy, unit, levelPercent, unitLangData, placeArmor; if (Math.abs(downEvent.x - moveEvent.x) + Math.abs(downEvent.y - moveEvent.y) > 7) { // detect press event without move return; } model = view.get('model'); xy = view.getEventXy(); unit = model.getUnitByXY(xy); if (!unit) { return; } model.clearAvailableActions(); view.clearAvailableActions(); lang = win.APP.lang; unitLangData = lang.get('unitsList')[unit.get('langKey')]; levelPercent = (function() { var levelList = win.APP.unitMaster.levelList, xp = unit.get('xp') || 0, level = unit.get('level') || 0, min = levelList[level], max = levelList[level + 1], length = max - min; if (!max) { // max level exceed return 100; } return ((xp - min) / length) * 100; // de })(); /*jslint white: true, nomen: true */ placeArmor = (function() { var unitXY = { x: unit.get('x'), y: unit.get('y') }, unitMoveType = unit.get('moveType'), unitTerrain = model.getTerrainByXY(unitXY); // detect armor for elementals if (unitMoveType === 'flow' && unitTerrain.terrainType === 'water') { return win.APP.unitMaster.bonusDefByWater; } return model.getArmorByXY(unitXY); })(); view.showPopup({ cssClass: 'full', popupName: 'full-unit-info', popupData: { unit: unit, defByTerrain: placeArmor, img: ['unit-image', unit.get('type'), unit.get('color')].join('-'), name: unitLangData.name, description: unitLangData.description, levelPercent: levelPercent } }); }, detectDblClick: function() { var view = this, model = view.get('model'), xy = view.getEventXy(), activePlayer = model.get('activePlayer'), availableActions, availableAttackMapWithPath, //x = markActiveSquareXy.x, //y = markActiveSquareXy.y, unit = model.getUnitByXY(xy); if (!unit) { return; } availableAttackMapWithPath = unit.getAvailableAttackMapWithPath(); if (unit.get('ownerId') === activePlayer.id) { // 'active' unit availableActions = unit.getAvailableActions(); availableActions.availableAttackMapWithPath = availableAttackMapWithPath; view.showAvailableActions(availableActions); model.set('availableActions', availableActions); } else { // enemy or teams unit model.clearAvailableActions(); view.clearAvailableActions(); view.showAvailableActions({ availablePathWithTeamUnit: unit.getAvailablePathWithTeamUnit(), availableAttackMapWithPath: availableAttackMapWithPath }); } }, getEventXy: function() { var view = this, x, y, downXY = view.get('downEvent'), selectors = view.selectors, $el = view.$el, $moveAreaWrapper = $el.find(selectors.moveAreaWrapper), $moveAreaContainer = $el.find(selectors.moveAreaContainer), squareSize = view.getSquareSize(), $mainEventHandler = $el.find(selectors.mainEventHandler), w = $moveAreaWrapper.width(), h = $moveAreaWrapper.height(), aw = $mainEventHandler.width(), ah = $mainEventHandler.height(), dxy = view.util.getXyFromStyle($moveAreaContainer.attr('style')); x = (aw - w) / 2 + downXY.x - dxy.x; y = (ah - h) / 2 + downXY.y - dxy.y; x = Math.floor(x / squareSize); y = Math.floor(y / squareSize); return { x: x, y: y }; }, saveDownEvent: function(e) { var events = this.getEvents(e); if (events.length === 1) { this.set('downEvent', events.events[0]); this.set('moveEvent', events.events[0]); } else { this.set('downEvent', false); this.set('moveEvent', false); } }, saveMoveEvent: function(e) { var events = this.getEvents(e); if (events.length === 1) { this.set('moveEvent', events.events[0]); } else { this.set('moveEvent', false); } }, getEvents: function(e) { e = e.originalEvent; var evt = {}, touches = e.touches, events = touches || [e]; evt.events = []; evt.length = events.length; _.each(events, function(e) { evt.events.push({ x: e.clientX, y: e.clientY }); }); return evt; }, ////////////////// // unit actions ////////////////// moveUnitTo: function(data) { var view = this, model = view.get('model'), deferred = $.Deferred(), pre = view.info.get('pre', true).css, transitionEnd = view.info.get('transitionEnd', true), squareSize = view.getSquareSize(), $unitNode = view.getUnitByUnit(data.unit), x = data.x, y = data.y, xPx = x * squareSize, yPx = y * squareSize; view.moveBack.pushUnit(data.unit); view.disable(); $unitNode.addClass('moving'); // set action on move end $unitNode.one(transitionEnd, function() { $(this) .removeClass('moving') .attr('data-x', x) .attr('data-y', y) .attr('data-xy', 'x' + x + 'y' + y); model.clearAvailableActions(); view.clearAvailableActions(); view.enable(); deferred.resolve(); }); // work only one time $unitNode.css(pre + 'transform', 'translate3d(' + xPx + 'px, ' + yPx + 'px, 0)'); return deferred.promise(); }, //showFightScreen: function (data) { // // var view = this, // info = view.info, // deferred = $.Deferred(), // fightAnimationView; // // if (info.get('fightAnimation') === 'on') { // fightAnimationView = new win.APP.BB.FightAnimationView({ // parentView: view, // parentDeferred: deferred, // attacker: { // unit: data.attacker // }, // defender: { // unit: data.defender // } // }); // // view.set('fightAnimationView', fightAnimationView); // // } else { // deferred.resolve(); // } // // return deferred.promise(); // //}, showAttack: function(data) { var view = this, model = view.get('model'), from = data.from, to = data.to, deferred = $.Deferred(), pre = view.info.get('pre', true).css, transitionEnd = view.info.get('transitionEnd', true), squareSize = view.getSquareSize(), attackNode = doc.createElement('div'), $attackNode, //$attackNode = $('<div class="attack-square square js-attack-square">&nbsp;</div>'), $unitsWrapper = view.$el.find(view.selectors.unitsWrapper); attackNode.className = 'attack-square square js-attack-square'; attackNode.innerHTML = '<div class="spark">&nbsp;</div>'; $attackNode = $(attackNode); view.removeActiveSquare(); $unitsWrapper.append($attackNode); $attackNode.css( pre + 'transform', 'translate3d(' + from.x * squareSize + 'px, ' + from.y * squareSize + 'px, 0)' ); $attackNode.one(transitionEnd, function() { //$(this).remove(); view.$el .find('.js-attack-square') .remove() .empty(); model.clearAvailableActions(); view.clearAvailableActions(); view.enable(); deferred.resolve(); }); // work only one time view.disable(); $attackNode.addClass('moving'); setTimeout(function() { // todo: try to do transitionEnd without this hack $attackNode.css( pre + 'transform', 'translate3d(' + to.x * squareSize + 'px, ' + to.y * squareSize + 'px, 0)' ); }, 50); return deferred.promise(); }, showDifferentUnitHealth: function(data) { var view = this, info = view.info, unit = data.unit, differentHealth = data.differentHealth, deferred = $.Deferred(), $unitWrapper = view.getUnitByUnit(unit), $deltaHealth = $( '<div class="js-delta-unit-health delta-unit-health"><div class="js-delta-unit-health-sign delta-unit-health-sign">&nbsp;</div><div class="js-delta-unit-health-ten delta-unit-health-ten">&nbsp;</div><div class="js-delta-unit-health-one delta-unit-health-one">&nbsp;</div></div>' ), animationEnd = view.info.get('animationEnd', true); $unitWrapper.append($deltaHealth); view.disable(); view.setUnitHealth({unit: unit}); view.setUnitDifferentHealth({ unit: unit, differentHealth: differentHealth }); $deltaHealth.one(animationEnd, function() { $(this) .remove() .empty(); view.enable(); deferred.resolve(); }); // work only one time //if (info.get('fightAnimation') === 'on') { // view.get('fightAnimationView').refreshStatusBar(); //} $deltaHealth.addClass('bounce'); return deferred.promise(); }, chars: { charsList: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'none', 'plus', 'minus', 'slash'], charReference: { '-': 'minus', '+': 'plus', '/': 'slash' } }, setUnitHealth: function(data) { var view = this, unit = data.unit, health = unit.get('health'), defaultHealth = unit.get('defaultHealth'), $unitWrapper = view.getUnitByUnit(unit), one = 'none', ten = 'none', $healthOne = $unitWrapper.find('.js-unit-health-one'), $healthTen = $unitWrapper.find('.js-unit-health-ten'); if (health === defaultHealth) { $healthOne.remove().empty(); $healthTen.remove().empty(); return; } health = health.toString().split(''); one = health.pop() || one; ten = health.pop() || ten; if (one === 'none') { $healthOne.remove().empty(); } else { if ($healthOne.length) { $healthOne.attr('class', 'js-unit-health-one unit-health-one number-1-' + one); } else { $unitWrapper.append( '<div class="js-unit-health-one unit-health-one number-1-' + one + '">&nbsp;</div>' ); } } if (ten === 'none') { $healthTen.remove().empty(); } else { if ($healthTen.length) { $healthTen.attr('class', 'js-unit-health-ten unit-health-ten number-1-' + ten); } else { $unitWrapper.append( '<div class="js-unit-health-ten unit-health-ten number-1-' + ten + '">&nbsp;</div>' ); } } }, setUnitDifferentHealth: function(data) { var view = this, $unitWrapper = view.getUnitByUnit(data.unit), sign = 'none', one = 'none', ten = 'none', $deltaHealthSign = $unitWrapper.find('.js-delta-unit-health-sign'), $deltaHealthOne = $unitWrapper.find('.js-delta-unit-health-one'), $deltaHealthTen = $unitWrapper.find('.js-delta-unit-health-ten'), differentHealth = data.differentHealth; if (differentHealth > 0) { sign = 'plus'; } if (differentHealth < 0) { sign = 'minus'; } differentHealth = Math.abs(differentHealth).toString(); if (differentHealth.length === 1) { one = differentHealth[0]; } if (differentHealth.length === 2) { one = differentHealth[1]; ten = differentHealth[0]; } $deltaHealthSign.addClass('number-2-' + sign); $deltaHealthOne.addClass('number-2-' + one); $deltaHealthTen.addClass('number-2-' + ten); }, setUnitLevel: function(data) { var view = this, unit = data.unit, level = unit.get('level'), $unitWrapper = view.getUnitByUnit(unit), $level = $unitWrapper.find('.js-unit-level'); if (!level) { return; } if ($level.length) { $level.attr('class', 'js-unit-level unit-level number-1-' + level); } else { $unitWrapper.append('<div class="js-unit-level unit-level number-1-' + level + '">&nbsp;</div>'); } if (!data.doNotShowLevelUp) { // when commander was killed and was buy in unit store view.showLevelUp({ unit: unit }); } }, showLevelUp: function(data) { var view = this, unit = data.unit, $unitWrapper = view.getUnitByUnit(unit), $levelUp = $('<div class="js-unit-level-up unit-level-up">&nbsp;</div>'), animationEnd = view.info.get('animationEnd', true); $unitWrapper.append($levelUp); $levelUp.one(animationEnd, function() { $(this) .remove() .empty(); }); // work only one time $levelUp.addClass('move-up'); }, //notifications showObjective: function() { var view = this, model = view.get('model'), map = model.get('map'), mapType = map.type, lang = win.APP.lang, languageField = 'objective-' + view.info.get('language'); if (mapType === 'mission') { return view.showPopup({ popupName: 'simple-notification', popupData: { header: lang.get('objective'), text: map[languageField] || map.objective } }); } if (/skirmish|userMap/.test(mapType)) { return view.showPopup({ popupName: 'simple-notification', popupData: { header: lang.get('objective'), text: lang.get('skirmishObjective') } }); } }, showBriefing: function(data) { data = data || {}; var view = this, model = view.get('model'), info = view.info, map = model.get('map'), briefingName = data.briefingName, languageField = briefingName + '-' + info.get('language'), briefingList = map[languageField] || map[briefingName] || [], // [] if map has no needed briefing deferred = $.Deferred(), promise = deferred.promise(), nextFunction; _.each(briefingList, function(item) { var onShow = item.onShow, onHide = item.onHide; if (onShow && onShow.context === 'parentView') { onShow.default_context = 'parentView'; onShow.context = view; } if (onHide && onHide.context === 'parentView') { onHide.default_context = 'parentView'; onHide.context = view; } nextFunction = (nextFunction || promise).then(function() { return view.showPopup(item); }); }); setTimeout(function() { deferred.resolve(); }, info.actionTime()); }, openMenu: function() { new APP.BB.BattleMenuView({ view: this }); }, showHelp: function() { var view = this, language = view.info.get('language'), model = view.get('model'), map = model.get('map'), help = map['help-' + language] || map.help || win.APP.lang.get('helpList'), $helpButton = view.$el.find(view.selectors.helpButton); if ($helpButton.hasClass('blink')) { $helpButton.addClass('hidden'); $helpButton.removeClass('blink'); setTimeout(function() { $helpButton.removeClass('hidden'); }, 200); } view.showPopup({ cssClass: 'full', popupName: 'help', popupData: { help: help } }); }, showUnitInfo: function() { var view = this, model = view.get('model'), unit, xy = view.get('markActiveSquare'), isNotXY = !xy.hasOwnProperty('x') || !xy.hasOwnProperty('y') || xy.x === null || xy.y === null; view.hideUnitInfo(); if (isNotXY) { return; } unit = model.getUnitByXY(xy); if (!unit) { return; } var placeArmor = model.getArmorByXY(xy), level = unit.get('level'), unitMoveType = unit.get('moveType'), unitXY = { x: unit.get('x'), y: unit.get('y') }, unitTerrain = model.getTerrainByXY(unitXY), atk = unit.get('atk'), atkMax = atk.max, atkMin = atk.min, def = unit.get('def'), underWispAura = unit.get('underWispAura'), poisonCount = unit.get('poisonCount'), unitMaster = win.APP.unitMaster, defByLevel = unitMaster.defByLevel, atkByLevel = unitMaster.atkByLevel, viewObj = {}; atkMin = atkMin + level * atkByLevel; atkMax = atkMax + level * atkByLevel; viewObj.atk = atkMin + '-' + atkMax; viewObj.def = def + level * defByLevel; viewObj.level = level; viewObj.underWispAura = underWispAura; viewObj.poisonCount = poisonCount; viewObj.placeArmor = placeArmor; // detect armor for elementals if (unitMoveType === 'flow' && unitTerrain.terrainType === 'water') { viewObj.placeArmor = unitMaster.bonusDefByWater; } view.$el.find(view.selectors.unitInfoWrapper).html(view.tmpl['unit-info'](viewObj)); }, hideUnitInfo: function() { var view = this; view.$el.find(view.selectors.unitInfoWrapper).empty(); }, cpuMode: function(onOff) { var view = this, $node = view.$el.find(view.selectors.viewCpuDisable); return onOff ? $node.removeClass('hidden') : $node.addClass('hidden'); }, centerToXY: function(xy) { var view = this, map = view.get('map'), mover = view.get('mover'), squareSize = view.getSquareSize(), width = map.size.width, height = map.size.height, x = Math.round((xy.x - width / 2) * squareSize), y = Math.round((xy.y - height / 2) * squareSize); mover.showXY({ x: -x, y: -y, time: view.info.actionTime() }); } }); })(window, window.document);
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M8 4c-.55 0-1 .45-1 1v1H6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h1v1c0 .55.45 1 1 1s1-.45 1-1v-1h1c.55 0 1-.45 1-1V7c0-.55-.45-1-1-1H9V5c0-.55-.45-1-1-1zm10 4h-1V5c0-.55-.45-1-1-1s-1 .45-1 1v3h-1c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h1v4c0 .55.45 1 1 1s1-.45 1-1v-4h1c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z" }), 'CandlestickChartRounded'); exports.default = _default;
import React, { Component } from 'react'; import { Menu, Dropdown, Button, Icon, message } from 'antd'; import { Link } from 'react-router'; import EmployeeTable from './table'; import { memberShip, employee, columns } from '../../accessConfig/employeeList'; import DropdownList from './../../commons/dropdown'; import { inject, observer } from 'mobx-react'; function handleButtonClick(e) { message.info('Click on left button.'); console.log('click left button', e); } function handleMenuClick(e) { message.info('Click on menu item.'); console.log('click', e); } const menu = ( <Menu onClick={handleMenuClick}> <Menu.Item key="1">1st menu item</Menu.Item> <Menu.Item key="2">2nd menu item</Menu.Item> <Menu.Item key="3">3d menu item</Menu.Item> </Menu> ); // <DevTools /> @inject('store') @observer export default class MemberShip extends Component { constructor(props, context) { super(props, context); this.state = { current: '1', }; } handleClick(e) { console.log('click ', e); this.setState({ current: e.key, }); } render() { const { memberShipStore } = this.props.store; return ( <div> <Dropdown overlay={menu}> <Button type="ghost" style={{ marginLeft: 8 }}> Button <Icon type="down" /> </Button> </Dropdown> <Link to="/setemployee">link</Link> <DropdownList dropdownList={memberShipStore.toJS()} mode={1} /> <Link to=""><Button type="primary">新增员工</Button></Link> <EmployeeTable columns={columns} dataSource={employee}/> </div> ) } }
define(['exports', './error-renderer'], function (exports, _errorRenderer) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var BootstrapErrorRenderer = (function (_ErrorRenderer) { _inherits(BootstrapErrorRenderer, _ErrorRenderer); function BootstrapErrorRenderer() { _classCallCheck(this, BootstrapErrorRenderer); _ErrorRenderer.apply(this, arguments); } BootstrapErrorRenderer.prototype.render = function render(rootElement, error, property) { if (property) { var formGroup = property.element.closest('.form-group'); formGroup.classList.add('has-error'); var messageContainer = property.element.closest('div:not(.input-group)'); var _message = document.createElement('span'); _message.classList.add('validation-error'); _message.error = error; _message.classList.add('help-block'); _message.classList.add('validation-error'); _message.textContent = error.errorMessage; messageContainer.appendChild(_message); } var alert = rootElement.querySelector('.validation-summary'); if (!alert) { alert = document.createElement('div'); alert.setAttribute('role', 'alert'); alert.classList.add('alert'); alert.classList.add('alert-danger'); alert.classList.add('validation-summary'); if (rootElement.firstChild) { rootElement.insertBefore(alert, rootElement.firstChild); } else { rootElement.appendChild(alert); } } var message = document.createElement('p'); message.classList.add('validation-error'); message.error = error; message.textContent = error.errorMessage; alert.appendChild(message); }; BootstrapErrorRenderer.prototype.unrender = function unrender(rootElement, error, property) { if (property) { var formGroup = property.element.closest('.form-group'); formGroup.classList.remove('has-error'); } var messages = rootElement.querySelectorAll('.validation-error'); var i = messages.length; while (i--) { var message = messages[i]; if (message.error.context.entity !== error.context.entity || message.error.key !== error.key) { continue; } message.error = null; message.remove(); } var alert = rootElement.querySelector('.validation-summary'); if (alert && alert.querySelectorAll('.validation-error').length === 0) { alert.remove(); } }; return BootstrapErrorRenderer; })(_errorRenderer.ErrorRenderer); exports.BootstrapErrorRenderer = BootstrapErrorRenderer; (function (ELEMENT) { ELEMENT.matches = ELEMENT.matches || ELEMENT.mozMatchesSelector || ELEMENT.msMatchesSelector || ELEMENT.oMatchesSelector || ELEMENT.webkitMatchesSelector; ELEMENT.closest = ELEMENT.closest || function closest(selector) { var element = this; while (element) { if (element.matches(selector)) { break; } element = element.parentElement; } return element; }; })(Element.prototype); });
var wxCharts = require('../../../utils/wxcharts.js'); var app = getApp(); var lineChart = null; var startPos = null; Page({ data: { }, touchHandler: function (e) { lineChart.scrollStart(e); }, moveHandler: function (e) { lineChart.scroll(e); }, touchEndHandler: function (e) { lineChart.scrollEnd(e); lineChart.showToolTip(e, { format: function (item, category) { return category + ' ' + item.name + ':' + item.data } }); }, createSimulationData: function () { var categories = []; var data = []; for (var i = 0; i < 10; i++) { categories.push('201620162-' + (i + 1)); data.push(Math.random()*(20-10)+10); } return { categories: categories, data: data } }, onLoad: function (e) { var windowWidth = 320; try { var res = wx.getSystemInfoSync(); windowWidth = res.windowWidth; } catch (e) { console.error('getSystemInfoSync failed!'); } var simulationData = this.createSimulationData(); lineChart = new wxCharts({ canvasId: 'lineCanvas', type: 'line', categories: simulationData.categories, animation: false, series: [{ name: '成交量1', data: simulationData.data, format: function (val, name) { return val.toFixed(2) + '万'; } }], xAxis: { disableGrid: false }, yAxis: { title: '成交金额 (万元)', format: function (val) { return val.toFixed(2); }, min: 0 }, width: windowWidth, height: 200, dataLabel: true, dataPointShape: true, enableScroll: true, extra: { lineStyle: 'curve' } }); } });
'use strict'; // // Scheduled or immediate backup. // var exec = require('child-process-promise').exec; var argv = require('yargs').argv; var quote = require('quote'); var moment = require('moment'); var path = require('path'); var Q = require("q"); var conf = require('confucious'); conf.pushJsonFile("config.json"); conf.pushArgv(); var databases = conf.get("databases") || []; if (databases.length <= 0) { console.log('No databases set in the to backup.'); process.exit(1); } // Validate databases. console.log('Using databases:'); databases.forEach(function(database) { console.log(database.host + ':' + database.port); }, this); var baseOutputDirectory = argv.out || 'dump'; console.log('Base output directory: ' + baseOutputDirectory); // // Backup a single database. // var backupDb = function (database, path) { console.log('Backing up database to: ' + path); var cmd = 'mongodump -h ' + quote(database.host) + ' --port ' + quote(database.port) + ' --out ' + quote(path); if (database.name) { cmd += ' --db ' + quote(database.name); } if (database.username && database.password) { cmd += ' --username ' + quote(database.username) + ' --password ' + quote(database.password); } console.log("> " + cmd); return exec(cmd) .then(function () { console.log('Backed up database' + database.name); }); }; // // Run the database backup. // var doBackup = function () { var year = moment().format('YYYY'); var month = moment().format('MM'); var timeStamp = moment().format('YYYY_MM_DD__HH_m'); var outputDirectory = path.join(baseOutputDirectory, year, month, timeStamp); return databases.reduce(function (promise, database) { return promise.then(function () { return backupDb(database, outputDirectory)}) .catch(function (err) { console.error('Failed to backup database.'); console.error(err.stack); return Q(); }); }, Q()) .then(function () { console.log("Database backup complete."); }) .catch(function (err) { console.log("Error."); console.log(err); }); } if (conf.get("immediate")) { doBackup(); } else { var pollFrequency = argv.poll || '0 0 * * *'; console.log('Scheduled frequency ' + pollFrequency); // Scheduled backup. var CronJob = require('cron').CronJob; new CronJob({ cronTime: pollFrequency, onTick: doBackup, start: true, }); }
/* * Copyright (C) 2014 Daiki Nogami. * All rights reserved. */ 'use strict'; var uploadFile = function(req, res) { var formidable = require('formidable'); var fs = require('fs'); var util = require('../lib/util'); var logger = require('../lib/debugLog'); var form = new formidable.IncomingForm(); form.uploadDir = "./public/voice"; form.encoding = 'utf-8'; // form.encoding = 'binary'; form.parse(req, function (err, fields, files) { if (err) { logger.error('[uploadFile.js] Parse error: ' + err); return res.send(500, 'Something is wrong while parse form.'); } if (files.file.size > 10000000) { logger.warn('[uploadFile.js] Upload file size is too large: ' + files.file.size); return res.send(500, 'File size is too large.'); } var name = fields.name ? fields.name : 'Unknown'; var oldPath = './' + files.file._writeStream.path; var newPath = './' + files.file._writeStream.path + '-' + files.file.name; //Filename becomes RANDOM_CODE + '-' + FILE_NAME fs.rename(oldPath, newPath, function (err) { if (err) { logger.error('[uploadFile.js] Rename error: ' + err); } }); //Save file path to DB var uuid = require('node-uuid'); var DB = require('../api/voice/voice.model'); DB.find({path: newPath}, function (err, item) { if (err) { logger.error('[uploadFile.js] DB find error: ' + err); return res.send(500, err); } if(!item) { logger.warn('[uploadFile.js] DB no item'); return res.send(404); } var newItem = { path: newPath, url: newPath.substr(newPath.indexOf('public') + 'public'.length), name: name, key: uuid.v1() } DB.create(newItem, function (err, item) { if (err) { logger.error('[uploadFile.js] DB create error: ' + err); return res.send(500, err); } var pushNotification = require('../lib/pushNotification'); var data = { type: 'voice', url: item.url, name: item.name } pushNotification.sendMessageAll(data); // Set latest item util.setLatestVoice(item); return res.redirect('/console'); }); }); }); } module.exports = uploadFile;
/* brackets-xunit: jasmine */ /* brackets-xunit: includes=bower_components/lodash/dist/lodash.js,bower_components/bilby.js/bilby.js,bower_components/mithril/mithril.js,js/utilities.js,js/engine.js,js/objects.js,js/controller.js,js/events.js */ //,ui.js /* global describe, it, expect, t, _, bilby */ /*jslint asi: true*/ /*jshint indent:3, curly:false, laxbreak:true */ describe("How the utilities are used in project", function () { //isWholeNumber it('should return true when a whole number is given', function () { expect(t.isWholeNumber(3)).toEqual(true) }) it('should return false when given number which is not a whole number', function () { expect(t.isWholeNumber(3.14)).toEqual(false) }) it('should return false when given an item which is not a number', function () { expect(t.isWholeNumber('3')).toEqual(false) }) //areUnique it('should determine if the values in an object array are unique', function () { var uniqueObject = [{ dogName: 'Lassie', color: 'multi' }] var uniqueObjects = [{ dogName: 'Lassie', color: 'multi' }, { dogName: 'Hassie', color: 'brown' }] var notUniqueObjects = [{ dogName: 'Lassie', color: 'multi' }, { dogName: 'Lassie', color: 'brown' }] expect(t.areUniqueNow('dogName', uniqueObject)).toBe(true) expect(t.areUniqueNow('dogName', uniqueObjects)).toBe(true) expect(t.areUniqueNow('dogName', notUniqueObjects)).not.toBe(true) }) it('should convert arguments to array and flatten array', function () { var test = function () { return t.toFlatArray(arguments) } expect(test(1, [2])).toEqual([1, 2]) }) it('should negate a function.', function () { var isNotString = t.complement(_.isString) expect(isNotString(0)).toBe(true) expect(isNotString('s')).toBe(false) }) describe("The function addRollingArray", function () { var array = [0.5, 0, 0, 0] it('should add rolling values to an array from beginning through the last index', function () { expect(t.addRollingArray(array, 1.5, 4, 1)).toEqual([0.5, 0.5, 1, 1]) }) it('should do partial adding at the beginning and end of the array when start and end are not integers', function () { expect(t.addRollingArray(array, 1.5, 3.5, 1)).toEqual([0.5, 0.5, 1, 0.5]) }) it('should add to previous values when within start and end values and be able to add full value to beginning of an array', function () { var array2 = _.clone(array); array2.push(5); array2[0] = 2 expect(t.addRollingArray(array2, 0, 3.5, 1)).toEqual([3, 1, 1, 0.5, 5]) }) it('should add the difference of the starting and ending points when they are on the same index', function () { expect(t.addRollingArray(array, 0, 0.25, 1)).toEqual([0.75, 0, 0, 0]) }) }) describe("fractionalHours", function () { it('should convert a date to a fractional hour value down to the seconds', function () { expect(t.fractionalHours(new Date(2014, 3, 6, 15, 15, 36))).toEqual(15.26) }) }) describe("sum", function () { it("should add the elements in an array", function () { expect(t.sum([1, 2, 3])).toEqual(6) }) it("should reject elements which are not numbers", function () { expect(t.sum([1, 2, '3', 'a'])).toEqual(6) }) }) describe("The function areUnique", function () { it("should return a function which evaluates an array of objects given a certain key - true when all unique", function () { expect(t.areUnique('myKey')([{ myKey: 1 }, { myKey: 2 }])).toBe(true) }) it("should return a function which evaluates an array of objects given a certain key - false when not unique", function () { expect(t.areUnique('myKey')([{ myKey: 2 }, { myKey: 2 }])).toBe(false) }) }) describe("The function zipObjectT", function () { it("should map an array to a key and value functions and return an object", function () { expect(t.zipObjectT(_.identity, function () { return ', world!' }, ['Hello'])).toEqual({ Hello: ', world!' }) }) }) describe("The function constants", function () { it("should return a function of constant value", function () { var keys = t.constants([['yep', 'yay!'], ['nope']]) expect(keys.yep()).toEqual('yay!') }) }) describe('The function hasAll', function(){ var o = {id:0,key1:'some value'} it('should be true when all specified keys are true', function(){ expect(t.hasAll(['id','key1'])(o)).toBe(true) }) it('should be false when all specified keys are not in object', function(){ expect(t.hasAll(['id','key1','key2'])(o)).toBe(false) }) }) describe('The function isNonEmpty', function(){ it('should return true when it has a value', function(){ expect(t.isSomething('a')).toBe(true) }) it('should return false when it is empty', function(){ expect(t.isSomething('')).toBe(false) }) }) describe('The function isSomeString', function(){ it('should return true when there is a string of length greater than 0', function(){ expect(t.isSomeString('1')).toBe(true) }) it("should return false when there isn't a string of length greater than 0", function(){ expect(t.isSomeString('')).toBe(false) }) }) describe('The function not', function(){ it('should return false when given true', function(){ expect(t.not(true)).toBe(false) }) it('should return true when given false', function(){ expect(t.not(false)).toBe(true) }) }) describe('The function hasDeep', function(){ var o = {otheKey: 'my', state: {in: 'some data'}} it('should return true when layered object has key', function(){ expect(t.hasDeep('in')(o)).toBe(true) }) it('should return false when layered object does not have the key', function(){ expect(t.hasDeep('out')(o)).toBe(false) }) it('should not disturb the original object', function(){ expect(o).toEqual({otheKey: 'my', state: {in: 'some data'}}) }) }) describe('The function invoke', function(){ it('should invoke a method with a single argument', function(){ expect(t.invoke('toLowerCase')('HELLO')).toEqual('hello') expect(t.invoke('toLowerCase')('HELLO')).not.toEqual('Hello') }) }) describe('The function isArrayOf', function(){ var O = b.tagged('O', ['o']) var F = b.tagged('F', ['f']) var aO = [O('hi'), O('bye')] it('should return true when array contains only what predicate describes as true', function(){ expect(t.isArrayOf(b.isInstanceOf(O))(aO)).toBe(true) }) it('should return false when array contains falsy object that predicate describes as false', function(){ expect(t.isArrayOf(b.isInstanceOf(O))(aO.concat(F('doh!')))).toBe(false) }) }) describe('The function isOptionOf', function(){ }) }) //describe('Core mithril extensions', function(){ // describe('The function parseM', function(){ // it('should create a mithril virtual element', function(){ // var el = mm.tag('#id'), // cls = mm.class('color'), // cls2 = mm.class('other-class'), // val = mm.value('laura'), // combined = zipOverObjects([el, cls, cls2, val]) // var m_ = mm.parse(combined) // expect(combined).toEqual({ tag: '#id', class : [ 'color', 'other-class' ], value : 'laura' }) // expect(m_).toEqual({tag:'div', attrs:{id:'id', 'class':' color other-class'}, children:'laura'}) // }) // }) //}) describe("Core constants", function () { it("should return the string 'id'", function () { expect(t.k.id()).toEqual("id") }) it("should return the string 'in'", function () { expect(t.k.in()).toEqual("in") }) it("should return the string 'out'", function () { expect(t.k.out()).toEqual("out") }) it("should return the string 'clockState'", function () { expect(t.k.state()).toEqual("clockState") }) it("should return the string 'day'", function () { expect(t.k.day()).toEqual('day') }) it("should return the string 'jobList'", function () { expect(t.k.jobList()).toEqual('jobList') }) it("should return the string 'clockedState'", function () { expect(t.k.clockedState()).toEqual('clockedState') }) it("should return the string 'name'", function () { expect(t.k.name()).toEqual('name') }) it("should return the string 'clocked'", function () { expect(t.k.comment()).toEqual('comment') }) it("should return the string 'jobActive'", function () { expect(t.k.jobActive()).toEqual('jobActive') }) }) describe('Job Setting object manipulation', function(){ var id = t.JobSetting.newId() var newJobSetting = t.JobSetting.create(id, 'I love my job', true) describe('the method newId', function(){ // can't be unique because it is too fast. Need to have a create multiple ids function. it('should create a ~~unique~~ new id', function(){ expect((id > 0)).toBe(true) }) }) describe('the method create', function(){ it('should create a new instance of Job Setting', function(){ var setting = toObject(newJobSetting) expect(b.isOption(newJobSetting)).toBe(true) expect(setting[t.k.id()]).toBe(id) expect(setting[t.k.name()]).toBe('I love my job') expect(setting[t.k.jobActive()]).toBe(true) }) }) describe('the function update', function(){ it('should be able to update the job name without changing original object', function(){ var newO = toObject(t.JobSetting.update('New Job Name', newJobSetting)) expect(newO).toEqual({id:id, name:'New Job Name', jobActive: true}) expect(toObject(newJobSetting)).not.toEqual(newO) }) it('should be able to update the job active status without changing the original object', function(){ var newO = toObject(t.JobSetting.update(false, newJobSetting)) expect(newO).toEqual({id:id, name:'I love my job', jobActive: false}) expect(toObject(newJobSetting)).not.toEqual(newO) }) }) }) describe('JobSettings object manipulation and creation', function(){ var settings = t.JobSettings.create([]) var s0 = t.JobSetting.create(0, 'My lovely job', true) var s1 = t.JobSetting.create(1, 'My second job', true) var newSettings = settings.update(s0).update(s1).update(b.none) describe('the function update', function(){ it('should add a new job setting to the job setting list, overwriting the old list', function(){ expect(_.isEqual(newSettings, settings)).toBe(false) expect(newSettings.toArray()).toEqual([toObject(s0), toObject(s1)]) expect(settings.toArray()).toEqual([]) }) }) describe('the function get', function(){ it('should select the object with selected id', function(){ expect(toObject(newSettings.get(0))).toEqual(s0.getOrElse(void 0)) expect(toObject(newSettings.get(1))).toEqual(s1.getOrElse(void 0)) }) }) describe('the function get', function(){ it('should select the object with selected name', function(){ expect(toObject(newSettings.get('My lovely job'))).toEqual(s0.getOrElse(void 0)) expect(toObject(newSettings.get('My second job'))).toEqual(s1.getOrElse(void 0)) }) }) describe('the method valid', function(){ var cata = {success: f('x'), failure: f('x')} it('should return cata with success as id wrapped in a singleton', function(){ expect(newSettings.valid(0).cata(cata)).toEqual(b.singleton('id', 0)) }) it('should return cata with success as name wrapped in a singleton', function(){ expect(newSettings.valid('My new job name').cata(cata)).toEqual(b.singleton('name', 'My new job name')) }) it('should return cata with failure as a string in an array', function(){ expect(newSettings.valid(3).cata(cata)).toEqual(['No ID number exists']) }) it('should return cata with failure as a string in an array', function(){ expect(newSettings.valid('My lovely job').cata(cata)).toEqual(['Job name already exists']) }) }) }) describe('Job object manipulation and creation', function(){ var s0 = t.JobSetting.create(0, 'My lovely job', true) var s1 = t.JobSetting.create(1, 'My second job', true) var settings = t.JobSettings.create([toObject(s0), toObject(s1)]) settings_ = settings.update(s0).update(s1) // (id, comment, singleDay, inOut, date) var j0 = t.Job.create(settings, 0, '', bilby.none, t.k.out(), new Date()) var j1 = t.Job.create(settings, 1, 'My Comment', bilby.some(_.range(24).map(function(){return 1})), t.k.in(), new Date()) describe('the function create', function(){ it('should be able to create a valid job', function(){ expect(get(L.id, toObject(j0))).toBe(0) expect(get(L.id, toObject(j1))).toBe(1) expect(t.Job.name(settings, toObject(j0))).toBe('My lovely job') }) }) describe('the function update', function(){ it('should be able to update the comment', function(){ expect(toObject(t.Job.update('New comment.', j0))).toEqual(_.extend({}, toObject(j0), {comment: 'New comment.'})) }) it('should be able to toggle clocked in/out status', function(){ var newDate = new Date(2014, 4, 2, 10) var dateOut = new Date(2014, 4, 2, 10, 30) var j0_ = b.extend(toObject(j0), {clockState: {'in': newDate}}) expect(toObject(t.Job.update(newDate, j0))).toEqual(j0_) // clock in var singleDay_ = _.range(24).map(f('0')); singleDay_[10] = 0.5 var j0$ = _.extend({}, j0_, {clockState: {'out': dateOut}}, {hours: singleDay_}) var j0_in = t.Job.create(settings, 0, '', b.none, t.k.in(), newDate) expect(toObject(t.Job.update(dateOut, j0_in))).toEqual(j0$) }) }) }) describe('Jobs object manipulation and creation', function(){ //This uses the same methods as JobSettings with only slight variation. So I won't repeat the tests. }) // //describe('Object helpers', function(){ // describe('the function isClockedIn', function(){ // var stateIn = {name: 'good', clockState: {'in': new Date()}} // var stateOut = {name: 'good', clockState: {'out': new Date()}} // it('should return true when object is clocked in', function(){ // expect(isClockedIn(stateIn)).toBe(true) // }) // it('should return false when object is clocked out', function(){ // expect(isClockedIn(stateOut)).toBe(false) // }) // }) //})
var later = require("../index"); console.log(JSON.stringify({ "name": "later", "version": later.version, "main": "./later.js" }, null, 2));
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; module.exports = ScopeSyncMessage; var assert = require('assert'); var BaseMessage = require('./base-message'); var SyncFragment = require('../sync-fragment'); var util = require('util'); function ScopeSyncMessage(options) { options = options || {}; BaseMessage.call(this, options); assert(typeof options.scopeIndex === 'number', 'Invalid ScopeSyncMessage scopeIndex'); assert(options.syncFragments instanceof Array, 'Invalid ScopeSyncMessage syncFragments'); this.atomic = !!options.atomic; this.scopeIndex = options.scopeIndex; this.syncFragments = options.syncFragments; } util.inherits(ScopeSyncMessage, BaseMessage); ScopeSyncMessage.type = 'ScopeSync'; /////////////////////////////////////////////////////////////////////////////// // METHODS ScopeSyncMessage.prototype.toJSON = function() { var json = BaseMessage.prototype.toJSON.call(this, ['atomic', 'scopeIndex']); json.fragments = this.syncFragments.map(function(fragment) { return fragment.toJSON(); }); return json; }; ScopeSyncMessage.parse = function(data) { assert(data.fragments instanceof Array, 'Invalid ScopeSyncMessage syncFragments'); data.syncFragments = data.fragments.map(function(fragment) { return new SyncFragment(fragment); }); return new ScopeSyncMessage(data); };
// @koala-prepend "js-polyfill.js" // @koala-prepend "nw.js-base-framework/source/js-base/!.js" // @koala-prepend "nw.js-base-framework/source/js-base/libs/jquery-2.1.3.min.js" // @koala-prepend "nw.js-base-framework/source/js-base/_g-variables.js" // @koala-prepend "nw.js-base-framework/source/js-base/_g.js" // @koala-prepend "nw.js-base-framework/source/js-base/_p.js" // @koala-prepend "nw.js-base-framework/source/js-base/libs/visibility/visibility.core.js" // @koala-prepend "nw.js-base-framework/source/js-base/libs/jquery.mousewheel.js" // @koala-prepend "nw.js-base-framework/source/js-base/prototype/Array.js" // @koala-prepend "nw.js-base-framework/source/js-base/prototype/date.js" // @koala-prepend "nw.js-base-framework/source/js-base/prototype/object.js" // @koala-prepend "nw.js-base-framework/source/js-base/prototype/string.js" // @koala-prepend "nw.js-base-framework/source/js-base/templates/_.js" // @koala-prepend "nw.js-base-framework/source/js-base/hotkey/_.js" // @koala-prepend "nw.js-base-framework/source/js-base/form/_.js" // @koala-prepend "nw.js-base-framework/source/js-base/node-webkit/!global.js" // @koala-prepend "nw.js-base-framework/source/js-base/node-webkit/configuration.js" // @koala-prepend "nw.js-base-framework/source/js-base/node-webkit/menu.js" // @koala-prepend "nw.js-base-framework/source/js-base/node-webkit/window.js" // @koala-prepend "nw.js-base-framework/source/js-base/frame/_global.js" // @koala-prepend "nw.js-base-framework/source/js-base/frame/menu.js" // @koala-prepend "nw.js-base-framework/source/js-base/frame/modal.js" // @koala-prepend "nw.js-base-framework/source/js-base/frame/tip.js" // @koala-prepend "nw.js-base-framework/source/js-base/elements/_a.js" // @koala-prepend "nw.js-base-framework/source/js-base/elements/form.js" // @koala-prepend "nw.js-base-framework/source/js-base/elements/flexgrid.js" // @koala-prepend "nw.js-base-framework/source/js-base/elements/input.js" // @koala-prepend "../_/node_modules/lockr/lockr.min.js" // @koala-prepend "../_/node_modules/lz-string/libs/lz-string.js" // @koala-prepend "../_/node_modules/sprintf-js/src/sprintf.js" // @koala-prepend "../_/node_modules/pepjs/dist/pep.js" // @koala-prepend "../_/node_modules/localforage/dist/localforage.nopromises.min.js" // @koala-prepend "../_/node_modules/kckit/dist/kckit.js" // @koala-prepend "../_/node_modules/clipboard/dist/clipboard.min.js" // @koala-prepend "nw.js-base-framework/source/js-base/!last.js"
/** section: Language * class String * * Extensions to the built-in `String` class. * * Prototype enhances the [[String]] object with a series of useful methods for * ranging from the trivial to the complex. Tired of stripping trailing * whitespace? Try [[String#strip]]. Want to replace `replace`? Have a look at * [[String#sub]] and [[String#gsub]]. Need to parse a query string? We have * [[String#toQueryParams what you need]]. **/ Object.extend(String, { /** * String.interpret(value) -> String * * Coerces `value` into a string. Returns an empty string for `null`. **/ interpret: function(value) { return value == null ? '' : String(value); }, specialChar: { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '\\': '\\\\' } }); Object.extend(String.prototype, (function() { var NATIVE_JSON_PARSE_SUPPORT = window.JSON && typeof JSON.parse === 'function' && JSON.parse('{"test": true}').test; function prepareReplacement(replacement) { if (Object.isFunction(replacement)) return replacement; var template = new Template(replacement); return function(match) { return template.evaluate(match) }; } /** * String#gsub(pattern, replacement) -> String * * Returns the string with _every_ occurence of a given pattern replaced by either a * regular string, the returned value of a function or a [[Template]] string. * The pattern can be a string or a regular expression. * * If its second argument is a string [[String#gsub]] works just like the native JavaScript * method `replace()` set to global match. * * var mouseEvents = 'click dblclick mousedown mouseup mouseover mousemove mouseout'; * * mouseEvents.gsub(' ', ', '); * // -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout' * * mouseEvents.gsub(/\s+/, ', '); * // -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout' * * If you pass it a function, it will be invoked for every occurrence of the pattern * with the match of the current pattern as its unique argument. Note that this argument * is the returned value of the `match()` method called on the current pattern. It is * in the form of an array where the first element is the entire match and every subsequent * one corresponds to a parenthesis group in the regex. * * mouseEvents.gsub(/\w+/, function(match){ return 'on' + match[0].capitalize() }); * // -> 'onClick onDblclick onMousedown onMouseup onMouseover onMousemove onMouseout' * * var markdown = '![a pear](/img/pear.jpg) ![an orange](/img/orange.jpg)'; * * markdown.gsub(/!\[(.*?)\]\((.*?)\)/, function(match) { * return '<img alt="' + match[1] + '" src="' + match[2] + '" />'; * }); * // -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />' * * Lastly, you can pass [[String#gsub]] a [[Template]] string in which you can also access * the returned value of the `match()` method using the ruby inspired notation: `#{0}` * for the first element of the array, `#{1}` for the second one, and so on. * So our last example could be easily re-written as: * * markdown.gsub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />'); * // -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />' * * If you need an equivalent to [[String#gsub]] but without global match set on, try [[String#sub]]. * * ##### Note * * Do _not_ use the `"g"` flag on the regex as this will create an infinite loop. **/ function gsub(pattern, replacement) { var result = '', source = this, match; replacement = prepareReplacement(replacement); if (Object.isString(pattern)) pattern = RegExp.escape(pattern); if (!(pattern.length || pattern.source)) { replacement = replacement(''); return replacement + source.split('').join(replacement) + replacement; } while (source.length > 0) { if (match = source.match(pattern)) { result += source.slice(0, match.index); result += String.interpret(replacement(match)); source = source.slice(match.index + match[0].length); } else { result += source, source = ''; } } return result; } /** * String#sub(pattern, replacement[, count = 1]) -> String * * Returns a string with the _first_ `count` occurrences of `pattern` replaced by either * a regular string, the returned value of a function or a [[Template]] string. * `pattern` can be a string or a regular expression. * * Unlike [[String#gsub]], [[String#sub]] takes a third optional parameter which specifies * the number of occurrences of the pattern which will be replaced. * If not specified, it will default to 1. * * Apart from that, [[String#sub]] works just like [[String#gsub]]. * Please refer to it for a complete explanation. * * ##### Examples * * var fruits = 'apple pear orange'; * * fruits.sub(' ', ', '); * // -> 'apple, pear orange' * * fruits.sub(' ', ', ', 1); * // -> 'apple, pear orange' * * fruits.sub(' ', ', ', 2); * // -> 'apple, pear, orange' * * fruits.sub(/\w+/, function(match){ return match[0].capitalize() + ',' }, 2); * // -> 'Apple, Pear, orange' * * var markdown = '![a pear](/img/pear.jpg) ![an orange](/img/orange.jpg)'; * * markdown.sub(/!\[(.*?)\]\((.*?)\)/, function(match) { * return '<img alt="' + match[1] + '" src="' + match[2] + '" />'; * }); * // -> '<img alt="a pear" src="/img/pear.jpg" /> ![an orange](/img/orange.jpg)' * * markdown.sub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />'); * // -> '<img alt="a pear" src="/img/pear.jpg" /> ![an orange](/img/orange.jpg)' * * ##### Note * * Do _not_ use the `"g"` flag on the regex as this will create an infinite loop. **/ function sub(pattern, replacement, count) { replacement = prepareReplacement(replacement); count = Object.isUndefined(count) ? 1 : count; return this.gsub(pattern, function(match) { if (--count < 0) return match[0]; return replacement(match); }); } /** related to: String#gsub * String#scan(pattern, iterator) -> String * * Allows iterating over every occurrence of the given pattern (which can be a * string or a regular expression). * Returns the original string. * * Internally just calls [[String#gsub]] passing it `pattern` and `iterator` as arguments. * * ##### Examples * * 'apple, pear & orange'.scan(/\w+/, alert); * // -> 'apple pear orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs) * * Can be used to populate an array: * * var fruits = []; * 'apple, pear & orange'.scan(/\w+/, function(match) { fruits.push(match[0]) }); * fruits.inspect() * // -> ['apple', 'pear', 'orange'] * * or even to work on the DOM: * * 'failure-message, success-message & spinner'.scan(/(\w|-)+/, Element.toggle) * // -> 'failure-message, success-message & spinner' (and toggles the visibility of each DOM element) * * ##### Note * * Do _not_ use the `"g"` flag on the regex as this will create an infinite loop. **/ function scan(pattern, iterator) { this.gsub(pattern, iterator); return String(this); } /** * String#truncate([length = 30[, suffix = '...']]) -> String * * Truncates a string to given `length` and appends `suffix` to it (indicating * that it is only an excerpt). * * ##### Examples * * 'A random sentence whose length exceeds 30 characters.'.truncate(); * // -> 'A random sentence whose len...' * * 'Some random text'.truncate(); * // -> 'Some random text.' * * 'Some random text'.truncate(10); * // -> 'Some ra...' * * 'Some random text'.truncate(10, ' [...]'); * // -> 'Some [...]' **/ function truncate(length, truncation) { length = length || 30; truncation = Object.isUndefined(truncation) ? '...' : truncation; return this.length > length ? this.slice(0, length - truncation.length) + truncation : String(this); } /** * String#strip() -> String * * Strips all leading and trailing whitespace from a string. * * ##### Example * * ' hello world! '.strip(); * // -> 'hello world!' **/ function strip() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); } /** * String#stripTags() -> String * * Strips a string of any HTML tags. * * Note that [[String#stripTags]] will only strip HTML 4.01 tags &mdash; like * `div`, `span`, and `abbr`. It _will not_ strip namespace-prefixed tags * such as `h:table` or `xsl:template`. * * Watch out for `<script>` tags in your string, as [[String#stripTags]] will * _not_ remove their content. Use [[String#stripScripts]] to do so. * * ##### Caveat User * * Note that the processing [[String#stripTags]] does is good enough for most * purposes, but you cannot rely on it for security purposes. If you're * processing end-user-supplied content, [[String#stripTags]] is _not_ * sufficiently robust to ensure that the content is completely devoid of * HTML tags in the case of a user intentionally trying to circumvent tag * restrictions. But then, you'll be running them through * [[String#escapeHTML]] anyway, won't you? * * ##### Examples * * 'a <a href="#">link</a>'.stripTags(); * // -> 'a link' * * 'a <a href="#">link</a><script>alert("hello world!");</script>'.stripTags(); * // -> 'a linkalert("hello world!");' * * 'a <a href="#">link</a><script>alert("hello world!");</script>'.stripScripts().stripTags(); * // -> 'a link' **/ function stripTags() { return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); } /** * String#stripScripts() -> String * * Strips a string of things that look like an HTML script blocks. * * ##### Example * * "<p>This is a test.<script>alert("Look, a test!");</script>End of test</p>".stripScripts(); * // => "<p>This is a test.End of test</p>" * * ##### Caveat User * * Note that the processing [[String#stripScripts]] does is good enough for * most purposes, but you cannot rely on it for security purposes. If you're * processing end-user-supplied content, [[String#stripScripts]] is probably * not sufficiently robust to prevent hack attacks. **/ function stripScripts() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); } /** * String#extractScripts() -> Array * * Extracts the content of any `<script>` blocks present in the string and * returns them as an array of strings. * * This method is used internally by [[String#evalScripts]]. It does _not_ * evaluate the scripts (use [[String#evalScripts]] to do that), but can be * usefull if you need to evaluate the scripts at a later date. * * ##### Examples * * 'lorem... <script>2 + 2</script>'.extractScripts(); * // -> ['2 + 2'] * * '<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts(); * // -> ['2 + 2', 'alert("hello world!")'] * * ##### Notes * * To evaluate the scripts later on, you can use the following: * * var myScripts = '<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts(); * // -> ['2 + 2', 'alert("hello world!")'] * * var myReturnedValues = myScripts.map(function(script) { * return eval(script); * }); * // -> [4, undefined] (and displays 'hello world!' in the alert dialog) **/ function extractScripts() { var matchAll = new RegExp(Prototype.ScriptFragment, 'img'), matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return (this.match(matchAll) || []).map(function(scriptTag) { return (scriptTag.match(matchOne) || ['', ''])[1]; }); } /** * String#evalScripts() -> Array * * Evaluates the content of any inline `<script>` block present in the string. * Returns an array containing the value returned by each script. * `<script>` blocks referencing external files will be treated as though * they were empty (the result for that position in the array will be `undefined`); * external files are _not_ loaded and processed by [[String#evalScripts]]. * * ##### Examples * * 'lorem... <script>2 + 2</script>'.evalScripts(); * // -> [4] * * '<script>2 + 2<script><script>alert("hello world!")</script>'.evalScripts(); * // -> [4, undefined] (and displays 'hello world!' in the alert dialog) * * ##### About `evalScripts`, `var`s, and defining functions * * [[String#evalScripts]] evaluates script blocks, but this **does not** mean * they are evaluated in the global scope. They aren't, they're evaluated in * the scope of the [[String#evalScripts]] method. This has important * ramifications for your scripts: * * * Anything in your script declared with the `var` keyword will be * discarded momentarily after evaluation, and will be invisible to any * other scope. * * If any `<script>` blocks _define functions_, they will need to be * assigned to properties of the `window` object. * * For example, this won't work: * * // This kind of script won't work if processed by evalScripts: * function coolFunc() { * // Amazing stuff! * } * * Instead, use the following syntax: * * // This kind of script WILL work if processed by evalScripts: * window.coolFunc = function() { * // Amazing stuff! * } * * (You can leave off the `window.` part of that, but it's bad form.) * Evaluates the content of any `script` block present in the string. Returns * an array containing the value returned by each script. **/ function evalScripts() { return this.extractScripts().map(function(script) { return eval(script.unescapeHTML() ) }); } /** related to: String#unescapeHTML * String#escapeHTML() -> String * * Converts HTML special characters to their entity equivalents. * * ##### Example * * '<div class="article">This is an article</div>'.escapeHTML(); * // -> "&lt;div class="article"&gt;This is an article&lt;/div&gt;" **/ function escapeHTML() { return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); } /** related to: String#escapeHTML * String#unescapeHTML() -> String * * Strips tags and converts the entity forms of special HTML characters * to their normal form. * * ##### Examples * * 'x &gt; 10'.unescapeHTML() * // -> 'x > 10' * * '<h1>Pride &amp; Prejudice</h1>;'.unescapeHTML() * // -> '<h1>Pride & Prejudice</h1>' **/ function unescapeHTML() { // Warning: In 1.7 String#unescapeHTML will no longer call String#stripTags. return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&'); } /** * String#parseQuery([separator = '&']) -> Object **/ /** alias of: String#parseQuery, related to: Hash#toQueryString * String#toQueryParams([separator = '&']) -> Object * * Parses a URI-like query string and returns an object composed of * parameter/value pairs. * * This method is realy targeted at parsing query strings (hence the default * value of`"&"` for the `separator` argument). * * For this reason, it does _not_ consider anything that is either before a * question mark (which signals the beginning of a query string) or beyond * the hash symbol (`"#"`), and runs `decodeURIComponent()` on each * parameter/value pair. * * [[String#toQueryParams]] also aggregates the values of identical keys into * an array of values. * * Note that parameters which do not have a specified value will be set to * `undefined`. * * ##### Examples * * 'section=blog&id=45'.toQueryParams(); * // -> {section: 'blog', id: '45'} * * 'section=blog;id=45'.toQueryParams(); * // -> {section: 'blog', id: '45'} * * 'http://www.example.com?section=blog&id=45#comments'.toQueryParams(); * // -> {section: 'blog', id: '45'} * * 'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams(); * // -> {section: 'blog', tag: ['javascript', 'prototype', 'doc']} * * 'tag=ruby%20on%20rails'.toQueryParams(); * // -> {tag: 'ruby on rails'} * * 'id=45&raw'.toQueryParams(); * // -> {id: '45', raw: undefined} **/ function toQueryParams(separator) { var match = this.strip().match(/([^?#]*)(#.*)?$/); if (!match) return { }; return match[1].split(separator || '&').inject({ }, function(hash, pair) { if ((pair = pair.split('='))[0]) { var key = decodeURIComponent(pair.shift()), value = pair.length > 1 ? pair.join('=') : pair[0]; if (value != undefined) value = decodeURIComponent(value); if (key in hash) { if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; hash[key].push(value); } else hash[key] = value; } return hash; }); } /** * String#toArray() -> Array * * Splits the string character-by-character and returns an array with * the result. * * ##### Examples * * 'a'.toArray(); * // -> ['a'] * * 'hello world!'.toArray(); * // -> ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'] **/ function toArray() { return this.split(''); } /** * String#succ() -> String * * Used internally by ObjectRange. * * Converts the last character of the string to the following character in * the Unicode alphabet. * * ##### Examples * * 'a'.succ(); * // -> 'b' * * 'aaaa'.succ(); * // -> 'aaab' **/ function succ() { return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); } /** * String#times(count) -> String * * Concatenates the string `count` times. * * ##### Example * * "echo ".times(3); * // -> "echo echo echo " **/ function times(count) { return count < 1 ? '' : new Array(count + 1).join(this); } /** * String#camelize() -> String * * Converts a string separated by dashes into a camelCase equivalent. For * instance, `'foo-bar'` would be converted to `'fooBar'`. * * Prototype uses this internally for translating CSS properties into their * DOM `style` property equivalents. * * ##### Examples * * 'background-color'.camelize(); * // -> 'backgroundColor' * * '-moz-binding'.camelize(); * // -> 'MozBinding' **/ function camelize() { return this.replace(/-+(.)?/g, function(match, chr) { return chr ? chr.toUpperCase() : ''; }); } /** * String#capitalize() -> String * * Capitalizes the first letter of a string and downcases all the others. * * ##### Examples * * 'hello'.capitalize(); * // -> 'Hello' * * 'HELLO WORLD!'.capitalize(); * // -> 'Hello world!' **/ function capitalize() { return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); } /** * String#underscore() -> String * * Converts a camelized string into a series of words separated by an * underscore (`_`). * * ##### Example * * 'borderBottomWidth'.underscore(); * // -> 'border_bottom_width' * * ##### Note * * Used in conjunction with [[String#dasherize]], [[String#underscore]] * converts a DOM style into its CSS equivalent. * * 'borderBottomWidth'.underscore().dasherize(); * // -> 'border-bottom-width' **/ function underscore() { return this.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/-/g, '_') .toLowerCase(); } /** * String#dasherize() -> String * * Replaces every instance of the underscore character `"_"` by a dash `"-"`. * * ##### Example * * 'border_bottom_width'.dasherize(); * // -> 'border-bottom-width' * * ##### Note * * Used in conjunction with [[String#underscore]], [[String#dasherize]] * converts a DOM style into its CSS equivalent. * * 'borderBottomWidth'.underscore().dasherize(); * // -> 'border-bottom-width' **/ function dasherize() { return this.replace(/_/g, '-'); } /** related to: Object.inspect * String#inspect([useDoubleQuotes = false]) -> String * * Returns a debug-oriented version of the string (i.e. wrapped in single or * double quotes, with backslashes and quotes escaped). * * For more information on `inspect` methods, see [[Object.inspect]]. * * #### Examples * * 'I\'m so happy.'.inspect(); * // -> '\'I\\\'m so happy.\'' * // (displayed as 'I\'m so happy.' in an alert dialog or the console) * * 'I\'m so happy.'.inspect(true); * // -> '"I'm so happy."' * // (displayed as "I'm so happy." in an alert dialog or the console) **/ function inspect(useDoubleQuotes) { var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { if (character in String.specialChar) { return String.specialChar[character]; } return '\\u00' + character.charCodeAt().toPaddedString(2, 16); }); if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; return "'" + escapedString.replace(/'/g, '\\\'') + "'"; } /** * String#unfilterJSON([filter = Prototype.JSONFilter]) -> String * * Strips comment delimiters around Ajax JSON or JavaScript responses. * This security method is called internally. * * ##### Example * * '/*-secure-\n{"name": "Violet", "occupation": "character", "age": 25}\n*\/'.unfilterJSON() * // -> '{"name": "Violet", "occupation": "character", "age": 25}' **/ function unfilterJSON(filter) { return this.replace(filter || Prototype.JSONFilter, '$1'); } /** * String#isJSON() -> Boolean * * Check if the string is valid JSON by the use of regular expressions. * This security method is called internally. * * ##### Examples * * "something".isJSON(); * // -> false * "\"something\"".isJSON(); * // -> true * "{ foo: 42 }".isJSON(); * // -> false * "{ \"foo\": 42 }".isJSON(); * // -> true **/ function isJSON() { var str = this; if (str.blank()) return false; str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(str); } /** * String#evalJSON([sanitize = false]) -> object * * Evaluates the JSON in the string and returns the resulting object. * * If the optional `sanitize` parameter is set to `true`, the string is * checked for possible malicious attempts; if one is detected, `eval` * is _not called_. * * ##### Warning * * If the JSON string is not well formated or if a malicious attempt is * detected a `SyntaxError` is thrown. * * ##### Examples * * var person = '{ "name": "Violet", "occupation": "character" }'.evalJSON(); * person.name; * //-> "Violet" * * person = 'grabUserPassword()'.evalJSON(true); * //-> SyntaxError: Badly formed JSON string: 'grabUserPassword()' * * person = '/*-secure-\n{"name": "Violet", "occupation": "character"}\n*\/'.evalJSON() * person.name; * //-> "Violet" * * ##### Note * * Always set the `sanitize` parameter to `true` for data coming from * externals sources to prevent XSS attacks. * * As [[String#evalJSON]] internally calls [[String#unfilterJSON]], optional * security comment delimiters (defined in [[Prototype.JSONFilter]]) are * automatically removed. **/ function evalJSON(sanitize) { var json = this.unfilterJSON(), cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; if (cx.test(json)) { json = json.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } try { if (!sanitize || json.isJSON()) return eval('(' + json + ')'); } catch (e) { } throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); } function parseJSON() { var json = this.unfilterJSON(); return JSON.parse(json); } /** * String#include(substring) -> Boolean * * Checks if the string contains `substring`. * * ##### Example * * 'Prototype framework'.include('frame'); * //-> true * 'Prototype framework'.include('frameset'); * //-> false **/ function include(pattern) { return this.indexOf(pattern) > -1; } /** * String#startsWith(substring) -> Boolean * * Checks if the string starts with `substring`. * * ##### Example * * 'Prototype JavaScript'.startsWith('Pro'); * //-> true **/ function startsWith(pattern) { // We use `lastIndexOf` instead of `indexOf` to avoid tying execution // time to string length when string doesn't start with pattern. return this.lastIndexOf(pattern, 0) === 0; } /** * String#endsWith(substring) -> Boolean * * Checks if the string ends with `substring`. * * ##### Example * * 'slaughter'.endsWith('laughter') * // -> true **/ function endsWith(pattern) { var d = this.length - pattern.length; // We use `indexOf` instead of `lastIndexOf` to avoid tying execution // time to string length when string doesn't end with pattern. return d >= 0 && this.indexOf(pattern, d) === d; } /** * String#empty() -> Boolean * * Checks if the string is empty. * * ##### Example * * ''.empty(); * //-> true * * ' '.empty(); * //-> false **/ function empty() { return this == ''; } /** * String#blank() -> Boolean * * Check if the string is "blank" &mdash; either empty (length of `0`) or * containing only whitespace. * * ##### Example * * ''.blank(); * //-> true * * ' '.blank(); * //-> true * * ' a '.blank(); * //-> false **/ function blank() { return /^\s*$/.test(this); } /** * String#interpolate(object[, pattern]) -> String * * Treats the string as a [[Template]] and fills it with `object`'s * properties. **/ function interpolate(object, pattern) { return new Template(this, pattern).evaluate(object); } return { gsub: gsub, sub: sub, scan: scan, truncate: truncate, // Firefox 3.5+ supports String.prototype.trim // (`trim` is ~ 5x faster than `strip` in FF3.5) strip: String.prototype.trim || strip, stripTags: stripTags, stripScripts: stripScripts, extractScripts: extractScripts, evalScripts: evalScripts, escapeHTML: escapeHTML, unescapeHTML: unescapeHTML, toQueryParams: toQueryParams, parseQuery: toQueryParams, toArray: toArray, succ: succ, times: times, camelize: camelize, capitalize: capitalize, underscore: underscore, dasherize: dasherize, inspect: inspect, unfilterJSON: unfilterJSON, isJSON: isJSON, evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, include: include, startsWith: startsWith, endsWith: endsWith, empty: empty, blank: blank, interpolate: interpolate }; })());
/* This file includes the code of TS Diagnostics error that should also be thrown from babel-parser. The TypeScript parser is highly tolerant on errors so these error would not produce parseDiagnostics which can be checked in the parser test runner. We check these error codes against the stderr log in the build/typescript/tests/baselines/reference Note that babel-parser should not throw for the TypeChecking Diagnostics The commented out diagnostic codes will introduce false positive cases that should be addressed in separate PRs. */ export default [ "TS1002", // Unterminated string literal. "TS1003", // Identifier expected. "TS1005", // '{0}' expected. "TS1009", // Trailing comma not allowed. "TS1014", // A rest parameter must be last in a parameter list. "TS1019", // An index signature parameter cannot have a question mark. "TS1028", // Accessibility modifier already seen. "TS1029", // '{0}' modifier must precede '{1}' modifier. "TS1030", // '{0}' modifier already seen. "TS1031", // '{0}' modifier cannot appear on a class element. "TS1034", // 'super' must be followed by an argument list or member access. "TS1039", // Initializers are not allowed in ambient contexts. "TS1042", // '{0}' modifier cannot be used here. "TS1048", // A rest parameter cannot have an initializer. "TS1053", // A 'set' accessor cannot have rest parameter. "TS1054", // A 'get' accessor cannot have parameters. // "TS1071", // '{0}' modifier cannot appear on an index signature. "TS1089", // '{0}' modifier cannot appear on a constructor declaration. "TS1090", // '{0}' modifier cannot appear on a parameter. "TS1100", // Invalid use of 'arguments' in strict mode. "TS1101", // 'with' statements are not allowed in strict mode. "TS1104", // A 'continue' statement can only be used within an enclosing iteration statement. "TS1105", // A 'break' statement can only be used within an enclosing iteration or switch statement. "TS1107", // Jump target cannot cross function boundary. "TS1108", // A 'return' statement can only be used within a function body. "TS1109", // Expression expected. "TS1110", // Type expected. "TS1011", // An element access expression should take an argument. "TS1113", // A 'default' clause cannot appear more than once in a 'switch' statement. "TS1115", // A 'continue' statement can only jump to a label of an enclosing iteration statement. "TS1116", // A 'break' statement can only jump to a label of an enclosing statement. "TS1123", // Variable declaration list cannot be empty. "TS1126", // Unexpected end of text. "TS1127", // Invalid character. "TS1128", // Declaration or statement expected. "TS1135", // Argument expression expected. "TS1136", // Property assignment expected. "TS1141", // String literal expected. "TS1142", // Line break not permitted here. "TS1144", // '{' or ';' expected. "TS1155", // 'const' declarations must be initialized. "TS1160", // Unterminated template literal. "TS1161", // Unterminated regular expression literal. "TS1162", // An object member cannot be declared optional. "TS1163", // A 'yield' expression is only allowed in a generator body. "TS1184", // Modifiers cannot appear here. "TS1185", // Merge conflict marker encountered. "TS1191", // An import declaration cannot have modifiers. "TS1196", // Catch clause variable type annotation must be 'any' or 'unknown' if specified. "TS1197", // Catch clause variable cannot have an initializer. "TS1200", // Line terminator not permitted before arrow. "TS1212", // Identifier expected. '{0}' is a reserved word in strict mode." "TS1213", // Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode. "TS1214", // Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode. "TS1246", // An interface property cannot have an initializer. "TS1247", // A type literal property cannot have an initializer. "TS1248", // A class member cannot have the 'const' keyword. "TS1260", // Keywords cannot contain escape characters. "TS1308", // 'await' expression is only allowed within an async function. "TS1312", // '=' can only be used in an object literal property inside a destructuring assignment. "TS1384", // A 'new' expression with type arguments must always be followed by a parenthesized argument list. "TS1385", // Function type notation must be parenthesized when used in a union type. "TS1386", // Constructor type notation must be parenthesized when used in a union type. "TS1437", // Namespace must be given a name. "TS1194", // Export declarations are not permitted in a namespace. // "TS2300", // Duplicate identifier '{0}'. "TS2337", // Super calls are not permitted outside constructors or in nested functions inside constructors. // "TS2340", // Only public and protected methods of the base class are accessible via the 'super' keyword. "TS2364", // The left-hand side of an assignment expression must be a variable or a property access. // "TS2369", // A parameter property is only allowed in a constructor implementation. // "TS2371", // A parameter initializer is only allowed in a function or constructor implementation. //"TS2393", // Duplicate function implementation. "TS2396", // Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters. // "TS2440", // Import declaration conflicts with local declaration of '{0}'. // "TS2451", // Cannot redeclare block-scoped variable '{0}'. "TS2452", // An enum member cannot have a numeric name. "TS2566", // A rest element cannot have a property name. //"TS2580", "TS2481", // Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{0}'. // "TS2567", // Enum declarations can only merge with namespace or other enum declarations. "TS2659", // 'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher. "TS2660", // 'super' can only be referenced in members of derived classes or object literal expressions. //"TS2693", // 'interface' only refers to a type, but is being used as a value here. "TS2699", // Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'. "TS2754", // 'super' may not use type arguments. "TS2809", // Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. "TS2815", // 'arguments' cannot be referenced in property initializers. "TS8018", // Octal literals are not allowed in enums members initializer. // "TS17012", // '{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'? ];
// @flow import React, { Component } from 'react' import styled from 'styled-components' import { injectIntl, type IntlShape } from 'react-intl' import LoginButton from './LoginButton' import Loading from './Loading' import ErrorNotify from './ErrorNotify' import Input from './Input' import Feild from './Feild' import messages from './messages' type InjectProp = { intl: IntlShape, } export type Props = { username: string, password: string, isLoginFailure: boolean, isLoading: boolean, onClick: (username: string, password: string) => void, } type State = { username: string, password: string, } const Wrap = styled.div` position: relative; max-width: 100%; margin-top: 2rem; margin-left: 3rem; margin-right: 3rem; ` class LoginModal extends Component<Props & InjectProp, State> { state: State = { username: this.props.username, password: this.props.password, } handleChangeName = (event: Event) => { if (event.target instanceof HTMLInputElement) { this.setState({ username: event.target.value }) } } handleChangePassword = (event: Event) => { if (event.target instanceof HTMLInputElement) { this.setState({ password: event.target.value }) } } handleClick = () => { this.props.onClick(this.state.username, this.state.password) } render() { const { isLoginFailure, isLoading, intl } = this.props if (isLoading) { return <Loading /> } const { username, password } = this.state return ( <Wrap> {isLoginFailure && <ErrorNotify />} <Feild> <Input placeholder={intl.formatMessage(messages.username)} type="text" value={username} onChange={this.handleChangeName} /> <Input placeholder={intl.formatMessage(messages.password)} type="password" value={password} onChange={this.handleChangePassword} /> <LoginButton onClick={this.handleClick} /> </Feild> </Wrap> ) } } export default injectIntl(LoginModal)
Template.pool.helpers({ poolOrder: function(fencers) { var poolOrder = [ {"left": 1, "right": 2}, {"left": 3, "right": 4}, {"left": 5, "right": 1}, {"left": 2, "right": 3}, {"left": 5, "right": 4}, {"left": 1, "right": 3}, {"left": 2, "right": 5}, {"left": 4, "right": 1}, {"left": 3, "right": 5}, {"left": 4, "right": 2} ]; var toReturn = []; poolOrder.forEach(function(item) { toReturn.push( { "left": item.left, "right": item.right, "leftName": fencers[item.left - 1].competitor.last_name, "rightName": fencers[item.right - 1].competitor.last_name } ); }); return toReturn; } });
import Button from '../Button'; import React from 'react'; import ReactTestUtils from 'react-dom/test-utils'; import renderer from 'react-test-renderer'; test('render button with correct label', () => { const mockCallback = jest.fn(); const button = renderer.create( <Button onClick={mockCallback} className="btn btn-default btn-xs">Export</Button> ); expect(button).toMatchSnapshot(); }); test('render button with correct label and glyphicon', () => { const mockCallback = jest.fn(); const button = renderer.create( <Button glyph="export" onClick={mockCallback} className="btn btn-default btn-xs">Export</Button> ); expect(button).toMatchSnapshot(); }); test('should call click handler callback when clicked', () => { const mockCallback = jest.fn(); // Must wrap `Button` in a Composite Component in order to find it using ReactTestUtils. class Wrapper extends React.Component { render() { return ( <div> <Button onClick={mockCallback} className="btn btn-default btn-xs">Export</Button> </div> ); } } const button = ReactTestUtils.renderIntoDocument( <Wrapper /> ); const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(button, 'button'); ReactTestUtils.Simulate.click(buttonNode); expect(mockCallback.mock.calls.length).toBe(1); });
/*! * Piwik - Web Analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ function initDashboard(dashboardId, dashboardLayout) { // Standard dashboard if($('#periodString').length) { $('#periodString').after($('#dashboardSettings')); $('#dashboardSettings').css({left:$('#periodString')[0].offsetWidth}); } // Embed dashboard if(!$('#topBars').length) { $('#dashboardSettings').css({left:0}); $('#dashboardSettings').after($('#Dashboard')); $('#Dashboard > ul li a').each(function(){$(this).css({width:this.offestWidth+30, paddingLeft:0, paddingRight:0});}); $('#Dashboard_embeddedIndex_'+dashboardId).addClass('sfHover'); } $('#dashboardSettings').on('click', function(){ $('#dashboardSettings').toggleClass('visible'); if ($('#dashboardWidgetsArea').dashboard('isDefaultDashboard')) { $('#removeDashboardLink').hide(); } else { $('#removeDashboardLink').show(); } // fix position $('#dashboardSettings .widgetpreview-widgetlist').css('paddingTop', $('#dashboardSettings .widgetpreview-categorylist').parent('li').position().top); }); $('body').on('mouseup', function(e) { if(!$(e.target).parents('#dashboardSettings').length && !$(e.target).is('#dashboardSettings')) { $('#dashboardSettings').widgetPreview('reset'); $('#dashboardSettings').removeClass('visible'); } }); widgetsHelper.getAvailableWidgets(); $('#dashboardWidgetsArea').on('dashboardempty', showEmptyDashboardNotification); $('#dashboardWidgetsArea').dashboard({ idDashboard: dashboardId, layout: dashboardLayout }); $('#dashboardSettings').widgetPreview({ isWidgetAvailable: function(widgetUniqueId) { return !$('#dashboardWidgetsArea [widgetId=' + widgetUniqueId + ']').length; }, onSelect: function(widgetUniqueId) { var widget = widgetsHelper.getWidgetObjectFromUniqueId(widgetUniqueId); $('#dashboardWidgetsArea').dashboard('addWidget', widget.uniqueId, 1, widget.parameters, true, false); $('#dashboardSettings').removeClass('visible'); }, resetOnSelect: true }); $('#columnPreview>div').each(function(){ var width = new Array(); $('div', this).each(function(){ width.push(this.className.replace(/width-/, '')); }); $(this).attr('layout', width.join('-')); }); $('#columnPreview>div').on('click', function(){ $('#columnPreview>div').removeClass('choosen'); $(this).addClass('choosen'); }); $('.submenu>li').on('mouseenter', function(event){ if (!$('.widgetpreview-categorylist', event.target).length) { $('#dashboardSettings').widgetPreview('reset'); } }); } function createDashboard() { $('#createDashboardName').attr('value', ''); piwikHelper.modalConfirm('#createDashboardConfirm', {yes: function(){ var dashboardName = $('#createDashboardName').attr('value'); var type = ($('#dashboard_type_empty:checked').length > 0) ? 'empty' : 'default'; piwikHelper.showAjaxLoading(); var ajaxRequest = { type: 'GET', url: 'index.php?module=Dashboard&action=createNewDashboard', dataType: 'json', async: true, error: piwikHelper.ajaxHandleError, success: function(id) { $('#dashboardWidgetsArea').dashboard('loadDashboard', id); }, data: { token_auth: piwik.token_auth, idSite: piwik.idSite, name: encodeURIComponent(dashboardName), type: type } }; $.ajax(ajaxRequest); }}); } function resetDashboard() { piwikHelper.modalConfirm('#resetDashboardConfirm', {yes: function(){ $('#dashboardWidgetsArea').dashboard('resetLayout'); }}); } function renameDashboard() { $('#newDashboardName').attr('value', $('#dashboardWidgetsArea').dashboard('getDashboardName')); piwikHelper.modalConfirm('#renameDashboardConfirm', {yes: function(){ $('#dashboardWidgetsArea').dashboard('setDashboardName', $('#newDashboardName').attr('value')); }}); } function removeDashboard() { $('#removeDashboardConfirm h2 span').html($('#dashboardWidgetsArea').dashboard('getDashboardName')); piwikHelper.modalConfirm('#removeDashboardConfirm', {yes: function(){ $('#dashboardWidgetsArea').dashboard('removeDashboard'); }}); } function showChangeDashboardLayoutDialog() { $('#columnPreview>div').removeClass('choosen'); $('#columnPreview>div[layout='+$('#dashboardWidgetsArea').dashboard('getColumnLayout')+']').addClass('choosen'); piwikHelper.modalConfirm('#changeDashboardLayout', {yes: function(){ $('#dashboardWidgetsArea').dashboard('setColumnLayout', $('#changeDashboardLayout .choosen').attr('layout')); }}); } function showEmptyDashboardNotification() { piwikHelper.modalConfirm('#dashboardEmptyNotification', { resetDashboard: function() { $('#dashboardWidgetsArea').dashboard('resetLayout'); }, addWidget: function(){ $('#dashboardSettings').trigger('click'); } }); } function setAsDefaultWidgets() { piwikHelper.modalConfirm('#setAsDefaultWidgetsConfirm', { yes: function(){ $('#dashboardWidgetsArea').dashboard('saveLayoutAsDefaultWidgetLayout'); } }); }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require underscore //= require backbone //= require_tree ./models //= require_tree ./collections //= require ./views/todo-view //= require ./views/app-view //= require_tree ./routers //= require ./app
var gulp = require('gulp'); var browserSync = require("browser-sync").create(); var nodemon = require('gulp-nodemon'); var browserify = require('browserify'); //Bundles JS var reactify = require('reactify'); //Transforms React JSX to JS var source = require('vinyl-source-stream'); // Use conventional text streams with Gulp var lint = require('gulp-eslint'); var concat = require('gulp-concat'); var minifyCss = require('gulp-minify-css'); var uglify = require('gulp-uglify'); var streamify = require('gulp-streamify'); var rename = require('gulp-rename'); var mocha = require('gulp-mocha'); var jest = require('gulp-jest'); var exec = require('child_process').exec; var config = { port: 8888, devBaseUrl: 'http://localhost', paths: { html: './client/app/*.html', js: './client/**/*.js', css: [ './client/lib/skeleton/css/normalize.css', './client/lib/skeleton/css/skeleton.css', './client/styles/styles.css' ], images: './client/images/*', server: './server/config/*.js', dist: './server/dist', mainJs: './client/app/main.js' } }; gulp.task('mocha', function () { gulp.src('./tests/server/ServerSpec.js', {read: false}) .pipe(mocha({reporter: 'nyan'})) }); var BROWSER_SYNC_RELOAD_DELAY = 50; gulp.task('nodemon', function (cb) { var called = false; return nodemon({ script: './server/server.js', watch: ['./server/server.js'] }) .on('start', function onStart() { // ensure start only got called once if (!called) { cb(); } called = true; }) .on('restart', function onRestart() { // reload connected browsers after a slight delay setTimeout(function reload() { browserSync.reload({ stream: false }); }, BROWSER_SYNC_RELOAD_DELAY); }); }); gulp.task('jest', function (cb) { exec('jest', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('test-api', function () { gulp.src('./tests/server/AshleySpec.js', {read: false}) .pipe(mocha({reporter: 'nyan', timeout: 5000})) }); gulp.task('browser-sync', ['nodemon'], function () { // for more browser-sync config options: http://www.browsersync.io/docs/options/ browserSync.init({ // informs browser-sync to proxy our expressjs app which would run at the following location proxy: 'http://localhost:8080', // informs browser-sync to use the following port for the proxied app // notice that the default port is 3000, which would clash with our expressjs port: 4000, // open the proxied app in chrome browser: ['google-chrome'] }); }); gulp.task('html', function () { gulp.src(config.paths.html) .pipe(gulp.dest(config.paths.dist)) }); gulp.task('js', function () { browserify(config.paths.mainJs) .transform(reactify) .bundle() .on('error', console.error.bind(console)) .pipe(source('main.js')) // .pipe(streamify(uglify())) .pipe(rename('bundle.js')) .pipe(gulp.dest(config.paths.dist + '/scripts')) }); gulp.task('css', function () { gulp.src(config.paths.css) .pipe(concat('bundle.css')) .pipe(minifyCss()) .pipe(gulp.dest(config.paths.dist + '/css')) }); gulp.task('images', function () { gulp.src(config.paths.images) .pipe(gulp.dest(config.paths.dist + '/images')) gulp.src('./client/favicon') .pipe(gulp.dest(config.paths.dist)) }); gulp.task('js-watch', browserSync.reload); gulp.task('lint', function() { return gulp.src([config.paths.js, config.paths.server]) .pipe(lint({config: 'eslint.config.json'})) .pipe(lint.format()); }); gulp.task('bs-reload', function () { browserSync.reload(); }); gulp.task('watch', function () { gulp.watch(config.paths.html, ['html', 'bs-reload']); gulp.watch(config.paths.js, ['js', 'jest', browserSync.reload]); gulp.watch(config.paths.server, ['nodemon']); }); gulp.task('default', ['mocha', 'test-api', 'html', 'js', 'css', 'images', 'jest','browser-sync', 'watch']);
// Perform a request against the simplepushclient server var doRequest = function doPost(type, uri, data, cb) { var xhr = new XMLHttpRequest({mozSystem: true}); xhr.onload = function onLoad(evt) { if (xhr.status === 200 || xhr.status === 0) { cb(null, xhr.response); } else { cb(xhr.status); } }; xhr.open(type, uri, true); xhr.onerror = function onError(e) { console.error('onerror en xhr ' + xhr.status); cb(e); } xhr.send(data); }; window.PushHelper.debug = true; window.PushHelper.listen('messages', function(version, endPoint, callback) { doRequest('GET', 'http://simplepushclient.eu01.aws.af.cm/api/v1/' + version + '?client=' + endPoint, null, function(err, data) { if (err) { alert('Cannot get message with version ' + version); } else { callback(data); } }); }, function(message) { alert(message); } ); window.PushHelper.register(function(channels) { var channel = channels[0]; var data = new FormData(); data.append('client', channel.endPoint); doRequest('POST', 'http://simplepushclient.eu01.aws.af.cm/api/v1/register', data, function(err, res) { if (err) { alert('Error registering'); } else { alert('Register to receive push notifications'); } }); }); window.PushHelper.init();
import React from "react" import { Global } from "@emotion/core" import { css } from "theme-ui" import { Layout, Main, Container } from "theme-ui" export default props => ( <> <Global styles={css({ "*": { boxSizing: `border-box`, }, body: { margin: 0, fontFamily: `body`, }, })} /> <Layout> <Main> <Container>{props.children}</Container> </Main> </Layout> </> )
import React from 'react'; import { Link } from 'react-router'; const App = () => ( <div> <h1>Hello App</h1> <Link to="/snap">SNAP!</Link> </div> ); export default App;
var total_records = 0; var url; var total_groups; var id; var loading = false; function initScroll(total_groups, url, id) { this.total_groups = total_groups; this.url = url; this.id = id; loading = true; $('#loader_image_div').show(); $.post(url + id,{'group_number': total_records}, function(data){ if (data != "") { $(data).each(function(index, element) { if($(element).data('id') == 2) { $("#main_characters_div div table tbody").append(element); } else { $("#secondary_characters_div div table tbody").append(element); } }); total_records++; } loading = false; $('#loader_image_div').hide(); }); $(window).scroll(function() { if(total_records >= total_groups) { $(window).off('scroll'); } if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) { if(total_records < total_groups) { loading = true; $('#loader_image_div').show(); $.post(url + id,{'group_number': total_records}, function(data){ if (data != "") { $(data).each(function(index, element) { if($(element).data('id') == 2) { $("#main_characters_div div table tbody").append(element); } else { $("#secondary_characters_div div table tbody").append(element); } }); total_records++; } loading = false; $('#loader_image_div').hide(); }); } } }); }
import React from 'react'; import { LinkHijacker } from '@r/platform/components'; // A pass-through for node-platform's `LinkHijacker` // that has the a regexp for catching all links that look like reddit links. export default function(props) { const { onLinkClick, children } = props; return ( <LinkHijacker onLinkClick={ onLinkClick } urlRegexp={ /^https?:\/\/(?:.+\.)?reddit\.com(.*)$/ } > { children } </LinkHijacker> ); }
/** * Is Provided object an RegExp? * * @param {*} object * @returns {boolean} */ export default function isRegExp(object) { return object instanceof RegExp; }
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: [true], accept: [ { code: ":fullscreen a {}", }, { code: ":root { --custom-property: {} }", }, { code: "input::placeholder { color: pink; }", }, { code: "a::before {}", description: "handles pseudo-element", }, { code: "a:hover {}", description: "handles pseudo-class", }, { code: "a[data-foo=\":-webkit-full-screen\"] {}", description: "string", } ], reject: [ { code: ":-webkit-full-screen a {}", message: messages.rejected(":-webkit-full-screen"), line: 1, column: 1, }, { code: ":-wEbKiT-fUlL-sCrEeN a {}", message: messages.rejected(":-wEbKiT-fUlL-sCrEeN"), line: 1, column: 1, }, { code: ":-WEBKIT-FULL-SCREEN a {}", message: messages.rejected(":-WEBKIT-FULL-SCREEN"), line: 1, column: 1, }, { code: "body, :-ms-fullscreen a {}", message: messages.rejected(":-ms-fullscreen"), line: 1, column: 7, }, { code: "input:-moz-placeholder, input::placeholder { color: pink; }", message: messages.rejected(":-moz-placeholder"), line: 1, column: 6, }, { code: "input::-moz-placeholder { color: pink; }", message: messages.rejected("::-moz-placeholder"), line: 1, column: 6, }, { code: "input::-webkit-input-placeholder { color: pink; }", message: messages.rejected("::-webkit-input-placeholder"), } ], })
'use strict'; const test = require('tape'); const express = require('express'); const rested = require('../lib'); class MyResource { constructor(id, info) { this.id = id; this.info = JSON.parse(JSON.stringify(info)); } createId() { this.id = 'foo'; return this.id; } } test('Core APIs', function (t) { t.test('Collection instances', function (t) { const col = rested.createCollection(MyResource); t.strictEqual(rested.getCollection('myresource'), col); rested.delCollection('myresource'); t.end(); }); t.test('Rest instance', function (t) { t.throws(function () { rested.route(); }, 'Argument to rested.route() must be a router'); const router = new express.Router(); const route = rested.route(router); const col = rested.createCollection(MyResource, { persist(ids, cb) { cb(); } }); route(col, { rights: true }); route(col, 'myresource', { rights: true }); route(col, '/myresource', { rights: true }); t.end(); }); t.test('Collection edge behaviors', function (t) { t.throws(function () { rested.createCollection('Not a class'); }, 'Resource class must be a function'); const col = rested.createCollection(MyResource); t.throws(function () { col.persist('not a function'); }, 'Persist must be a function'); col.del('FooBar', function (error) { t.ifError(error, 'Deleting non-existing is not an error'); }); col.delAll(function () { t.end(); }); col.persist(function () { t.fail('Persist should not be called'); }); }); t.test('Collection undos', function (t) { const col = rested.createCollection(MyResource); col.persist(function () { throw new Error('Save failure'); }); const id = 'abc'; const resource = new MyResource(id, { a: 'a' }); col.set(id, resource, function (error) { t.ok(error, 'Failed set (create)'); t.equal(col.has(id), false, 'Failed set (create) was undone'); col.loadOne(id, resource); col.set(id, { b: 'b' }, function (error) { t.ok(error, 'Failed set (update)'); t.deepEqual(col.get(id), resource, 'Failed set (update) was undone'); t.end(); }); }); }); t.test('Collection JSON', function (t) { const col = rested.createCollection(MyResource); col.set('abc', new MyResource('abc', {})); t.equal(JSON.stringify(col), '{"abc":{"id":"abc","info":{}}}', 'JSON.stringify(collection) produces valid JSON'); col.loadMap({ def: new MyResource('def', {}), ghi: {} }); t.end(); }); });
var Utils = { path: function(bucket, key) { return bucket + '/' + (key ? key : ''); }, toQuery: function(query, riak) { // use boolean strings since riak expects those for (var k in query) { if (typeof query[k] == 'boolean') { query[k] = String(query[k]); } } return riak.stringifyQuery(query); }, toJSON: function(data) { return JSON.stringify(data, function(key, val) { if (typeof val == 'function') { return val.toString(); } return val; }); }, ensure: function(obj) { return obj || {}; }, isArray: function(o) { return o && !(o.propertyIsEnumerable('length')) && typeof o === 'object' && typeof o.length === 'number'; }, // it always returns an array of phases, even an array of 1 phase makePhases: function(type, phase, args) { if (!Utils.isArray(phase)) { phase = [phase] } return phase.map(function(p) { var temp = {}; switch (typeof p) { case 'function': temp[type] = {source: p.toString(), arg: args}; break; case 'string': temp[type] = {name: p, arg: args}; break; case 'object': temp[type] = p; break; default: } return temp }) }, stringToLinks: function(links) { var result = []; if (links) { links.split(',').forEach(function(link) { var r = link.trim().match(/^<\/(.*)\/(.*)\/(.*)>;\sriaktag="(.*)"$/) if (r) { result.push({bucket: decodeURIComponent(r[2]), key: decodeURIComponent(r[3]), tag: decodeURIComponent(r[4])}) } }) } return result; }, // From jQuery.extend in the jQuery JavaScript Library v1.3.2 // Copyright (c) 2009 John Resig // Dual licensed under the MIT and GPL licenses. // http://docs.jquery.com/License // Modified for node.js (formely for copying properties correctly) mixin: function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, source; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !(typeof target === 'function') ) target = {}; for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (source = arguments[i]) != null ) { // Extend the base object Object.getOwnPropertyNames(source).forEach(function(k){ var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]}; if (d.get) { target.__defineGetter__(k, d.get); if (d.set) { target.__defineSetter__(k, d.set); } } else { // Prevent never-ending loop if (target !== d.value) { if (deep && d.value && typeof d.value === "object") { target[k] = exports.mixin(deep, // Never move original objects, clone them target[k] || (d.value.length != null ? [] : {}) , d.value); } else { target[k] = d.value; } } } }); } } // Return the modified object return target; } } // exports module.exports = Utils
import firebase from 'firebase'; try { var config = { apiKey: "AIzaSyDbDlzyK4-lW-tAmL7XMK4CpgsX2JsAOs4", authDomain: "cristian-todo-app.firebaseapp.com", databaseURL: "https://cristian-todo-app.firebaseio.com", projectId: "cristian-todo-app", storageBucket: "cristian-todo-app.appspot.com", messagingSenderId: "538666993345" }; firebase.initializeApp(config); } catch (e) { }; export var firebaseRef = firebase.database().ref(); export default firebase;
/*! lilmvc - v0.0.7 - 2013-02-12 * Copyright (c) 2013 August Hovland <gushov@gmail.com>; Licensed MIT */ (function (ctx) { "use strict"; var defined = {}; var exported = {}; function resolve(from, name) { if (name.indexOf('.') === -1) { return name; } name = name.split('/'); from = from ? from.split('/') : []; from.pop(); if (name[0] === '.') { name.shift(); } while(name[0] === '..') { name.shift(); from.pop(); } return from.concat(name).join('/'); } //@TODO handle provide/require/define already in scope ctx.provide = function (name, module, isDefinition) { if (isDefinition) { return defined[name] = module; } else { return exported[name] = module; } }; ctx.require = function (path, canonical) { var exports, module; var name = canonical || path; if (exported[name]) { return exported[name]; } else { exports = exported[name] = {}; module = { exports: exports }; defined[name](function (path) { return ctx.require(path, resolve(name, path)); }, module, exports); return (exported[name] = module.exports); } }; }(this)); provide('lil_', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ module.exports = { typeOf: function (x) { var type = typeof x; if (type === 'object') { type = Array.isArray(x) ? 'array' : type; type = x === null ? 'null' : type; } return type; }, each: function (thing, func, ctx) { var type = this.typeOf(thing); var keys; if (type === 'array' && thing.length) { thing.forEach(func, ctx); } else if (type === 'object') { keys = thing ? Object.keys(thing) : []; keys.forEach(function (name, i) { func.call(ctx, name, thing[name], i); }); } }, every: function (thing, func, ctx) { var type = this.typeOf(thing); var keys; if (type === 'array' && thing.length) { return thing.every(func, ctx); } else if (type === 'object') { keys = thing ? Object.keys(thing) : []; return keys.every(function (name, i) { return func.call(ctx, name, thing[name], i); }); } return false; }, some: function (thing, func, ctx) { var type = this.typeOf(thing); var keys; if (type === 'array' && thing.length) { return thing.some(func, ctx); } else if (type === 'object') { keys = thing ? Object.keys(thing) : []; return keys.some(function (name, i) { return func.call(ctx, name, thing[name], i); }); } return false; }, map: function (thing, func, ctx) { var type = this.typeOf(thing); var result = []; if (type === 'array' && thing.length) { return thing.map(func, ctx); } else if (type === 'object') { result = {}; this.each(thing, function (name, obj, i) { result[name] = func.call(this, name, obj, i); }, ctx); } return result; }, withOut: function (arr, value) { var result = []; this.each(arr, function (element) { if (element !== value) { result.push(element); } }); return result; }, walk: function (target, source, func, fill) { var self = this; var walkObj = function (target, source) { self.each(source, function (name, obj) { step(target[name], obj, name, target); }); }; var step = function (target, source, name, parent) { var type = self.typeOf(source); if (type === 'object') { if (!target && parent && fill) { target = parent[name] = {}; } walkObj(target, source); } else { func.call(parent, target, source, name); } }; step(target, source); }, extend: function () { var args = Array.prototype.slice.call(arguments); var target = args.shift(); this.each(args, function (src) { this.each(src, function (name, value) { target[name] = value; }); }, this); return target; }, defaults: function (target, defaults) { this.each(defaults, function (name, value) { var type = this.typeOf(target[name]); if (type === 'undefined' || type === 'null') { target[name] = value; } }, this); return target; }, match: function (obj, test) { var isMatch = true; this.walk(obj, test, function (target, src) { isMatch = (target === src); }); return isMatch; }, pick: function(obj, keys) { var picked = {}; keys = this.typeOf(keys) === 'array' ? keys : Object.keys(keys); this.each(keys, function (key) { picked[key] = obj && obj[key]; }); return picked; } }; }, true); provide('lilobj/arr', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true, proto:true */ var _ = require('lil_'); function Arr() { var arr = []; arr.push.apply(arr, arguments); arr.__proto__ = Arr.prototype; return arr; } Arr.prototype = []; Arr.prototype.isA = function (prototype) { function D() {} D.prototype = prototype; return this instanceof D; }; Arr.prototype.extend = function (props) { Arr.prototype = this; var child = new Arr(); _.each(props, function (name) { child[name] = props[name]; }); return child; }; Arr.prototype.create = function () { Arr.prototype = this; var child = new Arr(); if (child.construct !== undefined) { child.construct.apply(child, arguments); } return child; }; module.exports = new Arr(); }, true); provide('lilobj/obj', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var _ = require('lil_'); module.exports = { isA: function (prototype) { function D() {} D.prototype = prototype; return this instanceof D; }, extend: function (props) { var result = Object.create(this); _.each(props, function (name, value) { result[name] = value; }); return result; }, create: function () { var object = Object.create(this); if (object.construct !== undefined) { object.construct.apply(object, arguments); } return object; } }; }, true); provide('lilobj', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var obj = require('./lilobj/obj'); var arr = require('./lilobj/arr'); module.exports = { obj: obj, arr: arr }; }, true); provide('vladiator', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var _ = require('lil_'); var validator = { required: function (value) { return typeof value !== 'undefined' && value !== null; }, array: function (value) { return Array.isArray(value); }, number: function (value) { return typeof value === 'number'; }, string: function (value) { return typeof value === 'string'; }, boolean: function (value) { return typeof value === 'boolean'; }, object: function (value) { return typeof value === 'object'; }, length: function (value, min, max) { var isBigEnough = !min || value.length >= min; var isSmallEnough = !max || value.length <= max; return isBigEnough && isSmallEnough; }, gte: function (value, min) { return value >= min; } }; var validate = function (rules, value) { var result = { isValid: true }; if (rules[0] === 'required' || validator.required(value)) { _.every(rules, function(signature) { var method, args = []; if (typeof signature !== 'string') { method = signature[0]; args = signature.slice(1); } else { method = signature; } args.unshift(value); if (!validator[method].apply(null, args)) { result.isValid = false; result.error = method; return false; } return true; }); } result.$ = value; return result; }; module.exports = validate; }, true); provide('lilmodel/collection', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var arr = require('lilobj').arr; var _ = require('lil_'); var syncr = require('./syncr'); function parser(ctx, model, next) { return function (err, values) { var instance = !err && model.create(values); next.call(ctx, err, instance); }; } module.exports = arr.extend({ construct: function (values) { _.each(values, function (value) { this.push(this.model.create(value)); }, this); this.validate(); }, validate: function () { var validation = { isValid: true, error: [] }; _.each(this, function (model) { var v = model.validate(); validation.error.push(v.error); validation.isValid = validation.isValid && v.isValid; }); return validation; }, add: function (obj) { var model; if (obj.isA && obj.isA(this.model)) { model = obj; } else { model = this.model.create(obj); } this.push(model); }, remove: function (query) { var index; _.each(this, function (model, i) { if (_.match(model, query)) { index = i; } }); if (typeof index === 'number') { this.splice(index, 1); } }, get: function (query) { return this.filter(function (model) { return _.match(model, query); }); }, find: function (query, next, ctx) { var sync = syncr(); this.query = query; sync('find', this, parser(ctx, this, next)); }, serialize: function () { return _.map(this, function (elem) { return elem.serialize(); }); } }); }, true); provide('lilmodel/model', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var obj = require('lilobj').obj; var _ = require('lil_'); var vlad = require('vladiator'); var syncr = require('./syncr'); function getter(name) { return this.$[name]; } function setter(name, value) { var model = this.children && this.children[name]; if (model && model.create && typeof value === 'object') { this.$[name] = model.create(value); } else if (model && typeof value === 'object') { this.$[name] = this.create(value); } else if (!model) { this.$[name] = value; } } function parser(ctx, model, next) { return function (err, values) { var instance = !err ? model.create(values) : null; next.call(ctx, err, instance); }; } module.exports = obj.extend({ construct: function (values) { this.$ = {}; var props = _.map(this.rules, function (name, value) { return { enumerable: true, get: getter.bind(this, name), set: setter.bind(this, name) }; }, this); Object.defineProperties(this, props); values = _.pick(values, this.rules); _.defaults(values, this.defaults); _.each(values, function (name, value) { this[name] = value; }, this); this.validate(); }, validate: function () { var validation = { isValid: true, error: {} }; _.each(this.rules, function (prop, rules) { var value = this[prop]; var v; if (value && value.validate) { v = value.validate(); } else { v = vlad(rules, value); value = v.$; } validation.error[prop] = v.error; validation.isValid = validation.isValid && v.isValid; }, this); return validation; }, save: function (next, ctx) { var sync = syncr(); var method = this.$._id ? 'update' : 'create'; var validation = this.validate(); if (validation.isValid) { sync(method, this, parser(ctx, this, next)); } else { next.call(ctx, validation.error, this); } }, fetch: function (next, ctx) { var sync = syncr(); sync('fetch', this, parser(ctx, this, next)); }, destroy: function (next, ctx) { var sync = syncr(); sync('destroy', this, parser(ctx, this, next)); }, serialize: function () { return _.map(this.$, function (name, value) { if (this.children && this.children[name]) { return value.serialize(); } else { return value; } }, this); } }); }, true); provide('lilmodel/syncr', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var sync = function (method, obj, next) { next(null, obj); }; module.exports = function (handler) { if (handler) { sync = handler; } return sync; }; }, true); provide('lilmodel', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var syncr = require('./lilmodel/syncr'); var model = require('./lilmodel/model'); var collection = require('./lilmodel/collection'); module.exports = { syncr: syncr, model: model, collection: collection }; }, true); provide('lilrouter/win', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var win = typeof window === 'object' && window; module.exports = function (winObj) { if (winObj) { win = winObj; } return { go: function (state, url) { win.history.pushState(state, '', url); }, location: function (loc) { if (loc) { win.location = loc; } return win.location.pathname; }, onpopstate: function (func, ctx) { //bind after initial page load to ignore firefox       setTimeout(function () { win.onpopstate = func.bind(ctx); }, 0); } }; }; }, true); provide('lilrouter/matcher', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var _ = require('lil_'); module.exports = function (patterns, route) { var params, handler; if (route === '/') { return { handler: patterns['/'], params: {} }; } _.some(patterns, function (pattern, func) { var routeTokens = _.withOut(route.split('/'), ''); var patternTokens = _.withOut(pattern.split('/'), ''); params = {}; handler = func; if (pattern.charAt(0) !== '/') { routeTokens.reverse(); patternTokens.reverse(); routeTokens = routeTokens.slice(0, patternTokens.length); } else { routeTokens.length = patternTokens.length; } return _.every(patternTokens, function (token, i) { var isParam = token.indexOf(':') === 0; var isOptional = token.charAt(token.length - 1) === '?'; var tokenName; if (isParam && (isOptional || routeTokens[i])) { tokenName = isOptional ? token.substr(1, token.length - 2) : token.substr(1); params[tokenName] = routeTokens[i]; return true; } else if (token === routeTokens[i]) { return true; } else { return false; } }); }); return { handler: handler, params: params }; }; }, true); provide('lilrouter/router', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var _ = require('lil_'); var obj = require('lilobj').obj; var matcher = require('./matcher'); var win = require('./win'); module.exports = obj.extend({ win: undefined, start: undefined, routes: { get: {}, post: {} }, construct: function (config) { this.win = win(); this.start = this.win.location(); _.each(this.routes, function (method) { _.each(config[method], function (name, init) { this.routes[method][name] = init; }, this); }, this); this.ctx = config.init(this); this.win.onpopstate(function (ev) { if (ev.state) { this.route(ev.state.method, this.win.location(), ev.state.body); } else { this.route('get', this.start); } }, this); this.route('get', this.start, null, true); }, route: function (method, path, body, pageload) { var match = matcher(this.routes[method], path); var ctx = _.extend({}, this.ctx, { params: match.params, body: body || {}, pageload: !!pageload }); match.handler(ctx, this); }, get: function (path) { this.win.go({ method: 'get' }, path); this.route('get', path); }, post: function (path, body) { this.win.go({ method: 'post', body: body }, path); this.route('post', path, body); } }); }, true); provide('lilrouter', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var router = require('./lilrouter/router'); module.exports = router; }, true); provide('lilmvc/view', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var obj = require('lilobj').obj; var template = require('./template'); var dom = require('./dom'); module.exports = obj.extend({ construct: function (bus, selector) { this.$ = dom(); this.el = this.$(selector); this.init(bus); }, template: function (id, viewObj) { var engine = template(); return engine(id, viewObj); }, init: function (bus) {} }); }, true); provide('lilmvc/controller', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var obj = require('lilobj').obj; var _ = require('lil_'); var Bus = require('./bus'); module.exports = obj.extend({ events: [], views: {}, construct: function (views, router) { this.bus = Bus.create(this.events); this.router = router; _.each(views, function (selector, view) { this.views[selector] = view.create(this.bus, selector); }, this); this.init(this.bus); }, init: function (bus) {} }); }, true); provide('lilmvc/bus', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var obj = require('lilobj').obj; var _ = require('lil_'); module.exports = obj.extend({ construct: function (events) { this.listeners = {}; var ev = this.ev = {}; _.each(events, function (event) { ev[event] = event; }); }, on: function (event, method) { if (this.listeners[event]) { this.listeners[event].push(method); } else { this.listeners[event] = [method]; } }, emit: function (event, payload) { _.each(this.listeners[event], function (method) { method(payload); }); } }); }, true); provide('lilmvc/template', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var template = function (id, viewObj) { return viewObj; }; module.exports = function (handler) { if (handler) { template = handler; } return template; }; }, true); provide('lilmvc/dom', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var $ = function (stuff) { return this; }; module.exports = function (handler) { if (handler) { $ = handler; } return $; }; }, true); provide('lilmvc', function (require, module, exports) { /*jshint curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, undef:true, boss:true, strict:false, eqnull:true, browser:true, node:true */ var dom = require('./lilmvc/dom'); var template = require('./lilmvc/template'); var bus = require('./lilmvc/bus'); var controller = require('./lilmvc/controller'); var view = require('./lilmvc/view'); var lilmodel = require('lilmodel'); var lilrouter = require('lilrouter'); module.exports = { template: template, dom: dom, bus: bus, controller: controller, view: view, syncr: lilmodel.syncr, model: lilmodel.model, collection: lilmodel.collection, router: lilrouter }; }, true);
//Problem: Hints are shown even when form is valid //Solution: Hide and show them at appropriate times var $password = $("#password"); var $confirmPassword = $("#confirm_password"); //Hide hints $("form span").hide(); function isPasswordValid() { return $password.val().length > 8; } function arePasswordsMatching() { return $password.val() === $confirmPassword.val(); } function canSubmit() { return isPasswordValid() && arePasswordsMatching(); } function passwordEvent(){ //Find out if password is valid if(isPasswordValid()) { //Hide hint if valid $password.next().hide(); } else { //else show hint $password.next().show(); } } function confirmPasswordEvent() { //find out if password and confirmation match if(arePasswordsMatching()) { //Hide hint if match $confirmPassword.next().hide(); } else { //else show hint $confirmPassword.next().show(); } } function enableSubmitEvent() { $("#submit").prop("disabled", !canSubmit()); } //When event happens on password input $password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent); //When event happens on confirmation input $confirmPassword.focus(confirmPasswordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent); enableSubmitEvent();
"use strict"; exports.__esModule = true; var token_1 = require("./token"); var utils = require("./utils"); var AbstractScanner = (function () { function AbstractScanner(source, config) { this.source = source; this.marker = { index: 0, line: 1, column: 1 }; this.length = this.source.length; if (config) { if (config.start !== undefined) { this.marker.index = config.start; } if (config.line !== undefined) { this.marker.line = config.line; } if (config.column !== undefined) { this.marker.column = config.column; } if (config.end !== undefined) { this.length = config.end - this.marker.index; } } if (this.length === 0) { this.marker.line = 0; this.marker.column = 0; } this.scanStartingMarker = null; this.scanEndingMarker = null; } AbstractScanner.prototype.saveState = function () { return { index: this.marker.index, line: this.marker.line, column: this.marker.column }; }; AbstractScanner.prototype.restoreState = function (state) { this.marker = state; }; AbstractScanner.prototype.startScan = function () { this.scanStartingMarker = this.saveState(); }; AbstractScanner.prototype.endScan = function () { this.scanEndingMarker = this.saveState(); }; AbstractScanner.prototype.clear = function () { this.scanStartingMarker = null; this.scanEndingMarker = null; }; AbstractScanner.prototype.getScanLength = function () { if (this.scanStartingMarker !== null) { return this.marker.index - this.scanStartingMarker.index; } throw new Error('The scan has not been started. '); }; AbstractScanner.prototype.getScanResult = function () { if (this.scanStartingMarker !== null) { return this.source.substring(this.scanStartingMarker.index, this.marker.index); } throw new Error('The scan has not been started. '); }; AbstractScanner.prototype.constructToken = function (type) { if (this.scanStartingMarker !== null && this.scanEndingMarker !== null) { var token = new token_1.Token(type, this.source.substring(this.scanStartingMarker.index, this.scanEndingMarker.index), this.scanStartingMarker, this.scanEndingMarker); this.clear(); return token; } throw new Error('The function `startScan` or `endScan` might not have been called. '); }; AbstractScanner.prototype.constructIllegalToken = function (message) { if (message === void 0) { message = 'Illegal token. '; } var token = this.constructToken('ILLEGAL'); token.message = message; return token; }; AbstractScanner.prototype.eof = function () { return this.marker.index >= this.length; }; AbstractScanner.prototype.peek = function (length) { if (length === void 0) { length = 1; } return this.source.substr(this.marker.index, length); }; AbstractScanner.prototype.move = function (offset) { if (offset === void 0) { offset = 1; } this.marker.index += offset; this.marker.column += offset; }; // note: here is charCode but not codePoint AbstractScanner.prototype.moveWhen = function (judge) { while (!this.eof()) { var ch = this.peek(); var cc = ch.charCodeAt(0); if (!judge(cc, ch)) { break; } this.move(ch.length); } }; /* tslint:disable:no-bitwise */ AbstractScanner.prototype.fromCodePoint = function (cp) { return (cp < 0x10000) ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); }; AbstractScanner.prototype.fromCharCode = function (cc) { return String.fromCharCode(cc); }; AbstractScanner.prototype.getCodePoint = function (offset) { if (offset === void 0) { offset = 0; } var index = this.marker.index + offset; var first = this.source.charCodeAt(index); var cp = first; if (first >= 0xD800 && first <= 0xDBFF) { var second = this.source.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return cp; }; AbstractScanner.prototype.getCharCode = function (offset) { if (offset === void 0) { offset = 0; } return this.source.charCodeAt(this.marker.index + offset); }; AbstractScanner.prototype.scanLineTerminator = function () { var str = ''; var cc = this.getCharCode(); if (utils.isLineTerminator(cc)) { if (cc === 0x0D && this.getCharCode(1) === 0x0A) { str = '\r\n'; this.move(2); } else { str = this.fromCharCode(cc); this.move(); } this.marker.line++; this.marker.column = 1; } return str; }; AbstractScanner.prototype.scanBlankSpace = function () { var str = ''; var cc = this.getCharCode(); while (utils.isWhiteSpace(cc)) { str += this.fromCharCode(cc); this.move(); if (this.eof()) { break; } cc = this.getCharCode(); } return str; }; AbstractScanner.prototype.skipSpace = function () { while (!this.eof() && (this.scanBlankSpace().length > 0 || this.scanLineTerminator().length > 0)) ; }; return AbstractScanner; }()); exports.AbstractScanner = AbstractScanner;
'use strict' import { ContactPage } from './contactPage' module.exports = { ContactPage, }
const GatsbyThemeAdvanced = jest.requireActual("gatsby-theme-advanced"); jest.mock("gatsby-theme-advanced/src/config/useConfig", () => { const configFixture = jest.requireActual("../test/fixtures/config").default; return jest.fn().mockReturnValue(configFixture); }); module.exports = { ...GatsbyThemeAdvanced, };