code
stringlengths
2
1.05M
angular.module('app') .filter('date', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'll') : '<date>'; }; }) .filter('datetime', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'D MMM YYYY, HH:mm:ss') : '<datetime>'; }; }) .filter('time', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'LT') : '<time>'; }; }) .filter('humanTime', function(){ 'use strict'; return function(timestamp){ return timestamp ? moment(timestamp).fromNow(true) : '<humanTime>'; }; }) .filter('duration', function(){ 'use strict'; return function(seconds, humanize){ if(seconds || seconds === 0){ if(humanize){ return moment.duration(seconds, 'seconds').humanize(); } else { var prefix = -60 < seconds && seconds < 60 ? '00:' : ''; return prefix + moment.duration(seconds, 'seconds').format('hh:mm:ss'); } } else { console.warn('Unable to format duration', seconds); return '<duration>'; } }; }) .filter('mynumber', function($filter){ 'use strict'; return function(number, round){ var mul = Math.pow(10, round ? round : 0); return $filter('number')(Math.round(number*mul)/mul); }; }) .filter('rating', function($filter){ 'use strict'; return function(rating, max, withText){ var stars = rating ? new Array(Math.floor(rating)+1).join('★') : ''; var maxStars = max ? new Array(Math.floor(max)-Math.floor(rating)+1).join('☆') : ''; var text = withText ? ' ('+$filter('mynumber')(rating, 1)+' / '+$filter('mynumber')(max, 1)+')' : ''; return stars+maxStars+text; }; });
import MPopper from '../m-popper.vue'; import pick from 'lodash/pick'; /** * 默认显示一个按钮,hover 上去有提示 */ export const UIconTooltip = { name: 'u-icon-tooltip', props: { type: { type: String, default: 'info' }, // 按钮名称 size: { type: String, default: 'normal' }, // 提示大小 content: String, trigger: { type: String, default: 'hover' }, placement: { type: String, default: 'bottom' }, ...pick(MPopper.props, [ 'opened', 'reference', 'hideDelay', 'boundariesElement', 'followCursor', 'offset', 'disabled', ]), }, }; export default UIconTooltip;
'use strict'; var path = require('path'), express = require('express'), errors = require('./errors'), debug = require('debug')('express-toybox:logger'), DEBUG = debug.enabled; /** * logger middleware using "morgan" or "debug". * * @param {*|String} options or log format. * @param {Number|Boolean} [options.buffer] * @param {Boolean} [options.immediate] * @param {Function} [options.skip] * @param {*} [options.stream] * @param {String} [options.format='combined'] log format. "combined", "common", "dev", "short", "tiny" or "default". * @param {String} [options.file] file to emit log. * @param {String} [options.debug] namespace for tj's debug namespace to emit log. * @returns {Function} connect/express middleware function */ function logger(options) { DEBUG && debug('configure http logger middleware', options); var format; if (typeof options === 'string') { format = options; options = {}; } else { format = options.format || 'combined'; delete options.format; } if (options.debug) { try { return require('morgan-debug')(options.debug, format, options); } catch (e) { console.error('**fatal** failed to configure logger with debug', e); return process.exit(2); } } if (options.file) { try { var file = path.resolve(process.cwd(), options.file); // replace stream options with stream object delete options.file; options.stream = require('fs').createWriteStream(file, {flags: 'a'}); } catch (e) { console.error('**fatal** failed to configure logger with file stream', e); return process.exit(2); } } console.warn('**fallback** use default logger middleware'); return require('morgan')(format, options); } module.exports = logger;
/* eslint-disable new-cap */ /* eslint-disable no-console */ const express = require('express'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const routes = require('./server/routes'); const config = require('./server/config'); const app = express(); const apiRouter = express.Router(); const env = process.env.NODE_ENV; if (env === 'test') { config.database = config.test_database; config.port = 8080; } app.use(morgan('dev')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api', routes(apiRouter)); app.use((req, res, next) => { res.setHeader('Access-Coontrol-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type'); next(); }); mongoose.connect(config.database, (err) => { if (err) { console.log('connection error', err); } else { console.log('connection successful'); } }); app.listen(config.port, (err) => { if (err) { console.log('Connection error', err); } else { console.log('Listening on port:', config.port); } }); module.exports = app;
/* globals describe, it */ import Compiler from '../src/transpiler/compiler'; import assert from 'assert'; import fs from 'fs'; function compare(source, target) { const compiler = new Compiler(source); assert.equal(target, compiler.compiled); } describe('Transpiler', function() { it('should transpile a empty program', function() { compare('', ''); }); it('should transpile a declaration with no value', function() { compare('politico salario.,', 'var salario;'); }); it('should transpile a declaration with int value', function() { compare('politico salario = 100000.,', 'var salario = 100000;'); }); it('should transpile a declaration with string value', function() { compare('politico salario = \'salario\'.,', 'var salario = \'salario\';'); }); it('should transpile a declaration with boolean value', function() { compare('politico salario = true.,', 'var salario = true;'); compare('politico salario = false.,', 'var salario = false;'); }); it('should transpile a attribution of an expression', function() { compare('salario = salario + i.,', 'salario = salario + i;'); }); it('should transpile a print with no value', function() { compare('midiaGolpista().,', 'console.log();'); }); it('should transpile a print with string', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \').,', 'console.log(\'Número abaixo de 100.000: \');'); }); it('should transpile a print with expression', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \' + 1000).,', 'console.log(\'Número abaixo de 100.000: \' + 1000);'); }); it('should transpile a print with multiple values', function() { compare('midiaGolpista(\'Número abaixo de 100.000: \', 1000).,', 'console.log(\'Número abaixo de 100.000: \', 1000);'); }); it('should transpile a empty loop', function() { compare('euViVoceVeja (i = 0., i < 10000., i++) {}', 'for (i = 0; i < 10000; i++) {\n}'); }); it('should transpile a empty if', function() { compare('porque (salario < 100000) {}', 'if (salario < 100000) {\n}'); }); it('should transpile a empty if with empty else', function() { compare('porque (salario < 100000) {} casoContrario {}', 'if (salario < 100000) {\n}'); }); it('should transpile expression `1 + 1`', function() { compare('1 + 1', '1 + 1;'); }); it('should transpile expression `1 + 4 / 2`', function() { compare('1 + 4 / 2', '1 + 4 / 2;'); }); it('should transpile expression `4 / 2 + 1`', function() { compare('4 / 2 + 1', '4 / 2 + 1;'); }); it('should transpile expression `4 / 2 + 1 * 3 - 2`', function() { compare('4 / 2 + 1 * 3 - 2', '4 / 2 + 1 * 3 - 2;'); }); it('should transpile example 1', function() { const source = fs.readFileSync('Example - Loop.dilmalang').toString(); const target = fs.readFileSync('Example - Loop.js').toString().replace(/\n$/, ''); compare(source, target); }); });
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"2":"8 C D e K I N J"},C:{"2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB aB ZB"},D:{"2":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"6 E A B C D XB YB p bB","2":"4 F L H G SB KB UB VB WB"},F:{"2":"0 1 2 3 5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z cB dB eB fB p AB hB"},G:{"1":"D oB pB qB rB sB tB uB vB","2":"G KB iB FB kB lB MB nB"},H:{"2":"wB"},I:{"2":"BB F O xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"2":"LB"},M:{"2":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"selector list argument of :nth-child and :nth-last-child CSS pseudo-classes"};
/** * * @description Convert attribute value to boolean value * @param attribute * @return {Boolean} * @private */ jDoc.engines.OXML.prototype._attributeToBoolean = function (attribute) { return (!!attribute && (attribute.value == 'true' || attribute.value == '1' || attribute.value == 'on')); };
/* Copyright (c) 2014 Dominik Moritz This file is part of the leaflet locate control. It is licensed under the MIT license. You can find the project at: https://github.com/domoritz/leaflet-locatecontrol */ L.Control.Locate = L.Control.extend({ options: { position: 'topleft', drawCircle: true, follow: false, // follow with zoom and pan the user's location stopFollowingOnDrag: false, // if follow is true, stop following when map is dragged (deprecated) // range circle circleStyle: { color: '#136AEC', fillColor: '#136AEC', fillOpacity: 0.15, weight: 2, opacity: 0.5 }, // inner marker markerStyle: { color: '#136AEC', fillColor: '#2A93EE', fillOpacity: 0.7, weight: 2, opacity: 0.9, radius: 5 }, // changes to range circle and inner marker while following // it is only necessary to provide the things that should change followCircleStyle: {}, followMarkerStyle: { //color: '#FFA500', //fillColor: '#FFB000' }, circlePadding: [0, 0], metric: true, onLocationError: function(err) { // this event is called in case of any location error // that is not a time out error. alert(err.message); }, onLocationOutsideMapBounds: function(context) { // this event is repeatedly called when the location changes alert(context.options.strings.outsideMapBoundsMsg); }, setView: true, // automatically sets the map view to the user's location strings: { title: "Show me where I am", popup: "You are within {distance} {unit} from this point", outsideMapBoundsMsg: "You seem located outside the boundaries of the map" }, locateOptions: { maxZoom: Infinity, watch: true // if you overwrite this, visualization cannot be updated } }, onAdd: function (map) { var container = L.DomUtil.create('div', 'leaflet-control-locate leaflet-bar leaflet-control'); var self = this; this._layer = new L.LayerGroup(); this._layer.addTo(map); this._event = undefined; this._locateOptions = this.options.locateOptions; L.extend(this._locateOptions, this.options.locateOptions); L.extend(this._locateOptions, { setView: false // have to set this to false because we have to // do setView manually }); // extend the follow marker style and circle from the normal style var tmp = {}; L.extend(tmp, this.options.markerStyle, this.options.followMarkerStyle); this.options.followMarkerStyle = tmp; tmp = {}; L.extend(tmp, this.options.circleStyle, this.options.followCircleStyle); this.options.followCircleStyle = tmp; var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container); link.href = '#'; link.title = this.options.strings.title; L.DomEvent .on(link, 'click', L.DomEvent.stopPropagation) .on(link, 'click', L.DomEvent.preventDefault) .on(link, 'click', function() { if (self._active && (self._event === undefined || map.getBounds().contains(self._event.latlng) || !self.options.setView || isOutsideMapBounds())) { stopLocate(); } else { locate(); } }) .on(link, 'dblclick', L.DomEvent.stopPropagation); var locate = function () { if (self.options.setView) { self._locateOnNextLocationFound = true; } if(!self._active) { map.locate(self._locateOptions); } self._active = true; if (self.options.follow) { startFollowing(); } if (!self._event) { L.DomUtil.addClass(self._container, "requesting"); L.DomUtil.removeClass(self._container, "active"); L.DomUtil.removeClass(self._container, "following"); } else { visualizeLocation(); } }; var onLocationFound = function (e) { // no need to do anything if the location has not changed if (self._event && (self._event.latlng.lat === e.latlng.lat && self._event.latlng.lng === e.latlng.lng && self._event.accuracy === e.accuracy)) { return; } if (!self._active) { return; } self._event = e; if (self.options.follow && self._following) { self._locateOnNextLocationFound = true; } visualizeLocation(); }; var startFollowing = function() { map.fire('startfollowing'); self._following = true; if (self.options.stopFollowingOnDrag) { map.on('dragstart', stopFollowing); } }; var stopFollowing = function() { map.fire('stopfollowing'); self._following = false; if (self.options.stopFollowingOnDrag) { map.off('dragstart', stopFollowing); } visualizeLocation(); }; var isOutsideMapBounds = function () { if (self._event === undefined) return false; return map.options.maxBounds && !map.options.maxBounds.contains(self._event.latlng); }; var visualizeLocation = function() { if (self._event.accuracy === undefined) self._event.accuracy = 0; var radius = self._event.accuracy; if (self._locateOnNextLocationFound) { if (isOutsideMapBounds()) { self.options.onLocationOutsideMapBounds(self); } else { map.fitBounds(self._event.bounds, { padding: self.options.circlePadding, maxZoom: self._locateOptions.maxZoom }); } self._locateOnNextLocationFound = false; } // circle with the radius of the location's accuracy var style, o; if (self.options.drawCircle) { if (self._following) { style = self.options.followCircleStyle; } else { style = self.options.circleStyle; } if (!self._circle) { self._circle = L.circle(self._event.latlng, radius, style) .addTo(self._layer); } else { self._circle.setLatLng(self._event.latlng).setRadius(radius); for (o in style) { self._circle.options[o] = style[o]; } } } var distance, unit; if (self.options.metric) { distance = radius.toFixed(0); unit = "meters"; } else { distance = (radius * 3.2808399).toFixed(0); unit = "feet"; } // small inner marker var mStyle; if (self._following) { mStyle = self.options.followMarkerStyle; } else { mStyle = self.options.markerStyle; } var t = self.options.strings.popup; if (!self._circleMarker) { self._circleMarker = L.circleMarker(self._event.latlng, mStyle) .bindPopup(L.Util.template(t, {distance: distance, unit: unit})) .addTo(self._layer); } else { self._circleMarker.setLatLng(self._event.latlng) .bindPopup(L.Util.template(t, {distance: distance, unit: unit})) ._popup.setLatLng(self._event.latlng); for (o in mStyle) { self._circleMarker.options[o] = mStyle[o]; } } if (!self._container) return; if (self._following) { L.DomUtil.removeClass(self._container, "requesting"); L.DomUtil.addClass(self._container, "active"); L.DomUtil.addClass(self._container, "following"); } else { L.DomUtil.removeClass(self._container, "requesting"); L.DomUtil.addClass(self._container, "active"); L.DomUtil.removeClass(self._container, "following"); } }; var resetVariables = function() { self._active = false; self._locateOnNextLocationFound = self.options.setView; self._following = false; }; resetVariables(); var stopLocate = function() { map.stopLocate(); map.off('dragstart', stopFollowing); L.DomUtil.removeClass(self._container, "requesting"); L.DomUtil.removeClass(self._container, "active"); L.DomUtil.removeClass(self._container, "following"); resetVariables(); self._layer.clearLayers(); self._circleMarker = undefined; self._circle = undefined; }; var onLocationError = function (err) { // ignore time out error if the location is watched if (err.code == 3 && this._locateOptions.watch) { return; } stopLocate(); self.options.onLocationError(err); }; // event hooks map.on('locationfound', onLocationFound, self); map.on('locationerror', onLocationError, self); // make locate functions available to outside world this.locate = locate; this.stopLocate = stopLocate; this.stopFollowing = stopFollowing; return container; } }); L.Map.addInitHook(function () { if (this.options.locateControl) { this.locateControl = L.control.locate(); this.addControl(this.locateControl); } }); L.control.locate = function (options) { return new L.Control.Locate(options); };
import Component from '@glimmer/component'; import {action} from '@ember/object'; export default class KoenigMenuContentComponent extends Component { @action scrollIntoView(element, [doScroll]) { if (doScroll) { element.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } } }
'use strict';var __extends = (this && 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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var jit_proto_change_detector_1 = require('./jit_proto_change_detector'); var pregen_proto_change_detector_1 = require('./pregen_proto_change_detector'); var proto_change_detector_1 = require('./proto_change_detector'); var iterable_differs_1 = require('./differs/iterable_differs'); var default_iterable_differ_1 = require('./differs/default_iterable_differ'); var keyvalue_differs_1 = require('./differs/keyvalue_differs'); var default_keyvalue_differ_1 = require('./differs/default_keyvalue_differ'); var interfaces_1 = require('./interfaces'); var di_1 = require('angular2/di'); var collection_1 = require('angular2/src/core/facade/collection'); var lang_1 = require('angular2/src/core/facade/lang'); var ast_1 = require('./parser/ast'); exports.ASTWithSource = ast_1.ASTWithSource; exports.AST = ast_1.AST; exports.AstTransformer = ast_1.AstTransformer; exports.PropertyRead = ast_1.PropertyRead; exports.LiteralArray = ast_1.LiteralArray; exports.ImplicitReceiver = ast_1.ImplicitReceiver; var lexer_1 = require('./parser/lexer'); exports.Lexer = lexer_1.Lexer; var parser_1 = require('./parser/parser'); exports.Parser = parser_1.Parser; var locals_1 = require('./parser/locals'); exports.Locals = locals_1.Locals; var exceptions_1 = require('./exceptions'); exports.DehydratedException = exceptions_1.DehydratedException; exports.ExpressionChangedAfterItHasBeenCheckedException = exceptions_1.ExpressionChangedAfterItHasBeenCheckedException; exports.ChangeDetectionError = exceptions_1.ChangeDetectionError; var interfaces_2 = require('./interfaces'); exports.ChangeDetection = interfaces_2.ChangeDetection; exports.ChangeDetectorDefinition = interfaces_2.ChangeDetectorDefinition; exports.DebugContext = interfaces_2.DebugContext; exports.ChangeDetectorGenConfig = interfaces_2.ChangeDetectorGenConfig; var constants_1 = require('./constants'); exports.ChangeDetectionStrategy = constants_1.ChangeDetectionStrategy; var proto_change_detector_2 = require('./proto_change_detector'); exports.DynamicProtoChangeDetector = proto_change_detector_2.DynamicProtoChangeDetector; var binding_record_1 = require('./binding_record'); exports.BindingRecord = binding_record_1.BindingRecord; exports.BindingTarget = binding_record_1.BindingTarget; var directive_record_1 = require('./directive_record'); exports.DirectiveIndex = directive_record_1.DirectiveIndex; exports.DirectiveRecord = directive_record_1.DirectiveRecord; var dynamic_change_detector_1 = require('./dynamic_change_detector'); exports.DynamicChangeDetector = dynamic_change_detector_1.DynamicChangeDetector; var change_detector_ref_1 = require('./change_detector_ref'); exports.ChangeDetectorRef = change_detector_ref_1.ChangeDetectorRef; var iterable_differs_2 = require('./differs/iterable_differs'); exports.IterableDiffers = iterable_differs_2.IterableDiffers; var keyvalue_differs_2 = require('./differs/keyvalue_differs'); exports.KeyValueDiffers = keyvalue_differs_2.KeyValueDiffers; var change_detection_util_1 = require('./change_detection_util'); exports.WrappedValue = change_detection_util_1.WrappedValue; /** * Structural diffing for `Object`s and `Map`s. */ exports.keyValDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_keyvalue_differ_1.DefaultKeyValueDifferFactory())]); /** * Structural diffing for `Iterable` types such as `Array`s. */ exports.iterableDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_iterable_differ_1.DefaultIterableDifferFactory())]); exports.defaultIterableDiffers = lang_1.CONST_EXPR(new iterable_differs_1.IterableDiffers(exports.iterableDiff)); exports.defaultKeyValueDiffers = lang_1.CONST_EXPR(new keyvalue_differs_1.KeyValueDiffers(exports.keyValDiff)); /** * Map from {@link ChangeDetectorDefinition#id} to a factory method which takes a * {@link Pipes} and a {@link ChangeDetectorDefinition} and generates a * {@link ProtoChangeDetector} associated with the definition. */ // TODO(kegluneq): Use PregenProtoChangeDetectorFactory rather than Function once possible in // dart2js. See https://github.com/dart-lang/sdk/issues/23630 for details. exports.preGeneratedProtoDetectors = {}; /** * Implements change detection using a map of pregenerated proto detectors. */ var PreGeneratedChangeDetection = (function (_super) { __extends(PreGeneratedChangeDetection, _super); function PreGeneratedChangeDetection(config, protoChangeDetectorsForTest) { _super.call(this); this._dynamicChangeDetection = new DynamicChangeDetection(); this._protoChangeDetectorFactories = lang_1.isPresent(protoChangeDetectorsForTest) ? protoChangeDetectorsForTest : exports.preGeneratedProtoDetectors; this._genConfig = lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false); } PreGeneratedChangeDetection.isSupported = function () { return pregen_proto_change_detector_1.PregenProtoChangeDetector.isSupported(); }; PreGeneratedChangeDetection.prototype.getProtoChangeDetector = function (id, definition) { if (collection_1.StringMapWrapper.contains(this._protoChangeDetectorFactories, id)) { return collection_1.StringMapWrapper.get(this._protoChangeDetectorFactories, id)(definition); } return this._dynamicChangeDetection.getProtoChangeDetector(id, definition); }; Object.defineProperty(PreGeneratedChangeDetection.prototype, "genConfig", { get: function () { return this._genConfig; }, enumerable: true, configurable: true }); Object.defineProperty(PreGeneratedChangeDetection.prototype, "generateDetectors", { get: function () { return true; }, enumerable: true, configurable: true }); PreGeneratedChangeDetection = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig, Object]) ], PreGeneratedChangeDetection); return PreGeneratedChangeDetection; })(interfaces_1.ChangeDetection); exports.PreGeneratedChangeDetection = PreGeneratedChangeDetection; /** * Implements change detection that does not require `eval()`. * * This is slower than {@link JitChangeDetection}. */ var DynamicChangeDetection = (function (_super) { __extends(DynamicChangeDetection, _super); function DynamicChangeDetection(config) { _super.call(this); this._genConfig = lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false); } DynamicChangeDetection.prototype.getProtoChangeDetector = function (id, definition) { return new proto_change_detector_1.DynamicProtoChangeDetector(definition); }; Object.defineProperty(DynamicChangeDetection.prototype, "genConfig", { get: function () { return this._genConfig; }, enumerable: true, configurable: true }); Object.defineProperty(DynamicChangeDetection.prototype, "generateDetectors", { get: function () { return true; }, enumerable: true, configurable: true }); DynamicChangeDetection = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig]) ], DynamicChangeDetection); return DynamicChangeDetection; })(interfaces_1.ChangeDetection); exports.DynamicChangeDetection = DynamicChangeDetection; /** * Implements faster change detection by generating source code. * * This requires `eval()`. For change detection that does not require `eval()`, see * {@link DynamicChangeDetection} and {@link PreGeneratedChangeDetection}. */ var JitChangeDetection = (function (_super) { __extends(JitChangeDetection, _super); function JitChangeDetection(config) { _super.call(this); this._genConfig = lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false); } JitChangeDetection.isSupported = function () { return jit_proto_change_detector_1.JitProtoChangeDetector.isSupported(); }; JitChangeDetection.prototype.getProtoChangeDetector = function (id, definition) { return new jit_proto_change_detector_1.JitProtoChangeDetector(definition); }; Object.defineProperty(JitChangeDetection.prototype, "genConfig", { get: function () { return this._genConfig; }, enumerable: true, configurable: true }); Object.defineProperty(JitChangeDetection.prototype, "generateDetectors", { get: function () { return true; }, enumerable: true, configurable: true }); JitChangeDetection = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig]) ], JitChangeDetection); return JitChangeDetection; })(interfaces_1.ChangeDetection); exports.JitChangeDetection = JitChangeDetection; //# sourceMappingURL=change_detection.js.map
/** * Created by hbzhang on 8/7/15. */ 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Widget = mongoose.model('Widget'), Upload = mongoose.model('Upload'), _ = require('lodash'), grid = require('gridfs-stream'); /** * Find widget by id */ exports.widget = function(req, res, next, id) { //console.log(id); Widget.load(id, function(err, widget) { if (err) return next(err); if (!widget) return next(new Error('Failed to load the widget' + id)); req.widget = widget; next(); }); }; exports.view = function(req, res) { //res.jsonp(req.class_); Widget.findOne({_id: req.param('widgetID') }, function (err, widget){ res.jsonp(widget); console.log(widget); }); }; /** * Create a widget */ exports.create = function(req, res) { //console.log(req.body); var widget = new Widget(req.body); //console.log(form); /* var e = dateValidation(class_); if (e !== '') { console.log(e); return res.jsonp(500, { error: e }); } */ widget.save(function(err) { if (err) { console.log(err); return res.jsonp(500, {error: 'cannot save the widget'}); } res.jsonp(widget); }); }; /** * List all widgets */ exports.all = function(req, res) { var populateQuery = [{path:'widgetcreator'}]; Widget.find({}, '_id widgetbasicinformation widgetformbuilder widgetroles').populate(populateQuery).exec(function(err, widgets) { if (err) { return res.jsonp(500, { error: 'Cannot list all the widgets' }); } res.jsonp(widgets); }); }; /** * Delete a widget */ exports.destroy = function(req, res) { //var event = req.event; //console.log(req.param('eventID')); Widget.remove({ _id: req.param('widgetID') }, function(err) { if (err) { return res.jsonp(500, { error: 'Cannot delete the widget' }); } res.jsonp({ _id: req.param('widgetID') }); }); }; /** * Update a widget */ exports.update = function(req, res) { Widget.findOne({_id: req.param('widgetID') }, function (err, widget){ widget.widgetbasicinformation = req.param('widgetbasicinformation'); widget.widgetformbuilder = req.param('widgetformbuilder'); widget.widgetcreator = req.param('widgetcreator'); widget.widgetroles = req.param('widgetroles'); widget.save(); res.jsonp(widget); }); };
const sensor = require('node-dht-sensor'); const logger = require('../logging/Logger'); /** * Reads pin 4 of the raspberry PI to obtain temperature and humidity information. * @return {Promise} A promise that will resolve with the results. In the * case where there was an error reading, will return a zero filled object, * with an additional error field. * { temperature: Number, * humidity: Number, * error: Error|undefined } */ exports.getHumidityTemperature = function() { return new Promise( (resolve, reject) => { sensor.read(22, 4, (err, temperature, humidity) => { if(err) { logger.error("Could not read from the DHT sensor. " + err); return resolve({ temperature: 0, humidity: 0, error: err}); } resolve({ temperature: temperature * 1.8 + 32, humidity: humidity}); }); }); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow * @format */ // flowlint ambiguous-object-type:error 'use strict'; const React = require('react'); const Scheduler = require('scheduler'); import type {Direction} from '../useLoadMoreFunction'; import type {OperationDescriptor, Variables} from 'relay-runtime'; const {useEffect, useTransition, useMemo, useState} = React; const TestRenderer = require('react-test-renderer'); const invariant = require('invariant'); const useBlockingPaginationFragmentOriginal = require('../useBlockingPaginationFragment'); const ReactRelayContext = require('react-relay/ReactRelayContext'); const { ConnectionHandler, FRAGMENT_OWNER_KEY, FRAGMENTS_KEY, ID_KEY, createOperationDescriptor, graphql, getRequest, getFragment, } = require('relay-runtime'); const {createMockEnvironment} = require('relay-test-utils'); // TODO: We're switching the tuple order of useTransition so for ~1 day we // need to disable this test so we can flip in www then fbsource. const TEMPORARY_SKIP_WHILE_REFACTORING_USE_TRANSITION = true; describe('useBlockingPaginationFragment with useTransition', () => { if ( TEMPORARY_SKIP_WHILE_REFACTORING_USE_TRANSITION || typeof React.useTransition !== 'function' ) { it('empty test to prevent Jest from failing', () => { // This suite is only useful with experimental React build }); } else { let environment; let initialUser; let gqlQuery; let gqlQueryWithoutID; let gqlPaginationQuery; let gqlFragment; let query; let queryWithoutID; let paginationQuery; let variables; let variablesWithoutID; let setOwner; let renderFragment; let loadNext; let refetch; let forceUpdate; let release; let Renderer; class ErrorBoundary extends React.Component<any, any> { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { const {children, fallback} = this.props; const {error} = this.state; if (error) { return React.createElement(fallback, {error}); } return children; } } function useBlockingPaginationFragmentWithSuspenseTransition( fragmentNode, fragmentRef, ) { const [isPendingNext, startTransition] = useTransition(); // $FlowFixMe[incompatible-call] const {data, ...result} = useBlockingPaginationFragmentOriginal( fragmentNode, // $FlowFixMe[prop-missing] // $FlowFixMe[incompatible-call] fragmentRef, ); loadNext = (...args) => { let disposable = {dispose: () => {}}; startTransition(() => { disposable = result.loadNext(...args); }); return disposable; }; refetch = result.refetch; // $FlowFixMe[prop-missing] result.isPendingNext = isPendingNext; useEffect(() => { Scheduler.unstable_yieldValue({data, ...result}); }); return {data, ...result}; } function assertYieldsWereCleared() { const actualYields = Scheduler.unstable_clearYields(); if (actualYields.length !== 0) { throw new Error( 'Log of yielded values is not empty. ' + 'Call expect(Scheduler).toHaveYielded(...) first.', ); } } function assertYield(expected, actual) { expect(actual.data).toEqual(expected.data); expect(actual.isPendingNext).toEqual(expected.isPendingNext); expect(actual.hasNext).toEqual(expected.hasNext); expect(actual.hasPrevious).toEqual(expected.hasPrevious); } function expectFragmentResults( expectedYields: $ReadOnlyArray<{| data: $FlowFixMe, isPendingNext: boolean, hasNext: boolean, hasPrevious: boolean, |}>, ) { assertYieldsWereCleared(); Scheduler.unstable_flushNumberOfYields(expectedYields.length); const actualYields = Scheduler.unstable_clearYields(); expect(actualYields.length).toEqual(expectedYields.length); expectedYields.forEach((expected, idx) => assertYield(expected, actualYields[idx]), ); } function expectRequestIsInFlight(expected) { expect(environment.execute).toBeCalledTimes(expected.requestCount); expect( environment.mock.isLoading( gqlPaginationQuery, expected.paginationVariables, {force: true}, ), ).toEqual(expected.inFlight); } function expectFragmentIsPendingOnPagination( renderer, direction: Direction, expected: {| data: mixed, hasNext: boolean, hasPrevious: boolean, paginationVariables: Variables, |}, ) { // Assert fragment sets isPending to true expectFragmentResults([ { data: expected.data, isPendingNext: direction === 'forward', hasNext: expected.hasNext, hasPrevious: expected.hasPrevious, }, ]); // Assert refetch query was fetched expectRequestIsInFlight({...expected, inFlight: true, requestCount: 1}); } function createFragmentRef(id, owner) { return { [ID_KEY]: id, [FRAGMENTS_KEY]: { useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment: {}, }, [FRAGMENT_OWNER_KEY]: owner.request, }; } beforeEach(() => { // Set up mocks jest.resetModules(); jest.mock('warning'); jest.mock('scheduler', () => { return jest.requireActual('scheduler/unstable_mock'); }); // Supress `act` warnings since we are intentionally not // using it for most tests here. `act` currently always // flushes Suspense fallbacks, and that's not what we want // when asserting pending/suspended states, const originalLogError = console.error.bind(console); jest.spyOn(console, 'error').mockImplementation((message, ...args) => { if (typeof message === 'string' && message.includes('act(...)')) { return; } originalLogError(message, ...args); }); // Set up environment and base data environment = createMockEnvironment({ handlerProvider: () => ConnectionHandler, }); release = jest.fn(); environment.retain.mockImplementation((...args) => { return { dispose: release, }; }); graphql` fragment useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment on User { username } `; gqlFragment = getFragment(graphql` fragment useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment on User @refetchable( queryName: "useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery" ) @argumentDefinitions( isViewerFriendLocal: {type: "Boolean", defaultValue: false} orderby: {type: "[String]"} ) { id name friends( after: $after first: $first before: $before last: $last orderby: $orderby isViewerFriend: $isViewerFriendLocal ) @connection(key: "UserFragment_friends") { edges { node { id name ...useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment } } } } `); gqlQuery = getRequest( graphql` query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQuery( $id: ID! $after: ID $first: Int $before: ID $last: Int $orderby: [String] $isViewerFriend: Boolean ) { node(id: $id) { actor { ...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment @arguments( isViewerFriendLocal: $isViewerFriend orderby: $orderby ) } } } `, ); gqlQueryWithoutID = getRequest(graphql` query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQueryWithoutIDQuery( $after: ID $first: Int $before: ID $last: Int $orderby: [String] $isViewerFriend: Boolean ) { viewer { actor { ...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment @arguments( isViewerFriendLocal: $isViewerFriend orderby: $orderby ) } } } `); variablesWithoutID = { after: null, first: 1, before: null, last: null, isViewerFriend: false, orderby: ['name'], }; variables = { ...variablesWithoutID, id: '<feedbackid>', }; gqlPaginationQuery = require('./__generated__/useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery.graphql'); query = createOperationDescriptor(gqlQuery, variables); queryWithoutID = createOperationDescriptor( gqlQueryWithoutID, variablesWithoutID, ); paginationQuery = createOperationDescriptor( gqlPaginationQuery, variables, ); environment.commitPayload(query, { node: { __typename: 'Feedback', id: '<feedbackid>', actor: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', username: 'username:node:1', }, }, ], pageInfo: { endCursor: 'cursor:1', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }, }, }); environment.commitPayload(queryWithoutID, { viewer: { actor: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', username: 'username:node:1', }, }, ], pageInfo: { endCursor: 'cursor:1', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }, }, }); // Set up renderers Renderer = props => null; const Container = (props: { userRef?: {...}, owner: $FlowFixMe, fragment: $FlowFixMe, ... }) => { // We need a render a component to run a Hook const [owner, _setOwner] = useState(props.owner); const [_, _setCount] = useState(0); const fragment = props.fragment ?? gqlFragment; const artificialUserRef = useMemo(() => { const snapshot = environment.lookup(owner.fragment); return (snapshot.data: $FlowFixMe)?.node?.actor; }, [owner]); const userRef = props.hasOwnProperty('userRef') ? props.userRef : artificialUserRef; setOwner = _setOwner; forceUpdate = _setCount; const { data: userData, } = useBlockingPaginationFragmentWithSuspenseTransition( fragment, // $FlowFixMe[prop-missing] userRef, ); return <Renderer user={userData} />; }; const ContextProvider = ({children}) => { // TODO(T39494051) - We set empty variables in relay context to make // Flow happy, but useBlockingPaginationFragment does not use them, instead it uses // the variables from the fragment owner. const relayContext = useMemo(() => ({environment}), []); return ( <ReactRelayContext.Provider value={relayContext}> {children} </ReactRelayContext.Provider> ); }; const Fallback = () => { useEffect(() => { Scheduler.unstable_yieldValue('Fallback'); }); return 'Fallback'; }; renderFragment = (args?: { isConcurrent?: boolean, owner?: $FlowFixMe, userRef?: $FlowFixMe, fragment?: $FlowFixMe, ... }): $FlowFixMe => { const {isConcurrent = true, ...props} = args ?? {}; return TestRenderer.create( <ErrorBoundary fallback={({error}) => `Error: ${error.message}`}> <React.Suspense fallback={<Fallback />}> <ContextProvider> <Container owner={query} {...props} /> </ContextProvider> </React.Suspense> </ErrorBoundary>, // $FlowFixMe[prop-missing] - error revealed when flow-typing ReactTestRenderer {unstable_isConcurrent: isConcurrent}, ); }; initialUser = { id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', query), }, }, ], pageInfo: { endCursor: 'cursor:1', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }; }); afterEach(() => { environment.mockClear(); jest.dontMock('scheduler'); }); describe('loadNext', () => { const direction = 'forward'; // Sanity check test, should already be tested in useBlockingPagination test it('loads and renders next items in connection', () => { const callback = jest.fn(); const renderer = renderFragment(); expectFragmentResults([ { data: initialUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); loadNext(1, {onComplete: callback}); const paginationVariables = { id: '1', after: 'cursor:1', first: 1, before: null, last: null, isViewerFriendLocal: false, orderby: ['name'], }; expectFragmentIsPendingOnPagination(renderer, direction, { data: initialUser, hasNext: true, hasPrevious: false, paginationVariables, }); expect(callback).toBeCalledTimes(0); expect(renderer.toJSON()).toEqual(null); environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', username: 'username:node:2', }, }, ], pageInfo: { startCursor: 'cursor:2', endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: true, }, }, }, }, }); const expectedUser = { ...initialUser, friends: { ...initialUser.friends, edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', query), }, }, { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', ...createFragmentRef('node:2', query), }, }, ], pageInfo: { endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }; expectFragmentResults([ { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); expect(callback).toBeCalledTimes(1); }); it('renders pending flag correctly if pagination update is interrupted before it commits (unsuspends)', () => { const callback = jest.fn(); const renderer = renderFragment(); expectFragmentResults([ { data: initialUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); loadNext(1, {onComplete: callback}); const paginationVariables = { id: '1', after: 'cursor:1', first: 1, before: null, last: null, isViewerFriendLocal: false, orderby: ['name'], }; expectFragmentIsPendingOnPagination(renderer, direction, { data: initialUser, hasNext: true, hasPrevious: false, paginationVariables, }); expect(callback).toBeCalledTimes(0); expect(renderer.toJSON()).toEqual(null); // Schedule a high-pri update while the component is // suspended on pagination Scheduler.unstable_runWithPriority( Scheduler.unstable_UserBlockingPriority, () => { forceUpdate(prev => prev + 1); }, ); // Assert high-pri update is rendered when initial update // that suspended hasn't committed // Assert that the avoided Suspense fallback isn't rendered expect(renderer.toJSON()).toEqual(null); expectFragmentResults([ { data: initialUser, // Assert that isPending flag is still true isPendingNext: true, hasNext: true, hasPrevious: false, }, ]); // Assert list is updated after pagination request completes environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', username: 'username:node:2', }, }, ], pageInfo: { startCursor: 'cursor:2', endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: true, }, }, }, }, }); const expectedUser = { ...initialUser, friends: { ...initialUser.friends, edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', query), }, }, { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', ...createFragmentRef('node:2', query), }, }, ], pageInfo: { endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }; expectFragmentResults([ { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); expect(callback).toBeCalledTimes(1); }); it('loads more correctly when original variables do not include an id', () => { const callback = jest.fn(); const viewer = environment.lookup(queryWithoutID.fragment).data?.viewer; const userRef = typeof viewer === 'object' && viewer != null ? viewer?.actor : null; invariant(userRef != null, 'Expected to have cached test data'); let expectedUser = { ...initialUser, friends: { ...initialUser.friends, edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', queryWithoutID), }, }, ], }, }; const renderer = renderFragment({owner: queryWithoutID, userRef}); expectFragmentResults([ { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); loadNext(1, {onComplete: callback}); const paginationVariables = { id: '1', after: 'cursor:1', first: 1, before: null, last: null, isViewerFriendLocal: false, orderby: ['name'], }; expectFragmentIsPendingOnPagination(renderer, direction, { data: expectedUser, hasNext: true, hasPrevious: false, paginationVariables, }); expect(callback).toBeCalledTimes(0); expect(renderer.toJSON()).toEqual(null); environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', username: 'username:node:2', }, }, ], pageInfo: { startCursor: 'cursor:2', endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: true, }, }, }, }, }); expectedUser = { ...initialUser, friends: { ...initialUser.friends, edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', queryWithoutID), }, }, { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', ...createFragmentRef('node:2', queryWithoutID), }, }, ], pageInfo: { endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }; expectFragmentResults([ { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); expect(callback).toBeCalledTimes(1); }); it('calls callback with error when error occurs during fetch', () => { const callback = jest.fn(); const renderer = renderFragment(); expectFragmentResults([ { data: initialUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); loadNext(1, {onComplete: callback}); const paginationVariables = { id: '1', after: 'cursor:1', first: 1, before: null, last: null, isViewerFriendLocal: false, orderby: ['name'], }; expectFragmentIsPendingOnPagination(renderer, direction, { data: initialUser, hasNext: true, hasPrevious: false, paginationVariables, }); expect(callback).toBeCalledTimes(0); expect(renderer.toJSON()).toEqual(null); const error = new Error('Oops'); environment.mock.reject(gqlPaginationQuery, error); // We pass the error in the callback, but do not throw during render // since we want to continue rendering the existing items in the // connection expect(callback).toBeCalledTimes(1); expect(callback).toBeCalledWith(error); }); it('preserves pagination request if re-rendered with same fragment ref', () => { const callback = jest.fn(); const renderer = renderFragment(); expectFragmentResults([ { data: initialUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); loadNext(1, {onComplete: callback}); const paginationVariables = { id: '1', after: 'cursor:1', first: 1, before: null, last: null, isViewerFriendLocal: false, orderby: ['name'], }; expectFragmentIsPendingOnPagination(renderer, direction, { data: initialUser, hasNext: true, hasPrevious: false, paginationVariables, }); expect(callback).toBeCalledTimes(0); expect(renderer.toJSON()).toEqual(null); setOwner({...query}); // Assert that request is still in flight after re-rendering // with new fragment ref that points to the same data. expectRequestIsInFlight({ inFlight: true, requestCount: 1, gqlPaginationQuery, paginationVariables, }); expect(callback).toBeCalledTimes(0); environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', username: 'username:node:2', }, }, ], pageInfo: { startCursor: 'cursor:2', endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: true, }, }, }, }, }); const expectedUser = { ...initialUser, friends: { ...initialUser.friends, edges: [ { cursor: 'cursor:1', node: { __typename: 'User', id: 'node:1', name: 'name:node:1', ...createFragmentRef('node:1', query), }, }, { cursor: 'cursor:2', node: { __typename: 'User', id: 'node:2', name: 'name:node:2', ...createFragmentRef('node:2', query), }, }, ], pageInfo: { endCursor: 'cursor:2', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:1', }, }, }; expectFragmentResults([ { data: expectedUser, isPendingNext: true, hasNext: true, hasPrevious: false, }, { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); expect(callback).toBeCalledTimes(1); }); }); describe('refetch', () => { // The bulk of refetch behavior is covered in useRefetchableFragmentNode-test, // so this suite covers the pagination-related test cases. function expectRefetchRequestIsInFlight(expected) { expect(environment.executeWithSource).toBeCalledTimes( expected.requestCount, ); expect( environment.mock.isLoading( expected.gqlRefetchQuery ?? gqlPaginationQuery, expected.refetchVariables, {force: true}, ), ).toEqual(expected.inFlight); } function expectFragmentSuspendedOnRefetch( renderer, expected: {| data: mixed, hasNext: boolean, hasPrevious: boolean, refetchVariables: Variables, refetchQuery?: OperationDescriptor, gqlRefetchQuery?: $FlowFixMe, |}, flushFallback: boolean = true, ) { assertYieldsWereCleared(); TestRenderer.act(() => { // Wrap in act to ensure passive effects are run jest.runAllImmediates(); }); Scheduler.unstable_flushNumberOfYields(1); const actualYields = Scheduler.unstable_clearYields(); if (flushFallback) { // Flushing fallbacks by running a timer could cause other side-effects // such as releasing retained queries. Until React has a better way to flush // fallbacks, we can't test fallbacks and other timeout based effects at the same time. jest.runOnlyPendingTimers(); // Tigger fallbacks. // Assert component suspendeds expect(actualYields.length).toEqual(1); expect(actualYields[0]).toEqual('Fallback'); expect(renderer.toJSON()).toEqual('Fallback'); } // Assert refetch query was fetched expectRefetchRequestIsInFlight({ ...expected, inFlight: true, requestCount: 1, }); // Assert query is retained by loadQuery // and tentatively retained while component is suspended expect(environment.retain).toBeCalledTimes(2); expect(environment.retain.mock.calls[0][0]).toEqual( expected.refetchQuery, ); } it('loads more items correctly after refetching', () => { const renderer = renderFragment(); expectFragmentResults([ { data: initialUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); refetch({isViewerFriendLocal: true, orderby: ['lastname']}); // Assert that fragment is refetching with the right variables and // suspends upon refetch const refetchVariables = { after: null, first: 1, before: null, last: null, id: '1', isViewerFriendLocal: true, orderby: ['lastname'], }; paginationQuery = createOperationDescriptor( gqlPaginationQuery, refetchVariables, {force: true}, ); expectFragmentSuspendedOnRefetch( renderer, { data: initialUser, hasNext: true, hasPrevious: false, refetchVariables, refetchQuery: paginationQuery, }, false, ); // Mock network response environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:100', node: { __typename: 'User', id: 'node:100', name: 'name:node:100', username: 'username:node:100', }, }, ], pageInfo: { endCursor: 'cursor:100', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:100', }, }, }, }, }); // Assert fragment is rendered with new data const expectedUser = { id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:100', node: { __typename: 'User', id: 'node:100', name: 'name:node:100', ...createFragmentRef('node:100', paginationQuery), }, }, ], pageInfo: { endCursor: 'cursor:100', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:100', }, }, }; jest.runAllImmediates(); expectFragmentResults([ { data: expectedUser, isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); // Assert refetch query was retained by loadQuery and component expect(release).not.toBeCalled(); expect(environment.retain).toBeCalledTimes(2); expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery); // Paginate after refetching environment.execute.mockClear(); loadNext(1); const paginationVariables = { id: '1', after: 'cursor:100', first: 1, before: null, last: null, isViewerFriendLocal: true, orderby: ['lastname'], }; expectFragmentIsPendingOnPagination(renderer, 'forward', { data: expectedUser, hasNext: true, hasPrevious: false, paginationVariables, }); environment.mock.resolve(gqlPaginationQuery, { data: { node: { __typename: 'User', id: '1', name: 'Alice', friends: { edges: [ { cursor: 'cursor:200', node: { __typename: 'User', id: 'node:200', name: 'name:node:200', username: 'username:node:200', }, }, ], pageInfo: { startCursor: 'cursor:200', endCursor: 'cursor:200', hasNextPage: true, hasPreviousPage: true, }, }, }, }, }); const paginatedUser = { ...expectedUser, friends: { ...expectedUser.friends, edges: [ { cursor: 'cursor:100', node: { __typename: 'User', id: 'node:100', name: 'name:node:100', ...createFragmentRef('node:100', paginationQuery), }, }, { cursor: 'cursor:200', node: { __typename: 'User', id: 'node:200', name: 'name:node:200', ...createFragmentRef('node:200', paginationQuery), }, }, ], pageInfo: { endCursor: 'cursor:200', hasNextPage: true, hasPreviousPage: false, startCursor: 'cursor:100', }, }, }; expectFragmentResults([ { data: paginatedUser, // Assert pending flag is set back to false isPendingNext: false, hasNext: true, hasPrevious: false, }, ]); }); }); } });
var chartPrevious = [ {"Name":"", "Description":"charts"}, {"Name":"1 hour", "Description":"1 hour"}, {"Name":"2 hours", "Description":"2 hours"}, {"Name":"10 hours", "Description":"10 hours"}, {"Name":"1 day", "Description":"1 day"}, {"Name":"2 days", "Description":"2 days"}, {"Name":"3 days", "Description":"3 days"}, {"Name":"7 days", "Description":"7 days"}, {"Name":"14 days", "Description":"14 days"}, {"Name":"30 days", "Description":"30 days"} ]; var employees = [ {"name":"Employee10", "surname":"Employee1", "filename" : "sav3.png", "department":"marketing"}, {"name":"Employee11", "surname":"Employee1", "filename" : "who3.png", "department":"marketing"}, {"name":"Employee12", "surname":"Employee1", "filename" : "jac4.png", "department":"digital"}, {"name":"Employee13", "surname":"Employee1", "filename" : "mart4.png", "department":"digital"}, {"name":"Employee14", "surname":"Employee1", "filename" : "sav4.png", "department":"digital"}, {"name":"Employee15", "surname":"Employee1", "filename" : "who4.png", "department":"digital"}, {"name":"Employee16", "surname":"Employee1", "filename" : "jac5.png", "department":"digital"}, {"name":"Employee17", "surname":"Employee1", "filename" : "mart5.png", "department":"marketing"}, {"name":"Employee18", "surname":"Employee1", "filename" : "sav5.png", "department":"digital"}, {"name":"Employee19", "surname":"Employee1", "filename" : "who5.png", "department":"digital"}, {"name":"Employee1", "surname":"Employee1", "filename" : "jac1.png", "department":"marketing"}, {"name":"Employee2", "surname":"Employee1", "filename" : "mart1.png", "department":"marketing"}, {"name":"Employee3", "surname":"Employee1", "filename" : "sav1.png", "department":"marketing"}, {"name":"Employee4", "surname":"Employee1", "filename" : "who1.png", "department":"marketing"}, {"name":"Employee5", "surname":"Employee1", "filename" : "jac2.png", "department":"marketing"}, {"name":"Employee6", "surname":"Employee1", "filename" : "mart2.png", "department":"marketing"}, {"name":"Employee6", "surname":"Employee1", "filename" : "sav2.png", "department":"marketing"}, {"name":"Employee7", "surname":"Employee1", "filename" : "who2.png", "department":"marketing"}, {"name":"Employee8", "surname":"Employee1", "filename" : "jac3.png", "department":"marketing"}, {"name":"Employee9", "surname":"Employee1", "filename" : "mart3.png", "department":"marketing"}, {"name":"Employee20", "surname":"Employee1", "filename" : "jac6.png", "department":"marketing"}, {"name":"Employee21", "surname":"Employee1", "filename" : "mart6.png", "department":"marketing"}, {"name":"Employee22", "surname":"Employee1", "filename" : "sav6.png", "department":"marketing"}, {"name":"Employee23", "surname":"Employee1", "filename" : "who6.png", "department":"marketing"}, {"name":"Employee24", "surname":"Employee1", "filename" : "jac7.png", "department":"marketing"}, {"name":"Employee25", "surname":"Employee1", "filename" : "mart7.png", "department":"marketing"}, {"name":"Employee26", "surname":"Employee1", "filename" : "sav7.png", "department":"marketing"}, {"name":"Employee27", "surname":"Employee1", "filename" : "who7.png", "department":"marketing"}, {"name":"Employee28", "surname":"Employee1", "filename" : "jac8.png", "department":"staff"}, {"name":"Employee29", "surname":"Employee1", "filename" : "mart8.png", "department":"staff"}, {"name":"Employee40", "surname":"Employee1", "filename" : "jac11.png", "department":"staff"}, {"name":"Employee41", "surname":"Employee1", "filename" : "mart11.png", "department":"marketing"}, {"name":"Employee42", "surname":"Employee1", "filename" : "sav11.png", "department":"marketing"}, {"name":"Employee43", "surname":"Employee1", "filename" : "who11.png", "department":"marketing"}, {"name":"Employee44", "surname":"Employee1", "filename" : "jac12.png", "department":"staff"}, {"name":"Employee45", "surname":"Employee1", "filename" : "mart12.png", "department":"staff"}, {"name":"Employee46", "surname":"Employee1", "filename" : "sav12.png", "department":"staff"}, {"name":"Employee47", "surname":"Employee1", "filename" : "who12.png", "department":"staff"}, {"name":"Employee48", "surname":"Employee1", "filename" : "jac13.png", "department":"staff"}, {"name":"Employee49", "surname":"Employee1", "filename" : "mart13.png", "department":"staff"}, {"name":"Employee30", "surname":"Employee1", "filename" : "sav8.png", "department":"marketing"}, {"name":"Employee31", "surname":"Employee1", "filename" : "who8.png", "department":"marketing"}, {"name":"Employee32", "surname":"Employee1", "filename" : "jac9.png", "department":"marketing"}, {"name":"Employee33", "surname":"Employee1", "filename" : "mart9.png", "department":"staff"}, {"name":"Employee34", "surname":"Employee1", "filename" : "sav9.png", "department":"staff"}, {"name":"Employee35", "surname":"Employee1", "filename" : "who9.png", "department":"marketing"}, {"name":"Employee36", "surname":"Employee1", "filename" : "jac10.png", "department":"marketing"}, {"name":"Employee37", "surname":"Employee1", "filename" : "mart10.png", "department":"staff"}, {"name":"Employee38", "surname":"Employee1", "filename" : "sav10.png", "department":"staff"}, {"name":"Employee39", "surname":"Employee1", "filename" : "who10.png", "department":"staff"} ];
/*requires core.js*/ /*requires load.js*/ /*requires ajax.js*/ /*requires dom.js*/ /*requires selector.js*/ /*requires ua.js*/ /*requires event.js*/ /*requires ui.js*/ /*requires ui.tab.js*/ /*requires ui.slide.js*/ /*requires ui.nav.js*/ /** * nova.ui.flow * 在页面中四处飘浮的广告 * 遇到边界则改变飘浮方向 * @param number width element&img's width * @param number height element&img's height * @param string img's src * @param string anchor href */ nova.ui.flow = function() { var doc = document, html = doc.documentElement, body = doc.body, opt = arguments[0], xPos = 300, yPos = 200, step = 1, delay = 30, height = 0, Hoffset = 0, Woffset = 0, yon = 0, xon = 0, pause = true, interval; //生成广告元素 var elm = doc.createElement("div"); nova.dom.addClass(elm, "nova-ui-flow"); elm.innerHTML = '<a href="'+ opt.href + '"><img src="' + opt.src + '" width="' + opt.width + '" height="' + opt.height + '"></a>'; nova.dom.setCSS([elm], { position: "absolute", zIndex: "100", top: yPos + "px", left: "2px", width: opt.width + "px", height: opt.height + "px", visibility: "visible" }); body.appendChild(elm); var changePos = function () { width = body.clientWidth; height = html.clientHeight; Hoffset = elm.offsetHeight; Woffset = elm.offsetWidth; nova.dom.setCSS([elm], { left: xPos + doc.body.scrollLeft + "px", top: yPos + doc.body.scrollTop + "px" }); if (yon) { yPos = yPos + step; } else { yPos = yPos - step; } if (yPos < 0) { yon = 1; yPos = 0; } if (yPos >= (height - Hoffset)) { yon = 0; yPos = (height - Hoffset); } if (xon) { xPos = xPos + step; } else { xPos = xPos - step; } if (xPos < 0) { xon = 1; xPos = 0; } if (xPos >= (width - Woffset)) { xon = 0; xPos = (width - Woffset); } }; var pauseResume = function () { if (pause) { clearInterval(interval); pause = false; } else { interval = setInterval(changePos, delay); pause = true; } }; nova.Event.add(elm, "mouseover", pauseResume); nova.Event.add(elm, "mouseout", pauseResume); interval = setInterval(changePos, delay); };
$(document).ready(function () { $('#userData').hide(); $('#topScores').show(); // enchanced method addEventListener function addEventListener(selector, eventType, listener) { $(selector).on(eventType, listener); } function trigerClick($button) { $button.click(); } var GameManager = (function () { var numberToGuess = []; var guessNumber = []; var guesses = 0; function getRandomNumber() { var newNumber = []; guesses = 0; newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0 newNumber[1] = Math.round(Math.random() * 9); newNumber[2] = Math.round(Math.random() * 9); newNumber[3] = Math.round(Math.random() * 9); numberToGuess = newNumber; } function getUserInput(value) { value = validateNumber(value); guessNumber = String(parseInt(value)).split(''); } function validateNumber(number) { number = number.trim(); if (number.length != 4) { throw new Error("The number must be 4 digits long!"); } number = String(parseInt(number)); if (isNaN(number) || (number < 1000 || number > 10000)) { throw new Error("This is not a 4 digit number!"); } return number; } function checkNumber() { var rams = 0; var sheeps = 0; guesses += 1; //numberToGuess = [6, 1, 5, 4]; //guessNumber = [2, 3, 4, 5]; //numberToGuess = [5, 5, 8, 8]; //guessNumber = [8, 8, 8, 5]; var counted = [false, false, false, false]; //console.log(numberToGuess); //console.log(guessNumber); for (var i = 0; i < numberToGuess.length; i++) { if (guessNumber[i] == numberToGuess[i]) { //console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram'); rams++; if (counted[i]) { sheeps--; } counted[i] = true; } else { for (var j = 0; j < numberToGuess.length; j++) { if (!counted[j] && guessNumber[i] == numberToGuess[j]) { //console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep'); sheeps++; counted[j] = true; break; } } } } manageResult(guessNumber, rams, sheeps); } function manageResult(guessNumber, rams, sheeps) { var ul = $('#guesses ul'); var li = $('<li>'); if (rams < 4) { li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!'); ul.prepend(li); } else { $('#guesses').hide(); $('#userData').fadeIn(); } } function getUserName(name) { //validations return name; } function getUserGuesses() { return guesses; } return { getRandomNumber: getRandomNumber, getUserInput: getUserInput, getUserName: getUserName, getUserGuesses: getUserGuesses, checkNumber: checkNumber } })(); var HighScores = (function () { var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; function addScore(name, guesses) { var user = { name: name, score: guesses } ramsAndSheepsHighScores.push(user); var sortedHighScores = _.chain(ramsAndSheepsHighScores) .sortBy(function (user) { return user.name; }) .sortBy(function (user) { return user.score; }) .first(5).value(); console.log(sortedHighScores); localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores)); } function showAll() { var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || []; var ol = $('#topScores ol'); ol.empty(); _.chain(ramsAndSheepsHighScores) .each(function (user) { var li = $('<li>'); li.text(user.name + ' ' + user.score); ol.append(li); }); } return { addScore: addScore, showAll: showAll } })(); // hack the input for non digits $("#userInput").on({ // When a new character was typed in keydown: function (e) { var key = e.which; // the enter key code if (key == 13) { trigerClick($('#guessBtn')); return false; } // if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) { return false; } }, // When non digits managed to "sneak in" via copy/paste change: function () { // Regex-remove all non digits in the final value this.value = this.value.replace(/\D/g, "") } }); addEventListener('#guessBtn', 'click', function (event) { var $userInput = $('#userInput'); GameManager.getUserInput($userInput[0].value); GameManager.checkNumber(); }); addEventListener('#getNameBtn', 'click', function (event) { var $userName = $('#userName'); var userName = GameManager.getUserName($userName[0].value); HighScores.addScore(userName, GameManager.getUserGuesses()); $('#userData').hide(); HighScores.showAll(); $('#topScores').fadeIn(); }); addEventListener('#resetBtn', 'click', function (event) { var userInput = $('#userInput'); var guessesUl = $('#guesses ul'); guessesUl.empty(); userInput[0].value = ""; GameManager.getRandomNumber(); }); // add the scores HighScores.showAll(); // start the game GameManager.getRandomNumber(); });
/** * process_sqlite.js */ var fs = require('fs-extra') var debug = require('debug')('hostview') var async = require('async') var sqlite = require('sqlite3') var utils = require('./utils') /** * Process a single sqlite file from Hostview. * * We assume that each sqlite file corresponds to a 'session' and * all that all raw data related to this session is in this sqlite file. */ module.exports.process = function (file, db, cb) { if (!file || !db) { return cb(new Error('[process_sqlite] missing arguments')) } // wrap everything in a transaction on the backend db -- // any failure to write there will cancel the file processing // anc call cb with error // the session of this file var session = { file_id: file.id, device_id: file.device_id, started_at: null, ended_at: null, start_event: null, stop_event: null } var readloopESM = function (client, sql, dsttable, dstrow, callback) { var e = null var survey_session = {} var elementsToInsert = [] var loop = function () { if (elementsToInsert.length === 0) { return callback(null,survey_session) // done } var a = elementsToInsert.shift() db._db.insert(dsttable, a).returning('*').row(function (err, res) { if (err) return callback(err) else { survey_session[res.started_at] = res.id loop() } }) } file.db.each(sql, function (err, row) { if (e || err) { // we can't abort the .each(), so just record the error // -- alternative is to do .all() but .each avoids reading // all the data in memory (some tables can be huge !!) if (!e) debug('readloopESM fail: ' + dsttable, err) e = e || err return } // map from sqlite row to backend db row var o = dstrow(row) // track the latest data row just in case if (o.logged_at) { session.ended_at = utils.datemax(session.ended_at, o.logged_at) } elementsToInsert.push(o) }, function (err) { e = e || err loop() }) } // helper func to refactor out the common processing pattern // (read rows from sqlite and insert to the backend fb) var readloop = function (client, sql, dsttable, dstrow, callback) { var e = null // fetch data from the sqlite file.db.each(sql, function (err, row) { if (e || err) { // we can't abort the .each(), so just record the error // -- alternative is to do .all() but .each avoids reading // all the data in memory (some tables can be huge !!) if (!e) debug('readloop fail: ' + dsttable, err) e = e || err return } // map from sqlite row to backend db row var o = dstrow(row) // track the latest data row just in case if (o.logged_at) { session.ended_at = utils.datemax(session.ended_at, o.logged_at) } // add to the backend table client.insert(dsttable, o).run(function (err, res) { // we can't abort the .each(), so just record the error // -- alternative is to do .all() but .each avoids reading // all the data in memory (some tables can be huge !!) // TODO: does this really work or there's some race conditions here ? if (!e && err) debug('readloop insert fail: ' + dsttable, err) e = e || err }) }, function (err) { // .each() completed - pass on any error (or nothing on success) e = e || err debug('readloop complete: ' + dsttable, e) callback(e) }) } // another helper to convert empty strings to nulls var getstr = function (row, col) { if (!row[col] || row[col] === '' || row[col].trim() === '') { return null } return row[col].trim() } // the processing goes as follows: // // 1) uncompress the file to a temp location // 2) open sqlite connection to the temp file // 3) create the session on the backend db // 4) bulk of the work: map sqlite tables to backend db // 5) process other derived tables and data // 6) cleanup temp file async.waterfall([ function (callback) { callback(null, file.path, '/tmp/' + file.device_id) }, utils.uncompress, function (path, callback) { debug('sqlite connect ' + path) file.uncompressed_path = path file.db = new sqlite.Database(path, sqlite.OPEN_READONLY, callback) }, function (callback) { // get session start event (there should only be one) debug('select session start') var sql = `SELECT timestamp started_at, event start_event FROM session WHERE event IN ('start','restart','autorestart','resume','autostart') ORDER BY timestamp ASC` file.db.get(sql, callback) }, function (row, callback) { debug('session start', row) // stop here - there's no start event so the db is (assumed?) empty if (!row) return callback(new Error('no data')) session.started_at = new Date(row.started_at) session.start_event = row.start_event // get session end event (there should only be zero or one) var sql = `SELECT timestamp ended_at, event stop_event FROM session WHERE event IN ('pause','stop','autostop','suspend') ORDER BY timestamp DESC` file.db.get(sql, callback) }, function (row, callback) { debug('session stop', row) if (row) { session.ended_at = new Date(row.ended_at) session.stop_event = row.stop_event } else { // can happen if the hostview cli crashed session.stop_event = 'missing' session.ended_at = session.started_at } // store the session, returns the inserted row db._db.insert('sessions', session).returning('*').row(callback) }, function (row, callback) { session.id = row.id debug('session', session) callback(null) }, function (callback) { debug('wifistats') var sql = `SELECT * FROM wifistats ORDER BY timestamp ASC` readloop(db._db, sql, 'wifi_stats', function (row) { return { session_id: session.id, guid: getstr(row, 'guid'), t_speed: row.tspeed, r_speed: row.rspeed, signal: row.signal, rssi: row.rssi, state: row.state, logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('processes') var sql = `SELECT * FROM procs ORDER BY timestamp ASC LIMIT 10` readloop(db._db, sql, 'processes', function (row) { return { session_id: session.id, pid: row.pid, name: getstr(row, 'name'), memory: row.memory, cpu: row.cpu, logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('powerstates') var sql = `SELECT * FROM powerstate ORDER BY timestamp ASC` readloop(db._db, sql, 'power_states', function (row) { return { session_id: session.id, event: row.event, value: row.value, logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('ports') var sql = `SELECT * FROM ports ORDER BY timestamp ASC` readloop(db._db, sql, 'ports', function (row) { return { session_id: session.id, pid: row.pid, name: getstr(row, 'name'), protocol: row.protocol, source_ip: getstr(row, 'srcip'), destination_ip: getstr(row, 'destip'), source_port: row.srcport, destination_port: row.destport, state: row.state, logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('io') var sql = `SELECT * FROM io ORDER BY timestamp ASC` readloop(db._db, sql, 'io', function (row) { return { session_id: session.id, device: row.device, pid: row.pid, name: getstr(row, 'name'), logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('deviceinfo') var sql = `SELECT * FROM sysinfo ORDER BY timestamp ASC` readloop(db._db, sql, 'device_info', function (row) { return { session_id: session.id, manufacturer: row.manufacturer, product: row.product, operating_system: row.os, cpu: row.cpu, memory_installed: row.totalRAM, hdd_capacity: row.totalHDD, serial_number: row.serial, hostview_version: row.hostview_version, settings_version: row.settings_version, timezone: row.timezone, timezone_offset: row.timezone_offset, logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('netlabels') var sql = `SELECT * FROM netlabel ORDER BY timestamp ASC` readloop(db._db, sql, 'netlabels', function (row) { return { session_id: session.id, guid: getstr(row, 'guid'), gateway: getstr(row, 'gateway'), label: getstr(row, 'label'), logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('browseractivity') var sql = `SELECT * FROM browseractivity ORDER BY timestamp ASC` readloop(db._db, sql, 'browser_activity', function (row) { return { session_id: session.id, browser: getstr(row, 'browser'), location: getstr(row, 'location'), logged_at: new Date(row.timestamp) } }, callback) }, function (callback) { debug('esm') var sql = `SELECT * FROM esm ORDER BY timestamp ASC` readloopESM(db._db, sql, 'surveys', function (row) { return { session_id: session.id, ondemand: row.ondemand, qoe_score: row.qoe_score, duration: row.duration, started_at: new Date(row.timestamp), ended_at: new Date(row.timestamp + row.duration) } }, callback) }, function (survey_session, callback) { debug('esm activity') if (!survey_session) { callback("cannot fill survey info because survey_session is empty (esm activity)" ) //what should we do here? }else{ for (var elem in survey_session) debug('survey_session ' + elem) } var e = null var sql = `SELECT * FROM esm_activity_tags ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var surveyId = survey_session[new Date(row.timestamp)] if (surveyId == null){ debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere }else{ debug('find the corresponding survery with id ' + surveyId) var params = { survey_id : surveyId, process_name : row.appname, process_desc : row.description, tags : row.tags.split(',') } db._db.insert('survey_activity_tags', params).run(function (err, res) { e = e || err })} }, function (err) { // .each complete e = e || err callback(e, survey_session) }) }, function (survey_session, callback) { debug('esm problems') if (!survey_session) { callback("cannot fill survey info because survey_session is empty (esm problems)") //what should we do here? } var e = null var sql = `SELECT * FROM esm_problem_tags ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var surveyId = survey_session[new Date(row.timestamp)] if (surveyId == null){ debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere }else{ var params = { survey_id : surveyId, process_name : row.appname, process_desc : row.description, tags : row.tags.split(',') } db._db.insert('survey_problem_tags', params).run(function (err, res) { e = e || err })} }, function (err) { // .each complete e = e || err callback(e,survey_session) }) }, function (survey_session, callback) { debug('esm activity qoe') if (!survey_session) { callback("cannot fill survey info because survey_session is empty (esm activity qoe)") //what should we do here? } var e = null var sql = `SELECT * FROM esm_activity_qoe ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var surveyId = survey_session[new Date(row.timestamp)] if (surveyId == null){ debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere }else{ var params = { survey_id : surveyId, process_name : row.appname, process_desc : row.description, qoe : row.qoe } db._db.insert('survey_activity_qoe', params).run(function (err, res) { e = e || err })} }, function (err) { // .each complete e = e || err callback(e,survey_session) }) }, function (survey_session, callback) { debug('esm activity importance') if (!survey_session) { callback("cannot fill survey info because survey_session is empty (esm activity importance)") //what should we do here? } var e = null var sql = `SELECT * FROM esm_activity_importance ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var surveyId = survey_session[new Date(row.timestamp)] if (surveyId == null){ debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere }else{ var params = { survey_id : surveyId, process_name : row.appname, process_desc : row.description, importance : row.importance } db._db.insert('survey_activity_importance', params).run(function (err, res) { e = e || err })} }, function (err) { // .each complete e = e || err callback(e) }) }, function (callback) { debug('activity') // reading one ahead so we can log the finish as well var prev var rows = [] var e = null var sql = `SELECT * FROM activity ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err prev = undefined return }; var o = { session_id: session.id, user_name: getstr(row, 'user'), pid: row.pid, name: getstr(row, 'name'), description: getstr(row, 'description'), fullscreen: row.fullscreen, idle: row.idle, logged_at: new Date(row.timestamp) } session.ended_at = utils.datemax(session.ended_at, o.logged_at) if (prev) { // ends when the new event happens prev.finished_at = new Date(row.timestamp) rows.push(prev) } prev = o }, function (err) { // .each complete e = e || err if (prev) { // insert the last activity event prev.finished_at = session.ended_at rows.push(prev) } debug('activies read, found ' + rows.length, e) if (e) return callback(e) // something failed during .each // now add all rows var loop = function () { if (rows.length === 0) return callback(null) // done var a = rows.shift() db._db.insert('activities', a).run(function (err, res) { if (err) return callback(err) loop() }) } loop() }) }, db._db.update('sessions', { ended_at: session.ended_at }) .where({ id: session.id }).run, function (res, callback) { debug('connectivity') // FIXME:: this is really slow on sqlite - there's no indexes // or nothing so takes forever, do as with activity !!! var e = null var sql = `SELECT a.*, l.public_ip, l.reverse_dns, l.asnumber, l.asname, l.countryCode, l.city, l.lat, l.lon, l.connstart l_timestamp, a.timestamp started_at, MIN(b.timestamp) ended_at FROM connectivity a LEFT JOIN connectivity b ON a.mac = b.mac AND b.connected = 0 AND a.timestamp <= b.timestamp LEFT JOIN location l ON a.timestamp = l.connstart WHERE a.connected = 1 GROUP BY a.timestamp ORDER BY a.mac ASC, started_at ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var doconn = function (lid) { var o = { session_id: session.id, location_id: lid, started_at: new Date(row.started_at), ended_at: (row.ended_at ? new Date(row.ended_at) : session.ended_at), guid: getstr(row, 'guid'), friendly_name: getstr(row, 'row.friendlyname'), description: getstr(row, 'row.description'), dns_suffix: getstr(row, 'dnssuffix'), mac: getstr(row, 'mac'), ips: row.ips.split(','), gateways: row.gateways.split(','), dnses: row.dnses.split(','), t_speed: row.tspeed, r_speed: row.rspeed, wireless: row.wireless, profile: getstr(row, 'profile'), ssid: getstr(row, 'ssid'), bssid: getstr(row, 'bssid'), bssid_type: getstr(row, 'bssidtype'), phy_type: getstr(row, 'phytype'), phy_index: row.phyindex, channel: row.channel } db._db.insert('connections', o).run(function (err, res) { e = e || err }) } if (row.public_ip) { // insert/get the location first var l = { public_ip: getstr(row, 'public_ip'), reverse_dns: getstr(row, 'reverse_dns'), asn_number: getstr(row, 'asnumber'), asn_name: getstr(row, 'asname'), country_code: getstr(row, 'countryCode'), city: getstr(row, 'city'), latitude: getstr(row, 'lat'), longitude: getstr(row, 'lon') } var locations = 'locations' db._db.select('*').from(locations) .where(l).rows(function (err, rows) { if (err) return callback(err) if (rows.length === 0) { db._db.insert(locations, row).returning('*').row(function (err, res) { if (err) return callback(err) doconn(res.id) }) } else { doconn(rows[0].id) } }) } else { doconn(null) } }, function (err) { // .each complete e = e || err callback(e) }) }, function (callback) { debug('dnslogs') var isql = ` INSERT INTO dns_logs(connection_id, type, ip, host, protocol, source_ip, destination_ip, source_port, destination_port, logged_at) SELECT c.id, $1, $2, $3, $4, $5, $6, $7, $8, $9 FROM connections c WHERE c.started_at = $10;` var e = null var sql = `SELECT * FROM dns ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var params = [ row.type, row.ip, row.host, row.protocol, row.srcip, row.destip, row.srcport, row.destport, new Date(row.timestamp), new Date(row.connstart) ] db._db.raw(isql, params).run(function (err, res) { e = e || err }) }, function (err) { // .each complete e = e || err callback(e) }) }, function (callback) { debug('httplogs') var isql = ` INSERT INTO http_logs( connection_id, http_verb, http_verb_param, http_status_code, http_host, referer, content_type, content_length, protocol, source_ip, destination_ip, source_port, destination_port, logged_at) SELECT c.id, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13 FROM connections c WHERE c.started_at = $14;` var e = null var sql = `SELECT * FROM http ORDER BY timestamp ASC` file.db.each(sql, function (err, row) { if (e || err) { e = e || err return }; var params = [ getstr(row, 'httpverb'), getstr(row, 'httpverbparam'), getstr(row, 'httpstatuscode'), getstr(row, 'httphost'), getstr(row, 'referer'), getstr(row, 'contenttype'), getstr(row, 'contentlength'), row['protocol'], getstr(row, 'srcip'), getstr(row, 'destip'), row['srcport'], row['destport'], new Date(row.timestamp), new Date(row.connstart) ] db._db.raw(isql, params).run(function (err, res) { e = e || err }) }, function (err) { // .each complete e = e || err callback(e) }) } /*, TODO: these are working but do we need these ? function(callback) { debug('activity_io'); // Count foreground/background io for activities (running apps) // // FIXME: interpretation of the count really depends on the polling // interval, it would make more sense to store the real duration // instead no ... ?? // var sql = `INSERT INTO activity_io SELECT a.id, a.session_id, a.name, a.description, a.idle, a.pid, a.logged_at, a.finished_at, COUNT(io.logged_at) FROM activities a LEFT JOIN io ON io.logged_at BETWEEN a.logged_at AND a.finished_at AND io.pid = a.pid AND io.name = a.name AND io.session_id = a.session_id WHERE a.session_id = $1 GROUP BY a.id ORDER BY a.id;`; db._db.raw(sql, [session.id]).run(callback); }, function(res, callback) { debug('processes_running'); // Fill the processes_running table // TODO: what's with the intervals in the queries .. ? var sql = `INSERT INTO processes_running SELECT $1::integer as device_id, $2::integer as session_id, p.dname, ( SELECT COUNT(*) FROM ( SELECT 1 AS count FROM processes WHERE name = p.dname AND session_id = $2::integer AND logged_at BETWEEN $3::timestamp AND $4::timestamp GROUP BY date_trunc('minute',logged_at + interval '30 seconds') ) sq )::integer AS process_running, ( SELECT EXTRACT ( EPOCH FROM ( LEAST(date_trunc('minute',ended_at + interval '30 seconds'), $4::timestamp) - GREATEST(date_trunc('minute',started_at + interval '30 seconds'), $3::timestamp) ) )/60 FROM sessions WHERE id = $2::integer ) AS session_running, $3::timestamp as start_at, $4::timestamp as end_at FROM( SELECT DISTINCT name AS dname FROM processes WHERE session_id = $2::integer ) p`; // run the above query for 1h bins from session start to end var bin = 60 * 60 * 1000; var from = Math.floor(session.started_at.getTime()/bin)*bin; var to = Math.floor(session.ended_at.getTime()/bin+1)*bin; var loop = function(d) { if (d>=to) return callback(null); var args = [session.device_id, session.id, new Date(d), new Date(d+bin)]; db._db.raw(sql, args).run(function(err,res) { if (err) return callback(err); // stop on error process.nextTick(loop,d+bin); }); }; loop(from); } */ ], function (err) { // if we receive error here, something went wrong above ... async.waterfall([ function (callback) { if (err) { debug('failed to process session ' + session.id, err) if (session.id) { db._db.delete('sessions').where({ id: session.id }).run(callback) } callback(err) } else { debug('session inserted ' + session.id) callback(null, null) } }, function (res, callback) { if (file.db) { // sqlite conn file.db.close(function () { callback(null) }) } else { callback(null) } }, function (callback) { if (file.uncompressed_path) { // tmp file fs.unlink(file.uncompressed_path, function () { callback(null) }) } else { callback(null) } } ], function () { // return the original error (if any) return cb(err) }) // cleanup waterfall }) // main watefall } // process
version https://git-lfs.github.com/spec/v1 oid sha256:082a71326f3ffc5d4a12f1e2d1226bde6726d7e65fd21e9e633e1aa7bdd656d8 size 117145
define(['jquery', 'pubsub'], function($, pubsub) { function AudioPlayer(audio){ this.audio = audio; this._initSubscribe(); this.startPos = 0; this.endPos = 0; this.loopEnabled = false; } AudioPlayer.prototype._initSubscribe = function() { var self = this; $.subscribe("AudioCursor-clickedAudio", function(el, posCursor) { self.startPos = posCursor; self.audio.disableLoop(); }); $.subscribe("AudioCursor-selectedAudio", function(el, startPos, endPos) { self.startPos = startPos; self.endPos = endPos; self.audio.loop(startPos, endPos); }); $.subscribe("ToPlayer-play", function() { self.audio.play(self.startPos); }); $.subscribe("ToPlayer-pause", function() { self.startPos = null; self.audio.pause(); }); $.subscribe("Audio-end", function(){ self.startPos = null; }); $.subscribe("ToPlayer-stop", function() { self.startPos = null; self.audio.stop(); }); $.subscribe('ToAudioPlayer-disable', function(){ self.audio.disable(true); //true to not disable audio }); $.subscribe('ToAudioPlayer-enable', function(){ self.audio.enable(true); //true to not disable audio }); $.subscribe('ToPlayer-playPause', function() { if (self.audio.isPlaying){ $.publish('ToPlayer-pause'); } else { self.audio.play(self.startPos); } }); $.subscribe('ToPlayer-toggleLoop', function() { var toggle; if (self.loopEnabled){ toggle = self.audio.disableLoopSong(); }else{ toggle = self.audio.enableLoopSong(); } if (toggle){ self.loopEnabled = !self.loopEnabled; $.publish('PlayerModel-toggleLoop', self.loopEnabled); } }); }; return AudioPlayer; });
export class Schema { constructor(){ } createErrorMessage(schemaErrorObj, root){ let {errors, path} = schemaErrorObj; let pathName = path.replace('$root', root); let errorList = errors.reduce((errorListTemp, error, index)=>{ return `${errorListTemp} ${index+1}. ${error}` }, '') let errorMessage = ` Schema Error: Path: ${pathName} Errors: ${errorList} ` return errorMessage; } };
// Welcome. In this kata, you are asked to square every digit of a number. // // For example, if we run 9119 through the function, 811181 will come out. // // Note: The function accepts an integer and returns an integer function squareDigits(num){ let digits = (""+num).split(""); let arr=[]; for (var i = 0; i < digits.length; i++) { arr.push(Math.pow(digits[i],2)); } return +arr.join('') } //top codewars solution function squareDigits(num){ return Number(('' + num).split('').map(function (val) { return val * val;}).join('')); }
(function( $ ) { 'use strict'; var that; var fgj2wp = { plugin_id: 'fgj2wp', fatal_error: '', /** * Manage the behaviour of the Skip Media checkbox */ hide_unhide_media: function() { $("#media_import_box").toggle(!$("#skip_media").is(':checked')); }, /** * Security question before deleting WordPress content */ check_empty_content_option: function () { var confirm_message; var action = $('input:radio[name=empty_action]:checked').val(); switch ( action ) { case 'newposts': confirm_message = objectL10n.delete_new_posts_confirmation_message; break; case 'all': confirm_message = objectL10n.delete_all_confirmation_message; break; default: alert(objectL10n.delete_no_answer_message); return false; break; } return confirm(confirm_message); }, /** * Start the logger */ start_logger: function() { that.stop_logger_triggered = false; clearTimeout(that.timeout); that.timeout = setTimeout(that.update_display, 1000); }, /** * Stop the logger */ stop_logger: function() { that.stop_logger_triggered = true; }, /** * Update the display */ update_display: function() { that.timeout = setTimeout(that.update_display, 1000); // Actions if ( $("#logger_autorefresh").is(":checked") ) { that.display_logs(); } that.update_progressbar(); that.update_wordpress_info(); if ( that.stop_logger_triggered ) { clearTimeout(that.timeout); } }, /** * Display the logs */ display_logs: function() { $.ajax({ url: objectPlugin.log_file_url, cache: false }).done(function(result) { $("#logger").html(''); result.split("\n").forEach(function(row) { if ( row.substr(0, 7) === '[ERROR]' || row === 'IMPORT STOPPED BY USER') { row = '<span class="error_msg">' + row + '</span>'; // Mark the errors in red } // Test if the import is complete else if ( row === 'IMPORT COMPLETE' ) { row = '<span class="complete_msg">' + row + '</span>'; // Mark the complete message in green $('#action_message').html(objectL10n.import_complete) .removeClass('failure').addClass('success'); } $("#logger").append(row + "<br />\n"); }); $("#logger").append('<span class="error_msg">' + that.fatal_error + '</span>' + "<br />\n"); }); }, /** * Update the progressbar */ update_progressbar: function() { $.ajax({ url: objectPlugin.progress_url, cache: false, dataType: 'json' }).done(function(result) { // Move the progress bar var progress = Number(result.current) / Number(result.total) * 100; $('#progressbar').progressbar('option', 'value', progress); }); }, /** * Update WordPress database info */ update_wordpress_info: function() { var data = 'action=' + that.plugin_id + '_import&plugin_action=update_wordpress_info'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function(result) { $('#fgj2wp_database_info_content').html(result); }); }, /** * Empty WordPress content * * @returns {Boolean} */ empty_wp_content: function() { if (that.check_empty_content_option()) { // Start displaying the logs that.start_logger(); $('#empty').attr('disabled', 'disabled'); // Disable the button var data = $('#form_empty_wordpress_content').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=empty'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function() { that.stop_logger(); $('#empty').removeAttr('disabled'); // Enable the button alert(objectL10n.content_removed_from_wordpress); }); } return false; }, /** * Test the database connection * * @returns {Boolean} */ test_database: function() { // Start displaying the logs that.start_logger(); $('#test_database').attr('disabled', 'disabled'); // Disable the button var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=test_database'; $.ajax({ method: 'POST', url: ajaxurl, data: data, dataType: 'json' }).done(function(result) { that.stop_logger(); $('#test_database').removeAttr('disabled'); // Enable the button if ( typeof result.message !== 'undefined' ) { $('#database_test_message').toggleClass('success', result.status === 'OK') .toggleClass('failure', result.status !== 'OK') .html(result.message); } }).fail(function(result) { that.stop_logger(); $('#test_database').removeAttr('disabled'); // Enable the button that.fatal_error = result.responseText; }); return false; }, /** * Test the FTP connection * * @returns {Boolean} */ test_ftp: function() { // Start displaying the logs that.start_logger(); $('#test_ftp').attr('disabled', 'disabled'); // Disable the button var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=test_ftp'; $.ajax({ method: 'POST', url: ajaxurl, data: data, dataType: 'json' }).done(function(result) { that.stop_logger(); $('#test_ftp').removeAttr('disabled'); // Enable the button if ( typeof result.message !== 'undefined' ) { $('#ftp_test_message').toggleClass('success', result.status === 'OK') .toggleClass('failure', result.status !== 'OK') .html(result.message); } }).fail(function(result) { that.stop_logger(); $('#test_ftp').removeAttr('disabled'); // Enable the button that.fatal_error = result.responseText; }); return false; }, /** * Save the settings * * @returns {Boolean} */ save: function() { // Start displaying the logs that.start_logger(); $('#save').attr('disabled', 'disabled'); // Disable the button var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=save'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function() { that.stop_logger(); $('#save').removeAttr('disabled'); // Enable the button alert(objectL10n.settings_saved); }); return false; }, /** * Start the import * * @returns {Boolean} */ start_import: function() { that.fatal_error = ''; // Start displaying the logs that.start_logger(); // Disable the import button that.import_button_label = $('#import').val(); $('#import').val(objectL10n.importing).attr('disabled', 'disabled'); // Show the stop button $('#stop-import').show(); // Clear the action message $('#action_message').html(''); // Run the import var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=import'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function(result) { if (result) { that.fatal_error = result; } that.stop_logger(); that.reactivate_import_button(); }); return false; }, /** * Reactivate the import button * */ reactivate_import_button: function() { $('#import').val(that.import_button_label).removeAttr('disabled'); $('#stop-import').hide(); }, /** * Stop import * * @returns {Boolean} */ stop_import: function() { $('#stop-import').attr('disabled', 'disabled'); $('#action_message').html(objectL10n.import_stopped_by_user) .removeClass('success').addClass('failure'); // Stop the import var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=stop_import'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function() { $('#stop-import').removeAttr('disabled'); // Enable the button that.reactivate_import_button(); }); return false; }, /** * Modify the internal links * * @returns {Boolean} */ modify_links: function() { // Start displaying the logs that.start_logger(); $('#modify_links').attr('disabled', 'disabled'); // Disable the button var data = $('#form_modify_links').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=modify_links'; $.ajax({ method: "POST", url: ajaxurl, data: data }).done(function(result) { if (result) { that.fatal_error = result; } that.stop_logger(); $('#modify_links').removeAttr('disabled'); // Enable the button alert(objectL10n.internal_links_modified); }); return false; } }; /** * Actions to run when the DOM is ready */ $(function() { that = fgj2wp; $('#progressbar').progressbar({value : 0}); // Skip media checkbox $("#skip_media").bind('click', that.hide_unhide_media); that.hide_unhide_media(); // Empty WordPress content confirmation $("#form_empty_wordpress_content").bind('submit', that.check_empty_content_option); // Partial import checkbox $("#partial_import").hide(); $("#partial_import_toggle").click(function() { $("#partial_import").slideToggle("slow"); }); // Empty button $('#empty').click(that.empty_wp_content); // Test database button $('#test_database').click(that.test_database); // Test FTP button $('#test_ftp').click(that.test_ftp); // Save settings button $('#save').click(that.save); // Import button $('#import').click(that.start_import); // Stop import button $('#stop-import').click(that.stop_import); // Modify links button $('#modify_links').click(that.modify_links); // Display the logs $('#logger_autorefresh').click(that.display_logs); }); /** * Actions to run when the window is loaded */ $( window ).load(function() { }); })( jQuery );
$(function() { $("#content").focus(function() { $(this).animate({"height": "85px",}, "fast" ); $("#button_block").slideDown("fast"); return false; }); $("#cancel").click(function() { $("#content").animate({"height": "30px",}, "fast" ); $("#button_block").slideUp("fast"); return false; }); function dragDrop(drag,i,j){ $(drag+i).draggable({ helper: 'clone', revert : function(event, ui) { // on older version of jQuery use "draggable" // $(this).data("draggable") // on 2.x versions of jQuery use "ui-draggable" // $(this).data("ui-draggable") $(this).data("uiDraggable").originalPosition = { top : 0, left : 0 }; // return boolean return !event; // that evaluate like this: // return event !== false ? false : true; } }); if(j==0){ $('#dropzone'+j).droppable({ tolerance: 'touch', activeClass: 'ui-state-default', hoverClass: 'ui-state-hover', drop: function(event, ui) { var id = ui.draggable.attr("id"); var res = id.substr(9,9); var post = parseInt(res); text = $('div#contenttext'+post).text(); // alert(id); $('#text').val(text); $.ajax({ type: "POST", url: "index.php", data: text, success:function(data){ $( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>"); $( "#button" ).trigger( "click" ); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); //throw any errors } }); console.log(text); } }); } else { $('#dropzone'+j).droppable({ tolerance: 'touch', activeClass: 'ui-state-default', hoverClass: 'ui-state-hover'+j, drop: function(event, ui) { var id = ui.draggable.attr("id"); var res = id.substr(9,9); var post = parseInt(res); text = $('div#contenttext'+post).text(); // alert(id); $('#text').val(text); $.ajax({ type: "POST", url: "index.php", data: text, success:function(data){ $( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>"); $( "#button" ).trigger( "click" ); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); //throw any errors } }); console.log(text); } }); } } for (i=0;i<10; i++) { dragDrop("#draggable",i,0); dragDrop("#draggabletw",i,1); } $('#publish').click( function(){ $.ajax({ type: "POST", url: "index.php", data: $("#form2").serialize(), // serializes the form's elements. beforeSend: function(){ }, success: function(data) { alert(data); // show response from the php script. } }); } ); /*$("#form2").submit(function() { var url = "publish.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: $("#form2").serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); return false; // avoid to execute the actual submit of the form. });*/ });
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; $(".signin").parent("section").css("height", "100%"); // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/timeline'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/signin'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/timeline'); }).error(function(response) { $scope.error = response.message; }); }; } ]);
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ 'use strict'; if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); var binarySearch = require('./binary-search'); var ArraySet = require('./array-set').ArraySet; var base64VLQ = require('./base64-vlq'); var quickSort = require('./quick-sort').quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function (aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function get() { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function get() { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } if (!this._sources.has(needle.source)) { return []; } needle.source = this._sources.indexOf(needle.source); var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. sources = sources.map(util.normalize); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping(); destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function get() { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util.relative(this.sourceRoot, source); } if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; } source = this._sources.indexOf(source); var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) }; }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function get() { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } }; return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return needle.generatedColumn - section.generatedOffset.generatedColumn; }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[i]; var source = section.consumer._sources.at(mapping.source); if (section.consumer.sourceRoot !== null) { source = util.join(section.consumer.sourceRoot, source); } this._sources.add(source); source = this._sources.indexOf(source); var name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.column + (section.generatedOffset.generatedLine === mapping.generatedLine) ? section.generatedOffset.generatedColumn - 1 : 0, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } }; }; quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; }); //# sourceMappingURL=source-map-consumer-compiled.js.map
export const x = {"viewBox":"0 0 12 16","children":[{"name":"path","attribs":{"fill-rule":"evenodd","d":"M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"},"children":[]}],"attribs":{}};
// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*- // vim:set ft=javascript ts=2 sw=2 sts=2 cindent: require('./lib/webfont'); //jquery var $ = require('jquery'); var Util = (function(window, undefined) { var fontLoadTimeout = 5000; // 5 seconds var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var isMac = navigator.platform == 'MacIntel'; // XXX should we go broader? var cmp = function(a,b) { return a < b ? -1 : a > b ? 1 : 0; }; var cmpArrayOnFirstElement = function(a,b) { a = a[0]; b = b[0]; return a < b ? -1 : a > b ? 1 : 0; }; var unitAgo = function(n, unit) { if (n == 1) return "" + n + " " + unit + " ago"; return "" + n + " " + unit + "s ago"; }; var formatTimeAgo = function(time) { if (time == -1000) { return "never"; // FIXME make the server return the server time! } var nowDate = new Date(); var now = nowDate.getTime(); var diff = Math.floor((now - time) / 1000); if (!diff) return "just now"; if (diff < 60) return unitAgo(diff, "second"); diff = Math.floor(diff / 60); if (diff < 60) return unitAgo(diff, "minute"); diff = Math.floor(diff / 60); if (diff < 24) return unitAgo(diff, "hour"); diff = Math.floor(diff / 24); if (diff < 7) return unitAgo(diff, "day"); if (diff < 28) return unitAgo(Math.floor(diff / 7), "week"); var thenDate = new Date(time); var result = thenDate.getDate() + ' ' + monthNames[thenDate.getMonth()]; if (thenDate.getYear() != nowDate.getYear()) { result += ' ' + thenDate.getFullYear(); } return result; }; var realBBox = function(span) { var box = span.rect.getBBox(); var chunkTranslation = span.chunk.translation; var rowTranslation = span.chunk.row.translation; box.x += chunkTranslation.x + rowTranslation.x; box.y += chunkTranslation.y + rowTranslation.y; return box; }; var escapeHTML = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }; var escapeHTMLandQuotes = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;'); }; var escapeHTMLwithNewlines = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br/>'); }; var escapeQuotes = function(str) { // we only use double quotes for HTML attributes return str.replace(/\"/g,'&quot;'); }; var getSpanLabels = function(spanTypes, spanType) { var type = spanTypes[spanType]; return type && type.labels || []; }; var spanDisplayForm = function(spanTypes, spanType) { var labels = getSpanLabels(spanTypes, spanType); return labels[0] || spanType; }; var getArcLabels = function(spanTypes, spanType, arcType, relationTypesHash) { var type = spanTypes[spanType]; var arcTypes = type && type.arcs || []; var arcDesc = null; // also consider matches without suffix number, if any var noNumArcType; if (arcType) { var splitType = arcType.match(/^(.*?)(\d*)$/); noNumArcType = splitType[1]; } $.each(arcTypes, function(arcno, arcDescI) { if (arcDescI.type == arcType || arcDescI.type == noNumArcType) { arcDesc = arcDescI; return false; } }); // fall back to relation types for unconfigured or missing def if (!arcDesc) { arcDesc = $.extend({}, relationTypesHash[arcType] || relationTypesHash[noNumArcType]); } return arcDesc && arcDesc.labels || []; }; var arcDisplayForm = function(spanTypes, spanType, arcType, relationTypesHash) { var labels = getArcLabels(spanTypes, spanType, arcType, relationTypesHash); return labels[0] || arcType; }; // TODO: switching to use of $.param(), this function should // be deprecated and removed. var objectToUrlStr = function(o) { a = []; $.each(o, function(key,value) { a.push(key+"="+encodeURIComponent(value)); }); return a.join("&"); }; // color name RGB list, converted from // http://www.w3schools.com/html/html_colornames.asp // with perl as // perl -e 'print "var colors = {\n"; while(<>) { /(\S+)\s+\#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})\s*/i or die "Failed to parse $_"; ($r,$g,$b)=(hex($2),hex($3),hex($4)); print " '\''",lc($1),"'\'':\[$r,$g,$b\],\n" } print "};\n" ' var colors = { 'aliceblue':[240,248,255], 'antiquewhite':[250,235,215], 'aqua':[0,255,255], 'aquamarine':[127,255,212], 'azure':[240,255,255], 'beige':[245,245,220], 'bisque':[255,228,196], 'black':[0,0,0], 'blanchedalmond':[255,235,205], 'blue':[0,0,255], 'blueviolet':[138,43,226], 'brown':[165,42,42], 'burlywood':[222,184,135], 'cadetblue':[95,158,160], 'chartreuse':[127,255,0], 'chocolate':[210,105,30], 'coral':[255,127,80], 'cornflowerblue':[100,149,237], 'cornsilk':[255,248,220], 'crimson':[220,20,60], 'cyan':[0,255,255], 'darkblue':[0,0,139], 'darkcyan':[0,139,139], 'darkgoldenrod':[184,134,11], 'darkgray':[169,169,169], 'darkgrey':[169,169,169], 'darkgreen':[0,100,0], 'darkkhaki':[189,183,107], 'darkmagenta':[139,0,139], 'darkolivegreen':[85,107,47], 'darkorange':[255,140,0], 'darkorchid':[153,50,204], 'darkred':[139,0,0], 'darksalmon':[233,150,122], 'darkseagreen':[143,188,143], 'darkslateblue':[72,61,139], 'darkslategray':[47,79,79], 'darkslategrey':[47,79,79], 'darkturquoise':[0,206,209], 'darkviolet':[148,0,211], 'deeppink':[255,20,147], 'deepskyblue':[0,191,255], 'dimgray':[105,105,105], 'dimgrey':[105,105,105], 'dodgerblue':[30,144,255], 'firebrick':[178,34,34], 'floralwhite':[255,250,240], 'forestgreen':[34,139,34], 'fuchsia':[255,0,255], 'gainsboro':[220,220,220], 'ghostwhite':[248,248,255], 'gold':[255,215,0], 'goldenrod':[218,165,32], 'gray':[128,128,128], 'grey':[128,128,128], 'green':[0,128,0], 'greenyellow':[173,255,47], 'honeydew':[240,255,240], 'hotpink':[255,105,180], 'indianred':[205,92,92], 'indigo':[75,0,130], 'ivory':[255,255,240], 'khaki':[240,230,140], 'lavender':[230,230,250], 'lavenderblush':[255,240,245], 'lawngreen':[124,252,0], 'lemonchiffon':[255,250,205], 'lightblue':[173,216,230], 'lightcoral':[240,128,128], 'lightcyan':[224,255,255], 'lightgoldenrodyellow':[250,250,210], 'lightgray':[211,211,211], 'lightgrey':[211,211,211], 'lightgreen':[144,238,144], 'lightpink':[255,182,193], 'lightsalmon':[255,160,122], 'lightseagreen':[32,178,170], 'lightskyblue':[135,206,250], 'lightslategray':[119,136,153], 'lightslategrey':[119,136,153], 'lightsteelblue':[176,196,222], 'lightyellow':[255,255,224], 'lime':[0,255,0], 'limegreen':[50,205,50], 'linen':[250,240,230], 'magenta':[255,0,255], 'maroon':[128,0,0], 'mediumaquamarine':[102,205,170], 'mediumblue':[0,0,205], 'mediumorchid':[186,85,211], 'mediumpurple':[147,112,216], 'mediumseagreen':[60,179,113], 'mediumslateblue':[123,104,238], 'mediumspringgreen':[0,250,154], 'mediumturquoise':[72,209,204], 'mediumvioletred':[199,21,133], 'midnightblue':[25,25,112], 'mintcream':[245,255,250], 'mistyrose':[255,228,225], 'moccasin':[255,228,181], 'navajowhite':[255,222,173], 'navy':[0,0,128], 'oldlace':[253,245,230], 'olive':[128,128,0], 'olivedrab':[107,142,35], 'orange':[255,165,0], 'orangered':[255,69,0], 'orchid':[218,112,214], 'palegoldenrod':[238,232,170], 'palegreen':[152,251,152], 'paleturquoise':[175,238,238], 'palevioletred':[216,112,147], 'papayawhip':[255,239,213], 'peachpuff':[255,218,185], 'peru':[205,133,63], 'pink':[255,192,203], 'plum':[221,160,221], 'powderblue':[176,224,230], 'purple':[128,0,128], 'red':[255,0,0], 'rosybrown':[188,143,143], 'royalblue':[65,105,225], 'saddlebrown':[139,69,19], 'salmon':[250,128,114], 'sandybrown':[244,164,96], 'seagreen':[46,139,87], 'seashell':[255,245,238], 'sienna':[160,82,45], 'silver':[192,192,192], 'skyblue':[135,206,235], 'slateblue':[106,90,205], 'slategray':[112,128,144], 'slategrey':[112,128,144], 'snow':[255,250,250], 'springgreen':[0,255,127], 'steelblue':[70,130,180], 'tan':[210,180,140], 'teal':[0,128,128], 'thistle':[216,191,216], 'tomato':[255,99,71], 'turquoise':[64,224,208], 'violet':[238,130,238], 'wheat':[245,222,179], 'white':[255,255,255], 'whitesmoke':[245,245,245], 'yellow':[255,255,0], 'yellowgreen':[154,205,50], }; // color parsing function originally from // http://plugins.jquery.com/files/jquery.color.js.txt // (with slight modifications) // Parse strings looking for color tuples [255,255,255] var rgbNumRE = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var rgbPercRE = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/; var rgbHash6RE = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/; var rgbHash3RE = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/; var strToRgb = function(color) { var result; // Check if we're already dealing with an array of colors // if ( color && color.constructor == Array && color.length == 3 ) // return color; // Look for rgb(num,num,num) if (result = rgbNumRE.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])]; // Look for rgb(num%,num%,num%) if (result = rgbPercRE.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; // Look for #a0b1c2 if (result = rgbHash6RE.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = rgbHash3RE.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Otherwise, we're most likely dealing with a named color return colors[$.trim(color).toLowerCase()]; }; var rgbToStr = function(rgb) { // TODO: there has to be a better way, even in JS var r = Math.floor(rgb[0]).toString(16); var g = Math.floor(rgb[1]).toString(16); var b = Math.floor(rgb[2]).toString(16); // pad r = r.length < 2 ? '0' + r : r; g = g.length < 2 ? '0' + g : g; b = b.length < 2 ? '0' + b : b; return ('#'+r+g+b); }; // Functions rgbToHsl and hslToRgb originally from // http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript // implementation of functions in Wikipedia // (with slight modifications) // RGB to HSL color conversion var rgbToHsl = function(rgb) { var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; }; var hue2rgb = function(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; }; var hslToRgb = function(hsl) { var h = hsl[0], s = hsl[1], l = hsl[2]; var r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [r * 255, g * 255, b * 255]; }; var adjustLightnessCache = {}; // given color string and -1<=adjust<=1, returns color string // where lightness (in the HSL sense) is adjusted by the given // amount, the larger the lighter: -1 gives black, 1 white, and 0 // the given color. var adjustColorLightness = function(colorstr, adjust) { if (!(colorstr in adjustLightnessCache)) { adjustLightnessCache[colorstr] = {} } if (!(adjust in adjustLightnessCache[colorstr])) { var rgb = strToRgb(colorstr); if (rgb === undefined) { // failed color string conversion; just return the input adjustLightnessCache[colorstr][adjust] = colorstr; } else { var hsl = rgbToHsl(rgb); if (adjust > 0.0) { hsl[2] = 1.0 - ((1.0-hsl[2])*(1.0-adjust)); } else { hsl[2] = (1.0+adjust)*hsl[2]; } var lightRgb = hslToRgb(hsl); adjustLightnessCache[colorstr][adjust] = rgbToStr(lightRgb); } } return adjustLightnessCache[colorstr][adjust]; }; // Partially stolen from: http://documentcloud.github.com/underscore/ // MIT-License // TODO: Mention in LICENSE.md var isEqual = function(a, b) { // Check object identity. if (a === b) return true; // Different types? var atype = typeof(a), btype = typeof(b); if (atype != btype) return false; // Basic equality test (watch out for coercions). if (a == b) return true; // One is falsy and the other truthy. if ((!a && b) || (a && !b)) return false; // If a is not an object by this point, we can't handle it. if (atype !== 'object') return false; // Check for different array lengths before comparing contents. if (a.length && (a.length !== b.length)) return false; // Nothing else worked, deep compare the contents. for (var key in b) if (!(key in a)) return false; // Recursive comparison of contents. for (var key in a) if (!(key in b) || !isEqual(a[key], b[key])) return false; return true; }; var keyValRE = /^([^=]+)=(.*)$/; // key=value var isDigitsRE = /^[0-9]+$/; var deparam = function(str) { var args = str.split('&'); var len = args.length; if (!len) return null; var result = {}; for (var i = 0; i < len; i++) { var parts = args[i].match(keyValRE); if (!parts || parts.length != 3) break; var val = []; var arr = parts[2].split(','); var sublen = arr.length; for (var j = 0; j < sublen; j++) { var innermost = []; // map empty arguments ("" in URL) to empty arrays // (innermost remains []) if (arr[j].length) { var arrsplit = arr[j].split('~'); var subsublen = arrsplit.length; for (var k = 0; k < subsublen; k++) { if(arrsplit[k].match(isDigitsRE)) { // convert digits into ints ... innermost.push(parseInt(arrsplit[k], 10)); } else { // ... anything else remains a string. innermost.push(arrsplit[k]); } } } val.push(innermost); } result[parts[1]] = val; } return result; }; var paramArray = function(val) { val = val || []; var len = val.length; var arr = []; for (var i = 0; i < len; i++) { if ($.isArray(val[i])) { arr.push(val[i].join('~')); } else { // non-array argument; this is an error from the caller console.error('param: Error: received non-array-in-array argument [', i, ']', ':', val[i], '(fix caller)'); } } return arr; }; var param = function(args) { if (!args) return ''; var vals = []; for (var key in args) { if (args.hasOwnProperty(key)) { var val = args[key]; if (val == undefined) { console.error('Error: received argument', key, 'with value', val); continue; } // values normally expected to be arrays, but some callers screw // up, so check if ($.isArray(val)) { var arr = paramArray(val); vals.push(key + '=' + arr.join(',')); } else { // non-array argument; this is an error from the caller console.error('param: Error: received non-array argument', key, ':', val, '(fix caller)'); } } } return vals.join('&'); }; var profiles = {}; var profileStarts = {}; var profileOn = false; var profileEnable = function(on) { if (on === undefined) on = true; profileOn = on; }; // profileEnable var profileClear = function() { if (!profileOn) return; profiles = {}; profileStarts = {}; }; // profileClear var profileStart = function(label) { if (!profileOn) return; profileStarts[label] = new Date(); }; // profileStart var profileEnd = function(label) { if (!profileOn) return; var profileElapsed = new Date() - profileStarts[label] if (!profiles[label]) profiles[label] = 0; profiles[label] += profileElapsed; }; // profileEnd var profileReport = function() { if (!profileOn) return; if (window.console) { $.each(profiles, function(label, time) { console.log("profile " + label, time); }); console.log("-------"); } }; // profileReport var fontsLoaded = false; var fontNotifyList = false; var proceedWithFonts = function() { if (fontsLoaded) return; fontsLoaded = true; $.each(fontNotifyList, function(dispatcherNo, dispatcher) { dispatcher.post('triggerRender'); }); fontNotifyList = null; }; var loadFonts = function(webFontURLs, dispatcher) { if (fontsLoaded) { dispatcher.post('triggerRender'); return; } if (fontNotifyList) { fontNotifyList.push(dispatcher); return; } fontNotifyList = [dispatcher]; var families = []; $.each(webFontURLs, function(urlNo, url) { if (/Astloch/i.test(url)) families.push('Astloch'); else if (/PT.*Sans.*Caption/i.test(url)) families.push('PT Sans Caption'); else if (/Liberation.*Sans/i.test(url)) families.push('Liberation Sans'); }); webFontURLs = { families: families, urls: webFontURLs } var webFontConfig = { custom: webFontURLs, active: proceedWithFonts, inactive: proceedWithFonts, fontactive: function(fontFamily, fontDescription) { // Note: Enable for font debugging // console.log("font active: ", fontFamily, fontDescription); }, fontloading: function(fontFamily, fontDescription) { // Note: Enable for font debugging // console.log("font loading:", fontFamily, fontDescription); }, }; WebFont.load(webFontConfig); setTimeout(function() { if (!fontsLoaded) { console.error('Timeout in loading fonts'); proceedWithFonts(); } }, fontLoadTimeout); }; var areFontsLoaded = function() { return fontsLoaded; }; return { profileEnable: profileEnable, profileClear: profileClear, profileStart: profileStart, profileEnd: profileEnd, profileReport: profileReport, formatTimeAgo: formatTimeAgo, realBBox: realBBox, getSpanLabels: getSpanLabels, spanDisplayForm: spanDisplayForm, getArcLabels: getArcLabels, arcDisplayForm: arcDisplayForm, escapeQuotes: escapeQuotes, escapeHTML: escapeHTML, escapeHTMLandQuotes: escapeHTMLandQuotes, escapeHTMLwithNewlines: escapeHTMLwithNewlines, cmp: cmp, rgbToHsl: rgbToHsl, hslToRgb: hslToRgb, adjustColorLightness: adjustColorLightness, objectToUrlStr: objectToUrlStr, isEqual: isEqual, paramArray: paramArray, param: param, deparam: deparam, isMac: isMac, loadFonts: loadFonts, areFontsLoaded: areFontsLoaded, }; })(window); module.exports = Util;
(function(angular) { 'use strict'; //-----------------------------Controller Start------------------------------------ function AddBrandModalController($state, $http) { var ctrl = this; ctrl.init = function() { ctrl.brandDetail = (ctrl.resolve && ctrl.resolve.details) || {}; } ctrl.save = function(brand) { var data = { brandName: brand } $http({ url: "admin/addBrand", method: "POST", data: JSON.stringify(data), dataType: JSON }).then(function(response) { ctrl.modalInstance.close({ action: 'update'}); }) .catch(function(error) { console.log("Error while adding brand modal") }) } ctrl.cancel = function() { ctrl.modalInstance.close(); }; ctrl.init(); //------------------------------------Controller End------------------------------------ } angular.module('addBrandModalModule') .component('addBrandModalComponent', { templateUrl: 'admin/addBrand-modal/addBrand-modal.template.html', controller: ['$state', '$http', AddBrandModalController], bindings: { modalInstance: '<', resolve: '<' } }); })(window.angular);
$(function() { $('input:not(.button)').blur(function() { if (validation.isFieldValid(this.id, $(this).val())) { $('.error').text('').hide(); } else { $('.error').text(validation.form[this.id].errorMessage).show(); } }); });
'use strict'; /* Service to retrieve data from backend (CouchDB store) */ pissalotApp.factory('pissalotCouchService', function ($resource) { return $resource('http://192.168.1.4:8080/measurement/:listType',{ listType: '@listType' }, { get: { method: 'GET', isArray: false } }); });
const assert = require("assert"); describe("chain of iterators", function() { it("should conform to ES", function() { let finallyCalledSrc = 0; let finallyCalled1 = 0; let finallyCalled2 = 0; let cb; let p1 = new Promise(i => (cb = i)); let tasks = []; let cbtask; let p2 = { then(next) { tasks.push(next); cbtask(); } }; async function scheduler() { await new Promise(i => (cbtask = i)); tasks.pop()("t1"); } scheduler(); async function* src() { try { yield await p1; yield await p2; assert.fail("never"); } finally { finallyCalledSrc++; } } async function* a1() { try { for await (const i of src()) yield `a1:${i}`; assert.fail("never"); } finally { finallyCalled1 = true; } assert.fail("never"); } async function* a2() { try { yield* a1(); assert.fail("never"); } finally { finallyCalled2 = true; } } async function* a3() { const v = a2(); try { for (let i; !(i = await v.next()).done; ) { yield `a3:${i.value}`; } assert.fail("never"); } finally { await v.return(); } return 2; } async function a4() { const v = a3(); const i1 = await v.next(); assert.ok(!i1.done); assert.equal(i1.value, "a3:a1:hi"); const n = v.next(); const i2 = await n; assert.ok(!i2.done); assert.equal(i2.value, "a3:a1:t1"); const i3 = await v.return(4); assert.ok(i3.done); assert.equal(i3.value, 4); assert.ok(finallyCalledSrc); assert.ok(finallyCalled1); assert.ok(finallyCalled2); return 3; } const t4 = a4(); const res = t4.then(i => { assert.equal(i, 3); }); cb("hi"); return res; }); });
require("sdk/system/unload").when(function() { let prefService = require("sdk/preferences/service"); prefService.reset("general.useragent.site_specific_overrides"); prefService.reset("general.useragent.override.youtube.com"); prefService.reset("media.mediasource.enabled"); }); let prefService = require("sdk/preferences/service"); prefService.set('general.useragent.site_specific_overrides', true); prefService.set("general.useragent.override.youtube.com", "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36" ); prefService.set("media.mediasource.enabled", true);
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var orders = require('../../app/controllers/orders.server.controller'); // Orders Routes app.route('/orders') .get(orders.list) .post(users.requiresLogin, orders.create); app.route('/orders-analytics') .get(orders.analytics) app.route('/orders/:orderId') .get(orders.read) .put(users.requiresLogin, orders.hasAuthorization, orders.update) .delete(users.requiresLogin, orders.hasAuthorization, orders.delete); // Finish by binding the Order middleware app.param('orderId', orders.orderByID); };
// 2016-08-22 // // This is the wrapper for the native side /* prelim: start a server from the lib dir: python -m SimpleHTTPServer (python 2.x) (linux) python -m http.server (python 3.x) (windows) 1a) load jquery (note: may need a real active file open for this to work) Note: get message 'VM148:52 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.(…)' if a real file is not open and active, when loading the second file. Note: refer to yaml libray as 'jsyaml' e.g. 'jsyaml.load()' fetch('http://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => {eval(r); eval(r);}); 1b) make sure you're editing a real file. test: make sure: document.getElementById('workbench.editors.files.textFileEditor') 1c) load all the other files Note: you'll get this message if not in a split-panel 'editor-theme-change-listener.js:39 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'' document.MTA_VS = {}; $.when( fetch('http://localhost:8000/editor-theme-change-listener.js').then(r => r.text()).then(r => eval(r)), fetch('http://localhost:8000/local-theme-manager-native.js').then(r => r.text()).then(r => eval(r)), fetch('http://localhost:8000/mta-vs-native.js').then(r => r.text()).then(r => eval(r)) ) .done(function(first_call, second_call, third_call){ console.log('all loaded'); }) .fail(function(){ console.log('load failed'); }); // Note: server now automatically starts when your run 'mta-vs' 3) // then do a word setup so a "Theme:" appears in the status line 4) then change the theme with 'mta-vs' */ fetch('http://localhost:8000/cmd-channel-listener-native.js') .then(r => r.text()) .then(r => eval(r)) .then(() => { console.log('mta-vs-naitve: Now in final then for cmd-channel-listener setup.') var cmdChannelListenerNative = new document.CmdChannelListenerNative(); cmdChannelListenerNative.observe(); }); //@ sourceURL=mta-vs-native.js
(function(){ function newThreadCtrl($location, $state, MessageEditorService){ var vm = this; vm.getConstants = function(){ return MessageEditorService.pmConstants; }; vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId); vm.returnToBoard = function(){ var boardId = $location.search().boardId; $state.go('board',{boardId: boardId}); }; vm.previewThread = function(){ vm.previewThread = MessageEditorService.getThreadPreview(vm.newThread); vm.previewThread.$promise.then(function(data){ vm.preview = true; }); }; vm.postThread = function(){ MessageEditorService.saveThread(vm.newThread).$promise.then(function(data){ }); } vm.isOpen = false; } angular.module('zfgc.forum') .controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]); })();
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('JobIndexCtrl', function($rootScope, PetService) { // "Pets" is a service returning mock data (services.js) $rootScope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) { $rootScope.pet = PetService.get($stateParams.jobId); $scope.goBack = $state.go('job.pet-index'); }) .controller('NewJobDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) { $rootScope.pet = PetService.get($stateParams.jobId); $scope.goBack = $state.go('new-job'); }) .controller('LoginCtrl', function($scope, $state) { $scope.login = function () { $state.go("tab.adopt"); }; }) .controller('JobCreationCtrl', function($scope, $rootScope, $state, $stateParams, $localstorage, PetService) { $scope.createJob = function () { var title = document.getElementById("title"); var desc = document.getElementById("desc"); var location = document.getElementById("location"); if (title.value.trim() !== "" && desc.value.trim() !== "" && location.value.trim() !== "") { var newJobId = $localstorage.length() - 1; var newJob = { id: String(newJobId), title: String(title.value.trim()), description: String(desc.value.trim()), location: String(location.value.trim()), quote: { damageDesc: "", estimatedCost: "", estimatedTime: "", }, report: { fixDesc: "", actualCost: "", startTime: "", finishTime: "" } }; $rootScope.pet = PetService.get(newJobId); $rootScope.pets = PetService.all(); $localstorage.setObject(newJobId, newJob); $state.go('new-quote', {'jobId' : newJobId}); } } });
(function () { 'use strict'; describe('Posts Route Tests', function () { // Initialize global variables var $scope, PostsService; //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 ($rootScope, _PostsService_) { // Set a new global scope $scope = $rootScope.$new(); PostsService = _PostsService_; })); describe('Route Config', function () { describe('Main Route', function () { var mainstate; beforeEach(inject(function ($state) { mainstate = $state.get('posts'); })); it('Should have the correct URL', function () { expect(mainstate.url).toEqual('/posts'); }); it('Should be abstract', function () { expect(mainstate.abstract).toBe(true); }); it('Should have template', function () { expect(mainstate.template).toBe('<ui-view/>'); }); }); describe('View Route', function () { var viewstate, PostsController, mockPost; beforeEach(inject(function ($controller, $state, $templateCache) { viewstate = $state.get('posts.view'); $templateCache.put('modules/posts/client/views/view-post.client.view.html', ''); // create mock Post mockPost = new PostsService({ _id: '525a8422f6d0f87f0e407a33', name: 'Post Name' }); //Initialize Controller PostsController = $controller('PostsController as vm', { $scope: $scope, postResolve: mockPost }); })); it('Should have the correct URL', function () { expect(viewstate.url).toEqual('/:postId'); }); it('Should have a resolve function', function () { expect(typeof viewstate.resolve).toEqual('object'); expect(typeof viewstate.resolve.postResolve).toEqual('function'); }); it('should respond to URL', inject(function ($state) { expect($state.href(viewstate, { postId: 1 })).toEqual('/posts/1'); })); it('should attach an Post to the controller scope', function () { expect($scope.vm.post._id).toBe(mockPost._id); }); it('Should not be abstract', function () { expect(viewstate.abstract).toBe(undefined); }); it('Should have templateUrl', function () { expect(viewstate.templateUrl).toBe('modules/posts/client/views/view-post.client.view.html'); }); }); describe('Create Route', function () { var createstate, PostsController, mockPost; beforeEach(inject(function ($controller, $state, $templateCache) { createstate = $state.get('posts.create'); $templateCache.put('modules/posts/client/views/form-post.client.view.html', ''); // create mock Post mockPost = new PostsService(); //Initialize Controller PostsController = $controller('PostsController as vm', { $scope: $scope, postResolve: mockPost }); })); it('Should have the correct URL', function () { expect(createstate.url).toEqual('/create'); }); it('Should have a resolve function', function () { expect(typeof createstate.resolve).toEqual('object'); expect(typeof createstate.resolve.postResolve).toEqual('function'); }); it('should respond to URL', inject(function ($state) { expect($state.href(createstate)).toEqual('/posts/create'); })); it('should attach an Post to the controller scope', function () { expect($scope.vm.post._id).toBe(mockPost._id); expect($scope.vm.post._id).toBe(undefined); }); it('Should not be abstract', function () { expect(createstate.abstract).toBe(undefined); }); it('Should have templateUrl', function () { expect(createstate.templateUrl).toBe('modules/posts/client/views/form-post.client.view.html'); }); }); describe('Edit Route', function () { var editstate, PostsController, mockPost; beforeEach(inject(function ($controller, $state, $templateCache) { editstate = $state.get('posts.edit'); $templateCache.put('modules/posts/client/views/form-post.client.view.html', ''); // create mock Post mockPost = new PostsService({ _id: '525a8422f6d0f87f0e407a33', name: 'Post Name' }); //Initialize Controller PostsController = $controller('PostsController as vm', { $scope: $scope, postResolve: mockPost }); })); it('Should have the correct URL', function () { expect(editstate.url).toEqual('/:postId/edit'); }); it('Should have a resolve function', function () { expect(typeof editstate.resolve).toEqual('object'); expect(typeof editstate.resolve.postResolve).toEqual('function'); }); it('should respond to URL', inject(function ($state) { expect($state.href(editstate, { postId: 1 })).toEqual('/posts/1/edit'); })); it('should attach an Post to the controller scope', function () { expect($scope.vm.post._id).toBe(mockPost._id); }); it('Should not be abstract', function () { expect(editstate.abstract).toBe(undefined); }); it('Should have templateUrl', function () { expect(editstate.templateUrl).toBe('modules/posts/client/views/form-post.client.view.html'); }); xit('Should go to unauthorized route', function () { }); }); }); }); })();
goog.provide('glift.displays.commentbox'); glift.displays.commentbox = {};
/**YEngine2D * author:YYC * date:2014-04-21 * email:395976266@qq.com * qq: 395976266 * blog:http://www.cnblogs.com/chaogex/ */ describe("CallFunc", function () { var action = null; var sandbox = null; beforeEach(function () { sandbox = sinon.sandbox.create(); action = new YE.CallFunc(); }); afterEach(function () { }); describe("init", function () { it("获得方法上下文、方法、传入方法的参数数组", function () { }); }); describe("update", function () { // it("如果方法为空,则直接完成动作", function () { // sandbox.stub(action, "finish"); // // action.update(); // // expect(action.finish).toCalledOnce(); // }); // describe("否则", function () { var context = null, func = null, data = null, target = null; function setParam(func, context, dataArr) { action.ye___context = context; action.ye___callFunc = func; action.ye___dataArr = dataArr; } beforeEach(function () { context = {}; func = sandbox.createSpyObj("call"); data = 1; target = {a: 1}; setParam(func, context, [data]); sandbox.stub(action, "getTarget").returns(target); }); it("调用方法,设置其上下文为context,并传入target和参数数组", function () { action.update(); expect(func.call).toCalledWith(context, target, [data]); }); it("完成动作", function () { sandbox.stub(action, "finish"); action.update(); expect(action.finish).toCalledOnce(); }); // }); }); describe("copy", function () { it("返回动作副本", function () { var a = action.copy(); expect(a).toBeInstanceOf(YE.CallFunc); expect(a === action).toBeFalsy(); }); it("传入的参数要进行深拷贝", function () { var data = {a: 1}; action.ye___dataArr = [data]; var a = action.copy(); a.ye___dataArr[0].a = 100; expect(data.a).toEqual(1); }); }); describe("reverse", function () { it("直接返回动作", function () { expect(action.reverse()).toBeSame(action); }); }); // describe("isFinish", function () { // it("返回true", function () { // expect(action.isFinish()).toBeTruthy(); // }); // }); describe("create", function () { it("创建实例并返回", function () { expect(YE.CallFunc.create()).toBeInstanceOf(YE.CallFunc); }); }); });
/////////////////////////////////////////////////////////////////////////// // Copyright © 2014 - 2016 Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', 'jimu/BaseFeatureAction', 'jimu/WidgetManager' ], function(declare, BaseFeatureAction, WidgetManager) { var clazz = declare(BaseFeatureAction, { iconClass: 'icon-direction-to', isFeatureSupported: function(featureSet) { return featureSet.features.length === 1 && featureSet.geometryType === "point"; }, onExecute: function(featureSet) { WidgetManager.getInstance().triggerWidgetOpen(this.widgetId).then(function(directionWidget) { if (featureSet.features.length === 1 && featureSet.geometryType === "point") { if (featureSet.features[0].geometry && featureSet.features[0].geometry.type === "point") { directionWidget.addStop(featureSet.features[0].geometry); } } }); } }); return clazz; });
module.exports = { path: { scripts: '/assets/scripts', styles: '/assets/styles', images: '/assets/images' }, site: { url: require('./package.json').mylly.url, name: 'My website', lang: 'en', charset: 'utf-8', ua: '' // UA-XXXXXX-XX }, page: {} };
/* eslint-env mocha */ 'use strict' const path = require('path') const cwd = process.cwd() const NetSuite = require(path.join(cwd, 'netsuite')) const chai = require('chai') const expect = chai.expect const config = require('config') describe('NetSuite class', function () { this.timeout(24 * 60 * 60 * 1000) it('should export a function', function () { expect(NetSuite).to.be.a('function') expect(new NetSuite({})).to.be.a('object') }) it('should search and searchMoreWithId', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FolderSearch'}) expect(result.searchResult).to.be.a('object') expect(result.searchResult.status).to.be.a('object') expect(result.searchResult.status.attributes).to.be.a('object') expect(result.searchResult.status.attributes.isSuccess).to.equal('true') expect(result.searchResult.pageIndex).to.equal(1) let more = await ns.searchMoreWithId(result) expect(more.searchResult).to.be.a('object') expect(more.searchResult.pageIndex).to.equal(2) }) it('should search folders', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FolderSearch'}) expect(result.searchResult.status.attributes.isSuccess).to.equal('true') }) it('should search files', async function () { let ns = new NetSuite(opts()) let result = await ns.search({type: 'FileSearch'}) expect(result.searchResult.status.attributes.isSuccess).to.equal('true') }) it('should get files', async function () { let ns = new NetSuite(opts()) let internalId = '88' let result = await ns.get({type: 'file', internalId: internalId}) expect(result.readResponse).to.be.a('object') expect(result.readResponse.status).to.be.a('object') expect(result.readResponse.status.attributes).to.be.a('object') expect(result.readResponse.status.attributes.isSuccess).to.equal('true') expect(result.readResponse.record.attributes.internalId).to.equal(internalId) }) }) const opts = () => { return { appId: config.get('appId'), passport: {account: config.get('account'), email: config.get('email'), password: config.get('password')}, searchPrefs: {bodyFieldsOnly: false, pageSize: 10}, debug: false } }
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Popup windows //>>label: Popups //>>group: Widgets //>>css.theme: ../css/themes/default/jquery.mobile.theme.css //>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery.mobile.transition.fade.css // Lessons: // You must remove nav bindings even if there is no history. Make sure you // remove nav bindings in the same frame as the beginning of the close process // if there is no history. If there is history, remove nav bindings from the nav // bindings handler - that way, only one of them can fire per close process. define( [ "jquery", "../links", "../widget", "../support", "../events/navigate", "../navigation/path", "../navigation/history", "../navigation/navigator", "../navigation/method", "../animationComplete", "../navigation", "jquery-plugins/jquery.hashchange" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) { var returnValue = desired; if ( windowSize < segmentSize ) { // Center segment if it's bigger than the window returnValue = offset + ( windowSize - segmentSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize ); } return returnValue; } function getWindowCoordinates( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, overlayTheme: null, shadow: true, corners: true, transition: "none", positionTo: "origin", tolerance: null, closeLinkSelector: "a:jqmData(rel='back')", closeLinkEvents: "click.popup", navigateEvents: "navigate.popup", closeEvents: "navigate.popup pagebeforechange.popup", dismissible: true, enhanced: false, // NOTE Windows Phone 7 has a scroll position caching issue that // requires us to disable popup history management by default // https://github.com/jquery/jquery-mobile/issues/4784 // // NOTE this option is modified in _create! history: !$.mobile.browser.oldIE }, _create: function() { var theElement = this.element, myId = theElement.attr( "id" ), currentOptions = this.options; // We need to adjust the history option to be false if there's no AJAX nav. // We can't do it in the option declarations because those are run before // it is determined whether there shall be AJAX nav. currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; // Define instance variables $.extend( this, { _scrollTop: 0, _page: theElement.closest( ".ui-page" ), _ui: null, _fallbackTransition: "", _currentTransition: false, _prerequisites: null, _isOpen: false, _tolerance: null, _resizeData: null, _ignoreResizeTo: 0, _orientationchangeInProgress: false }); if ( this._page.length === 0 ) { this._page = $( "body" ); } if ( currentOptions.enhanced ) { this._ui = { container: theElement.parent(), screen: theElement.parent().prev(), placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) ) }; } else { this._ui = this._enhance( theElement, myId ); this._applyTransition( currentOptions.transition ); } this ._setTolerance( currentOptions.tolerance ) ._ui.focusElement = this._ui.container; // Event handlers this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } ); this._on( this.window, { orientationchange: $.proxy( this, "_handleWindowOrientationchange" ), resize: $.proxy( this, "_handleWindowResize" ), keyup: $.proxy( this, "_handleWindowKeyUp" ) }); this._on( this.document, { "focusin": "_handleDocumentFocusIn" } ); }, _enhance: function( theElement, myId ) { var currentOptions = this.options, wrapperClass = currentOptions.wrapperClass, ui = { screen: $( "<div class='ui-screen-hidden ui-popup-screen " + this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ), placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ), container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" + ( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" ) }, fragment = this.document[ 0 ].createDocumentFragment(); fragment.appendChild( ui.screen[ 0 ] ); fragment.appendChild( ui.container[ 0 ] ); if ( myId ) { ui.screen.attr( "id", myId + "-screen" ); ui.container.attr( "id", myId + "-popup" ); ui.placeholder .attr( "id", myId + "-placeholder" ) .html( "<!-- placeholder for " + myId + " -->" ); } // Apply the proto this._page[ 0 ].appendChild( fragment ); // Leave a placeholder where the element used to be ui.placeholder.insertAfter( theElement ); theElement .detach() .addClass( "ui-popup " + this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " + ( currentOptions.shadow ? "ui-overlay-shadow " : "" ) + ( currentOptions.corners ? "ui-corner-all " : "" ) ) .appendTo( ui.container ); return ui; }, _eatEventAndClose: function( theEvent ) { theEvent.preventDefault(); theEvent.stopImmediatePropagation(); if ( this.options.dismissible ) { this.close(); } return false; }, // Make sure the screen covers the entire document - CSS is sometimes not // enough to accomplish this. _resizeScreen: function() { var screen = this._ui.screen, popupHeight = this._ui.container.outerHeight( true ), screenHeight = screen.removeAttr( "style" ).height(), // Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where // the browser hangs if the screen covers the entire document :/ documentHeight = this.document.height() - 1; if ( screenHeight < documentHeight ) { screen.height( documentHeight ); } else if ( popupHeight > screenHeight ) { screen.height( popupHeight ); } }, _handleWindowKeyUp: function( theEvent ) { if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) { return this._eatEventAndClose( theEvent ); } }, _expectResizeEvent: function() { var windowCoordinates = getWindowCoordinates( this.window ); if ( this._resizeData ) { if ( windowCoordinates.x === this._resizeData.windowCoordinates.x && windowCoordinates.y === this._resizeData.windowCoordinates.y && windowCoordinates.cx === this._resizeData.windowCoordinates.cx && windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) { // timeout not refreshed return false; } else { // clear existing timeout - it will be refreshed below clearTimeout( this._resizeData.timeoutId ); } } this._resizeData = { timeoutId: this._delay( "_resizeTimeout", 200 ), windowCoordinates: windowCoordinates }; return true; }, _resizeTimeout: function() { if ( this._isOpen ) { if ( !this._expectResizeEvent() ) { if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-open the popup while leaving the screen intact this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" ); this.reposition( { positionTo: "window" } ); this._ignoreResizeEvents(); } this._resizeScreen(); this._resizeData = null; this._orientationchangeInProgress = false; } } else { this._resizeData = null; this._orientationchangeInProgress = false; } }, _stopIgnoringResizeEvents: function() { this._ignoreResizeTo = 0; }, _ignoreResizeEvents: function() { if ( this._ignoreResizeTo ) { clearTimeout( this._ignoreResizeTo ); } this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 ); }, _handleWindowResize: function(/* theEvent */) { if ( this._isOpen && this._ignoreResizeTo === 0 ) { if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-close the popup while leaving the screen intact this._ui.container .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); } } }, _handleWindowOrientationchange: function(/* theEvent */) { if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) { this._expectResizeEvent(); this._orientationchangeInProgress = true; } }, // When the popup is open, attempting to focus on an element that is not a // child of the popup will redirect focus to the popup _handleDocumentFocusIn: function( theEvent ) { var target, targetElement = theEvent.target, ui = this._ui; if ( !this._isOpen ) { return; } if ( targetElement !== ui.container[ 0 ] ) { target = $( targetElement ); if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) { $( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) { target.blur(); }); ui.focusElement.focus(); theEvent.preventDefault(); theEvent.stopImmediatePropagation(); return false; } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) { ui.focusElement = target; } } this._ignoreResizeEvents(); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) ); }, _applyTransition: function( value ) { if ( value ) { this._ui.container.removeClass( this._fallbackTransition ); if ( value !== "none" ) { this._fallbackTransition = $.mobile._maybeDegradeTransition( value ); if ( this._fallbackTransition === "none" ) { this._fallbackTransition = ""; } this._ui.container.addClass( this._fallbackTransition ); } } return this; }, _setOptions: function( newOptions ) { var currentOptions = this.options, theElement = this.element, screen = this._ui.screen; if ( newOptions.wrapperClass !== undefined ) { this._ui.container .removeClass( currentOptions.wrapperClass ) .addClass( newOptions.wrapperClass ); } if ( newOptions.theme !== undefined ) { theElement .removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) ) .addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) ); } if ( newOptions.overlayTheme !== undefined ) { screen .removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) ) .addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) ); if ( this._isOpen ) { screen.addClass( "in" ); } } if ( newOptions.shadow !== undefined ) { theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow ); } if ( newOptions.corners !== undefined ) { theElement.toggleClass( "ui-corner-all", newOptions.corners ); } if ( newOptions.transition !== undefined ) { if ( !this._currentTransition ) { this._applyTransition( newOptions.transition ); } } if ( newOptions.tolerance !== undefined ) { this._setTolerance( newOptions.tolerance ); } if ( newOptions.disabled !== undefined ) { if ( newOptions.disabled ) { this.close(); } } return this._super( newOptions ); }, _setTolerance: function( value ) { var tol = { t: 30, r: 15, b: 30, l: 15 }, ar; if ( value !== undefined ) { ar = String( value ).split( "," ); $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } ); switch( ar.length ) { // All values are to be the same case 1: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.r = tol.b = tol.l = ar[ 0 ]; } break; // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance case 2: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.b = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.l = tol.r = ar[ 1 ]; } break; // The array contains values in the order top, right, bottom, left case 4: if ( !isNaN( ar[ 0 ] ) ) { tol.t = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.r = ar[ 1 ]; } if ( !isNaN( ar[ 2 ] ) ) { tol.b = ar[ 2 ]; } if ( !isNaN( ar[ 3 ] ) ) { tol.l = ar[ 3 ]; } break; default: break; } } this._tolerance = tol; return this; }, _clampPopupWidth: function( infoOnly ) { var menuSize, windowCoordinates = getWindowCoordinates( this.window ), // rectangle within which the popup must fit rectangle = { x: this._tolerance.l, y: windowCoordinates.y + this._tolerance.t, cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b }; if ( !infoOnly ) { // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rectangle.cx ); } menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; return { rc: rectangle, menuSize: menuSize }; }, _calculateFinalLocation: function( desired, clampInfo ) { var returnValue, rectangle = clampInfo.rc, menuSize = clampInfo.menuSize; // Center the menu over the desired coordinates, while not going outside // the window tolerances. This will center wrt. the window if the popup is // too large. returnValue = { left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ), top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y ) }; // Make sure the top of the menu is visible returnValue.top = Math.max( 0, returnValue.top ); // If the height of the menu is smaller than the height of the document // align the bottom with the bottom of the document returnValue.top -= Math.min( returnValue.top, Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) ); return returnValue; }, // Try and center the overlay over the given coordinates _placementCoords: function( desired ) { return this._calculateFinalLocation( desired, this._clampPopupWidth() ); }, _createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) { var prerequisites, self = this; // It is important to maintain both the local variable prerequisites and // self._prerequisites. The local variable remains in the closure of the // functions which call the callbacks passed in. The comparison between the // local variable and self._prerequisites is necessary, because once a // function has been passed to .animationComplete() it will be called next // time an animation completes, even if that's not the animation whose end // the function was supposed to catch (for example, if an abort happens // during the opening animation, the .animationComplete handler is not // called for that animation anymore, but the handler remains attached, so // it is called the next time the popup is opened - making it stale. // Comparing the local variable prerequisites to the widget-level variable // self._prerequisites ensures that callbacks triggered by a stale // .animationComplete will be ignored. prerequisites = { screen: $.Deferred(), container: $.Deferred() }; prerequisites.screen.then( function() { if ( prerequisites === self._prerequisites ) { screenPrerequisite(); } }); prerequisites.container.then( function() { if ( prerequisites === self._prerequisites ) { containerPrerequisite(); } }); $.when( prerequisites.screen, prerequisites.container ).done( function() { if ( prerequisites === self._prerequisites ) { self._prerequisites = null; whenDone(); } }); self._prerequisites = prerequisites; }, _animate: function( args ) { // NOTE before removing the default animation of the screen // this had an animate callback that would resolve the deferred // now the deferred is resolved immediately // TODO remove the dependency on the screen deferred this._ui.screen .removeClass( args.classToRemove ) .addClass( args.screenClassToAdd ); args.prerequisites.screen.resolve(); if ( args.transition && args.transition !== "none" ) { if ( args.applyTransition ) { this._applyTransition( args.transition ); } if ( this._fallbackTransition ) { this._ui.container .addClass( args.containerClassToAdd ) .removeClass( args.classToRemove ) .animationComplete( $.proxy( args.prerequisites.container, "resolve" ) ); return; } } this._ui.container.removeClass( args.classToRemove ); args.prerequisites.container.resolve(); }, // The desired coordinates passed in will be returned untouched if no reference element can be identified via // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid // x and y coordinates by specifying the center middle of the window if the coordinates are absent. // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector _desiredCoords: function( openOptions ) { var offset, dst = null, windowCoordinates = getWindowCoordinates( this.window ), x = openOptions.x, y = openOptions.y, pTo = openOptions.positionTo; // Establish which element will serve as the reference if ( pTo && pTo !== "origin" ) { if ( pTo === "window" ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; y = windowCoordinates.cy / 2 + windowCoordinates.y; } else { try { dst = $( pTo ); } catch( err ) { dst = null; } if ( dst ) { dst.filter( ":visible" ); if ( dst.length === 0 ) { dst = null; } } } } // If an element was found, center over it if ( dst ) { offset = dst.offset(); x = offset.left + dst.outerWidth() / 2; y = offset.top + dst.outerHeight() / 2; } // Make sure x and y are valid numbers - center over the window if ( $.type( x ) !== "number" || isNaN( x ) ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; } if ( $.type( y ) !== "number" || isNaN( y ) ) { y = windowCoordinates.cy / 2 + windowCoordinates.y; } return { x: x, y: y }; }, _reposition: function( openOptions ) { // We only care about position-related parameters for repositioning openOptions = { x: openOptions.x, y: openOptions.y, positionTo: openOptions.positionTo }; this._trigger( "beforeposition", undefined, openOptions ); this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) ); }, reposition: function( openOptions ) { if ( this._isOpen ) { this._reposition( openOptions ); } }, _openPrerequisitesComplete: function() { var id = this.element.attr( "id" ); this._ui.container.addClass( "ui-popup-active" ); this._isOpen = true; this._resizeScreen(); this._ui.container.attr( "tabindex", "0" ).focus(); this._ignoreResizeEvents(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true ); } this._trigger( "afteropen" ); }, _open: function( options ) { var openOptions = $.extend( {}, this.options, options ), // TODO move blacklist to private method androidBlacklist = ( function() { var ua = navigator.userAgent, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ), andversion = !!androidmatch && androidmatch[ 1 ], chromematch = ua.indexOf( "Chrome" ) > -1; // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) { return true; } return false; }()); // Count down to triggering "popupafteropen" - we have two prerequisites: // 1. The popup window animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.noop, $.noop, $.proxy( this, "_openPrerequisitesComplete" ) ); this._currentTransition = openOptions.transition; this._applyTransition( openOptions.transition ); this._ui.screen.removeClass( "ui-screen-hidden" ); this._ui.container.removeClass( "ui-popup-truncate" ); // Give applications a chance to modify the contents of the container before it appears this._reposition( openOptions ); this._ui.container.removeClass( "ui-popup-hidden" ); if ( this.options.overlayTheme && androidBlacklist ) { /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): https://github.com/jquery/jquery-mobile/issues/4816 https://github.com/jquery/jquery-mobile/issues/4844 https://github.com/jquery/jquery-mobile/issues/4874 */ // TODO sort out why this._page isn't working this.element.closest( ".ui-page" ).addClass( "ui-popup-open" ); } this._animate({ additionalCondition: true, transition: openOptions.transition, classToRemove: "", screenClassToAdd: "in", containerClassToAdd: "in", applyTransition: false, prerequisites: this._prerequisites }); }, _closePrerequisiteScreen: function() { this._ui.screen .removeClass( "out" ) .addClass( "ui-screen-hidden" ); }, _closePrerequisiteContainer: function() { this._ui.container .removeClass( "reverse out" ) .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); }, _closePrerequisitesDone: function() { var container = this._ui.container, id = this.element.attr( "id" ); container.removeAttr( "tabindex" ); // remove the global mutex for popups $.mobile.popup.active = undefined; // Blur elements inside the container, including the container $( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false ); } // alert users that the popup is closed this._trigger( "afterclose" ); }, _close: function( immediate ) { this._ui.container.removeClass( "ui-popup-active" ); this._page.removeClass( "ui-popup-open" ); this._isOpen = false; // Count down to triggering "popupafterclose" - we have two prerequisites: // 1. The popup window reverse animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.proxy( this, "_closePrerequisiteScreen" ), $.proxy( this, "_closePrerequisiteContainer" ), $.proxy( this, "_closePrerequisitesDone" ) ); this._animate( { additionalCondition: this._ui.screen.hasClass( "in" ), transition: ( immediate ? "none" : ( this._currentTransition ) ), classToRemove: "in", screenClassToAdd: "out", containerClassToAdd: "reverse out", applyTransition: true, prerequisites: this._prerequisites }); }, _unenhance: function() { if ( this.options.enhanced ) { return; } // Put the element back to where the placeholder was and remove the "ui-popup" class this._setOptions( { theme: $.mobile.popup.prototype.options.theme } ); this.element // Cannot directly insertAfter() - we need to detach() first, because // insertAfter() will do nothing if the payload div was not attached // to the DOM at the time the widget was created, and so the payload // will remain inside the container even after we call insertAfter(). // If that happens and we remove the container a few lines below, we // will cause an infinite recursion - #5244 .detach() .insertAfter( this._ui.placeholder ) .removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" ); this._ui.screen.remove(); this._ui.container.remove(); this._ui.placeholder.remove(); }, _destroy: function() { if ( $.mobile.popup.active === this ) { this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) ); this.close(); } else { this._unenhance(); } return this; }, _closePopup: function( theEvent, data ) { var parsedDst, toUrl, currentOptions = this.options, immediate = false; if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) { return; } // restore location on screen window.scrollTo( 0, this._scrollTop ); if ( theEvent && theEvent.type === "pagebeforechange" && data ) { // Determine whether we need to rapid-close the popup, or whether we can // take the time to run the closing transition if ( typeof data.toPage === "string" ) { parsedDst = data.toPage; } else { parsedDst = data.toPage.jqmData( "url" ); } parsedDst = $.mobile.path.parseUrl( parsedDst ); toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) { // Going to a different page - close immediately immediate = true; } else { theEvent.preventDefault(); } } // remove nav bindings this.window.off( currentOptions.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents ); this._close( immediate ); }, // any navigation event after a popup is opened should close the popup // NOTE the pagebeforechange is bound to catch navigation events that don't // alter the url (eg, dialogs from popups) _bindContainerClose: function() { this.window .on( this.options.closeEvents, $.proxy( this, "_closePopup" ) ); }, widget: function() { return this._ui.container; }, // TODO no clear deliniation of what should be here and // what should be in _open. Seems to be "visual" vs "history" for now open: function( options ) { var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory, self = this, currentOptions = this.options; // make sure open is idempotent if ( $.mobile.popup.active || currentOptions.disabled ) { return this; } // set the global popup mutex $.mobile.popup.active = this; this._scrollTop = this.window.scrollTop(); // if history alteration is disabled close on navigate events // and leave the url as is if ( !( currentOptions.history ) ) { self._open( options ); self._bindContainerClose(); // When histoy is disabled we have to grab the data-rel // back link clicks so we can close the popup instead of // relying on history to do it for us self.element .delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) { self.close(); theEvent.preventDefault(); }); return this; } // cache some values for min/readability urlHistory = $.mobile.navigate.history; hashkey = $.mobile.dialogHashKey; activePage = $.mobile.activePage; currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false ); this._myUrl = url = urlHistory.getActive().url; hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 ); if ( hasHash ) { self._open( options ); self._bindContainerClose(); return this; } // if the current url has no dialog hash key proceed as normal // otherwise, if the page is a dialog simply tack on the hash key if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) { url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey); } else { url = $.mobile.path.parseLocation().hash + hashkey; } // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += hashkey; } // swallow the the initial navigation event, and bind for the next this.window.one( "beforenavigate", function( theEvent ) { theEvent.preventDefault(); self._open( options ); self._bindContainerClose(); }); this.urlAltered = true; $.mobile.navigate( url, { role: "dialog" } ); return this; }, close: function() { // make sure close is idempotent if ( $.mobile.popup.active !== this ) { return this; } this._scrollTop = this.window.scrollTop(); if ( this.options.history && this.urlAltered ) { $.mobile.back(); this.urlAltered = false; } else { // simulate the nav bindings having fired this._closePopup(); } return this; } }); // TODO this can be moved inside the widget $.mobile.popup.handleLink = function( $link ) { var offset, path = $.mobile.path, // NOTE make sure to get only the hash from the href because ie7 (wp7) // returns the absolute href in this case ruining the element selection popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first(); if ( popup.length > 0 && popup.data( "mobile-popup" ) ) { offset = $link.offset(); popup.popup( "open", { x: offset.left + $link.outerWidth() / 2, y: offset.top + $link.outerHeight() / 2, transition: $link.jqmData( "transition" ), positionTo: $link.jqmData( "position-to" ) }); } //remove after delay setTimeout( function() { $link.removeClass( $.mobile.activeBtnClass ); }, 300 ); }; // TODO move inside _create $.mobile.document.on( "pagebeforechange", function( theEvent, data ) { if ( data.options.role === "popup" ) { $.mobile.popup.handleLink( data.options.link ); theEvent.preventDefault(); } }); })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
/** * version: 1.1.10 */ angular.module('ngWig', ['ngwig-app-templates']); angular.module('ngWig') .directive('ngWig', function () { return { scope: { content: '=ngWig' }, restrict: 'A', replace: true, templateUrl: 'ng-wig/views/ng-wig.html', link: function (scope, element, attrs) { scope.editMode = false; scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off'; scope.toggleEditMode = function () { scope.editMode = !scope.editMode; }; scope.execCommand = function (command, options) { if (command === 'createlink') { options = prompt('Please enter the URL', 'http://'); } if (command === 'insertimage') { options = prompt('Please enter an image URL to insert', 'http://'); } if (options !== null) { scope.$emit('execCommand', {command: command, options: options}); } }; scope.styles = [ {name: 'Normal text', value: 'p'}, {name: 'Header 1', value: 'h1'}, {name: 'Header 2', value: 'h2'}, {name: 'Header 3', value: 'h3'} ]; scope.style = scope.styles[0]; scope.$on("colorpicker-selected", function ($event, color) { scope.execCommand('foreColor', color.value); }); } } }); angular.module('ngWig') .directive('ngWigEditable', function () { function init(scope, $element, attrs, ctrl) { var document = $element[0].ownerDocument; $element.attr('contenteditable', true); //model --> view ctrl.$render = function () { $element.html(ctrl.$viewValue || ''); }; //view --> model function viewToModel() { ctrl.$setViewValue($element.html()); //to support Angular 1.2.x if (angular.version.minor < 3) { scope.$apply(); } } $element.bind('blur keyup change paste', viewToModel); scope.$on('execCommand', function (event, params) { $element[0].focus(); var ieStyleTextSelection = document.selection, command = params.command, options = params.options; if (ieStyleTextSelection) { var textRange = ieStyleTextSelection.createRange(); } document.execCommand(command, false, options); if (ieStyleTextSelection) { textRange.collapse(false); textRange.select(); } viewToModel(); }); } return { restrict: 'A', require: 'ngModel', replace: true, link: init } } ); angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']); angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("ng-wig/views/ng-wig.html", "<div class=\"ng-wig\">\n" + " <ul class=\"nw-toolbar\">\n" + " <li class=\"nw-toolbar__item\">\n" + " <select class=\"nw-select\" ng-model=\"style\" ng-change=\"execCommand('formatblock', style.value)\" ng-options=\"style.name for style in styles\">\n" + " </select>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button colorpicker ng-model=\"fontcolor\" class=\"nw-button nw-button--text-color\" title=\"Font Color\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--image\" title=\"image\" ng-click=\"execCommand('insertimage')\"></button>\n" + " </li><!--\n" + " --><li class=\"nw-toolbar__item\">\n" + " <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" + " </li>\n" + " </ul>\n" + "\n" + " <div class=\"nw-editor-container\">\n" + " <div class=\"nw-editor\">\n" + " <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" + " <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" + " </div>\n" + " </div>\n" + "</div>\n" + ""); }]);
/** * main.js: The entry point for MuTube. * Plays the role of the 'main process' in Electron. */ // define constants from various packages for the main process const { app, BrowserWindow, ipcMain } = require('electron'); let mainWindow; // execute the application app.on('ready', () => { // create the main broswer window with the following array values mainWindow = new BrowserWindow({ title: "MuTube", width: 600, height: 600, minWidth: 600, minHeight: 600, center: true, backgroundColor: "#181818", // mainly for Linux-based OSes running GTK darkTheme: true, // only for macOS when scrolling passed the beginning and ends of page scrollBounce: true }); // remove the menu bar mainWindow.setMenu(null); // load broswer window content mainWindow.loadURL('file://' + __dirname + '/html/index.html'); }); // when ipc receives signal, 'toggleDevTools', from renderer ipcMain.on('toggleDevTools', function() { if (mainWindow.isDevToolsOpened()) { mainWindow.closeDevTools(); } else { mainWindow.openDevTools({ mode: 'detach' }); } });
/*global Backbone */ var Generator = Generator || {}; (function () { 'use strict'; // Aspect Model // ---------- Generator.Aspect = Backbone.Model.extend({ defaults: { result: 0, text: '' } }); })();
version https://git-lfs.github.com/spec/v1 oid sha256:4fc049501415815d5fa555bc735c359c381441d2107851b32b30ae5ba192a892 size 11548
function Loader() { var self = this; self.cache = {}; // Filename -> {Geometry, Material, [callbacks]} self.textureCache = {}; // Filename -> Texture self.loader = new THREE.JSONLoader(); } Loader.prototype.loadTexture = function(filename, callback) { var self = this; var texture = self.textureCache[filename]; if(texture === undefined) { texture = THREE.ImageUtils.loadTexture(filename, undefined, callback); self.textureCache[filename] = texture; } return texture; }; Loader.prototype.loadTextureCube = function(filenames, callback) { var self = this; var filename = filenames[0]; // Use the first texture as the lookup name var texture = self.textureCache[filename]; if(texture === undefined) { texture = THREE.ImageUtils.loadTextureCube(filenames, undefined, callback); self.textureCache[filename] = texture; } else { callback(texture); } }; Loader.prototype.loadMesh = function(filename, callback) { var self = this; // Don't worry about texture caching because ThreeJS caches all loaded images // and material.clone creates shallow copies of textures. var cacheData = self.cache[filename]; if(cacheData === undefined) { // Not found in cache, load now // Add initial entry to cache var cacheData = { loaded: false, geometry: null, material: null, callbacks: [] }; self.cache[filename] = cacheData; // Load the json file self.loader.load(filename, function(geometry, materials) { // Finished loading // Update the cache var material = self.createMaterial(materials); cacheData.geometry = geometry; cacheData.material = material; cacheData.loaded = true; // Call the callback on this callback(geometry, self.cloneMaterial(material)); // Call the callbacks for all other objects created before this finished loading for(var i = 0; i < cacheData.callbacks.length; i++) { var callbackCached = cacheData.callbacks[i]; callbackCached(geometry, self.cloneMaterial(material)); } }); } else { // Check if the cache data is loaded. If not add the callback if(cacheData.loaded) { var geometry = cacheData.geometry; var material = self.cloneMaterial(cacheData.material); callback(geometry, material); } else { cacheData.callbacks.push(callback); } } }; Loader.prototype.createMaterial = function(materials) { var meshMaterial; if(materials === undefined){ meshMaterial = new THREE.MeshLambertMaterial(); materials = [meshMaterial]; } else if(materials.length == 1) meshMaterial = materials[0]; else meshMaterial = new THREE.MeshFaceMaterial(materials); // Fix materials for(var i = 0; i < materials.length; i++) { var material = materials[i]; if(material.map) { material.map.wrapS = material.map.wrapT = THREE.RepeatWrapping; // Set repeat wrapping //if(material.transparent) material.opacity = 1.0; // If transparent and it has a texture, set opacity to 1.0 } if(material.transparent) { material.depthWrite = false; //material.side = THREE.DoubleSide; material.side = THREE.FrontSide; } else { material.side = THREE.FrontSide; } // For editor purposes material.transparentOld = material.transparent; material.opacityOld = material.opacity; } return meshMaterial; }; Loader.prototype.cloneMaterial = function(material) { var newMaterial = material.clone(); newMaterial.transparentOld = material.transparentOld; newMaterial.opacityOld = material.opacityOld; return newMaterial; }; Loader.prototype.dispose = function() { // Not really necessary to call this function since the memory will be reused elsewhere var self = this; // Dispose geometries var geometryKeys = Object.keys(self.geometryCache); for(var i = 0; i < geometryKeys.length; i++) { var key = geometryKeys[i]; var geometry = self.geometryCache[key]; geometry.dispose(); } self.geometryCache = {}; // Dispose materials // No listeners are attached in the ThreeJS source, so this doesn't do anything var materialKeys = Object.keys(self.materialCache); for(var i = 0; i < materialKeys.length; i++) { var key = materialKeys[i]; var material = self.matericalCache[key]; var materials = Util.getMaterials(material); // Get all the materials in the material (e.g. MeshFaceMaterial) for(var j = 0; j < materials.length; j++) { var material = materials[j]; material.dispose(); } } self.materialCache = {}; // TO-DO: Dispose textures. // Find all the textures on all the materials // or go directly to WebGLTextures.js and manually delete there };
import header from 'head'; class Loader { constructor () { // Singleton Object if(window.CM == null){ window.CM = {}; } window.CM.Loader = this; let scope = this; head.ready(document, function() { head.load([ "/assets/css/app.css", "/assets/js/app.js", "/assets/js/shim.js", "//fast.fonts.com/cssapi/6536d2ad-a624-4b33-9405-4c303cfb6253.css" ], CM.Loader.startApplication); }); } removeGFX (){ document.body.setAttribute("class", document.body.getAttribute("class").split("hideloader").join("run")); CM.App.showPage(); let preloader = document.getElementsByClassName("preloader")[0]; if(preloader && preloader.parentNode){ preloader.parentNode.removeChild(preloader); } } startApplication (){ if(window.CM.App == undefined){ setTimeout(CM.Loader.startApplication, 500); } else { CM.App.blastoff(); document.body.setAttribute("class", document.body.getAttribute("class").split("loading").join("loaded") ); setTimeout(function(){ document.body.setAttribute("class", document.body.getAttribute("class").split("loaded").join("hideloader") ); }, 500); setTimeout(function(){ CM.Loader.removeGFX(); }, 1750); } } }; export default new Loader();
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { // Wrap the data object in jquery object var body = $("<div/>").html(data); // Remove the first heading from the returned data var header = body.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); // Remove the first submit button from the returned data var footer = body.find("form").find("input[type=submit]").eq(0).remove(); // Add in content if (header) $("#modal").find("[data-role=modal-title-content]").text(header.text()); if (body) $("#modal").find("[data-role=modal-body-content]").html(body.html()); if (footer) $("#modal").find("[data-role=modal-footer-content]").html(footer); // Toggle the ajax-loader $("#modal").find(".ajax-loader").hide(); } var cleanup_modal = function() { $("#modal").find("[data-role=modal-title-content]").text(''); $("#modal").find("[data-role=modal-body-content]").text(''); $("#modal").find("[data-role=modal-footer-content]").text(''); $("#modal").find(".ajax-loader").hide(); } var display_modal = function(event) { event.preventDefault(); cleanup_modal(); $("#modal").find(".ajax-loader").show(); $("#modal").modal("show"); $.get(this.href, "", populate_modal, "html"); } var ajax_form_catch = function(event) { event.preventDefault(); $("#modal").find(".ajax-loader").show(); var form = $("#modal").find("form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); cleanup_modal(); }; $(document).on("click", "a.ajax_window", display_modal); $(document).on("click", "#modal .modal-footer input[type=submit]", ajax_form_catch); $(document).on("submit", "#modal form", ajax_form_catch); });
'use strict'; moduloCategoria.factory('categoriaService', ['serverService', function (serverService) { return { getFields: function () { return [ {name: "id", shortname: "ID", longname: "Identificador", visible: true, type: "id"}, {name: "nombre", shortname: "Nombre", longname: "Nombre", visible: true, type: "text", required: true,pattern: serverService.getRegExpr("alpha-numeric"), help: serverService.getRegExpl("alpha-numeric")}, ]; }, getIcon: function () { return "fa-tags"; }, getObTitle: function () { return "categoria"; }, getTitle: function () { return "categoria"; } }; }]);
var NAVTREE = [ [ "game_of_life", "index.html", [ [ "game_of_life", "md__r_e_a_d_m_e.html", null ], [ "Classes", null, [ [ "Class List", "annotated.html", "annotated" ], [ "Class Index", "classes.html", null ], [ "Class Members", "functions.html", [ [ "All", "functions.html", null ], [ "Functions", "functions_func.html", null ] ] ] ] ], [ "Files", null, [ [ "File List", "files.html", "files" ], [ "File Members", "globals.html", [ [ "All", "globals.html", null ], [ "Functions", "globals_func.html", null ], [ "Variables", "globals_vars.html", null ] ] ] ] ] ] ] ]; var NAVTREEINDEX = [ "annotated.html" ]; var SYNCONMSG = 'click to disable panel synchronisation'; var SYNCOFFMSG = 'click to enable panel synchronisation'; var navTreeSubIndices = new Array(); function getData(varName) { var i = varName.lastIndexOf('/'); var n = i>=0 ? varName.substring(i+1) : varName; return eval(n.replace(/\-/g,'_')); } function stripPath(uri) { return uri.substring(uri.lastIndexOf('/')+1); } function stripPath2(uri) { var i = uri.lastIndexOf('/'); var s = uri.substring(i+1); var m = uri.substring(0,i+1).match(/\/d\w\/d\w\w\/$/); return m ? uri.substring(i-6) : s; } function localStorageSupported() { try { return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem; } catch(e) { return false; } } function storeLink(link) { if (!$("#nav-sync").hasClass('sync') && localStorageSupported()) { window.localStorage.setItem('navpath',link); } } function deleteLink() { if (localStorageSupported()) { window.localStorage.setItem('navpath',''); } } function cachedLink() { if (localStorageSupported()) { return window.localStorage.getItem('navpath'); } else { return ''; } } function getScript(scriptName,func,show) { var head = document.getElementsByTagName("head")[0]; var script = document.createElement('script'); script.id = scriptName; script.type = 'text/javascript'; script.onload = func; script.src = scriptName+'.js'; if ($.browser.msie && $.browser.version<=8) { // script.onload does not work with older versions of IE script.onreadystatechange = function() { if (script.readyState=='complete' || script.readyState=='loaded') { func(); if (show) showRoot(); } } } head.appendChild(script); } function createIndent(o,domNode,node,level) { var level=-1; var n = node; while (n.parentNode) { level++; n=n.parentNode; } var imgNode = document.createElement("img"); imgNode.style.paddingLeft=(16*level).toString()+'px'; imgNode.width = 16; imgNode.height = 22; imgNode.border = 0; if (node.childrenData) { node.plus_img = imgNode; node.expandToggle = document.createElement("a"); node.expandToggle.href = "javascript:void(0)"; node.expandToggle.onclick = function() { if (node.expanded) { $(node.getChildrenUL()).slideUp("fast"); node.plus_img.src = node.relpath+"ftv2pnode.png"; node.expanded = false; } else { expandNode(o, node, false, false); } } node.expandToggle.appendChild(imgNode); domNode.appendChild(node.expandToggle); imgNode.src = node.relpath+"ftv2pnode.png"; } else { imgNode.src = node.relpath+"ftv2node.png"; domNode.appendChild(imgNode); } } var animationInProgress = false; function gotoAnchor(anchor,aname,updateLocation) { var pos, docContent = $('#doc-content'); if (anchor.parent().attr('class')=='memItemLeft' || anchor.parent().attr('class')=='fieldtype' || anchor.parent().is(':header')) { pos = anchor.parent().position().top; } else if (anchor.position()) { pos = anchor.position().top; } if (pos) { var dist = Math.abs(Math.min( pos-docContent.offset().top, docContent[0].scrollHeight- docContent.height()-docContent.scrollTop())); animationInProgress=true; docContent.animate({ scrollTop: pos + docContent.scrollTop() - docContent.offset().top },Math.max(50,Math.min(500,dist)),function(){ if (updateLocation) window.location.href=aname; animationInProgress=false; }); } } function newNode(o, po, text, link, childrenData, lastNode) { var node = new Object(); node.children = Array(); node.childrenData = childrenData; node.depth = po.depth + 1; node.relpath = po.relpath; node.isLast = lastNode; node.li = document.createElement("li"); po.getChildrenUL().appendChild(node.li); node.parentNode = po; node.itemDiv = document.createElement("div"); node.itemDiv.className = "item"; node.labelSpan = document.createElement("span"); node.labelSpan.className = "label"; createIndent(o,node.itemDiv,node,0); node.itemDiv.appendChild(node.labelSpan); node.li.appendChild(node.itemDiv); var a = document.createElement("a"); node.labelSpan.appendChild(a); node.label = document.createTextNode(text); node.expanded = false; a.appendChild(node.label); if (link) { var url; if (link.substring(0,1)=='^') { url = link.substring(1); link = url; } else { url = node.relpath+link; } a.className = stripPath(link.replace('#',':')); if (link.indexOf('#')!=-1) { var aname = '#'+link.split('#')[1]; var srcPage = stripPath($(location).attr('pathname')); var targetPage = stripPath(link.split('#')[0]); a.href = srcPage!=targetPage ? url : "javascript:void(0)"; a.onclick = function(){ storeLink(link); if (!$(a).parent().parent().hasClass('selected')) { $('.item').removeClass('selected'); $('.item').removeAttr('id'); $(a).parent().parent().addClass('selected'); $(a).parent().parent().attr('id','selected'); } var anchor = $(aname); gotoAnchor(anchor,aname,true); }; } else { a.href = url; a.onclick = function() { storeLink(link); } } } else { if (childrenData != null) { a.className = "nolink"; a.href = "javascript:void(0)"; a.onclick = node.expandToggle.onclick; } } node.childrenUL = null; node.getChildrenUL = function() { if (!node.childrenUL) { node.childrenUL = document.createElement("ul"); node.childrenUL.className = "children_ul"; node.childrenUL.style.display = "none"; node.li.appendChild(node.childrenUL); } return node.childrenUL; }; return node; } function showRoot() { var headerHeight = $("#top").height(); var footerHeight = $("#nav-path").height(); var windowHeight = $(window).height() - headerHeight - footerHeight; (function (){ // retry until we can scroll to the selected item try { var navtree=$('#nav-tree'); navtree.scrollTo('#selected',0,{offset:-windowHeight/2}); } catch (err) { setTimeout(arguments.callee, 0); } })(); } function expandNode(o, node, imm, showRoot) { if (node.childrenData && !node.expanded) { if (typeof(node.childrenData)==='string') { var varName = node.childrenData; getScript(node.relpath+varName,function(){ node.childrenData = getData(varName); expandNode(o, node, imm, showRoot); }, showRoot); } else { if (!node.childrenVisited) { getNode(o, node); } if (imm || ($.browser.msie && $.browser.version>8)) { // somehow slideDown jumps to the start of tree for IE9 :-( $(node.getChildrenUL()).show(); } else { $(node.getChildrenUL()).slideDown("fast"); } if (node.isLast) { node.plus_img.src = node.relpath+"ftv2mlastnode.png"; } else { node.plus_img.src = node.relpath+"ftv2mnode.png"; } node.expanded = true; } } } function glowEffect(n,duration) { n.addClass('glow').delay(duration).queue(function(next){ $(this).removeClass('glow');next(); }); } function highlightAnchor() { var aname = $(location).attr('hash'); var anchor = $(aname); if (anchor.parent().attr('class')=='memItemLeft'){ var rows = $('.memberdecls tr[class$="'+ window.location.hash.substring(1)+'"]'); glowEffect(rows.children(),300); // member without details } else if (anchor.parents().slice(2).prop('tagName')=='TR') { glowEffect(anchor.parents('div.memitem'),1000); // enum value } else if (anchor.parent().attr('class')=='fieldtype'){ glowEffect(anchor.parent().parent(),1000); // struct field } else if (anchor.parent().is(":header")) { glowEffect(anchor.parent(),1000); // section header } else { glowEffect(anchor.next(),1000); // normal member } gotoAnchor(anchor,aname,false); } function selectAndHighlight(hash,n) { var a; if (hash) { var link=stripPath($(location).attr('pathname'))+':'+hash.substring(1); a=$('.item a[class$="'+link+'"]'); } if (a && a.length) { a.parent().parent().addClass('selected'); a.parent().parent().attr('id','selected'); highlightAnchor(); } else if (n) { $(n.itemDiv).addClass('selected'); $(n.itemDiv).attr('id','selected'); } if ($('#nav-tree-contents .item:first').hasClass('selected')) { $('#nav-sync').css('top','30px'); } else { $('#nav-sync').css('top','5px'); } showRoot(); } function showNode(o, node, index, hash) { if (node && node.childrenData) { if (typeof(node.childrenData)==='string') { var varName = node.childrenData; getScript(node.relpath+varName,function(){ node.childrenData = getData(varName); showNode(o,node,index,hash); },true); } else { if (!node.childrenVisited) { getNode(o, node); } $(node.getChildrenUL()).show(); if (node.isLast) { node.plus_img.src = node.relpath+"ftv2mlastnode.png"; } else { node.plus_img.src = node.relpath+"ftv2mnode.png"; } node.expanded = true; var n = node.children[o.breadcrumbs[index]]; if (index+1<o.breadcrumbs.length) { showNode(o,n,index+1,hash); } else { if (typeof(n.childrenData)==='string') { var varName = n.childrenData; getScript(n.relpath+varName,function(){ n.childrenData = getData(varName); node.expanded=false; showNode(o,node,index,hash); // retry with child node expanded },true); } else { var rootBase = stripPath(o.toroot.replace(/\..+$/, '')); if (rootBase=="index" || rootBase=="pages" || rootBase=="search") { expandNode(o, n, true, true); } selectAndHighlight(hash,n); } } } } else { selectAndHighlight(hash); } } function getNode(o, po) { po.childrenVisited = true; var l = po.childrenData.length-1; for (var i in po.childrenData) { var nodeData = po.childrenData[i]; po.children[i] = newNode(o, po, nodeData[0], nodeData[1], nodeData[2], i==l); } } function gotoNode(o,subIndex,root,hash,relpath) { var nti = navTreeSubIndices[subIndex][root+hash]; o.breadcrumbs = $.extend(true, [], nti ? nti : navTreeSubIndices[subIndex][root]); if (!o.breadcrumbs && root!=NAVTREE[0][1]) { // fallback: show index navTo(o,NAVTREE[0][1],"",relpath); $('.item').removeClass('selected'); $('.item').removeAttr('id'); } if (o.breadcrumbs) { o.breadcrumbs.unshift(0); // add 0 for root node showNode(o, o.node, 0, hash); } } function navTo(o,root,hash,relpath) { var link = cachedLink(); if (link) { var parts = link.split('#'); root = parts[0]; if (parts.length>1) hash = '#'+parts[1]; else hash=''; } if (hash.match(/^#l\d+$/)) { var anchor=$('a[name='+hash.substring(1)+']'); glowEffect(anchor.parent(),1000); // line number hash=''; // strip line number anchors //root=root.replace(/_source\./,'.'); // source link to doc link } var url=root+hash; var i=-1; while (NAVTREEINDEX[i+1]<=url) i++; if (i==-1) { i=0; root=NAVTREE[0][1]; } // fallback: show index if (navTreeSubIndices[i]) { gotoNode(o,i,root,hash,relpath) } else { getScript(relpath+'navtreeindex'+i,function(){ navTreeSubIndices[i] = eval('NAVTREEINDEX'+i); if (navTreeSubIndices[i]) { gotoNode(o,i,root,hash,relpath); } },true); } } function showSyncOff(n,relpath) { n.html('<img src="'+relpath+'sync_off.png" title="'+SYNCOFFMSG+'"/>'); } function showSyncOn(n,relpath) { n.html('<img src="'+relpath+'sync_on.png" title="'+SYNCONMSG+'"/>'); } function toggleSyncButton(relpath) { var navSync = $('#nav-sync'); if (navSync.hasClass('sync')) { navSync.removeClass('sync'); showSyncOff(navSync,relpath); storeLink(stripPath2($(location).attr('pathname'))+$(location).attr('hash')); } else { navSync.addClass('sync'); showSyncOn(navSync,relpath); deleteLink(); } } function initNavTree(toroot,relpath) { var o = new Object(); o.toroot = toroot; o.node = new Object(); o.node.li = document.getElementById("nav-tree-contents"); o.node.childrenData = NAVTREE; o.node.children = new Array(); o.node.childrenUL = document.createElement("ul"); o.node.getChildrenUL = function() { return o.node.childrenUL; }; o.node.li.appendChild(o.node.childrenUL); o.node.depth = 0; o.node.relpath = relpath; o.node.expanded = false; o.node.isLast = true; o.node.plus_img = document.createElement("img"); o.node.plus_img.src = relpath+"ftv2pnode.png"; o.node.plus_img.width = 16; o.node.plus_img.height = 22; if (localStorageSupported()) { var navSync = $('#nav-sync'); if (cachedLink()) { showSyncOff(navSync,relpath); navSync.removeClass('sync'); } else { showSyncOn(navSync,relpath); } navSync.click(function(){ toggleSyncButton(relpath); }); } navTo(o,toroot,window.location.hash,relpath); $(window).bind('hashchange', function(){ if (window.location.hash && window.location.hash.length>1){ var a; if ($(location).attr('hash')){ var clslink=stripPath($(location).attr('pathname'))+':'+ $(location).attr('hash').substring(1); a=$('.item a[class$="'+clslink+'"]'); } if (a==null || !$(a).parent().parent().hasClass('selected')){ $('.item').removeClass('selected'); $('.item').removeAttr('id'); } var link=stripPath2($(location).attr('pathname')); navTo(o,link,$(location).attr('hash'),relpath); } else if (!animationInProgress) { $('#doc-content').scrollTop(0); $('.item').removeClass('selected'); $('.item').removeAttr('id'); navTo(o,toroot,window.location.hash,relpath); } }) $(window).load(showRoot); }
var ConfigInitializer = { name: 'config', initialize: function (container, application) { var apps = $('body').data('apps'), tagsUI = $('body').data('tagsui'), fileStorage = $('body').data('filestorage'), blogUrl = $('body').data('blogurl'), blogTitle = $('body').data('blogtitle'); application.register( 'ghost:config', {apps: apps, fileStorage: fileStorage, blogUrl: blogUrl, tagsUI: tagsUI, blogTitle: blogTitle}, {instantiate: false} ); application.inject('route', 'config', 'ghost:config'); application.inject('controller', 'config', 'ghost:config'); application.inject('component', 'config', 'ghost:config'); } }; export default ConfigInitializer;
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { var i = Math.floor(Math.abs(n)); if (i === 0 || i === 1) return 1; return 5; } global.ng.common.locales['fr-vu'] = [ 'fr-VU', [['AM', 'PM'], u, u], u, [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.' ], [ 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre' ] ], u, [['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', '{1} \'à\' {0}', u, u], [',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'VUV', 'VT', 'vatu vanuatuan', { 'ARS': ['$AR', '$'], 'AUD': ['$AU', '$'], 'BEF': ['FB'], 'BMD': ['$BM', '$'], 'BND': ['$BN', '$'], 'BZD': ['$BZ', '$'], 'CAD': ['$CA', '$'], 'CLP': ['$CL', '$'], 'CNY': [u, '¥'], 'COP': ['$CO', '$'], 'CYP': ['£CY'], 'EGP': [u, '£E'], 'FJD': ['$FJ', '$'], 'FKP': ['£FK', '£'], 'FRF': ['F'], 'GBP': ['£GB', '£'], 'GIP': ['£GI', '£'], 'HKD': [u, '$'], 'IEP': ['£IE'], 'ILP': ['£IL'], 'ITL': ['₤IT'], 'JPY': [u, '¥'], 'KMF': [u, 'FC'], 'LBP': ['£LB', '£L'], 'MTP': ['£MT'], 'MXN': ['$MX', '$'], 'NAD': ['$NA', '$'], 'NIO': [u, '$C'], 'NZD': ['$NZ', '$'], 'RHD': ['$RH'], 'RON': [u, 'L'], 'RWF': [u, 'FR'], 'SBD': ['$SB', '$'], 'SGD': ['$SG', '$'], 'SRD': ['$SR', '$'], 'TOP': [u, '$T'], 'TTD': ['$TT', '$'], 'TWD': [u, 'NT$'], 'USD': ['$US', '$'], 'UYU': ['$UY', '$'], 'VUV': ['VT'], 'WST': ['$WS'], 'XCD': [u, '$'], 'XPF': ['FCFP'], 'ZMW': [u, 'Kw'] }, 'ltr', plural, [ [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin'] ], [ ['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u, ['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit'] ], [ '00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '04:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/logiql', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/logiql_highlight_rules', 'ace/mode/folding/coffee', 'ace/token_iterator', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/matching_brace_outdent'], function (require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LogiQLHighlightRules = require("./logiql_highlight_rules").LogiQLHighlightRules; var FoldMode = require("./folding/coffee").FoldMode; var TokenIterator = require("../token_iterator").TokenIterator; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function Mode() { this.HighlightRules = LogiQLHighlightRules; this.foldingRules = new FoldMode(); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); }; oop.inherits(Mode, TextMode); (function () { this.lineCommentStart = "//"; this.blockComment = { start: "/*", end: "*/" }; this.getNextLineIndent = function (state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (/comment|string/.test(endState)) return indent; if (tokens.length && tokens[tokens.length - 1].type == "comment.single") return indent; var match = line.match(); if (/(-->|<--|<-|->|{)\s*$/.test(line)) indent += tab; return indent; }; this.checkOutdent = function (state, line, input) { if (this.$outdent.checkOutdent(line, input)) return true; if (input !== "\n" && input !== "\r\n") return false; if (!/^\s+/.test(line)) return false; return true; }; this.autoOutdent = function (state, doc, row) { if (this.$outdent.autoOutdent(doc, row)) return; var prevLine = doc.getLine(row); var match = prevLine.match(/^\s+/); var column = prevLine.lastIndexOf(".") + 1; if (!match || !row || !column) return 0; var line = doc.getLine(row + 1); var startRange = this.getMatching(doc, { row: row, column: column }); if (!startRange || startRange.start.row == row) return 0; column = match[0].length; var indent = this.$getIndent(doc.getLine(startRange.start.row)); doc.replace(new Range(row + 1, 0, row + 1, column), indent); }; this.getMatching = function (session, row, column) { if (row == undefined) row = session.selection.lead; if ((typeof row === 'undefined' ? 'undefined' : _typeof(row)) == "object") { column = row.column; row = row.row; } var startToken = session.getTokenAt(row, column); var KW_START = "keyword.start", KW_END = "keyword.end"; var tok; if (!startToken) return; if (startToken.type == KW_START) { var it = new TokenIterator(session, row, column); it.step = it.stepForward; } else if (startToken.type == KW_END) { var it = new TokenIterator(session, row, column); it.step = it.stepBackward; } else return; while (tok = it.step()) { if (tok.type == KW_START || tok.type == KW_END) break; } if (!tok || tok.type == startToken.type) return; var col = it.getCurrentTokenColumn(); var row = it.getCurrentTokenRow(); return new Range(row, col, row, col + tok.value.length); }; this.$id = "ace/mode/logiql"; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/logiql_highlight_rules', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function (require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LogiQLHighlightRules = function LogiQLHighlightRules() { this.$rules = { start: [{ token: 'comment.block', regex: '/\\*', push: [{ token: 'comment.block', regex: '\\*/', next: 'pop' }, { defaultToken: 'comment.block' }] }, { token: 'comment.single', regex: '//.*' }, { token: 'constant.numeric', regex: '\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?[fd]?' }, { token: 'string', regex: '"', push: [{ token: 'string', regex: '"', next: 'pop' }, { defaultToken: 'string' }] }, { token: 'constant.language', regex: '\\b(true|false)\\b' }, { token: 'entity.name.type.logicblox', regex: '`[a-zA-Z_:]+(\\d|\\a)*\\b' }, { token: 'keyword.start', regex: '->', comment: 'Constraint' }, { token: 'keyword.start', regex: '-->', comment: 'Level 1 Constraint' }, { token: 'keyword.start', regex: '<-', comment: 'Rule' }, { token: 'keyword.start', regex: '<--', comment: 'Level 1 Rule' }, { token: 'keyword.end', regex: '\\.', comment: 'Terminator' }, { token: 'keyword.other', regex: '!', comment: 'Negation' }, { token: 'keyword.other', regex: ',', comment: 'Conjunction' }, { token: 'keyword.other', regex: ';', comment: 'Disjunction' }, { token: 'keyword.operator', regex: '<=|>=|!=|<|>', comment: 'Equality' }, { token: 'keyword.other', regex: '@', comment: 'Equality' }, { token: 'keyword.operator', regex: '\\+|-|\\*|/', comment: 'Arithmetic operations' }, { token: 'keyword', regex: '::', comment: 'Colon colon' }, { token: 'support.function', regex: '\\b(agg\\s*<<)', push: [{ include: '$self' }, { token: 'support.function', regex: '>>', next: 'pop' }] }, { token: 'storage.modifier', regex: '\\b(lang:[\\w:]*)' }, { token: ['storage.type', 'text'], regex: '(export|sealed|clauses|block|alias|alias_all)(\\s*\\()(?=`)' }, { token: 'entity.name', regex: '[a-zA-Z_][a-zA-Z_0-9:]*(@prev|@init|@final)?(?=(\\(|\\[))' }, { token: 'variable.parameter', regex: '([a-zA-Z][a-zA-Z_0-9]*|_)\\s*(?=(,|\\.|<-|->|\\)|\\]|=))' }] }; this.normalizeRules(); }; oop.inherits(LogiQLHighlightRules, TextHighlightRules); exports.LogiQLHighlightRules = LogiQLHighlightRules; }); define('ace/mode/folding/coffee', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function (require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function () {}; oop.inherits(FoldMode, BaseFoldMode); (function () { this.getFoldWidgetRange = function (session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function (session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent != -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent != -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start";else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start";else return ""; }; }).call(FoldMode.prototype); }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function (require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function initContext(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.id; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = { rangeCount: editor.multiSelect.rangeCount }; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var CstyleBehaviour = function CstyleBehaviour() { this.add("braces", "insertion", function (state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return { text: '{' + selected + '}', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', { column: cursor.column + 1, row: cursor.row }); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({ row: cursor.row, column: cursor.column + 1 }, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '(' + selected + ')', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', { column: cursor.column + 1, row: cursor.row }); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '[' + selected + ']', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', { column: cursor.column + 1, row: cursor.row }); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column - 1, cursor.column); if (leftChar == '\\') { return null; } var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if (token.value.length + col > selection.start.column) { break; } col += tokens[x].value.length; } if (!token || quotepos < 0 && token.type !== "comment" && (token.type !== "string" || selection.start.column !== token.value.length + col - 1 && token.value.lastIndexOf(quote) === token.value.length - 1)) { if (!CstyleBehaviour.isSaneInsertion(editor, session)) return; return { text: quote + quote, selection: [1, 1] }; } else if (token && token.type === "string") { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function (editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function (token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function (editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function (editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function (cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function (cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function () { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function () { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module', 'ace/range'], function (require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function MatchingBraceOutdent() {}; (function () { this.checkOutdent = function (line, input) { if (!/^\s+$/.test(line)) return false; return (/^\s*\}/.test(input) ); }; this.autoOutdent = function (doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({ row: row, column: column }); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column - 1), indent); }; this.$getIndent = function (line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
/** * @param {string} s * @return {boolean} */ const checkValidString = function (s) { let leftCount = 0, rightCount = 0, starCount = 0; let idx = 0; while (idx < s.length) { let ch = s[idx++]; if (ch === '(') { ++leftCount; } else if (ch === '*') { ++starCount; } else { // ch === ')' ++rightCount; if (rightCount > leftCount + starCount) { return false; } } } idx = s.length - 1; leftCount = rightCount = starCount = 0; while (idx >= 0) { let ch = s[idx--]; if (ch === ')') { ++rightCount; } else if (ch === '*') { ++starCount; } else { // ch === '(' ++leftCount; if (leftCount > rightCount + starCount) { return false; } } } return true; }; module.exports = checkValidString;
// noinspection JSUnusedLocalSymbols const React = require('react') const moment = require('moment') const agent = require('../agent') import {Link} from 'react-router' import {Row, Col} from 'react-bootstrap' import ClientForm from './ClientForm' import _ from 'underscore' class RegisterClient extends React.Component { constructor (props, context) { super(props) this.state = {} } save () { let client = JSON.parse(JSON.stringify(_(this.state).omit(['loading']))) client.dob = moment(client.dob).valueOf() this.setState({loading: true}) agent.post('/services/clients') .send(client) .then(({body}) => { body.saved = true this.setState(body) if (this.props.location.query.returnTo) { this.props.router.push({ pathname: `${this.props.location.query.returnTo}/${body.id}` }) } }) .catch((error) => { console.error(error) this.setState(client) }) } render () { const {query} = this.props.location const state = this.state return ( <div className='container'> <Row> <Col> <h1> <span>Register a New Client </span> <small> <span>or </span> <Link to={{pathname: `/clients/locate`, query: query}}>find an existing client</Link> </small> </h1> </Col> </Row> <ClientForm {...state} setState={(x) => this.setState(x)} save={() => this.save()} location={this.props.location} history={this.props.history} /> </div> ) } } RegisterClient.propTypes = { location: React.PropTypes.object, history: React.PropTypes.object, router: React.PropTypes.object } export default RegisterClient
/** * Created by liushuo on 17/2/20. */ import React , {Component} from 'react'; import {AppRegistry , ListView , Text , View, StyleSheet,TouchableOpacity, Image, Dimensions} from 'react-native'; let badgeDatas = require('../Json/BadgeData.json') let {width,height,scale} = Dimensions.get("window"); let cols = 3; let bWidth = 100; let hM = (width - 3 * bWidth) / (cols + 1) let vM = 25; export default class BagImageDemo extends Component { renderAllBadge(){ let allBadgeDatas = []; for (let i = 0; i<badgeDatas.data.length;i++){ let data = badgeDatas.data[i]; allBadgeDatas.push( <View key={i} style={styles.outViewStyle}> <Image style={styles.imageStyle} source={{uri:data.icon}}></Image> <Text style={styles.bottomTextsStyle}>{data.title}</Text> </View> ); } return allBadgeDatas; } render() { return ( <View style={styles.contain}> {/*返回所有数据包*/} {this.renderAllBadge()} </View> ) } } const styles = StyleSheet.create({ contain:{ backgroundColor:'#F5FCFF', flexDirection:"row", flexWrap:'wrap', }, outViewStyle:{ width:bWidth, height: bWidth, marginLeft:hM, marginTop:vM, backgroundColor:'red', alignItems:"center" }, imageStyle:{ width:80, height:80 }, bottomTextsStyle:{ fontSize:12 } });
$ = require("jquery"); jQuery = require("jquery"); var StatusTable = require("./content/status-table"); var ArchiveTable = require("./content/archive-table"); var FailuresTable = require("./content/failures-table"); var UploadTestFile = require("./content/upload-test-file"); var UploadCredentials = require("./content/upload-credentials"); var UploadServerInfo = require("./content/upload-server-info"); var UploadBatch = require("./content/upload-batch"); var Bluebird = require("bluebird"); var StandardReport = require("./content/standard-report"); var JmeterReportTable = require("./content/jmeter-report-table"); require('expose?$!expose?jQuery!jquery'); require("bootstrap-webpack"); require('./vendor/startbootstrap-sb-admin-2-1.0.8/deps'); require("./vendor/startbootstrap-sb-admin-2-1.0.8/dist/js/sb-admin-2"); var ss = require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/bootstrap/dist/css/bootstrap.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/metisMenu/dist/metisMenu.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/dist/css/sb-admin-2.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/font-awesome/css/font-awesome.min.css").toString(); ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/datatables/media/css/dataTables.jqueryui.min.css").toString(); function GetQueryStringParams(sParam){ var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++){ var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam){ return sParameterName[1]; } } } //module.exports = function(){ $(document).ready(function(){ $("<style></style>").text(ss).appendTo($("head")); new UploadTestFile($("form")); //new SwimLanes($("#swimlanes")); new UploadCredentials($("#credentials")); new UploadServerInfo($("#server-info")); new UploadBatch($("#batch")); if($("#batches-status")){ new StatusTable($("#batches-status"), "batches"); } if($("#runs-status")){ new StatusTable($("#runs-status"), "runs"); } if($("#standard-report")){ if(GetQueryStringParams("batchId")){ var batchId = GetQueryStringParams("batchId"); new StandardReport($("#standard-report"), batchId); new JmeterReportTable($("#jmeter-report-table"), batchId); } else { new FailuresTable($("#failures-table")); new ArchiveTable($("#archive-table")); } } }); //}
Meteor.publish('movieDetails.user', publishUserMovieDetails); function publishUserMovieDetails({ movieId }) { validate(); this.autorun(autorun); return; function validate() { new SimpleSchema({ movieId: ML.fields.id }).validate({ movieId }); } function autorun(computation) { if (!this.userId) { return this.ready(); } else { return Movies.find({ _id: movieId }, { fields: Movies.publicFields }); } } }
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'ul', classNames: 'ember-autocomplete-list', });
/** * Widget Footer Directive */ angular .module('Home') .directive('rdWidgetFooter', rdWidgetFooter); function rdWidgetFooter() { var directive = { requires: '^rdWidget', transclude: true, template: '<div class="widget-footer" ng-transclude></div>', restrict: 'E' }; return directive; };
game.PlayScreen = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { // reset the score game.data.score = 0; me.levelDirector.loadLevel("level01"); this.resetPlayer(0, 420); // the level i'm going to load // levelDirector is telling it what to look at var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {}); me.game.world.addChild(gameTimerManager, 0); // this adds the player to the screen var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {}); me.game.world.addChild(heroDeathManager, 0); var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {}); me.game.world.addChild(experienceManager, 0); me.input.bindKey(me.input.KEY.RIGHT, "right"); me.input.bindKey(me.input.KEY.LEFT, "left"); me.input.bindKey(me.input.KEY.SPACE, "jump"); me.input.bindKey(me.input.KEY.A, "attack"); // add our HUD to the game world this.HUD = new game.HUD.Container(); me.game.world.addChild(this.HUD); }, /** * action to perform when leaving this screen (state change) */ onDestroyEvent: function() { // remove the HUD from the game world me.game.world.removeChild(this.HUD); }, resetPlayer: function(x, y){ game.data.player = me.pool.pull("player", x, y, {}); me.game.world.addChild(game.data.player, 5); } }); // where the game starts
Palette = function(name,colors){ this.name = name; this.colors = colors; }; Palette.prototype.hasName = function(name){ return this.name.toLowerCase() == name.toLowerCase()?true:false; }; Palette.prototype.getRandomColor = function(){ return this.colors[(Math.floor(Math.random() * this.colors.length))]; }; Palette.prototype.getName = function(){ return this.name; }; Palette.prototype.setName = function(name){ this.name = name; }; Palette.prototype.getColors = function(){ return this.colors; }; Palette.prototype.setColors = function(colors){ this.colors = colors; }; Palette.generateRandomPalette = function(){ var colors = []; for(var i = 0; i< 5; i++){ colors.push(('#'+Math.floor(Math.random()*16777215).toString(16)).toUpperCase()); } return new Palette("RandomizePalette",colors); };
'use strict'; const inflect = require('i')(); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const options = { adapter: 'mongodb', connectionString: 'mongodb://127.0.0.1:27017/testDB', db: 'testDB', inflect: true }; console.log(JSON.stringify(options)); const runningAsScript = !module.parent; /* *** Elastic-Search mapping maker. *** * -------------------------------- * Generate scaffolded elastic-search mapping from a harvester app. Meant to be run @cmd line, but can also be required and used in code. #Usage: node mappingMaker.js path-to-harvester-app primary-es-graph-resource(e.g. people) file-to-create.json NB: argv[3] (in this case, "file-to-create.json") is optional. If not specified, no file will be written to disk; instead the mapping will be console.logged. */ const functionTypeLookup = { 'function Stri': 'string', 'function Numb': 'number', 'function Bool': 'boolean', 'function Date': 'date', 'function Buff': 'buffer', 'function Arra': 'array' }; function getFunctionType(fn) { return functionTypeLookup[fn.toString().substr(0, 13)]; } function MappingMaker() { } MappingMaker.prototype.generateMapping = function generateMapping(harvestApp, pov, outputFile) { let harvesterApp; if (_.isString(harvestApp)) { harvesterApp = require(harvestApp)(options); } else { harvesterApp = Promise.resolve(harvestApp); } return harvesterApp .catch() // harvestApp doesn't have to work perfectly; we just need its schemas. .then((_harvesterApp) => { return make(_harvesterApp, pov); }) .then((mappingData) => { if (outputFile) { console.log(`Saving mapping to ${outputFile}`); return fs.writeFileAsync(outputFile, JSON.stringify(mappingData, null, 4)).then(() => { console.log('Saved.'); return mappingData; }).error((e) => { console.error('Unable to save file, because: ', e.message); }); } console.log('Generated Mapping: '); console.log(JSON.stringify(mappingData, null, 4)); return mappingData; }); }; function make(harvestApp, pov) { const schemaName = inflect.singularize(pov); const startingSchema = harvestApp._schema[schemaName]; const maxDepth = 4; const _depth = 0; const retVal = {}; retVal[pov] = { properties: {} }; const _cursor = retVal[pov].properties; function getNextLevelSchema(propertyName, propertyValue, cursor, depth) { let nextCursor; if (depth === 1) { cursor.links = cursor.links || { type: 'nested' }; cursor.links.properties = cursor.links.properties || {}; cursor.links.properties[propertyName] = { type: 'nested', properties: {} }; nextCursor = cursor.links.properties[propertyName].properties; } else { if (depth === maxDepth) { return; } cursor[propertyName] = { type: 'nested', properties: {} }; nextCursor = cursor[propertyName].properties; } harvestApp._schema[propertyValue] && getLinkedSchemas(harvestApp._schema[propertyValue], nextCursor, depth); } function getLinkedSchemas(_startingSchema, cursor, depth) { if (depth >= maxDepth) { console.warn(`[Elastic-harvest] Graph depth of ${depth} exceeds ${maxDepth}. Graph dive halted prematurely` + ' - please investigate.'); // harvest schema may have circular references. return null; } const __depth = depth + 1; _.each(_startingSchema, (propertyValue, propertyName) => { if (typeof propertyValue !== 'function') { if (_.isString(propertyValue)) { getNextLevelSchema(propertyName, propertyValue, cursor, __depth); } else if (_.isArray(propertyValue)) { if (_.isString(propertyValue[0])) { getNextLevelSchema(propertyName, propertyValue[0], cursor, __depth); } else { getNextLevelSchema(propertyName, propertyValue[0].ref, cursor, __depth); } } else if (_.isObject(propertyValue)) { getNextLevelSchema(propertyName, propertyValue.ref, cursor, __depth); } } else { const fnType = getFunctionType(propertyValue); if (fnType === 'string') { cursor.id = { type: 'string', index: 'not_analyzed' }; cursor[propertyName] = { type: 'string', index: 'not_analyzed' }; } else if (fnType === 'number') { cursor[propertyName] = { type: 'long' }; } else if (fnType === 'date') { cursor[propertyName] = { type: 'date' }; } else if (fnType === 'boolean') { cursor[propertyName] = { type: 'boolean' }; } else if (fnType === 'array') { console.warn('[mapping-maker] Array-type scaffolding not yet implemented; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } else if (fnType === 'buffer') { console.warn('[mapping-maker] Buffer-type scaffolding not yet implemented; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } else { console.warn('[mapping-maker] unsupported type; ' + `The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`); } } }); return cursor; } getLinkedSchemas(startingSchema, _cursor, _depth); return retVal; } if (runningAsScript) { const mappingMaker = new MappingMaker(); mappingMaker.generateMapping(process.argv[2], process.argv[3], process.argv[4]); } else { module.exports = MappingMaker; }
$(document).ready(function(){(new WOW).init()}),$(document).ready(function(){var e=document.getElementById("scene");new Parallax(e);$.stellar()});
function noReservedDays(date) { var m = date.getMonth(), d = date.getDate(), y = date.getFullYear(); for (i = 0; i < reservedDays.length; i++) { if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) { return [false]; } } return [true]; } $("#input_from").datepicker({ dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"], dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"], firstDay: 1, dateFormat: "dd.mm.yy", constrainInput: true, beforeShowDay: noReservedDays, minDate: 0, onSelect: function(selected) { $("#input_until").datepicker("option", "minDate", selected); } }); $("#input_until").datepicker({ dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"], dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"], firstDay: 1, dateFormat: "dd.mm.yy", constrainInput: true, beforeShowDay: noReservedDays, minDate: 1, onSelect: function(selected) { $("#input_from").datepicker("option", "maxDate", selected); } });
define([], function() { function System(options) { var options = options || {}, requirements = options.requires ? options.requires.slice(0).sort() : []; return { getRequirements: function() { return requirements; }, init: options.init || function() {}, shutdown: options.shutdown || function() {}, update: options.update || function(game, entities) { for (var i = 0, len = entities.length; i < len; ++i) { this.updateEach(game, entities[i]); } }, updateEach: options.updateEach }; } return System; });
export const ic_alternate_email_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12 1.95c-5.52 0-10 4.48-10 10s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57v-1.43c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57v-1.43c0-5.52-4.48-10-10-10zm0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"},"children":[]}]};
/** * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /*jslint sloppy: true, plusplus: true */ /*global define, java, Packages, com */ define(['logger', 'env!env/file'], function (logger, file) { //Add .reduce to Rhino so UglifyJS can run in Rhino, //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce //but rewritten for brevity, and to be good enough for use by UglifyJS. if (!Array.prototype.reduce) { Array.prototype.reduce = function (fn /*, initialValue */) { var i = 0, length = this.length, accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { if (length) { while (!(i in this)) { i++; } accumulator = this[i++]; } } for (; i < length; i++) { if (i in this) { accumulator = fn.call(undefined, accumulator, this[i], i, this); } } return accumulator; }; } var JSSourceFilefromCode, optimize, mapRegExp = /"file":"[^"]+"/; //Bind to Closure compiler, but if it is not available, do not sweat it. try { JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); } catch (e) {} //Helper for closure compiler, because of weird Java-JavaScript interactions. function closurefromCode(filename, content) { return JSSourceFilefromCode.invoke(null, [filename, content]); } function getFileWriter(fileName, encoding) { var outFile = new java.io.File(fileName), outWriter, parentDir; parentDir = outFile.getAbsoluteFile().getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw "Could not create directory: " + parentDir.getAbsolutePath(); } } if (encoding) { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); } else { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); } return new java.io.BufferedWriter(outWriter); } optimize = { closure: function (fileName, fileContents, outFileName, keepLines, config) { config = config || {}; var result, mappings, optimized, compressed, baseName, writer, outBaseName, outFileNameMap, outFileNameMapContent, srcOutFileName, concatNameMap, jscomp = Packages.com.google.javascript.jscomp, flags = Packages.com.google.common.flags, //Set up source input jsSourceFile = closurefromCode(String(fileName), String(fileContents)), sourceListArray = new java.util.ArrayList(), options, option, FLAG_compilation_level, compiler, Compiler = Packages.com.google.javascript.jscomp.Compiler, CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner; logger.trace("Minifying file: " + fileName); baseName = (new java.io.File(fileName)).getName(); //Set up options options = new jscomp.CompilerOptions(); for (option in config.CompilerOptions) { // options are false by default and jslint wanted an if statement in this for loop if (config.CompilerOptions[option]) { options[option] = config.CompilerOptions[option]; } } options.prettyPrint = keepLines || options.prettyPrint; FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS']; FLAG_compilation_level.setOptionsForCompilationLevel(options); if (config.generateSourceMaps) { mappings = new java.util.ArrayList(); mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js")); options.setSourceMapLocationMappings(mappings); options.setSourceMapOutputPath(fileName + ".map"); } //Trigger the compiler Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']); compiler = new Compiler(); //fill the sourceArrrayList; we need the ArrayList because the only overload of compile //accepting the getDefaultExterns return value (a List) also wants the sources as a List sourceListArray.add(jsSourceFile); result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options); if (result.success) { optimized = String(compiler.toSource()); if (config.generateSourceMaps && result.sourceMap && outFileName) { outBaseName = (new java.io.File(outFileName)).getName(); srcOutFileName = outFileName + ".src.js"; outFileNameMap = outFileName + ".map"; //If previous .map file exists, move it to the ".src.js" //location. Need to update the sourceMappingURL part in the //src.js file too. if (file.exists(outFileNameMap)) { concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map'); file.saveFile(concatNameMap, file.readFile(outFileNameMap)); file.saveFile(srcOutFileName, fileContents.replace(/\/\# sourceMappingURL=(.+).map/, '/# sourceMappingURL=$1.src.js.map')); } else { file.saveUtf8File(srcOutFileName, fileContents); } writer = getFileWriter(outFileNameMap, "utf-8"); result.sourceMap.appendTo(writer, outFileName); writer.close(); //Not sure how better to do this, but right now the .map file //leaks the full OS path in the "file" property. Manually //modify it to not do that. file.saveFile(outFileNameMap, file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"')); fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map"; } else { fileContents = optimized; } return fileContents; } else { throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.'); } return fileContents; } }; return optimize; });
module.exports = ({ config }, options = {}) => config.module .rule('style') .test(/\.css$/) .use('style') .loader(require.resolve('style-loader')) .when(options.style, use => use.options(options.style)) .end() .use('css') .loader(require.resolve('css-loader')) .when(options.css, use => use.options(options.css));
/** * Created by Kaloyan on 24.5.2015 ã.. */ console.log('============'); console.log('Exercise 1: Exchange if first is greater'); var a = 5; var b = 2; if (a > b) { var temp = a; a = b; b = temp; } console.log(a + ' ' + b);
$(document).ready(function () { // Regex pour avoir les contenus des balises <amb> // Exemple : L'<amb>avocat</amb> mange des <amb>avocats</amb>. // Donne : $1 = avocat, puis $1 = avocats var regAmb = new RegExp('<amb>(.*?)</amb>', 'ig'); // Regex pour avoir les contenus des balises <amb> et leurs id // Exemple : L'<amb id="1">avocat</amb> mange des <amb id="2">avocats</amb>. // Donne : $1 = 1 et $3 = avocat, puis $1 = 2 et $3 = avocats var regAmbId = new RegExp('<amb id="([0-9]+)"( title=".*")?>(.*?)</amb>', 'ig'); // Le formulaire d'édition var editorForm = $("#phrase-editor-form"); // Div contenant le prototype du formulaire MAP var $container = $('div#proto_motsAmbigusPhrase'); // La div modifiable var phraseEditor = $("div.phrase-editor"); // Div des erreurs var errorForm = $('#form-errors'); // Le mode actif var modeEditor = $('#nav-editor li.active').data('mode'); // Pour numéroter le mot ambigu var indexMotAmbigu = 0; // Tableau des mots ambigus de la phrase var motsAmbigus = []; function getPhraseTexte() { return phraseEditor .html() .replace(/&nbsp;/ig, ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/<br>/g, '') .replace(/ style=""/g, '') .replace(/ title="Ce mot est ambigu \(id : [0-9]+\)"/ig, ''); } // Mise à jour du mode d'éditeur $('#nav-editor li').on('click', function(){ $('#nav-editor li.active').removeClass('active'); $(this).addClass('active'); var oldModeEditor = modeEditor; modeEditor = $(this).data('mode'); if (oldModeEditor != modeEditor) { if (modeEditor === 'wysiwyg') { // Affiche la phrase en mode HTML phraseEditor.html(phraseEditor.text()); $.each(phraseEditor.find('amb'), function (i, val) { $(this).attr('title', 'Ce mot est ambigu (id : ' + $(this).attr('id') + ')'); }); } else if (modeEditor === 'source') { // Affiche la phrase en mode texte phraseEditor.text(getPhraseTexte()); } } }); // Ajout d'un mot ambigu $("#addAmb").on('click', function () { var sel = window.getSelection(); var selText = sel.toString(); // S'il y a bien un mot séléctionné if (selText.trim() !== '') { var regAlpha = /[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ]/; var parentBase = sel.anchorNode.parentNode; var parentFocus = sel.focusNode.parentNode; var numPrevChar = Math.min(sel.focusOffset, sel.anchorOffset) - 1; var numFirstChar = Math.min(sel.focusOffset, sel.anchorOffset); var numLastChar = Math.max(sel.focusOffset, sel.anchorOffset) - 1; var numNextChar = Math.max(sel.focusOffset, sel.anchorOffset); var prevChar = sel.focusNode.textContent.charAt(numPrevChar); var firstChar = sel.focusNode.textContent.charAt(numFirstChar); var lastChar = sel.focusNode.textContent.charAt(numLastChar); var nextChar = sel.focusNode.textContent.charAt(numNextChar); errorForm.empty(); var success = true; if (phraseEditor.html() != parentBase.innerHTML || phraseEditor.html() != parentFocus.innerHTML) { errorForm.append('Le mot sélectionné est déjà ambigu<br>'); success = false; } if (sel.anchorNode != sel.focusNode) { errorForm.append('Le mot sélectionné contient déjà un mot ambigu<br>'); success = false; } if (prevChar.match(regAlpha)) { errorForm.append('Le premier caractère sélectionné ne doit pas être précédé d\'un caractère alphabétique<br>'); success = false; } if (!firstChar.match(regAlpha)) { errorForm.append('Le premier caractère sélectionné doit être alphabétique<br>'); success = false; } if (!lastChar.match(regAlpha)) { errorForm.append('Le dernier caractère sélectionné doit être alphabétique<br>'); success = false; } if (nextChar.match(regAlpha)) { errorForm.append('Le dernier caractère sélectionné ne doit pas être suivi d\'un caractère alphabétique<br>'); success = false; } // S'il y a une erreur on affiche la div des erreurs if (!success) { errorForm.show(); return false; } // Sinon on cache la div else { errorForm.hide(); } // Transformation du texte sélectionné en mot ambigu selon le mode utilisé var range = document.getSelection().getRangeAt(0); var clone = $(range.cloneContents()); range.deleteContents(); range.insertNode($('<amb>').append(clone).get(0)); document.getSelection().setPosition(null); phraseEditor.trigger('input'); } }); // A chaque modification de la phrase phraseEditor.on('input', function (){ var phrase = getPhraseTexte(); // Compte le nombre d'occurence de balise <amb> var replaced = phrase.search(regAmb) >= 0; // Si au moins 1 if(replaced) { // On ajout dans la balise <amb> l'id du mot ambigu var temp = phrase.replace(regAmb, function ($0, motAmbigu) { indexMotAmbigu++; var indexLocal = indexMotAmbigu; motsAmbigus[indexMotAmbigu] = motAmbigu; // On ajoute le nom unique et l'id var template = $container.attr('data-prototype') .replace(/__name__label__/g, '') .replace(/__name__/g, indexMotAmbigu) .replace(/__id__/g, indexMotAmbigu) .replace(/__MA__/g, motAmbigu); var $prototype = $(template); // Trouve la balise qui à la class amb var amb = $prototype.find('.amb'); // Ajoute la valeur du mot ambigu en supprimant les espaces avant et après le mot, et ajoute l'id amb.val(motAmbigu); $prototype.attr('id', 'rep' + indexMotAmbigu); var $deleteLink = $('<a href="#" class="sup-amb btn btn-danger">Supprimer le mot ambigu</a>'); $prototype.find('.gloseAction').append($deleteLink); getGloses($prototype.find('select.gloses'), motAmbigu, function () { // Pour la page d'édition, sélection des gloses automatique if (typeof reponsesOri != 'undefined') { reponsesOri.forEach((item, index) => { if (item.map_ordre == indexLocal) { $prototype.find('option[value=' + item.glose_id + ']').prop('selected', true) } }); } }); $container.append($prototype); if (modeEditor == 'wysiwyg') { return '<amb id="' + indexMotAmbigu + '" title="Ce mot est ambigu (id : ' + indexMotAmbigu + ')">' + motAmbigu + '</amb>'; } else { return '<amb id="' + indexMotAmbigu + '">' + motAmbigu + '</amb>'; } }); if (modeEditor == 'wysiwyg') { phraseEditor.html(temp); } else { phraseEditor.text(temp); } } var phrase = getPhraseTexte(); phrase.replace(regAmbId, function ($0, $1, $2, $3) { var motAmbiguForm = $('#phrase_motsAmbigusPhrase_' + $1 + '_valeur'); // Mot ambigu modifié dans la phrase -> passage en rouge du MA dans le formulaire if (motsAmbigus[$1] != $3) { motAmbiguForm.val($3).css('color', 'red'); } // Si le MA modifié reprend sa valeur initiale -> efface la couleur rouge du MA dans le formulaire else if (motsAmbigus[$1] != motAmbiguForm.val($3)) { motAmbiguForm.val(motsAmbigus[$1]).css('color', ''); } }); }); phraseEditor.trigger('input'); // Pour mettre en forme en cas de phrase au chargement (édition ou création échouée) // Mise à jour des gloses des mots ambigus phraseEditor.on('focusout', function () { var phrase = getPhraseTexte(); phrase.replace(regAmbId, function ($0, $1, $2, $3) { if (motsAmbigus[$1] != $3) { $('#phrase_motsAmbigusPhrase_' + $1 + '_valeur').trigger('focusout'); motsAmbigus[$1] = $3; } }); }); // Désactive la touche entrée dans l'éditeur de phrase phraseEditor.on('keypress', function(e) { var keyCode = e.which; if (keyCode == 13) { return false; } }); // Coller sans le formatage phraseEditor.on('paste', function(e) { e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/plain'); if (modeEditor == 'wysiwyg') { $(this).html(text); } else { $(this).text(text); } phraseEditor.trigger('input'); // Pour mettre en forme après avoir collé }); // Modification d'un mot ambigu editorForm.on('input', '.amb', function () { // On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, ''); // Mot ambigu modifié -> passage en rouge du MA if (motsAmbigus[id] != $(this).val()) { $(this).css('color', 'red'); } // Si le MA modifié reprend sa valeur initiale -> efface la couleur rouge du MA else { $(this).css('color', ''); } var phrase = getPhraseTexte(); // Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu var reg3 = new RegExp('<amb id="' + id + '">(.*?)' + '</amb>', 'g'); // Met à jour le mot ambigu dans la phrase if (modeEditor == 'wysiwyg') { phraseEditor.html(phrase.replace(reg3, '<amb id="' + id + '" title="Ce mot est ambigu (id : ' + id + ')">' + $(this).val() + '</amb>')); } else { phraseEditor.text(phrase.replace(reg3, '<amb id="' + id + '">' + $(this).val() + '</amb>')); } }); // Mise à jour des gloses d'un mot ambigu editorForm.on('focusout', '.amb', function (){ // On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, ''); if (motsAmbigus[id] != $(this).val()) { $(this).css('color', ''); motsAmbigus[id] = $(this).val(); var phrase = getPhraseTexte(); // Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu var reg3 = new RegExp('<amb id="' + id + '">(.*?)' + '</amb>', 'g'); // Met à jour le mot ambigu dans la phrase if (modeEditor == 'wysiwyg') { phraseEditor.html(phrase.replace(reg3, '<amb id="' + id + '" title="Ce mot est ambigu (id : ' + id + ')">' + $(this).val() + '</amb>')); } else { phraseEditor.text(phrase.replace(reg3, '<amb id="' + id + '">' + $(this).val() + '</amb>')); } getGloses($(this).closest('.colAmb').next().find('select.gloses'), $(this).val()); } }); // Suppression d'un mot ambigu editorForm.on('click', '.sup-amb', function(e) { $(this).closest('.reponseGroupe').trigger('mouseleave'); var phrase = getPhraseTexte(); // On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, ''); delete motsAmbigus[id]; // Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu var reg3 = new RegExp('<amb id="' + id + '">(.*?)</amb>', 'g'); // Modifie le textarea pour supprimé la balise <amb id=""></amb> et remettre le contenu if (modeEditor == 'wysiwyg') { phraseEditor.html(phrase.replace(reg3, '$1')); } else { phraseEditor.text(phrase.replace(reg3, '$1')); } $(this).closest('.reponseGroupe').remove(); e.preventDefault(); // Évite qu'un # soit ajouté dans l'URL }); // A la soumission du formulaire $('.btn-phrase-editor').on('click', function(){ $('#phrase_contenu').val(getPhraseTexte()); }); });
'use strict'; var express = require('express'), logger = require('morgan'), bodyParser = require('body-parser'), stylus = require('stylus'), cookieParser = require('cookie-parser'), session = require('express-session'), passport = require('passport'); module.exports = function(app, config) { function compile(str, path) { // compile function for stylus return stylus(str).set('filename', path); } app.set('views', config.rootPath + '/server/views'); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(cookieParser()); app.use(bodyParser()); app.use(session({secret: 'multi vision unicorns'})); app.use(passport.initialize()); app.use(passport.session()); app.use(stylus.middleware( { src: config.rootPath + '/public', compile: compile } )); app.use(express.static(config.rootPath + '/public')); }
/** * Created by cin on 1/18/14. */ /** * Created by cin on 1/18/14. */ var _ = require('underscore'), chance = new (require('chance'))(), syBookshelf = require('./base'), User = require('./user'), CoStatus = require('./co-status'), UserCooperation = require('./user-cooperation'), UserCooperations = UserCooperation.Set, Picture = require('./picture'), Pictures = Picture.Set, CoComment = require('./co-comment'), Cooperation, Cooperations, config = require('../config'), tbCooperation = 'cooperations', fkStatus = 'statusid', fkCooperation = 'cooperationid', fkOwner = 'ownerid'; Cooperation = module.exports = syBookshelf.Model.extend({ tableName: tbCooperation, fields: [ 'id', 'name', 'description', 'company', 'avatar', 'statusid', 'ownerid', 'isprivate', 'regdeadline', 'createtime' ], appended: ['user', 'status'], fieldToAssets: { avatar: 'cooperations' }, defaults: function () { return { createtime: new Date() } }, toJSON: function () { var self = this, Model = this.constructor, ret = Model.__super__.toJSON.apply(this, arguments); _.each(this.fieldToAssets, function (type, field) { if (self.get(field) != null) { var file = self.getAssetPath(type); ret[field] = config.toStaticURI(file) + '?t=' + ret[field]; } }); return ret; }, saving: function () { return Cooperation.__super__ .saving.apply(this, arguments); }, usership: function () { return this.hasMany(UserCooperations, fkCooperation); }, fetched: function (model, attrs, options) { return Cooperation.__super__.fetched.apply(this, arguments) .return(model) .call('countComments') .call('countUsership') .call('countPictures') .then(function (cooperation) { return model.related('pictures').fetch(); }) .then(function () { if (!options['detailed']) return; return model.related('cocomments') .query(function (qb) { qb.orderBy('id', 'desc'); }).fetch(); }) }, countUsership: function () { var self = this; return this.usership().fetch() .then(function (userships) { var numUserships = userships.length; return self.data('numUserships', numUserships); }) }, status: function () { return this.belongsTo(CoStatus, fkStatus); }, user: function () { return this.belongsTo(require('./user'), fkOwner); }, cocomments: function () { return this.hasMany(CoComment, 'cooperationid'); }, pictures: function () { return this.hasMany(Picture, 'cooperationid'); }, countComments: function () { var self = this; return this.cocomments().fetch() .then(function (cocomments) { var numComments = cocomments.length; return self.data('numComments', numComments); }); }, countPictures: function () { var self = this; return Pictures.forge().query() .where(fkCooperation, '=', self.id) .count('id') .then(function (d) { return self.data('numPictures', d[0]["count(`id`)"]); }); } }, { randomForge: function () { var status = _.random(1, 2); return Cooperation.forge({ 'name': chance.word(), 'description': chance.paragraph(), 'ownerid': chance.integer({ min: 1, max: 20 }), 'company': chance.word(), 'avatar': chance.word(), 'statusid': status, 'isprivate': chance.bool(), 'regdeadline': chance.date({ year: 2013 }) }); } }); Cooperations = Cooperation.Set = syBookshelf.Collection.extend({ model: Cooperation, lister: function (req, qb) { var query = req.query; this.qbWhere(qb, req, query, ['id', 'statusid', 'ownerid', 'isprivate'], tbCooperation); if (!req.query['fuzzy']) { this.qbWhere(qb, req, query, ['name', 'company'], tbCooperation); } else { this.qbWhereLike(qb, req, query, ['name', 'description', 'company'], tbCooperation); } } });
'use strict'; var mongoose = require('mongoose'); require('./models/StockPoint'); require('./models/Pattern'); var mongoDbURL = 'mongodb://localhost/pttnrs'; if (process.env.MONGOHQ_URL) { mongoDbURL = process.env.MONGOHQ_URL; } mongoose.connect(mongoDbURL);
function setMaximizeCookie(i,e,a){if(a){var o=new Date;o.setTime(o.getTime()+864e5*a);var t="; expires="+o.toGMTString()}else var t="";document.cookie=i+"="+e+t+"; path=/"}function getMaximizeCookie(i){for(var e=i+"=",a=document.cookie.split(";"),o=0;o<a.length;o++){for(var t=a[o];" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return t.substring(e.length,t.length)}return null}var cookie_scaniaBootstrap_maximize=getMaximizeCookie("scaniaBootstrap_maximize");"maximized"===cookie_scaniaBootstrap_maximize&&($("body").addClass("maximized"),$("#maximize-icon").toggleClass("icon-fullscreen icon-resize-small")),$("#maximize-button").click(function(){$(this).children("#maximize-icon").toggleClass("icon-fullscreen icon-resize-small"),$("body").toggleClass("maximized"),$("body").hasClass("maximized")?setMaximizeCookie("scaniaBootstrap_maximize","maximized",30):setMaximizeCookie("scaniaBootstrap_maximize","minimized",30)});
// Copyright IBM Corp. 2014. All Rights Reserved. // Node module: async-tracker // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT var assert = require('assert'); require('../index.js'); var fs = require('fs'); var util = require('util'); var cnt = 0; var Listener = function() { var evtName = asyncTracker.events.fs.open; this.deferredCreated = {}; this.invokeDeferred = {}; this.deferredReleased = {}; this.deferredCreated[evtName] = function(fName, fId, args) { assert.equal(cnt, 0); cnt += 1; }; this.deferredCreated['default'] = function(fName, fId, args) { assert.equal(cnt, 4); cnt += 1; }; this.invokeDeferred[evtName] = function(fName, fId, next) { assert.equal(cnt, 2); cnt += 1; next(); }; this.invokeDeferred['default'] = function(fName, fId, next) { assert.equal(cnt, 6); cnt += 1; next(); }; this.deferredReleased[evtName] = function(fName, fId) { assert.equal(cnt, 5); cnt += 1; }; this.deferredReleased['default'] = function(fName, fId) { assert.equal(cnt, 7); cnt += 1; }; this.objectCreated = function(obj) { assert.equal(cnt, 1); cnt += 1; }; this.objectReleased = function(obj) { assert.equal(cnt, 3); cnt += 1; }; }; var listener = new Listener(); asyncTracker.addListener(listener, 'listener'); function closeCallback() { } function openCallback(err, fd) { fs.close(fd, closeCallback); } fs.open(__filename, 'r', openCallback); asyncTracker.removeListener('listener');
var prettyURLs = require('../middleware/pretty-urls'), cors = require('../middleware/api/cors'), urlRedirects = require('../middleware/url-redirects'), auth = require('../../auth'); /** * Auth Middleware Packages * * IMPORTANT * - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect * - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains * - url redirects MUST happen after cors, otherwise cors header can get lost on redirect */ /** * Authentication for public endpoints */ module.exports.authenticatePublic = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, // This is a labs-enabled middleware auth.authorize.requiresAuthorizedUserPublicAPI, cors, urlRedirects, prettyURLs ]; /** * Authentication for private endpoints */ module.exports.authenticatePrivate = [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedUser, cors, urlRedirects, prettyURLs ]; /** * Authentication for client endpoints */ module.exports.authenticateClient = function authenticateClient(client) { return [ auth.authenticate.authenticateClient, auth.authenticate.authenticateUser, auth.authorize.requiresAuthorizedClient(client), cors, urlRedirects, prettyURLs ]; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SearchBar = function (_Component) { _inherits(SearchBar, _Component); function SearchBar(props) { _classCallCheck(this, SearchBar); var _this = _possibleConstructorReturn(this, (SearchBar.__proto__ || Object.getPrototypeOf(SearchBar)).call(this, props)); _this.state = { term: '' }; _this.onInputChange = _this.onInputChange.bind(_this); return _this; } _createClass(SearchBar, [{ key: 'onInputChange', value: function onInputChange(term) { this.setState({ term: term }); this.props.getResults(term); } }, { key: 'render', value: function render() { var _this2 = this; return _react2.default.createElement( 'div', { className: 'searchBarContainer' }, _react2.default.createElement('input', { type: 'text', value: this.state.term, onChange: function onChange(event) { return _this2.onInputChange(event.target.value); } }) ); } }]); return SearchBar; }(_react.Component); exports.default = SearchBar; {/*<button><i id="searchIcon" className="fa fa-search" /></button>*/} //# sourceMappingURL=searchbar-compiled.js.map
var SuperheroesShowRoute = Ember.Route.extend({ model: function(params) { return(this.store.find('superhero', params.id)); } }); export default SuperheroesShowRoute;
{ if (this.props.x === 227) { return React.createElement( "span", { className: "_38my" }, "Campaign Details", null, React.createElement("span", { className: "_c1c" }) ); } if (this.props.x === 265) { return React.createElement( "span", { className: "_38my" }, [ React.createElement( "span", { key: 1 }, "Campaign ID", ": ", "98010048849317" ), React.createElement( "div", { className: "_5lh9", key: 2 }, React.createElement( FluxContainer_AdsCampaignGroupStatusSwitchContainer_119, { x: 264 } ) ) ], null, React.createElement("span", { className: "_c1c" }) ); } }
const Discord = require("discord.js"); const client = new Discord.Client(); const settings = require("./settings.json"); const chalk = require("chalk"); const fs = require("fs"); const moment = require("moment"); require("./util/eventLoader")(client); const log = message => { console.log(`[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir('./commands/', (err, files) => { if (err) console.error(err); log(`Loading a total of ${files.length} commands.`); files.forEach(f => { let props = require(`./commands/${f}`); log(`Loading Command: ${props.help.name}. 👌`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./commands/${command}`)]; let cmd = require(`./commands/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.on("ready", () => { const games = ["Not a Game", "The Joker Game Returns", "The Coven", "Nintendo: Choose Your Own Character 2!", "PokéDonalds"]; setInterval(() => { const playingGame = games[~~(Math.random() * games.length)]; console.log(`Changing playing game to ${playingGame} now`); client.user.setGame(playingGame); }, 1800000); client.channels.get("339257481740156928").fetchMessages({ limit: 30 }) .then(messages => console.log(`Received ${messages.size} messages`)) .catch(console.error); }); client.elevation = message => { /* This function should resolve to an ELEVATION level which is then sent to the command handler for verification*/ let permlvl = 0; let mod_role = message.guild.roles.find("name", settings.modrolename); if (mod_role && message.member.roles.has(mod_role.id)) permlvl = 2; let admin_role = message.guild.roles.find("name", settings.adminrolename); if (admin_role && message.member.roles.has(admin_role.id)) permlvl = 3; if (message.author.id === settings.ownerid) permlvl = 4; return permlvl; }; let autoResponse = { "ayy": "lmao", "ayyy": "lmao", "ayyyy": "lmao", "that's hot": "eso es caliente", "lenny": "( ͡° ͜ʖ ͡°)", "eso es caliente": "that's hot", "drewbie": "!kick drewbie" }; client.on("message", message => { if (message.content === "lala") { console.log(guild.members.find(nickname, 'asd')); } if (message.author.bot) return; let msg = message.content.toLowerCase(); if (autoResponse[msg]) { message.channel.send(autoResponse[msg]); } }); var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; // client.on('debug', e => { // console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); // }); client.on("warn", e => { console.log(chalk.bgYellow(e.replace(regToken, "that was redacted"))); }); client.on("error", e => { console.log(chalk.bgRed(e.replace(regToken, "that was redacted"))); }); client.login(process.env.TOKEN);
/* * provider.js: Abstraction providing an interface into pluggable configuration storage. * * (C) 2011, Nodejitsu Inc. * */ var async = require('async'), common = require('./common'); // // ### function Provider (options) // #### @options {Object} Options for this instance. // Constructor function for the Provider object responsible // for exposing the pluggable storage features of `nconf`. // var Provider = exports.Provider = function (options) { // // Setup default options for working with `stores`, // `overrides`, `process.env` and `process.argv`. // options = options || {}; this.stores = {}; this.sources = []; this.init(options); }; // // Define wrapper functions for using basic stores // in this instance // ['argv', 'env', 'file'].forEach(function (type) { Provider.prototype[type] = function (options) { return this.add(type, options); }; }); // // Define wrapper functions for using // overrides and defaults // ['defaults', 'overrides'].forEach(function (type) { Provider.prototype[type] = function (options) { return this.add('literal', options); }; }); // // ### function use (name, options) // #### @type {string} Type of the nconf store to use. // #### @options {Object} Options for the store instance. // Adds (or replaces) a new store with the specified `name` // and `options`. If `options.type` is not set, then `name` // will be used instead: // // provider.use('file'); // provider.use('file', { type: 'file', filename: '/path/to/userconf' }) // Provider.prototype.use = function (name, options) { options = options || {}; var type = options.type || name; function sameOptions (store) { return Object.keys(options).every(function (key) { return options[key] === store[key]; }); } var store = this.stores[name], update = store && !sameOptions(store); if (!store || update) { if (update) { this.remove(name); } this.add(name, options); } return this; }; // // ### function add (name, options) // #### @name {string} Name of the store to add to this instance // #### @options {Object} Options for the store to create // Adds a new store with the specified `name` and `options`. If `options.type` // is not set, then `name` will be used instead: // // provider.add('memory'); // provider.add('userconf', { type: 'file', filename: '/path/to/userconf' }) // Provider.prototype.add = function (name, options) { options = options || {}; var type = options.type || name; if (!require('../nconf')[common.capitalize(type)]) { throw new Error('Cannot add store with unknown type: ' + type); } this.stores[name] = this.create(type, options); if (this.stores[name].loadSync) { this.stores[name].loadSync(); } return this; }; // // ### function remove (name) // #### @name {string} Name of the store to remove from this instance // Removes a store with the specified `name` from this instance. Users // are allowed to pass in a type argument (e.g. `memory`) as name if // this was used in the call to `.add()`. // Provider.prototype.remove = function (name) { delete this.stores[name]; return this; }; // // ### function create (type, options) // #### @type {string} Type of the nconf store to use. // #### @options {Object} Options for the store instance. // Creates a store of the specified `type` using the // specified `options`. // Provider.prototype.create = function (type, options) { return new (require('../nconf')[common.capitalize(type.toLowerCase())])(options); }; // // ### function init (options) // #### @options {Object} Options to initialize this instance with. // Initializes this instance with additional `stores` or `sources` in the // `options` supplied. // Provider.prototype.init = function (options) { var self = this; // // Add any stores passed in through the options // to this instance. // if (options.type) { this.add(options.type, options); } else if (options.store) { this.add(options.store.name || options.store.type, options.store); } else if (options.stores) { Object.keys(options.stores).forEach(function (name) { var store = options.stores[name]; self.add(store.name || name || store.type, store); }); } // // Add any read-only sources to this instance // if (options.source) { this.sources.push(this.create(options.source.type || options.source.name, options.source)); } else if (options.sources) { Object.keys(options.sources).forEach(function (name) { var source = options.sources[name]; self.sources.push(self.create(source.type || source.name || name, source)); }); } }; // // ### function get (key, callback) // #### @key {string} Key to retrieve for this instance. // #### @callback {function} **Optional** Continuation to respond to when complete. // Retrieves the value for the specified key (if any). // Provider.prototype.get = function (key, callback) { // // If there is no callback we can short-circuit into the default // logic for traversing stores. // if (!callback) { return this._execute('get', 1, key, callback); } // // Otherwise the asynchronous, hierarchical `get` is // slightly more complicated because we do not need to traverse // the entire set of stores, but up until there is a defined value. // var current = 0, names = Object.keys(this.stores), self = this, response; async.whilst(function () { return typeof response === 'undefined' && current < names.length; }, function (next) { var store = self.stores[names[current]]; current++; if (store.get.length >= 2) { return store.get(key, function (err, value) { if (err) { return next(err); } response = value; next(); }); } response = store.get(key); next(); }, function (err) { return err ? callback(err) : callback(null, response); }); }; // // ### function set (key, value, callback) // #### @key {string} Key to set in this instance // #### @value {literal|Object} Value for the specified key // #### @callback {function} **Optional** Continuation to respond to when complete. // Sets the `value` for the specified `key` in this instance. // Provider.prototype.set = function (key, value, callback) { return this._execute('set', 2, key, value, callback); }; // // ### function reset (callback) // #### @callback {function} **Optional** Continuation to respond to when complete. // Clears all keys associated with this instance. // Provider.prototype.reset = function (callback) { return this._execute('reset', 0, callback); }; // // ### function clear (key, callback) // #### @key {string} Key to remove from this instance // #### @callback {function} **Optional** Continuation to respond to when complete. // Removes the value for the specified `key` from this instance. // Provider.prototype.clear = function (key, callback) { return this._execute('clear', 1, key, callback); }; // // ### function merge ([key,] value [, callback]) // #### @key {string} Key to merge the value into // #### @value {literal|Object} Value to merge into the key // #### @callback {function} **Optional** Continuation to respond to when complete. // Merges the properties in `value` into the existing object value at `key`. // // 1. If the existing value `key` is not an Object, it will be completely overwritten. // 2. If `key` is not supplied, then the `value` will be merged into the root. // Provider.prototype.merge = function () { var self = this, args = Array.prototype.slice.call(arguments), callback = typeof args[args.length - 1] === 'function' && args.pop(), value = args.pop(), key = args.pop(); function mergeProperty (prop, next) { return self._execute('merge', 2, prop, value[prop], next); } if (!key) { if (Array.isArray(value) || typeof value !== 'object') { return onError(new Error('Cannot merge non-Object into top-level.'), callback); } return async.forEach(Object.keys(value), mergeProperty, callback || function () { }) } return this._execute('merge', 2, key, value, callback); }; // // ### function load (callback) // #### @callback {function} Continuation to respond to when complete. // Responds with an Object representing all keys associated in this instance. // Provider.prototype.load = function (callback) { var self = this; function getStores () { return Object.keys(self.stores).map(function (name) { return self.stores[name]; }); } function loadStoreSync(store) { if (!store.loadSync) { throw new Error('nconf store ' + store.type + ' has no loadSync() method'); } return store.loadSync(); } function loadStore(store, next) { if (!store.load && !store.loadSync) { return next(new Error('nconf store ' + store.type + ' has no load() method')); } return store.loadSync ? next(null, store.loadSync()) : store.load(next); } function loadBatch (targets, done) { if (!done) { return common.merge(targets.map(loadStoreSync)); } async.map(targets, loadStore, function (err, objs) { return err ? done(err) : done(null, common.merge(objs)); }); } function mergeSources (data) { // // If `data` was returned then merge it into // the system store. // if (data && typeof data === 'object') { self.use('sources', { type: 'literal', store: data }); } } function loadSources () { // // If we don't have a callback and the current // store is capable of loading synchronously // then do so. // if (!callback) { mergeSources(loadBatch(self.sources)); return loadBatch(getStores()); } loadBatch(self.sources, function (err, data) { if (err) { return callback(err); } mergeSources(data); return loadBatch(getStores(), callback); }); } return self.sources.length ? loadSources() : loadBatch(getStores(), callback); }; // // ### function save (value, callback) // #### @value {Object} **Optional** Config object to set for this instance // #### @callback {function} Continuation to respond to when complete. // Removes any existing configuration settings that may exist in this // instance and then adds all key-value pairs in `value`. // Provider.prototype.save = function (value, callback) { if (!callback && typeof value === 'function') { callback = value; value = null; } var self = this, names = Object.keys(this.stores); function saveStoreSync(name) { var store = self.stores[name]; // // If the `store` doesn't have a `saveSync` method, // just ignore it and continue. // return store.saveSync ? store.saveSync() : null; } function saveStore(name, next) { var store = self.stores[name]; // // If the `store` doesn't have a `save` or saveSync` // method(s), just ignore it and continue. // if (!store.save && !store.saveSync) { return next(); } return store.saveSync ? next(null, store.saveSync()) : store.save(next); } // // If we don't have a callback and the current // store is capable of saving synchronously // then do so. // if (!callback) { return common.merge(names.map(saveStoreSync)); } async.map(names, saveStore, function (err, objs) { return err ? callback(err) : callback(); }); }; // // ### @private function _execute (action, syncLength, [arguments]) // #### @action {string} Action to execute on `this.store`. // #### @syncLength {number} Function length of the sync version. // #### @arguments {Array} Arguments array to apply to the action // Executes the specified `action` on all stores for this instance, ensuring a callback supplied // to a synchronous store function is still invoked. // Provider.prototype._execute = function (action, syncLength /* [arguments] */) { var args = Array.prototype.slice.call(arguments, 2), callback = typeof args[args.length - 1] === 'function' && args.pop(), destructive = ['set', 'clear', 'merge'].indexOf(action) !== -1, self = this, response; function runAction (name, next) { var store = self.stores[name]; if (destructive && store.readOnly) { return next(); } return store[action].length > syncLength ? store[action].apply(store, args.concat(next)) : next(null, store[action].apply(store, args)); } if (callback) { return async.forEach(Object.keys(this.stores), runAction, function (err) { return err ? callback(err) : callback(); }); } Object.keys(this.stores).forEach(function (name) { if (typeof response === 'undefined') { var store = self.stores[name]; if (destructive && store.readOnly) { return; } response = store[action].apply(store, args); } }); return response; } // // Throw the `err` if a callback is not supplied // function onError(err, callback) { if (callback) { return callback(err); } throw err; }
import React from 'react'; import { storiesOf } from '@storybook/react'; import moment from 'moment'; import { withKnobs, number, object, boolean, text, select, date, array, color, files, } from '../../src'; const stories = storiesOf('Example of Knobs', module); stories.addDecorator(withKnobs); stories.add('simple example', () => <button>{text('Label', 'Hello Button')}</button>); stories.add('with all knobs', () => { const name = text('Name', 'Tom Cary'); const dob = date('DOB', new Date('January 20 1887')); const bold = boolean('Bold', false); const selectedColor = color('Color', 'black'); const favoriteNumber = number('Favorite Number', 42); const comfortTemp = number('Comfort Temp', 72, { range: true, min: 60, max: 90, step: 1 }); const passions = array('Passions', ['Fishing', 'Skiing']); const images = files('Happy Picture', 'image/*', [ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfiARwMCyEWcOFPAAAAP0lEQVQoz8WQMQoAIAwDL/7/z3GwghSp4KDZyiUpBMCYUgd8rehtH16/l3XewgU2KAzapjXBbNFaPS6lDMlKB6OiDv3iAH1OAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE4LTAxLTI4VDEyOjExOjMzLTA3OjAwlAHQBgAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxOC0wMS0yOFQxMjoxMTozMy0wNzowMOVcaLoAAAAASUVORK5CYII=', ]); const customStyle = object('Style', { fontFamily: 'Arial', padding: 20, }); const style = { ...customStyle, fontWeight: bold ? 800 : 400, favoriteNumber, color: selectedColor, }; return ( <div style={style}> I'm {name} and I was born on "{moment(dob).format('DD MMM YYYY')}" I like:{' '} <ul>{passions.map(p => <li key={p}>{p}</li>)}</ul> <p>My favorite number is {favoriteNumber}.</p> <p>My most comfortable room temperature is {comfortTemp} degrees Fahrenheit.</p> <p> When I am happy I look like this: <img src={images[0]} alt="happy" /> </p> </div> ); }); stories.add('dates Knob', () => { const today = date('today'); const dob = date('DOB', null); const myDob = date('My DOB', new Date('July 07 1993')); return ( <ul style={{ listStyleType: 'none', listStyle: 'none', paddingLeft: '15px' }}> <li> <p> <b>Javascript Date</b> default value, passes date value </p> <blockquote> <code>const myDob = date('My DOB', new Date('July 07 1993'));</code> <pre>{`// I was born in: "${moment(myDob).format('DD MMM YYYY')}"`}</pre> </blockquote> </li> <li> <p> <b>undefined</b> default value passes today's date </p> <blockquote> <code>const today = date('today');</code> <pre>{`// Today's date is: "${moment(today).format('DD MMM YYYY')}"`}</pre> </blockquote> </li> <li> <p> <b>null</b> default value passes null value </p> <blockquote> <code>const dob = date('DOB', null);</code> <pre> {`// You were born in: "${ dob ? moment(dob).format('DD MMM YYYY') : 'Please select date.' }"`} </pre> </blockquote> </li> </ul> ); }); stories.add('dynamic knobs', () => { const showOptional = select('Show optional', ['yes', 'no'], 'yes'); return ( <div> <div>{text('compulsary', 'I must be here')}</div> {showOptional === 'yes' ? <div>{text('optional', 'I can disapear')}</div> : null} </div> ); }); stories.add('without any knob', () => <button>This is a button</button>);
import { expect } from 'chai' import { describe, it } from 'mocha' import { or } from 'opensource-challenge-client/helpers/or' describe('Unit | Helper | or', function() { it('works', function() { expect(or([42, 42])).to.equal(true) expect(or([false, 42, false])).to.equal(true) expect(or([true, 42])).to.equal(true) expect(or([null, undefined, 1])).to.equal(true) }) })
/* */ define(['exports', './i18n', 'aurelia-event-aggregator', 'aurelia-templating', './utils'], function (exports, _i18n, _aureliaEventAggregator, _aureliaTemplating, _utils) { 'use strict'; exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TValueConverter = (function () { TValueConverter.inject = function inject() { return [_i18n.I18N]; }; function TValueConverter(i18n) { _classCallCheck(this, TValueConverter); this.service = i18n; } TValueConverter.prototype.toView = function toView(value, options) { return this.service.tr(value, options); }; return TValueConverter; })(); exports.TValueConverter = TValueConverter; var TParamsCustomAttribute = (function () { _createClass(TParamsCustomAttribute, null, [{ key: 'inject', value: [Element], enumerable: true }]); function TParamsCustomAttribute(element) { _classCallCheck(this, _TParamsCustomAttribute); this.element = element; } TParamsCustomAttribute.prototype.valueChanged = function valueChanged() {}; var _TParamsCustomAttribute = TParamsCustomAttribute; TParamsCustomAttribute = _aureliaTemplating.customAttribute('t-params')(TParamsCustomAttribute) || TParamsCustomAttribute; return TParamsCustomAttribute; })(); exports.TParamsCustomAttribute = TParamsCustomAttribute; var TCustomAttribute = (function () { _createClass(TCustomAttribute, null, [{ key: 'inject', value: [Element, _i18n.I18N, _aureliaEventAggregator.EventAggregator, _utils.LazyOptional.of(TParamsCustomAttribute)], enumerable: true }]); function TCustomAttribute(element, i18n, ea, tparams) { _classCallCheck(this, _TCustomAttribute); this.element = element; this.service = i18n; this.ea = ea; this.lazyParams = tparams; } TCustomAttribute.prototype.bind = function bind() { var _this = this; this.params = this.lazyParams(); setTimeout(function () { if (_this.params) { _this.params.valueChanged = function (newParams, oldParams) { _this.paramsChanged(_this.value, newParams, oldParams); }; } var p = _this.params !== null ? _this.params.value : undefined; _this.subscription = _this.ea.subscribe('i18n:locale:changed', function () { _this.service.updateValue(_this.element, _this.value, p); }); setTimeout(function () { _this.service.updateValue(_this.element, _this.value, p); }); }); }; TCustomAttribute.prototype.paramsChanged = function paramsChanged(newValue, newParams) { this.service.updateValue(this.element, newValue, newParams); }; TCustomAttribute.prototype.valueChanged = function valueChanged(newValue) { var p = this.params !== null ? this.params.value : undefined; this.service.updateValue(this.element, newValue, p); }; TCustomAttribute.prototype.unbind = function unbind() { this.subscription.dispose(); }; var _TCustomAttribute = TCustomAttribute; TCustomAttribute = _aureliaTemplating.customAttribute('t')(TCustomAttribute) || TCustomAttribute; return TCustomAttribute; })(); exports.TCustomAttribute = TCustomAttribute; });
class sppcomapi_elevationconfig_1 { constructor() { // ISPPLUA Elevated () {get} this.Elevated = undefined; // bool IsElevated () {get} this.IsElevated = undefined; // _ElevationConfigOptions Mode () {get} {set} this.Mode = undefined; // uint64 UIHandle () {set} this.UIHandle = undefined; } // void ConfigureObject (IUnknown) ConfigureObject(IUnknown) { } } module.exports = sppcomapi_elevationconfig_1;
// 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, or any plugin's // vendor/assets/javascripts directory 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. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // // require rails-ujs //= require turbolinks //= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require bootstrap.file-input document.addEventListener("turbolinks:load", function() { if ($('.btn-file').length === 0) { $('input[type=file]').bootstrapFileInput(); $('.file-inputs').bootstrapFileInput(); } }); $(document).ready(function() { // Javascript for button validation $(document).on('click', 'input[type=radio]', function() { el = $(this); col = el.data("col"); el .parents(".table") .find("input[data-col=" + col + "]") .prop("checked", false); el.prop("checked", true); }) // Javascript for submit button validation $(document).on('click', '#quizSubmit', function() { var questions = validate_form(); if(questions.size == 0 ) { return; } else { questionString = ""; questions.forEach(function(value) { questionString = questionString + ", " + value; }); if (questions.size == 1) { alert("Please finish question" + questionString.substring(1) + " before submitting!"); } else { alert("Please finish questions" + questionString.substring(1) + " before submitting!"); } event.preventDefault(); } }) // Iterates through all answers and checks that they are ranked // Returns 0 if all are checked, otherwise returns first question that isn't finished function validate_form() { var numbers = new Set(); scroll = 0; for (i = 1; i < 19; i++) { $("#q" + i).css("border", "2px solid white"); for (j = 1; j < 5; j++) { name = "q" + i + "a" + j; if ($("input[name='" + name + "']:checked").length == 0) { numbers.add(i); $("#q" + i).css("border", "2px solid red"); if (scroll == 0) { var top = $('#q' + i).position().top; $(window).scrollTop( top - 75); //Offset because header blocks some of screen scroll = 1; } } } } return numbers; } // Prevents arrow keys from moving radio button $(document).on('click', 'input[type=radio]', function() { document.addEventListener("keydown", function (e) { if ([37].indexOf(e.keyCode) > -1) { // left e.preventDefault(); window.scrollBy(-50, -0); } if ([38].indexOf(e.keyCode) > -1) { //up e.preventDefault(); window.scrollBy(0, -50); } if ([39].indexOf(e.keyCode) > -1) { //right e.preventDefault(); window.scrollBy(50, 0); } if([40].indexOf(e.keyCode) > -1) { //down e.preventDefault(); window.scrollBy(0, 50); } }, false); }) });
version https://git-lfs.github.com/spec/v1 oid sha256:7678f6e4188a6066c45fd9a295882aea8e986bbc11eea3dbeabf24eca190b774 size 394
version https://git-lfs.github.com/spec/v1 oid sha256:d1ae7db9f7928706e5601ba8c7d71d4c9fbd1c4463c6b6465b502115eae45c07 size 77153
"use strict"; //////////////////////////////////////////////////////////////////////////////// // デスクトップ通知履歴 //////////////////////////////////////////////////////////////////////////////// Contents.notify_history = function( cp ) { var p = $( '#' + cp.id ); var cont = p.find( 'div.contents' ); var notify_history_list; var scrollPos = null; cp.SetIcon( 'icon-bubble' ); //////////////////////////////////////////////////////////// // リスト部作成 //////////////////////////////////////////////////////////// var ListMake = function( type ) { var s = ''; for ( var i = g_cmn.notsave.notify_history.length - 1 ; i >= 0 ; i-- ) { var assign = {}; for ( var arg in g_cmn.notsave.notify_history[i].data ) { try { assign[arg] = decodeURIComponent( g_cmn.notsave.notify_history[i].data[arg] ); } catch ( err ) { assign[arg] = g_cmn.notsave.notify_history[i].data[arg]; } } s += OutputTPL( 'notify_' + g_cmn.notsave.notify_history[i].type, assign ); } notify_history_list.html( s ) .scrollTop( 0 ); notify_history_list.find( '.notify' ).each( function() { var account_id = $( this ).attr( 'account_id' ); $( this ).find( '.notify_username' ).click( function( e ) { OpenUserTimeline( $( this ).attr( 'src' ), account_id ); e.stopPropagation(); } ); $( this ).find( '.notify_dmname' ).click( function( e ) { var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'dmrecv', reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); $( this ).find( '.notify_followname' ).click( function( e ) { var _cp = new CPanel( null, null, 320, 360 ); var num = $( this ).attr( 'num' ); _cp.SetType( 'follow' ); _cp.SetParam( { type: 'followers', account_id: account_id, screen_name: g_cmn.account[account_id].screen_name, number: num, } ); _cp.Start(); e.stopPropagation(); } ); $( this ).find( '.notify_listname' ).click( function( e ) { var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'list', list_id: $( this ).attr( 'list_id' ), screen_name: $( this ).attr( 'screen_name' ), slug: $( this ).attr( 'slug' ), reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); } ); cont.trigger( 'contents_resize' ); }; //////////////////////////////////////////////////////////// // 開始処理 //////////////////////////////////////////////////////////// this.start = function() { //////////////////////////////////////// // 最小化/設定切替時のスクロール位置 // 保存/復元 //////////////////////////////////////// cont.on( 'contents_scrollsave', function( e, type ) { // 保存 if ( type == 0 ) { if ( scrollPos == null ) { scrollPos = notify_history_list.scrollTop(); } } // 復元 else { if ( scrollPos != null ) { notify_history_list.scrollTop( scrollPos ); scrollPos = null; } } } ); //////////////////////////////////////// // リサイズ処理 //////////////////////////////////////// cont.on( 'contents_resize', function() { $( '#notify_history_list' ).height( cont.height() - cont.find( '.panel_btns' ).height() - 1 ); } ); // 全体を作成 cont.addClass( 'notify_history' ) .html( OutputTPL( 'notify_history', {} ) ); notify_history_list = $( '#notify_history_list' ); //////////////////////////////////////// // 更新ボタンクリック //////////////////////////////////////// $( '#notify_history_reload' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } ListMake(); } ); // リスト部作成処理 ListMake(); }; //////////////////////////////////////////////////////////// // 終了処理 //////////////////////////////////////////////////////////// this.stop = function() { }; }
import net from 'net'; import log from './log.js'; export default function(options, onConnect) { // proxy server let proxy = net.createServer(function(client) { let server; // Create a new connection to the target server server = net.connect(options.port); // 2-way pipe between proxy and target server client.pipe(server).pipe(client); client.on('close', function() { server.end(); }); server.on('close', function() { client.end(); }); client.on('error', function(err) { log.error('Client: ' + err.toString()); client.end(); server.end(); }); server.on('error', function(err) { log.error('Server: ' + err.toString()); client.end(); server.end(); }); onConnect(client, server); }); proxy.listen(options.proxyPort); }
'use strict'; var util = require('util') , yeoman = require('yeoman-generator') , github = require('../lib/github') , path = require('path') , inflect = require('inflect'); var BBBGenerator = module.exports = function BBBGenerator(args, options, config) { // By calling `NamedBase` here, we get the argument to the subgenerator call // as `this.name`. yeoman.generators.NamedBase.apply(this, arguments); if (!this.name) { this.log.error('You have to provide a name for the subgenerator.'); process.exit(1); } this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); // Set destination root back to project root to help with testability this.destinationRoot('../../'); }); this.appName = this.name; this.destPath = util.format('client/%s', this.appName); }; util.inherits(BBBGenerator, yeoman.generators.NamedBase); BBBGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [{ name: 'githubUser', message: 'Tell me again your username on Github?', default: 'someuser' },{ name: 'appDescription', message: 'Give this app a description', },{ name: 'version', message: 'What is the starting version number for this app you\'d like to use?', default: '0.1.0' }]; this.prompt(prompts, function (props) { this.githubUser = props.githubUser; this.appDescription = props.appDescription; this.version = props.version; cb(); }.bind(this)); }; BBBGenerator.prototype.userInfo = function userInfo() { var self = this , done = this.async(); github.githubUserInfo(this.githubUser, function (res) { /*jshint camelcase:false */ self.realname = res.name; self.email = res.email; self.githubUrl = res.html_url; done(); }); }; BBBGenerator.prototype.createDestFolder = function createDestFolder() { this.mkdir(this.destPath); this.destinationRoot(path.join(this.destinationRoot(), this.destPath)); }; BBBGenerator.prototype.fetchBoilerplate = function fetchBoilerplate() { var self = this , done = this.async(); this.remote('duro', 'clutch-backbone-boilerplate', function(err, remote) { self.sourceRoot(remote.cachePath); done(); }); }; BBBGenerator.prototype.buildApp = function buildSkeleton() { var self = this; this.directory('.','.'); };
import {mount, render, shallow} from 'enzyme'; global.mount = mount; global.render = render; global.shallow = shallow;
'use strict'; var _require = require('./parseProps'), parsePropTypes = _require.parsePropTypes, parseDefaultProps = _require.parseDefaultProps, resolveToValue = require('./util/resolveToValue'); module.exports = function (state) { var json = state.result, components = state.seen; var isAssigning = function isAssigning(node, name) { return node.operator === '=' && node.left.property && node.left.property.name === name; }; var seenClass = function seenClass(name, scope) { return components.indexOf(name) !== -1 && scope.hasBinding(name); }; return { enter: function enter(_ref) { var node = _ref.node, scope = _ref.scope; var component = node.left.object && node.left.object.name; if (isAssigning(node, 'propTypes') && seenClass(component, scope)) parsePropTypes(resolveToValue(node.right, scope), json[component], scope);else if (isAssigning(node, 'defaultProps') && seenClass(component, scope)) { parseDefaultProps(resolveToValue(node.right, scope), json[component], state.file, scope); } } }; };
'use strict'; const expect = require('chai').expect; const deepfind = require('../index'); const simpleFixture = { 'key': 'value' }; const complexFixture = { 'key1': { 'key': 'value1' }, 'key2': { 'key': 'value2' }, 'key3': { 'key': 'value3' } }; describe('deepfind', () => { it('should throw an error when given no object', () => { expect(() => deepfind(null, 'key')).to.throw('deepfind must be supplied an object'); }); it('should throw an error when given no key', () => { expect(() => deepfind({}, null)).to.throw('deepfind must be supplied a key'); }); it('should return an empty array when no key is found', () => { expect(deepfind({}, 'key')).to.be.an.array; expect(deepfind({}, 'key')).to.be.empty; }); it('should return an array when one value matches', () => { expect(deepfind(simpleFixture, 'key')).to.be.an.array; expect(deepfind(simpleFixture, 'key')).to.deep.equal(['value']); }); it('should return an array when multiple values match', () => { expect(deepfind(complexFixture, 'key')).to.be.an.array; expect(deepfind(complexFixture, 'key')).to.deep.equal(['value1', 'value2', 'value3']) }); });
/** * Created by Roman on 16.12.13. */ var moment = require('moment'); function AuthController($scope, $api) { var ctrl = this; $scope.client_id = store.get('client_id'); $scope.api_key = store.get('api_key'); $scope.api_secret = store.get('api_secret'); $scope.err = null; // catch html pieces var $modal = $('#modal-auth').modal({backdrop: true, show: false}); $scope.authenticate_clicked = function(){ NProgress.start(); $scope.err = null; // validate keys and update scopes $api.bitstamp.get_transactions($scope.api_key, $scope.api_secret, $scope.client_id) .success(function(transactions){ $modal.modal('hide'); // save data store.set('client_id', $scope.client_id); store.set('api_key', $scope.api_key); store.set('api_secret', $scope.api_secret); store.set('transactions', transactions); store.set('transactions_updated', moment().unix()); // notify parent that we authenticated $scope.$parent.authenticated(); NProgress.done(); }) .error(function(){ $scope.err = "Failed to verify credentials. Are they correct?"; NProgress.done(); }); }; // init code $('#btn-start').click(function(){ $modal.modal('show'); }); } module.exports = AuthController;
require('babel-core/register') const path = require('path') const jsdom = require('jsdom').jsdom const exposedProperties = ['window', 'navigator', 'document'] global.document = jsdom('') global.window = document.defaultView Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) global.navigator = { userAgent: 'node.js' } global.__base = `${path.resolve()}/`
module.exports = (client, reaction, user) => { client.log('Log', `${user.tag} reagiu à mensagem de id ${reaction.message.id} com a reação: ${reaction.emoji}`); };