code
stringlengths
2
1.05M
/*! jQuery UI - v1.10.4 - 2014-03-23 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.cs={closeText:"Zavřít",prevText:"<Dříve",nextText:"Později>",currentText:"Nyní",monthNames:["leden","únor","březen","duben","květen","červen","červenec","srpen","září","říjen","listopad","prosinec"],monthNamesShort:["led","úno","bře","dub","kvě","čer","čvc","srp","zář","říj","lis","pro"],dayNames:["neděle","pondělí","úterý","středa","čtvrtek","pátek","sobota"],dayNamesShort:["ne","po","út","st","čt","pá","so"],dayNamesMin:["ne","po","út","st","čt","pá","so"],weekHeader:"Týd",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.cs)});
const log = require("npmlog"); const peaks = require("./peaks"); module.exports = function(data, opts) { // years to look in either direction before declaring it's a local maximum if (!data[0].peak) { console.log("Getting peaks in order to find maxima"); peaks(data); } const WINDOW_SIZE = +opts.window || 5; // years on either side that a peak must be the highest value const PEAK_MIN = +opts.peak_min || 0.25; // lowest value for a peak data.forEach(function(name) { let maxima = []; for (let year = opts.start; year <= opts.end; year += 1) { let isMaxima = true; if (typeof name.percents[year] == "undefined") { isMaxima = false; continue; } for (let i = Math.max(opts.start, year - WINDOW_SIZE); i <= Math.min(opts.end, year + WINDOW_SIZE); i += 1) { if (i == year) { continue; } if (typeof name.percents[i] == "undefined" || name.percents[i] > name.percents[year]) { isMaxima = false; break; } } if (isMaxima && name.percents[year] / name.peak.percent >= PEAK_MIN) { maxima.push({ year: year, value: name.values[year], percent: name.percents[year], height: name.percents[year] / name.peak.percent }); } } name.maxima = maxima; }); }
var path = require('path'), glob = require('glob'), util = require('util'), _ = require('lodash'), protractor = require('./protractor.js'); // Coffee is required here to enable config files written in coffee-script. try { require('coffee-script').register(); } catch (e) { // Intentionally blank - ignore if coffee-script is not available. } // LiveScript is required here to enable config files written in LiveScript. try { require('LiveScript'); } catch (e) { // Intentionally blank - ignore if LiveScript is not available. } var ConfigParser = function() { // Default configuration. this.config_= { specs: [], capabilities: { browserName: 'chrome' }, splitTestsBetweenCapabilities: false, multiCapabilities: [], rootElement: 'body', allScriptsTimeout: 11000, params: {}, framework: 'jasmine', jasmineNodeOpts: { isVerbose: false, showColors: true, includeStackTrace: true, stackFilter: protractor.filterStackTrace, defaultTimeoutInterval: (30 * 1000) }, seleniumArgs: [], cucumberOpts: {}, mochaOpts: { ui: 'bdd', reporter: 'list' }, chromeDriver: null, configDir: './' }; }; /** * Merge config objects together. * * @private * @param {Object} into * @param {Object} from * * @return {Object} The 'into' config. */ var merge_ = function(into, from) { for (var key in from) { if (into[key] instanceof Object && !(into[key] instanceof Array)) { merge_(into[key], from[key]); } else { into[key] = from[key]; } } return into; }; /** * Returns the item if it's an array or puts the item in an array * if it was not one already. */ var makeArray = function(item) { return _.isArray(item) ? item : [item]; }; /** * Resolve a list of file patterns into a list of individual file paths. * * @param {Array.<string> | string} patterns * @param {=boolean} opt_omitWarnings Whether to omit did not match warnings * @param {=string} opt_relativeTo Path to resolve patterns against * * @return {Array} The resolved file paths. */ ConfigParser.resolveFilePatterns = function(patterns, opt_omitWarnings, opt_relativeTo) { var resolvedFiles = []; var cwd = opt_relativeTo || process.cwd(); patterns = (typeof patterns === 'string') ? [patterns] : patterns; if (patterns) { for (var i = 0; i < patterns.length; ++i) { var matches = glob.sync(patterns[i], {cwd: cwd}); if (!matches.length && !opt_omitWarnings) { util.puts('Warning: pattern ' + patterns[i] + ' did not match any files.'); } for (var j = 0; j < matches.length; ++j) { resolvedFiles.push(path.resolve(cwd, matches[j])); } } } return resolvedFiles; }; /** * Returns only the specs that should run currently based on `config.suite` * * @return {Array} An array of globs locating the spec files */ ConfigParser.getSpecs = function(config) { if (config.suite) { return config.suites[config.suite]; } if (config.specs.length > 0) { return config.specs; } var specs = []; _.forEach(config.suites, function(suite) { specs = _.union(specs, makeArray(suite)); }); return specs; }; /** * Add the options in the parameter config to this runner instance. * * @private * @param {Object} additionalConfig * @param {string} relativeTo the file path to resolve paths against */ ConfigParser.prototype.addConfig_ = function(additionalConfig, relativeTo) { // All filepaths should be kept relative to the current config location. // This will not affect absolute paths. ['seleniumServerJar', 'chromeDriver', 'onPrepare'].forEach(function(name) { if (additionalConfig[name] && typeof additionalConfig[name] === 'string') { additionalConfig[name] = path.resolve(relativeTo, additionalConfig[name]); } }); // Make sure they're not trying to add in deprecated config vals. if (additionalConfig.jasmineNodeOpts && additionalConfig.jasmineNodeOpts.specFolders) { throw new Error('Using config.jasmineNodeOpts.specFolders is deprecated ' + 'since Protractor 0.6.0. Please switch to config.specs.'); } merge_(this.config_, additionalConfig); }; /** * Public function specialized towards merging in a file's config * * @public * @param {String} filename */ ConfigParser.prototype.addFileConfig = function(filename) { if (!filename) { return this; } var filePath = path.resolve(process.cwd(), filename); var fileConfig = require(filePath).config; fileConfig.configDir = path.dirname(filePath); this.addConfig_(fileConfig, fileConfig.configDir); return this; }; /** * Public function specialized towards merging in config from argv * * @public * @param {Object} argv */ ConfigParser.prototype.addConfig = function(argv) { this.addConfig_(argv, process.cwd()); return this; }; /** * Public getter for the final, computed config object * * @public * @return {Object} config */ ConfigParser.prototype.getConfig = function() { return this.config_; }; module.exports = ConfigParser;
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/hxbirthdays', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
export const u2665 = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M2074.5 1479.5Q1973 1663 1775 1845t-409 309l-47 28q-8 6-19 6-12 0-19-6l-47-28q-201-119-402-302t-305-368.5T423 1123q0-187 135-322.5T882 665q134 0 249 74.5T1300 935q56-124 170.5-197t247.5-73q190 0 324 135.5t134 322.5q0 173-101.5 356.5z"},"children":[]}]};
import React, { PropTypes as T } from 'react' import when from 'when' import subscribe from '../utils/subscribeToPromise' import Spinner from '../ui/loading/Spinner' import NonFieldErrors from '../ui/form/NonFieldErrors' export default React.createClass({ displayName: 'EntityEdit', propTypes: { endpoint: T.string, sendMethod: T.string, dataLoader: T.func, onSuccess: T.func, Renderer: T.func.isRequired, rendererProps: T.object }, contextTypes: { fetch: T.func.isRequired }, getDefaultProps() { return { rendererProps: {}, sendMethod: 'put', dataLoader(fetch, endpoint) { return fetch({ path: endpoint }) }, onSuccess() {} } }, getInitialState() { return { data: null, loading: true, loadingError: null, updating: false, updatingError: null } }, componentWillMount() { this.loadData(this.props.endpoint) }, componentWillReceiveProps(nextProps) { if (nextProps.endpoint !== this.props.endpoint) { this.loadData(nextProps.endpoint) } }, componentWillUnmount() { this.unsub() }, unsub() { if (this._unsubLoading) { this._unsubLoading() this._unsubLoading = null } if (this._unsubUpdating) { this._unsubUpdating() this._unsubUpdating = null } }, loadData(endpoint) { const { fetch } = this.context const { dataLoader } = this.props this.unsub() this.setState(this.getInitialState()) this._unsubLoading = subscribe(dataLoader(fetch, endpoint), { success: resp => this.setState({ loading: false, data: resp.entity }), failure: resp => this.setState({ loading: false, loadingError: resp }) }) }, handleUpdateReq(nextData) { const { fetch } = this.context const { endpoint, sendMethod, onSuccess } = this.props const { loading, updating } = this.state // If we get request to update during loading/updating, just ignore it // This should never happen if (loading || updating) { return } this.unsub() this.setState({ updating: true, updatingError: null }) this._unsubUpdating = subscribe(fetch({ method: sendMethod, path: endpoint, entity: nextData }).then(resp => when.resolve(onSuccess(resp.entity)).yield(resp)), { success: resp => { this.setState({ updating: false, data: resp.entity }) }, failure: resp => this.setState({ updating: false, updatingError: resp }) }) }, render() { const { Renderer, rendererProps } = this.props const { loading, data, loadingError, updating, updatingError } = this.state if (loading) { return <Spinner /> } if (data) { return <Renderer data={data} onUpdateReq={this.handleUpdateReq} updating={updating} updatingError={updatingError} {...rendererProps} /> } return <NonFieldErrors errors={loadingError} auto={false} /> } })
{ var x = scale .scaleUtc() .domain([ date.utc(2011, 0, 1, 12, 28, 27), date.utc(2011, 0, 1, 16, 34, 12) ]); test.deepEqual(x.ticks(4), [ date.utc(2011, 0, 1, 13, 0), date.utc(2011, 0, 1, 14, 0), date.utc(2011, 0, 1, 15, 0), date.utc(2011, 0, 1, 16, 0) ]); test.end(); }
var ArticleVM = require('../view-models/article'); /** * Expose "Main" Controller. */ module.exports = new MainController; /** * Constructor for the MainController. * @constructor */ function MainController() {} /** * Renders the home page - lists all articles. * @param {http.IncomingMessage} req Node/Express request object. * @param {http.ServerResponse} res Node/Express response object. */ MainController.prototype.index = function(req, res) { var viewModel = new ArticleVM(req.app); viewModel.find(function(err, articles) { res.render('main/index', { articles: articles, title: 'Publish: Home Page' }); }); }; /** * Renders the about page. * @param {http.IncomingMessage} req Node/Express request object. * @param {http.ServerResponse} res Node/Express response object. */ MainController.prototype.about = function(req, res) { res.render('main/about', {title: 'About Us'}); }; /** * Renders the contact page. * @param {http.IncomingMessage} req Node/Express request object. * @param {http.ServerResponse} res Node/Express response object. */ MainController.prototype.contact = function(req, res) { res.render('main/contact', {title: 'Contact Us'}); };
import React, { Component } from 'react'; import sinon from 'sinon'; import Autosuggest from '../../src/AutosuggestContainer'; import languages from '../plain-list/languages'; import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js'; function getMatchingLanguages(value) { const escapedValue = escapeRegexCharacters(value.trim()); const regex = new RegExp('^' + escapedValue, 'i'); return languages.filter(language => regex.test(language.name)); } let app = null; export const getSuggestionValue = sinon.spy(suggestion => { return suggestion.name; }); export const renderSuggestion = sinon.spy(suggestion => { return ( <span>{suggestion.name}</span> ); }); export const onChange = sinon.spy((event, { newValue }) => { app.setState({ value: newValue }); }); export const onSuggestionSelected = sinon.spy(); export const onSuggestionsUpdateRequested = sinon.spy(({ value }) => { app.setState({ suggestions: getMatchingLanguages(value) }); }); export default class AutosuggestApp extends Component { constructor() { super(); app = this; this.state = { value: '', suggestions: getMatchingLanguages('') }; } render() { const { value, suggestions } = this.state; const inputProps = { value, onChange }; return ( <Autosuggest suggestions={suggestions} onSuggestionsUpdateRequested={onSuggestionsUpdateRequested} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} onSuggestionSelected={onSuggestionSelected} alwaysRenderSuggestions={true} /> ); } }
/** script for generating console */ (function () { function createJsConsole(selector) { var self = this; //var consoleElement = document.querySelector(selector); var consoleElement = document.getElementById(selector); if (consoleElement.className) { consoleElement.className = consoleElement.className + " js-console"; } else { consoleElement.className = "js-console"; } var textArea = document.createElement("p"); consoleElement.appendChild(textArea); self.write = function jsConsoleWrite(text) { var textLine = document.createElement("span"); if (text !== "" && text !== undefined) { var toWrite = text.toString(); textLine.innerHTML = toWrite; textArea.appendChild(textLine); consoleElement.scrollTop = consoleElement.scrollHeight; } }; self.writeLine = function jsConsoleWriteLine(text) { self.write(text); textArea.appendChild(document.createElement("br")); }; self.read = function readText(inputSelector) { var element = document.querySelector(inputSelector); if (element.innerHTML) { return element.innerHTML; } else { return element.value; } }; self.readInteger = function readInteger(inputSelector) { var text = self.read(inputSelector); return parseInt(text, 10); }; self.readFloat = function readFloat(inputSelector) { var text = self.read(inputSelector); return parseFloat(text); }; self.clearConsole = function clearConsole() { textArea.innerHTML = ""; }; return self; } jsConsole = new createJsConsole("js-console"); }).call(this); /** * Problem visualization */ var previousButton = document.getElementById('previous'); nextButton = document.getElementById('next'); nextButton.onclick = next; previousButton.onclick = previous; count = 1; function next(){ if(count < 12){ document.getElementById('article' + count).style.display = "none"; count++; document.getElementById('article' + count).style.display = "block"; jsConsole.clearConsole(); } } function previous() { if (count > 1) { document.getElementById('article' + count).style.display = "none"; count--; document.getElementById('article' + count).style.display = "block"; jsConsole.clearConsole(); } }
var _ = require('lodash'); var glob = require('glob'); var yargs = require('yargs'); // Tasks var Files = require('./task/Files'); var Less = require('./task/Less'); var Js = require('./task/Js'); var Inline = require('./task/Inline'); class Manager { /** * * @param gulp */ constructor(gulp) { this._config = { dest: 'public', name: 'app', compress: null, watch: null }; this._names = []; this._nameIndexes = {}; this._tasks = []; this._isProduction = process.env.NODE_ENV === 'production' || !!yargs.argv.production || yargs.argv._.indexOf('production') !== -1; this._isShowTasks = !!yargs.argv.tasks; // Set production move (for example, to react build) if (this._isProduction) { process.env.NODE_ENV = 'production'; } this._gulp = gulp || require('gulp'); this._gulp.task('default', this._tasks); this._gulp.task('production', this._tasks); // Do not exit on exceptions if (!this._isProduction) { process.on('uncaughtException', function(e) { console.error(e.stack || String(e)); }); } } /** * * @param {object} config * @returns {self} */ config(config) { if (config.gulp) { this._gulp = config.gulp; } _.merge(this._config, config); return this; } isWatch() { return this._config.watch !== null ? this._config.watch : !this._isProduction && !this._isShowTasks; } isCompress() { return this._config.compress !== null ? this._config.compress : this._isProduction && !this._isShowTasks; } /** * * @param {string|string[]} src * @param {string} [dest] Path to destination file * @param {object} [config] * @returns {self} */ files(src, dest, config) { var task = new Files(); task.src = this._normalizeSrc(src); task.dest = this._parseDest(dest, !dest.match(/\/$/)); task.config = _.merge(task.config, this._config.files || {}, config || {}); task.name = this._getTaskName(task.dest.name + '_files'); this._runTask(task); return this; } /** * * @param {string|string[]} src * @param {string} [dest] Path to destination file * @param {object} [config] * @returns {self} */ less(src, dest, config) { var task = new Less(); task.src = this._normalizeSrc(src); task.dest = this._parseDest(dest, true, 'css'); task.config = _.merge(task.config, this._config.less || {}, config || {}); task.name = this._getTaskName(task.dest.name + '_css'); this._runTask(task); return this; } /** * * @param {string|string[]} src * @param {string} [dest] Path to destination file * @param {object} [config] * @returns {self} */ js(src, dest, config) { var task = new Js(); task.src = this._normalizeSrc(src); task.dest = this._parseDest(dest, true, 'js'); task.config = _.merge(task.config, this._config.js || {}, config || {}); task.name = this._getTaskName(task.dest.name + '_js'); this._runTask(task); return this; } /** * * @param {function} taskHandler * @param {function} [watchHandler] * @returns {self} */ task(taskHandler, watchHandler) { var task = new Inline(); task.taskHandler = taskHandler; task.watchHandler = watchHandler || null; task.name = this._getTaskName('task'); this._runTask(task); return this; } _getTaskName(name) { name = '_' + name; if (this._names.indexOf(name) !== -1) { if (name.match(/[0-9]$/)) { name = name.replace(/[0-9]+$/, function(num) { return parseInt(num) + 1 }); } else { name = name + '2'; } } this._names.push(name); return name; } _runTask(task) { task.manager = this; task.gulp = this._gulp; task.init(); this._tasks.push(task.name); this._gulp.task(task.name, task.run.bind(task)); if (this.isWatch()) { task.watch(); } } _generateName(group) { if (!this._nameIndexes[group]) { this._nameIndexes[group] = 0; } this._nameIndexes[group]++; return this._config.name + (this._nameIndexes[group] > 1 ? this._nameIndexes[group] : ''); } _parseDest(dest, isFile, group) { dest = dest || ''; if (isFile) { var matchFile = /\/?([^\/]+)$/.exec(dest); var file = matchFile !== null ? matchFile[1] : this._generateName(group); var dir = dest.replace(/\/?[^\/]*$/, ''); if (!dir) { dir = this._config.dest; } var matchExt = /\.([^\.]+)$/.exec(file); var ext = matchExt !== null ? matchExt[1] : ''; return { dir: dir, file: file, name: ext ? file.substr(0, file.length - ext.length - 1) : file, ext: ext }; } else { var matchName = /\/?([^\/]+)$/.exec(dest); return { dir: dest.replace('/\/$/', ''), file: '', name: matchName !== null ? matchName[1] : this._generateName(group), ext: '' }; } } _normalizeSrc(src) { if (!_.isArray(src)) { src = [src]; } var files = []; _.each(src, function(path) { files = files.concat(glob.sync(path, {cwd: process.cwd(), root: '/'})); }); return files; } } module.exports = Manager;
var eol = require('os').EOL; var indent = function(n) { var space = ''; for (var i=0 ; i < n; i++) { space += ' '; } return space; }; // Utility templates require chai var tempRequire = function(it) { return 'var ' + (it.varName) + ' = require(\'' + (it.module) + '\');'; }; //Should Execute Statement var shouldExecute = function(it) { return 'var should = chai.should();' + eol; }; // Base template var baseTemplate = function(it) { return 'describe(\'' + (it.testTitle) + '\', function() { '; }; // Individual assertion templates var equalTemplate = function(it) { return 'it(\'' + (it.assertionMessage) + '\', function() {' + eol + indent(4) + 'file.' + (it.assertionInput) + '.should.equal(' + (it.assertionOutput) + ');' + eol + indent(2) + '});'; }; var notEqualTemplate = function(it) { return 'it(\'' + (it.assertionMessage) + '\', function() {' + eol + indent(4) + 'file.' + (it.assertionInput) + '.should.not.equal(' + (it.assertionOutput) + ');' + eol + indent(2) + '});'; }; var deepEqualTemplate = function(it) { return 'it(\'' + (it.assertionMessage) + '\', function() {' + eol + indent(4) + 'file.' + (it.assertionInput) + '.should.deep.equal(' + (it.assertionOutput) + ');' + eol + indent(2) + '});'; }; var notDeepEqualTemplate = function(it) { return 'it(\'' + (it.assertionMessage) + '\', function() {' + eol + indent(4) + 'file.' + (it.assertionInput) + '.should.not.deep.equal(' + (it.assertionOutput) + ');' + eol + indent(2) + '});'; }; module.exports = { require: tempRequire, shouldExecute: shouldExecute, base: baseTemplate, equal: equalTemplate, notEqual: notEqualTemplate, deepEqual: deepEqualTemplate, notDeepEqual: notDeepEqualTemplate };
/*global describe, beforeEach, it */ 'use strict'; var path = require('path'); var helpers = require('yeoman-test'); var assert = require('yeoman-assert'); var os = require('os'); describe('repo generator', function () { describe('Polymer Test', function () { beforeEach(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp')) .withPrompts({ githubRepo : 'fake-element-repo', boilerplate: 'Polymer', polymerVersion: '1.4.0', elementName: 'fake-element', elementDescription: 'A awesome web component', githubUser: 'componentCreatorAccount', authorName: 'Koan Kyuka', authorEmail: 'Koan.Kyuka@ghost.com', authorUrl: 'http://Koan.go', keywords: ['generator-keyword', 'component-keyword', 'web-keyword'], license: 'MIT', 'lifecycle': true }) .withOptions({'skip-install': true}) .on('end', done); }); it('should create the required static files', function () { assert.file([ 'test/fake-element-tests.html', 'src/fake-element.html', 'bower.json', 'package.json', 'demo/index.html', 'README.md', 'Gruntfile.js', '.editorconfig', 'LICENSE', '.gitignore' ]); }); it('fills the README with project data', function () { assert.fileContent('README.md', 'fake-element'); assert.fileContent('README.md', 'https://travis-ci.org/componentCreatorAccount/fake-element-repo.svg?branch=master'); assert.fileContent('README.md', 'http://Koan.go'); }); it('fills the index html with project data', function () { assert.fileContent('src/fake-element.html', 'fake-element'); }); it('fills the bower with the correct library', function () { assert.fileContent('bower.json', '"polymer": "Polymer/polymer#^1.4.0"'); }); it('fills the package.json with the correct info', function () { assert.fileContent('package.json', 'fake-element-repo'); assert.fileContent('package.json', '"generator-keyword"'); }); }); });
define("utils/index", ["require", "exports", "module", "configs/settings", "configs/dict", "lang/index", "utils/dom", "utils/string", "utils/timeformat", "utils/condition", "configs/keycode"], function(e, t) { var i = e("configs/settings"), n = e("configs/dict"), s = (e("lang/index"), e("utils/dom")), a = (e("utils/string"), e("utils/timeformat")), o = (e("utils/condition"), e("configs/keycode")); t.getTodoTasksCount = function(e) { var t = 0; return _.each(e, function(e) { e.get("dueDate") && 0 == e.get("status") && a.getDueDateLocalZoneDate(e.get("dueDate")).diff(a.prefMoment().startOf("day"), "days") <= 0 && t++ }), t }, t.setBadgeForExtension = function(e) { chrome.browserAction.setBadgeText(e > 0 ? { text: e.toString() } : { text: "" }) }, t.getDefaultColorIndex = function(e) { var t = 0; return null != e && $.each(i.colors, function(n) { i.colors[n].toUpperCase() == e.toUpperCase() && (t = n) }), t }, t.getProjectColor = function(e) { return i.colors[t.getDefaultColorIndex(e)] }, t.clone = function(e) { return JSON.parse(JSON.stringify(e)) }, t.cloneDeep = function(e) { if ("object" != typeof e || null == e) return e; if (e instanceof Date) return new Date(e.getTime()); var t = {}; "[object Array]" === Object.prototype.toString.call(e) && (t = []); for (var i in e) t[i] = this.cloneDeep(e[i]); return t }, t.verifyPasteEnter = function(e, t) { var i, n, s, a, r, o = [], l = t.indexOf("\n"); if (-1 == t.indexOf("\n")) return t; if (i = t.substr(0, l), _.isEmpty(e.get("items"))) e.set({ content: t.substr(l + 1) + "\n" + e.get("content") }); else { if (n = t.substr(l + 1), !n) return i; s = n.split("\n"), a = e.get("items"), r = -11111, _.each(s, function(e) { var t = { id: ObjectId(), status: 0, title: e, sortOrder: r }; o.push(t), r += 1 }), e.set({ items: o.concat(a), content: "" }) } return i }, t.screenshotImage = function(e, t) { var i = document.createElement("canvas"); i.width = e.width, i.height = e.height; var n = i.getContext("2d"); n.drawImage(e, 0, 0, e.width, e.height); var s = document.createElement("canvas"); s.width = t[2], s.height = t[3]; var a = s.getContext("2d"); return a.drawImage(i, t[0], t[1], t[2], t[3], 0, 0, t[2], t[3]), s.toDataURL("image/jpeg", .5) }, t.hasReminders = function(e) { return e && e.length }, t.svgIcon = function(e, t) { var i = []; return i.push('<svg class="' + e + " "), _.isObject(t) || i.push(t), i.push('"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#'), i.push(e), i.push('"></use></svg>'), i.join("") }, t.imgIcon = function(e, t) { var i = []; return i.push('<i class="' + e + " "), _.isObject(t) || i.push(t), i.push('"></i>'), i.join("") }, t.getImg = function(e, t) { var n = new Array, s = "upgrade-img", r = window.devicePixelRatio > 1; return n.push("<img"), i.iscnlang || (s = "tick-" + s), r && (s = s.concat("@2")), s = 'src="static/img/' + s.concat("/", e, ".png?v=" + a.prefMoment().format("YYYYMMDD")) + '"', n.push(s), n.push(">"), n.join(" ") }, t.getPriorityIcon = function(e) { var i = { 0: t.svgIcon("icon-priority-3", "i-4"), 1: t.svgIcon("icon-priority-1"), 3: t.svgIcon("icon-priority-2"), 5: t.svgIcon("icon-priority-3") }; return i[e] }, t.convertHex = function(e, t) { return e = e.replace("#", ""), r = parseInt(e.substring(0, 2), 16), g = parseInt(e.substring(2, 4), 16), b = parseInt(e.substring(4, 6), 16), result = "rgba(" + r + "," + g + "," + b + "," + t / 100 + ")", result }, t.getOffsetDays = function(e) { return t.getOffsetDaysOfDay(e.get("dueDate")) }, t.getOffsetDaysOfDay = function(e) { e = a.prefMomentFromUtc(e, n.format.atomTime), e.startOf("day"); var t = a.prefMoment().startOf("day"); return e.diff(t, "days") }, t.timeKeyLimit = function(e) { var t = e.which ? e.which : event.keyCode, i = s.getInputCaretPosition(e.currentTarget); return 1 >= i || i > 2 && 5 > i ? t >= o[0] && t <= o[9] || t >= o.numpad_0 && t <= o.numpad_9 ? !0 : !1 : 6 === i ? t === o.numpad_1 || t === o.f1 || t === o.a || t === o.p ? !0 : !1 : 7 === i ? t === o.subtract || t === o.m ? !0 : !1 : void 0 } })
/** * Enable validation of separators between function parameters. Will ignore newlines. * * Type: `String` * * Values: * * - `","`: function parameters are immediately followed by a comma * - `", "`: function parameters are immediately followed by a comma and then a space * - `" ,"`: function parameters are immediately followed by a space and then a comma * - `" , "`: function parameters are immediately followed by a space, a comma, and then a space * * #### Example * * ```js * "validateParameterSeparator": ", " * ``` * * ##### Valid * * ```js * function a(b, c) {} * ``` * * ##### Invalid * * ```js * function a(b , c) {} * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( typeof options === 'string' && /^[ ]?,[ ]?$/.test(options), this.getOptionName() + ' option requires string value containing only a comma and optional spaces' ); this._separator = options; }, getOptionName: function() { return 'validateParameterSeparator'; }, check: function(file, errors) { var separators = this._separator.split(','); var whitespaceBeforeComma = Boolean(separators.shift()); var whitespaceAfterComma = Boolean(separators.pop()); file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) { node.params.forEach(function(paramNode) { var prevParamToken = file.getFirstNodeToken(paramNode); var punctuatorToken = file.getNextToken(prevParamToken); if (punctuatorToken.value === ',') { if (whitespaceBeforeComma) { errors.assert.whitespaceBetween({ token: prevParamToken, nextToken: punctuatorToken, spaces: 1, message: 'One space required after function parameter \'' + prevParamToken.value + '\'' }); } else { errors.assert.noWhitespaceBetween({ token: prevParamToken, nextToken: punctuatorToken, message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\'' }); } var nextParamToken = file.getNextToken(punctuatorToken); if (whitespaceAfterComma) { errors.assert.whitespaceBetween({ token: punctuatorToken, nextToken: nextParamToken, spaces: 1, message: 'One space required before function parameter \'' + nextParamToken.value + '\'' }); } else { errors.assert.noWhitespaceBetween({ token: punctuatorToken, nextToken: nextParamToken, message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\'' }); } } }); }); } };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Created by Andrey Gayvoronsky on 13/04/16. */ var _ru_RU = require('gregorian-calendar/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); var _ru_RU3 = require('rc-calendar/lib/locale/ru_RU'); var _ru_RU4 = _interopRequireDefault(_ru_RU3); var _ru_RU5 = require('../../time-picker/locale/ru_RU'); var _ru_RU6 = _interopRequireDefault(_ru_RU5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var locale = _extends({}, _ru_RU2["default"]); locale.lang = _extends({ placeholder: 'Выберите дату', rangePlaceholder: ['Начальная дата', 'Конечная дата'] }, _ru_RU4["default"]); locale.timePickerLocale = _extends({}, _ru_RU6["default"]); // All settings at: // https://github.com/ant-design/ant-design/issues/424 exports["default"] = locale; module.exports = exports['default'];
/*! * Native JavaScript for Bootstrap Toast v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Toast = factory()); }(this, (function () { 'use strict'; var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend'; var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style; var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration'; var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty'; function getElementTransitionDuration(element) { var computedStyle = getComputedStyle(element); var propertyValue = computedStyle[transitionProperty]; var durationValue = computedStyle[transitionDuration]; var durationScale = durationValue.includes('ms') ? 1 : 1000; var duration = supportTransition && propertyValue && propertyValue !== 'none' ? parseFloat(durationValue) * durationScale : 0; return !Number.isNaN(duration) ? duration : 0; } function emulateTransitionEnd(element, handler) { var called = 0; var endEvent = new Event(transitionEndEvent); var duration = getElementTransitionDuration(element); if (duration) { element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) { if (e.target === element) { handler.apply(element, [e]); element.removeEventListener(transitionEndEvent, transitionEndWrapper); called = 1; } }); setTimeout(function () { if (!called) { element.dispatchEvent(endEvent); } }, duration + 17); } else { handler.apply(element, [endEvent]); } } function queryElement(selector, parent) { var lookUp = parent && parent instanceof Element ? parent : document; return selector instanceof Element ? selector : lookUp.querySelector(selector); } function reflow(element) { return element.offsetHeight; } function bootstrapCustomEvent(eventType, componentName, eventProperties) { var OriginalCustomEvent = new CustomEvent((eventType + ".bs." + componentName), { cancelable: true }); if (typeof eventProperties !== 'undefined') { Object.keys(eventProperties).forEach(function (key) { Object.defineProperty(OriginalCustomEvent, key, { value: eventProperties[key], }); }); } return OriginalCustomEvent; } function dispatchCustomEvent(customEvent) { if (this) { this.dispatchEvent(customEvent); } } /* Native JavaScript for Bootstrap 4 | Toast -------------------------------------------- */ // TOAST DEFINITION // ================== function Toast(elem, opsInput) { var element; // set options var options = opsInput || {}; // bind var self = this; // toast, timer var toast; var timer = 0; // custom events var showCustomEvent; var hideCustomEvent; var shownCustomEvent; var hiddenCustomEvent; var ops = {}; // private methods function showComplete() { toast.classList.remove('showing'); toast.classList.add('show'); dispatchCustomEvent.call(toast, shownCustomEvent); if (ops.autohide) { self.hide(); } } function hideComplete() { toast.classList.add('hide'); dispatchCustomEvent.call(toast, hiddenCustomEvent); } function close() { toast.classList.remove('show'); if (ops.animation) { emulateTransitionEnd(toast, hideComplete); } else { hideComplete(); } } function disposeComplete() { clearTimeout(timer); element.removeEventListener('click', self.hide, false); delete element.Toast; } // public methods self.show = function () { if (toast && !toast.classList.contains('show')) { dispatchCustomEvent.call(toast, showCustomEvent); if (showCustomEvent.defaultPrevented) { return; } if (ops.animation) { toast.classList.add('fade'); } toast.classList.remove('hide'); reflow(toast); // force reflow toast.classList.add('showing'); if (ops.animation) { emulateTransitionEnd(toast, showComplete); } else { showComplete(); } } }; self.hide = function (noTimer) { if (toast && toast.classList.contains('show')) { dispatchCustomEvent.call(toast, hideCustomEvent); if (hideCustomEvent.defaultPrevented) { return; } if (noTimer) { close(); } else { timer = setTimeout(close, ops.delay); } } }; self.dispose = function () { if (ops.animation) { emulateTransitionEnd(toast, disposeComplete); } else { disposeComplete(); } }; // init // initialization element element = queryElement(elem); // reset on re-init if (element.Toast) { element.Toast.dispose(); } // toast, timer toast = element.closest('.toast'); // DATA API var animationData = element.getAttribute('data-animation'); var autohideData = element.getAttribute('data-autohide'); var delayData = element.getAttribute('data-delay'); // custom events showCustomEvent = bootstrapCustomEvent('show', 'toast'); hideCustomEvent = bootstrapCustomEvent('hide', 'toast'); shownCustomEvent = bootstrapCustomEvent('shown', 'toast'); hiddenCustomEvent = bootstrapCustomEvent('hidden', 'toast'); // set instance options ops.animation = options.animation === false || animationData === 'false' ? 0 : 1; // true by default ops.autohide = options.autohide === false || autohideData === 'false' ? 0 : 1; // true by default ops.delay = parseInt((options.delay || delayData), 10) || 500; // 500ms default if (!element.Toast) { // prevent adding event handlers twice element.addEventListener('click', self.hide, false); } // associate targets to init object element.Toast = self; } return Toast; })));
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ var EXPORTED_SYMBOLS = ["Logger"]; const Cc = Components.classes; const Ci = Components.interfaces; function Logger(filename) { this.filename = filename; this.init(); } Logger.prototype = { _file: null, _fostream: null, init : function () { this._file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); this._file.initWithPath(this.filename); this._fostream = Cc["@mozilla.org/network/file-output-stream;1"]. createInstance(Ci.nsIFileOutputStream); // Create with PR_WRITE_ONLY(0x02), PR_CREATE_FILE(0x08), PR_APPEND(0x10) this._fostream.init(this._file, 0x02 | 0x08 | 0x10, 0664, 0); }, write: function(msg) { if (this._fostream) { var msgn = msg + "\n"; this._fostream.write(msgn, msgn.length); } }, close: function() { if (this._fostream) { this._fostream.close(); } this._fostream = null; this._file = null; } };
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes, Component } from 'react'; import styles from './LoginPage.css'; import withStyles from '../../decorators/withStyles'; import { Form, Input, Button, Grid, Row, Col, MenuItem, OverlayTrigger, Popover, Glyphicon } from 'react-bootstrap'; import UserActions from '../../actions/UserActions'; import userStore from '../../stores/userStore'; @withStyles(styles) class LoginPage extends Component { static contextTypes = { onSetTitle: PropTypes.func.isRequired, }; render() { const title = 'Log In'; const inputSizeInstance = ( <div> <Grid> <Row> <Col xs={6} sm={6} md={6} lg={6} > <h1> {title} <OverlayTrigger trigger="click" placement="right" overlay={<Popover title="Log In"> Enter your username and password into the form and then press the <strong> Submit </strong> button </Popover>}> <span className="helpIcon"> <Glyphicon glyph="glyphicon glyphicon-question-sign" /> </span> </OverlayTrigger> </h1> <form className="centeredLoginForm"> <Input className="test" type="text" bsSize="large" placeholder="Username" id="userID" /> <Input className="test" type="password" bsSize="large" placeholder="Password" id="userPassword" /> <Button className="test"bsStyle="primary" block bsSize="large" onClick={this.logUser}>Submit</Button> </form> </Col> </Row> </Grid> </div> ); this.context.onSetTitle(title); return ( <div desktop={true} width={320}> <div className="LoginPage-container"> {inputSizeInstance} </div> </div> ); } logUser() { console.log("THIS WORKS") var un = document.getElementById("userID").value; var up = document.getElementById("userPassword").value; UserActions.logUser(un, up); console.log(un); console.log(up); } } export default LoginPage;
import { shallow } from 'enzyme'; import React from 'react'; import MenuItem from './menu_item'; const keyCodeEnter = 13; describe('manager.ui.components.menu_item', () => { describe('render', () => { test('should use "a" tag', () => { const wrap = shallow( <MenuItem title="title" onClick={() => undefined}> Content </MenuItem> ); expect( wrap.matchesElement( <div role="menuitem" tabIndex="0" title="title"> Content </div> ) ).toBe(true); }); }); describe('events', () => { let onClick; let wrap; beforeEach(() => { onClick = jest.fn(); wrap = shallow(<MenuItem onClick={onClick}>Content</MenuItem>); }); test('should call onClick on a click', () => { wrap.simulate('click'); expect(onClick).toHaveBeenCalled(); }); test('should call onClick on enter key', () => { const e = { keyCode: keyCodeEnter }; wrap.simulate('keyDown', e); expect(onClick).toHaveBeenCalledWith(e); }); test("shouldn't call onClick on other keys", () => { wrap.simulate('keyDown', {}); expect(onClick).not.toHaveBeenCalled(); }); test('should prevent default on mousedown', () => { const e = { preventDefault: jest.fn(), }; wrap.simulate('mouseDown', e); expect(e.preventDefault).toHaveBeenCalled(); }); }); });
const router = require('koa-router')() router.get('/', async (ctx, next) => { await ctx.render('index', { title: 'just make real better place' }) }) router.get('/string', async (ctx, next) => { ctx.body = 'koa2 string' }) router.get('/json', async (ctx, next) => { ctx.body = { title: 'koa2 json' } }) module.exports = router
import { combineReducers } from 'redux' import thoughts from './thoughts' import * as thoughtActs from './thoughts' import notes from './notes' import * as noteActs from './notes' import groups from './groups' import * as groupActs from './groups' const entities = combineReducers({ thoughts, notes, groups }) export { thoughtActs, noteActs, groupActs } export default entities
/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: * Chris Cummins <christopher.e.cummins@intel.com> */ /* * Place the API in a `GenRegions' namepsace. */ var GenRegions = GenRegions || {}; (function() { 'use strict'; /* Global Constants *********************************************************/ var REG_FILE_SIZE = 128; var REG_SIZE = 32; /* In bytes. */ var MAX_SUBREGNUM = Math.pow(2, 16); var MAX_REG_SPAN = 2; /* The number of register a region can span. */ /* Default values for regions. */ var DEFAULT_REG_FILE = 'g'; var DEFAULT_DATA_SIZE = 4; /* Float (4 bytes) */ /* Vertical grid size. */ var ROWS = 6; /* Our drawing context. */ var canvas = $('#canvas')[0]; var ctx = canvas.getContext('2d'); /* x,y offset to start drawing grid (leaves room for labels). */ var START_Y = 21; var START_X = 3; var COLOR_GOOD = '#dff0d8'; var COLOR_BAD = '#f2dede'; var COLOR_CELL_GOOD = '#0f4fa8'; var COLOR_CELL_BAD = '#e27171'; var COL_W = Math.floor((canvas.width - START_X) / REG_SIZE) - 1; var ROW_H = Math.floor((canvas.height - START_Y) / ROWS); /* This regexp will match the syntax of any direct addressing register address * region description. Note that matching this regexp only ensure that the * syntax is correct, there may still be non-syntactic errors in the * description, e.g., an invalid combination of strides, etc. */ var REGION_REGEXP = new RegExp(['^\s*(g|r)?0*', '([0-9]?[0-9]|1[0-1][0-9]|12[0-7])', '(\\.0*([0-9]?[0-9]?[0-9]|', '[0-5][0-9]{3}|6[0-4][0-9]{3}|', '65[0-4][0-9]{2}|', '655[0-2][0-9]|6553[0-6]))?', '(\s*<((0|1|2|4|8|16|32)[;,]\s*', '(1|2|4|8|16),\*)?(0|1|2|4)>)?', '(:?(ub|b|uw|w|ud|d|f|v))?$'].join(''), 'i'); /* Erros in region parsing will through this. */ function ParseError(title, msg) { this.title = title; this.msg = msg; } /* Dynamic Content **********************************************************/ function refresh() { hideAlerts(); /* Enable the 'Share' button. */ $('#share-btn').removeAttr('disabled'); try { submitRegion(); drawRegion(); } catch (e) { if (e instanceof ParseError) { showAlertError(e.title, e.msg); submitEmptyRegion(); flashRegionFormBackground(COLOR_BAD); } else { showAlertError('Application Error', 'Uncaught JavaScript exception.'); } } } /* Region input. */ $('#region-form').keyup(function(event) { var key = event.keyCode; /* We want to update the region if we're typing something useful. */ if (key == 13) { refresh(); } }); /* --advanced. */ $('#advanced').click(function() { if (isValidRegion()) refresh(); }); function setAdvanced(advanced) { $('#advanced').prop('checked', advanced); } function getAdvanced(advanced) { return $('#advanced')[0].checked; } function toggleAdvanced() { setAdvanced(!getAdvanced()); hideAlerts(); refresh(); } /* Submit. */ $('#submit').click(function() { refresh(); }); /* Share. */ $('#share-btn').click(function() { toggleShare(); }); $('#share .close').click(function() { $('#share').hide(); }); /* Alerts. */ $('#alert-error .close').click(function() { $('#alert-error').hide(); }); $('#alert .close').click(function() { $('#alert').hide(); }); function showAlertError(title, msg) { $('#alert-error-placeholder').html('<strong>' + title + '</strong> ' + msg); $('#alert-error').show(); } function showAlert(title, msg) { $('#alert-placeholder').html('<strong>' + title + '</strong> ' + msg); $('#alert').show(); } /* * Decode a region from URL hash. If the hash contains a malformed region, * show an error. Returns 1 if hash contained region description, else 0. */ function loadStateFromHash() { var hash = decodeURIComponent(location.hash); var args = hash.split('&'); var argc = 0; for (var i = 0; i < args.length; i++) { var pair = args[i].split('='); switch (String(pair[0])) { case '#e': setExecSize(pair[1]); argc++; break; case 'r': /* We only set the region text if it does not match the current * text. This prevents the caret from being moved to the end of the * string while typing. */ if (getRegionString() != pair[1]) setRegionString(pair[1]); argc++; break; case 'a': setAdvanced(parseInt(pair[1]) ? true : false); argc++; break; } } if (argc === 3) { /* We got all our arguments. */ return 1; } else { if (argc) { /* We got some arguments, but not all. */ showAlertError('Malformed URL', 'URL hash contained invalid ' + 'region description.'); submitEmptyRegion(); } return 0; } } /* * Encodes the current state and returns it as a URL hash string. */ function saveStateToHash() { var reg = encodeURIComponent(getRegionString()); return '#e=' + getExecSize() + '&r=' + reg + '&a=' + ((getAdvanced()) ? 1 : 0); } function toggleShare() { var shareDiv = $('#share'); if (shareDiv.is(':visible')) { shareDiv.hide(); } else { /* Show the hash and highlight it for quick copying. */ var urlBox = $('#share-hash')[0]; urlBox.value = 'https://chriscummins.cc/gen-regions' + saveStateToHash(); shareDiv.show(); urlBox.focus(); urlBox.select(); urlBox.setSelectionRange(0, 120); } } function hideAlerts() { $('.alert').hide(); } function flashRegionFormBackground(color) { var regionForm = $('#region-form')[0]; regionForm.style.background = color; var interval = setInterval(function() { regionForm.style.background = '#FFF'; clearInterval(interval); }, 500); } function getRegionString() { return $('#region-form')[0].value; } function setRegionString(string) { $('#region-form')[0].value = string; } function clearRegionString(string) { setRegionString(''); return false; } function setCanvasTooltip(message) { if (message) { $('#canvas').attr('data-original-title', message).tooltip('fixTitle'); } } /* exec size */ $('#exec-size').change(function() { if (isValidRegion()) refresh(); }); function getExecSize() { return parseInt($('#exec-size option:selected').text()); } function setExecSize(size) { $('#exec-size').val(size).attr('select', true); } /* Clear the canvas. */ function clearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#f5f5f5'; ctx.fillRect(START_X, START_Y, (32 * COL_W), (ROWS * ROW_H)); } /* Draw the vertical column lines. */ function drawGridColumns() { var col_x = START_X; ctx.strokeStyle = '#c0c0c0'; ctx.lineWidth = 1; for (var i = 0; i <= REG_SIZE; i++) { ctx.moveTo(col_x + .5, START_Y); ctx.lineTo(col_x + .5, START_Y + (ROWS * ROW_H)); ctx.stroke(); col_x += COL_W; } } /* Draw the column labels (byte indexes). */ function drawColLabels() { var col_x = START_X + 5; ctx.textAlign = 'center'; ctx.fillStyle = '#000'; ctx.font = '12px arial'; for (var i = 0; i < REG_SIZE; i++) { ctx.fillText(REG_SIZE - 1 - i, col_x + COL_W / 2 - 5, START_Y - 5); col_x += COL_W; } } /* Draw the horizontal row lines. */ function drawGridRows() { var row_y = START_Y; ctx.strokeStyle = '#c0c0c0'; ctx.lineWidth = 1; for (var i = 0; i <= ROWS; i++) { ctx.moveTo(START_X, row_y + .5); ctx.lineTo(START_X + (REG_SIZE * COL_W), row_y + .5); ctx.stroke(); row_y += ROW_H; } } /* * Draw the row labels (register numbers). */ function drawRowLabels(regFile, startRegister) { var row_y = START_Y + ROW_H - (canvas.height / 30); ctx.textAlign = 'left'; ctx.fillStyle = '#000'; ctx.font = 'bold 12px arial'; for (var i = 0; i < ROWS; i++) { ctx.fillText(regFile + (startRegister + i), canvas.width - 45, row_y); row_y += ROW_H; } } /* Key Bindings *************************************************************/ function pageBind(key, func) { $(document).bind('keydown', key, func); $('#region-form').bind('keydown', key, func); $('#share-hash').bind('keydown', key, func); } pageBind('a', toggleAdvanced); pageBind('s', toggleShare); pageBind('esc', hideAlerts); pageBind('c', clearRegionString); $(document).bind('keydown', 'r', function() { $('#region-form').focus(); return false; }); $('#share-hash').bind('keydown', 'r', function() { $('#region-form').focus(); return false; }); $(document).bind('keydown', 'return', function() { refresh(); }); /* Register Region parsing **************************************************/ var execSize; var regFile; var register; var subRegNum; var vertStride; var width; var horzStride; var dataSize; /* * Perform a dry-run parse of the region description. */ function isValidRegion() { if (getRegionString().match(REGION_REGEXP)) { /* It passed the regexp match, so lets see if we can submit it (without * drawing anything. */ try { submitRegion(); return 1; } catch (e) { return 0; } } return 0; } /* Gets the region description, execSize and --advanced. If any of the input * data is invalid, it will throw a descriptive ParseError exception. * * Region descriptions take the form: * [RegFile] RegNum[.SubRegNum][<[VertStride;Width,]HorzStide>][:type] * * Values in square brackets ([x]) denote optional additions. Where optional * parts are omitted, the following assumptions are made: * * [RegFile] RegFile is DEFAULT_REG_FILE. * [.SubRegNum] SubRegNum is 0. * [VertSride;Width,] Region is 1D. * [<VertStride;Width,HorzStride>] Region is scalar. * [:type] Elements are of size DEFAULT_DATA_SIZE. */ function submitRegion() { var regionString = getRegionString(); if (!regionString) { throw new ParseError('Syntax Error', 'Region must be in the form: ' + '<code>RegNum.SubRegNum&lt;VertStride;' + 'Width,HorzStide&gt;:type</code>'); } /* We don't want whitespace getting in our way, so lets remove it. */ while (regionString.match(/\s/)) regionString = regionString.replace(/\s+/, ''); if (regionString.match(/:$/)) { throw new ParseError('Syntax Error', 'Illegal trailing <code>:</code> character.'); } /* Strip the data type from the region string and set the dataSize, or use * default. */ dataSize = regionString.match(/[a-z]+$/i); if (dataSize) { switch (String(dataSize).toLowerCase()) { case 'b': case 'ub': dataSize = 1; break; case 'uw': case 'w': dataSize = 2; break; case 'ud': case 'd': case 'f': case 'v': dataSize = 4; break; default: throw new ParseError('Illegal Data Type \'' + dataSize + '\'', 'Possible values: ' + '<code>ub|b|uw|w|ud|d|f|v</code>.'); } /* Strip the data type from the region string. */ regionString = regionString.replace(/[a-z]+$/i, ''); } else { dataSize = DEFAULT_DATA_SIZE; } /* Test and set the [optional] RegFile. */ regFile = regionString.match(/^[a-z]+/i); if (regFile) { /* We have a regFile, so strip it from the region string. */ regionString = regionString.replace(/^[a-z]+/i, ''); } else { /* No RegFile, use the default. */ regFile = DEFAULT_REG_FILE; } /* Strip the register number from the region string. */ register = parseInt(regionString.match(/^\d+/)); regionString = regionString.replace(/^\d+/g, ''); /* Get or set the number of execution channels. */ execSize = getExecSize(); /* Strip the the SubRegNum from the region string, or use default. Here, we * deliberately catch a wider set of values then are permissible, so that in * the case of region descriptions containing syntax errors such as * '10.foo<1>', we still receive the 'foo' as a subRegNum, which we can then * use to give a more informative syntax error. */ if (regionString.match(/^\.\w+/)) { regionString = regionString.replace(/^\./, ''); subRegNum = parseInt(regionString.match(/^\w+/)); regionString = regionString.replace(/^\w+/, ''); } else { subRegNum = 0; } if (isNaN(subRegNum)) { throw new ParseError('Invalid SubRegNum', 'A subregister must be an ' + 'integer value in the range [0, ' + MAX_SUBREGNUM + '].'); } if (subRegNum > MAX_SUBREGNUM) { throw new ParseError('Invalid SubRegNum \'' + subRegNum + '\'', 'A subregister must be an integer value in the ' + 'range [0, ' + MAX_SUBREGNUM + '].'); } /* Convert subRegNum to a byte offset if in --advanced mode. */ if (getAdvanced()) subRegNum *= dataSize; /* Validate the the region description syntax. */ if (!regionString.match(/^(<[\d;,]+>)?:?$/g)) { throw new ParseError('Syntax Error', 'Region descriptions must be in ' + 'the form: <code>&lt;VertStride;Width,' + 'HorzStride&gt;</code>'); } /* Discard the angle brackets, and the trailing ':', if present. */ if (regionString) { regionString = regionString.replace(/^</, ''); regionString = regionString.replace(/>?:?$/, ''); } /* Direct addressing region descriptions can take 3 forms: * * Region ::= <VertStride> “;” <Width> “,” <HorzStride> * | <VertStride> “,” <Width> “,” <HorzStride> * RegionV ::= <VertStride> * RegionE ::= "" * * Here we'll extract the vertStride, width and horzStride from this * description, inserting defaults if any of the values are missing. If the * region does not match any of those forms, it is a syntax error. */ if (regionString.match(/^\d+[;,]\d+,\d+$/)) { /* Region ::= <VertStride> “;” <Width> “,” <HorzStride> * | <VertStride> “,” <Width> “,” <HorzStride> */ vertStride = parseInt(regionString.match(/^\d+/)); regionString = regionString.replace(/^\d+[;,]/, ''); width = parseInt(regionString.match(/^\d+/)); regionString = regionString.replace(/^\d+,/, ''); horzStride = parseInt(regionString); } else if (regionString.match(/^\d+$/)) { /* RegionV ::= <VertStride> */ vertStride = parseInt(regionString); width = 1; horzStride = 0; } else if (regionString.match(/^$/)) { /* RegionE ::= "" */ vertStride = 0; width = 1; horzStride = 0; } else { throw new ParseError('Syntax Error', 'Region descriptions must be in ' + 'the form: <code>&lt;VertStride;Width,' + 'HorzStride&gt;</code>'); } /* Now that the input string is parsed, we perform some checks for general * restrictions on regioning parameters. */ if (isNaN(register)) { throw new ParseError('Syntax Error', 'RegNum must be an integer in ' + 'the range [0, ' + REF_FILE_SIZE - 1 + '].'); } if (register >= REG_FILE_SIZE) { throw new ParseError('Out of Bounds', 'RegNum \'' + register + '\' must be an integer in the range [0, ' + REF_FILE_SIZE - 1 + '].'); } if (!String(vertStride).match(/^(0|1|2|4|8|16|32)$/)) { throw new ParseError('Invalid Vertical Stride \'' + vertStride + '\'', 'Possible values: <code>0|1|2|4|8|16|32</code>.'); } if (!String(width).match(/^(1|2|4|8|16)$/)) { throw new ParseError('Invalid Width \'' + width + '\'', 'Possible values: <code>1|2|4|8|16</code>.'); } if (!String(horzStride).match(/^(0|1|2|4)$/)) { throw new ParseError('Invalid Horizontal Stride \'' + horzStride + '\'', 'Possible values: <code>0|1|2|4</code>.'); } if (execSize < width) { throw new ParseError('Out of Bounds', 'Execution size must be ' + 'greater or equal to width. (execSize: \'' + execSize + '\', width: \'' + width + '\')'); } if (execSize == width && horzStride && vertStride != width * horzStride) { throw new ParseError('Invalid Region', 'If execution size is equal ' + 'to width and horizontal stride is greater ' + 'than 0, vertical stride must be set to the ' + 'product of the width and horizontal strides. ' + '(execSize: width: \'' + width + '\', ' + 'horzStride: \'' + horzStride + '\', vertStride: \'' + vertStride + '\')'); } if (width == 1 && horzStride) { throw new ParseError('Invalid Region', 'If width is equal to \'1\', ' + 'horizontal stride must be \'0\'. ' + '(width: \'' + width + '\', ' + 'horzStride: \'' + horzStride + '\')'); } if (execSize == 1 && width == 1 && (vertStride || horzStride)) { throw new ParseError('Invalid Scalar', 'If both the execution size ' + 'and width are equal to \'1\', both vertical ' + 'stride and horizontal stride must be \'0\'. ' + '(execSize: \'' + execSize + '\', ' + 'width: \'' + width + '\', ' + 'vertStride: \'' + vertStride + '\', horzStride: \'' + horzStride + '\')'); } if (!vertStride && !horzStride && width != 1) { throw new ParseError('Invalid Region', 'If both vertical and ' + 'horizontal strides are equal to \'0\', ' + 'width must be set to \'1\'. ' + '(vertStride: \'' + vertStride + '\', ' + 'horzStride: \'' + horzStride + '\', ' + 'width: \'' + width + '\')'); } } function submitEmptyRegion() { execSize = 0; regFile = DEFAULT_REG_FILE; register = 0; subRegNum = 0; vertStride = 0; width = 0; horzStride = 0; dataSize = 0; drawRegion(); } function drawRegion() { var startRegister; /* The lowermost register to draw. */ /* * Draw the region cells. */ function drawRegionCells(startRegister) { /* * Draw a cell at the given coordinates. */ function drawCell(label, x, y, width, color) { /* Don't draw anything outside of the grid */ if (y + ROW_H > canvas.height) return; ctx.fillStyle = color; ctx.globalAlpha = 0.7; ctx.fillRect(x, y, width, ROW_H); ctx.strokeStyle = '#06266F'; ctx.lineWidth = 2; ctx.strokeRect(x + .5, y + .5, width - .5, ROW_H - .5); ctx.fillStyle = '#FFF'; ctx.globalAlpha = 1.0; ctx.fillText(label, x + (width / 2), y + (ROW_H / 2) + 5); } var count = 0; var rows = execSize / width; var firstReg; ctx.textAlign = 'center'; ctx.font = 'bold 14px arial'; for (var r = 0; r < rows; r++) { for (var c = 0; c < width; c++) { /* The absolute offset (in bytes) of the target element from the * starting register. */ var regByte = subRegNum + (r * vertStride * dataSize) + (c * horzStride * dataSize); /* The register of the current element. */ var reg = register + Math.floor(regByte / REG_SIZE); var regOffset = (regByte % REG_SIZE); /* We cache the first reg so that we can detect when a region spans * more than 2 registers. */ if (!r && !c) firstReg = reg; /* We only show a warning for out of range accesses. */ if (reg - firstReg >= MAX_REG_SPAN) { flashRegionFormBackground(COLOR_BAD); showAlert('Out of Bounds', 'A source cannot span more ' + 'than 2 adjacent GRF registers ' + '(affected region is shown in red).'); } /* We check now that everything is in bounds. If not, alert the user. */ if (reg >= REG_FILE_SIZE) { showAlertError('Out of Bounds', 'Register access \'' + reg + '\' out of bounds!'); flashRegionFormBackground(COLOR_BAD); } /* Now lets get the canvas coordinates of the cell for drawing. */ var x = START_X + (REG_SIZE - regOffset - dataSize) * COL_W; var y = START_Y + ((reg - startRegister) * ROW_H); /* Finally, we can paint the cell, assuming of course that we are * painting a cell within the execution size. Otherwise, we are * done. This check is needed for cases where: * (execSize % width) != 0. */ if (count < execSize && reg < REG_FILE_SIZE) { var color = (reg - firstReg < MAX_REG_SPAN) ? COLOR_CELL_GOOD : COLOR_CELL_BAD; var cw = dataSize * COL_W; if (x < START_X) { var overlap = START_X - x; /* The element overlaps a register boundary. */ cw -= overlap; color = COLOR_CELL_BAD; drawCell(count, START_X + REG_SIZE * COL_W - overlap, y + ROW_H, overlap, COLOR_CELL_BAD); x = START_X; showAlert('Out of Bounds', 'An element cannot span a register ' + 'boundary (affected element is shown in red).'); flashRegionFormBackground(COLOR_BAD); } drawCell(count++, x, y, cw, color); } else return; } } } if (execSize) { setCanvasTooltip(execSize + ' channels executing on a region starting at ' + 'register ' + regFile + register + '.' + subRegNum + ', with a width of ' + width + ', a horizontal stride of ' + horzStride + ' and a vertical stride of ' + vertStride + '.'); } else { setCanvasTooltip(); } if (execSize) flashRegionFormBackground(COLOR_GOOD); startRegister = Math.max(register - 2, 0); startRegister = Math.min(startRegister, REG_FILE_SIZE - ROWS); clearCanvas(); drawGridColumns(); drawGridRows(); drawColLabels(); drawRowLabels(regFile, startRegister); drawRegionCells(startRegister); } /* * Bootstrap our page. */ this.init = function() { /* Dropdown */ $("select[name='exec-size']").selectpicker({ style: 'btn-primary', menuStyle: 'dropdown-inverse' }); $('.dropdown-toggle').attr('data-original-title', 'Execution size').tooltip('fixTitle'); /* Switch */ $('.switch').attr('data-original-title', 'Advanced mode').tooltip('fixTitle'); $('#share-btn').attr('disabled', 'disabled'); if (loadStateFromHash()) { refresh(); } else { hideAlerts(); submitEmptyRegion(); } /* Tooltips */ $('#canvas').tooltip('hide'); $('#exec-size').tooltip('hide'); $('#region-form').tooltip('hide'); $('#advanced').tooltip('hide'); }; }).call(GenRegions); /** * Bootstrap the gen regions code */ window.onload = GenRegions.init;
(function ($) { Drupal.behaviors.addGMapCurrentLocation = { attach: function (context, settings) { // Start with a map canvas, then add marker and balloon with address info // when the geo-position comes in. var mapOptions = settings.ip_geoloc_current_location_map_options; if (!mapOptions) { mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP, zoom: 15 }; } var map = new google.maps.Map(document.getElementById(settings.ip_geoloc_current_location_map_div), mapOptions); /* Use the geo.js unified API. This covers W3C Geolocation API, Google Gears * and some specific devices like Palm and Blackberry. */ if (geo_position_js.init()) { geo_position_js.getCurrentPosition(displayMap, displayMapError, {enableHighAccuracy: true}); } else { // Don't pop up annoying alert. Just show blank map of the world. map.setZoom(0); map.setCenter(new google.maps.LatLng(0, 0)); } function displayMap(position) { var coords = position.coords; var center = new google.maps.LatLng(coords.latitude, coords.longitude); map.setCenter(center); var marker = new google.maps.Marker({ map: map, position: center }); new google.maps.Geocoder().geocode({'latLng': center}, function(response, status) { if (status == google.maps.GeocoderStatus.OK) { addressText = response[0]['formatted_address']; } else { alert(Drupal.t('IP Geolocation displayMap(): Google address lookup failed with status code !code.', { '!code': status })); } // lat/long and address are revealed when clicking marker var lat = coords.latitude.toFixed(4); var lng = coords.longitude.toFixed(4); var latLongText = Drupal.t('lat. !lat, long. !long', { '!lat': lat, '!long': lng }) + '<br/>' + Drupal.t('accuracy !accuracy m', { '!accuracy': coords.accuracy }); var infoPopUp = new google.maps.InfoWindow({ content: addressText + '<br/>' + latLongText }); google.maps.event.addListener(marker, 'click', function() { infoPopUp.open(map, marker) }); }); } function displayMapError(error) { switch (error.code) { case 1: text = Drupal.t('user declined to share location'); break; case 2: text = Drupal.t('position unavailable (connection lost?)'); break; case 3: text = Drupal.t('timeout'); break; default: text = Drupal.t('unknown error'); } //alert(Drupal.t('IP Geolocation, current location map: getCurrentPosition() returned error !code: !text', {'!code': error.code, '!text': text})); } } } })(jQuery);
// server.js // modules ================================================= var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var session = require('express-session'); var MongoStore = require('connect-mongostore')(session); var cookieParser = require('cookie-parser'); // express route definitions var playerfetcher = require('./routes/playerfetcher'); var playerfetcherRandom = require('./routes/playerfetcherRandom'); var load = require('./routes/load'); var newgame = require('./routes/newgame'); // configuration =========================================== // config files var db = require('./config/db'); // set our port var port = process.env.PORT || 8080; // connect to our mongoDB database // (uncomment after you enter in your own credentials in config/db.js) // mongoose.connect(db.url); // use a favicon app.use(favicon(path.join(__dirname, 'public', 'favicon.png'))); // logger app.use(logger('dev')); //parse cookies app.use(cookieParser()); // get all data/stuff of the body (POST) parameters // parse application/json app.use(bodyParser.json()); // parse application/vnd.api+json as json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT app.use(methodOverride('X-HTTP-Method-Override')); // set the static files location /public/img will be /img for users app.use(express.static(__dirname + '/public')); // store session in mongodb app.use(session( { secret: 'secret1', resave: true, saveUninitialized: true, rolling: true, store: new MongoStore( { db: 'login', host: '127.0.0.1', port: '27017', autoRemove: 'disabled', collection: 'users', w:1, }), name: 'managersession', // unset: 'destroy', cookie: { maxAge: 2629746000 } })); // error handler // will print stacktrace app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); // routes ================================================== // require('./app/routes')(app); // configure our routes app.use('/load', load); app.use('/newgame', newgame); app.use('/playerfetcher', playerfetcher); app.use('/playerfetcherRandom', playerfetcherRandom); app.get('/*', function(req, res){ // res.render('index'); // res.sendFile(__dirname + '/public/index.html'); }); // start app =============================================== // startup our app at http://localhost:8080 app.listen(port); // shoutout to the user console.log('Magic happens on port ' + port); // expose app module.exports = app;
window.onload=function(){ function $(selector) { var i,arr,length,element,selec; element=document;//element默认为document对象 arr=selector.split(' ');//将选择字符串用空格分开 length=arr.length;//获取选择器的层级数 i=0; while(i<length){ if(arr[i].charAt(0)=="#"){ selec=/[^#].*/.exec(arr[i])[0];//使用正则提取id选择器 element=element.getElementById(selec); //alert("ID selector!") }else if(arr[i].charAt(0)=="."){ selec=/[^.].*/.exec(arr[i]);//使用正则提取class选择器 element=element.getElementsByClassName(selec)[0]; //alert("class selector!") }else if(arr[i].charAt(0)=="["){ alert("attr selector!") }else { element=element.getElementsByTagName(arr[i]); //alert("Tag selector!") } i++; } return element; } $("btn").click=function(){ var string=$("btn").value } }
module.exports = function ({ parsers, $lookup }) { parsers.chk.object = function () { return function () { return function ($buffer, $start, $end) { let object = { nudge: 0, value: 0, sentry: 0 } if ($end - $start < 1) { return parsers.inc.object(object, 1)($buffer, $start, $end) } object.nudge = ($buffer[$start++]) if ($end - $start < 2) { return parsers.inc.object(object, 3)($buffer, $start, $end) } object.value = ($buffer[$start++]) * 0x80 + ($buffer[$start++]) if ($end - $start < 1) { return parsers.inc.object(object, 5)($buffer, $start, $end) } object.sentry = ($buffer[$start++]) return { start: $start, object: object, parse: null } } } () } }
var removed = [ "minecraft:anvil:0", "minecraft:anvil:1", "minecraft:anvil:2", "minecraft:mushroom_stew" ] for (var n in removed) { removeRecipes(removed[n]); hideFromNEI(removed[n]); } addToolTip(removed, ["info.sotc.jmod.tooltips.removed.item"]); // Remove string crafting recipes, will reset them myself. removeRecipes("minecraft:string"); removeRecipes("minecraft:wool"); // Remove these food items, will add recipes to iron plate removeRecipes("minecraft:bread"); removeRecipes("minecraft:cookie"); removeRecipes("minecraft:pumpkin_pie"); // removeRecipes("minecraft:cake"); // No need for vanilla mushroom stew removeRecipes("minecraft:mushroom_stew"); removeSmeltingRecipes("minecraft:bread");
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var forms_1 = require("@angular/forms"); var lang_1 = require("../util/lang"); exports.lt = function (lt) { return function (control) { if (!lang_1.isPresent(lt)) return null; if (lang_1.isPresent(forms_1.Validators.required(control))) return null; var v = +control.value; return v < +lt ? null : { lt: true }; }; }; //# sourceMappingURL=validator.js.map
'use strict'; describe('Controller Tests', function() { describe('Operation Management Detail Controller', function() { var $scope, $rootScope; var MockEntity, MockPreviousState, MockOperation, MockBankAccount, MockLabel; var createController; beforeEach(inject(function($injector) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); MockEntity = jasmine.createSpy('MockEntity'); MockPreviousState = jasmine.createSpy('MockPreviousState'); MockOperation = jasmine.createSpy('MockOperation'); MockBankAccount = jasmine.createSpy('MockBankAccount'); MockLabel = jasmine.createSpy('MockLabel'); var locals = { '$scope': $scope, '$rootScope': $rootScope, 'entity': MockEntity, 'previousState': MockPreviousState, 'Operation': MockOperation, 'BankAccount': MockBankAccount, 'Label': MockLabel }; createController = function() { $injector.get('$controller')("OperationDetailController", locals); }; })); describe('Root Scope Listening', function() { it('Unregisters root scope listener upon scope destruction', function() { var eventType = 'helloJhipsterApp:operationUpdate'; createController(); expect($rootScope.$$listenerCount[eventType]).toEqual(1); $scope.$destroy(); expect($rootScope.$$listenerCount[eventType]).toBeUndefined(); }); }); }); });
(function () { 'use strict'; // PasswordValidator service used for testing the password strength angular .module('users.services') .factory('PasswordValidator', PasswordValidator); PasswordValidator.$inject = ['$window']; function PasswordValidator($window) { var owasp = $window.owaspPasswordStrengthTest; owasp.config({ minLength: 8 }); var service = { getResult: getResult, getPopoverMsg: getPopoverMsg }; return service; function getResult(password) { var result = owasp.test(password); return result; } function getPopoverMsg() { var popoverMsg = 'Please enter a passphrase or password with 8 or more characters, numbers, lowercase, uppercase, and special characters.'; return popoverMsg; } } }());
'use strict'; module.exports = function pagingLogLine(Janeway, Blast, Bound) { var stripEsc = Janeway.stripEsc, esc = Janeway.esc, F = Bound.Function; /** * A paging log line * * @author Jelle De Loecker <jelle@develry.be> * @since 0.3.0 * @version 0.3.0 * * @param {LogList} logList The parent LogList instance */ var PagingLogLine = Janeway.PropertyLogLine.extend(function PagingLogLine(logList) { // Call the parent constructor PagingLogLine.super.call(this, logList); }); /** * Return the parent's pagination object * * @author Jelle De Loecker <jelle@develry.be> * @since 0.3.0 * @version 0.3.0 * * @param {Object} */ PagingLogLine.setProperty(function pagination() { return this.parent.pagination || {}; }); /** * Return the (coloured) representation of this line's contents * * @author Jelle De Loecker <jelle@develry.be> * @since 0.3.0 * @version 0.3.0 * * @param {Number} x On what (plain) char position was clicked */ PagingLogLine.setMethod(function getContentString(x) { var result, page_nr, start, prev, next; prev = '« Previous page'; next = 'Next page »'; page_nr = 'Page ' + (this.pagination.page + 1) + ' of ' + (Math.ceil(this.pagination.max_page) + 1); start = ' ' + page_nr + ' '; // We need to remember the "button" indexes this.prev_button = [start.length, start.length + prev.length]; result = esc('2', start) + esc('30;47', prev); // Only add the "next" button if there is a next page if (this.pagination.max_page >= this.pagination.page) { result += ' ' + esc('30;47', next); this.next_button = [this.prev_button[1] + 2, this.prev_button[1] + next.length + 2]; } return result; }); /** * Select this line * * @author Jelle De Loecker <jelle@develry.be> * @since 0.3.0 * @version 0.3.0 * * @param {Number} x On what (plain) char position was clicked */ PagingLogLine.setMethod(function select(absX, level) { var index = absX - 3; if (this.next_button && index >= this.next_button[0] && index <= this.next_button[1]) { this.pagination.page++; } else if (index >= this.prev_button[0] && index <= this.prev_button[1]) { this.pagination.page--; if (this.pagination.page < 0) { this.pagination.page = 0; } } else { return; } this.parent.select(this.parent.selected_abs_x); }); Janeway.PagingLogLine = PagingLogLine; };
'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var ghPages = require('gulp-gh-pages'); var del = require('del'); gulp.task('publish', function() { return gulp.src(path.join(conf.paths.dist, '/**/*')) .pipe(ghPages()); }); gulp.task('cleanPub', ['publish'], function () { return del(['.publish']); }); gulp.task('deploy', ['publish', 'cleanPub']);
'use strict'; // {signature} {pubKey} Object.defineProperty(exports, '__esModule', { value: true }); const bscript = require('../../script'); function isCompressedCanonicalPubKey(pubKey) { return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33; } function check(script) { const chunks = bscript.decompile(script); return ( chunks.length === 2 && bscript.isCanonicalScriptSignature(chunks[0]) && isCompressedCanonicalPubKey(chunks[1]) ); } exports.check = check; check.toJSON = () => { return 'witnessPubKeyHash input'; };
!function() { var topojson = { version: "1.6.13", mesh: function(topology) { return object(topology, meshArcs.apply(this, arguments)); }, meshArcs: meshArcs, merge: function(topology) { return object(topology, mergeArcs.apply(this, arguments)); }, mergeArcs: mergeArcs, feature: featureOrCollection, neighbors: neighbors, presimplify: presimplify }; function stitchArcs(topology, arcs) { var stitchedArcs = {}, fragmentByStart = {}, fragmentByEnd = {}, fragments = [], emptyIndex = -1; // Stitch empty arcs first, since they may be subsumed by other arcs. arcs.forEach(function(i, j) { var arc = topology.arcs[i < 0 ? ~i : i], t; if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; } }); arcs.forEach(function(i) { var e = ends(i), start = e[0], end = e[1], f, g; if (f = fragmentByEnd[start]) { delete fragmentByEnd[f.end]; f.push(i); f.end = end; if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[end]) { delete fragmentByStart[f.start]; f.unshift(i); f.start = start; if (g = fragmentByEnd[start]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else { f = [i]; fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; } }); function ends(i) { var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); else p1 = arc[arc.length - 1]; return i < 0 ? [p1, p0] : [p0, p1]; } function flush(fragmentByEnd, fragmentByStart) { for (var k in fragmentByEnd) { var f = fragmentByEnd[k]; delete fragmentByStart[f.start]; delete f.start; delete f.end; f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); fragments.push(f); } } flush(fragmentByEnd, fragmentByStart); flush(fragmentByStart, fragmentByEnd); arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); return fragments; } function meshArcs(topology, o, filter) { var arcs = []; if (arguments.length > 1) { var geomsByArc = [], geom; function arc(i) { var j = i < 0 ? ~i : i; (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); } function line(arcs) { arcs.forEach(arc); } function polygon(arcs) { arcs.forEach(line); } function geometry(o) { if (o.type === "GeometryCollection") o.geometries.forEach(geometry); else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs) { arcs.forEach(polygon); } }; geometry(o); geomsByArc.forEach(arguments.length < 3 ? function(geoms) { arcs.push(geoms[0].i); } : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); } else { for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); } return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; } function mergeArcs(topology, objects) { var polygonsByArc = {}, polygons = [], components = []; objects.forEach(function(o) { if (o.type === "Polygon") register(o.arcs); else if (o.type === "MultiPolygon") o.arcs.forEach(register); }); function register(polygon) { polygon.forEach(function(ring) { ring.forEach(function(arc) { (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); }); }); polygons.push(polygon); } function exterior(ring) { return cartesianRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]) > 0; // TODO allow spherical? } polygons.forEach(function(polygon) { if (!polygon._) { var component = [], neighbors = [polygon]; polygon._ = 1; components.push(component); while (polygon = neighbors.pop()) { component.push(polygon); polygon.forEach(function(ring) { ring.forEach(function(arc) { polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { if (!polygon._) { polygon._ = 1; neighbors.push(polygon); } }); }); }); } } }); polygons.forEach(function(polygon) { delete polygon._; }); return { type: "MultiPolygon", arcs: components.map(function(polygons) { var arcs = []; // Extract the exterior (unique) arcs. polygons.forEach(function(polygon) { polygon.forEach(function(ring) { ring.forEach(function(arc) { if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { arcs.push(arc); } }); }); }); // Stitch the arcs into one or more rings. arcs = stitchArcs(topology, arcs); // If more than one ring is returned, // at most one of these rings can be the exterior; // this exterior ring has the same winding order // as any exterior ring in the original polygons. if ((n = arcs.length) > 1) { var sgn = exterior(polygons[0][0]); for (var i = 0, t; i < n; ++i) { if (sgn === exterior(arcs[i])) { t = arcs[0], arcs[0] = arcs[i], arcs[i] = t; break; } } } return arcs; }) }; } function featureOrCollection(topology, o) { return o.type === "GeometryCollection" ? { type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); }) } : feature(topology, o); } function feature(topology, o) { var f = { type: "Feature", id: o.id, properties: o.properties || {}, geometry: object(topology, o) }; if (o.id == null) delete f.id; return f; } function object(topology, o) { var absolute = transformAbsolute(topology.transform), arcs = topology.arcs; function arc(i, points) { if (points.length) points.pop(); for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { points.push(p = a[k].slice()); absolute(p, k); } if (i < 0) reverse(points, n); } function point(p) { p = p.slice(); absolute(p, 0); return p; } function line(arcs) { var points = []; for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); if (points.length < 2) points.push(points[0].slice()); return points; } function ring(arcs) { var points = line(arcs); while (points.length < 4) points.push(points[0].slice()); return points; } function polygon(arcs) { return arcs.map(ring); } function geometry(o) { var t = o.type; return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} : t in geometryType ? {type: t, coordinates: geometryType[t](o)} : null; } var geometryType = { Point: function(o) { return point(o.coordinates); }, MultiPoint: function(o) { return o.coordinates.map(point); }, LineString: function(o) { return line(o.arcs); }, MultiLineString: function(o) { return o.arcs.map(line); }, Polygon: function(o) { return polygon(o.arcs); }, MultiPolygon: function(o) { return o.arcs.map(polygon); } }; return geometry(o); } function reverse(array, n) { var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; } function bisect(a, x) { var lo = 0, hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid] < x) lo = mid + 1; else hi = mid; } return lo; } function neighbors(objects) { var indexesByArc = {}, // arc index -> array of object indexes neighbors = objects.map(function() { return []; }); function line(arcs, i) { arcs.forEach(function(a) { if (a < 0) a = ~a; var o = indexesByArc[a]; if (o) o.push(i); else indexesByArc[a] = [i]; }); } function polygon(arcs, i) { arcs.forEach(function(arc) { line(arc, i); }); } function geometry(o, i) { if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); else if (o.type in geometryType) geometryType[o.type](o.arcs, i); } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } }; objects.forEach(geometry); for (var i in indexesByArc) { for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { for (var k = j + 1; k < m; ++k) { var ij = indexes[j], ik = indexes[k], n; if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); } } } return neighbors; } function presimplify(topology, triangleArea) { var absolute = transformAbsolute(topology.transform), relative = transformRelative(topology.transform), heap = minAreaHeap(), maxArea = 0, triangle; if (!triangleArea) triangleArea = cartesianTriangleArea; topology.arcs.forEach(function(arc) { var triangles = []; arc.forEach(absolute); for (var i = 1, n = arc.length - 1; i < n; ++i) { triangle = arc.slice(i - 1, i + 2); triangle[1][2] = triangleArea(triangle); triangles.push(triangle); heap.push(triangle); } // Always keep the arc endpoints! arc[0][2] = arc[n][2] = Infinity; for (var i = 0, n = triangles.length; i < n; ++i) { triangle = triangles[i]; triangle.previous = triangles[i - 1]; triangle.next = triangles[i + 1]; } }); while (triangle = heap.pop()) { var previous = triangle.previous, next = triangle.next; // If the area of the current point is less than that of the previous point // to be eliminated, use the latter's area instead. This ensures that the // current point cannot be eliminated without eliminating previously- // eliminated points. if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; else maxArea = triangle[1][2]; if (previous) { previous.next = next; previous[2] = triangle[2]; update(previous); } if (next) { next.previous = previous; next[0] = triangle[0]; update(next); } } topology.arcs.forEach(function(arc) { arc.forEach(relative); }); function update(triangle) { heap.remove(triangle); triangle[1][2] = triangleArea(triangle); heap.push(triangle); } return topology; }; function cartesianRingArea(ring) { var i = -1, n = ring.length, a, b = ring[n - 1], area = 0; while (++i < n) { a = b; b = ring[i]; area += a[0] * b[1] - a[1] * b[0]; } return area * .5; } function cartesianTriangleArea(triangle) { var a = triangle[0], b = triangle[1], c = triangle[2]; return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1])); } function compareArea(a, b) { return a[1][2] - b[1][2]; } function minAreaHeap() { var heap = {}, array = [], size = 0; heap.push = function(object) { up(array[object._ = size] = object, size++); return size; }; heap.pop = function() { if (size <= 0) return; var removed = array[0], object; if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); return removed; }; heap.remove = function(removed) { var i = removed._, object; if (array[i] !== removed) return; // invalid request if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); return i; }; function up(object, i) { while (i > 0) { var j = ((i + 1) >> 1) - 1, parent = array[j]; if (compareArea(object, parent) >= 0) break; array[parent._ = i] = parent; array[object._ = i = j] = object; } } function down(object, i) { while (true) { var r = (i + 1) << 1, l = r - 1, j = i, child = array[j]; if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; if (j === i) break; array[child._ = i] = child; array[object._ = i = j] = object; } } return heap; } function transformAbsolute(transform) { if (!transform) return noop; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(point, i) { if (!i) x0 = y0 = 0; point[0] = (x0 += point[0]) * kx + dx; point[1] = (y0 += point[1]) * ky + dy; }; } function transformRelative(transform) { if (!transform) return noop; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(point, i) { if (!i) x0 = y0 = 0; var x1 = (point[0] - dx) / kx | 0, y1 = (point[1] - dy) / ky | 0; point[0] = x1 - x0; point[1] = y1 - y0; x0 = x1; y0 = y1; }; } function noop() {} if (typeof define === "function" && define.amd) define(topojson); else if (typeof module === "object" && module.exports) module.exports = topojson; else this.topojson = topojson; }();
/** * Created by ramone on 01/06/16. */ (function () { 'use strict'; angular .module('gg.directives') .directive('imgAreaSelect', imgAreaSelect); imgAreaSelect.$inject = ['ImageService']; /* @ngInject */ function imgAreaSelect(ImageService) { var directive = { // transclude: true, // bindToController: true, // controller: ImgAreaSelectCtrl, // controllerAs: 'vm', link: link, restrict: 'EA' }; return directive; function link(scope, element, attrs) { $(element).imgAreaSelect({ handles: true, fadeSpeed: 200, onSelectChange: function (img, selection) { scope.$apply(function () { preview(img, selection); }) } }); $(element).load(function () { initImage(); }); scope.$on('$destroy', function () { $(element).imgAreaSelect({ remove: true }); }); function initImage() { var i = ImageService.getImage(element.attr('src')); i.naturalWidth = element.prop('naturalWidth'); i.naturalHeight = element.prop('naturalHeight'); i.width = element.prop('width'); i.height = element.prop('height'); i.scaleWidth = i.naturalWidth / i.width; i.scaleHeight = i.naturalHeight / i.height; } function preview(img, selection) { // console.log(selection); var i = ImageService.getImage(img.attributes.src.value); var photoWidth = img.width; var photoHeight = img.height; var previewWidth = $('#preview').width(); var previewHeight = $('#preview').height(); if (!selection.width || !selection.height) return; ImageService.setSelection(img.attributes.src.value, selection); // scope.selection = selection; var scaleX = 100 / selection.width; var scaleY = 100 / selection.height; var ratio = Math.min(100 / selection.width, 100 / selection.height); $('#preview img').css({ width: photoWidth * ratio, height: photoHeight * ratio, marginLeft: -selection.x1 * ratio, marginTop: -selection.y1 * ratio }); // scope.$digest() $('#preview').css({ width: ratio * selection.width, height: ratio * selection.height }); $('#photo').data('selection', selection); } } } ImgAreaSelectCtrl.$inject = ['$q']; /* @ngInject */ function ImgAreaSelectCtrl($q) { } })();
describe('Helper Service', function() { beforeEach(module('clientApp')); var appHelper; beforeEach(inject(function(_appHelper_){ appHelper = _appHelper_; })); describe('isValidResponse', function() { it('should check that the response is valid', function() { var invalidResponses = [ "", {}, {id: "foo"}, {status: 200}, {config: {}} ]; for (var invalid of invalidResponses) { expect(appHelper.isValidResponse(invalid)).toBeFalsy(); } var valid = {status: 200, config: {}}; expect(appHelper.isValidResponse(valid)).toBeTruthy(); }); }); describe('isHtml', function() { it('should not be blank', function() { expect(appHelper.isHtml()).toBeFalsy(); expect(appHelper.isHtml("")).toBeFalsy(); }); it('should be of type HTML', function() { expect(appHelper.isHtml("application/json")).toBeFalsy(); expect(appHelper.isHtml("text/html; charset=utf-8")).toBeTruthy(); expect(appHelper.isHtml("text/html")).toBeTruthy(); }); }); describe('calculateObjectSize', function() { it('should roughly calculate the size of the specifed object', function() { expect(appHelper.calculateObjectSize({})).toBe(0); var largeObject = {}; for (var x = 0; x <= 100; x++) { largeObject[x] = new Date().toUTCString(); } expect(appHelper.calculateObjectSize(largeObject)).toBeGreaterThan(1000); //TODO trigger an exception to test -1 is returned //expect(appHelper.calculateObjectSize({})).toBe(-1); }); }); describe('determineStatus', function() { it('should return the XMLHttpRequest value if the request failed', function() { expect(appHelper.determineStatus(-1, "error")).toBe("ERROR"); expect(appHelper.determineStatus(-1, "foo")).toBe("FOO"); expect(appHelper.determineStatus(-1, "")).toBe(""); expect(appHelper.determineStatus(-1, undefined)).toBe(""); }); it('should return the status value if the request succeeded', function() { expect(appHelper.determineStatus(200, "foo")).toBe(200); expect(appHelper.determineStatus(500, undefined)).toBe(500); expect(appHelper.determineStatus(undefined, "foo")).toBeUndefined(); }); }); describe('determineStatusText', function() { it('should return an unknown status text if none is available', function() { expect(appHelper.determineStatusText(999, undefined)).toBe("Unknown HTTP Status Code."); expect(appHelper.determineStatusText(999, "")).toBe("Unknown HTTP Status Code."); expect(appHelper.determineStatusText("", "")).toBe("Unknown HTTP Status Code."); }); it('should return a description for the provided status value', function() { expect(appHelper.determineStatusText(200, "foo")).toBe("OK"); expect(appHelper.determineStatusText(500, "foo")).toBe("Internal Server Error"); expect(appHelper.determineStatusText("ABORT", "foo")).toBe("The request was cancelled."); }); it('should return the status text from the response if no other status text is available', function() { expect(appHelper.determineStatusText(999, "foo")).toBe("foo"); expect(appHelper.determineStatusText(undefined, "foo")).toBe("foo"); }); }); });
(function() { var CSON, Command, Unlink, config, fs, optimist, path, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; path = require('path'); CSON = require('season'); optimist = require('optimist'); Command = require('./command'); config = require('./apm'); fs = require('./fs'); module.exports = Unlink = (function(_super) { __extends(Unlink, _super); Unlink.commandNames = ['unlink']; function Unlink() { this.devPackagesPath = path.join(config.getAtomDirectory(), 'dev', 'packages'); this.packagesPath = path.join(config.getAtomDirectory(), 'packages'); } Unlink.prototype.parseOptions = function(argv) { var options; options = optimist(argv); options.usage("\nUsage: apm unlink [<package_path>]\n\nDelete the symlink in ~/.atom/packages for the package. The package in the\ncurrent working directory is unlinked if no path is given.\n\nRun `apm links` to view all the currently linked packages."); options.alias('h', 'help').describe('help', 'Print this usage message'); options.alias('d', 'dev').boolean('dev').describe('dev', 'Unlink package from ~/.atom/dev/packages'); options.boolean('hard').describe('hard', 'Unlink package from ~/.atom/packages and ~/.atom/dev/packages'); return options.alias('a', 'all').boolean('all').describe('all', 'Unlink all packages in ~/.atom/packages and ~/.atom/dev/packages'); }; Unlink.prototype.getDevPackagePath = function(packageName) { return path.join(this.devPackagesPath, packageName); }; Unlink.prototype.getPackagePath = function(packageName) { return path.join(this.packagesPath, packageName); }; Unlink.prototype.unlinkPath = function(pathToUnlink) { var error; try { process.stdout.write("Unlinking " + pathToUnlink + " "); if (fs.isSymbolicLinkSync(pathToUnlink)) { fs.unlinkSync(pathToUnlink); } return this.logSuccess(); } catch (_error) { error = _error; this.logFailure(); throw error; } }; Unlink.prototype.unlinkAll = function(options, callback) { var child, error, packagePath, _i, _j, _len, _len1, _ref, _ref1; try { _ref = fs.list(this.devPackagesPath); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; packagePath = path.join(this.devPackagesPath, child); if (fs.isSymbolicLinkSync(packagePath)) { this.unlinkPath(packagePath); } } if (!options.argv.dev) { _ref1 = fs.list(this.packagesPath); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { child = _ref1[_j]; packagePath = path.join(this.packagesPath, child); if (fs.isSymbolicLinkSync(packagePath)) { this.unlinkPath(packagePath); } } } return callback(); } catch (_error) { error = _error; return callback(error); } }; Unlink.prototype.unlinkPackage = function(options, callback) { var error, linkPath, packageName, targetPath, _ref; linkPath = path.resolve(process.cwd(), (_ref = options.argv._[0]) != null ? _ref : '.'); try { packageName = CSON.readFileSync(CSON.resolve(path.join(linkPath, 'package'))).name; } catch (_error) {} if (!packageName) { packageName = path.basename(linkPath); } if (options.argv.hard) { try { this.unlinkPath(this.getDevPackagePath(packageName)); this.unlinkPath(this.getPackagePath(packageName)); return callback(); } catch (_error) { error = _error; return callback(error); } } else { if (options.argv.dev) { targetPath = this.getDevPackagePath(packageName); } else { targetPath = this.getPackagePath(packageName); } try { this.unlinkPath(targetPath); return callback(); } catch (_error) { error = _error; return callback(error); } } }; Unlink.prototype.run = function(options) { var callback; callback = options.callback; options = this.parseOptions(options.commandArgs); if (options.argv.all) { return this.unlinkAll(options, callback); } else { return this.unlinkPackage(options, callback); } }; return Unlink; })(Command); }).call(this);
'use strict'; angular.module('payment').controller('TransactionsController', TransactionsController); function TransactionsController($scope, $http) { $http.get('findTransactions').success(function(data){ $scope.transactions = data; }); $scope.result = ''; var test = function(id){ $http.get('findTransaction/'+id).success(function(data){ $scope.result = data; }); }; $scope.findT = function(id){ console.log(id); test(id); } }
import Woowahan from 'woowahan'; import Template from './index.hbs'; export default Woowahan.ItemView.create('RowItem', { template: Template, onSelectedRow(event, trigger) { trigger({ id: this.getModel('id') }); } });
"use strict"; // JSPipe is free software distributed under the terms of the MIT license reproduced here. // JSPipe may be used for any purpose, including commercial purposes, at absolutely no cost. // No paperwork, no royalties, no GNU-like "copyleft" restrictions, either. // Just download it and use it. // Copyright (c) 2013 Joubert Nel // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var sentinel = '|Ω|'; function isGeneratorFunction(fn) { return true; // Don't do real checking yet, because it fails // in Firefox when using traceur for simulating // generators. // var fn = Function.isGenerator; // return fn && fn.call(x); } /** * Kick off a job. A job runs concurrently with other jobs. * * To communicate and synchronize with another job, communicate via a * Pipe. */ function job(fn, args) { var generator, next; if (isGeneratorFunction(fn)) { generator = fn.apply(fn, args); next = function(data) { var nextItem = generator.next(data), done = nextItem.done, value = nextItem.value, res; if (done) { res = null; } else { res = value ? value(next) : next(); } return res; }; next(); } else { throw new TypeError('function must be a generator function, i.e. function* () {...} '); } } /** * A pipe provides a way for two jobs to communicate data + synchronize their execution. * * One job can send data by calling "yield pipe.put(data)" and another job can * receive data by calling "yield pipe.get()". */ function Pipe() { this.syncing = false; this.inbox = []; this.outbox = []; this.isOpen = true; } Pipe.prototype.close = function() { this.isOpen = false; }; /** * Call "yield pipe.put(data)" from a job (the sender) to put data in the pipe. * * The put method will then try to rendezvous with a receiver job, if any. * If there is no receiver waiting for data, the sender will pause until another * job calls "yield pipe.get()", which will then trigger a rendezvous. */ Pipe.prototype.put = function(data) { var self = this; return function(resume) { self.inbox.push(data, resume); // Try to rendezvous with a receiver self._rendezvous(); }; }; Pipe.prototype.waiting = function() { return this.outbox.length; }; /** * Call "yield pipe.get()" from a job (the receiver) to get data from the pipe. * * The get method will then try to rendezvous with a sender job, if any. * If there is no sender waiting for the data it sent to be delivered, the receiver will * pause until another job calls "yield pipe.put(data)", which will then trigger * a rendezvous. */ Pipe.prototype.get = function() { var self = this; return function(resume) { self.outbox.push(resume); // Try to rendezvous with sender self._rendezvous(); }; }; Pipe.prototype.send = function(message) { this.put(message)(); }; /** * A pipe is a rendezvous point for two otherwise independently executing jobs. * Such communication + synchronization on a pipe requires a sender and receiver. * * A job sends data to a pipe using "yield pipe.put(data)". * Another job receives data from a pipe using "yield pipe.get()". * * Once both a sender job and a receiver job are waiting on the pipe, * the _rendezvous method transfers the data in the pipe to the receiver and consequently * synchronizes the two waiting jobs. * * Once synchronized, the two jobs continue execution. */ Pipe.prototype._rendezvous = function() { var syncing = this.syncing, inbox = this.inbox, outbox = this.outbox, data, notify, send, receipt, senderWaiting, receiverWaiting; if (!syncing) { this.syncing = true; while ((senderWaiting = inbox.length > 0) && (receiverWaiting = outbox.length > 0)) { // Get the data that the sender job put in the pipe data = inbox.shift(); // Get the method to notify the sender once the data has been // delivered to the receiver job notify = inbox.shift(); // Get the method used to send the data to the receiver job. send = outbox.shift(); // Send the data receipt = send(data); // Notify the sender that the data has been sent if (notify) { notify(receipt); } } this.syncing = false; } }; function EventPipe(el, type, handler) { // super Pipe.call(this); this._el = el; this._type = type; this._handler = handler; el.addEventListener(type, handler); } EventPipe.prototype = Object.create(Pipe.prototype); EventPipe.prototype.close = function() { this._el.removeEventListener(this._type, this._handler); delete this._el; delete this._type; delete this._handler; // super Pipe.prototype.close.call(this); }; /// /// Pipe producers /// function timeout(ms, interruptor) { // TODO: model timeout as a process var output = new Pipe(); setTimeout(function() { job(wrapGenerator.mark(function() { return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: $ctx.next = 2; return output.put(ms); case 2: case "end": return $ctx.stop(); } }, this); })); }, ms); return output; } function listen(el, type) { var handler = function(e) { job(wrapGenerator.mark(function() { return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: $ctx.next = 2; return output.put(e); case 2: case "end": return $ctx.stop(); } }, this); })); }; var output = new EventPipe(el, type, handler); return output; } function jsonp(url, id) { var output = new Pipe(); $.getJSON(url, function(data) { job(wrapGenerator.mark(function() { return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: $ctx.next = 2; return output.put({ data: data, id: id }) case 2: case "end": return $ctx.stop(); } }, this); })); }); return output; } function lazyseq(count, fn) { var output = new Pipe(); job(wrapGenerator.mark(function() { var data, i; return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: i = 0; case 1: if (!(0 < count--)) { $ctx.next = 8; break; } data = fn(i); $ctx.next = 5; return output.put(data); case 5: i++; $ctx.next = 1; break; case 8: $ctx.next = 10; return output.put(sentinel); case 10: output.close(); case 11: case "end": return $ctx.stop(); } }, this); })); return output; } /// /// Pipe transformers /// function unique(pipe) { var output = new Pipe(); job(wrapGenerator.mark(function() { var isFirstData, data, lastData; return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: isFirstData = true; case 1: if (!pipe.isOpen) { $ctx.next = 12; break; } $ctx.next = 4; return pipe.get(); case 4: data = $ctx.sent; if (!(isFirstData || data !== lastData)) { $ctx.next = 9; break; } $ctx.next = 8; return output.put(data); case 8: isFirstData = false; case 9: lastData = data; $ctx.next = 1; break; case 12: output.close(); case 13: case "end": return $ctx.stop(); } }, this); })); return output; } function pace(ms, pipe) { var output = new Pipe(); job(wrapGenerator.mark(function() { var timeoutId, data, send; return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: send = function(data) { output.send(data); }; case 1: if (!pipe.isOpen) { $ctx.next = 9; break; } $ctx.next = 4; return pipe.get(); case 4: data = $ctx.sent; clearTimeout(timeoutId); timeoutId = setTimeout(send.bind(output, data), ms); $ctx.next = 1; break; case 9: output.close(); case 10: case "end": return $ctx.stop(); } }, this); })); return output; } function delay(pipe, ms) { var output = new Pipe(); job(wrapGenerator.mark(function() { var data; return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: if (!pipe.isOpen) { $ctx.next = 9; break; } $ctx.next = 3; return timeout(ms).get(); case 3: $ctx.next = 5; return pipe.get(); case 5: data = $ctx.sent; output.send(data); $ctx.next = 0; break; case 9: case "end": return $ctx.stop(); } }, this); })); return output; } /// /// Pipe coordination /// function select(cases) { // TODO: consider rewriting as a sweetjs macro var output = new Pipe(), done = new Pipe(), remaining = cases.length; cases.forEach(function(item) { job(wrapGenerator.mark(function() { var pipe, response, data; return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: pipe = item.pipe, response = item.response; $ctx.next = 3; return pipe.get(); case 3: data = $ctx.sent; response(data); $ctx.next = 7; return done.put(true); case 7: case "end": return $ctx.stop(); } }, this); })); }); job(wrapGenerator.mark(function() { return wrapGenerator(function($ctx) { while (1) switch ($ctx.next) { case 0: if (!(remaining > 0)) { $ctx.next = 6; break; } $ctx.next = 3; return done.get(); case 3: remaining = remaining - 1; $ctx.next = 0; break; case 6: $ctx.next = 8; return output.put(sentinel); case 8: case "end": return $ctx.stop(); } }, this); })); return output; } function range() { // TODO: consider writing as a sweetjs macro throw 'Range has not been implemented yet.'; } exports.job = job; exports.Pipe = Pipe; exports.EventPipe = EventPipe; exports.timeout = timeout; exports.listen = listen; exports.jsonp = jsonp; exports.lazyseq = lazyseq; exports.unique = unique; exports.pace = pace; exports.delay = delay; exports.sentinel = sentinel; exports.select = select; exports.range = range;
/** * Page Component for Tag Test */ // Import Node Packages import React, { Component } from 'react'; import PropTypes from 'prop-types'; // Import Local Components import TagListContainer from './containers/TagListContainer'; // Import Helpers // Component Metadata const propTypes = { updateNotebook: PropTypes.func.isRequired, }; const defaultProps = { }; // Component Class for Template Page class TagTest extends Component { /** * Other Class Methods */ /** * React Functions */ constructor (props) { super(props); // Member Variables this.state = { tags: ["tag1", "tag2", "tag3", "tag4"], }; // Function Bindings this.handleAddTag = this.handleAddTag.bind(this); this.handleDeleteTag = this.handleDeleteTag.bind(this); this.render = this.render.bind(this); } // end constructor /** * Click and Event Handlers */ handleAddTag (s) { var newTags = this.state.tags; newTags.push(s); this.setState({tags: newTags}); } // end handleAddTag handleDeleteTag (i) { console.log(i); var newTags = this.state.tags; newTags.splice(i, 1); this.setState({tags: newTags}); } // end handleDeleteTag /** * Getter Methods */ /** * Other Render Methods */ /** * Render Function */ render () { return ( <TagListContainer tags={this.state.tags} handleAdd={this.handleAddTag} handleDelete={this.handleDeleteTag} /> ); } // end render } TagTest.propTypes = propTypes; TagTest.defaultProps = defaultProps; export default TagTest;
/* * * */ (function($) { 'use strict'; // // Class DEFINITION var Untouchable = function(element, options) { this.options = options; this.$element = $(element); $(document).on('mousemove', this.away.bind(this)); }; // // DEFAULT SETTING Untouchable.DEFAULTS = { distance: 100, duration: 100 }; Untouchable.prototype.getXvactor = function(elem, mouseX) { console.log(elem) return mouseX - (elem.offset().left + (elem.width() / 2)); }; Untouchable.prototype.getYvactor = function(elem, mouseY) { return mouseY - (elem.offset().top + (elem.height() / 2)); }; Untouchable.prototype.getDistance = function(elem, mouseX, mouseY) { return Math.sqrt(Math.pow(this.getXvactor(elem, mouseX), 2) + Math.pow(this.getYvactor(elem, mouseY), 2)); }; Untouchable.prototype.away = function(e) { console.log('onAway'); var mouseX = e.pageX; var mouseY = e.pageY; console.log('mouseX', mouseX); console.log('mouseY', mouseY); var distance = this.getDistance(this.$element, mouseX, mouseY); console.log('d', distance) if (distance < this.options.distance) { var x = this.getXvactor(this.$element, mouseX); var y = this.getYvactor(this.$element, mouseY); console.log('x', x); console.log('y', y); var topMove = ( y > 0 ? '-=' : '+=') + Math.abs(this.getYvactor(this.$element, mouseY)); var leftMove = ( x > 0 ? '-=' : '+=') + Math.abs(this.getXvactor(this.$element, mouseX)); // away this.$element.stop().animate({ top : topMove, left: leftMove }, this.options.duration, this.options.easing, this.options.onAway); } }; // // PLUGIN DEFINITION var old = $.fn.untouchable; $.fn.untouchable = function(option) { return this.each(function() { var $this = $(this); var data = $this.data('untouchable'); var options = $.extend({}, Untouchable.DEFAULTS, $this.data(), typeof option == 'object' && options); if (!data) $this.data('untouchable', (data = new Untouchable(this, options))); }); }; $.fn.untouchable.Constructor = Untouchable; // // NO CONFLICT $.fn.untouchable.noConflict = function () { $.fn.untouchable = old; return this; }; }(jQuery))
export { default } from 'ember-cli-mgmco-common/models/project';
(function(){ function paginator($resource,$q){ var directive = {}; directive.restrict = 'E'; directive.templateUrl = "scripts/directives/paginator/paginator.html"; directive.scope = { loadUrl : '@', resultsModel : '=' } directive.link = function ($scope, element, attrs) { $scope.pageNumber = 1; $scope.resultsPerPage = 10; $scope.service = $resource($scope.loadUrl,{},{isArray: false, method : 'GET'}); $scope.reloadData = function(){ $scope.resultsModel = $scope.service.get({pageNo : $scope.pageNumber, usersPerPage : $scope.resultsPerPage}); } $scope.forward = function(){ //todo add bounds checking $scope.pageNumber += 1; $scope.reloadData(); } $scope.back = function(){ if($scope.pageNumber > 1){ $scope.pageNumber -=1 ; $scope.reloadData(); } } $scope.reloadData(); $scope.resultsModel.$promise.then(function(data){ $scope.totalPages = Math.ceil(data.totalCount / $scope.resultsPerPage); }); } return directive; } angular.module('zfgc.forum') .directive('paginator',['$resource','$q',paginator]); })();
import { overcast, tearDown, expectInLog, expectNotInLog } from './utils.js'; describe('digitalocean', () => { beforeAll((nextFn) => { tearDown(nextFn); }); describe('create', () => { it('should create an instance', (nextFn) => { overcast('digitalocean create TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" (192.168.100.101) saved'); expectInLog(expect, logs, 'Connection established'); overcast('list', (logs) => { expectInLog(expect, logs, '(root@192.168.100.101:22)'); nextFn(); }); }); }); it('should not allow duplicate instance names', (nextFn) => { overcast('digitalocean create TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" already exists'); nextFn(); }); }); }); describe('boot', () => { it('should not allow an invalid instance to be booted', (nextFn) => { overcast('digitalocean boot INVALID_NAME', (logs) => { expectInLog(expect, logs, 'No instance found matching "INVALID_NAME"'); nextFn(); }); }); it('should boot a valid instance', (nextFn) => { overcast('digitalocean boot TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" booted'); nextFn(); }); }); }); describe('reboot', () => { it('should not allow an invalid instance to be rebooted', (nextFn) => { overcast('digitalocean reboot INVALID_NAME', (logs) => { expectInLog(expect, logs, 'No instance found matching "INVALID_NAME"'); nextFn(); }); }); it('should reboot an instance', (nextFn) => { overcast('digitalocean reboot TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" rebooted'); nextFn(); }); }); }); describe('shutdown', () => { it('should not allow an invalid instance to be shut down', (nextFn) => { overcast('digitalocean shutdown INVALID_NAME', (logs) => { expectInLog(expect, logs, 'No instance found matching "INVALID_NAME"'); nextFn(); }); }); it('should shutdown an instance', (nextFn) => { overcast('digitalocean shutdown TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" has been shut down'); nextFn(); }); }); }); describe('destroy', () => { it('should not allow an invalid instance to be destroyed', (nextFn) => { overcast('digitalocean destroy INVALID_NAME', (logs) => { expectInLog(expect, logs, 'No instance found matching "INVALID_NAME"'); nextFn(); }); }); it('should destroy an instance', (nextFn) => { overcast('digitalocean destroy TEST_NAME', (logs) => { expectInLog(expect, logs, 'Instance "TEST_NAME" destroyed'); overcast('list', (logs) => { expectNotInLog(expect, logs, '(root@192.168.100.101:22)'); nextFn(); }); }); }); }); });
import { INIT } from 'state/actions'; import { getConnected, getWrapWidth } from 'state/app'; import { searchChannels } from 'state/channelSearch'; import { addMessages } from 'state/messages'; import { when } from 'utils/observe'; function loadState({ store }, env) { store.dispatch({ type: INIT, settings: env.settings, networks: env.networks, channels: env.channels, openDMs: env.openDMs, users: env.users, app: { connectDefaults: env.defaults, initialized: true, hexIP: env.hexIP, version: env.version } }); if (env.messages) { // Wait until wrapWidth gets initialized so that height calculations // only happen once for these messages when(store, getWrapWidth, () => { const { messages, network, to, next } = env.messages; store.dispatch(addMessages(messages, network, to, false, next)); }); } if (env.networks) { when(store, getConnected, () => // Cache top channels for each network env.networks.forEach(({ host }) => store.dispatch(searchChannels(host, '')) ) ); } } /* eslint-disable no-underscore-dangle */ export default async function initialState(ctx) { const env = await window.__init__; ctx.socket.connect(); loadState(ctx, env); }
var _ = require('src/util') var Vue = require('src') describe('el', function () { var el beforeEach(function () { el = document.createElement('div') spyWarns() }) it('normal', function (done) { var vm = new Vue({ el: el, data: { ok: true }, template: '<div v-if="ok" v-el:test-el id="test"></div>' }) expect(vm.$els.testEl).toBeTruthy() expect(vm.$els.testEl.id).toBe('test') vm.ok = false _.nextTick(function () { expect(vm.$els.testEl).toBeNull() vm.ok = true _.nextTick(function () { expect(vm.$els.testEl.id).toBe('test') done() }) }) }) it('inside v-for', function () { var vm = new Vue({ el: el, data: { items: [1, 2] }, template: '<div v-for="n in items"><p v-el:test>{{n}}</p>{{$els.test.textContent}}</div>' }) expect(vm.$el.textContent).toBe('1122') }) })
try { throw new Error(200, "x equals zero"); } catch (e) { document.write(e.message); }
'use strict'; var Q = require('q'), _ = require('underscore'), diacritic = require('diacritic').clean, purify = require('./purify'); module.exports = function($, url){ var esquemaRuta, esquemaSinTildes = [], infoPrincipal, ruta, titulo, id, horario, horas, q = Q.defer(); ruta = $('h1.pub').text(); infoPrincipal = $('#infoPrincipalNoticias').length; if(ruta){ if(infoPrincipal) { esquemaRuta = $('div.pub') .find('table').find('.azulBold').parent() .html(); } else { esquemaRuta = $('#texto_principal') .find('.azulBold').parent() .html(); } horario = $('#texto_principal') .children('table:last-child') .find('tr > td:last-child') .html(); ruta = purify(ruta); id = ruta.match(/R?r?uta( Nocturna| Urbana)? ([A-Z0-9]{1,5}):?/)[2]; esquemaRuta = purify(esquemaRuta).replace(/\sy\s/, ',').split(','); horas = purify(horario).match(/([0-9]{1,2}:[0-9]{2} a?p?\.m\.?) a ([0-9]{1,2}:[0-9]{2} a?p?\.m\.?)/g); horas = crearHorarios(horas); esquemaRuta = esquemaRuta.length > 1 ? esquemaRuta : null; _.each(esquemaRuta, function(ruta){ esquemaSinTildes.push(diacritic(ruta.toLowerCase().replace('.', ''))); }); q.resolve({ id_ruta: id, url: url, ruta: ruta.replace(': ', ' ').replace(':', ''), esquema: esquemaRuta, buscable: esquemaSinTildes, horario: horario }); } else { console.log('Error en ' + url); q.reject(false); } return q.promise; }; function crearHorarios (horas) { var horario; if(horas){ if(horas.length > 1){ horario = { lun_sab: horas[0].replace(/\sa\s/, ' - ').replace(/\./g, ''), dom_fes: horas[1].replace(/\sa\s/, ' - ').replace(/\./g, '') }; } else { horario = { lun_dom: horas[0].replace(/\sa\s/, ' - ').replace(/\./g, '') }; } } return horario; }
function alertClicked() { alert('You clicked the third ListGroupItem'); } render( <ListGroup defaultActiveKey="#link1"> <ListGroup.Item action href="#link1"> Link 1 </ListGroup.Item> <ListGroup.Item action href="#link2" disabled> Link 2 </ListGroup.Item> <ListGroup.Item action onClick={alertClicked}> This one is a button </ListGroup.Item> </ListGroup>, );
'use strict'; const OCLE = require('openchemlib-extended'); const chemcalc = require('chemcalc'); const mfUtil = require('../util/mf'); module.exports = function getMolecule(molecule) { const oclMol = OCLE.Molecule.fromMolfile(molecule.molfile); const oclID = oclMol.getIDCodeAndCoordinates(); const mfParts = oclMol.getMF().parts; const nbFragments = mfParts.length; const mf = mfParts.join('.'); const result = { _id: +molecule.PUBCHEM_COMPOUND_CID, seq: 0, ocl: { id: oclID.idCode, coordinates: oclID.coordinates, index: oclMol.getIndex() }, iupac: molecule.PUBCHEM_IUPAC_NAME, mf: mf, nbFragments }; try { const chemcalcMF = chemcalc.analyseMF(mf); result.em = chemcalcMF.em; result.mw = chemcalcMF.mw; result.unsaturation = chemcalcMF.unsaturation; result.charge = chemcalcMF.charge; result.atom = mfUtil.getAtoms(chemcalcMF); } catch (e) { console.log(e, mf); } return result; };
function isDefined(v) { return v !== undefined; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); } function attachSessionAndSpeakersTogether(session, speakersRaw) { if (isDefined(session.speakers)) { for (var speakerIdx = 0; speakerIdx < session.speakers.length; speakerIdx++) { if (isDefined(session.speakers[speakerIdx]) && !isDefined(session.speakers[speakerIdx].id)) { session.speakers[speakerIdx] = speakersRaw[session.speakers[speakerIdx]]; var tempSession = clone(session); delete tempSession.speakers; if (isDefined(session.speakers[speakerIdx])) { if (!isDefined(session.speakers[speakerIdx].sessions)) { session.speakers[speakerIdx].sessions = []; } session.speakers[speakerIdx].sessions.push(tempSession); } } } } } function getEndTime(date, startTime, endTime, totalNumber, number) { var timezone = new Date().toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1], timeStart = new Date(date + ' ' + startTime + ' ' + timezone).getTime(), timeEnd = new Date(date + ' ' + endTime + ' ' + timezone).getTime(), difference = Math.floor((timeEnd - timeStart) / totalNumber), result = new Date(timeStart + difference * number); return result.getHours() + ':' + result.getMinutes(); } function hasSpeakersAndSessionsAndSchedule(speakers, sessions, schedule) { return hasSpeakersAndSessions(speakers, sessions) && Object.keys(schedule).length ; } function hasSpeakersAndSessions(speakers, sessions) { return Object.keys(speakers).length && Object.keys(sessions).length; } function addTagTo(tag, tags) { if (tags.indexOf(tag) < 0) { tags.push(tag); } } self.addEventListener('message', function (e) { var speakers = e.data.speakers; var sessions = e.data.sessions; var days = e.data.schedule; var schedule = { days: days }; if (hasSpeakersAndSessionsAndSchedule(speakers, sessions, schedule.days)) { schedule.tags = []; for (var dayIdx = 0, scheduleLen = schedule.days.length; dayIdx < scheduleLen; dayIdx++) { var day = schedule.days[dayIdx]; day.tags = []; for (var timeSlotIdx = 0, timeslotsLen = day.timeslots.length; timeSlotIdx < timeslotsLen; timeSlotIdx++) { var timeslot = day.timeslots[timeSlotIdx]; for (var sessionIndex = 0, sessionsLen = timeslot.sessions.length; sessionIndex < sessionsLen; sessionIndex++) { for (var subSessIdx = 0, subSessionsLen = timeslot.sessions[sessionIndex].length; subSessIdx < subSessionsLen; subSessIdx++) { var session = sessions[timeslot.sessions[sessionIndex][subSessIdx]]; session.mainTag = session.tags ? session.tags[0] : 'General'; session.day = dayIdx + 1; addTagTo(session.mainTag, day.tags); addTagTo(session.mainTag, schedule.tags); if (!isDefined(session.track)) { // [temp fix] when we have 1 session and 1 workshop, to have correct location for workshop (not Stage 2) if (sessionsLen == 2 && sessionIndex == sessionsLen - 1) { session.track = day.tracks[day.tracks.length - 1]; } else { session.track = day.tracks[sessionIndex]; } } session.startTime = timeslot.startTime; session.endTime = subSessionsLen > 1 ? getEndTime(day.date, timeslot.startTime, timeslot.endTime, subSessionsLen, subSessIdx + 1) : timeslot.endTime; session.dateReadable = day.dateReadable; attachSessionAndSpeakersTogether(session, speakers); schedule.days[dayIdx].timeslots[timeSlotIdx].sessions[sessionIndex][subSessIdx] = session; } } } } } else if (hasSpeakersAndSessions(speakers, sessions)) { Object.keys(sessions).forEach(function(sessionId) { return attachSessionAndSpeakersTogether(sessions[sessionId], speakers) }); } self.postMessage({ speakers: speakers, sessions: sessions, schedule: Array.isArray(schedule.days) && Object.keys(sessions).length ? schedule : {} }); }, false);
function getParamFunc(getParam, setParam, obj){ return function(data, widthBaseParam){ if (isPlainObject(data)) { setParam(data, widthBaseParam); return obj; } else { return getParam(data, widthBaseParam); } }; } function getRunParamFunc(run, base, paramFunc){ extendDeep(paramFunc, base); extend(paramFunc, run); return paramFunc; } function setDisabledCall(funcData){ funcData.disabled = true; } function findFuncInList(func, list, callback){ forEach(list, function(funcData){ if (funcData.func === func) callback(funcData); }); } function returnFalseFunc(){ return false; } return function(defaultCall, _obj){ // obj 仅仅作为方法返回值及call apply作用域使用 无特殊作用 var _before = [], _after = [], _final = [], _baseParam = {}, _runParam = {}; function getList(stepName) { return stepName == 'after' ? _after : stepName == 'final' ? _final : _before; } function addEventListener(stepName, data, func){ if (!func) { func = data; data = {}; } if (!func) { func = stepName; stepName = ''; } var funcData = { data: data, func: func, disabled: false }; getList(stepName).push(funcData); return funcData; } function setParam(data, widthBaseParam){ if (widthBaseParam) extend(_baseParam, data); extend(_runParam, data); } function getParam(name, isBaseParam){ return isBaseParam ? _baseParam[name] : _runParam[name]; } function removeParam(name, widthBaseParam) { if (widthBaseParam) delete _baseParam[name]; delete _runParam[name]; } function on(){ addEventListener.apply(null, arguments); return _obj; } function off(stepName, func){ if (stepName && func) { findFuncInList(func, getList(stepName), setDisabledCall); } else if (stepName) { if (typeof(stepName) == 'function') { findFuncInList(stepName, _before, setDisabledCall); findFuncInList(stepName, _after, setDisabledCall); findFuncInList(stepName, _final, setDisabledCall); } else { forEach(getList(stepName), setDisabledCall); } } else { forEach(_before, setDisabledCall); forEach(_after, setDisabledCall); forEach(_final, setDisabledCall); } return _obj; } function once(){ var funcData = addEventListener.apply(null, arguments); addEventListener('final', function(){ funcData.disabled = true; }); } return { 'on': on, 'off': off, 'once': once, 'param': getParamFunc(getParam, setParam, _obj), 'removeParam': removeParam, 'trigger': function(){ if (defaultCall) return defaultCall.apply(_obj, arguments); }, 'emit': function(){ var args = toArray(arguments), defCall = defaultCall, curIndex, curFuncData, curList, isStop = false, isDefaultPrevented = false, runList = function(list, startIndex){ curList = list; for (curIndex = startIndex; !isStop && curIndex < list.length; curIndex++) { curFuncData = list[curIndex]; if (curFuncData.disabled) { list.splice(curIndex, 1); curIndex--; continue; } args[0] = new Event(); if ((EventProto['preReturn'] = curFuncData.func.apply(_obj, args)) === false) { isStop = true; return false; } if (isInAsync) return false; } return true; }, setDefReturn = function(defReturn){ EventProto['defReturn'] = defReturn; return true; }, isInAsync = false, hasRunAfter = false, runAfter = function(){ hasRunAfter = true; EventProto['preventDefault'] = returnFalseFunc; EventProto['overrideDefault'] = returnFalseFunc; // defaultCall run if (!isStop && !isDefaultPrevented) { EventProto['defReturn'] = EventProto['preReturn'] = defCall ? defCall.apply(_obj, arguments) : undefined; } EventProto['setDefReturn'] = setDefReturn; // after list run if (!isDefaultPrevented) runList(_after, 0); }, hasRunFinal = false, runFinal = function(){ // final list run isStop = false; // 为final 重置isStop runList(_final, 0); }, myRunParam = getRunParamFunc(_runParam, _baseParam, getParamFunc(getParam, setParam, _obj)), Event = function(){ this['data'] = curFuncData.data; }, EventProto = Event.prototype = { 'isDefaultPrevented': false, 'isDefaultOverrided': false, 'isInAsync': false, 'on': on, 'off': off, 'once': once, 'param': myRunParam, 'removeParam': removeParam, 'setDefReturn': returnFalseFunc, 'offSelf': function(){ curFuncData.disabled = true; }, 'next': function(){ // 调用next只可能返回两种值 true 和 false return runList(curList, ++curIndex); }, 'preventDefault': function(defReturn){ isDefaultPrevented = true; EventProto['isDefaultPrevented'] = true; EventProto['preventDefault'] = EventProto['setDefReturn'] = setDefReturn; EventProto['overrideDefault'] = returnFalseFunc; return setDefReturn(defReturn); }, 'overrideDefault': function(newDefaultReturn){ defCall = newDefaultReturn; EventProto['isDefaultOverrided'] = true; EventProto['setDefReturn'] = setDefReturn; return true; }, 'async': function(){ isInAsync = true; EventProto['isInAsync'] = true; return function(){ if (isInAsync) { isInAsync = false; EventProto['isInAsync'] = false; runList(curList, ++curIndex); if (!hasRunAfter) runAfter(); if (!hasRunFinal) runFinal(); } if (!isInAsync) return EventProto['defReturn']; }; } }; _runParam = {}; // 清空 防止影响到内部的嵌套调用 args.unshift(null); // Event placeholder // before list run runList(_before, 0); if (!isInAsync) runAfter(); if (!isInAsync) runFinal(); if (!isInAsync) return EventProto['defReturn']; } }; };
'use strict' var test = require('test-runner') var jsdoc = require('../') var Fixture = require('./lib/fixture') var path = require('path') var fs = require('then-fs') var a = require('core-assert') if (require('child_process').spawnSync) { test('.explainSync({ files, cache: true })', function () { var f = new Fixture('class-all') jsdoc.cache.dir = 'tmp/cache-sync' jsdoc.cache.clear() var output = jsdoc.explainSync({ files: f.sourcePath, cache: true }) var expectedOutput = f.getExpectedOutput(output) a.ok(typeof output === 'object') a.deepEqual(output, expectedOutput) }) } test('.explain({ files, cache: true })', function () { var f = new Fixture('class-all') jsdoc.cache.dir = 'tmp/cache' jsdoc.cache.clear() return jsdoc.explain({ files: f.sourcePath, cache: true }) .then(function (output) { var cachedFiles = fs.readdirSync(jsdoc.cache.dir) .map(function (file) { return path.resolve(jsdoc.cache.dir, file) }) a.strictEqual(cachedFiles.length, 1) a.deepEqual(output, f.getExpectedOutput(output)) var cachedData = JSON.parse(fs.readFileSync(cachedFiles[0], 'utf8')) Fixture.removeFileSpecificData(cachedData) a.deepEqual( cachedData, f.getExpectedOutput(output) ) }) .catch(function (err) { console.error(err.stack) }) })
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var DeviceSignalCellular0Bar = React.createClass({ displayName: 'DeviceSignalCellular0Bar', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { 'fillOpacity': '.3', d: 'M2 22h20V2z' }) ); } }); module.exports = DeviceSignalCellular0Bar;
// For more information about this template visit http://aka.ms/azurebots-node-qnamaker "use strict"; var builder = require("botbuilder"); var botbuilder_azure = require("botbuilder-azure"); var builder_cognitiveservices = require("botbuilder-cognitiveservices"); var path = require('path'); var utils = require('./utils'); var useEmulator = (process.env.NODE_ENV == 'development'); var connector = useEmulator ? new builder.ChatConnector() : new botbuilder_azure.BotServiceConnector({ appId: process.env['MicrosoftAppId'], appPassword: process.env['MicrosoftAppPassword'], stateEndpoint: process.env['BotStateEndpoint'], openIdMetadata: process.env['BotOpenIdMetadata'] }); var bot = new builder.UniversalBot(connector); bot.localePath(path.join(__dirname, './locale')); var sessionSaved; var isDay = false; var whatIKnow = "\n * Konta" + "\n * Karty płatnicze \n" + "\n\n Podczas kolejnego spotkania odpowiem także na pytania o:" + "\n\n * Kredyty" + "\n * Bankowość internetowa" + "\n * Bankowość mobilna" + "\n * Kredyty i pożyczki hipoteczne w CHF \n" + "\n\n A w przyszłości na każde zadane pytanie oraz wykonam wiele akcji za Ciebie automatycznie!"; var callQNA = function() { basicQnAMakerDialog.replyReceived(sessionSaved, null, true); } var redirectToConsultant = function(session) { session.send("Rozumiem. W tym temacie pomoże Ci wyspecjalizowany doradca. Łaczę.."); } var storeNumberForConsultent = function (session) { session.beginDialog('/storeNumberForConsultent'); } var recognizer = new builder_cognitiveservices.QnAMakerRecognizer({ knowledgeBaseId: process.env.QnAKnowledgebaseId, subscriptionKey: process.env.QnASubscriptionKey, top: 3}); var qnaMakerTools = new builder_cognitiveservices.QnAMakerTools(); bot.library(qnaMakerTools.createLibrary()); var basicQnAMakerDialog = new builder_cognitiveservices.QnAMakerDialog({ recognizers: [recognizer], defaultMessage: 'Już niedługo odpowiem na to pytanie! Póki co, spróbuj czegoś innego.', qnaThreshold: 0.3, feedbackLib: qnaMakerTools, errorCallback: function (session, error, noFeedback) { if (noFeedback) { var msg = new builder.Message(session); msg.attachments([ new builder.HeroCard(session) .title("Jeśli chodzi o Twoje pierwotne pytanie: '" + session.message.text + "', odpowie na nie nasz doradca.") .buttons([ builder.CardAction.openUrl(session, "https://microsoft.com", "Skontaktuj się z doradcą"), builder.CardAction.openUrl(session, "https://microsoft.com", "Odwiedź naszą stronę") ]) ]); session.send(msg); } else { sessionSaved = session; session.send('System w tej chwili wyszukuje informacje na ten temat..'); session.endDialog(); session.beginDialog('/feedback'); } }, noMatchCallback: function (session) { if (!isDay) { session.endDialog(); storeNumberForConsultent(session); } else { redirectToConsultant(session); session.endDialog(); } } }); bot.on('contactRelationUpdate', function (message) { if (message.action === 'add') { var name = message.user ? message.user.name : null; var reply = new builder.Message() .address(message.address) .text("Dzień dobry %s, nazywam się Bezek. Będąc supernowoczesnym doradcą jestem w stanie odpowiedzieć na Twoje pytania z zakresu: " + whatIKnow, name || ''); bot.send(reply); } else { // delete their data } }); bot.on('conversationUpdate', function (message) { if (message.membersAdded.length) { if (!utils.botEntered(message)) { bot.send(new builder.Message() .address(message.address) .text("Witaj! Chętnie, udzielę Ci informacji z zakresu: " + whatIKnow)) } } // message.source // session.sendTyping(); }); bot.dialog('/storeNumberForConsultent', [ function (session, args, next) { builder.Prompts.text(session, "Temat tego typu wymaga głębszej analizy. Skontaktujemy się z Panem." + " Proszę o podanie numeru telefonu lub adresu email."); next(); }, function(session, results) { session.send('Dziękuję.'); session.send('Możesz także skorzystać z usług konsultanta online klikając **TUTAJ**'); session.endDialog(); }] // function(session, results) { // session.send('Dziękuję.'); // session.send('Nadal jestem do Pańskiej dyspozycji w tematach: ' + whatIKnow + ', proszę pytać.'); // session.endDialog(); // }] ); bot.dialog('/feedback', [ function (session, args, next) { builder.Prompts.text(session, 'W międzyczasie, powiedz nam, jakie usługi mają Twoi znajomi, a nie masz Ty?'); var msg = new builder.Message(session); msg.attachments([ new builder.HeroCard(session) .buttons([ builder.CardAction.openUrl(session, "https://microsoft.com", "Niczego mi nie brakuje, jestem zadowolonym klientem.") ]) ]); session.send(msg); next(); }, function(session, results) { session.send('Dziękujemy, za informację'); session.endDialog(); callQNA(); } ]); bot.dialog('/', basicQnAMakerDialog); if (useEmulator) { var restify = require('restify'); var server = restify.createServer(); server.listen(3978, function() { console.log('test bot endpont at http://localhost:3978/api/messages'); }); server.post('/api/messages', connector.listen()); } else { module.exports = { default: connector.listen() } } // var msg = new builder.Message(session) // .text("W tej chwili nie mogę odpowiedzieć na to ") // .suggestedActions( // builder.SuggestedActions.create( // session, [ // builder.CardAction.openUrl(session, "http://microsoft.com", "Odpowiedź znajdziesz tutaj"), // builder.CardAction.call(session, "555 12 33", "Zadzwoń do konsultanta") // ] // ));
import testSettingList from '../samples/chart-config/testSettingList'; import { readFile, readFileSync } from 'fs'; import d3 from 'd3'; import { merge } from 'd3'; import jsdom from 'jsdom'; import webcharts from '../../build/webcharts'; import expect from 'expect'; import testCreateChart from '../chart/createChart'; import testRendering from '../chart/rendering'; var settingsList = []; var numLoaded = 0; var testSettingList_charts = testSettingList.filter(function(d) { return d.type == 'charts'; }); testSettingList_charts.forEach(function(d) { var path = require('path'); var jsonPath = path.join(__dirname, '..', 'samples', 'chart-config', d.filename); var jsonRaw = readFileSync(jsonPath, 'utf8'); var jsonData = JSON.parse(jsonRaw); settingsList = merge([settingsList, jsonData]); numLoaded = numLoaded + 1; if (numLoaded == testSettingList_charts.length) runTests(settingsList); //if (numLoaded == 1) runTests(settingsList); }); function runTests(settingsList) { it('run tests once for each settings object', done => { settingsList.forEach((settings, i) => { const dataFile = `./test/samples/data/${settings.filename}`, raw = readFileSync(dataFile, 'utf8'), data = d3.csv.parse(raw); describe(`Chart Test ${i + 1} of ${settingsList.length}: ${settings.label}. `, () => { describe('Create Chart. ', () => { testCreateChart(settings.settings, false); }); describe('Render Chart. ', () => { testRendering(settings.settings, data, false); }); }); }); done(); }); }
import Article from '../models/article'; import moment from 'moment'; export const query = async function() { const filter = { enabled: true, deleted: false }; const articles = await Article.find(filter).select('title createTime viewCount commentCount'); const map = new Map(); articles.forEach(article => { const cloneArticle = article._doc; cloneArticle.id = cloneArticle._id; delete cloneArticle._id; const date = moment(cloneArticle.createTime).format('YYYY-MM'); if (!map.has(date)) { map.set(date, [cloneArticle]); } else { let archives = map.get(date); archives.push(cloneArticle); map.set(date, archives); } }); const result = []; map.forEach((value, key) => { result.push({ date: key, articles: value }); }); return result; }; export const queryCount = async function() { const filter = { enabled: true, deleted: false }; const items = await Article.find(filter).select('createTime'); const map = new Map(); items.forEach(item => { const date = moment(item.createTime).format('YYYY-MM'); if (!map.has(date)) { map.set(date, 1); } else { let count = map.get(date); count++; map.set(date, count); } }); const result = []; map.forEach((value, key) => { result.push({ date: key, count: value }); }); return result; };
var trigger = require('trigger-event'); /** * Expose `submitForm`. */ module.exports = submitForm; /** * Submit a `form` programmatically, triggering submit handlers. * * @param {Element} form */ function submitForm (form) { var button = document.createElement('button'); button.style.display = 'none'; form.appendChild(button); trigger(button, 'click'); form.removeChild(button); }
const users = require('./users/users.service.js'); const experiments = require('./experiments/experiments.service.js'); const participations = require('./participations/participations.service.js'); module.exports = function () { const app = this; // eslint-disable-line no-unused-vars app.configure(users); app.configure(experiments); app.configure(participations); };
var searchData= [ ['variable',['Variable',['../structvku_1_1_shader_module_1_1_variable.html',1,'vku::ShaderModule']]], ['vertexbuffer',['VertexBuffer',['../classvku_1_1_vertex_buffer.html',1,'vku']]] ];
(function() { require.config({ paths: { 'jquery': '../bower_components/jquery/jquery', 'angular': '../bower_components/angular/angular', 'angular-resource': '../bower_components/angular-resource/angular-resource', 'angular-translate':'../bower_components/angular-translate/angular-translate', 'angular-translate-loader-static-files':'../bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files', 'angular-mocks': '../bower_components/angular-mocks/angular-mocks', 'angularui': '../bower_components/angular-bootstrap/ui-bootstrap', 'angularuitpls': '../bower_components/angular-bootstrap/ui-bootstrap-tpls', 'underscore': '../bower_components/underscore/underscore', 'webstorage': '../bower_components/angular-webstorage/angular-webstorage', 'require-css': '../bower_components/require-css/css', 'd3': '../bower_components/d3/d3', 'nvd3': '../bower_components/nvd3/nv.d3', 'nvd3ChartDirectives':'../scripts/modules/angularjs-nvd3-directives', 'styles': '../styles', 'test': '../test/functional', 'notificationWidget':'../scripts/modules/notificationWidget', 'configurations':'../scripts/modules/configurations', 'angularFileUpload':'../bower_components/angularjs-file-upload/angular-file-upload', 'angularFileUploadShim':'../bower_components/angularjs-file-upload/angular-file-upload-shim', 'ngSanitize': '../bower_components/angular-sanitize/angular-sanitize', 'ckEditor': '../bower_components/ckeditor/ckeditor', 'LocalStorageModule':'../scripts/modules/localstorage', 'ngCsv': "../scripts/modules/csv", 'chosen.jquery.min': "../scripts/modules/chosen.jquery.min", 'frAngular': '../scripts/modules/KeyboardManager', 'modified.datepicker':'../scripts/modules/datepicker', 'ionic': '../bower_components/ionic/ionic.min', 'ionic-angular': '../bower_components/ionic/ionic-angular.min' }, shim: { 'angular': { exports: 'angular' }, 'ionic-angular': { deps: ['ionic'], exports: 'ionic-angular' }, 'angular-resource': { deps: ['angular'] }, 'angular-translate': { deps: ['angular'] }, 'angular-translate-loader-static-files': {deps: ['angular' , 'angular-translate'] }, 'angularui': { deps: ['angular'] }, 'angularuitpls': { deps: ['angular' ,'angularui' ] }, 'angular-mocks': { deps: ['angular'] }, 'ngSanitize':{deps:['angular'],exports:'ngSanitize'}, 'webstorage': { deps: ['angular'] }, 'd3': {exports: 'd3'}, 'nvd3': { deps: ['d3']}, 'nvd3ChartDirectives': {deps: ['angular','nvd3']}, 'configurations':{deps: ['angular']}, 'notificationWidget':{deps: ['angular','jquery'],exports:'notificationWidget'}, 'angularFileUpload':{deps: ['angular','jquery','angularFileUploadShim'],exports:'angularFileUpload'}, 'ckEditor':{deps:['jquery']}, 'LocalStorageModule':{deps:['angular']}, 'ngCsv':{deps:['angular']}, 'chosen.jquery.min':{deps:['jquery']}, 'frAngular':{deps:['angular']}, 'modified.datepicker':{deps: ['angular']}, 'mifosX': { deps: [ 'angular', 'jquery', 'angular-resource', 'angular-translate', 'angular-translate-loader-static-files', 'angularui', 'angularuitpls', 'webstorage', 'nvd3ChartDirectives', 'notificationWidget', 'angularFileUpload', 'modified.datepicker', 'ngSanitize', 'ckEditor', 'configurations', 'LocalStorageModule', 'angularFileUploadShim', 'ngCsv', 'chosen.jquery.min', 'frAngular', 'ionic', 'ionic-angular' ], exports: 'mifosX' } }, packages: [ { name: 'css', location: '../bower_components/require-css', main: 'css' } ] }); require(['mifosXComponents', 'mifosXStyles'], function() { require(['test/testInitializer'], function(testMode) { if (!testMode) { angular.bootstrap(document, ['MifosX_Application']); } }); }); }());
const func = require('../../src/_utils/kmp'); const assert = require('assert'); describe('kmp', function () { describe('#kmp()', function () { it('should return [0,1] then text is AAAAABAAABA and pattern is AAAA', function () { let ret = func('AAAAABAAABA', 'AAAA', false); assert.deepEqual(ret, [0, 1]); }); it('should return [0] then text is AAAAABAAABA and pattern is AAAA and onlyFirst is true', function () { let ret = func('AAAAABAAABA', 'AAAA', true); assert.deepEqual(ret, [0]); }); }); });
import './forms/smallFeedBack.js'; import './forms/feedBack.js';
import actions from '../../app/actions/'; import chai from 'chai'; import thunk from 'redux-thunk'; const assert = chai.assert, expect = chai.expect; let testedActions = 0; module.exports = () => { describe("Script actions", () => { describe("loadScript", () => { it("should return a function", () => { let res = actions.scripts.loadScript(__dirname + '/scripts/ValidSyntax.js'); assert(typeof res, 'function'); }); }); describe("refreshScript", () => { it("should return a function", () => { let res = actions.scripts.refreshScript(__dirname + '/scripts/ValidSyntax.js'); assert(typeof res, 'function'); }); }); beforeEach(() => { testedActions++; }) describe("loadScriptSuccess", () => { it("should return the correct action", () => { let scriptPath = __dirname + '/scripts/ValidSyntax.js' let expected = { type: 'LOAD_SCRIPT_SUCCESSFUL', src: scriptPath, content: 'console.log("Hey guys");', name: 'Test', validated: false }; let result = actions.scripts.loadScriptSuccess(scriptPath, 'console.log("Hey guys");', 'Test', false); expect(result).to.deep.equal(expected); }); }); describe("loadScriptUnsuccess", () => { it("should return the correct action", () => { let scriptPath = __dirname + '/does/not/exist.js'; let expected = { type: 'LOAD_SCRIPT_UNSUCCESSFUL', src: scriptPath, name: 'Test', error: new Error('ENOENT: File not found'), }; let result = actions.scripts.loadScriptUnsuccess(scriptPath, 'Test', new Error('ENOENT: File not found')) expect(result).to.deep.equal(expected); }); }); describe("addLog", () => { it("should return the correct action", () => { let scriptPath = __dirname + '/some/path.js'; let expected = { type: 'ADD_SCRIPT_LOG', src: scriptPath, log: 'Message text.' }; let result = actions.scripts.addLog(scriptPath, 'Message text.'); expect(result).to.deep.equal(expected); }); }); describe("log", () => { it("should return a function", () => { let scriptPath = __dirname + '/some/path.js'; let func = actions.scripts.log(scriptPath, 'Message text.'); assert(typeof func === 'function', true); }); }); describe("loadScriptPending", () => { it("should return the correct action", () => { let scriptPath = __dirname + '/some/path.js'; let expected = { type: 'LOAD_SCRIPT_PENDING', src: scriptPath, status: 'Pending', name: 'Test' }; let result = actions.scripts.loadScriptPending(scriptPath, 'Test', 'Pending'); expect(result).to.deep.equal(expected); }); }); describe("refreshScriptPending", () => { it("should return the correct action", () => { let scriptPath = __dirname + '/some/path.js'; let expected = { type: 'REFRESH_SCRIPT_PENDING', name: 'Test', src: scriptPath, status: 'Pending' }; let result = actions.scripts.refreshScriptPending(scriptPath,'Test', 'Pending'); expect(result).to.deep.equal(expected); }); }); describe("refreshScriptSuccess", () => { it("should return the correct action", () => { let expected = { type: 'REFRESH_SCRIPT_SUCCESSFUL', src: 'Some/src', validated: false, name: 'name', content: 'some code' } let result = actions.scripts.refreshScriptSuccess('Some/src', 'name', 'some code', false); expect(result).to.deep.equal(expected); }); }); describe("refreshScriptUnsuccess", () => { it("should return the correct action", () => { let expected = { type: 'REFRESH_SCRIPT_UNSUCCESSFUL', src: 'Some/src', error: new Error('Some error'), name: 'name', } let result = actions.scripts.refreshScriptUnsuccess('Some/src', 'name', new Error('Some error')); expect(result).to.deep.equal(expected); }); }); describe("toggleScript", () => { it("should return the correct action", () => { let expected = { type: 'TOGGLE_SCRIPT', src: 'Some/src', } let result = actions.scripts.toggleScript('Some/src'); expect(result).to.deep.equal(expected); }); }); describe("removeScript", () => { it("should return the correct action", () => { let expected = { type: 'REMOVE_SCRIPT', src: 'Some/src', } let result = actions.scripts.removeScript('Some/src'); expect(result).to.deep.equal(expected); }); }); describe("All script actions", () => { it("should be tested", () => { let actual = Object.keys(actions.scripts).length; assert(actual === testedActions, (actual-testedActions) + ' actions in app/actions/scripts has not been tested'); }); }); }); }
import Ember from 'ember'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import {module, test} from 'qunit'; import DS from 'ember-data'; const run = Ember.run; const Application = Ember.Application; const Controller = Ember.Controller; const Store = DS.Store; const Namespace = Ember.Namespace; let app, App, container; /* These tests ensure that Ember Data works with Ember.js' application initialization and dependency injection APIs. */ function getStore() { return lookup('service:store'); } function lookup(thing) { return run(container, 'lookup', thing); } module("integration/application - Injecting a Custom Store", { beforeEach() { run(() => { app = Application.create({ StoreService: Store.extend({ isCustom: true }), FooController: Controller.extend(), BazController: {}, ApplicationController: Controller.extend(), rootElement: '#qunit-fixture' }); }); container = app.__container__; }, afterEach() { run(app, app.destroy); Ember.BOOTED = false; } }); test("If a Store property exists on an Ember.Application, it should be instantiated.", function(assert) { run(() => { assert.ok(getStore().get('isCustom'), "the custom store was instantiated"); }); }); test("If a store is instantiated, it should be made available to each controller.", function(assert) { let fooController = lookup('controller:foo'); let isCustom = run(fooController, 'get', 'store.isCustom'); assert.ok(isCustom, "the custom store was injected"); }); test("The JSONAPIAdapter is the default adapter when no custom adapter is provided", function(assert) { run(() => { let store = getStore(); let adapter = store.adapterFor('application'); assert.ok(adapter instanceof DS.JSONAPIAdapter, 'default adapter should be the JSONAPIAdapter'); }); }); module("integration/application - Injecting the Default Store", { beforeEach() { run(() => { app = Application.create({ FooController: Controller.extend(), BazController: {}, ApplicationController: Controller.extend() }); }); container = app.__container__; }, afterEach() { run(app, 'destroy'); Ember.BOOTED = false; } }); test("If a Store property exists on an Ember.Application, it should be instantiated.", function(assert) { assert.ok(getStore() instanceof DS.Store, "the store was instantiated"); }); test("If a store is instantiated, it should be made available to each controller.", function(assert) { run(() => { let fooController = lookup('controller:foo'); assert.ok(fooController.get('store') instanceof DS.Store, "the store was injected"); }); }); test("the DS namespace should be accessible", function(assert) { run(() => { assert.ok(Namespace.byName('DS') instanceof Namespace, "the DS namespace is accessible"); }); }); if (Ember.inject && Ember.inject.service) { module("integration/application - Using the store as a service", { beforeEach() { run(() => { app = Application.create({ DoodleService: Ember.Service.extend({ store: Ember.inject.service() }) }); }); container = app.__container__; }, afterEach() { run(app, 'destroy'); Ember.BOOTED = false; } }); test("The store can be injected as a service", function(assert) { run(() => { let doodleService = lookup('service:doodle'); assert.ok(doodleService.get('store') instanceof Store, "the store can be used as a service"); }); }); } module("integration/application - Attaching initializer", { beforeEach() { App = Application.extend(); }, afterEach() { if (app) { run(app, app.destroy); } Ember.BOOTED = false; } }); test("ember-data initializer is run", function(assert) { let ran = false; App.initializer({ name: "after-ember-data", after: "ember-data", initialize() { ran = true; } }); run(() => { app = App.create(); }); assert.ok(ran, 'ember-data initializer was found'); }); test("ember-data initializer does not register the store service when it was already registered", function(assert) { let AppStore = Store.extend({ isCustomStore: true }); App.initializer({ name: "after-ember-data", before: "ember-data", initialize(registry) { registry.register('service:store', AppStore); } }); run(() => { app = App.create(); container = app.__container__; }); let store = getStore(); assert.ok(store && store.get('isCustomStore'), 'ember-data initializer does not overwrite the previous registered service store'); }); testInDebug("store initializer is run (DEPRECATED)", function(assert) { let ran = false; App.initializer({ name: "after-store", after: 'store', initialize() { ran = true; } }); assert.expectDeprecation(() => { run(() => { app = App.create(); }); }, /The initializer `store` has been deprecated/) assert.ok(ran, 'store initializer was found'); }); testInDebug("injectStore initializer is run (DEPRECATED)", function(assert) { let ran = false; App.initializer({ name: "after-store", after: 'injectStore', initialize() { ran = true; } }); assert.expectDeprecation(() => { run(() => { app = App.create(); }); }, /The initializer `injectStore` has been deprecated/) assert.ok(ran, 'injectStore initializer was found'); }); testInDebug("transforms initializer is run (DEPRECATED)", function(assert) { let ran = false; App.initializer({ name: "after-store", after: 'transforms', initialize() { ran = true; } }); assert.expectDeprecation(() => { run(() => { app = App.create(); }); }, /The initializer `transforms` has been deprecated/) assert.ok(ran, 'transforms initializer was found'); });
var myObject = { myValue: 123, getMyValue: function(prefix, suffix) { return [prefix, this.myValue, suffix].join(" "); } }; var otherObject = { myValue: 456 }; var test = myObject.getMyValue; var myArgs = ["<!--", "-->"]; console.log(test.apply(myObject, myArgs)); // <!-- 123 --> console.log(test.apply(otherObject, myArgs)); // <!-- 456 -->
var $M = require("@effectful/debugger"), $iterator = $M.iterator, $yld = $M.yld, $awt = $M.awt, $iterErr = $M.iterErr, $iterFin = $M.iterFin, $iterNext = $M.iterNext, $x = $M.context, $ret = $M.ret, $retA = $M.retA, $retG = $M.retG, $unhandled = $M.unhandled, $unhandledA = $M.unhandledA, $unhandledG = $M.unhandledG, $raise = $M.raise, $brk = $M.brk, $mcall = $M.mcall, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ a: [1, "12:10-12:11"], b: [2, "17:10-17:11"], c: [3, "26:10-26:11"], d: [4, "37:10-37:11"], af1: [5, "44:15-44:18"], b2: [6, "51:10-51:12"], af2: [7, "60:15-60:18"] }, null, 0], $s$2 = [{}, $s$1, 1], $s$3 = [{}, $s$1, 1], $s$4 = [{ e: [1, "21:11-21:12"] }, $s$3, 1], $s$5 = [{}, $s$1, 1], $s$6 = [{ e: [1, "30:11-30:12"] }, $s$5, 1], $s$7 = [{}, $s$1, 1], $s$8 = [{ i: [1, "38:13-38:14"] }, $s$7, 1], $s$9 = [{}, $s$1, 1], $s$10 = [{}, $s$1, 1], $s$11 = [{ e: [1, "55:11-55:12"] }, $s$10, 1], $s$12 = [{}, $s$1, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 8, "1:0-64:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $l[2] = $m$2($); $l[3] = $m$3($); $l[4] = $m$4($); $l[5] = $m$5($); $l[6] = $m$6($); $l[7] = $m$7($); $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; $mcall("profile", M, "disabled"); $.state = 2; case 2: $.goto = 3; $brk(); $.state = 3; case 3: $.goto = 4; $mcall("profile", M, "generators"); $.state = 4; case 4: $.goto = 5; $brk(); $.state = 5; case 5: $.goto = 6; $mcall("option", M, { defunct: true, state: false, contextState: true, markRepeat: false, inlineContAssign: true, storeCont: "$cont" }); $.state = 6; case 6: $.goto = 7; $brk(); $.state = 7; case 7: $.goto = 9; $mcall("option", M, { tailCalls: false }); continue; case 8: $.goto = 9; return $unhandled($.error); case 9: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[4, "1:0-1:22", $s$1], [2, "1:0-1:21", $s$1], [4, "2:0-2:24", $s$1], [2, "2:0-2:23", $s$1], [4, "3:0-10:3", $s$1], [2, "3:0-10:2", $s$1], [4, "49:0-49:31", $s$1], [2, "49:0-49:30", $s$1], [16, "64:0-64:0", $s$1], [16, "64:0-64:0", $s$1]]), $m$1 = $M.fun("m$1", "a", null, $m$0, [], 0, 1, "12:0-15:1", 2, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $yld(1); case 2: $.goto = 3; $brk(); $.state = 3; case 3: $.goto = 4; return $yld(2); case 4: $.goto = 6; $brk(); continue; case 5: $.goto = 6; return $unhandledG($.error); case 6: return $retG($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "13:2-13:10", $s$2], [2, "13:2-13:9", $s$2], [4, "14:2-14:10", $s$2], [2, "14:2-14:9", $s$2], [36, "15:1-15:1", $s$2], [16, "15:1-15:1", $s$2], [16, "15:1-15:1", $s$2]]), $m$2 = $M.fun("m$2", "b", null, $m$0, [], 0, 2, "17:0-24:1", 2, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $yld(1); case 2: $.goto = 3; $brk(); $.state = 3; case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; return $yld(2); case 5: $.goto = 6; $brk(); $.state = 6; case 6: $.goto = 11; $brk(); continue; case 7: $l[1] = $.error; $.error = void 0; $.goto = 8; $brk(); $.state = 8; case 8: $.goto = 9; return $yld($l[1]); case 9: $.goto = 6; $brk(); continue; case 10: $.goto = 11; return $unhandledG($.error); case 11: return $retG($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 5: case 4: case 3: $.goto = 7; break; default: $.goto = 10; } }, null, 1, [[4, "18:2-18:10", $s$3], [2, "18:2-18:9", $s$3], [4, "19:2-23:3", $s$3], [5, "20:4-20:12", $s$3], [3, "20:4-20:11", $s$3], [37, "21:3-21:3", $s$3], [36, "24:1-24:1", $s$3], [4, "22:4-22:12", $s$4], [2, "22:4-22:11", $s$4], [36, "23:3-23:3", $s$3], [16, "24:1-24:1", $s$3], [16, "24:1-24:1", $s$3]]), $m$3 = $M.fun("m$3", "c", null, $m$0, [], 0, 4, "26:0-35:1", 2, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $yld(1); case 2: $.goto = 3; $brk(); $.state = 3; case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; return $yld(2); case 5: $l[2] = 14; $.goto = 10; $brk(); continue; case 6: $l[1] = $.error; $.error = void 0; $.goto = 7; $brk(); $.state = 7; case 7: $.goto = 8; return $yld($l[1]); case 8: $l[2] = 14; $.goto = 10; $brk(); continue; case 9: return $raise($l[3]); case 10: $.goto = 11; $brk(); $.state = 11; case 11: $.goto = 12; return $yld("F"); case 12: $.goto = 13; $brk(); $.state = 13; case 13: $.goto = $l[2]; continue; case 14: $.goto = 16; $brk(); continue; case 15: $.goto = 16; return $unhandledG($.error); case 16: return $retG($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 8: case 7: case 6: $.goto = 10; $l[2] = 9; $l[3] = $.error; break; case 5: case 4: case 3: $.goto = 6; break; default: $.goto = 15; } }, function ($, $l) { switch ($.state) { case 8: case 7: case 6: case 5: case 4: case 3: $l[2] = 16; $.goto = 10; break; default: $.goto = 16; break; } }, 1, [[4, "27:2-27:10", $s$5], [2, "27:2-27:9", $s$5], [4, "28:2-34:3", $s$5], [5, "29:4-29:12", $s$5], [3, "29:4-29:11", $s$5], [37, "30:3-30:3", $s$5], [4, "31:4-31:12", $s$6], [2, "31:4-31:11", $s$6], [36, "32:3-32:3", $s$5], [0, null, $s$5], [4, "33:4-33:14", $s$5], [2, "33:4-33:13", $s$5], [36, "34:3-34:3", $s$5], [0, null, $s$5], [36, "35:1-35:1", $s$5], [16, "35:1-35:1", $s$5], [16, "35:1-35:1", $s$5]]), $m$4 = $M.fun("m$4", "d", null, $m$0, [], 0, 7, "37:0-42:1", 2, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; $p = $iterator(s); $.state = 2; case 2: $l[4] = $p; $.state = 3; case 3: $.goto = 4; $brk(); $.state = 4; case 4: $x.call = $l[4].next; $.goto = 5; $p = $l[4].next(); $.state = 5; case 5: if ($p.done) { $.state = 6; } else { $.goto = 8; continue; } case 6: $.state = 7; case 7: $.goto = 33; $brk(); continue; case 8: $l[1] = $p.value; $.goto = 9; $brk(); $.state = 9; case 9: $.goto = 10; $p = $iterator([$l[1]]); $.state = 10; case 10: $l[5] = $p; $.state = 11; case 11: $.goto = 12; $p = $iterNext($l[5], $l[6]); $.state = 12; case 12: $l[6] = $p; $.state = 13; case 13: if ($l[6].done) { $.state = 14; } else { $.goto = 17; continue; } case 14: $.goto = 15; $brk(); $.state = 15; case 15: $.goto = 16; return $yld($l[1]); case 16: $.goto = 3; $brk(); continue; case 17: $.goto = 18; return $yld($l[6].value); case 18: $l[6] = $p; $.goto = 11; continue; case 19: if ($l[5].throw) { $.state = 20; } else { $.goto = 22; continue; } case 20: $.goto = 21; $p = $iterErr($l[5], $.error); $.state = 21; case 21: $l[6] = $p; $.goto = 13; continue; case 22: $.error = $M.iterErrUndef(); $l[3] = 30; $l[2] = 32; $.goto = 24; continue; case 23: return $raise($.error); case 24: $.goto = 25; $p = $iterFin($l[5], $.result); $.state = 25; case 25: if ($p.done) { $.state = 26; } else { $.goto = 27; continue; } case 26: $.goto = $l[3]; continue; case 27: $.goto = 28; return $yld($p.value); case 28: $l[6] = $p; $.goto = 11; continue; case 29: return $raise($.error); case 30: $.goto = 31; $iterFin($l[4]); $.state = 31; case 31: $.goto = $l[2]; continue; case 32: $.goto = 33; return $unhandledG($.error); case 33: return $retG($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 28: case 27: case 26: case 25: case 24: case 23: case 21: case 20: case 16: case 15: case 14: case 10: case 9: case 8: case 6: case 5: case 4: case 3: $.goto = 30; $l[2] = 29; break; case 22: case 19: case 12: case 11: $.goto = 24; $l[3] = 23; break; case 18: case 17: case 13: $.goto = 19; break; default: $.goto = 32; } }, function ($, $l) { switch ($.state) { case 28: case 27: case 26: case 25: case 24: case 23: case 21: case 20: case 16: case 15: case 14: case 10: case 9: case 8: case 6: case 5: case 4: case 3: $l[2] = 33; $.goto = 30; break; case 22: case 19: case 18: case 17: case 13: case 12: case 11: $l[3] = 30; $l[2] = 33; $.goto = 24; break; default: $.goto = 33; break; } }, 1, [[4, "38:2-41:3", $s$7], [2, "38:18-38:19", $s$8], [0, null, $s$7], [4, "38:13-38:14", $s$8], [2, "38:18-38:19", $s$8], [0, null, $s$7], [0, null, $s$7], [36, "42:1-42:1", $s$7], [4, "39:4-39:15", $s$8], [2, "39:4-39:14", $s$8], [0, null, $s$7], [2, "39:4-39:14", $s$8], [0, null, $s$7], [0, null, $s$7], [4, "40:4-40:12", $s$8], [2, "40:4-40:11", $s$8], [36, "41:3-41:3", $s$7], [2, "39:4-39:14", $s$8], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [0, null, $s$7], [2, "39:4-39:14", $s$8], [0, null, $s$7], [0, null, $s$7], [2, "38:18-38:19", $s$8], [0, null, $s$7], [16, "42:1-42:1", $s$7], [16, "42:1-42:1", $s$7]]), $m$5 = $M.fun("m$5", "af1", null, $m$0, [], 0, 1, "44:0-47:1", 1, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $awt($l[0][1]); case 2: if ($p) { $.state = 3; } else { $.goto = 5; continue; } case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; return $awt($l[0][2]); case 5: $.goto = 6; $brk(); $.state = 6; case 6: $.goto = 7; return $awt($l[0][3]); case 7: $.result = $p; $.goto = 9; continue; case 8: $.goto = 9; return $unhandledA($.error); case 9: return $retA($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "45:2-45:23", $s$9], [2, "45:6-45:13", $s$9], [0, null, $s$9], [4, "45:15-45:23", $s$9], [2, "45:15-45:22", $s$9], [4, "46:2-46:17", $s$9], [2, "46:9-46:16", $s$9], [0, null, $s$9], [16, "47:1-47:1", $s$9], [16, "47:1-47:1", $s$9]]), $m$6 = $M.fun("m$6", "b2", null, $m$0, [], 0, 2, "51:0-58:1", 2, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $yld(1); case 2: $.goto = 3; $brk(); $.state = 3; case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; return $yld(2); case 5: $.goto = 6; $brk(); $.state = 6; case 6: $.goto = 11; $brk(); continue; case 7: $l[1] = $.error; $.error = void 0; $.goto = 8; $brk(); $.state = 8; case 8: $.goto = 9; return $yld($l[1]); case 9: $.goto = 6; $brk(); continue; case 10: $.goto = 11; return $unhandledG($.error); case 11: return $retG($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 5: case 4: case 3: $.goto = 7; break; default: $.goto = 10; } }, null, 1, [[4, "52:2-52:10", $s$10], [2, "52:2-52:9", $s$10], [4, "53:2-57:3", $s$10], [5, "54:4-54:12", $s$10], [3, "54:4-54:11", $s$10], [37, "55:3-55:3", $s$10], [36, "58:1-58:1", $s$10], [4, "56:4-56:12", $s$11], [2, "56:4-56:11", $s$11], [36, "57:3-57:3", $s$10], [16, "58:1-58:1", $s$10], [16, "58:1-58:1", $s$10]]), $m$7 = $M.fun("m$7", "af2", null, $m$0, [], 0, 1, "60:0-63:1", 1, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; return $awt($l[0][1]); case 2: if ($p) { $.state = 3; } else { $.goto = 5; continue; } case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; return $awt($l[0][2]); case 5: $.goto = 6; $brk(); $.state = 6; case 6: $.goto = 7; return $awt($l[0][3]); case 7: $.result = $p; $.goto = 9; continue; case 8: $.goto = 9; return $unhandledA($.error); case 9: return $retA($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "61:2-61:23", $s$12], [2, "61:6-61:13", $s$12], [0, null, $s$12], [4, "61:15-61:23", $s$12], [2, "61:15-61:22", $s$12], [4, "62:2-62:17", $s$12], [2, "62:9-62:16", $s$12], [0, null, $s$12], [16, "63:1-63:1", $s$12], [16, "63:1-63:1", $s$12]]); $M.moduleExports();
'use strict'; class LarxShader { constructor() { this.light = { ambient: [0.1, 0.1, 0.1], directional: [0.7, 0.7, 0.7], specular: [1.0, 1.0, 1.0], direction: [-0.5, -0.8, 0.5] }; } downloadShader(id, type) { return new Promise((resolve) => { let http = new XMLHttpRequest(); http.onreadystatechange = () => { if(http.readyState === 4 && http.status === 200) { resolve(http.responseText); } }; http.open('GET', 'shaders/' + id + '.' + type + '?rnd=' + Math.random() * 1000); http.send(); }); } createShader(id, ext, type) { return new Promise((resolve, reject) => { this.downloadShader(id, ext).then((shaderData) => { let shader = Larx.gl.createShader(type); Larx.gl.shaderSource(shader, shaderData); Larx.gl.compileShader(shader); if(!Larx.gl.getShaderParameter(shader, Larx.gl.COMPILE_STATUS)) { console.error(id, ext); console.error(Larx.gl.getShaderInfoLog(shader)); reject(Larx.gl.getShaderInfoLog(shader)); } else { resolve(shader); } }); }); } downloadShaderProgram(name) { return new Promise((resolve) => { this.createShader(name, 'fs', Larx.gl.FRAGMENT_SHADER).then((fs) => { this.createShader(name, 'vs', Larx.gl.VERTEX_SHADER).then((vs) => { let program = Larx.gl.createProgram(); Larx.gl.attachShader(program, vs); Larx.gl.attachShader(program, fs); resolve(program); }); }); }); } setDefaults(shader, useLights) { shader.pMatrixUniform = Larx.gl.getUniformLocation(shader, 'uPMatrix'); shader.mvMatrixUniform = Larx.gl.getUniformLocation(shader, 'uMVMatrix'); shader.nMatrixUniform = Larx.gl.getUniformLocation(shader, 'uNMatrix'); shader.vertexPositionAttribute = Larx.gl.getAttribLocation(shader, 'aVertexPosition'); Larx.gl.enableVertexAttribArray(shader.vertexPositionAttribute); if(useLights) { shader.ambientColor = Larx.gl.getUniformLocation(shader, 'uAmbientColor'); shader.directionalColor = Larx.gl.getUniformLocation(shader, 'uDirectionalColor'); shader.specularColor = Larx.gl.getUniformLocation(shader, 'uSpecularColor'); shader.lightDirection = Larx.gl.getUniformLocation(shader, 'uLightingDirection'); shader.shininess = Larx.gl.getUniformLocation(shader, 'uShininess'); shader.specularWeight = Larx.gl.getUniformLocation(shader, 'uSpecularWeight'); Larx.gl.uniform3f(shader.ambientColor, this.light.ambient[0], this.light.ambient[1], this.light.ambient[2]); Larx.gl.uniform3f(shader.directionalColor, this.light.directional[0], this.light.directional[1], this.light.directional[2]); Larx.gl.uniform3f(shader.specularColor, this.light.specular[0], this.light.specular[1], this.light.specular[2]); let adjustedLightDir = vec3.create(); vec3.normalize(adjustedLightDir, this.light.direction); vec3.scale(adjustedLightDir, adjustedLightDir, -1); Larx.gl.uniform3fv(shader.lightDirection, adjustedLightDir); } } get() { return this.shader; } };
module.exports = require("./bin/Watch");
import createBubbleChart from './bubble-chart-controller'; import createBarChart from './bar-chart-controller'; const moment = require('moment'); const dayColors = [ '#F44336', '#9C27B0', '#3F51B5', '#00BCD4', '#4CAF50', '#FFC107', '#FF5722', ]; const currencies = { EUR: '€', USD: '$', }; // Processes a single movement and returns an objects // representing a single bubble in a Bubble Chart const bubbleChartProcessor = (movement) => { const date = moment.utc(movement.date, 'YYYY-MM-DD'); return { // Sets movement amount has visual z so that smaller bubbles // are drawn above bigger one and easier to select zIndex: movement.amount, data: [{ y: date.valueOf('x'), z: Math.abs(movement.amount), name: movement.category, color: dayColors[date.weekday()], description: movement.description, }], }; }; const barChartProcessor = (movement) => { const date = moment.utc(movement.date, 'YYYY-MM-DD'); return { y: Math.abs(movement.amount), x: date.valueOf('x'), name: movement.category, color: dayColors[date.weekday()], description: movement.description, }; }; const createMovementListElement = (movement) => { const item = document.createElement('li'); // Date const date = document.createTextNode(movement.date); const dateParagraph = document.createElement('p'); dateParagraph.className = 'date'; dateParagraph.appendChild(date); // Description const description = document.createTextNode(movement.description); const descriptionParagraph = document.createElement('p'); descriptionParagraph.className = 'description'; descriptionParagraph.appendChild(description); // Amount const amount = document.createTextNode(`${Math.abs(movement.amount).toFixed(2)} ${currencies[movement.amount_currency]}`); const amountHeader = document.createElement('h4'); amountHeader.className = 'amount'; amountHeader.appendChild(amount); const amountDescriptionContainer = document.createElement('div'); amountDescriptionContainer.className = 'amount-description-container'; amountDescriptionContainer.appendChild(amountHeader); amountDescriptionContainer.appendChild(descriptionParagraph); item.appendChild(dateParagraph); item.appendChild(amountDescriptionContainer); return item; }; const updateMovementList = (movements, container) => { // Removes currently shown Movements while (container.firstChild) { container.removeChild(container.firstChild); } const fragment = document.createDocumentFragment(); // Creates and appends list of movements to container movements.forEach((movement) => { const el = createMovementListElement(movement); fragment.appendChild(el); }); container.appendChild(fragment); }; const globalProcessor = (data) => { const bubbleCategories = new Set(); const bubbleData = []; const barData = [{ data: [] }]; const greatestSpendings = []; const smallestSpendings = []; data.forEach((movement) => { // Only losses should be shown if (movement.amount < 0) { bubbleCategories.add(movement.category); bubbleData.push(bubbleChartProcessor(movement)); barData[0].data.push(barChartProcessor(movement)); greatestSpendings.push(movement); smallestSpendings.push(movement); } }); // Sorts spendings greatestSpendings.sort((m1, m2) => { const amount1 = Number(m1.amount); const amount2 = Number(m2.amount); if (amount1 < amount2) { return -1; } else if (amount1 > amount2) { return 1; } return 0; }); smallestSpendings.sort((m1, m2) => { const amount1 = Number(m1.amount); const amount2 = Number(m2.amount); if (amount1 > amount2) { return -1; } else if (amount1 < amount2) { return 1; } return 0; }); // We only want to see some Movements for these lists greatestSpendings.splice(5); smallestSpendings.splice(5); updateMovementList(greatestSpendings, document.getElementById('greatest-spendings-list')); updateMovementList(smallestSpendings, document.getElementById('smallest-spendings-list')); createBubbleChart('bubble-chart-container', bubbleCategories, bubbleData); createBarChart('bar-chart-container', barData); }; export { bubbleChartProcessor, barChartProcessor, globalProcessor };
/* eslint-disable quotes */ require('./style/main.scss'); import $ from 'jquery'; import * as Rx from 'rx'; import videojs from 'video.js'; import HotkeyModal from './hotkeysModal'; import HotkeysModalButton from './hotkeysModalButton'; import RangeBarCollection from './rangeBarCollection'; import RangeCollection from './rangeCollection'; import RangeControlBar from './rangeControlBar'; import {WebVTT} from 'videojs-vtt.js'; import {overrideHotkeys, hotkeys} from './hotkeys'; import RangeItemContainer from './rangeItemContainer'; import * as appCommons from 'phraseanet-common'; // import rangeControls from './oldControlBar'; const icons = ` <svg style="position: absolute; width: 0; height: 0;" width="0" height="0" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <symbol id="icon-loop-range" viewBox="0 0 30 30"> <title>loop-range</title> <path class="path1" d="M25.707 9.92l-2.133 1.813h1.707c0.107 0 0.32 0.213 0.32 0.213v8.107c0 0.107-0.213 0.213-0.32 0.213h-11.093l-0.853 2.133h11.947c1.067 0 2.453-1.28 2.453-2.347v-8.107c0-1.067-1.067-1.92-2.027-2.027z"></path> <path class="path2" d="M7.040 22.4l1.92-2.133h-2.24c-0.107 0-0.32-0.213-0.32-0.213v-8.107c0 0 0.213-0.213 0.32-0.213h11.627l0.853-2.133h-12.48c-1.173 0-2.453 1.28-2.453 2.347v8.107c0 1.067 1.28 2.347 2.453 2.347h0.32z"></path> <path class="path3" d="M17.493 6.827l4.053 3.947-4.053 3.947z"></path> <path class="path4" d="M14.933 24.96l-3.947-3.84 3.947-3.947z"></path> </symbol> <symbol id="icon-prev-forward-frame" viewBox="0 0 30 30"> <title>prev-forward-frame</title> <path class="path1" d="M25.432 9.942l-9.554 9.554-3.457-3.457 9.554-9.554 3.457 3.457z"></path> <path class="path2" d="M21.912 25.578l-9.554-9.554 3.457-3.457 9.554 9.554-3.457 3.457z"></path> <path class="path3" d="M6.578 6.489h2.578v19.111h-2.578v-19.111z"></path> </symbol> <symbol id="icon-next-forward-frame" viewBox="0 0 30 30"> <title>next-forward-frame</title> <path class="path1" d="M10.131 6.462l9.554 9.554-3.457 3.457-9.554-9.554 3.457-3.457z"></path> <path class="path2" d="M6.611 22.018l9.554-9.554 3.457 3.457-9.554 9.554-3.457-3.457z"></path> <path class="path3" d="M22.756 6.489h2.578v19.111h-2.578v-19.111z"></path> </symbol> <symbol id="icon-prev-frame" viewBox="0 0 30 30"> <title>prev-frame</title> <path class="path1" d="M22.538 9.962l-9.554 9.554-3.457-3.457 9.554-9.554 3.457 3.457z"></path> <path class="path2" d="M19.018 25.558l-9.554-9.554 3.457-3.457 9.554 9.554-3.457 3.457z"></path> </symbol> <symbol id="icon-next-frame" viewBox="0 0 30 30"> <title>next-frame</title> <path class="path1" d="M12.984 6.441l9.554 9.554-3.457 3.457-9.554-9.554 3.457-3.457z"></path> <path class="path2" d="M9.464 22.039l9.554-9.554 3.457 3.457-9.554 9.554-3.457-3.457z"></path> </symbol> <symbol id="icon-cue-start" viewBox="0 0 30 30"> <title>cue-start</title> <path class="path1" d="M20.356 24.089v-15.733c0-0.533-0.356-0.889-0.889-0.889h-8c-0.444 0-0.889 0.356-0.889 0.889v5.067c0 0.533 0.267 1.156 0.622 1.511l8.622 9.422c0.267 0.356 0.533 0.267 0.533-0.267z"></path> </symbol> <symbol id="icon-cue-end" viewBox="0 0 30 30"> <title>cue-end</title> <path class="path1" d="M10.578 24.089v-15.733c0-0.533 0.356-0.889 0.889-0.889h8c0.444 0 0.889 0.356 0.889 0.889v5.067c0 0.533-0.267 1.156-0.622 1.511l-8.622 9.422c-0.267 0.356-0.533 0.267-0.533-0.267z"></path> </symbol> <symbol id="icon-trash" viewBox="0 0 30 30"> <title>trash</title> <path class="path1" d="M22.667 8.978h-3.822v-1.333c0-0.8-0.622-1.422-1.422-1.422h-2.756c-0.8 0-1.422 0.622-1.422 1.422v1.422h-3.822c-0.178 0-0.356 0.178-0.356 0.356v0.711c0 0.178 0.178 0.356 0.356 0.356h13.333c0.178 0 0.356-0.178 0.356-0.356v-0.711c-0.089-0.267-0.267-0.444-0.444-0.444zM14.667 8.978v0-1.422h2.756v1.422h-2.756z"></path> <path class="path2" d="M21.778 11.111h-11.733c-0.267 0-0.356 0.089-0.356 0.356v14.133c0 0 0.089 0.267 0.356 0.267h11.733c0.267 0 0.533-0.089 0.533-0.356v-14.133c0-0.178-0.267-0.267-0.533-0.267zM13.156 23.378c0 0.178-0.178 0.356-0.356 0.356h-0.711c-0.178 0-0.356-0.178-0.356-0.356v-9.778c0-0.178 0.178-0.356 0.356-0.356h0.711c0.178 0 0.356 0.178 0.356 0.356v9.778zM16.711 23.378c0 0.178-0.178 0.356-0.356 0.356h-0.711c-0.178 0-0.356-0.178-0.356-0.356v-9.778c0-0.178 0.178-0.356 0.356-0.356h0.711c0.178 0 0.356 0.178 0.356 0.356v9.778zM20.178 23.378c0 0.178-0.178 0.356-0.356 0.356h-0.711c-0.178 0-0.356-0.178-0.356-0.356v-9.778c0-0.178 0.178-0.356 0.356-0.356h0.711c0.178 0 0.356 0.178 0.356 0.356v9.778z"></path> </symbol> </defs> </svg> `; const defaults = { seekBackwardStep: 1000, seekForwardStep: 1000, align: 'top-left', class: '', content: 'This overlay will show up while the video is playing', debug: false, overlays: [{ start: 'playing', end: 'paused' }] }; const Component = videojs.getComponent('Component'); const plugin = function (options) { const settings = videojs.mergeOptions(defaults, options); this.looping = false; this.loopData = []; this.activeRange = {}; this.activeRangeStream = new Rx.Subject(); //new Rx.Observable.ofObjectChanges(this.activeRange); this.rangeStream = new Rx.Subject(); this.rangeBarCollection = this.controlBar.getChild('progressControl').getChild('seekBar').addChild('RangeBarCollection', settings); this.rangeControlBar = this.addChild('RangeControlBar', settings); this.rangeItemContainer = this.addChild('RangeItemContainer', settings); this.rangeCollection = this.rangeItemContainer.getChild('RangeCollection'); this.hotkeysModalButton = this.addChild('HotkeysModalButton', settings); $(this.el()).prepend(icons); this.setEditorWidth = () => { let editorWidth = this.currentWidth(); if (editorWidth < 672) { $(this.el()).addClass('vjs-mini-screen'); } else { $(this.el()).removeClass('vjs-mini-screen'); } } this.setEditorHeight = () => { // gather components sizes let editorHeight = this.currentHeight() + $(this.rangeControlBar.el()).height() + $(this.rangeCollection.el()).height(); if (editorHeight > 0) { options.$container.height(editorHeight + 'px'); } } // range actions: this.rangeStream.subscribe((params) => { params.handle = params.handle || false; console.log('RANGE EVENT ===========', params.action, '========>>>') switch (params.action) { case 'initialize': this.rangeCollection.update(params.range); break; case 'select': case 'change': params.range = this.shouldTakeSnapShot(params.range, false); this.activeRange = this.rangeCollection.update(params.range); this.activeRangeStream.onNext({ activeRange: this.activeRange }); this.rangeBarCollection.refreshRangeSliderPosition(this.activeRange); this.rangeControlBar.refreshRangePosition(this.activeRange, params.handle); setTimeout(() => { this.rangeControlBar.setRangePositonToBeginning(params.range); }, 300); break; // flow through update: case 'create': case 'update': params.range = this.shouldTakeSnapShot(params.range, false); this.activeRange = this.rangeCollection.update(params.range); this.activeRangeStream.onNext({ activeRange: this.activeRange }); this.rangeBarCollection.refreshRangeSliderPosition(this.activeRange); this.rangeControlBar.refreshRangePosition(this.activeRange, params.handle); break; case 'remove': // if a range is specified remove it from collection: if (params.range !== undefined) { this.rangeCollection.remove(params.range); if (params.range.id === this.activeRange.id) { // remove from controls components too if active: this.rangeBarCollection.removeActiveRange(); this.rangeControlBar.removeActiveRange(); } } else { this.rangeBarCollection.removeActiveRange(); this.rangeControlBar.removeActiveRange(); this.rangeCollection.remove(this.activeRange); } break; case 'drag-update': // if changes come from range bar this.rangeControlBar.refreshRangePosition(params.range, params.handle); this.rangeCollection.updatingByDragging(params.range); // setting currentTime may take some additionnal time, // so let's wait: setTimeout(() => { if (params.handle === 'start') { params.range = this.shouldTakeSnapShot(params.range, false); this.rangeCollection.update(params.range); } }, 900); break; case 'export-ranges': break; case 'export-vtt-ranges': this.rangeCollection.exportRangesData(params.data); break; case 'resize': this.setEditorWidth(); break; case 'saveRangeCollectionPref':
 this.saveRangeCollectionPref(params.data); break; case 'capture': // if a range is specified remove it from collection: if (params.range !== undefined) { params.range = this.shouldTakeSnapShot(params.range, true); this.rangeCollection.update(params.range); } break; default: } console.log('<<< =================== RANGE EVENT COMPLETE') }); this.shouldTakeSnapShot = (range, atCurrentPosition) => { if(atCurrentPosition) { this.takeSnapshot(range); range.manualSnapShot = true; return range; } else if (Math.round(range.startPosition) == Math.round(this.currentTime()) && !range.manualSnapShot) { this.takeSnapshot(range); return range; } else { return range; } } this.takeSnapshot = (range) => { let video = this.el().querySelector('video'); let canvas = document.createElement('canvas'); let ratio = settings.ratios[this.cache_.src]; canvas.width = 50 * ratio; canvas.height = 50; let context = canvas.getContext('2d'); context.fillRect(0, 0, canvas.width, canvas.height); context.drawImage(video, 0, 0, canvas.width, canvas.height); let dataURI = canvas.toDataURL('image/jpeg'); range.image = { src: dataURI, ratio: settings.ratios[this.cache_.src], width: canvas.width, height: canvas.height } return range; } this.setVTT = () => { if (settings.vttFieldValue !== false) { // reset existing collection this.rangeCollection.reset([]) // prefill chapters with vtt data let parser = new WebVTT.Parser(window, window.vttjs, WebVTT.StringDecoder()); let errors = []; parser.oncue = (cue) => { // try to parse text: let parsedCue = false; try { parsedCue = JSON.parse(cue.text || '{}'); } catch (e) { console.error('failed to parse cue text', e) } if (parsedCue === false) { parsedCue = { title: cue.text } } let newRange = this.rangeCollection.addRange({ startPosition: cue.startTime, endPosition: cue.endTime, title: parsedCue.title, image: { src: parsedCue.image || '' }, manualSnapShot: parsedCue.manualSnapShot }); this.rangeStream.onNext({ action: 'initialize', range: newRange }) }; parser.onparsingerror = function (error) { errors.push(error); }; parser.parse(settings.vttFieldValue); if (errors.length > 0) { if (console.groupCollapsed) { console.groupCollapsed(`Text Track parsing errors`); } errors.forEach((error) => console.error(error)); if (console.groupEnd) { console.groupEnd(); } } parser.flush(); } } this.ready(() => { /*resize video*/ var videoChapterH = $('#rangeExtractor').height(); $('#rangeExtractor .video-player-container').css('max-height', videoChapterH); $('#rangeExtractor .range-collection-container').css('height', videoChapterH - 100); $('#rangeExtractor .video-range-editor-container').css('max-height', videoChapterH).css('overflow','hidden'); this.setVTT(); // if we have to load existing chapters, let's trigger loadedmetadata: if (settings.vttFieldValue !== false) { var playPromise = null; if (this.paused()) { playPromise = this.play().then(() => { this.pause(); }).catch(error => { }); } if (!this.paused()) { if (playPromise !== undefined) { playPromise.then(() => { this.pause(); }) .catch(error => { }); } } } }); this.one('loadedmetadata', () => { //this.setEditorHeight(); this.setEditorWidth(); if (settings.vttFieldValue !== false) { //this.currentTime(0); } }); // ensure control bar is always visible by simulating user activity: this.on('timeupdate', () => { this.userActive(true); }); // override existing hotkeys: this.getRangeCaptureOverridedHotkeys = () => overrideHotkeys(settings); // set new hotkeys this.getRangeCaptureHotkeys = () => hotkeys(this, settings); // init a default range once every components are ready: this.rangeCollection.initDefaultRange(); this.saveRangeCollectionPref = (isChecked) => {
 appCommons.userModule.setPref('overlapChapters', (isChecked ? '1' : '0'));
 } } videojs.plugin('rangeCapturePlugin', plugin); export default plugin;
var States; (function (States) { var RectangleBuilder = Classes.RectangleBuilder; class EncounterCharacter { constructor(state, x, y, imageKey, imageHeight) { this.state = state; this.x = x; this.y = y; this.imageKey = imageKey; this.imageHeight = imageHeight; this.WHITE = '#FFFFFF'; this.RED = "#C85054"; this.GREEN = '#70f17b'; this.currentRemainingHealthColor = this.GREEN; this.state.add.sprite(this.x, this.y, this.imageKey); this.createTotalHealthBar(); this.createRemainingHealthBar(this.GREEN); } createRemainingHealthBar(color) { this.remainingHealthBar = RectangleBuilder.rectangle() .withState(this.state) .withFillColor(color) .withX(this.x) .withY(this.y + this.imageHeight + 5) .withWidth(180) .withHeight(15) .build(); } createTotalHealthBar() { this.totalHealthBar = RectangleBuilder.rectangle() .withState(this.state) .withFillColor(this.WHITE) .withX(this.x) .withY(this.y + this.imageHeight + 5) .withWidth(180) .withHeight(15) .build(); } decrementHealthBarUntil(percentage) { if (this.remainingHealthBarWidthTooBig(percentage)) { this.remainingHealthBar.width--; this.replaceByRedBarIfSizeLessThanOrEqualThanHalf(); } } remainingHealthBarWidthTooBig(actualRemainingPercentage) { var totalHealthBarWidth = this.totalHealthBar.width; var remainingHealthBarWidth = this.remainingHealthBar.width; return remainingHealthBarWidth > (totalHealthBarWidth / 100) * actualRemainingPercentage; } replaceByRedBarIfSizeLessThanOrEqualThanHalf() { if (this.barWidthLessThanOrEqualThanHalf() && this.currentRemainingHealthColor === this.GREEN) { var newHealthBarWidth = this.remainingHealthBar.width; this.remainingHealthBar.destroy(true); this.createRemainingHealthBar(this.RED); this.remainingHealthBar.width = newHealthBarWidth; this.currentRemainingHealthColor = this.RED; } } barWidthLessThanOrEqualThanHalf() { return this.remainingHealthBar.width <= this.totalHealthBar.width / 2; } } States.EncounterCharacter = EncounterCharacter; class EncounterCharacterBuilder { static encounterCharacter() { return new EncounterCharacterBuilder(); } build() { return new EncounterCharacter(this.state, this.x, this.y, this.imageKey, this.imageHeight); } withState(value) { this.state = value; return this; } withX(value) { this.x = value; return this; } withY(value) { this.y = value; return this; } withImageKey(value) { this.imageKey = value; return this; } withImageHeight(value) { this.imageHeight = value; return this; } } States.EncounterCharacterBuilder = EncounterCharacterBuilder; })(States || (States = {})); //# sourceMappingURL=EncounterCharacter.js.map
(function() { var options = { sourceAttr: php_vars.ar_sl_sourceAttr, overlay: (php_vars.ar_sl_overlay == '1') ? true : false, overlayOpacity: parseFloat(php_vars.ar_sl_overlayOpacity), spinner: (php_vars.ar_sl_spinner == '1') ? true : false, nav: (php_vars.ar_sl_nav === '1') ? true : false, navText: [php_vars.ar_sl_navtextPrev,php_vars.ar_sl_navtextNext], captions: (php_vars.ar_sl_caption === '1') ? true : false, captionSelector:php_vars.ar_sl_captionSelector, captionType: php_vars.ar_sl_captionType, captionsData: php_vars.ar_sl_captionData, captionPosition:php_vars.ar_sl_captionPosition, captionDelay: parseInt(php_vars.ar_sl_captionDelay,10), captionClass: php_vars.ar_sl_captionClass, close: (php_vars.ar_sl_close === '1') ? true : false, closeText: php_vars.ar_sl_closeText, showCounter: (php_vars.ar_sl_showCounter === '1') ? true : false, fileExt: (php_vars.ar_sl_fileExt == 'false') ? false : php_vars.ar_sl_fileExt, animationSpeed: parseInt(php_vars.ar_sl_animationSpeed,10), animationSlide: (php_vars.ar_sl_animationSlide === '1') ? true : false, preloading: (php_vars.ar_sl_preloading === '1') ? true : false, enableKeyboard: (php_vars.ar_sl_enableKeyboard === '1') ? true : false, loop: (php_vars.ar_sl_loop === '1') ? true : false, rel: (php_vars.ar_sl_rel == 'false') ? false : php_vars.ar_sl_rel, docClose: (php_vars.ar_sl_docClose === '1') ? true : false, swipeTolerance: parseInt(php_vars.ar_sl_swipeTolerance,10), className: php_vars.ar_sl_className, widthRatio: php_vars.ar_sl_widthRatio, heightRatio: php_vars.ar_sl_heightRatio, scaleImageToRatio: (php_vars.ar_sl_scaleImageToRatio == '1') ? true : false, disableRightClick:(php_vars.ar_sl_disableRightClick == '1') ? true : false, disableScroll: (php_vars.ar_sl_disableScroll == '1') ? true : false, alertError: (php_vars.ar_sl_alertError == '1') ? true : false, alertErrorMessage:php_vars.ar_sl_alertErrorMessage, additionalHtml: php_vars.ar_sl_additionalHtml, history: (php_vars.ar_sl_history == '1') ? true : false, throttleInterval:parseInt(php_vars.ar_sl_throttleInterval,10), doubleTapZoom: parseInt(php_vars.ar_sl_doubleTapZoom,10), maxZoom: parseInt(php_vars.ar_sl_maxZoom,10), htmlClass: php_vars.ar_sl_htmlClass, rtl: (php_vars.ar_sl_rtl == '1') ? true : false, fixedClass: php_vars.ar_sl_fixedClass, fadeSpeed: parseInt(php_vars.ar_sl_fadeSpeed,10), uniqueImages: (php_vars.ar_sl_uniqueImages == '1') ? true : false, focus: (php_vars.ar_sl_focus == '1') ? true : false, scrollZoom: (php_vars.ar_sl_scrollZoom == '1') ? true : false, scrollZoomFactor:parseFloat(php_vars.ar_sl_scrollZoomFactor) } if(document.querySelectorAll('a.simplelightbox').length ) { var simplelightbox = new SimpleLightbox('a.simplelightbox', options); } if(php_vars.ar_sl_additionalSelectors) { var selectors = php_vars.ar_sl_additionalSelectors.split(','); for(var i = 0; i <= selectors.length; i++) { var selector = selectors[i]; if(selector) { selector = selector.trim(); if(selector != '' && document.querySelectorAll(selector).length) { new SimpleLightbox(selector, options); } } } } })();
/*global module*/ module.exports = function(grunt, tasks) { // Load our node module required for this task. grunt.loadNpmTasks('grunt-html'); // The configuration for a specific task. tasks.htmllint = { // The files that we want to check. dist: { options: { path: false, reportpath: false // Turns logging to a file off, output will show in the CLI. }, // The files that we want to check. src: [ grunt.uriSrc + '*.html', // Include all HTML files in this directory. '!' + grunt.uriSrc + '*.min.html' // Exclude any files ending with `.min.html` ] } }; return tasks; };
/* */ 'use strict'; var format = require("util").format; var _ = require("underscore"); _.str = require("underscore.string"); var $$ = require("./const"); var ActionHelp = require("./action\help"); var ActionAppend = require("./action\append"); var ActionAppendConstant = require("./action\append\constant"); var ActionCount = require("./action\count"); var ActionStore = require("./action\store"); var ActionStoreConstant = require("./action\store\constant"); var ActionStoreTrue = require("./action\store\true"); var ActionStoreFalse = require("./action\store\false"); var ActionVersion = require("./action\version"); var ActionSubparsers = require("./action\subparsers"); var argumentErrorHelper = require("./argument\error"); var ActionContainer = module.exports = function ActionContainer(options) { options = options || {}; this.description = options.description; this.argumentDefault = options.argumentDefault; this.prefixChars = options.prefixChars || ''; this.conflictHandler = options.conflictHandler; this._registries = {}; this.register('action', null, ActionStore); this.register('action', 'store', ActionStore); this.register('action', 'storeConst', ActionStoreConstant); this.register('action', 'storeTrue', ActionStoreTrue); this.register('action', 'storeFalse', ActionStoreFalse); this.register('action', 'append', ActionAppend); this.register('action', 'appendConst', ActionAppendConstant); this.register('action', 'count', ActionCount); this.register('action', 'help', ActionHelp); this.register('action', 'version', ActionVersion); this.register('action', 'parsers', ActionSubparsers); this._getHandler(); this._actions = []; this._optionStringActions = {}; this._actionGroups = []; this._mutuallyExclusiveGroups = []; this._defaults = {}; this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); this._hasNegativeNumberOptionals = []; }; var ArgumentGroup = require("./argument\group"); var MutuallyExclusiveGroup = require("./argument\exclusive"); ActionContainer.prototype.register = function(registryName, value, object) { this._registries[registryName] = this._registries[registryName] || {}; this._registries[registryName][value] = object; }; ActionContainer.prototype._registryGet = function(registryName, value, defaultValue) { if (3 > arguments.length) { defaultValue = null; } return this._registries[registryName][value] || defaultValue; }; ActionContainer.prototype.setDefaults = function(options) { options = options || {}; for (var property in options) { this._defaults[property] = options[property]; } this._actions.forEach(function(action) { if (action.dest in options) { action.defaultValue = options[action.dest]; } }); }; ActionContainer.prototype.getDefault = function(dest) { var result = (_.has(this._defaults, dest)) ? this._defaults[dest] : null; this._actions.forEach(function(action) { if (action.dest === dest && _.has(action, 'defaultValue')) { result = action.defaultValue; } }); return result; }; ActionContainer.prototype.addArgument = function(args, options) { args = args; options = options || {}; if (!_.isArray(args)) { throw new TypeError('addArgument first argument should be an array'); } if (!_.isObject(options) || _.isArray(options)) { throw new TypeError('addArgument second argument should be a hash'); } if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { if (args && !!options.dest) { throw new Error('dest supplied twice for positional argument'); } options = this._getPositional(args, options); } else { options = this._getOptional(args, options); } if (_.isUndefined(options.defaultValue)) { var dest = options.dest; if (_.has(this._defaults, dest)) { options.defaultValue = this._defaults[dest]; } else if (!_.isUndefined(this.argumentDefault)) { options.defaultValue = this.argumentDefault; } } var ActionClass = this._popActionClass(options); if (!_.isFunction(ActionClass)) { throw new Error(format('Unknown action "%s".', ActionClass)); } var action = new ActionClass(options); var typeFunction = this._registryGet('type', action.type, action.type); if (!_.isFunction(typeFunction)) { throw new Error(format('"%s" is not callable', typeFunction)); } return this._addAction(action); }; ActionContainer.prototype.addArgumentGroup = function(options) { var group = new ArgumentGroup(this, options); this._actionGroups.push(group); return group; }; ActionContainer.prototype.addMutuallyExclusiveGroup = function(options) { var group = new MutuallyExclusiveGroup(this, options); this._mutuallyExclusiveGroups.push(group); return group; }; ActionContainer.prototype._addAction = function(action) { var self = this; this._checkConflict(action); this._actions.push(action); action.container = this; action.optionStrings.forEach(function(optionString) { self._optionStringActions[optionString] = action; }); action.optionStrings.forEach(function(optionString) { if (optionString.match(self._regexpNegativeNumber)) { if (!_.any(self._hasNegativeNumberOptionals)) { self._hasNegativeNumberOptionals.push(true); } } }); return action; }; ActionContainer.prototype._removeAction = function(action) { var actionIndex = this._actions.indexOf(action); if (actionIndex >= 0) { this._actions.splice(actionIndex, 1); } }; ActionContainer.prototype._addContainerActions = function(container) { var titleGroupMap = {}; this._actionGroups.forEach(function(group) { if (titleGroupMap[group.title]) { throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); } titleGroupMap[group.title] = group; }); var groupMap = {}; function actionHash(action) { return action.getName(); } container._actionGroups.forEach(function(group) { if (!titleGroupMap[group.title]) { titleGroupMap[group.title] = this.addArgumentGroup({ title: group.title, description: group.description }); } group._groupActions.forEach(function(action) { groupMap[actionHash(action)] = titleGroupMap[group.title]; }); }, this); var mutexGroup; container._mutuallyExclusiveGroups.forEach(function(group) { mutexGroup = this.addMutuallyExclusiveGroup({required: group.required}); group._groupActions.forEach(function(action) { groupMap[actionHash(action)] = mutexGroup; }); }, this); container._actions.forEach(function(action) { var key = actionHash(action); if (!!groupMap[key]) { groupMap[key]._addAction(action); } else { this._addAction(action); } }); }; ActionContainer.prototype._getPositional = function(dest, options) { if (_.isArray(dest)) { dest = _.first(dest); } if (options.required) { throw new Error('"required" is an invalid argument for positionals.'); } if (options.nargs !== $$.OPTIONAL && options.nargs !== $$.ZERO_OR_MORE) { options.required = true; } if (options.nargs === $$.ZERO_OR_MORE && options.defaultValue === undefined) { options.required = true; } options.dest = dest; options.optionStrings = []; return options; }; ActionContainer.prototype._getOptional = function(args, options) { var prefixChars = this.prefixChars; var optionStrings = []; var optionStringsLong = []; args.forEach(function(optionString) { if (prefixChars.indexOf(optionString[0]) < 0) { throw new Error(format('Invalid option string "%s": must start with a "%s".', optionString, prefixChars)); } optionStrings.push(optionString); if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { optionStringsLong.push(optionString); } }); var dest = options.dest || null; delete options.dest; if (!dest) { var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; dest = _.str.strip(optionStringDest, this.prefixChars); if (dest.length === 0) { throw new Error(format('dest= is required for options like "%s"', optionStrings.join(', '))); } dest = dest.replace(/-/g, '_'); } options.dest = dest; options.optionStrings = optionStrings; return options; }; ActionContainer.prototype._popActionClass = function(options, defaultValue) { defaultValue = defaultValue || null; var action = (options.action || defaultValue); delete options.action; var actionClass = this._registryGet('action', action, action); return actionClass; }; ActionContainer.prototype._getHandler = function() { var handlerString = this.conflictHandler; var handlerFuncName = "_handleConflict" + _.str.capitalize(handlerString); var func = this[handlerFuncName]; if (typeof func === 'undefined') { var msg = "invalid conflict resolution value: " + handlerString; throw new Error(msg); } else { return func; } }; ActionContainer.prototype._checkConflict = function(action) { var optionStringActions = this._optionStringActions; var conflictOptionals = []; action.optionStrings.forEach(function(optionString) { var conflOptional = optionStringActions[optionString]; if (typeof conflOptional !== 'undefined') { conflictOptionals.push([optionString, conflOptional]); } }); if (conflictOptionals.length > 0) { var conflictHandler = this._getHandler(); conflictHandler.call(this, action, conflictOptionals); } }; ActionContainer.prototype._handleConflictError = function(action, conflOptionals) { var conflicts = _.map(conflOptionals, function(pair) { return pair[0]; }); conflicts = conflicts.join(', '); throw argumentErrorHelper(action, format('Conflicting option string(s): %s', conflicts)); }; ActionContainer.prototype._handleConflictResolve = function(action, conflOptionals) { var self = this; conflOptionals.forEach(function(pair) { var optionString = pair[0]; var conflictingAction = pair[1]; var i = conflictingAction.optionStrings.indexOf(optionString); if (i >= 0) { conflictingAction.optionStrings.splice(i, 1); } delete self._optionStringActions[optionString]; if (conflictingAction.optionStrings.length === 0) { conflictingAction.container._removeAction(conflictingAction); } }); };
const express = require('express'); const router = express.Router(); const userController = require('../controllers/userController.js'); const passportService = require('../services/passport'); const passport = require('passport'); const requireAuth = passport.authenticate('jwt', { session: false }); const requireSignin = passport.authenticate('local', {session: false}); /* * GET */ router.get('/', requireAuth, function(req, res) { userController.list(req, res); }); /* * GET */ router.get('/:id', function(req, res) { userController.show(req, res); }); /* * POST */ router.post('/signin', requireSignin, function(req, res, next) { userController.signin(req, res, next); }); router.post('/signup', function(req, res, next) { userController.signup(req, res); }); /* * PUT */ router.put('/:id', function(req, res) { userController.update(req, res); }); /* * DELETE */ router.delete('/:id', function(req, res) { userController.remove(req, res); }); module.exports = router;
/** * Class that handles the default view */ window.themingStore.views.BrowseView = window.themingStore.views.AbstractView.extend({ /** * Master element */ el: $('body'), /** * events bound to the view */ events: { 'click .filter': 'filterClicked' }, /** * filter container cookie name */ filter_cookie: 'filters_theming', /** * filter manager */ currentFilterManager: {}, /** * the filter applied to the collection */ filterApplied: null, /** * flag to know how many times a filter has been applied */ filterStack: 0, /** * Title of the page */ title: 'ThemingSto.re - Browse Templates', /** * value of the stalker position on the screen */ baseStalkerScroll: 0, /** * the products to display */ products: null, /** * filtered collection */ filteredCollection: false, /** * this variable tells the class if the products are usable */ productsReady: false, /** * basic bind of elements */ basicNavigationBind: function(){ var self = this; $('.basic_cart').unbind('click').bind("click", function(event){ window.themingStore.currentRouter.navigate("cart"); }); $('.login').unbind('click').bind("click", function(event){ window.themingStore.currentRouter.navigate("login"); }); $('.signup').unbind('click').bind("click", function(event){ window.themingStore.currentRouter.navigate("register"); }); $('.pwrfilters_indicator').unbind('click').bind('click',function(event){ event.preventDefault(); event.stopPropagation(); $('.filter_pane').animate({width: "show"}, 100, "easeOutQuad", function(){ // hide some $('.pwrfilters_indicator').hide(); $('.paginator_filtered').hide(); $('.start_here').hide(); $('.cat_buttons').hide(); $('.breadcrumb_container').show(); $('.cat_buttons_power_filters').show(); $('.button_return').unbind('click').bind('click', function(event){ $('.filter_pane').animate({width: "hide"}, 100, "easeOutQuad", function(){ // show element again $('.pwrfilters_indicator').show(); $('.paginator_filtered').show(); $('.breadcrumb_container').hide(); $('.cat_buttons_power_filters').hide(); $('.start_here').show(); $('.cat_buttons').show(); }); }); }); }); }, basicFilterManagement: function(){ this.currentFilterManager.setData(this.filter_cookie); this.currentFilterManager.processBindElements(); // listen to changes by the mediator window.themingStore.mediator.subscribe("notification:basicAlert", this.showErrorBubled, this); window.themingStore.mediator.subscribe("notification:processing", this.showProcessingAlert, this); window.themingStore.mediator.subscribe("notification:templates:refresh", this.refreshTemplates, this); window.themingStore.mediator.subscribe("notification:templates:inline_filter", this.filterTemplates, this); window.themingStore.mediator.subscribe("notification:templates:reset_collection_master", this.filterTemplates, this); window.themingStore.mediator.subscribe("notification:templates:new_elements_arrived", this.filterTemplates, this); }, filterTemplates: function(){ var self = this; var currentCollection = self.products; var basequery = ""; var _r = this.currentFilterManager.hasFirstFilterBarElements(); if(this.currentFilterManager.hasFirstFilterBarElements()){ basequery = this.currentFilterManager.getFirstFilterBarElements(); currentCollection = currentCollection.byTitleDescription(basequery); } // Power filters if (this.currentFilterManager.hasPowerFiltersApplied()) { currentCollection = currentCollection.byPowerFiltersApplied(this.currentFilterManager.getPowerFilters()); } self.filteredCollection = currentCollection; self.renderFiltered(); }, showErrorBubled: function(message){ this.showMessage(message, 'error'); }, showProcessingAlert: function(_basicObj){ if(_basicObj.flag){ //alert('processing'); }else{ //hide alert //alert('hide alert'); } }, /** * bind click on products */ bindElements: function () { $('.products-container').on('click', 'article .thumbnail', function(event){ var $container = $(this).parent(); }); }, /** * Called upon initialization (constructor ?) */ initialize: function () { _.bindAll( this, "basicNavigationBind", "showErrorBubled", "filterTemplates", "renderFiltered", "showProcessingAlert", "refreshTemplates", "renderProducts", "basicFilterManagement" ); this.currentFilterManager = new window.themingStore.managers.BrowseFilterManagerView(); var self = this; $(window).scroll(function (event){self.windowScroll(event, self)}); this.loadTemplate('browse', false, function () { self.$el.removeClass('login'); self.render(); self.basicNavigationBind(); self.basicFilterManagement(); // get the position of the stalker after the rendering process self.baseStalkerScroll = 100; // get the products to display self.products = new window.themingStore.collections.ProductCollection(); $('.products-container').html(''); self.bindElements(); self.products.reset(); self.products.fetch({ chunkArrival: function () { self.renderProducts(); }, lastChunkArrival: function () { self.productsReady = true; } }); }); window.themingStore.views.AbstractView.prototype.initialize.call(this); }, /** * */ refreshTemplates: function(){ var self = this; var _filters = self.currentFilterManager.getCurrentFilter(); $('.products-container').html(''); self.products.reset(); self.products.fetch({ data:_filters, chunkArrival: function () { self.renderProducts(); }, lastChunkArrival: function () { self.productsReady = true; } }); }, /** * renders the default view, this loads the main layout */ render: function () { var categories = this.currentFilterManager.getCategories(); var browsers = this.currentFilterManager.getBrowsers(); this.$el.html(this.renderTemplate('#browsePage', {'categories': categories, 'browsers': browsers} )); }, /** * hander when the user clicks any filter */ filterClicked: function (event){ /** * this private method extracts the filter from the classes of the object * @param classes * @return string | null */ var extractFilterClass = function (classes) { classes = classes.split(' '); for (var i = 0; i < classes.length; i++) { if (classes[i].match(/f\-[a-z]{2,}/)) { return classes[i].replace(/^f\-/, ''); } } return null; }; if (this.productsReady) { // only proceed if we have the products loaded var $filter = $(event.target); var classes = $filter.attr('class'); var filter = extractFilterClass(classes); if (filter) { if (this.filterApplied == filter && this.filterStack == 1) { this.filterStack = 2; this.products.comparator = function(product) { return -product.get(filter); }; } else { this.filterApplied = filter; this.filterStack = 1; this.products.comparator = function(product) { return product.get(filter); }; } this.products.sort(); this.renderProducts(); } } return false; }, /** * renders the products that arrived from the rest field */ renderProducts: function () { var self = this; var _showedElements = $('article.product').map(function () { return parseInt($(this).attr('class').replace("product template_", "")); }).get(); var template = $('#browseProduct').text(); var products = ''; var counter = 0; var product = ''; var indx = ''; for (var i in this.filteredCollection.models) { product = ''; product = this.filteredCollection.models[i]; indx = product.get('id'); if(_showedElements.indexOf(indx) === -1){ products += _.template(template, product.attributes); counter++; } if(counter % 10 == 0){ counter = 0; $('.products-container').append(products); products = ''; } } if(products.length > 0){ $('.products-container').append(products); products = ''; } _showedElements = false; self.filterTemplates(); return; }, /** * renders the filtered products that arrived from the rest field */ renderFiltered: function () { var self = this; // avoid this .... $('.products-container article').hide(); for (var i in this.filteredCollection.models) { var product = this.filteredCollection.models[i]; var index = product.get('id'); $('.template_'+index).show(); } }, /** * fired when the window scrolls, handles the stalker classes * @param event * @param context */ windowScroll: function (event, context) { if ($(window).scrollTop() > context.baseStalkerScroll) { $('.stalker').addClass('detached'); } else { $('.stalker').removeClass('detached'); } } });
/* * this script opens the scorecard data, parses numbers and dates, filters by year, then iterates through each record and * creates pinwheels for the map and array, and sends data to the circular charts and bar charts */ /**** Code to open dataset and preform functions ****/ // function to create pinwheels function originalPinwheels() { // use d3 to open process and scale csv data d3.csv("data/indexData.csv", function(data) { dataset = data; //functions to parse dates and numbers to ensure these are javascript dates and numbers parseNumbers(dataset); parseDates(dataset); // pad lat/lons once padLatLons(dataset); // function to set up crossfilter dimensions // set a globa variable for crossfilter on the dataset var cf = crossfilter(dataset); var byGeoID = setupCrossfilterByGeoID(cf, dataset); var byYear = setupCrossfilterByYear(cf, dataset); // set initial year as the max year in the array to initially filter the data var year = d3.max(dataset, function(d) { return d.year; }); // filter the dataset for just this year using the filter function we created var filteredDataByYear = filterByYear(byYear, year); // get size of the dataset for determining the number of rows and columns of pinwheels var count = filteredDataByYear.length; var countPerRow = Math.ceil(count/numberOfRows); // D3 scale for the x position of pinwheel graphics var centerXScale = d3.scale.linear() .domain([1, countPerRow]) // numbers go from 1 to the number of elements per row .range([sidePadding, width-sidePadding]) // number of pixels left to right .clamp(true); // iterate through each city and plot pinwheels for each city at intervals along the chart $.each(filteredDataByYear, function( i, d ) { var city = d.geoid; // filter data to this city var filteredDataByGeoID = filterByGeoID(byGeoID, city); // clear filter for city for next one clearFilterByGeoID(byGeoID); var rowOfData = createObjectForPinwheel(filteredDataByGeoID); // for the pinwheel array: set the center for each pinwheel depending on the number shown and width and height of chart var centerX = centerXScale(city - ((Math.floor((city-1)/countPerRow)) * countPerRow)); var centerY = (Math.floor((city-1)/countPerRow) * (height/numberOfRows)) + topPadding; // set size and smallestPie for chart pinwheels var smallestPie = 10; var size = 30; createPinwheel(size, smallestPie, rowOfData, svgContainer, centerX, centerY); // clear centerX and centerY to position the pinwheels on the map centerX = 0; centerY = 0; // reset size for pinwheel and smallestPie smallestPie = 8; size = 20; // set centers of pinwheels for map centerX = projection([rowOfData.meta[0].lon, rowOfData.meta[0].lat])[0]; centerY = projection([rowOfData.meta[0].lon, rowOfData.meta[0].lat])[1]; // draw pinwheels on the map: container set up in statesPinwheel.js createPinwheel(size, smallestPie, rowOfData, svgContainerStates, centerX, centerY); }); // create initial the national level circular heat chart and table from this dataset // sort data by region var byRegion = setupCrossfilterByRegion(cf, dataset); var filteredDataByYear = orderByRegion(byRegion); // set up data to be passed to the chart var circularChartData = createObjectForCircularHeatChart(filteredDataByYear); // calculat the number of cities var numberOfCities = Object.size(circularChartData.meta); // set Detroit as the default city var city = 15; // create national level circular heat chart createNationalCircularHeatChart(svgContainerNationalCircularHeatChart, circularChartData, numberOfCities, city); // clear the year filter clearFilterByYear(byYear); /**** Pass dataset to the slider ****/ generateSlider(dataset); }); } /**** Close code to open dataset and preform functions ****/
'use strict'; /** * @ngdoc function * @name healthAnalyticsSiteApp.controller:FoodCtrl * @description * # FoodCtrl * Controller of the healthAnalyticsSiteApp */ angular.module('healthAnalyticsSiteApp') .controller('FoodCtrl', function ($scope, $stateParams, $location, AuthenticationService, FoodService) { // Types of meal $scope.mealTypes = [ {text: 'Breakfast', value: 'breakfast', id: 0}, {text: 'Lunch', value: 'lunch', id: 1}, {text: 'Dinner', value: 'dinner', id: 2}, {text: 'Snack', value: 'snack', id: 3}, {text: 'Other', value: 'other', id: 4} ]; // Types of serving $scope.servingTypes = [ {text: 'Quick Snack', value: '0.5', id: 0}, {text: 'Normal', value: '1', id: 1}, {text: 'Moderate', value: '2', id: 2}, {text: 'A Lot', value: '3', id: 3} ]; $scope.selected = {}; $scope.selected.selectedMealType = $scope.mealTypes[0]; // Default to 'Breakfast' $scope.selected.selectedServingType = $scope.servingTypes[1]; // Default to 'Normal' // template user food data object $scope.foodData = { food: 1, // food id meal: 'breakfast', serving: '0.5', food_timestamp: moment().toDate(), comments: null }; // Submit new user Food to server $scope.submitFood = function() { // overrite some of the foodData values $scope.foodData.food = $scope.selected.selectedFoodType.food_id; // food id $scope.foodData.meal = $scope.selected.selectedMealType.value; // meal value $scope.foodData.serving = $scope.selected.selectedServingType.value; // serving value $scope.foodData.food_timestamp = moment($scope.foodData.food_timestamp).utc().toDate(); // convert date to utc // Send to server FoodService.Create(AuthenticationService.CurrentUser().username, $scope.foodData) .then(function (response) { if (response.success) { //NEEDS CONVERSION TO ANGULAR //$ionicHistory.nextViewOptions({disableBack: true}); $location.path('app/foods'); } else { alert('Update Failed!'); } }); } // Get list of pre-defined foods. FoodService.GetFoodList().then(function (response){ if(response.success) { $scope.foods = response.data; } }); // Load the scope data before enetering the view... $scope.$on('$ionicView.beforeEnter', function(){ // Get user's list of foods FoodService.GetAll($scope.username).then(function(response) { if(response.success) { $scope.foodList = response.data; } }); }); // Refresh mechanism for pull-to-refresh $scope.doRefresh = function() { FoodService.GetAll($scope.username).then(function(response) { if(response.success) { $scope.foodList = response.data; // Stop the ion-refresher from spinning $scope.$broadcast('scroll.refreshComplete'); } }); } // Format the date using 'moment' $scope.formatDate = function(date) { if(date) { return moment(date).format('ll'); } } // Format the calories using 'moment' $scope.formatCalories = function(calories) { if(calories) { var calculatedCalories = parseFloat(calories); var value = calculatedCalories.toFixed(2) + " calories"; return value; } } });
/*globals document */ const hasDOM = typeof document !== 'undefined'; function appendContainerElement(rootElementId, id) { if (!hasDOM) { return; } const rootEl = document.querySelector(rootElementId); const modalContainerEl = document.createElement('div'); modalContainerEl.id = id; rootEl.appendChild(modalContainerEl); } export function initialize(application) { const delugeDropdown = application.delugeDropdown || {}; const dropdownContainerElId = delugeDropdown.dropdownRootElementId || 'deluge-dropdown-container'; application.register('config:deluge-dropdown-container-id', dropdownContainerElId, { instantiate: false }); application.inject('service:deluge-dropdown', 'destinationElementId', 'config:deluge-dropdown-container-id'); appendContainerElement(application.rootElement, dropdownContainerElId); } export default { name: 'add-dropdown-container', initialize };
/* global on:false */ import { AbilityChecks } from './AbilityChecks'; const abilityChecks = new AbilityChecks(); import { Actions } from './Actions'; const actions = new Actions(); import { Attacks } from './Attacks'; const attacks = new Attacks(); import { Spells } from './Spells'; const spells = new Spells(); import { Psionics } from './Psionics'; const psionics = new Psionics(); import { getSetItems, getIntValue, getAbilityMod, addArithmeticOperator, showSign, firstThree } from './utilities'; export class Abilities { updateModifier(ability) { const collectionArray = [ability, `${ability}_bonus`, `${ability}_mod`, `${ability}_mod_with_sign`, `${ability}_check_mod`, `${ability}_check_mod_formula`, `${ability}_check_bonus`, 'global_ability_bonus', 'strength_mod', 'dexterity_mod', 'jack_of_all_trades_toggle', 'jack_of_all_trades', 'remarkable_athlete_toggle', 'remarkable_athlete', 'global_check_bonus']; if (ability === 'strength' || ability === 'dexterity') { collectionArray.push('finesse_mod'); } getSetItems('abilities.updateModifier', { collectionArray, callback: (v, finalSetAttrs) => { const abilityScore = getIntValue(v[ability]); const abilityBonus = getIntValue(v[`${ability}_bonus`]); const globalAbilityBonus = v.global_ability_bonus; let abilityScoreCalc = abilityScore + abilityBonus; if (!isNaN(globalAbilityBonus)) { abilityScoreCalc += getIntValue(globalAbilityBonus); } const abilityCheckBonus = getIntValue(v[`${ability}_check_bonus`]); const abilityMod = getAbilityMod(abilityScoreCalc); let abilityCheck = abilityMod; let abilityCheckFormula = ''; if (abilityMod !== 0) { abilityCheckFormula = `${abilityMod}[${firstThree(ability)} mod with bonus]`; } if ((ability === 'strength' || ability === 'dexterity' || ability === 'constitution') && v.remarkable_athlete_toggle === '@{remarkable_athlete}') { const remarkableAthlete = getIntValue(v.remarkable_athlete); abilityCheck += remarkableAthlete; abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, remarkableAthlete)}[remarkable athlete]`; } else if (v.jack_of_all_trades_toggle === '@{jack_of_all_trades}') { const jackOfAllTrades = getIntValue(v.jack_of_all_trades); abilityCheck += jackOfAllTrades; abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, jackOfAllTrades)}[jack of all trades]`; } if (abilityCheckBonus) { abilityCheck += abilityCheckBonus; abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, abilityCheckBonus)}[${ability} check bonus]`; } if (v.global_check_bonus) { if (!isNaN(v.global_check_bonus)) { abilityCheck += getIntValue(v.global_check_bonus); } if (abilityCheckFormula) { abilityCheckFormula += ' + '; } abilityCheckFormula += '(@{global_check_bonus})[global check bonus]'; } finalSetAttrs[`${ability}_calculated`] = abilityScoreCalc; finalSetAttrs[`${ability}_mod`] = abilityMod; finalSetAttrs[`${ability}_mod_with_sign`] = showSign(abilityMod); finalSetAttrs[`${ability}_check_mod`] = abilityCheck; finalSetAttrs[`${ability}_check_mod_with_sign`] = showSign(abilityCheck); finalSetAttrs[`${ability}_check_mod_formula`] = abilityCheckFormula; if (ability === 'strength') { finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.dexterity_mod)); } else if (ability === 'dexterity') { finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.strength_mod)); } }, }); } updateModifiers() { this.updateModifier('strength'); this.updateModifier('dexterity'); this.updateModifier('constitution'); this.updateModifier('intelligence'); this.updateModifier('wisdom'); this.updateModifier('charisma'); } setup() { on('change:jack_of_all_trades_toggle change:jack_of_all_trades change:global_ability_bonus change:global_check_bonus', () => { this.updateModifiers(); }); on('change:strength change:strength_bonus change:strength_check_mod change:strength_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => { this.updateModifier('strength'); }); on('change:dexterity change:dexterity_bonus change:dexterity_check_mod change:dexterity_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => { this.updateModifier('dexterity'); }); on('change:constitution change:constitution_bonus change:constitution_check_mod change:constitution_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => { this.updateModifier('constitution'); }); on('change:intelligence change:intelligence_bonus change:intelligence_check_mod change:intelligence_check_bonus', () => { this.updateModifier('intelligence'); }); on('change:wisdom change:wisdom_bonus change:wisdom_check_mod change:wisdom_check_bonus', () => { this.updateModifier('wisdom'); }); on('change:charisma change:charisma_bonus change:charisma_check_mod change:charisma_check_bonus', () => { this.updateModifier('charisma'); }); on('change:strength_mod change:dexterity_mod change:constitution_mod change:intelligence_mod change:wisdom_mod change:charisma_mod', () => { abilityChecks.updateSkill(); attacks.update(); spells.update(); psionics.update(); actions.updateAll(); }); } }
/* Copyright 2013, KISSY UI Library v1.40dev MIT Licensed build time: Jul 3 13:56 */ KISSY.add("json/quote",function(i){var k={"":"\\b"," ":"\\f","\n":"\\n","\r":"\\r","\t":"\\t",'"':'\\"'},f={},m=/["\b\f\n\r\t\x00-\x1f]/g,a=/\\b|\\f|\\n|\\r|\\t|\\"|\\u[0-9a-zA-Z]{4}/g;i.each(k,function(b,a){f[a]=b});f["\\/"]="/";return{quote:function(a){return'"'+a.replace(m,function(a){var b;if(!(b=k[a]))b="\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);return b})+'"'},unQuote:function(b){return b.slice(1,b.length-1).replace(a,function(a){var b;if(!(b=f[a]))b=String.fromCharCode(parseInt(a.slice(2), 16));return b})}}}); KISSY.add("json/stringify",function(i,k){function f(a){return 10>a?"0"+a:a}function m(a,b,c,e,g,h,n){var d=b[a];if(d&&"object"===typeof d)if("function"===typeof d.toJSON)d=d.toJSON(a);else if(d instanceof Date)d=isFinite(d.valueOf())?d.getUTCFullYear()+"-"+f(d.getUTCMonth()+1)+"-"+f(d.getUTCDate())+"T"+f(d.getUTCHours())+":"+f(d.getUTCMinutes())+":"+f(d.getUTCSeconds())+"Z":null;else if(d instanceof String||d instanceof Number||d instanceof Boolean)d=d.valueOf();void 0!==c&&(d=c.call(b,a,d));switch(typeof d){case "number":return isFinite(d)? ""+d:"null";case "string":return k.quote(d);case "boolean":return""+d;case "object":if(d){if(i.isArray(d)){a=d;if(i.inArray(a,h))throw new TypeError("cyclic json");h[h.length]=a;for(var b=n,n=n+g,d=[],r=a.length,l=0;l<r;){var p=m(""+l,a,c,e,g,h,n);d[d.length]=void 0===p?"null":p;++l}d.length?g?(c=d.join("\n,"+n),c="[\n"+n+c+"\n"+b+"]"):c="["+d.join(",")+"]":c="[]"}else{a=d;if(i.inArray(a,h))throw new TypeError("cyclic json");h[h.length]=a;for(var b=n,n=n+g,j,d=void 0!==e?e:i.keys(a),p=[],l=0,r=d.length;l< r;l++){j=d[l];var o=m(j,a,c,e,g,h,n);void 0!==o&&(j=k.quote(j),j+=":",g&&(j+=" "),j+=o,p[p.length]=j)}p.length?g?(c=p.join(",\n"+n),c="{\n"+n+c+"\n"+b+"}"):c="{"+p.join(",")+"}":c="{}"}h.pop();h=c}else h="null";return h}}return function(a,b,c){var e="",g,h;b&&("function"===typeof b?h=b:i.isArray(b)&&(g=b));"number"===typeof c?(c=Math.min(10,c),e=Array(c+1).join(" ")):"string"===typeof c&&(e=c.slice(0,10));return m("",{"":a},h,g,e,[],"")}},{requires:["./quote"]}); KISSY.add("json/parser",function(){var i={},k=KISSY,f=function(a){this.rules=[];k.mix(this,a);this.resetInput(this.input)};f.prototype={constructor:function(a){this.rules=[];k.mix(this,a);this.resetInput(this.input)},resetInput:function(a){k.mix(this,{input:a,matched:"",stateStack:[f.STATIC.INITIAL],match:"",text:"",firstLine:1,lineNumber:1,lastLine:1,firstColumn:1,lastColumn:1})},getCurrentRules:function(){var a=this.stateStack[this.stateStack.length-1],b=[],a=this.mapState(a);k.each(this.rules, function(c){var e=c.state||c[3];e?k.inArray(a,e)&&b.push(c):a==f.STATIC.INITIAL&&b.push(c)});return b},pushState:function(a){this.stateStack.push(a)},popState:function(){return this.stateStack.pop()},getStateStack:function(){return this.stateStack},showDebugInfo:function(){var a=f.STATIC.DEBUG_CONTEXT_LIMIT,b=this.matched,c=this.match,e=this.input,b=b.slice(0,b.length-c.length),b=(b.length>a?"...":"")+b.slice(-a).replace(/\n/," "),c=c+e,c=c.slice(0,a)+(c.length>a?"...":"");return b+c+"\n"+Array(b.length+ 1).join("-")+"^"},mapSymbol:function(a){var b=this.symbolMap;return!b?a:b[a]||(b[a]=++this.symbolId)},mapReverseSymbol:function(a){var b=this.symbolMap,c,e=this.reverseSymbolMap;if(!e&&b)for(c in e=this.reverseSymbolMap={},b)e[b[c]]=c;return e?e[a]:a},mapState:function(a){var b=this.stateMap;return!b?a:b[a]||(b[a]=++this.stateId)},lex:function(){var a=this.input,b,c,e,g=this.getCurrentRules();this.match=this.text="";if(!a)return this.mapSymbol(f.STATIC.END_TAG);for(b=0;b<g.length;b++){c=g[b];var h= c.token||c[0];e=c.action||c[2]||void 0;if(c=a.match(c.regexp||c[1])){if(b=c[0].match(/\n.*/g))this.lineNumber+=b.length;k.mix(this,{firstLine:this.lastLine,lastLine:this.lineNumber+1,firstColumn:this.lastColumn,lastColumn:b?b[b.length-1].length-1:this.lastColumn+c[0].length});b=this.match=c[0];this.matches=c;this.text=b;this.matched+=b;e=e&&e.call(this);e=void 0==e?h:this.mapSymbol(e);this.input=a=a.slice(b.length);return e?e:this.lex()}}}};f.STATIC={INITIAL:"I",DEBUG_CONTEXT_LIMIT:20,END_TAG:"$EOF"}; var m=new f({rules:[[2,/^"(\\"|\\\\|\\\/|\\b|\\f|\\n|\\r|\\t|\\u[0-9a-zA-Z]{4}|[^\\"\x00-\x1f])*"/,0],[0,/^[\t\r\n\x20]/,0],[3,/^,/,0],[4,/^:/,0],[5,/^\[/,0],[6,/^\]/,0],[7,/^\{/,0],[8,/^\}/,0],[9,/^-?\d+(?:\.\d+)?(?:e-?\d+)?/i,0],[10,/^true|false/,0],[11,/^null/,0],[12,/^./,0]]});i.lexer=m;m.symbolMap={$EOF:1,STRING:2,COMMA:3,COLON:4,LEFT_BRACKET:5,RIGHT_BRACKET:6,LEFT_BRACE:7,RIGHT_BRACE:8,NUMBER:9,BOOLEAN:10,NULL:11,INVALID:12,$START:13,json:14,value:15,object:16,array:17,elementList:18,member:19, memberList:20};i.productions=[[13,[14]],[14,[15],function(){return this.$1}],[15,[2],function(){return this.yy.unQuote(this.$1)}],[15,[9],function(){return parseFloat(this.$1)}],[15,[16],function(){return this.$1}],[15,[17],function(){return this.$1}],[15,[10],function(){return"true"===this.$1}],[15,[11],function(){return null}],[18,[15],function(){return[this.$1]}],[18,[18,3,15],function(){this.$1[this.$1.length]=this.$3;return this.$1}],[17,[5,6],function(){return[]}],[17,[5,18,6],function(){return this.$2}], [19,[2,4,15],function(){return{key:this.yy.unQuote(this.$1),value:this.$3}}],[20,[19],function(){var a={};a[this.$1.key]=this.$1.value;return a}],[20,[20,3,19],function(){this.$1[this.$3.key]=this.$3.value;return this.$1}],[16,[7,8],function(){return{}}],[16,[7,20,8],function(){return this.$2}]];i.table={gotos:{"0":{14:7,15:8,16:9,17:10},2:{15:12,16:9,17:10,18:13},3:{19:16,20:17},18:{15:23,16:9,17:10},20:{15:24,16:9,17:10},21:{19:25}},action:{"0":{2:[1,0,1],5:[1,0,2],7:[1,0,3],9:[1,0,4],10:[1,0,5], 11:[1,0,6]},1:{1:[2,2,0],3:[2,2,0],6:[2,2,0],8:[2,2,0]},2:{2:[1,0,1],5:[1,0,2],6:[1,0,11],7:[1,0,3],9:[1,0,4],10:[1,0,5],11:[1,0,6]},3:{2:[1,0,14],8:[1,0,15]},4:{1:[2,3,0],3:[2,3,0],6:[2,3,0],8:[2,3,0]},5:{1:[2,6,0],3:[2,6,0],6:[2,6,0],8:[2,6,0]},6:{1:[2,7,0],3:[2,7,0],6:[2,7,0],8:[2,7,0]},7:{1:[0,0,0]},8:{1:[2,1,0]},9:{1:[2,4,0],3:[2,4,0],6:[2,4,0],8:[2,4,0]},10:{1:[2,5,0],3:[2,5,0],6:[2,5,0],8:[2,5,0]},11:{1:[2,10,0],3:[2,10,0],6:[2,10,0],8:[2,10,0]},12:{3:[2,8,0],6:[2,8,0]},13:{3:[1,0,18],6:[1, 0,19]},14:{4:[1,0,20]},15:{1:[2,15,0],3:[2,15,0],6:[2,15,0],8:[2,15,0]},16:{3:[2,13,0],8:[2,13,0]},17:{3:[1,0,21],8:[1,0,22]},18:{2:[1,0,1],5:[1,0,2],7:[1,0,3],9:[1,0,4],10:[1,0,5],11:[1,0,6]},19:{1:[2,11,0],3:[2,11,0],6:[2,11,0],8:[2,11,0]},20:{2:[1,0,1],5:[1,0,2],7:[1,0,3],9:[1,0,4],10:[1,0,5],11:[1,0,6]},21:{2:[1,0,14]},22:{1:[2,16,0],3:[2,16,0],6:[2,16,0],8:[2,16,0]},23:{3:[2,9,0],6:[2,9,0]},24:{3:[2,12,0],8:[2,12,0]},25:{3:[2,14,0],8:[2,14,0]}}};i.parse=function(a){var b=this,c=b.lexer,e,g,h= b.table,f=h.gotos,h=h.action,d=b.productions,i=[null],l=[0];for(c.resetInput(a);;){a=l[l.length-1];e||(e=c.lex());if(!e)return!1;g=h[a]&&h[a][e];if(!g){var m=[];h[a]&&k.each(h[a],function(a,c){m.push(b.lexer.mapReverseSymbol(c))});c.showDebugInfo();m.join(", ");return!1}switch(g[0]){case 1:l.push(e);i.push(c.text);l.push(g[2]);e=null;break;case 2:var j=d[g[1]],a=j.symbol||j[0];g=j.action||j[2];var o=(j.rhs||j[1]).length,q=0,s=void 0,j=i[i.length-o];for(b.$$=j;q<o;q++)b["$"+(o-q)]=i[i.length-1-q]; g&&(s=g.call(b));j=void 0!==s?s:b.$$;o&&(l=l.slice(0,-2*o),i=i.slice(0,-1*o));l.push(a);i.push(j);l.push(f[l[l.length-2]][l[l.length-1]]);break;case 0:return j}}};return i}); KISSY.add("json/parse",function(i,k,f){function m(a,b,c){var e=a[b],g,h,f;if("object"===typeof e)if(i.isArray(e)){g=0;h=e.length;for(var d=[];g<h;)f=m(e,""+g,c),void 0!==f&&(d[d.length]=f);e=d}else{d=i.keys(e);g=0;for(h=d.length;g<h;g++){var k=d[g];f=m(e,k,c);void 0===f?delete e[k]:e[k]=f}}return c.call(a,b,e)}k.yy={unQuote:f.unQuote};return function(a,b){var c=k.parse(""+a);return b?m({"":c},"",b):c}},{requires:["./parser","./quote"]}); KISSY.add("json",function(i,k,f){return i.JSON={stringify:k,parse:f}},{requires:["./json/stringify","./json/parse"]});
function player(whichPlayer){ this.cards = []; this.spot = whichPlayer; this.state = -2; this.prevState; this.updateFunction = this.renderVisuals; //TODO: Make sure these are synced this.betThisRound = 0; //how much player has put in the pot total this betting round this.currentBet = 0; //how much the player wants to put in the pot right now this.totalBet = 0; //how much the player has put into the pot in total //defined later this.userId = null; this.money = 0; this.hand = {}; this.chipStack = {}; this.joinButton; this.name = "Unknown"; //set to 'true' first time they try to raise //so we can increment it by the minimum bet this.raised = false; } player.prototype.myCardsFriendly = function(){ var retArray = []; for(var i=0; i<this.cards.length; i++){ retArray.push(numArray[this.cards[i].number]+" of "+this.cards[i].suit); } return retArray; } player.prototype.renderVisuals = function(timeSince){ if(this.prevState !== this.state){ console.group('player'+this.spot+' moved from ', this.prevState, this.state); //state init switch(this.state){ case -3: //spot is locked //hide everything toggleVisible(this.bettingui.mesh, false); //toggleVisible(this.optionsui.mesh, false); toggleVisible(this.hand, false); toggleVisible(this.chipCount.mesh, false); toggleVisible(this.dealerChip.mesh, false); toggleVisible(this.dealerUI.mesh, false); toggleVisible(this.joinButton.mesh, false); break; case -2: this.hand = new THREE.Object3D(); //var hideButton = this.createHideButton(); //hideButton.position.z = 50; //this.hand.add(hideButton); this.chipStack = new THREE.Object3D(); this.hand.add(this.chipStack); this.chipCount = new chipCount(this); this.bettingui = new bettingUI(this); this.dealerChip = new dealerChip(this); //this.bettingui.mesh.rotation.y = -Math.PI/8; this.bettingui.mesh.rotation.x = -Math.PI/2 + Math.PI/4; this.optionsui = new optionsUI(this); this.hand.add(this.optionsui.mesh); this.hand.add(this.bettingui.mesh); //this.renderChips(); arrangeHand(this.hand, this.spot); sim.scene.add(this.hand); if(typeof this.joinButton === "undefined"){ this.joinButton = new makeJoinButton(this.spot); sim.scene.add(this.joinButton.mesh); }else{ this.joinButton.mesh.visible = true; } this.state = -1; this.renderVisuals(0); break; case -1: //no one playing if(this.money === 0){ this.money = startingMoney; } toggleVisible(this.hand, true); toggleVisible(this.dealerChip.mesh, false); toggleVisible(this.dealerUI.mesh, false); toggleVisible(this.joinButton.mesh, true); toggleVisible(this.chipCount.mesh, false); toggleVisible(this.bettingui.mesh, false); toggleVisible(this.optionsui.mesh, false); break; case 0: //someone playing, they haven't started yet //make buttons and UI toggleVisible(this.joinButton.mesh, false); toggleVisible(this.chipCount.mesh, true); this.renderChips(); var numPlayers = 0; for(var i=0; i<theGame.players.length; i++){ if(theGame.players[i].state != -1){ numPlayers++; } } if(numPlayers === 1){ //first player this.startGame = new makeStartGameButton(this); this.hand.add(this.startGame.mesh); this.startGame.mesh.position.z = 10; this.startGame.mesh.position.y -= 125; this.startGame.mesh.position.x = -50; this.startGame.mesh.rotation.y = Math.PI/8; theGame.startGameButton = this.startGame.mesh; if(this.userId !== globalUserId){ toggleVisible(theGame.startGameButton, false); }else{ toggleVisible(this.optionsui.mesh, true); } } break; case 1: toggleVisible(theGame.startGameButton, false); //give cards to player var offset = 0; for(var i=0; i<this.cards.length; i++){ //if this is the correct player, get correct card this.cards[i] = theGame.deck.getCard(this.cards[i], false, globalUserId === this.userId); //otherwise, get a blank card this.cards[i].geom.position.y += offset; giveCard(this.cards, this.hand, i); window.setTimeout((function(that){ return function(){ if(that.state === 1){ //only do this if our state hasn't been changed by an update that.state = 2; } } })(this), 4000); offset+=0.1; } this.state = 2; break; case 2: //waiting toggleVisible(this.bettingui.mesh, false); //move the cube to someone else break; case 3: //this players turn to bet //put the bet cube over this player toggleVisible(this.bettingui.mesh, true); toggleVisible(theGame.betCube, true); //make sure we have enough money if((theGame.currentBet - this.betThisRound) <= this.money){ this.currentBet = theGame.currentBet - this.betThisRound; }else{ this.currentBet = this.money; } if(this.currentBet > 0){ this.bettingui.toggleBetUI(this.bettingui.callMesh); }else{ this.bettingui.toggleBetUI(this.bettingui.betMesh); } this.raised = false; this.bettingui.updateBet(this.currentBet); this.chipCount.updateMoney(this.money); //to show the current bet amount //theGame.betCube.visible = true; theGame.betCube.position.copy(this.hand.position); theGame.betCube.position.setY(this.hand.position.y + 150); break; case 4: //folded, out for this round toggleVisible(this.bettingui.mesh, false); break; } //console.log(getSafeGameObj()); //theGame.syncInstance.update(getSafeGameObj()); //going to move this to the actual player functions, so we can be more specific about when we send things and don't send crap data. console.groupEnd(); this.prevState = this.state; } //state update for(var i=0; i<this.cards.length; i++){ if(this.cards[i].movementTween){ //this.cards[i].geom.updateBehaviors(timeSince); } } } player.prototype.chipColors = { "white": 1, "red": 5, "blue": 10, "green": 25, "black": 100 } /* white - 1 red - 5 blue - 10 green - 25 black - 100 */ player.prototype.renderChips = function(){ renderChips(this.chipStack, this.money); //Update the canvas with the new amount this.chipCount.updateMoney(this.money); this.chipStack.position.copy(tableOffset); } player.prototype.moveChipsFrom = function(amount, where){ //where is a Vector3 var trackingVector = new THREE.Vector3(); trackingVector.setFromMatrixPosition(theGame.potHolder.matrixWorld); //trackingVector.y = tableOffset.y; var toVector = new THREE.Vector3(); toVector.setFromMatrixPosition(where.matrixWorld); var theseChips = makeChipStack(amount); sim.scene.add(theseChips); theseChips.position.copy(trackingVector); var toHolderTween = new TWEEN.Tween(trackingVector).to(toVector, 2000); toHolderTween.onUpdate((function(chips){ return function(value1){ chips.position.copy(trackingVector); } }(theseChips))); toHolderTween.onComplete((function(movingChips, player){ return function(value1){ //delete the moving chips, update the world chip pot sim.scene.remove(movingChips); player.renderChips(); } }(theseChips, this))); toHolderTween.start(); renderChips(theGame.potHolder, 0); } //disabling chip animation for now until it's consistent player.prototype.moveChipsTo = function(amount, where){ //where is a Vector3 var trackingVector = new THREE.Vector3(); trackingVector.setFromMatrixPosition(this.chipStack.matrixWorld); trackingVector.y = tableOffset.y; var toVector = new THREE.Vector3(); toVector.setFromMatrixPosition(where.matrixWorld); var theseChips = makeChipStack(amount); sim.scene.add(theseChips); theseChips.position.copy(trackingVector); var toHolderTween = new TWEEN.Tween(trackingVector).to(toVector, 2000); toHolderTween.onUpdate((function(chips){ return function(value1){ //move the cards to the player chips.position.copy(trackingVector); } }(theseChips))); toHolderTween.onComplete((function(movingChips){ return function(value1){ //delete the moving chips, update the world chip pot sim.scene.remove(movingChips); makePot(); } }(theseChips))); toHolderTween.start(); } player.prototype.bet = function(amount){ //we may need to split the pot here //go through each player, find the person with the lowest money //if their money is less than the current amount //make the current betting pot the players minimum amount //take the leftover, and make a new pot; this.contributeToPot(amount); this.betThisRound += amount; this.totalBet += amount; this.money -= amount; if(theGame.minRaise < amount){ theGame.minRaise = amount; } if(this.betThisRound > theGame.currentBet){ theGame.currentBet = this.betThisRound; } } player.prototype.contributeToPot = function(amount){ var alreadyBet = this.totalBet; var potSoFar = 0; var amountToSatisfy; for(var i=theGame.bettingPots.length-1; i>=0; i--){ if(amount < 0){ debugger; return false; }else if(amount === 0){ return false; } var thisPot = theGame.bettingPots[i]; potSoFar += theGame.bettingPots[i].amountToContribute; if(thisPot.locked === true){ amountToSatisfy = potSoFar - alreadyBet; if(amountToSatisfy > 0){ thisPot.amount += amountToSatisfy; alreadyBet += amountToSatisfy; amount -= amountToSatisfy; } }else if(potSoFar >= alreadyBet){ //this is the one we need to contribute to //This number is not right var amountToRaise = (alreadyBet - potSoFar) + amount; amountToSatisfy = amount - amountToRaise; if(amountToRaise < 0){ console.log("Should not be negative!"); } console.log('raising', amountToRaise); //see if we need to preemptively split the pot var lowestPlayer = false; for(var j=0; j<theGame.players.length; j++){ var player = theGame.players[j]; if(player.state > 0 && player.state < 4 && (player.money + player.totalBet) > potSoFar){ //in the round still if(player.money < amountToRaise){ //they have less than this person is trying to raise if(lowestPlayer !== false && lowestPlayer.money < player.money){ //do nothing }else{ lowestPlayer = player; } } } } if(lowestPlayer !== false){ var minBet = potSoFar - lowestPlayer.totalBet + lowestPlayer.money; thisPot.amount += minBet + amountToSatisfy; thisPot.amountToContribute += minBet; potSoFar += minBet; alreadyBet += minBet + amountToSatisfy; theGame.newPot(); i++; amount -= (minBet + amountToSatisfy); }else{ thisPot.amount += amount; thisPot.amountToContribute += amountToRaise; amount = 0; } }else{ //we've already fulfilled this pot alreadyBet -= thisPot.amountToContribute; } } } player.prototype.betUpdate = function(amount){ /* var maxAmount = 0; for(var i=0; i<theGame.players.length; i++){ var player = theGame.players[i]; if(player.spot !== this.spot){ if(player.money > maxAmount && player.state === 2){ maxAmount = player.money; } } } if(amount > maxAmount){ amount = maxAmount; }*/ sendUpdate({i:theGame.players.indexOf(this), amount: amount}, "playerBet"); this.bet(amount); this.renderChips(); makePot(); theGame.nextBet(); } player.prototype.fold = function(){ //theGame.bettingOrder.splice(theGame.better, 1); for(var i=0; i<this.cards.length; i++){ console.log(this.cards[i]); if(this.cards[i].geom.parent.type === "Object3D"){ THREE.SceneUtils.detach(this.cards[i].geom, this.hand, sim.scene); cardToDeck(this.cards[i]); delete this.cards[i].geom; }else{ this.cards[i].geom.parent.remove(this.cards[i].geom); delete this.cards[i].geom; } } this.cards = []; this.state = 4; var potentialPlayers = []; for(var i=0; i<theGame.dealingOrder.length; i++){ if(theGame.dealingOrder[i].state > 0 && theGame.dealingOrder[i].state < 4){ potentialPlayers.push(theGame.dealingOrder[i]); } } if(potentialPlayers.length === 1){ theGame.better = 0; theGame.step = 10; if(theGame.currentAuthority === globalUserId){ setTimeout(function(){ sendUpdate({winnerByForfeit: getSafePlayer(potentialPlayers[0])}, "playerWinByForfeit", {thenUpdate: true}); theGame.runStep(); }, 0); } }else{ if(_checkForDoneBetting()){ //do nothing, wait for authority to tell us what to do next }else{ theGame.nextBet(); } } } player.prototype.foldUpdate = function(){ sendUpdate({i:theGame.players.indexOf(this)}, "playerFold"); this.fold(); }
import { hooks } from 'botframework-webchat-api'; import PropTypes from 'prop-types'; import React, { useCallback } from 'react'; import InlineMarkdown from '../../../Utils/InlineMarkdown'; const { useLocalizer } = hooks; const MARKDOWN_REFERENCES = ['RETRY']; const SendFailedRetry = ({ onRetryClick }) => { const handleReference = useCallback(({ data }) => data === 'RETRY' && onRetryClick(), [onRetryClick]); const localize = useLocalizer(); const sendFailedText = localize('ACTIVITY_STATUS_SEND_FAILED_RETRY'); return ( <InlineMarkdown onReference={handleReference} references={MARKDOWN_REFERENCES}> {sendFailedText} </InlineMarkdown> ); }; SendFailedRetry.propTypes = { onRetryClick: PropTypes.func.isRequired }; export default SendFailedRetry;
require('../build/classes/test/keuix-browser-test');
// this is a lazy load controller, // so start with "app." to register this controller define(['app', 'angular'], function(app, angular) { app.filter('propsFilter', function() { return function(items, props) { var out = []; if (angular.isArray(items)) { items.forEach(function(item) { var itemMatches = false; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; }) app.controller('SelectCtrl', function($scope, $http, $timeout) { $scope.disabled = undefined; $scope.searchEnabled = undefined; $scope.enable = function() { $scope.disabled = false; }; $scope.disable = function() { $scope.disabled = true; }; $scope.enableSearch = function() { $scope.searchEnabled = true; } $scope.disableSearch = function() { $scope.searchEnabled = false; } $scope.clear = function() { $scope.person.selected = undefined; $scope.address.selected = undefined; $scope.country.selected = undefined; }; $scope.someGroupFn = function (item){ if (item.name[0] >= 'A' && item.name[0] <= 'M') return 'From A - M'; if (item.name[0] >= 'N' && item.name[0] <= 'Z') return 'From N - Z'; }; $scope.personAsync = {selected : "wladimir@email.com"}; $scope.peopleAsync = []; $timeout(function(){ $scope.peopleAsync = [ { name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States' }, { name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina' }, { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' }, { name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador' }, { name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador' }, { name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States' }, { name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia' }, { name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador' }, { name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia' }, { name: 'Nicolás', email: 'nicole@email.com', age: 43, country: 'Colombia' } ]; },3000); $scope.counter = 0; $scope.someFunction = function (item, model){ $scope.counter++; $scope.eventResult = {item: item, model: model}; }; $scope.removed = function (item, model) { $scope.lastRemoved = { item: item, model: model }; }; $scope.person = {}; $scope.people = [ { name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States' }, { name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina' }, { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' }, { name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador' }, { name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador' }, { name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States' }, { name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia' }, { name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador' }, { name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia' }, { name: 'Nicolás', email: 'nicolas@email.com', age: 43, country: 'Colombia' } ]; $scope.availableColors = ['Red','Green','Blue','Yellow','Magenta','Maroon','Umbra','Turquoise']; $scope.multipleDemo = {}; $scope.multipleDemo.colors = ['Blue','Red']; $scope.multipleDemo.selectedPeople = [$scope.people[5], $scope.people[4]]; $scope.multipleDemo.selectedPeopleWithGroupBy = [$scope.people[8], $scope.people[6]]; $scope.multipleDemo.selectedPeopleSimple = ['samantha@email.com','wladimir@email.com']; $scope.address = {}; $scope.refreshAddresses = function(address) { var params = {address: address, sensor: false}; return $http.get( 'http://maps.googleapis.com/maps/api/geocode/json', {params: params} ).then(function(response) { $scope.addresses = response.data.results; }); }; $scope.country = {}; $scope.countries = [ // Taken from https://gist.github.com/unceus/6501985 {name: 'Afghanistan', code: 'AF'}, {name: 'Åland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'}, {name: 'Algeria', code: 'DZ'}, {name: 'American Samoa', code: 'AS'}, {name: 'Andorra', code: 'AD'}, {name: 'Angola', code: 'AO'}, {name: 'Anguilla', code: 'AI'}, {name: 'Antarctica', code: 'AQ'}, {name: 'Antigua and Barbuda', code: 'AG'}, {name: 'Argentina', code: 'AR'}, {name: 'Armenia', code: 'AM'}, {name: 'Aruba', code: 'AW'}, {name: 'Australia', code: 'AU'}, {name: 'Austria', code: 'AT'}, {name: 'Azerbaijan', code: 'AZ'}, {name: 'Bahamas', code: 'BS'}, {name: 'Bahrain', code: 'BH'}, {name: 'Bangladesh', code: 'BD'}, {name: 'Barbados', code: 'BB'}, {name: 'Belarus', code: 'BY'}, {name: 'Belgium', code: 'BE'}, {name: 'Belize', code: 'BZ'}, {name: 'Benin', code: 'BJ'}, {name: 'Bermuda', code: 'BM'}, {name: 'Bhutan', code: 'BT'}, {name: 'Bolivia', code: 'BO'}, {name: 'Bosnia and Herzegovina', code: 'BA'}, {name: 'Botswana', code: 'BW'}, {name: 'Bouvet Island', code: 'BV'}, {name: 'Brazil', code: 'BR'}, {name: 'British Indian Ocean Territory', code: 'IO'}, {name: 'Brunei Darussalam', code: 'BN'}, {name: 'Bulgaria', code: 'BG'}, {name: 'Burkina Faso', code: 'BF'}, {name: 'Burundi', code: 'BI'}, {name: 'Cambodia', code: 'KH'}, {name: 'Cameroon', code: 'CM'}, {name: 'Canada', code: 'CA'}, {name: 'Cape Verde', code: 'CV'}, {name: 'Cayman Islands', code: 'KY'}, {name: 'Central African Republic', code: 'CF'}, {name: 'Chad', code: 'TD'}, {name: 'Chile', code: 'CL'}, {name: 'China', code: 'CN'}, {name: 'Christmas Island', code: 'CX'}, {name: 'Cocos (Keeling) Islands', code: 'CC'}, {name: 'Colombia', code: 'CO'}, {name: 'Comoros', code: 'KM'}, {name: 'Congo', code: 'CG'}, {name: 'Congo, The Democratic Republic of the', code: 'CD'}, {name: 'Cook Islands', code: 'CK'}, {name: 'Costa Rica', code: 'CR'}, {name: 'Cote D\'Ivoire', code: 'CI'}, {name: 'Croatia', code: 'HR'}, {name: 'Cuba', code: 'CU'}, {name: 'Cyprus', code: 'CY'}, {name: 'Czech Republic', code: 'CZ'}, {name: 'Denmark', code: 'DK'}, {name: 'Djibouti', code: 'DJ'}, {name: 'Dominica', code: 'DM'}, {name: 'Dominican Republic', code: 'DO'}, {name: 'Ecuador', code: 'EC'}, {name: 'Egypt', code: 'EG'}, {name: 'El Salvador', code: 'SV'}, {name: 'Equatorial Guinea', code: 'GQ'}, {name: 'Eritrea', code: 'ER'}, {name: 'Estonia', code: 'EE'}, {name: 'Ethiopia', code: 'ET'}, {name: 'Falkland Islands (Malvinas)', code: 'FK'}, {name: 'Faroe Islands', code: 'FO'}, {name: 'Fiji', code: 'FJ'}, {name: 'Finland', code: 'FI'}, {name: 'France', code: 'FR'}, {name: 'French Guiana', code: 'GF'}, {name: 'French Polynesia', code: 'PF'}, {name: 'French Southern Territories', code: 'TF'}, {name: 'Gabon', code: 'GA'}, {name: 'Gambia', code: 'GM'}, {name: 'Georgia', code: 'GE'}, {name: 'Germany', code: 'DE'}, {name: 'Ghana', code: 'GH'}, {name: 'Gibraltar', code: 'GI'}, {name: 'Greece', code: 'GR'}, {name: 'Greenland', code: 'GL'}, {name: 'Grenada', code: 'GD'}, {name: 'Guadeloupe', code: 'GP'}, {name: 'Guam', code: 'GU'}, {name: 'Guatemala', code: 'GT'}, {name: 'Guernsey', code: 'GG'}, {name: 'Guinea', code: 'GN'}, {name: 'Guinea-Bissau', code: 'GW'}, {name: 'Guyana', code: 'GY'}, {name: 'Haiti', code: 'HT'}, {name: 'Heard Island and Mcdonald Islands', code: 'HM'}, {name: 'Holy See (Vatican City State)', code: 'VA'}, {name: 'Honduras', code: 'HN'}, {name: 'Hong Kong', code: 'HK'}, {name: 'Hungary', code: 'HU'}, {name: 'Iceland', code: 'IS'}, {name: 'India', code: 'IN'}, {name: 'Indonesia', code: 'ID'}, {name: 'Iran, Islamic Republic Of', code: 'IR'}, {name: 'Iraq', code: 'IQ'}, {name: 'Ireland', code: 'IE'}, {name: 'Isle of Man', code: 'IM'}, {name: 'Israel', code: 'IL'}, {name: 'Italy', code: 'IT'}, {name: 'Jamaica', code: 'JM'}, {name: 'Japan', code: 'JP'}, {name: 'Jersey', code: 'JE'}, {name: 'Jordan', code: 'JO'}, {name: 'Kazakhstan', code: 'KZ'}, {name: 'Kenya', code: 'KE'}, {name: 'Kiribati', code: 'KI'}, {name: 'Korea, Democratic People\'s Republic of', code: 'KP'}, {name: 'Korea, Republic of', code: 'KR'}, {name: 'Kuwait', code: 'KW'}, {name: 'Kyrgyzstan', code: 'KG'}, {name: 'Lao People\'s Democratic Republic', code: 'LA'}, {name: 'Latvia', code: 'LV'}, {name: 'Lebanon', code: 'LB'}, {name: 'Lesotho', code: 'LS'}, {name: 'Liberia', code: 'LR'}, {name: 'Libyan Arab Jamahiriya', code: 'LY'}, {name: 'Liechtenstein', code: 'LI'}, {name: 'Lithuania', code: 'LT'}, {name: 'Luxembourg', code: 'LU'}, {name: 'Macao', code: 'MO'}, {name: 'Macedonia, The Former Yugoslav Republic of', code: 'MK'}, {name: 'Madagascar', code: 'MG'}, {name: 'Malawi', code: 'MW'}, {name: 'Malaysia', code: 'MY'}, {name: 'Maldives', code: 'MV'}, {name: 'Mali', code: 'ML'}, {name: 'Malta', code: 'MT'}, {name: 'Marshall Islands', code: 'MH'}, {name: 'Martinique', code: 'MQ'}, {name: 'Mauritania', code: 'MR'}, {name: 'Mauritius', code: 'MU'}, {name: 'Mayotte', code: 'YT'}, {name: 'Mexico', code: 'MX'}, {name: 'Micronesia, Federated States of', code: 'FM'}, {name: 'Moldova, Republic of', code: 'MD'}, {name: 'Monaco', code: 'MC'}, {name: 'Mongolia', code: 'MN'}, {name: 'Montserrat', code: 'MS'}, {name: 'Morocco', code: 'MA'}, {name: 'Mozambique', code: 'MZ'}, {name: 'Myanmar', code: 'MM'}, {name: 'Namibia', code: 'NA'}, {name: 'Nauru', code: 'NR'}, {name: 'Nepal', code: 'NP'}, {name: 'Netherlands', code: 'NL'}, {name: 'Netherlands Antilles', code: 'AN'}, {name: 'New Caledonia', code: 'NC'}, {name: 'New Zealand', code: 'NZ'}, {name: 'Nicaragua', code: 'NI'}, {name: 'Niger', code: 'NE'}, {name: 'Nigeria', code: 'NG'}, {name: 'Niue', code: 'NU'}, {name: 'Norfolk Island', code: 'NF'}, {name: 'Northern Mariana Islands', code: 'MP'}, {name: 'Norway', code: 'NO'}, {name: 'Oman', code: 'OM'}, {name: 'Pakistan', code: 'PK'}, {name: 'Palau', code: 'PW'}, {name: 'Palestinian Territory, Occupied', code: 'PS'}, {name: 'Panama', code: 'PA'}, {name: 'Papua New Guinea', code: 'PG'}, {name: 'Paraguay', code: 'PY'}, {name: 'Peru', code: 'PE'}, {name: 'Philippines', code: 'PH'}, {name: 'Pitcairn', code: 'PN'}, {name: 'Poland', code: 'PL'}, {name: 'Portugal', code: 'PT'}, {name: 'Puerto Rico', code: 'PR'}, {name: 'Qatar', code: 'QA'}, {name: 'Reunion', code: 'RE'}, {name: 'Romania', code: 'RO'}, {name: 'Russian Federation', code: 'RU'}, {name: 'Rwanda', code: 'RW'}, {name: 'Saint Helena', code: 'SH'}, {name: 'Saint Kitts and Nevis', code: 'KN'}, {name: 'Saint Lucia', code: 'LC'}, {name: 'Saint Pierre and Miquelon', code: 'PM'}, {name: 'Saint Vincent and the Grenadines', code: 'VC'}, {name: 'Samoa', code: 'WS'}, {name: 'San Marino', code: 'SM'}, {name: 'Sao Tome and Principe', code: 'ST'}, {name: 'Saudi Arabia', code: 'SA'}, {name: 'Senegal', code: 'SN'}, {name: 'Serbia and Montenegro', code: 'CS'}, {name: 'Seychelles', code: 'SC'}, {name: 'Sierra Leone', code: 'SL'}, {name: 'Singapore', code: 'SG'}, {name: 'Slovakia', code: 'SK'}, {name: 'Slovenia', code: 'SI'}, {name: 'Solomon Islands', code: 'SB'}, {name: 'Somalia', code: 'SO'}, {name: 'South Africa', code: 'ZA'}, {name: 'South Georgia and the South Sandwich Islands', code: 'GS'}, {name: 'Spain', code: 'ES'}, {name: 'Sri Lanka', code: 'LK'}, {name: 'Sudan', code: 'SD'}, {name: 'Suriname', code: 'SR'}, {name: 'Svalbard and Jan Mayen', code: 'SJ'}, {name: 'Swaziland', code: 'SZ'}, {name: 'Sweden', code: 'SE'}, {name: 'Switzerland', code: 'CH'}, {name: 'Syrian Arab Republic', code: 'SY'}, {name: 'Taiwan, Province of China', code: 'TW'}, {name: 'Tajikistan', code: 'TJ'}, {name: 'Tanzania, United Republic of', code: 'TZ'}, {name: 'Thailand', code: 'TH'}, {name: 'Timor-Leste', code: 'TL'}, {name: 'Togo', code: 'TG'}, {name: 'Tokelau', code: 'TK'}, {name: 'Tonga', code: 'TO'}, {name: 'Trinidad and Tobago', code: 'TT'}, {name: 'Tunisia', code: 'TN'}, {name: 'Turkey', code: 'TR'}, {name: 'Turkmenistan', code: 'TM'}, {name: 'Turks and Caicos Islands', code: 'TC'}, {name: 'Tuvalu', code: 'TV'}, {name: 'Uganda', code: 'UG'}, {name: 'Ukraine', code: 'UA'}, {name: 'United Arab Emirates', code: 'AE'}, {name: 'United Kingdom', code: 'GB'}, {name: 'United States', code: 'US'}, {name: 'United States Minor Outlying Islands', code: 'UM'}, {name: 'Uruguay', code: 'UY'}, {name: 'Uzbekistan', code: 'UZ'}, {name: 'Vanuatu', code: 'VU'}, {name: 'Venezuela', code: 'VE'}, {name: 'Vietnam', code: 'VN'}, {name: 'Virgin Islands, British', code: 'VG'}, {name: 'Virgin Islands, U.S.', code: 'VI'}, {name: 'Wallis and Futuna', code: 'WF'}, {name: 'Western Sahara', code: 'EH'}, {name: 'Yemen', code: 'YE'}, {name: 'Zambia', code: 'ZM'}, {name: 'Zimbabwe', code: 'ZW'} ]; });});
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Projekat Schema */ var ArticleDHSchema = new Schema({ authors: { //type: [Schema.ObjectId], //ref: 'User', type: String, //required: 'Morate uneti barem jednog autora.' }, editors: { //type: [Schema.ObjectId], type: String/*, ref: 'User'*/ }, reviewers: { //type: [Schema.ObjectId], type: String/*, ref: 'User'*/ }, title: { type: String, default: '', trim: true, required: 'Morate uneti naslov.' }, abstract: { type: String, default: '', trim: true, required: 'Ovo polje je obavezno.' }, tags: { type: [Schema.ObjectId], ref: 'Tag' }, documents: { type: [Schema.ObjectId], ref: 'DocumentSch' }, comments: { type: [Schema.ObjectId], ref: 'Comment' }, grade: { type: Number, default: 1, validate: [ function(grade) { return grade && (grade < 5 && grade >0 ); }, 'Ocena ne sme biti manja od 0 i mora biti veca od 5' ] } }); /** * Validations */ ArticleDHSchema.path('authors').validate(function(authors) { return !!authors; }, 'Morate uneti barem jednog autora.'); ArticleDHSchema.path('title').validate(function(title) { return !!title; }, 'Morate uneti naslov.'); ArticleDHSchema.path('abstract').validate(function(abstract) { return !!abstract; }, 'Morate uneti abstrakt.'); /** * Statics */ ArticleDHSchema.statics.load = function(id, cb) { this.findOne({ _id: id }).exec(cb); }; mongoose.model('ArticleDH', ArticleDHSchema);
const test = require('tap').test; const fixtures = require('./fixtures'); const intlDT = require('../index'); test('get months in long words', (t) => { t.same(intlDT.months('en'), fixtures.en.monthsLong); t.end(); }); test('get months in short words', (t) => { t.same(intlDT.months('en', 'short'), fixtures.en.monthsShort); t.end(); });
define(function (require, exports) { "use strict"; // Dependencies var _ = brackets.getModule("thirdparty/lodash"); var DefaultDialogs = brackets.getModule("widgets/DefaultDialogs"); var Dialogs = brackets.getModule("widgets/Dialogs"); var FileUtils = brackets.getModule("file/FileUtils"); var Nls = require("i18n!nls/strings"); var Preferences = require("Preferences"); var Strings = brackets.getModule("strings"); var StringUtils = brackets.getModule("utils/StringUtils"); /** * @const * @private */ var _ACTION_SAVEAS = Dialogs.DIALOG_BTN_SAVE_AS; /** * @const * @private */ var _ACTION_OPEN_PREFERENCES = "open_preferences"; /** * @const * @private */ var _ACTION_SAVE_PREFERENCES = "save_preferences"; /** * @private * @type {object.<string, string>} */ var _selectors = { bottomMargin: "#docBottomMargin", content: "input[name='pdfexport-content']:checked", fontSize: "#pdfexport-fontsize", includepagenumbers: "#pdfexport-includepagenumbers", leftMargin: "#docLeftMargin", rightMargin: "#docRightMargin", topMargin: "#docTopMargin", openPdf: "#pdfexport-openpdf", syntaxHighlight: "#pdfexport-syntaxhighlight" }; /** * @private * @type {string} */ var _exportDialogTemplate = _.template(require("text!htmlContent/export-dialog.html")); /** * @private * @type {string} */ var _prefsDialogTemplate = _.template(require("text!htmlContent/prefs-dialog.html")); /** * @private * @param {!string} title * @param {!string} message * @param {?string} inputFile * @param {?string} outputFile */ function showErrorDialog(title, message, inputFile, outputFile) { return Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, title, StringUtils.format(message, inputFile, outputFile) ); } /** * @param {!string} inputFile * @return {!promise} */ function showExportDialog(inputFile) { var deferred = new $.Deferred(); var response = null; var $element, dialog; dialog = Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_INFO, StringUtils.format(Nls.DIALOG_TITLE, FileUtils.getBaseName(inputFile)), _exportDialogTemplate({ Nls: Nls, Preferences: Preferences }), [ { className: Dialogs.DIALOG_BTN_CLASS_NORMAL, id: Dialogs.DIALOG_BTN_CANCEL, text: Nls.BTN_CANCEL }, { className: Dialogs.DIALOG_BTN_CLASS_PRIMARY, id: _ACTION_SAVEAS, text: Nls.BTN_OK }, { className: Dialogs.DIALOG_BTN_CLASS_LEFT, id: _ACTION_OPEN_PREFERENCES, text: Nls.BTN_SET_DEFAULTS } ] ); dialog.getPromise().then(function (action) { $element = dialog.getElement(); if (action === _ACTION_SAVEAS) { response = { content: $element.find(_selectors.content).val(), fontSize: parseInt($element.find(_selectors.fontSize).val(), 10), margins: { bottom: parseInt($element.find(_selectors.bottomMargin).val(), 10), left: parseInt($element.find(_selectors.leftMargin).val(), 10), right: parseInt($element.find(_selectors.rightMargin).val(), 10), top: parseInt($element.find(_selectors.topMargin).val(), 10), }, includepagenumbers: $element.find(_selectors.includepagenumbers).is(":checked"), openPdf: $element.find(_selectors.openPdf).prop("checked"), syntaxHighlight: $element.find(_selectors.syntaxHighlight).is(":checked") }; } else if (action === _ACTION_OPEN_PREFERENCES) { dialog.close(); showPreferencesDialog(); } deferred.resolve(response); }); return deferred.promise(); } /** * @return {!promise} */ function showPreferencesDialog() { var dialog, $element, formField, formValue; dialog = Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_INFO, Nls.DIALOG_PREFERENCES_TITLE, _prefsDialogTemplate({ Nls: Nls, Preferences: Preferences }), [ { className: Dialogs.DIALOG_BTN_CLASS_NORMAL, id: Dialogs.DIALOG_BTN_CANCEL, text: Nls.BTN_CLOSE }, { className: Dialogs.DIALOG_BTN_CLASS_PRIMARY, id: _ACTION_SAVE_PREFERENCES, text: Nls.BTN_SAVE_DEFAULTS } ], false ); $element = dialog.getElement(); $element.one("buttonClick", function (event, action) { if (action === _ACTION_SAVE_PREFERENCES) { _selectors.content = "#rangeExport"; _.each(_selectors, function(value, index) { formField = $element.find(_selectors[index]); formValue = formField.val(); if (formField.attr("type") === "number") { formValue = parseInt(formValue, 10); } if (formField.attr("type") === "checkbox") { if (formField.is(":checked")) { formValue = 1; } else { formValue = 0; } } if (Preferences.getPreference(index) !== formValue) { Preferences.setPreference(index, formValue); console.log(Preferences.getPreference(index)); } }); dialog.close(); } else if (action === Dialogs.DIALOG_BTN_CANCEL) { dialog.close(); } }); } // Define public API exports.showErrorDialog = showErrorDialog; exports.showExportDialog = showExportDialog; exports.showPreferencesDialog = showPreferencesDialog; });
import DS from 'ember-data'; export default DS.Model.extend({ endDate: DS.attr('date') });
/** * A Node.js client for The Eye Tribe eye tracker */ module.exports = require('./lib/GazeManager');
// import Email from 'meteor/nova:email'; Telescope.createNotification = (userIds, notificationName, data) => { // if userIds is not an array, wrap it in one if (!Array.isArray(userIds)) userIds = [userIds]; userIds.forEach(userId => { const user = Users.findOne(userId); const email = Telescope.email.emails[notificationName]; const properties = email.getProperties(data); const subject = email.subject(properties); const html = Telescope.email.getTemplate(email.template)(properties); Telescope.email.buildAndSendHTML(Users.getEmail(user), subject, html); }); }; if (typeof Telescope.settings.collection !== "undefined") { Telescope.settings.collection.addField({ fieldName: 'emailNotifications', fieldSchema: { type: Boolean, optional: true, defaultValue: true, autoform: { group: 'notifications', instructions: 'Enable email notifications for new posts and new comments (requires restart).' } } }); }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), errorHandler = require('../errors.server.controller.js'), mongoose = require('mongoose'), passport = require('passport'), User = mongoose.model('User'); /** * Update user details */ exports.update = function(req, res) { // Init Variables var user = req.user; var message = null; // For security measurement we remove the roles from the req.body object delete req.body.roles; if (user) { // Merge existing user user = _.extend(user, req.body); user.updated = Date.now(); user.displayName = user.firstName + ' ' + user.lastName; user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.json(user); } }); } }); } else { res.status(400).send({ message: 'User is not signed in' }); } }; /** * Send User */ exports.me = function(req, res) { res.json(req.user || null); }; exports.duplicateEmail = function(req, res ){ var email = req.params.emailId; User.find({email: email}).exec(function(err, user) { res.json(user ); }); };
/* global _ */ (function () { 'use strict'; /* jshint ignore:start */ // Underscore's Template Module // Courtesy of underscorejs.org var _ = function (_) { f__assign(_, f__StringLiteral("defaults"), function (object) { if (f__useValue(f__not(object))) { return object; } for (var argsIndex = 1, argsLength = arguments.length; f__useValue(argsIndex < argsLength); argsIndex++) { var iterable = arguments[argsIndex]; if (f__useValue(iterable)) { for (var __fromJSForIn357 in f__getForInLoopKeyObject(iterable)) { var key;key = f__getTrackedPropertyName(iterable, __fromJSForIn357); if (f__useValue(f__doubleEqual(object[key], null))) { var key;key = f__getTrackedPropertyName(iterable, __fromJSForIn357); f__assign(object, key, iterable[key]); } } } } return object; }); // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. f__assign(_, f__StringLiteral("templateSettings"), f__makeObject([["ObjectProperty", f__StringLiteral("evaluate"), /<%([\s\S]+?)%>/g], ["ObjectProperty", f__StringLiteral("interpolate"), /<%=([\s\S]+?)%>/g], ["ObjectProperty", f__StringLiteral("escape"), /<%-([\s\S]+?)%>/g]])); // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = f__makeObject([["ObjectProperty", f__StringLiteral("'"), f__StringLiteral("'")], ["ObjectProperty", f__StringLiteral("\\"), f__StringLiteral("\\")], ["ObjectProperty", f__StringLiteral("\r"), f__StringLiteral("r")], ["ObjectProperty", f__StringLiteral("\n"), f__StringLiteral("n")], ["ObjectProperty", f__StringLiteral("\t"), f__StringLiteral("t")], ["ObjectProperty", f__StringLiteral("\u2028"), f__StringLiteral("u2028")], ["ObjectProperty", f__StringLiteral("\u2029"), f__StringLiteral("u2029")]]); var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. f__assign(_, f__StringLiteral("template"), function (text, data, settings) { var render; settings = _.defaults(f__makeObject([]), settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp(f__add([(f__useValue((f__setCachedValue(settings.escape), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : noMatch).source, (f__useValue((f__setCachedValue(settings.interpolate), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : noMatch).source, (f__useValue((f__setCachedValue(settings.evaluate), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : noMatch).source].join(f__StringLiteral("|")), f__StringLiteral("|$")), f__StringLiteral("g")); // Compile the template source, escaping string literals appropriately. var index = 0; var source = f__StringLiteral("__p+='"); text.replace(matcher, function (match, escape, interpolate, evaluate, offset) { source = f__add(source, text.slice(index, offset).replace(escaper, function (match) { return f__add(f__StringLiteral("\\"), escapes[match]); })); if (f__useValue(escape)) { source = f__add(source, f__add(f__add(f__StringLiteral("'+\n((__t=("), escape), f__StringLiteral("))==null?'':_.escape(__t))+\n'"))); } if (f__useValue(interpolate)) { source = f__add(source, f__add(f__add(f__StringLiteral("'+\n((__t=("), interpolate), f__StringLiteral("))==null?'':__t)+\n'"))); } if (f__useValue(evaluate)) { source = f__add(source, f__add(f__add(f__StringLiteral("';\n"), evaluate), f__StringLiteral("\n__p+='"))); } index = f__add(offset, match.length); return match; }); source = f__add(source, f__StringLiteral("';\n")); // If a variable is not specified, place data values in local scope. if (f__useValue(f__not(settings.variable))) source = f__add(f__add(f__StringLiteral("with(obj||{}){\n"), source), f__StringLiteral("}\n")); source = f__add(f__add(f__add(f__StringLiteral("var __t,__p='',__j=Array.prototype.join,"), f__StringLiteral("print=function(){__p+=__j.call(arguments,'');};\n")), source), f__StringLiteral("return __p;\n")); try { render = new Function(f__useValue((f__setCachedValue(settings.variable), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : f__StringLiteral("obj"), f__StringLiteral("_"), source); } catch (e) { f__assign(e, f__StringLiteral("source"), source); throw e; } if (f__useValue(data)) return render(data, _); var template = function (data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. f__assign(template, f__StringLiteral("source"), f__add(f__add(f__add(f__add(f__StringLiteral("function("), f__useValue((f__setCachedValue(settings.variable), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : f__StringLiteral("obj")), f__StringLiteral("){\n")), source), f__StringLiteral("}"))); return template; }); return _; }(f__makeObject([])); if (f__useValue(f__tripleEqual(location.hostname, f__StringLiteral("todomvc.com")))) { (function (i, s, o, g, r, a, m) { f__assign(i, f__StringLiteral("GoogleAnalyticsObject"), r);f__assign(i, r, f__useValue((f__setCachedValue(i[r]), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : function () { f__assign(i[r], f__StringLiteral("q"), f__useValue((f__setCachedValue(i[r].q), f__useValue(f__getCachedValue()))) ? f__getCachedValue() : []).push(arguments); }), f__assign(i[r], f__StringLiteral("l"), f__multiply(1, new Date()));a = s.createElement(o), m = s.getElementsByTagName(o)[0];f__assign(a, f__StringLiteral("async"), 1);f__assign(a, f__StringLiteral("src"), g);m.parentNode.insertBefore(a, m); })(window, document, f__StringLiteral("script"), f__StringLiteral("https://www.google-analytics.com/analytics.js"), f__StringLiteral("ga")); ga(f__StringLiteral("create"), f__StringLiteral("UA-31081062-1"), f__StringLiteral("auto")); ga(f__StringLiteral("send"), f__StringLiteral("pageview")); } /* jshint ignore:end */ function redirect() { if (f__useValue(f__tripleEqual(location.hostname, f__StringLiteral("tastejs.github.io")))) { f__assign(location, f__StringLiteral("href"), location.href.replace(f__StringLiteral("tastejs.github.io/todomvc"), f__StringLiteral("todomvc.com"))); } } function findRoot() { var base = location.href.indexOf(f__StringLiteral("examples/")); return location.href.substr(0, base); } function getFile(file, callback) { if (f__useValue(f__not(location.host))) { return console.info(f__StringLiteral("Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.")); } var xhr = new XMLHttpRequest(); xhr.open(f__StringLiteral("GET"), f__add(findRoot(), file), true); xhr.send(); f__assign(xhr, f__StringLiteral("onload"), function () { if (f__useValue(f__useValue((f__setCachedValue(f__tripleEqual(xhr.status, 200)), f__useValue(f__getCachedValue()))) ? callback : f__getCachedValue())) { callback(xhr.responseText); } }); } function Learn(learnJSON, config) { if (f__useValue(f__not(this instanceof Learn))) { return new Learn(learnJSON, config); } var template, framework; if (f__useValue(f__notTripleEqual(f__useValue(typeof learnJSON === "undefined") ? "undefined" : f__typeof(learnJSON), f__StringLiteral("object")))) { try { learnJSON = JSON.parse(learnJSON); } catch (e) { return; } } if (f__useValue(config)) { template = config.template; framework = config.framework; } if (f__useValue(f__useValue((f__setCachedValue(f__not(template)), f__useValue(f__getCachedValue()))) ? learnJSON.templates : f__getCachedValue())) { template = learnJSON.templates.todomvc; } if (f__useValue(f__useValue((f__setCachedValue(f__not(framework)), f__useValue(f__getCachedValue()))) ? document.querySelector(f__StringLiteral("[data-framework]")) : f__getCachedValue())) { framework = document.querySelector(f__StringLiteral("[data-framework]")).dataset.framework; } f__assign(this, f__StringLiteral("template"), template); if (f__useValue(learnJSON.backend)) { f__assign(this, f__StringLiteral("frameworkJSON"), learnJSON.backend); f__assign(this.frameworkJSON, f__StringLiteral("issueLabel"), framework); this.append(f__makeObject([["ObjectProperty", f__StringLiteral("backend"), true]])); } else if (f__useValue(learnJSON[framework])) { f__assign(this, f__StringLiteral("frameworkJSON"), learnJSON[framework]); f__assign(this.frameworkJSON, f__StringLiteral("issueLabel"), framework); this.append(); } this.fetchIssueCount(); } f__assign(Learn.prototype, f__StringLiteral("append"), function (opts) { var aside = document.createElement(f__StringLiteral("aside")); f__assign(aside, f__StringLiteral("innerHTML"), _.template(this.template, this.frameworkJSON)); f__assign(aside, f__StringLiteral("className"), f__StringLiteral("learn")); if (f__useValue(f__useValue((f__setCachedValue(opts), f__useValue(f__getCachedValue()))) ? opts.backend : f__getCachedValue())) { // Remove demo link var sourceLinks = aside.querySelector(f__StringLiteral(".source-links")); var heading = sourceLinks.firstElementChild; var sourceLink = sourceLinks.lastElementChild; // Correct link path var href = sourceLink.getAttribute(f__StringLiteral("href")); sourceLink.setAttribute(f__StringLiteral("href"), href.substr(href.lastIndexOf(f__StringLiteral("http")))); f__assign(sourceLinks, f__StringLiteral("innerHTML"), f__add(heading.outerHTML, sourceLink.outerHTML)); } else { // Localize demo links var demoLinks = aside.querySelectorAll(f__StringLiteral(".demo-link")); Array.prototype.forEach.call(demoLinks, function (demoLink) { if (f__useValue(f__notTripleEqual(demoLink.getAttribute(f__StringLiteral("href")).substr(0, 4), f__StringLiteral("http")))) { demoLink.setAttribute(f__StringLiteral("href"), f__add(findRoot(), demoLink.getAttribute(f__StringLiteral("href")))); } }); } f__assign(document.body, f__StringLiteral("className"), f__add(document.body.className, f__StringLiteral(" learn-bar")).trim()); document.body.insertAdjacentHTML(f__StringLiteral("afterBegin"), aside.outerHTML); }); f__assign(Learn.prototype, f__StringLiteral("fetchIssueCount"), function () { var issueLink = document.getElementById(f__StringLiteral("issue-count-link")); if (f__useValue(issueLink)) { var url = issueLink.href.replace(f__StringLiteral("https://github.com"), f__StringLiteral("https://api.github.com/repos")); var xhr = new XMLHttpRequest(); xhr.open(f__StringLiteral("GET"), url, true); f__assign(xhr, f__StringLiteral("onload"), function (e) { var parsedResponse = JSON.parse(e.target.responseText); if (f__useValue(parsedResponse instanceof Array)) { var count = parsedResponse.length; if (f__useValue(f__notTripleEqual(count, 0))) { f__assign(issueLink, f__StringLiteral("innerHTML"), f__add(f__add(f__StringLiteral("This app has "), count), f__StringLiteral(" open issues"))); f__assign(document.getElementById(f__StringLiteral("issue-count")).style, f__StringLiteral("display"), f__StringLiteral("inline")); } } }); xhr.send(); } }); redirect(); getFile(f__StringLiteral("learn.json"), Learn); })(); //# sourceMappingURL=base.js.map
(function() { 'use strict'; app.factory('userService', ['$http', '$window', function($http, $window) { var self = this; self.user = { userName: $window.localStorage.getItem('userName'), _id: $window.localStorage.getItem('_id'), token: $window.localStorage.getItem('token') }; function loginUser(userName, password) { return $http.post('api/login', { 'name': userName, 'password': password }); } function registerUser(userName, password, email, school, schoolAddress) { return $http.post('api/register', { 'name': userName, 'password': password, 'email': email, 'school': school, 'schoolAddress': schoolAddress }); } function setUser(data) { self.user.userName = data.name; self.user._id = data._id; self.user.token = data.token; self.user.password = null; $window.localStorage.setItem('userName', data.name); $window.localStorage.setItem('_id', data._id); $window.localStorage.setItem('token', data.token); } function getUser() { return self.user; } function logoutUser(userNama) { // remove user props for (var prop in self.user) delete self.user[prop]; $window.localStorage.clear(); } return { loginUser: loginUser, registerUser: registerUser, setUser: setUser, getUser: getUser, logoutUser: logoutUser }; }]); }());
const webpack = require('webpack'); module.exports = { devtool: 'source-map', module: { rules: [{ test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: [[ '@babel/preset-env', { targets: { browsers: [ '> 0.25%', 'not dead', ], android: 7, ios: 10, ie: 11, }, modules: false } ]] } } }] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" }) ] };
// describe('LoginFormController:', function () { // beforeEach(function () { // module('indexApp'); // }); // describe("Controller", function () { // var scope, httpBackend; // beforeEach(inject(function ($rootScope, $controller, $httpBackend) { // scope = $rootScope.$new(); // httpBackend = $httpBackend; // $controller('LoginFormController', { $scope: scope }); // })); // it("should have auth error when incorrect user data has been set", function () { // var auth = new AuthMock(httpBackend); // auth.configureFailLogin(); // scope.user = { // email: 'test@mail.com', // password: 'some_password', // rememberMe: 1 // }; // scope.login(); // httpBackend.flush(); // expect(scope.authError).toBe('Неверный логин или пароль.'); // }); // }); // });
module.exports = Snackbar; /** * Creates a snackbar component. It is possible to pass a global options object as an attribute. For public methods, see ./actions. */ function Snackbar() {} Snackbar.prototype.view = __dirname + '/views'; Snackbar.prototype.style = __dirname + '/styles'; Snackbar.prototype.name = 'snackbar'; Snackbar.prototype.components = []; require('./operations'); require('./actions'); Snackbar.prototype.init = function(model) { this.globalOptions = this.getAttribute('options'); model.set('queue', []); };