code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const auth = require('http-auth'); // const basicAuth = require('basic-auth-connect'); const apiHandler = require('./api-handler') /** * Installs routes that serve production-bundled client-side assets. * It is set up to allow for HTML5 mode routing (404 -> /dist/index.html). * This should be the last router in your express server's chain. */ console.log('running node-app-server.js'); module.exports = (app) => { const distPath = path.join(__dirname, '../dist'); const indexFileName = 'index.html'; console.log('Setting up Express'); console.log(' distPath=%s',distPath); console.log(' indexFileName=%s',indexFileName); // configure app to use bodyParser() // this will let us get the data from a POST // app.use(bodyParser.urlencoded({ extended: true })); // app.use(bodyParser.json()); // basic authentication. not production-ready // TODO: add more robust authentication after POC console.log ("__dirname = " + __dirname); var basic = auth.basic({ realm: "Project NLS.", file: __dirname + "/users.htpasswd" // username === "nielsen" && password === "W@ts0n16" } ); app.use( auth.connect(basic)); // var router = express.Router(); // middleware to use for all requests app.use(function(req, res, next) { // do logging console.log('Router request %s',req.url); next(); // make sure we go to the next routes and don't stop here }); // app.get() app.get(/localapi\/.*$/, (req, res) => apiHandler(req, res) ); app.post(/localapi\/.*$/, (req, res) => apiHandler(req, res) ); // note: this regex exludes API app.use( express.static(distPath)); app.get('*', (req, res) =>res.sendFile(path.join(distPath, indexFileName)));; }
codycoggins/angular2-starter-cody
server/node-app-server.js
JavaScript
mit
1,845
__history = [{"date":"Fri, 12 Jul 2013 08:56:55 GMT","sloc":9,"lloc":7,"functions":0,"deliveredBugs":0.05805500935039566,"maintainability":67.90674087790423,"lintErrors":3,"difficulty":5.3076923076923075}]
Schibsted-Tech-Polska/stp.project_analysis
reports/files/node_modules_mocha_node_modules_debug_example_wildcards_js/report.history.js
JavaScript
mit
205
/**! * * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ /* eslint-disable */ 'use strict'; var path = require('path'); module.exports = function configGrunt(grunt, p) { grunt.registerTask('test', []); };
nickclar/spark-js-sdk
packages/node_modules/@ciscospark/storage-adapter-spec/Gruntfile.js
JavaScript
mit
231
"use strict"; const util = require("util"); const colors = require("colors"); const consoleLog = console.log; const consoleWarn = console.warn; const consoleError = console.error; const EError = require("../eerror"); function padd(str, length = process.stdout.columns) { return str + " ".repeat(length - str.length % length); } /** * Terminal output formatter that makes output colorful and organized. */ const Formatter = module.exports = { /** * Adds tabs to the given text. * * @param {string} str * The text to tab. * @param {number} x * Amount of tabs to add. * * @returns {string} * Tabbed text. */ tab(str = "", x = 1) { let tab = " ".repeat(x); let cols = process.stdout.columns - tab.length; let match = str.match(new RegExp(`.{1,${cols}}|\n`, "g")); str = match ? match.join(tab) : str; return tab + str; }, /** * Formats given text into a heading. * * @param {string} str * The heading text. * @param {string} marker * Heading character. * @param {string} color2 * The color of the heading. */ heading(str, marker = "»".blue, color2 = "cyan") { consoleLog(); consoleLog(marker + " " + str.toUpperCase()[color2]); consoleLog(" " + "¨".repeat(process.stdout.columns - 3)[color2]); }, /** * Prints given items in list format. * * @param {Array|Object|string} items * The items to print. * @param {number} inset * The tabbing. * @param {string} color * Color of the item text. */ list(items, inset = 0, color = "green") { const insetTab = " ".repeat(inset) + "• "[color]; if (Array.isArray(items)) { items.forEach((item) => { consoleLog(this.tab(item).replace(/ /, insetTab)); }); } else if (typeof items === "object") { for (let [key, text] of Object.entries(items)) { consoleLog(insetTab + key[color]); if (typeof text !== "string") { this.list(text, (inset || 0) + 1, color); } else { consoleLog(this.tab(text, inset + 2)); } } } else if (typeof items === "string") { consoleLog(insetTab + items); } }, /** * Prints formatted errors. * * @param {Error|string} error * The error to print. */ error(error) { consoleLog(); // Handling extended errors which provided in better format error data. if (error instanceof EError) { consoleLog(); consoleLog("!! ERROR ".red + "& STACK".yellow); consoleLog(" ¨¨¨¨¨¨ ".red + "¨".yellow.repeat(process.stdout.columns - " ¨¨¨¨¨¨ ".length) + "\n"); let messageNum = 0; error.getStackedErrors().forEach((error) => { error.messages.forEach((message, i) => { console.log((i === 0 ? (" #" + (++messageNum)).red : " ") + " " + message) }); error.stacks.forEach((stack) => console.log(" • ".yellow + stack.gray)); console.log(); }); return; } // Handling for default errors. Formatter.heading("ERROR", "!!".red, "red"); if (!(error instanceof Error)) { return consoleError(error); } let firstBreak = error.message.indexOf("\n"); if (firstBreak === -1) { firstBreak = error.message.length; } let errorBody = error.message.substr(firstBreak).replace(/\n(.)/g, "\n • ".red + "$1"); consoleError(error.message.substr(0, firstBreak)); consoleError(errorBody); Formatter.heading("STACK TRACE", ">>".yellow, "yellow"); consoleError(error.stack.substr(error.stack.indexOf(" at ")).replace(/ /g, " • ".yellow)); }, /** * Prints formatted warning. * * @param {string} str * Warning text. */ warn(str) { Formatter.heading("WARNING", "!".yellow, "yellow"); consoleWarn(str); }, /** * Registers listeners for formatting text from recognized tags. */ infect() { console.log = function(str, ...args) { str = str || ""; if (typeof str === "string") { if (args) { str = util.format(str, ...args); } const headingMatch = str.match(/.{2}/); if (str.length > 2 && headingMatch[0] === "--") { Formatter.heading(str.substr(headingMatch.index + 2)); return; } } consoleLog(str); }; console.error = function(str, ...args) { str = str || ""; if (typeof str === "string" && args) { str = util.format(str, ...args); } Formatter.error(str); // Used for exit codes. Errors can specify error codes. if (str instanceof Error && Number.isInteger(str.code)) { return str.code; } // If not an error object then default to 1. return 1; }; console.warn = function(str, ...args) { str = str || ""; if (typeof str === "string" && args) { str = util.format(str, ...args); } Formatter.warn(str); }; }, };
archfz/drup
src/terminal-utils/formatter.js
JavaScript
mit
5,026
var express = require('express'); var bodyParser = require('body-parser'); var path = require('path'); var url = require('url'); var log4js = require('log4js'); var stashBoxConfig = require('./lib/config'); var pkg = require('./package.json'); var proxy = require('express-http-proxy'); var fileDriver = require('./drivers/file-driver'); var envDriver = require('./drivers/env-driver'); var mantaDriver = require('./drivers/manta-driver'); var s3compatibleDriver = require('./drivers/s3compatible-driver'); var pgkcloudDriver = require('./drivers/pkgcloud-driver'); // Process command line params // var commander = require('commander'); commander.version(pkg.version); commander.option('-p, --port <n>', 'The port on which the StashBox server will listen', parseInt); commander.option('-c, --config <value>', 'Use the specified configuration file'); commander.parse(process.argv); var overrides = {}; if (commander.port) { overrides.PORT = commander.port; } var config = stashBoxConfig.getConfig(commander.config, overrides); log4js.configure(config.get('LOG4JS_CONFIG')); var logger = log4js.getLogger("app"); logger.info("StashBox server v%s loading - %s", pkg.version, config.configDetails); var app = express(); app.use(bodyParser.raw( { type: function(type) { // This is required (setting */* doesn't work when sending client doesn't specify c/t) return true; }, verify: function(req, res, buf, encoding) { // This is a way to get a shot at the raw body (some people store it in req.rawBody for later use) } })); function handleError(req, res) { logger.error("%s error in request for: %s, details: %s", req.method, req.url, JSON.stringify(err)); res.sendStatus(500); } function handleUnsupported(driver, req, res) { if (driver) { logger.error("Unsupported method, '%s' driver doesn't support method: %s", driver.provider, req.method); } else { logger.error("Unsupported method:", req.method); } res.sendStatus(403); // Method Not Allowed } function getDriverMiddleware(driver) { return function(req, res) { logger.info("Processing %s of %s using '%s' driver", req.method, req.originalUrl, driver.provider); if (req.method === "GET") // All drivers support GET { driver.getObject(req.url, function(err, contents) { if (err) { handleError(req, res); } else if (contents === null) { // null response from driver means not found... // res.status(404).send('Not found'); } else { res.send(contents); } }); } else if (req.method === "HEAD") { if (driver.doesObjectExist) { driver.doesObjectExist(req.url, function(err, exists) { if (err) { handleError(req, res); } else { res.sendStatus(exists ? 200 : 404); } }); } else { handleUnsupported(driver, req, res); } } else if (req.method === "PUT") { if (driver.putObject) { driver.putObject(req.url, req.body, function(err) { if (err) { handleError(req, res); } else { res.sendStatus(200); } }); } else { handleUnsupported(driver, req, res); } } else if (req.method === "DELETE") { if (driver.deleteObject) { driver.deleteObject(req.url, function(err) { if (err) { handleError(req, res); } else { res.sendStatus(200); } }); } else { handleUnsupported(driver, req, res); } } else { handleUnsupported(null, req, res); } } } function addMountPoint(mount) { logger.debug("Mount point: %s, mount: %s", mount.mount, JSON.stringify(mount)); if (mount.provider === "proxy") { logger.info("Adding proxy mount for:", mount.mount); app.use(mount.mount, proxy(mount.host, { forwardPath: function(req, res) { var path = url.parse(req.url).path; logger.info("Processing proxy request for:", path); return mount.basePath + path; } })); } else { var driver; if (mount.provider === "file") { logger.info("Adding file mount for:", mount.mount); driver = new fileDriver(mount); } else if (mount.provider === "env") { logger.info("Adding env mount for:", mount.mount); driver = new envDriver(mount); } else if (mount.provider === "manta") { logger.info("Adding manta mount for:", mount.mount); driver = new mantaDriver(mount); } else if (mount.provider === "s3compatible") { logger.info("Adding S3 Compatible mount for:", mount.mount); driver = new s3compatibleDriver(mount); } else { logger.info("Adding pkgcloud mount for:", mount.mount); driver = new pgkcloudDriver(mount); } app.use(mount.mount, getDriverMiddleware(driver)); } } // We are going to apply the mounts in the order they are defined - the first qualifying mount point will be // applied, so more specific mount points should be defined before less specific ones. // // The default behavior is a file mount point on "/" pointing to "stash". // var mounts = config.get('mounts'); for (var i = 0; i < mounts.length; i++) { if (mounts[i]) { addMountPoint(mounts[i]); } } // This is our catch-all to handle requests that didn't match any mount point. We do this so we can control // the 404 response (and maybe log if desired). // app.all('*', function(req, res) { res.status(404).send('Not found'); }); app.listen(config.get('PORT'), function () { logger.info('StashBox listening on port:', this.address().port); }); process.on('SIGTERM', function () { logger.info('SIGTERM - preparing to exit.'); process.exit(); }); process.on('SIGINT', function () { logger.info('SIGINT - preparing to exit.'); process.exit(); }); process.on('exit', function (code) { logger.info('Process exiting with code:', code); });
SynchroLabs/StashBox
app.js
JavaScript
mit
7,225
// test/main.js var Parser = require('../src/markdown-parser'); var parser = new Parser(); var parserOptions = new Parser(); var assert = require("assert"); describe('tests', function() { describe('parsing', function() { it('bold', function(done) { parser.parse("**b** __b__", function(err, result) { assert.equal(result.bolds.length, 2); done(); }); }); it('code', function(done) { parser.parse("```js \n var a; \n ```", function(err, result) { assert.equal(result.codes.length, 1); done(); }); }); it('headings', function(done) { parser.parse("#header1 \n#header2", function(err, result) { assert.equal(result.headings.length, 2); done(); }); }); it('italics', function(done) { parser.parse("*iiiii*\nother\n\n *iiiii*", function(err, result) { assert.equal(result.italics.length, 2); done(); }); }); it('list', function(done) { parser.parse("- item1 \n- item2 \nother\n*item1\nitem2", function(err, result) { assert.equal(result.lists[0].length, 2); done(); }); }); it('headings', function(done) { parser.parse("#header1 \n#header2", function(err, result) { assert.equal(result.headings.length, 2); done(); }); }); it('images full no options', function(done) { parser.parse("[google](http://www.google.com)", function(err, result) { assert.equal(result.references.length, 1); done(); }); }); it('images full', function(done) { parserOptions.parse("[google](http://www.google.com)", function(err, result) { assert.equal(result.references.length, 1); done(); }); }); it('images relative', function(done) { parserOptions.options = {html_url: "https://github.com/darul75/markdown-parser"}; parserOptions.parse("[zoubida](./images/zoubida.png)", function(err, result) { assert.equal(result.references.length, 1); assert.equal(result.references[0].href, parserOptions.options.html_url+'/blob/master/images/zoubida.png'); parserOptions.options.html_url = "https://github.com/CMBJS/NodeBots"; var res = parserOptions.parse("![Alt text](poster.jpg)", function(err, result) { assert.equal(result.references.length, 1); assert.equal(result.references[0].href, parserOptions.options.html_url+'/blob/master/poster.jpg'); done(); }); }); }); it('images relative not needed', function(done) { parserOptions.options = {html_url: "https://github.com/darul75/markdown-parser"}; parserOptions.parse("[zoubida](http://www.google.com/images/zoubida.png)", function(err, result) { assert.equal(result.references.length, 1); assert.equal(result.references[0].href, 'http://www.google.com/images/zoubida.png'); done(); }); }); }); });
darul75/markdown-parser
test/main.js
JavaScript
mit
3,107
import React from "react"; import { connect } from "react-redux"; import { withRouter, Route } from "react-router"; import { Link } from "react-router-dom"; import { Entry } from "../../pages/entry"; class BlogCard extends React.Component { render() { return ( <div> <h2>{this.props.title}</h2> <p>{this.props.content}</p> <Link to={`/blog/${this.props.slug}`}>Read more..</Link> </div> ); } } export default withRouter(BlogCard);
relhtml/prologue
components/BlogCard/index.js
JavaScript
mit
481
module.exports = { stores: process.env.STORES ? process.env.STORES.split(',') : [ 'elasticsearch', 'postgresql', 'leveldb' ], postgresql: { host: process.env.POSTGRESQL_HOST || 'localhost', port: process.env.POSTGRESQL_PORT || '5432', username: process.env.POSTGRESQL_USER || 'postgres', password: process.env.POSTGRESQL_PASSWORD || 'postgres' }, elasticsearch: { hosts: [ process.env.ELASTICSEARCH_HOST || 'http://localhost:9200' ] }, level: { path: process.env.LEVEL_PATH || '/tmp/level' }, queue: { client: process.env.QUEUE_CLIENT || 'kue', kue: { port: process.env.QUEUE_KUE_PORT ? Number(process.env.QUEUE_KUE_PORT) : 3000 }, rabbitmq: { connectionString: process.env.QUEUE_RABBITMQ_CONNECTIONSTRING } }, project: { client: process.env.PROJECT_CLIENT || 'file', file: { path: process.env.PROJECT_FILE_PATH || '/tmp/dstore' } }, api: { port: (process.env.API_PORT ? Number(process.env.API_PORT) : (process.env.PORT ? process.env.PORT : 2020)) } };
trappsnl/dstore
config.js
JavaScript
mit
1,089
import React from 'react'; import { createStore } from 'redux'; import { createBrowserHistory } from 'history'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import rootReducer from '../../src/reducers'; import Routes from '../../src/Routes'; import App from '../../src/containers/App'; const configureStore = initialState => createStore( rootReducer, initialState, ); describe('Container | App', () => { it('renders Routes component', () => { const wrapper = shallow(<App history={createBrowserHistory()} store={configureStore()}/>); expect(wrapper.find(Routes)).to.have.lengthOf(1); }); });
elemus/react-redux-todo-example
test/containers/App.spec.js
JavaScript
mit
652
import appActions from './application' import todosActions from './todos' import filterActions from './filter' import commentsActions from './comments' import userActions from './user' export { appActions, todosActions, filterActions, commentsActions, userActions } export * from './application' export * from './todos' export * from './filter' export * from './comments' export * from './user'
Angarsk8/elixir-cowboy-react-spa
client/src/actions/index.js
JavaScript
mit
407
function browserSupportsHtml5HistoryApi() { return !! (history && history.replaceState && history.pushState); } $(document).ready(function() { //_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']); if(browserSupportsHtml5HistoryApi()) { var formSelector = ".current form"; initializeHistory(); var getCurrentPosition = function () { var slugArray = document.URL.split('/'); return slugArray.splice(3, slugArray.length).join('/'); }; // events // get new questions on submit $(formSelector).live('submit', function(event) { $('input[type=submit]', this).attr('disabled', 'disabled'); var form = $(this); var postData = form.serializeArray(); reloadQuestions(form.attr('action'), postData); event.preventDefault(); return false; }); // Track when a user clicks on 'Start again' link $('.start-right').live('click', function() { window._gaq && window._gaq.push(['_trackEvent', 'MS_smart_answer', getCurrentPosition(), 'Start again']); reloadQuestions($(this).attr('href')); return false; }); // Track when a user clicks on a 'Change Answer' link $('.link-right a').live('click', function() { var href = $(this).attr('href'); window._gaq && window._gaq.push(['_trackEvent', 'MS_smart_answer', href, 'Change Answer']); reloadQuestions(href); return false; }); // manage next/back by tracking popstate event window.onpopstate = function (event) { if(event.state !== null) { updateContent(event.state['html_fragment']); } else { return false; } }; } $('#current-error').focus(); // helper functions function toJsonUrl(url) { var parts = url.split('?'); var json_url = parts[0].replace(/\/$/, "") + ".json"; if (parts[1]) { json_url += "?"; json_url += parts[1]; } return window.location.protocol + "//" + window.location.host + json_url; } function fromJsonUrl(url) { return url.replace(/\.json$/, ""); } function redirectToNonAjax(url) { window.location = url; } // replace all the questions currently in the page with whatever is returned for given url function reloadQuestions(url, params) { var url = toJsonUrl(url); addLoading('<p class="next-step">Loading next step&hellip;</p>'); $.ajax(url, { type: 'GET', dataType:'json', data: params, timeout: 10000, error: function(jqXHR, textStatus, errorStr) { var paramStr = $.param(params); redirectToNonAjax(url.replace('.json', '?' + paramStr).replace('??', '?')); }, success: function(data, textStatus, jqXHR) { addToHistory(data); updateContent(data['html_fragment']); } }); } // manage the URL function addToHistory(data) { history.pushState(data, data['title'], data['url']); window._gaq && window._gaq.push(['_trackPageview', data['url']]); } // add an indicator of loading function addLoading(fragment){ $('#content .step.current') .addClass('loading') .find('form .next-question') .append(fragment); $.event.trigger('smartanswerAnswer'); }; // update the content (i.e. plonk in the html fragment) function updateContent(fragment){ $('.smart_answer #js-replaceable').html(fragment); $.event.trigger('smartanswerAnswer'); if ($(".outcome").length !== 0) { $.event.trigger('smartanswerOutcome'); } } function initializeHistory(data) { if (! browserSupportsHtml5HistoryApi() && window.location.pathname.match(/\/.*\//) ) { addToHistory({url: window.location.pathname}); } data = { html_fragment: $('.smart_answer #js-replaceable').html(), title: "Question", url: window.location.toString() }; history.replaceState(data, data['title'], data['url']); } var contentPosition = { latestQuestionTop : 0, latestQuestionIsOffScreen: function($latestQuestion) { var top_of_view = $(window).scrollTop(); this.latestQuestionTop = $latestQuestion.offset().top; return (this.latestQuestionTop < top_of_view); }, correctOffscreen: function() { $latestQuestion = $('.smart_answer .done-questions li.done:last-child'); if (!$latestQuestion.length) { $latestQuestion = $('body'); } if(this.latestQuestionIsOffScreen($latestQuestion)) { $(window).scrollTop(this.latestQuestionTop); } }, init: function() { var self = this; $(document).bind('smartanswerAnswer', function() { self.correctOffscreen(); $('.meta-wrapper').show(); }); // Show feedback form in outcomes $(document).bind('smartanswerOutcome', function() { $('.report-a-problem-container form #url').val(window.location.href); $('.meta-wrapper').show(); }); } }; contentPosition.init(); });
ministryofjustice/smart-answers
app/assets/javascripts/smart-answers.js
JavaScript
mit
4,962
Ext.define('CustomIcons.view.Main', { extend: 'Ext.tab.Panel', xtype: 'main', requires: [ 'Ext.TitleBar', 'Ext.Video' ], config: { tabBarPosition: 'bottom', items: [ { title: 'Welcome', iconCls: 'headphones', styleHtmlContent: true, scrollable: true, items: { docked: 'top', xtype: 'titlebar', title: 'Welcome to Sencha Touch 2' }, html: [ "You've just generated a new Sencha Touch 2 project. What you're looking at right now is the ", "contents of <a target='_blank' href=\"app/view/Main.js\">app/view/Main.js</a> - edit that file ", "and refresh to change what's rendered here." ].join("") }, { title: 'Get Started', iconCls: 'facebook2', items: [ { docked: 'top', xtype: 'titlebar', title: 'Getting Started' }, { xtype: 'video', url: 'http://av.vimeo.com/64284/137/87347327.mp4?token=1330978144_f9b698fea38cd408d52a2393240c896c', posterUrl: 'http://b.vimeocdn.com/ts/261/062/261062119_640.jpg' } ] } ] } });
joshuamorony/CustomIcons
app/view/Main.js
JavaScript
mit
1,564
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _index = require('../../../_lib/setUTCDay/index.js'); var _index2 = _interopRequireDefault(_index); var _index3 = require('../../../_lib/setUTCISODay/index.js'); var _index4 = _interopRequireDefault(_index3); var _index5 = require('../../../_lib/setUTCISOWeek/index.js'); var _index6 = _interopRequireDefault(_index5); var _index7 = require('../../../_lib/setUTCISOWeekYear/index.js'); var _index8 = _interopRequireDefault(_index7); var _index9 = require('../../../_lib/startOfUTCISOWeek/index.js'); var _index10 = _interopRequireDefault(_index9); var _index11 = require('../../../_lib/startOfUTCISOWeekYear/index.js'); var _index12 = _interopRequireDefault(_index11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MILLISECONDS_IN_MINUTE = 60000; function setTimeOfDay(hours, timeOfDay) { var isAM = timeOfDay === 0; if (isAM) { if (hours === 12) { return 0; } } else { if (hours !== 12) { return 12 + hours; } } return hours; } var units = { twoDigitYear: { priority: 10, set: function set(dateValues, value) { var century = Math.floor(dateValues.date.getUTCFullYear() / 100); var year = century * 100 + value; dateValues.date.setUTCFullYear(year, 0, 1); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, year: { priority: 10, set: function set(dateValues, value) { dateValues.date.setUTCFullYear(value, 0, 1); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, isoYear: { priority: 10, set: function set(dateValues, value, options) { dateValues.date = (0, _index12.default)((0, _index8.default)(dateValues.date, value, options), options); return dateValues; } }, quarter: { priority: 20, set: function set(dateValues, value) { dateValues.date.setUTCMonth((value - 1) * 3, 1); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, month: { priority: 30, set: function set(dateValues, value) { dateValues.date.setUTCMonth(value, 1); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, isoWeek: { priority: 40, set: function set(dateValues, value, options) { dateValues.date = (0, _index10.default)((0, _index6.default)(dateValues.date, value, options), options); return dateValues; } }, dayOfWeek: { priority: 50, set: function set(dateValues, value, options) { dateValues.date = (0, _index2.default)(dateValues.date, value, options); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, dayOfISOWeek: { priority: 50, set: function set(dateValues, value, options) { dateValues.date = (0, _index4.default)(dateValues.date, value, options); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, dayOfMonth: { priority: 50, set: function set(dateValues, value) { dateValues.date.setUTCDate(value); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, dayOfYear: { priority: 50, set: function set(dateValues, value) { dateValues.date.setUTCMonth(0, value); dateValues.date.setUTCHours(0, 0, 0, 0); return dateValues; } }, timeOfDay: { priority: 60, set: function set(dateValues, value, options) { dateValues.timeOfDay = value; return dateValues; } }, hours: { priority: 70, set: function set(dateValues, value, options) { dateValues.date.setUTCHours(value, 0, 0, 0); return dateValues; } }, timeOfDayHours: { priority: 70, set: function set(dateValues, value, options) { var timeOfDay = dateValues.timeOfDay; if (timeOfDay != null) { value = setTimeOfDay(value, timeOfDay); } dateValues.date.setUTCHours(value, 0, 0, 0); return dateValues; } }, minutes: { priority: 80, set: function set(dateValues, value) { dateValues.date.setUTCMinutes(value, 0, 0); return dateValues; } }, seconds: { priority: 90, set: function set(dateValues, value) { dateValues.date.setUTCSeconds(value, 0); return dateValues; } }, milliseconds: { priority: 100, set: function set(dateValues, value) { dateValues.date.setUTCMilliseconds(value); return dateValues; } }, timezone: { priority: 110, set: function set(dateValues, value) { dateValues.date = new Date(dateValues.date.getTime() - value * MILLISECONDS_IN_MINUTE); return dateValues; } }, timestamp: { priority: 120, set: function set(dateValues, value) { dateValues.date = new Date(value); return dateValues; } } }; exports.default = units; module.exports = exports['default'];
lucionei/chamadotecnico
chamadosTecnicosFinal-app/node_modules/date-fns/parse/_lib/units/index.js
JavaScript
mit
4,996
// get params function getParams() { var params = { initial_amount: parseInt($('#initial_amount').val(), 10) || 0, interest_rate_per_annum: parseFloat($('#interest_rate_per_annum').val()) / 100 || 0, monthly_amount: parseFloat($('#monthly_amount').val()), num_months: parseInt($('#num_months').val(), 10) }; params.method = $('#by_monthly_amount').is(':checked') ? 'by_monthly_amount' : 'by_num_months'; return params; } function updateUI() { var params = getParams(); var data = computeLoanData(params); updatePaymentTable(data); console.log(data); } function computeLoanData(params) { var total_paid = 0, num_months = 0, remainder = Math.floor(params.initial_amount * 100), monthly_interest_rate = params.interest_rate_per_annum / 12, monthly_amount, months = []; if (params.method == 'by_num_months') { var pow = Math.pow(1 + monthly_interest_rate, params.num_months); monthly_amount = remainder * monthly_interest_rate * pow / (pow - 1); } else { monthly_amount = params.monthly_amount * 100; } monthly_amount = Math.ceil(monthly_amount); // compute by amount first while (remainder > 0) { var interest = Math.floor(remainder * monthly_interest_rate); remainder += interest; var to_pay = remainder > monthly_amount ? monthly_amount : remainder; total_paid += to_pay; remainder -= to_pay; months.push({ interest: interest / 100, repayment: to_pay / 100, remainder: remainder / 100 }); } $('#monthly_amount').val((monthly_amount / 100).toFixed(2)); $('#num_months').val(months.length); return { total_paid: total_paid / 100, interest_paid: (total_paid - params.initial_amount * 100) / 100, months: months }; } function updatePaymentTable(data) { $('#total_repayment').text(data.total_paid.toFixed(2)); $('#total_interested_paid').text(data.interest_paid.toFixed(2)); var rows = $('#monthly_breakdown').empty(); for (var idx=0; idx < data.months.length; idx++) { var month_num = idx+1; var is_new_year = (idx % 12) === 0; var tr = $('<tr />') .append($('<td />').text(month_num)) .append($('<td />').text(data.months[idx].interest.toFixed(2))) .append($('<td />').text(data.months[idx].repayment.toFixed(2))) .append($('<td />').text(data.months[idx].remainder.toFixed(2))) .addClass(is_new_year ? 'jan' : '') .appendTo(rows); } } // initiatilize listeners $('#initial_amount').on('change', updateUI); $('#interest_rate_per_annum').on('change', updateUI); $('#monthly_amount').on('change', updateUI); $('#num_months').on('change', updateUI); $('#by_monthly_amount').on('change', updateUI); $('#by_num_months').on('change', updateUI);
timotheeg/html_loan_calculator
js/main.js
JavaScript
mit
2,663
define([ "dojo/_base/declare", "dojo/_base/fx", "dojo/_base/lang", "dojo/dom-style", "dojo/mouse", "dojo/on", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dojo/text!./templates/TGPrdItem.html", "dijit/_OnDijitClickMixin", "dijit/_WidgetsInTemplateMixin", "dijit/form/Button" ], function(declare, baseFx, lang, domStyle, mouse, on, _WidgetBase, _TemplatedMixin, template,_OnDijitClickMixin,_WidgetsInTemplateMixin,Button){ return declare([_WidgetBase, _OnDijitClickMixin,_TemplatedMixin,_WidgetsInTemplateMixin], { // Some default values for our author // These typically map to whatever you're passing to the constructor // 产品名称 rtzzhmc: "No Name", // Using require.toUrl, we can get a path to our AuthorWidget's space // and we want to have a default avatar, just in case // 产品默认图片 rimg: require.toUrl("./images/defaultAvatar.png"), // //起点金额 // code5:"", // //投资风格 // code7: "", // //收益率 // code8:"", // //产品经理 // code3:"", // //产品ID // rprid:"", // Our template - important! templateString: template, // A class to be applied to the root node in our template baseClass: "TGPrdWidget", // A reference to our background animation mouseAnim: null, // Colors for our background animation baseBackgroundColor: "#fff", // mouseBackgroundColor: "#def", postCreate: function(){ // Get a DOM node reference for the root of our widget var domNode = this.domNode; // Run any parent postCreate processes - can be done at any point this.inherited(arguments); // Set our DOM node's background color to white - // smoothes out the mouseenter/leave event animations domStyle.set(domNode, "backgroundColor", this.baseBackgroundColor); }, //设置属性 _setRimgAttr: function(imagePath) { // We only want to set it if it's a non-empty string if (imagePath != "") { // Save it on our widget instance - note that // we're using _set, to support anyone using // our widget's Watch functionality, to watch values change // this._set("avatar", imagePath); // Using our avatarNode attach point, set its src value this.imgNode.src = HTTP+imagePath; } } }); });
MingXingTeam/dojo-mobile-test
contactsList/widgets/TGPrdWidget/TGPrdWidget.js
JavaScript
mit
2,307
const { ipcRenderer, remote } = require('electron'); const mainProcess = remote.require('./main'); const currentWindow = remote.getCurrentWindow(); const $name = $('.name-input'); const $servings = $('.servings-input'); const $time = $('.time-input'); const $ingredients = $('.ingredients-input'); const $directions = $('.directions-input'); const $notes = $('.notes-input'); const $saveButton = $('.save-recipe-button'); const $seeAllButton = $('.see-all-button'); const $homeButton = $('.home-button'); const $addRecipeButton = $('.add-button'); let pageNav = (page) => { currentWindow.loadURL(`file://${__dirname}/${page}`); }; $saveButton.on('click', () => { let name = $name.val(); let servings = $servings.val(); let time = $time.val(); let ingredients = $ingredients.val(); let directions = $directions.val(); let notes = $notes.val(); let recipe = { name, servings, time, ingredients, directions, notes}; mainProcess.saveRecipe(recipe); pageNav('full-recipe.html'); }); $seeAllButton.on('click', () => { mainProcess.getRecipes(); pageNav('all-recipes.html'); }); $homeButton.on('click', () => { pageNav('index.html'); }); $addRecipeButton.on('click', () => { pageNav('add-recipe.html'); });
mjvalade/electron-recipes
app/renderer.js
JavaScript
mit
1,232
/* * Store drawing on server */ function saveDrawing() { var drawing = $('#imagePaint').wPaint('image'); var imageid = $('#imageTarget').data('imageid'); var creatormail = $('input[name=creatorMail]').val(); //Add spinning wheel var spin = $(document.createElement('div')); spin.addClass('spin'); $('#dialog-content').html(spin); $.ajax({ type: 'POST', url: 'savedrawing', dataType: 'json', data: {drawing: drawing, imageid: imageid, creatormail: creatormail}, success: function (resp) { if (resp.kind == 'success') popup("<p>Die Zeichnung wurde erfolgreich gespeichert.</p><p>Sie wird jedoch zuerst überprüft bevor sie in der Galerie zu sehen ist.</p>"); if (resp.kind == 'error') popup("<p>Die Zeichnung konnte leider nicht gespeichert werden.</p><p>Der Fehler wird untersucht.</p>"); }, fail: function() { popup("<p>Die Zeichnung konnte leider nicht gespeichert werden.</p><p>Der Fehler wird untersucht.</p>"); } }); } function saveDrawingLocal() { var imageid = $('img#imageTarget').data('imageid'); var drawingid = $('img#drawingTarget').data('drawingid'); window.location.href = 'getfile?drawingid=' + drawingid + '&imageid=' + imageid; } /* * Popup message */ function popup(message) { // get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); // calculate the values for center alignment var dialogTop = (maskHeight/2) - ($('#dialog-box').height()/2); var dialogLeft = (maskWidth/2) - ($('#dialog-box').width()/2); // assign values to the overlay and dialog box $('#dialog-overlay').css({height:maskHeight, width:maskWidth}).show(); $('#dialog-box').css({top:dialogTop, left:dialogLeft}).show(); // display the message $('#dialog-content').html(message); } $(document).ready(function() { /*********************************************** * Encrypt Email script- Please keep notice intact * Tool URL: http://www.dynamicdrive.com/emailriddler/ * **********************************************/ var emailriddlerarray=[104,111,115,116,109,97,115,116,101,114,64,109,97,99,104,100,105,101,115,116,114,97,115,115,101,98,117,110,116,46,99,111,109] var encryptedemail_id65='' //variable to contain encrypted email for (var i=0; i<emailriddlerarray.length; i++) encryptedemail_id65+=String.fromCharCode(emailriddlerarray[i]) $('#mailMaster').attr('href', 'mailto:' + encryptedemail_id65 ); var emailriddlerarray=[105,110,102,111,64,109,97,99,104,100,105,101,115,116,114,97,115,115,101,98,117,110,116,46,99,111,109] var encryptedemail_id23='' //variable to contain encrypted email for (var i=0; i<emailriddlerarray.length; i++) encryptedemail_id23+=String.fromCharCode(emailriddlerarray[i]) $('#mailInfo').attr('href', 'mailto:' + encryptedemail_id23 ); /* * Change image */ $(".imageSmallContainer").click(function(evt){ var imageid = $(this).data('imageid'); var drawingid = $(this).data('drawingid'); var ids = {imageid : imageid, drawingid : drawingid}; $.get('changeimage', ids) .done(function(data){ var imageContainer = $('#imageContainer'); //Hide all images in container imageContainer.children('.imageRegular').hide(); //Add spinning wheel var spin = $(document.createElement('div')); spin.addClass('spin'); imageContainer.prepend(spin); //Remove hidden old image $('#imageTarget').remove(); //Create new hidden image var imageNew = $(document.createElement('img')); imageNew.attr('id', 'imageTarget'); imageNew.addClass('imageRegular'); imageNew.attr('data-imageid', imageid); imageNew.data('imageid', imageid); imageNew.attr('src', data.imagefile); imageNew.css('display', 'none'); //Prepend new Image to container imageContainer.prepend(imageNew); //For Admin and Gallery also change Drawing if (typeof drawingid != 'undefined') { var drawing = $('#drawingTarget'); drawing.attr('src', data.drawingfile); drawing.attr('data-drawingid', drawingid); drawing.data('drawingid', drawingid); drawing.attr('drawingid', drawingid); } // If newImage src is loaded, remove spin and fade all imgs // Fires too early in FF imageContainer.imagesLoaded(function() { spin.remove(); imageContainer.children('.imageRegular').fadeIn(); }); }); }); /* * Change the class of moderated images */ $('.imageSmallContainerOuter input').change(function(evt){ var container = $(this).parent(); var initial = container.data('initialstate'); var checked = $(this).prop('checked'); container.removeClass('notApproved'); container.removeClass('approved'); container.removeClass('changed'); if (checked && initial == 'approved') container.addClass('approved'); else if ((checked && initial == 'notApproved') || (!checked && initial == 'approved')) container.addClass('changed'); else if (!checked && initial == 'notApproved') container.addClass('notApproved') }); $('#dialog-box .close, #dialog-overlay').click(function () { $('#dialog-overlay, #dialog-box').hide(); return false; }); $('#drawingDialogBtn').click(function(evt){ popup("<p>Aus den besten eingeschickten Zeichnungen werden Freecards gedruckt.</p> \ <p>Mit dem Klick auf den Speicherbutton erklärst du dich dafür bereit, dass dein Bild vielleicht veröffentlicht wird.</p> \ <p>Wenn du deine Email-Adresse angibst können wir dich informieren falls wir deine Zeichnung ausgewählt haben.</p> \ <input type='text' name='creatorMail' placeholder='Email Adresse'> \ <a id='drawingSaveBtn' href='javascript:saveDrawing();' class='btn'>Speichern</a>"); }); });
lukpueh/Mach-die-strasse-bunt
static/js/main.js
JavaScript
mit
6,075
'use strict' //Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer. var stage = new PIXI.Container(); var canvas = document.getElementById("game");; var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")}); var graphics = new PIXI.Graphics(); // Create or grab the application var app = app || {}; function init(){ resize(); renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} ); renderer.backgroundColor = 0x50503E; //level(); canvas.focus(); app.Game.init(renderer, window, canvas, stage); } function resize(){ var gameWidth = window.innerWidth; var gameHeight = window.innerHeight; var scaleToFitX = gameWidth / 1000; var scaleToFitY = gameHeight / 500; // Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/ var optimalRatio = Math.min(scaleToFitX, scaleToFitY); var currentScreenRatio = gameWidth / gameHeight; if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) { canvas.style.width = gameWidth + "px"; canvas.style.height = gameHeight + "px"; }else{ canvas.style.width = 1000 * optimalRatio + "px"; canvas.style.height = 500 * optimalRatio + "px"; } } //do not REMOVE /* //takes two arrays // the w_array is an array of column width values [w1, w2, w3, ...], y_array is //3d array setup as such [[row 1], [row 2], [row3]] and the rows are arrays // that contain pairs of y,l values where y is the fixed corner of the //rectangle and L is the height of the rectangle. function level(){ // drawRect( xstart, ystart, x size side, y size side) app.levelData = { w_array: [102 * 2, 102 * 2, 102 * 2, 102 * 2, 102 * 2], y_array: [ [ [0 * 2, 90 * 2], [0 * 2, 90 * 2], [0 * 2, 90 * 2], [0 * 2, 90 * 2], [0 * 2, 90 * 2], ], [ [90 * 2, 90 * 2], [90 * 2, 90 * 2], [90 * 2, 90 * 2], [90 * 2, 90 * 2], [90 * 2, 90 * 2], ], [ [180 * 2, 90 * 2], [180 * 2, 90 * 2], [180 * 2, 90 * 2], [180 * 2, 90 * 2], [180 * 2, 90 * 2], ], [ [270 * 2, 90 * 2], [270 * 2, 90 * 2], [270 * 2, 90 * 2], [270 * 2, 90 * 2], [270 * 2, 90 * 2], ] ], p_array: [ [50,50,50,50], [50,450,50,50], [920,50,50,50], [920,450,50,50], ] }; // set a fill and a line style again and draw a rectangle graphics.lineStyle(2, 0x995702, 1); graphics.beginFill(0x71FF33, 1); var x = 0; //reset the x x = 0; //post fence post for(var h = 0, hlen = app.levelData.y_array.length; h < hlen; h++){ for( var i = 0, len = app.levelData.w_array.length; i < len; i++){ //setup the y value graphics.drawRect(x, app.levelData.y_array[h][i][0], app.levelData.w_array[i], app.levelData.y_array[h][i][1]); x += app.levelData.w_array[i]; } //reset the x x = 0; } graphics.lineStyle(2, 0x3472D8, 1); graphics.beginFill(0x3472D8, 1); for(var i = 0, len = app.levelData.p_array.length; i < len; i++){ graphics.drawRect(app.levelData.p_array[i][0], app.levelData.p_array[i][1], app.levelData.p_array[i][2], app.levelData.p_array[i][3]); } stage.addChild(graphics); } // Reads in a JSON object with data function readJSONFile( filePath ){ $.getJSON( filePath, function(){} ) .done( function( data ){ console.log( "SUCCESS: File read from " + filePath ); app.levelData = data; } ) .fail( function( ){ console.log( "FAILED: File at " + filePath ); } ); } */ window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false);
Sanguinary/Poolhopper
bin/init.js
JavaScript
mit
4,385
import React, {Component} from 'react'; import {connect} from 'react-redux'; class MapFull extends Component { constructor() { super(); this.state = { htmlContent: null }; } componentDidMount() { this.getMapHtml(); } componentDidUpdate(prevProps, prevState) { if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) { this.getMapHtml(); } } getMapHtml() { const path = this.props.settings.html_url + this.props.map.filehash; fetch(path).then(response => { return response.text(); }).then(response => { this.setState({ htmlContent: response }); }); } getMarkup() { return {__html: this.state.htmlContent} } render() { return ( <div className="MapFull layoutbox"> <h3>{this.props.map.titlecache}</h3> <div id="overDiv" style={{position: 'fixed', visibility: 'hide', zIndex: 1}}></div> <div> {this.state.htmlContent ? <div> <div dangerouslySetInnerHTML={this.getMarkup()}></div> </div> : null} </div> </div> ) } } function mapStateToProps(state) { return {settings: state.settings} } export default connect(mapStateToProps)(MapFull);
howardjones/network-weathermap
websrc/cacti-user/src/components/MapFull.js
JavaScript
mit
1,270
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
positive-js/mosaic
packages/docs/karma.conf.js
JavaScript
mit
866
var f = require('fs'); var _ = require('underscore'); var r = {}; var cr = require('../config.json').resources; var k = require('../config.json').plugins; var b = require('../config.json').APIVARS.PLUGINS; var n = __dirname.replace('/autoform', b.DIR); var w = ['tokens', 'settings']; var s = ['actions', 'login', 'recover', 'register' ]; var p = './views/index/forms'; var c = function (n) { return n.replace('.jade',''); }; var j = function (props) { for (var p in props) { if(props.hasOwnProperty(p)){ if(!props[p].exclude){ r[p] = props[p]; } } } }; var init = function() { for(var i in k){ if(k.hasOwnProperty(i)){ var e = k[i]; var g = '/' + e; var a = require(n + g + b.CONFIG); j(a.resources); } } }; init(); j(r); var generator = function (cb) { var t; var x; var v; var u = _.union(Object.keys(r), Object.keys(cr)); var m = _.difference(u, w); for(var idx in r) { if (r.hasOwnProperty(idx)) { rc[idx] = r[idx]; } } if(f.existsSync(p)){ t = f.readdirSync(p); t = _.map(t, c); t = _.difference(t,s); x = _.intersection(m,t); v = _.difference(m,t); } cb({ models: m, valid: x, missing: v, resources: u, schemas: cr }); }; module.exports = generator;
obandox/JS-Xmas-Store-App-CodingClubVP
autoform/_wizard.js
JavaScript
mit
1,313
/* =========================================================== * bootstrap-modal.js v2.1 * =========================================================== * Copyright 2012 Jordan Schroter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.init(element, options); }; Modal.prototype = { constructor: Modal, init: function (element, options) { this.options = options; this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)); this.options.remote && this.$element.find('.modal-body').load(this.options.remote); var manager = typeof this.options.manager === 'function' ? this.options.manager.call(this) : this.options.manager; manager = manager.appendModal ? manager : $(manager).modalmanager().data('modalmanager'); manager.appendModal(this); }, toggle: function () { return this[!this.isShown ? 'show' : 'hide'](); }, show: function () { var e = $.Event('show'); if (this.isShown) return; this.$element.triggerHandler(e); if (e.isDefaultPrevented()) return; this.escape(); this.tab(); this.options.loading && this.loading(); }, hide: function (e) { e && e.preventDefault(); e = $.Event('hide'); this.$element.triggerHandler(e); if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false); this.isShown = false; this.escape(); this.tab(); this.isLoading && this.loading(); $(document).off('focusin.modal'); this.$element .removeClass('in') .removeClass('animated') .removeClass(this.options.attentionAnimation) .removeClass('modal-overflow') .attr('aria-hidden', true); $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal(); }, layout: function () { var prop = this.options.height ? 'height' : 'max-height', value = this.options.height || this.options.maxHeight; if (this.options.width){ this.$element.css('width', this.options.width); var that = this; this.$element.css('margin-left', function () { if (/%/ig.test(that.options.width)){ return -(parseInt(that.options.width) / 2) + '%'; } else { return -($(this).width() / 2) + 'px'; } }); } else { this.$element.css('width', ''); this.$element.css('margin-left', ''); } this.$element.find('.modal-body') .css('overflow', '') .css(prop, ''); var modalOverflow = $(window).height() - 10 < this.$element.height(); if (value){ this.$element.find('.modal-body') .css('overflow', 'auto') .css(prop, value); } if (modalOverflow || this.options.modalOverflow) { this.$element .css('margin-top', 0) .addClass('modal-overflow'); } else { this.$element .css('margin-top', 0 - this.$element.height() / 2) .removeClass('modal-overflow'); } }, tab: function () { var that = this; if (this.isShown && this.options.consumeTab) { this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) { if (e.keyCode && e.keyCode == 9){ var $next = $(this), $rollover = $(this); that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) { if (!e.shiftKey){ $next = $next.data('tabindex') < $(this).data('tabindex') ? $next = $(this) : $rollover = $(this); } else { $next = $next.data('tabindex') > $(this).data('tabindex') ? $next = $(this) : $rollover = $(this); } }); $next[0] !== $(this)[0] ? $next.focus() : $rollover.focus(); e.preventDefault(); } }); } else if (!this.isShown) { this.$element.off('keydown.tabindex.modal'); } }, escape: function () { var that = this; if (this.isShown && this.options.keyboard) { if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1); this.$element.on('keyup.dismiss.modal', function (e) { e.which == 27 && that.hide(); }); } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } }, hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end); that.hideModal(); }, 500); this.$element.one($.support.transition.end, function () { clearTimeout(timeout); that.hideModal(); }); }, hideModal: function () { this.$element .hide() .triggerHandler('hidden'); var prop = this.options.height ? 'height' : 'max-height'; var value = this.options.height || this.options.maxHeight; if (value){ this.$element.find('.modal-body') .css('overflow', '') .css(prop, ''); } }, removeLoading: function () { this.$loading.remove(); this.$loading = null; this.isLoading = false; }, loading: function (callback) { callback = callback || function () {}; var animate = this.$element.hasClass('fade') ? 'fade' : ''; if (!this.isLoading) { var doAnimate = $.support.transition && animate; this.$loading = $('<div class="loading-mask ' + animate + '">') .append(this.options.spinner) .appendTo(this.$element); if (doAnimate) this.$loading[0].offsetWidth; // force reflow this.$loading.addClass('in'); this.isLoading = true; doAnimate ? this.$loading.one($.support.transition.end, callback) : callback(); } else if (this.isLoading && this.$loading) { this.$loading.removeClass('in'); var that = this; $.support.transition && this.$element.hasClass('fade')? this.$loading.one($.support.transition.end, function () { that.removeLoading() }) : that.removeLoading(); } else if (callback) { callback(this.isLoading); } }, focus: function () { var $focusElem = this.$element.find(this.options.focusOn); $focusElem = $focusElem.length ? $focusElem : this.$element; $focusElem.focus(); }, attention: function (){ // NOTE: transitionEnd with keyframes causes odd behaviour if (this.options.attentionAnimation){ this.$element .removeClass('animated') .removeClass(this.options.attentionAnimation); var that = this; setTimeout(function () { that.$element .addClass('animated') .addClass(that.options.attentionAnimation); }, 0); } this.focus(); }, destroy: function () { var e = $.Event('destroy'); this.$element.triggerHandler(e); if (e.isDefaultPrevented()) return; this.teardown(); }, teardown: function () { if (!this.$parent.length){ this.$element.remove(); this.$element = null; return; } if (this.$parent !== this.$element.parent()){ this.$element.appendTo(this.$parent); } this.$element.off('.modal'); this.$element.removeData('modal'); this.$element .removeClass('in') .attr('aria-hidden', true); } }; /* MODAL PLUGIN DEFINITION * ======================= */ $.fn.modal = function (option, args) { return this.each(function () { var $this = $(this), data = $this.data('modal'), options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option); if (!data) $this.data('modal', (data = new Modal(this, options))); if (typeof option == 'string') data[option].apply(data, [].concat(args)); else if (options.show) data.show() }) }; $.fn.modal.defaults = { keyboard: true, backdrop: true, loading: false, show: true, width: null, height: null, maxHeight: null, modalOverflow: false, consumeTab: true, focusOn: null, replace: false, resize: false, attentionAnimation: 'shake', manager: 'body', spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>' }; $.fn.modal.Constructor = Modal; /* MODAL DATA-API * ============== */ $(function () { $(document).off('.modal').on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this), href = $this.attr('href'), $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7 option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()); e.preventDefault(); $target .modal(option) .one('hide', function () { $this.focus(); }) }); }); }(window.jQuery);
ner0tic/landmarxApp
src/Landmarx/UtilityBundle/Resources/public/js/bootstrap-modal.js
JavaScript
mit
9,265
var AWS = require('aws-sdk'); var Policy = require("./s3post").Policy; var helpers = require("./helpers"); var POLICY_FILE = "policy.json"; var schedule = require('node-schedule'); var Worker = function(sqsCommnad, s3Object, simpleData){ var queue = sqsCommnad; var s3 = s3Object; var simpleDataAuth = simpleData; var policyData = helpers.readJSONFile(POLICY_FILE); var policy = new Policy(policyData); var bucket_name = policy.getConditionValueByKey("bucket"); Worker.prototype.job = function(){ var run = schedule.scheduleJob('*/4 * * * * *', function(){ queue.recv(function(err, data){ if (err) { console.log(err); return; } console.log({Body : data.Body, MD5OfBody : data.MD5OfBody}); params = { Bucket: bucket_name, Key: data.Body } s3.getObject(params, function(err, data) { if (err) { console.log(err, err.stack); } else { var request = require('request'); var mime = require('mime'); var gm = require('gm').subClass({ imageMagick: true }); var src = 'http://s3-us-west-2.amazonaws.com/'+params.Bucket+'/'+params.Key; gm(request(src, params.Key)) .rotate('black', 15) .stream(function(err, stdout, stderr) { var buf = new Buffer(''); stdout.on('data', function(res) { buf = Buffer.concat([buf, res]); }); stdout.on('end', function(data) { var atr = { Bucket: params.Bucket, Key: params.Key, Body: buf, ACL: 'public-read', Metadata: { "username" : "Szymon Glowacki", "ip" : "192.168.1.10" } }; s3.putObject(atr, function(err, res) { console.log("done"); }); }); }); } }); }); }); } } module.exports = Worker;
GlowackiHolak/awsWorker
worker.js
JavaScript
mit
1,975
import React, { Component } from 'react' import { Form, Grid, Image, Transition } from 'shengnian-ui-react' const transitions = [ 'scale', 'fade', 'fade up', 'fade down', 'fade left', 'fade right', 'horizontal flip', 'vertical flip', 'drop', 'fly left', 'fly right', 'fly up', 'fly down', 'swing left', 'swing right', 'swing up', 'swing down', 'browse', 'browse right', 'slide down', 'slide up', 'slide right', ] const options = transitions.map(name => ({ key: name, text: name, value: name })) export default class TransitionExampleSingleExplorer extends Component { state = { animation: transitions[0], duration: 500, visible: true } handleChange = (e, { name, value }) => this.setState({ [name]: value }) handleVisibility = () => this.setState({ visible: !this.state.visible }) render() { const { animation, duration, visible } = this.state return ( <Grid columns={2}> <Grid.Column as={Form}> <Form.Select label='Choose transition' name='animation' onChange={this.handleChange} options={options} value={animation} /> <Form.Input label={`Duration: ${duration}ms `} min={100} max={2000} name='duration' onChange={this.handleChange} step={100} type='range' value={duration} /> <Form.Button content={visible ? 'Unmount' : 'Mount'} onClick={this.handleVisibility} /> </Grid.Column> <Grid.Column> <Transition.Group animation={animation} duration={duration}> {visible && <Image centered size='small' src='/assets/images/leaves/4.png' />} </Transition.Group> </Grid.Column> </Grid> ) } }
shengnian/shengnian-ui-react
docs/app/Examples/modules/Transition/Explorers/TransitionExampleGroupExplorer.js
JavaScript
mit
1,810
var Game = { map: { width: 980, height: 62 * 12 }, tiles: { size: 62, count: [100, 12] }, sprite: { 8: 'LAND_LEFT', 2: 'LAND_MID', 10: 'LAND_RIGHT', 9: 'LAND', 5: 'WATER_TOP', 12: 'WATER', 4: 'STONE_WITH_MONEY', 11: 'STONE', 6: 'CACTUS', 13: 'GRASS', 7: 'START', 1: 'END' } }; Crafty.init(Game.map.width, Game.map.height, document.getElementById('game')); Crafty.background('url(./assets/images/bg.png)'); Crafty.scene('Loading');
luin/Love-and-Peace
src/game.js
JavaScript
mit
508
'use strict'; import _ from 'lodash'; import bluebird from 'bluebird'; import fs from 'fs'; import requireDir from 'require-dir'; import Logger from '../../logger'; bluebird.promisifyAll(fs); function main() { const imports = _.chain(requireDir('./importers')) .map('default') .map((importer) => importer.run()) .value(); return Promise.all(imports); } Logger.info('base.data.imports.imports: Running...'); main() .then(() => { Logger.info('base.data.imports.imports: Done!'); process.exit(0); }) .catch((error) => { Logger.error('base.data.imports.imports:', error); process.exit(1); });
mehmetbajin/gt-course-surveys
server/src/server/base/data/imports/imports.js
JavaScript
mit
635
Ext.define('Category.view.GenericList', { extend: 'Ext.grid.Panel', alias: 'widget.genericlist', store: 'Generic', title: Raptor.getTag('category_header'), iconCls:'', initComponent: function() { this.columns = [{ header:Raptor.getTag('category_name'), dataIndex: 'name', flex: 1 }]; this.dockedItems = [{ dock: 'top', xtype: 'toolbar', items: [{ xtype: 'button', text: Raptor.getTag('add'), privilegeName:'insert', action:'addAction', iconCls:'icon-add' },{ xtype: 'button', text: Raptor.getTag('edit'), disabled:true, privilegeName:'edit/:id', action:'editAction', iconCls:'icon-edit' },{ xtype: 'button', text: Raptor.getTag('delete'), disabled:true, privilegeName:'delete/:id', action:'deleteAction', iconCls:'icon-del' }] }]; this.callParent(); } });
williamamed/Raptor.js
@raptorjs-production/troodon/Resources/category/js/app/view/GenericList.js
JavaScript
mit
1,321
var searchData= [ ['nalloc',['NALLOC',['../dwarfDbgInt_8h.html#a30e913ccf93d7ea095a144407af0f9a5',1,'dwarfDbgInt.h']]], ['name',['name',['../structattrValues.html#ac7cb0154aaced069f3b1d24a4b40bf26',1,'attrValues']]], ['nextcompileunitoffset',['nextCompileUnitOffset',['../structcompileUnit.html#a1f5c469b922f6fcfe3abe6b5dd983495',1,'compileUnit']]], ['numaddchild',['numAddChild',['../dwarfDbgGetDbgInfo_8c.html#a6620daa01bc49c37e1850f9101cd240b',1,'dwarfDbgGetDbgInfo.c']]], ['numaddsibling',['numAddSibling',['../dwarfDbgGetDbgInfo_8c.html#a5f08554c0dc92b8611b48e024e84c7d5',1,'dwarfDbgGetDbgInfo.c']]], ['numattr',['numAttr',['../structdieInfo.html#aa7815765cabb001eff45e8d908b733ff',1,'dieInfo']]], ['numattrstr',['numAttrStr',['../structdwarfDbgCompileUnitInfo.html#a3f9747b4bf3a3c420e2b9658f1e3face',1,'dwarfDbgCompileUnitInfo']]], ['numchildren',['numChildren',['../structdieAndChildrenInfo.html#a280ccfdcd796e9b7bd7fb365a02ac281',1,'dieAndChildrenInfo']]], ['numciefde',['numCieFde',['../structframeInfo.html#a9bc9dfa7dfbe5161b9454c22803336ec',1,'frameInfo']]], ['numcompileunit',['numCompileUnit',['../structdwarfDbgCompileUnitInfo.html#a24a90186d262c29e8f3aec7816eb0692',1,'dwarfDbgCompileUnitInfo']]], ['numdieandchildren',['numDieAndChildren',['../structcompileUnit.html#a2d3ebcbf3cef4a2a1b777411fa12ad1e',1,'compileUnit']]], ['numdies',['numDies',['../dwarfDbgGetDbgInfo_8c.html#acc7b29b6d4c897948ace423095d48374',1,'dwarfDbgGetDbgInfo.c']]], ['numdirname',['numDirName',['../structdirNamesInfo.html#a36bc650195a2492fdc4ce208ee2fc9b1',1,'dirNamesInfo']]], ['numdwarraytype',['numDwArrayType',['../structdwarfDbgTypeInfo.html#a4731409d5947b1ace3cb0e6d22c82085',1,'dwarfDbgTypeInfo']]], ['numdwbasetype',['numDwBaseType',['../structdwarfDbgTypeInfo.html#a99d053257682ec963ca7ba41febee943',1,'dwarfDbgTypeInfo']]], ['numdwconsttype',['numDwConstType',['../structdwarfDbgTypeInfo.html#a9073033a9af6498d353d3074fcd6e776',1,'dwarfDbgTypeInfo']]], ['numdwenumerationtype',['numDwEnumerationType',['../structdwarfDbgTypeInfo.html#a0c3c6e13970688bc030fcc0ab03be937',1,'dwarfDbgTypeInfo']]], ['numdwenumeratortype',['numDwEnumeratorType',['../structdwarfDbgTypeInfo.html#a131bebca9296b13ae01bee9091a47e87',1,'dwarfDbgTypeInfo']]], ['numdwmember',['numDwMember',['../structdwarfDbgTypeInfo.html#a0c32301131e1174173a6687c7643ee25',1,'dwarfDbgTypeInfo']]], ['numdwpointertype',['numDwPointerType',['../structdwarfDbgTypeInfo.html#a317ed6269cb72dd3b7027e75de016d41',1,'dwarfDbgTypeInfo']]], ['numdwstructuretype',['numDwStructureType',['../structdwarfDbgTypeInfo.html#a225af72daa609f73f608df45c7690a6b',1,'dwarfDbgTypeInfo']]], ['numdwsubroutinetype',['numDwSubroutineType',['../structdwarfDbgTypeInfo.html#a2ba56760d9d3697582e6fb77abbb38e3',1,'dwarfDbgTypeInfo']]], ['numdwtypedef',['numDwTypeDef',['../structdwarfDbgTypeInfo.html#a1b78f04c8216ec36e16296c78d35abdb',1,'dwarfDbgTypeInfo']]], ['numdwuniontype',['numDwUnionType',['../structdwarfDbgTypeInfo.html#a3c34aae02d2c0125e9e1eee64247f6c9',1,'dwarfDbgTypeInfo']]], ['numdwvolatiletype',['numDwVolatileType',['../structdwarfDbgTypeInfo.html#a4c92bb8ff7f43382caa3651465ea9d61',1,'dwarfDbgTypeInfo']]], ['numfde',['numFde',['../structcieFde.html#a080816ba7436820c85f5327f1b5f59aa',1,'cieFde::numFde()'],['../structframeInfo.html#a1dabaf73bfd8ec4e746dd8032396b3a5',1,'frameInfo::numFde()']]], ['numfileinfo',['numFileInfo',['../structcompileUnit.html#a6fb20bccb16ae86ef9b4f87dd0ed1327',1,'compileUnit']]], ['numfileline',['numFileLine',['../structfileInfo.html#a1931d7c00f70afbf960c6c4521bdcd84',1,'fileInfo']]], ['numformalparameterinfo',['numFormalParameterInfo',['../structsubProgramInfo.html#a2ccc0b535ec89eefbc9b1c8fc8fd61d0',1,'subProgramInfo']]], ['numframeregcol',['numFrameRegCol',['../structframeDataEntry.html#ad5a00c5ef02350b1e388ab26a774fa48',1,'frameDataEntry']]], ['numlocentry',['numLocEntry',['../structlocationInfo.html#a72a38f9b38b05c2278bfcb6cee811015',1,'locationInfo']]], ['numpathname',['numPathName',['../structpathNamesInfo.html#a57a942792bec3a1198db069eff6158e5',1,'pathNamesInfo']]], ['numrangeinfo',['numRangeInfo',['../structcompileUnit.html#aabfa5a93c0791354cf2357eee5e9c259',1,'compileUnit']]], ['numsiblings',['numSiblings',['../structdieAndChildrenInfo.html#a594643b40a2e2c26d4f99c990250b67b',1,'dieAndChildrenInfo::numSiblings()'],['../dwarfDbgGetDbgInfo_8c.html#ab34dbb2cc194c304000747b02081d960',1,'numSiblings():&#160;dwarfDbgGetDbgInfo.c']]], ['numsourcefile',['numSourceFile',['../structcompileUnit.html#a004d068e8e8ea12f5f5f04bea1860860',1,'compileUnit']]], ['numsubprograminfo',['numSubProgramInfo',['../structcompileUnit.html#a61551a73c12d2c6a7e2bd35037940a21',1,'compileUnit']]], ['numtypestr',['numTypeStr',['../structdwarfDbgTypeInfo.html#a954ab297265cb3b7e36f3ce5d74367c9',1,'dwarfDbgTypeInfo']]], ['numvariableinfo',['numVariableInfo',['../structsubProgramInfo.html#aee427adb0c32497900dd9eb0a00b1ac5',1,'subProgramInfo']]] ];
apwiede/nodemcu-firmware
docs/dwarfDbg/search/all_c.js
JavaScript
mit
5,000
const moment = require('moment') const expect = require('chai').expect const sinon = require('sinon') const proxyquire = require('proxyquire') const breadcrumbHelper = require('../../helpers/breadcrumb-helper') const orgUnitConstant = require('../../../app/constants/organisation-unit.js') const activeStartDate = moment('25-12-2017', 'DD-MM-YYYY').toDate() // 2017-12-25T00:00:00.000Z const activeEndDate = moment('25-12-2018', 'DD-MM-YYYY').toDate() // 2018-12-25T00:00:00.000Z const breadcrumbs = breadcrumbHelper.TEAM_BREADCRUMBS const expectedReductionExport = [ { offenderManager: 'Test_Forename Test_Surname', reason: 'Disability', amount: 5, startDate: activeStartDate, endDate: activeEndDate, status: 'ACTIVE', additionalNotes: 'New Test Note' }] let getReductionsData let exportReductionService let getBreadcrumbsStub beforeEach(function () { getReductionsData = sinon.stub() getBreadcrumbsStub = sinon.stub().resolves(breadcrumbs) exportReductionService = proxyquire('../../../app/services/get-reductions-export', { './data/get-reduction-notes-export': getReductionsData, './get-breadcrumbs': getBreadcrumbsStub }) }) describe('services/get-reductions-export', function () { it('should return the expected reductions exports for team level', function () { getReductionsData.resolves(expectedReductionExport) return exportReductionService(1, orgUnitConstant.TEAM.name) .then(function (result) { expect(getReductionsData.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true) expect(getBreadcrumbsStub.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true) expect(result.reductionNotes[0].offenderManager).to.be.eql(expectedReductionExport[0].offenderManager) expect(result.reductionNotes[0].reason).to.be.eql(expectedReductionExport[0].reason) expect(result.reductionNotes[0].amount).to.be.eql(expectedReductionExport[0].amount) expect(result.reductionNotes[0].startDate).to.be.eql('25 12 2017, 00:00') expect(result.reductionNotes[0].endDate).to.be.eql('25 12 2018, 00:00') expect(result.reductionNotes[0].status).to.be.eql(expectedReductionExport[0].status) expect(result.reductionNotes[0].additionalNotes).to.be.eql(expectedReductionExport[0].additionalNotes) }) }) })
ministryofjustice/wmt-web
test/unit/services/test-get-reduction-export.js
JavaScript
mit
2,361
/** * Conversion: * All dynamic tweaked dom id or class names are prefixed with 't-'. */ /** * Config */ var PRIVATE_TOKEN = 'xYDh7cpVX8BS2unon1hp'; /** * Globals. */ var autocompleteOpts, projectOpts, currentProjectID, currentProjectPath; $(function () { initGlobals(); handleAll(); mapUrlHandler(location.pathname, [ { pattern: /^\/[^\/]+\/[^\/]+$/, handle: handleProjectDashboard }, { pattern: /^.+\/tree\/.+/, handle: handleTreeView }, { pattern: /^.+\/blob\/[^\/]+\/.+\.md$/, handle: handleMdBlobView } ]); }); $(document).ajaxSuccess(function (event, xhr, settings) { mapUrlHandler(settings.url, [ { pattern: /.+\?limit=20/, handle: handleDashboardActivities }, { pattern: /.+\/refs\/.+\/logs_tree\/.+/, handle: handleLogsTree }, { pattern: /.+notes\.js\?target_type=issue.+/, handle: handleIssueComments } ]); }); /** * Parse useful data from dom elements and assign them to globals for later use. */ function initGlobals () { autocompleteOpts = JSON.parse($('.search-autocomplete-json').attr('data-autocomplete-opts')); projectOpts = _.where(autocompleteOpts, function (opt) { if (opt.label.indexOf('project:') !== -1) { return true; } }); currentUser = $('.profile-pic').attr('href').slice(3); currentProjectID = $(document.body).attr('data-project-id'); currentProjectPath = '/'; if ($('h1.project_name span').length) { currentProjectPath += $('h1.project_name span').text() .replace(/\s/, '').replace(/\s/, '').replace(' ', '-').toLowerCase(); } else { currentProjectPath += currentUser + '/' + $('h1.project_name').text().replace(' ', '-').toLowerCase(); } currentBranch = $('.project-refs-select').val(); console.log(currentUser, currentProjectID, currentProjectPath, currentBranch); } /** * Document loaded url handlers. */ /** * Handle tweak tasks for all pages. */ function handleAll() { $('.home a').attr('href', $('.home a').attr('href') + '#'); addProjectSelect(); } /** * Handle tweak tasks for project dashboard page. */ function handleProjectDashboard() { // Nothing to do. } /** * Handle tweak tasks for files tree view. */ function handleTreeView() { genMdFileTOCAndAdjustHyperlink(); } /** * Handle tweak tasks for markdown file blob view. */ function handleMdBlobView() { var slideLink = $('<a class="btn btn-tiny" target="_blank">slide</a>') .attr('href', '/reveal/md.html?p=' + location.pathname.replace('blob', 'raw')); $('.file-title .options .btn-group a:nth-child(2)').after(slideLink); genMdFileTOCAndAdjustHyperlink(); } /** * Add project select on the top bar. */ function addProjectSelect() { var projectSelectForm = $('<form class="navbar-form pull-left">' + '<select id="t-project-list"></select>' + '</form>'); $('.navbar .container .nav li:nth-child(2)').after(projectSelectForm); var options = projectOpts.map(function (project) { return $('<option />').val(project.url.toLowerCase()).text(project.label.slice(9)); }); if (!$('h1.project_name span').length) { options.unshift('<option>Go to Project</option>'); } $('#t-project-list').append(options) .val(currentProjectPath) .change(function () { location.href = $(this).val(); }); } /** * Generate TOC for markdown file. */ function genMdFileTOCAndAdjustHyperlink() { // Assume there is only one .file-holder. var fileHolder = $('.file-holder'); if (fileHolder.length !== 1) { return; } var fileTitle = fileHolder.find('.file-title'), fileContent = fileHolder.find('.file-content'); fileTitle.wrapInner('<div class="t-file-title-header" />') .scrollToFixed(); var fileTitleFooter = $('<div class="t-file-title-footer"><div class="t-file-title-toc navbar-inner" /></div>') .appendTo(fileTitle) .hide(); var fileTitleToc = fileTitleFooter.find('.t-file-title-toc') .tocify({ context: fileContent, selectors: 'h1,h2,h3,h4,h5,h6', showAndHide: false, hashGenerator: 'pretty', scrollTo: 38 }); // Some special characters will cause tocify hash error, replace them with empty string. fileHolder.find('[data-unique]').each(function () { $(this).attr('data-unique', $(this).attr('data-unique').replace(/\./g, '')); }); $('<span class="t-file-title-toc-toggler options">' + '<div class="btn-group tree-btn-group">' + '<a class="btn btn-tiny" title="Table of Content, \'m\' for shortcut.">TOC</a>' + '</div>' + '</span>') .click(function () { fileTitleFooter.toggle(); }) .appendTo(fileTitle.find('.t-file-title-header')); $(document).keyup(function(e) { switch (e.which) { case 27: fileTitleFooter.hide(); break; case 77: fileTitleFooter.toggle(); break; } }); // Jumpt to ahchor if has one. if (location.hash) { var anchor = location.hash.slice(1); fileTitleToc.find('li[data-unique="' + anchor + '"] a').click(); } // Adjust hyperlink. fileContent.find('a').each(function () { var href = $(this).attr('href'); // Sine 6-2-stable, gitlab will handle relative links when rendering markdown, // but it didn't work, all relative links fallback to wikis path, // I didn't have much time to figure out why, so I did this quick fix. var gitlabPrefixedWikisPath = currentProjectPath + '/wikis/'; var gitlabPrefixedWikisPathIndex = href.indexOf(gitlabPrefixedWikisPath); if (gitlabPrefixedWikisPathIndex != -1) { href = href.slice(gitlabPrefixedWikisPath.length); } // If not start with '/' and doesn't have '//', consider it as a relative path. if (/^[^\/]/.test(href) && !/.*\/\/.*/.test(href)) { var middlePath; // If end with .ext, this is a file path, otherwise is a directory path. if (/.*\.[^\/]+$/.test(href)) { middlePath = '/blob/'; } else { middlePath = '/tree/'; } $(this).attr('href', currentProjectPath + middlePath + currentBranch + '/' + href); } }); } /** * Ajax success url handlers. */ /** * Handle tweak tasks for dashboard activities. */ function handleDashboardActivities() { // Nothing to do. } /** * Handle tweak tasks for issue comments. */ function handleIssueComments() { $('.note-image-attach').each(function () { var img = $(this); var wrapper = $('<a class="t-fancybox-note-image-attach" rel="gallery-note-image-attach" />') .attr('href', img.attr('src')) .attr('title', img.attr('alt')); img.wrap(wrapper); wrapper.commonFancybox(); }); $('.t-fancybox-note-image-attach').commonFancybox(); } /** * Handle tweak tasks for git logs tree. */ function handleLogsTree() { // Nothing to do. } /** * Helpers. */ function mapUrlHandler(url, handlers) { handlers.forEach(function (handler) { if (handler.pattern.test(url)) { handler.handle(); } }); } function mySetInterval(fn, interval) { setTimeout(function () { fn(function () { mySetInterval(fn, interval); }); }, interval); } function myGitLabAPIGet(url, data, cb) { $.get('/api/v3/' + url + '?private_token=' + PRIVATE_TOKEN, data, function (data) { cb(data); }); } /** * Extensions */ if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } (function ($) { $.fn.extend({ commonFancybox: function () { $(this).fancybox({ closeBtn: false, helpers: { title: { type : 'inside' }, buttons: {} } }); } }); })(jQuery);
inetfuture/gitlab-tweak
public/tweak.js
JavaScript
mit
7,663
import axios from 'axios' import pipelineApi from './api' import { addMessage } from '../../../client/utils/flash-messages' import { transformValueForAPI } from '../../../client/utils/date' function transformValuesForApi(values, oldValues = {}) { const data = { name: values.name, status: values.category, } function addValue(key, value) { const existingValue = oldValues[key] const hasExistingValue = Array.isArray(existingValue) ? !!existingValue.length : !!existingValue if (hasExistingValue || (Array.isArray(value) ? value.length : value)) { data[key] = value || null } } addValue('likelihood_to_win', parseInt(values.likelihood, 10)) addValue('sector', values.sector?.value) addValue( 'contacts', values.contacts ? values.contacts.map(({ value }) => value) : [] ) addValue('potential_value', values.export_value) addValue('expected_win_date', transformValueForAPI(values.expected_win_date)) return data } export async function getPipelineByCompany({ companyId }) { const { data } = await pipelineApi.list({ company_id: companyId }) return { companyId, count: data.count, results: data.results, } } export async function addCompanyToPipeline({ values, companyId }) { const { data } = await pipelineApi.create({ company: companyId, ...transformValuesForApi(values), }) addMessage('success', `You added ${values.name} to your pipeline`) return data } export async function getPipelineItem({ pipelineItemId }) { const { data } = await pipelineApi.get(pipelineItemId) return data } export async function getCompanyContacts({ companyId, features }) { const contactEndpointVersion = features['address-area-contact-required-field'] ? 'v4' : 'v3' const { data } = await axios.get( `/api-proxy/${contactEndpointVersion}/contact`, { params: { company_id: companyId, limit: 500 }, } ) return data.results } export async function editPipelineItem({ values, pipelineItemId, currentPipelineItem, }) { const { data } = await pipelineApi.update( pipelineItemId, transformValuesForApi(values, currentPipelineItem) ) addMessage('success', `You saved changes to ${values.name}`) return data } export async function archivePipelineItem({ values, pipelineItemId, projectName, }) { const { data } = await pipelineApi.archive(pipelineItemId, { reason: values.reason, }) addMessage('success', `You archived ${projectName}`) return data } export async function unarchivePipelineItem({ projectName, pipelineItemId }) { const { data } = await pipelineApi.unarchive(pipelineItemId) addMessage('success', `You unarchived ${projectName}`) return data } export async function deletePipelineItem({ projectName, pipelineItemId }) { const { status } = await pipelineApi.delete(pipelineItemId) addMessage('success', `You deleted ${projectName} from your pipeline`) return status }
uktrade/data-hub-fe-beta2
src/apps/my-pipeline/client/tasks.js
JavaScript
mit
2,963
var global = require('../../global'); module.exports = function (data, offset) { var items = data.items.map(invoiceNote => { var invoiceItem = invoiceNote.items.map(dataItem => { var _items = dataItem.items.map(item => { dueDate = new Date(dataItem.deliveryOrderSupplierDoDate); dueDate.setDate(dueDate.getDate() + item.paymentDueDays); return { deliveryOrderNo: dataItem.deliveryOrderNo, date: dataItem.deliveryOrderDate, purchaseRequestRefNo: item.purchaseRequestRefNo, product: item.product.name, productDesc: item.product.description, quantity: item.deliveredQuantity, uom: item.purchaseOrderUom.unit, unit: item.unit, price: item.pricePerDealUnit, priceTotal: item.pricePerDealUnit * item.deliveredQuantity, correction: item.correction, dueDate: dueDate, paymentMethod: item.paymentMethod, currRate: item.kursRate, } }); _items = [].concat.apply([], _items); return _items; }) invoiceItem = [].concat.apply([], invoiceItem); return invoiceItem; }); items = [].concat.apply([], items); var dueDate, paymentMethod; var dueDates = items.map(item => { return item.dueDate }) dueDate = Math.max.apply(null, dueDates); paymentMethod = items[0].paymentMethod; var useIncomeTax = data.items .map((item) => item.useIncomeTax) .reduce((prev, curr, index) => { return prev && curr }, true); var useVat = data.items .map((item) => item.useVat) .reduce((prev, curr, index) => { return prev && curr }, true); var vatRate = 0; if (useVat) { vatRate = data.items[0].vat.rate; } var sumByUnit = []; items.reduce(function (res, value) { if (!res[value.unit]) { res[value.unit] = { priceTotal: 0, unit: value.unit }; sumByUnit.push(res[value.unit]) } res[value.unit].priceTotal += value.priceTotal return res; }, {}); var locale = global.config.locale; var moment = require('moment'); moment.locale(locale.name); var header = [ { stack: [ 'PT. DAN LIRIS', 'Head Office : ', 'Kelurahan Banaran, Kecamatan Grogol', 'Sukoharjo 57193 - INDONESIA', 'PO.BOX 166 Solo 57100', 'Telp. (0271) 740888, 714400', 'Fax. (0271) 735222, 740777' ], alignment: "left", style: ['size06', 'bold'] }, { alignment: "center", text: 'NOTA INTERN', style: ['size08', 'bold'] }, '\n' ]; var subHeader = [ { columns: [ { width: '50%', stack: [ { columns: [{ width: '25%', text: 'No. Nota Intern', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.no, style: ['size06'] }] }, { columns: [{ width: '25%', text: 'Kode Supplier', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.supplier.code, style: ['size06'] }] }, { columns: [{ width: '25%', text: 'Nama Supplier', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: data.supplier.name, style: ['size06'] }] } ] }, { width: '50%', stack: [ { columns: [{ width: '28%', text: 'Tgl. Nota Intern', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: `${moment(data.date).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06'] }] }, { columns: [{ width: '28%', text: 'Tgl. Jatuh Tempo', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: `${moment(dueDate).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06'] }] },{ columns: [{ width: '28%', text: 'Term Pembayaran', style: ['size06'] }, { width: '2%', text: ':', style: ['size06'] }, { width: '*', text: paymentMethod, style: ['size06'] }] }, ] } ] }, { text: '\n', style: ['size06'] } ]; var thead = [ { text: 'No. Surat Jalan', style: ['size06', 'bold', 'center'] }, { text: 'Tgl. Surat Jalan', style: ['size06', 'bold', 'center'] }, { text: 'Nomor referensi PR', style: ['size06', 'bold', 'center'] }, { text: 'Keterangan Barang', style: ['size06', 'bold', 'center'] }, { text: 'Jumlah', style: ['size06', 'bold', 'center'] }, { text: 'Satuan', style: ['size06', 'bold', 'center'] }, { text: 'Harga Satuan', style: ['size06', 'bold', 'center'] }, { text: 'Harga Total', style: ['size06', 'bold', 'center'] } ]; var tbody = items.map(function (item, index) { return [{ text: item.deliveryOrderNo, style: ['size06', 'left'] }, { text: `${moment(item.date).add(offset, 'h').format("DD MMM YYYY")}`, style: ['size06', 'left'] }, { text: item.purchaseRequestRefNo, style: ['size06', 'left'] }, { text: `${item.product};${item.productDesc}`, style: ['size06', 'left'] }, { text: item.quantity, style: ['size06', 'right'] }, { text: item.uom, style: ['size06', 'left'] }, { text: parseFloat(item.price).toLocaleString(locale, locale.currency), style: ['size06', 'right'] }, { text: parseFloat(item.priceTotal).toLocaleString(locale, locale.currency), style: ['size06', 'right'] }]; }); tbody = tbody.length > 0 ? tbody : [ [{ text: "tidak ada barang", style: ['size06', 'center'], colSpan: 8 }, "", "", "", "", "", "", ""] ]; var table = [{ table: { widths: ['12%', '12%', '10%', '25%', '7%', '7%', '12%', '15%'], headerRows: 1, body: [].concat([thead], tbody) } }]; var unitK1 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2A"); var unitK2 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2B"); var unitK3 = sumByUnit.find((item) => item.unit.toUpperCase() == "C2C"); var unitK4 = sumByUnit.find((item) => item.unit.toUpperCase() == "C1A"); var unit2D = sumByUnit.find((item) => item.unit.toUpperCase() == "C1B"); var sum = sumByUnit.map(item => item.priceTotal) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var sumKoreksi = items.map(item => item.correction) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var sumByCurrency = items.map(item => item.priceTotal * item.currRate) .reduce(function (prev, curr, index, arr) { return prev + curr; }, 0); var incomeTaxTotal = useIncomeTax ? sumByCurrency * 0.1 : 0; var vatTotal = useVat ? sumByCurrency * vatRate / 100 : 0; var sumTotal = sumByCurrency - vatTotal + incomeTaxTotal + sumKoreksi; var subFooter = [ { text: '\n', style: ['size06'] }, { columns: [ { stack: [ { columns: [ { width: '25%', text: 'Total K1 (2A)' }, { width: '2%', text: ':' }, { width: '*', text: unitK1 ? parseFloat(unitK1.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K2 (2B)' }, { width: '2%', text: ':' }, { width: '*', text: unitK2 ? parseFloat(unitK2.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K3 (2C)' }, { width: '2%', text: ':' }, { width: '*', text: unitK3 ? parseFloat(unitK3.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total K4 (1)' }, { width: '2%', text: ':' }, { width: '*', text: unitK4 ? parseFloat(unitK4.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, { columns: [ { width: '25%', text: 'Total 2D' }, { width: '2%', text: ':' }, { width: '*', text: unit2D ? parseFloat(unit2D.priceTotal).toLocaleString(locale, locale.currency) : "" } ] }, ] }, { stack: [ { columns: [ { width: '45%', text: 'Total Harga Pokok (DPP)' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sum).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Mata Uang' }, { width: '2%', text: ':' }, { width: '*', text: data.currency.code } ] }, { columns: [ { width: '45%', text: 'Total Harga Pokok (Rp)' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sum * data.currency.rate).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota Koreksi' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sumKoreksi).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota PPN' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(incomeTaxTotal).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total Nota PPH' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(vatTotal).toLocaleString(locale, locale.currency) } ] }, { columns: [ { width: '45%', text: 'Total yang harus dibayar' }, { width: '2%', text: ':' }, { width: '*', text: parseFloat(sumTotal).toLocaleString(locale, locale.currency) } ] }, ] } ], style: ['size07'] }]; var footer = ['\n\n', { alignment: "center", table: { widths: ['33%', '33%', '33%'], body: [ [ { text: 'Administrasi', style: ['size06', 'bold', 'center'] }, { text: 'Staff Pembelian', style: ['size06', 'bold', 'center'] }, { text: 'Verifikasi', style: ['size06', 'bold', 'center'] } ], [ { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] }, { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] }, { stack: ['\n\n\n\n', { text: '(Nama & Tanggal)', style: ['size06', 'center'] } ] } ] ] } }]; var dd = { pageSize: 'A5', pageOrientation: 'portrait', pageMargins: 20, content: [].concat(header, subHeader, table, subFooter, footer), styles: { size06: { fontSize: 6 }, size07: { fontSize: 7 }, size08: { fontSize: 8 }, size09: { fontSize: 9 }, size10: { fontSize: 10 }, bold: { bold: true }, center: { alignment: 'center' }, left: { alignment: 'left' }, right: { alignment: 'right' }, justify: { alignment: 'justify' } } }; return dd; };
indriHutabalian/dl-module
src/pdf/definitions/garment-intern-note.js
JavaScript
mit
21,593
const multiples = '(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)' const here = 'fraction-tagger' // plural-ordinals like 'hundredths' are already tagged as Fraction by compromise const tagFractions = function (doc) { // hundred doc.match(multiples).tag('#Multiple', here) // half a penny doc.match('[(half|quarter)] of? (a|an)', 0).tag('Fraction', 'millionth') // nearly half doc.match('#Adverb [half]', 0).tag('Fraction', 'nearly-half') // half the doc.match('[half] the', 0).tag('Fraction', 'half-the') // two-halves doc.match('#Value (halves|halfs|quarters)').tag('Fraction', 'two-halves') // ---ordinals as fractions--- // a fifth doc.match('a #Ordinal').tag('Fraction', 'a-quarter') // seven fifths doc.match('(#Fraction && /s$/)').lookBefore('#Cardinal+$').tag('Fraction') // one third of .. doc.match('[#Cardinal+ #Ordinal] of .', 0).tag('Fraction', 'ordinal-of') // 100th of doc.match('[(#NumericValue && #Ordinal)] of .', 0).tag('Fraction', 'num-ordinal-of') // a twenty fifth doc.match('(a|one) #Cardinal?+ #Ordinal').tag('Fraction', 'a-ordinal') // doc.match('(a|one) [#Ordinal]', 0).tag('Fraction', 'a-ordinal') // values.if('#Ordinal$').tag('Fraction', '4-fifths') // seven quarters // values.tag('Fraction', '4-quarters') // doc.match('(#Value && !#Ordinal)+ (#Ordinal|#Fraction)').tag('Fraction', '4-fifths') // 12 and seven fifths // doc.match('#Value+ and #Value+ (#Ordinal|half|quarter|#Fraction)').tag('Fraction', 'val-and-ord') // fixups // doc.match('#Cardinal+? (second|seconds)').unTag('Fraction', '3 seconds') // doc.match('#Ordinal (half|quarter)').unTag('Fraction', '2nd quarter') // doc.match('#Ordinal #Ordinal+').unTag('Fraction') // doc.match('[#Cardinal+? (second|seconds)] of (a|an)', 0).tag('Fraction', here) // doc.match(multiples).tag('#Multiple', here) // // '3 out of 5' doc.match('#Cardinal+ out? of every? #Cardinal').tag('Fraction', here) // // one and a half // doc.match('#Cardinal and a (#Fraction && #Value)').tag('Fraction', here) // fraction - 'a third of a slice' // TODO:fixme // m = doc.match(`[(#Cardinal|a) ${ordinals}] of (a|an|the)`, 0).tag('Fraction', 'ord-of') // tag 'thirds' as a ordinal // m.match('.$').tag('Ordinal', 'plural-ordinal') return doc } module.exports = tagFractions
nlp-compromise/nlp_compromise
plugins/numbers/src/tagger/fractions.js
JavaScript
mit
2,380
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { range: '-480', containers: 'fluid', lockViewport: true, grid: { collapse: true } } } }; $(document).ready(function () { $("#calculate").click(function () { var opOne = $("#opOneID").val(); var opTwo = $("#opTwoID").val(); var selected = $('#mathFunction :selected').val(); if (opOne.length != 0) { $("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page. } else if (opTwo.length != 0) { $("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page. } }); $("#clear").click(function () { $("#opOneID").val(''); $("#opTwoID").val(''); $("#resultID").val(''); }); $("#pnlRemove").click(function () { /* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the manchester United chrest with the image that ] was the front panel image] this only shows the panels being changed by using code*/ var imageName = 'img/v8liv.PNG'; var changepnl = $('#btmpnl'); var pnlID = $('#v8front'); $(pnlID).hide(); // hide the front panel $('#btmpnl').attr('src', imageName); // change the bottom image to v8rear.PNG }); $('#mathFunction :selected').val(); $('#mathFunction').change(function () { /* this fucntion calls the calucate funtion with the number to be converted with the conversion type which comes from the select tag, eg pk is pounds to kilo's this function fires when the select dropdown box changes */ var opOne = $("#opOneID").val(); var opTwo = $("#opTwoID").val(); var selected = $('#mathFunction :selected').val(); // console.log($('#conversion :selected').val()); //write it out to the console to verify what was $("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page. }).change(); }); function process(selected, opOne,opTwo) { switch (selected) { case "+": return Calc.AddNo(opOne,opTwo); break; case "-": return Calc.SubNo(opOne, opTwo); break; case "/": return Calc.DivideNo(opOne, opTwo); break; case "*": return Calc.MultplyNo(opOne, opTwo); break; default: return "Error ! "; // code to be executed if n is different from case 1 and 2 } }
akabob/ARIA_CA2_Code
js/sk1.js
JavaScript
mit
3,079
(function(app, undefined) { 'use strict'; if(!app) throw new Error('Application "app" namespace not found.'); //---------------------------------------------------------------------------- console.log( 'hello world' ); console.log( 'Application Running...' ); //---------------------------------------------------------------------------- // @begin: renders app.render.jquery(); app.render.vanilla(); // @end: renders //---------------------------------------------------------------------------- // @begin: to_jquery app.to_jquery.run(); // @end: to_jquery //---------------------------------------------------------------------------- // @begin: mustache app.menu.render(); app.menu.option.reset(); // @begin: mustache //---------------------------------------------------------------------------- })(window.app);
soudev/requirejs-steps
src/01/scripts/app.js
JavaScript
mit
867
import Ember from 'ember'; import CheckboxMixin from '../mixins/checkbox-mixin'; export default Ember.Component.extend(CheckboxMixin, { type: 'checkbox', checked: false, onChange: function() { this.set('checked', this.$('input').prop('checked')); this.sendAction("action", { checked: this.get('checked'), value: this.get('value') }); } });
CrshOverride/Semantic-UI-Ember
addon/components/ui-checkbox.js
JavaScript
mit
374
"use strict" var express = require('express'); var app = express(); var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); var router = express.Router(); router.get('/accidents', function(req, res) { var query = { index: 'wildmap', type: 'accidents', size: 10000, body: { query: { bool: { must: [ { match_all: {} } ] } } } } var animal_type = req.query.animal_type; var day_type = req.query.day_type; var season = req.query.season; if(animal_type && animal_type!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.animal_type": animal_type } }); } if(day_type && day_type!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.day_type": day_type } }); } if(season && season!="all"){ query.body.query.bool.must.push({ term: { "accidents.pin.season": season } }); } console.log(query); client.search(query).then(function (resp) { console.log(resp.hits.hits); var response = resp.hits.hits.map(function(e){ return e._source.pin; }) res.send(response); }, function (err) { console.log(err.message); res.status(500).end(); }); }); app.use('/api', router); var port = process.env.PORT || 8080; app.listen(port); console.log("Backend is running on port " + port);
Jugendhackt/wildmap
backend/index.js
JavaScript
mit
1,488
var generatetask = require('../source/ajgenesis/tasks/generate'), createtask = require('../create'), path = require('path'), fs = require('fs'), ajgenesis = require('ajgenesis'); exports['generate'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); ajgenesis.createDirectory('build'); process.chdir('build'); generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync('app.rb')); test.ok(fs.existsSync('public')); //test.ok(fs.existsSync(path.join('views', 'index.erb'))); test.ok(fs.existsSync('views')); test.ok(fs.existsSync(path.join('views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentlist.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentnew.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentview.erb'))); test.ok(fs.existsSync(path.join('views', 'departmentedit.erb'))); test.ok(fs.existsSync(path.join('views', 'employeelist.erb'))); test.ok(fs.existsSync(path.join('views', 'employeenew.erb'))); test.ok(fs.existsSync(path.join('views', 'employeeview.erb'))); test.ok(fs.existsSync(path.join('views', 'employeeedit.erb'))); test.ok(fs.existsSync(path.join('entities'))); test.ok(fs.existsSync(path.join('entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('entities', 'department.rb'))); test.ok(fs.existsSync(path.join('entities', 'employee.rb'))); test.ok(fs.existsSync('controllers')); test.ok(fs.existsSync(path.join('controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); } exports['generate in directory'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); model.builddir = 'build'; if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync(path.join('build', 'app.rb'))); test.ok(fs.existsSync(path.join('build', 'public'))); test.ok(fs.existsSync(path.join('build', 'views'))); //test.ok(fs.existsSync(path.join('views', 'index.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('build', 'entities'))); test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); } exports['create and generate'] = function (test) { test.async(); var cwd = process.cwd(); process.chdir('test'); var model = ajgenesis.loadModel(); test.ok(model.entities); test.ok(Array.isArray(model.entities)); test.equal(model.entities.length, 4); if (fs.existsSync('build') && !fs.existsSync(path.join('build', 'development.db'))) removeDirSync('build'); createtask(null, ['build'], ajgenesis, function (err, result) { test.equal(err, null); test.ok(fs.existsSync('build')); model.builddir = 'build'; generatetask(model, [], ajgenesis, function (err, result) { test.equal(err, null); test.equal(result, null); test.ok(fs.existsSync(path.join('build', 'app.rb'))); test.ok(fs.existsSync(path.join('build', 'public'))); test.ok(fs.existsSync(path.join('build', 'views'))); test.ok(fs.existsSync(path.join('build', 'views', 'index.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customerview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'customeredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'suppliernew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplierview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'supplieredit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentlist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentnew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'departmentedit.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeelist.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeenew.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeeview.erb'))); test.ok(fs.existsSync(path.join('build', 'views', 'employeeedit.erb'))); test.ok(fs.existsSync(path.join('build', 'entities'))); test.ok(fs.existsSync(path.join('build', 'entities', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'entities', 'employee.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'customer.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'supplier.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'department.rb'))); test.ok(fs.existsSync(path.join('build', 'controllers', 'employee.rb'))); process.chdir(cwd); test.done(); }); }); } function removeDirSync(dirname) { var filenames = fs.readdirSync(dirname); filenames.forEach(function (filename) { filename = path.join(dirname, filename); if (isDirectory(filename)) removeDirSync(filename); else removeFileSync(filename); }); fs.rmdirSync(dirname); } function removeFileSync(filename) { fs.unlinkSync(filename); } function isDirectory(filename) { try { var stats = fs.lstatSync(filename); return stats.isDirectory(); } catch (err) { return false; } }
ajlopez/AjGenesisNode-Sinatra
test/generate.js
JavaScript
mit
9,507
const S$ = require('S$'); function loadSrc(obj, src) { throw src; } const cookies = S$.symbol('Cookie', ''); const world = {}; if (cookies) { if (/iPhone/.exec(cookies)) { loadSrc(world, '/resources/' + cookies); } loadSrc(world, '/resources/unknown'); } else { loadSrc(world, '/resources/fresh'); }
ExpoSEJS/ExpoSE
tests/regex/cookies/t1.js
JavaScript
mit
332
module.exports = function (seneca, util) { //var Joi = util.Joi }
senecajs/seneca-dynamo-store
dynamo-store-doc.js
JavaScript
mit
68
'use strict' var test = require('tap').test var strip = require('./') test('stripFalsy', function(t) { t.plan(5) t.deepEqual(strip(null), {}) t.deepEqual(strip('test'), {}) t.deepEqual(strip(13), {}) t.deepEqual(strip(), {}) var input = { a: false , b: 0 , c: null , d: undefined , e: '' , f: 'biscuits' , g: '0' } var exp = { f: 'biscuits' , g: '0' } t.deepEqual(strip(input), exp) })
helpdotcom/strip-falsy
test.js
JavaScript
mit
433
$(function () { $('.imageUploadMultiple').each(function (index, item) { var $item = $(item); var $group = $item.closest('.form-group'); var $innerGroup = $item.find('.form-group'); var $errors = $item.find('.errors'); var $input = $item.find('.imageValue'); var flow = new Flow({ target: $item.data('target'), testChunks: false, chunkSize: 1024 * 1024 * 1024, query: { _token: $item.data('token') } }); var updateValue = function () { var values = []; $item.find('img[data-value]').each(function () { values.push($(this).data('value')); }); $input.val(values.join(',')); }; flow.assignBrowse($item.find('.imageBrowse')); flow.on('filesSubmitted', function (file) { flow.upload(); }); flow.on('fileSuccess', function (file, message) { flow.removeFile(file); $errors.html(''); $group.removeClass('has-error'); var result = $.parseJSON(message); $innerGroup.append('<div class="col-xs-6 col-md-3 imageThumbnail"><div class="thumbnail">' + '<img data-value="' + result.value + '" src="' + result.url + '" />' + '<a href="#" class="imageRemove">Remove</a></div></div>'); updateValue(); }); flow.on('fileError', function (file, message) { flow.removeFile(file); var response = $.parseJSON(message); var errors = ''; $.each(response, function (index, error) { errors += '<p class="help-block">' + error + '</p>' }); $errors.html(errors); $group.addClass('has-error'); }); $item.on('click', '.imageRemove', function (e) { e.preventDefault(); $(this).closest('.imageThumbnail').remove(); updateValue(); }); $innerGroup.sortable({ onUpdate: function () { updateValue(); } }); }); });
Asvae/SleepingOwlAdmin
resources/assets/js/form/image/initMultiple.js
JavaScript
mit
2,178
/** * k-d Tree JavaScript - V 1.01 * * https://github.com/ubilabs/kd-tree-javascript * * @author Mircea Pricop <[email protected]>, 2012 * @author Martin Kleppe <[email protected]>, 2012 * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License <http://www.opensource.org/licenses/mit-license.php> */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports === 'object') { factory(exports); } else { factory((root.commonJsStrict = {})); } }(this, function (exports) { function Node(obj, dimension, parent) { this.obj = obj; this.left = null; this.right = null; this.parent = parent; this.dimension = dimension; } function kdTree(points, metric, dimensions) { var self = this; function buildTree(points, depth, parent) { var dim = depth % dimensions.length, median, node; if (points.length === 0) { return null; } if (points.length === 1) { return new Node(points[0], dim, parent); } points.sort(function (a, b) { return a[dimensions[dim]] - b[dimensions[dim]]; }); median = Math.floor(points.length / 2); node = new Node(points[median], dim, parent); node.left = buildTree(points.slice(0, median), depth + 1, node); node.right = buildTree(points.slice(median + 1), depth + 1, node); return node; } // Reloads a serialied tree function loadTree (data) { // Just need to restore the `parent` parameter self.root = data; function restoreParent (root) { if (root.left) { root.left.parent = root; restoreParent(root.left); } if (root.right) { root.right.parent = root; restoreParent(root.right); } } restoreParent(self.root); } // If points is not an array, assume we're loading a pre-built tree if (!Array.isArray(points)) loadTree(points, metric, dimensions); else this.root = buildTree(points, 0, null); // Convert to a JSON serializable structure; this just requires removing // the `parent` property this.toJSON = function (src) { if (!src) src = this.root; var dest = new Node(src.obj, src.dimension, null); if (src.left) dest.left = self.toJSON(src.left); if (src.right) dest.right = self.toJSON(src.right); return dest; }; this.insert = function (point) { function innerSearch(node, parent) { if (node === null) { return parent; } var dimension = dimensions[node.dimension]; if (point[dimension] < node.obj[dimension]) { return innerSearch(node.left, node); } else { return innerSearch(node.right, node); } } var insertPosition = innerSearch(this.root, null), newNode, dimension; if (insertPosition === null) { this.root = new Node(point, 0, null); return; } newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); dimension = dimensions[insertPosition.dimension]; if (point[dimension] < insertPosition.obj[dimension]) { insertPosition.left = newNode; } else { insertPosition.right = newNode; } }; this.remove = function (point) { var node; function nodeSearch(node) { if (node === null) { return null; } if (node.obj === point) { return node; } var dimension = dimensions[node.dimension]; if (point[dimension] < node.obj[dimension]) { return nodeSearch(node.left, node); } else { return nodeSearch(node.right, node); } } function removeNode(node) { var nextNode, nextObj, pDimension; function findMin(node, dim) { var dimension, own, left, right, min; if (node === null) { return null; } dimension = dimensions[dim]; if (node.dimension === dim) { if (node.left !== null) { return findMin(node.left, dim); } return node; } own = node.obj[dimension]; left = findMin(node.left, dim); right = findMin(node.right, dim); min = node; if (left !== null && left.obj[dimension] < own) { min = left; } if (right !== null && right.obj[dimension] < min.obj[dimension]) { min = right; } return min; } if (node.left === null && node.right === null) { if (node.parent === null) { self.root = null; return; } pDimension = dimensions[node.parent.dimension]; if (node.obj[pDimension] < node.parent.obj[pDimension]) { node.parent.left = null; } else { node.parent.right = null; } return; } // If the right subtree is not empty, swap with the minimum element on the // node's dimension. If it is empty, we swap the left and right subtrees and // do the same. if (node.right !== null) { nextNode = findMin(node.right, node.dimension); nextObj = nextNode.obj; removeNode(nextNode); node.obj = nextObj; } else { nextNode = findMin(node.left, node.dimension); nextObj = nextNode.obj; removeNode(nextNode); node.right = node.left; node.left = null; node.obj = nextObj; } } node = nodeSearch(self.root); if (node === null) { return; } removeNode(node); }; this.nearest = function (point, maxNodes, maxDistance) { var i, result, bestNodes; bestNodes = new BinaryHeap( function (e) { return -e[1]; } ); function nearestSearch(node) { var bestChild, dimension = dimensions[node.dimension], ownDistance = metric(point, node.obj), linearPoint = {}, linearDistance, otherChild, i; function saveNode(node, distance) { bestNodes.push([node, distance]); if (bestNodes.size() > maxNodes) { bestNodes.pop(); } } for (i = 0; i < dimensions.length; i += 1) { if (i === node.dimension) { linearPoint[dimensions[i]] = point[dimensions[i]]; } else { linearPoint[dimensions[i]] = node.obj[dimensions[i]]; } } linearDistance = metric(linearPoint, node.obj); if (node.right === null && node.left === null) { if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { saveNode(node, ownDistance); } return; } if (node.right === null) { bestChild = node.left; } else if (node.left === null) { bestChild = node.right; } else { if (point[dimension] < node.obj[dimension]) { bestChild = node.left; } else { bestChild = node.right; } } nearestSearch(bestChild); if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { saveNode(node, ownDistance); } if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) { if (bestChild === node.left) { otherChild = node.right; } else { otherChild = node.left; } if (otherChild !== null) { nearestSearch(otherChild); } } } if (maxDistance) { for (i = 0; i < maxNodes; i += 1) { bestNodes.push([null, maxDistance]); } } if(self.root) nearestSearch(self.root); result = []; for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) { if (bestNodes.content[i][0]) { result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]); } } return result; }; this.balanceFactor = function () { function height(node) { if (node === null) { return 0; } return Math.max(height(node.left), height(node.right)) + 1; } function count(node) { if (node === null) { return 0; } return count(node.left) + count(node.right) + 1; } return height(self.root) / (Math.log(count(self.root)) / Math.log(2)); }; } // Binary heap implementation from: // http://eloquentjavascript.net/appendix2.html function BinaryHeap(scoreFunction){ this.content = []; this.scoreFunction = scoreFunction; } BinaryHeap.prototype = { push: function(element) { // Add the new element to the end of the array. this.content.push(element); // Allow it to bubble up. this.bubbleUp(this.content.length - 1); }, pop: function() { // Store the first element so we can return it later. var result = this.content[0]; // Get the element at the end of the array. var end = this.content.pop(); // If there are any elements left, put the end element at the // start, and let it sink down. if (this.content.length > 0) { this.content[0] = end; this.sinkDown(0); } return result; }, peek: function() { return this.content[0]; }, remove: function(node) { var len = this.content.length; // To remove a value, we must search through the array to find // it. for (var i = 0; i < len; i++) { if (this.content[i] == node) { // When it is found, the process seen in 'pop' is repeated // to fill up the hole. var end = this.content.pop(); if (i != len - 1) { this.content[i] = end; if (this.scoreFunction(end) < this.scoreFunction(node)) this.bubbleUp(i); else this.sinkDown(i); } return; } } throw new Error("Node not found."); }, size: function() { return this.content.length; }, bubbleUp: function(n) { // Fetch the element that has to be moved. var element = this.content[n]; // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1, parent = this.content[parentN]; // Swap the elements if the parent is greater. if (this.scoreFunction(element) < this.scoreFunction(parent)) { this.content[parentN] = element; this.content[n] = parent; // Update 'n' to continue at the new position. n = parentN; } // Found a parent that is less, no need to move it further. else { break; } } }, sinkDown: function(n) { // Look up the target element and its score. var length = this.content.length, element = this.content[n], elemScore = this.scoreFunction(element); while(true) { // Compute the indices of the child elements. var child2N = (n + 1) * 2, child1N = child2N - 1; // This is used to store the new position of the element, // if any. var swap = null; // If the first child exists (is inside the array)... if (child1N < length) { // Look it up and compute its score. var child1 = this.content[child1N], child1Score = this.scoreFunction(child1); // If the score is less than our element's, we need to swap. if (child1Score < elemScore) swap = child1N; } // Do the same checks for the other child. if (child2N < length) { var child2 = this.content[child2N], child2Score = this.scoreFunction(child2); if (child2Score < (swap == null ? elemScore : child1Score)){ swap = child2N; } } // If the element needs to be moved, swap it, and continue. if (swap != null) { this.content[n] = this.content[swap]; this.content[swap] = element; n = swap; } // Otherwise, we are done. else { break; } } } }; this.kdTree = kdTree; exports.kdTree = kdTree; exports.BinaryHeap = BinaryHeap; }));
tsurantino/roadtrip
lib/kdTree.js
JavaScript
mit
13,331
// function that finds the sum of two parameters function findSum(firstnr, secondnr){ return firstnr + secondnr; } //function that finds the product of two parameters function findProduct(firstnr, secondnr){ return firstnr * secondnr; } /* threeOperation calls the operation parameter as a function so it's able to run and "do" different things depending on the global function it takes as a parameter when calling it*/ function threeOperation (x, operation){ /*put console.log here so it doesn't only returns the result but also prints it in the console first: to check if it gives the right answer when it's called*/ console.log(operation(3, x)); return operation(3, x); } //Call "threeOperation" with the values of "4" and "findSum" threeOperation(4, findSum); //Call "threeOperation" with the values of "5" and "findSum" threeOperation(5, findSum); //Call "threeOperation" with the values of "4" and "findProduct" threeOperation(4, findProduct); //Call "threeOperation" with the values of "5" and "findProduct" threeOperation(5, findProduct);
InekeScheffers/NYCDA-individual-assignments
09-29-2016-Anonymous-Functions-Practice/Anonymous Functions Practice.js
JavaScript
mit
1,060
// GPG4Browsers - An OpenPGP implementation in javascript // Copyright (C) 2011 Recurity Labs GmbH // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /** * Public-Key Encrypted Session Key Packets (Tag 1)<br/> * <br/> * {@link http://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key * used to encrypt a message. Zero or more Public-Key Encrypted Session Key * packets and/or Symmetric-Key Encrypted Session Key packets may precede a * Symmetrically Encrypted Data Packet, which holds an encrypted message. The * message is encrypted with the session key, and the session key is itself * encrypted and stored in the Encrypted Session Key packet(s). The * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted * Session Key packet for each OpenPGP key to which the message is encrypted. * The recipient of the message finds a session key that is encrypted to their * public key, decrypts the session key, and then uses the session key to * decrypt the message. * @requires crypto * @requires enums * @requires type/s2k * @module packet/sym_encrypted_session_key */ var type_s2k = require('../type/s2k.js'), enums = require('../enums.js'), crypto = require('../crypto'); module.exports = SymEncryptedSessionKey; /** * @constructor */ function SymEncryptedSessionKey() { this.tag = enums.packet.symEncryptedSessionKey; this.sessionKeyEncryptionAlgorithm = null; this.sessionKeyAlgorithm = 'aes256'; this.encrypted = null; this.s2k = new type_s2k(); } /** * Parsing function for a symmetric encrypted session key packet (tag 3). * * @param {String} input Payload of a tag 1 packet * @param {Integer} position Position to start reading from the input string * @param {Integer} len * Length of the packet or the remaining length of * input at position * @return {module:packet/sym_encrypted_session_key} Object representation */ SymEncryptedSessionKey.prototype.read = function(bytes) { // A one-octet version number. The only currently defined version is 4. this.version = bytes.charCodeAt(0); // A one-octet number describing the symmetric algorithm used. var algo = enums.read(enums.symmetric, bytes.charCodeAt(1)); // A string-to-key (S2K) specifier, length as defined above. var s2klength = this.s2k.read(bytes.substr(2)); // Optionally, the encrypted session key itself, which is decrypted // with the string-to-key object. var done = s2klength + 2; if (done < bytes.length) { this.encrypted = bytes.substr(done); this.sessionKeyEncryptionAlgorithm = algo; } else this.sessionKeyAlgorithm = algo; }; SymEncryptedSessionKey.prototype.write = function() { var algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm; var bytes = String.fromCharCode(this.version) + String.fromCharCode(enums.write(enums.symmetric, algo)) + this.s2k.write(); if (this.encrypted !== null) bytes += this.encrypted; return bytes; }; /** * Decrypts the session key (only for public key encrypted session key * packets (tag 1) * * @return {String} The unencrypted session key */ SymEncryptedSessionKey.prototype.decrypt = function(passphrase) { var algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm; var length = crypto.cipher[algo].keySize; var key = this.s2k.produce_key(passphrase, length); if (this.encrypted === null) { this.sessionKey = key; } else { var decrypted = crypto.cfb.decrypt( this.sessionKeyEncryptionAlgorithm, key, this.encrypted, true); this.sessionKeyAlgorithm = enums.read(enums.symmetric, decrypted[0].keyCodeAt()); this.sessionKey = decrypted.substr(1); } }; SymEncryptedSessionKey.prototype.encrypt = function(passphrase) { var length = crypto.getKeyLength(this.sessionKeyEncryptionAlgorithm); var key = this.s2k.produce_key(passphrase, length); var private_key = String.fromCharCode( enums.write(enums.symmetric, this.sessionKeyAlgorithm)) + crypto.getRandomBytes( crypto.getKeyLength(this.sessionKeyAlgorithm)); this.encrypted = crypto.cfb.encrypt( crypto.getPrefixRandom(this.sessionKeyEncryptionAlgorithm), this.sessionKeyEncryptionAlgorithm, key, private_key, true); }; /** * Fix custom types after cloning */ SymEncryptedSessionKey.prototype.postCloneTypeFix = function() { this.s2k = type_s2k.fromClone(this.s2k); };
openilabs/crypto
node_modules/openpgp/src/packet/sym_encrypted_session_key.js
JavaScript
mit
5,248
export default { FETCH_TAGS_PENDING: Symbol("FETCH_TAGS_PENDING"), FETCH_TAGS_SUCCESS: Symbol("FETCH_TAGS_SUCCESS"), FETCH_TAGS_FAILURE: Symbol("FETCH_TAGS_FAILURE"), FILTER_TAGS: Symbol("FILTER_TAGS"), ORDER_TAGS: Symbol("ORDER_TAGS") };
danjac/photoshare
ui/actionTypes/tags.js
JavaScript
mit
251
/** * * @function * @param {Array|arraylike} value * @param {Function} cmd * @param {any} context * @returns {?} */ export default function eachValue(value, cmd, context, keepReverse) { if (value === undefined || value === null) return undefined; const size = (0 | value.length) - 1; for (let index = size; index > -1; index -= 1) { const i = keepReverse ? index : size - index; const item = value[i]; const resolve = cmd.call(context || item, item, i, value, i); if (resolve === undefined === false) { return resolve; } } return undefined; }
adriancmiranda/describe-type
internal/eachValue.next.js
JavaScript
mit
568
const should = require('should'), sinon = require('sinon'), _ = require('lodash'), settingsCache = require('../../../../server/services/settings/cache'), common = require('../../../../server/lib/common'), controllers = require('../../../../server/services/routing/controllers'), TaxonomyRouter = require('../../../../server/services/routing/TaxonomyRouter'), RESOURCE_CONFIG = require('../../../../server/services/routing/assets/resource-config'), sandbox = sinon.sandbox.create(); describe('UNIT - services/routing/TaxonomyRouter', function () { let req, res, next; beforeEach(function () { sandbox.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/'); sandbox.stub(common.events, 'emit'); sandbox.stub(common.events, 'on'); sandbox.spy(TaxonomyRouter.prototype, 'mountRoute'); sandbox.spy(TaxonomyRouter.prototype, 'mountRouter'); req = sandbox.stub(); res = sandbox.stub(); next = sandbox.stub(); res.locals = {}; }); afterEach(function () { sandbox.restore(); }); it('instantiate', function () { const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/'); should.exist(taxonomyRouter.router); should.exist(taxonomyRouter.rssRouter); taxonomyRouter.taxonomyKey.should.eql('tag'); taxonomyRouter.getPermalinks().getValue().should.eql('/tag/:slug/'); common.events.emit.calledOnce.should.be.true(); common.events.emit.calledWith('router.created', taxonomyRouter).should.be.true(); taxonomyRouter.mountRouter.callCount.should.eql(1); taxonomyRouter.mountRouter.args[0][0].should.eql('/tag/:slug/'); taxonomyRouter.mountRouter.args[0][1].should.eql(taxonomyRouter.rssRouter.router()); taxonomyRouter.mountRoute.callCount.should.eql(3); // permalink route taxonomyRouter.mountRoute.args[0][0].should.eql('/tag/:slug/'); taxonomyRouter.mountRoute.args[0][1].should.eql(controllers.channel); // pagination feature taxonomyRouter.mountRoute.args[1][0].should.eql('/tag/:slug/page/:page(\\d+)'); taxonomyRouter.mountRoute.args[1][1].should.eql(controllers.channel); // edit feature taxonomyRouter.mountRoute.args[2][0].should.eql('/tag/:slug/edit'); taxonomyRouter.mountRoute.args[2][1].should.eql(taxonomyRouter._redirectEditOption.bind(taxonomyRouter)); }); it('fn: _prepareContext', function () { const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/'); taxonomyRouter._prepareContext(req, res, next); next.calledOnce.should.eql(true); res.locals.routerOptions.should.eql({ name: 'tag', permalinks: '/tag/:slug/', type: RESOURCE_CONFIG.QUERY.tag.resource, data: {tag: _.omit(RESOURCE_CONFIG.QUERY.tag, 'alias')}, filter: RESOURCE_CONFIG.TAXONOMIES.tag.filter, context: ['tag'], slugTemplate: true, identifier: taxonomyRouter.identifier }); res._route.type.should.eql('channel'); }); });
dbalders/Ghost
core/test/unit/services/routing/TaxonomyRouter_spec.js
JavaScript
mit
3,184
import React from 'react'; import $ from 'jquery'; import _ from 'lodash'; import Block from './Block'; export default class BlockGrid extends React.Component { constructor() { super(); this.setDefaults(); this.setContainerWidth = this.setContainerWidth.bind(this); this.handleWindowResize = this.handleWindowResize.bind(this); this.resizeTimer = null; // throttle call to this func whenever an image is loaded this.throttledSetContainerWidth = _.throttle(this.setContainerWidth, 500); } setDefaults(){ this.blockWidth = 260; // initial desired block width this.borderWidth = 5; this.wrapperWidth = 0; this.colCount = 0; this.blocks = []; this.blockCount = 0; } handleWindowResize(){ clearTimeout(this.resizeTimer); const _this = this; this.resizeTimer = setTimeout(function() { $('.block-container').css('width', '100%'); _this.setDefaults(); _this.setContainerWidth(); // above code computes false height of blocks // so as a lose patch re-position blocks after 500 ms setTimeout(_this.setContainerWidth, 700); }, 200); } componentDidMount(){ this.setContainerWidth(); /* height of each block is measured with an error the first time so there are some space between blocks specially the top values of the grid. Only solution seems like re calculating positions of the block after few seconds */ // _.delay(this.setContainerWidth, 3000); // reset all blocks when window resized $(window).resize(this.handleWindowResize); } componentWillReceiveProps(nextProps){ // after clicking Load More there will be newProps here // Re calculate block positions so no error occurs when there are // all image less blocks // _.delay(this.setContainerWidth, 2000); } componentDidUpdate(prevProps, prevState){ if(this.blockCount != this.props.data.length){ this.setDefaults(); this.setContainerWidth(); } } componentWillUnmount(){ $(window).off("resize", this.handleWindowResize); } setContainerWidth(){ // setContainerWidth only first time we recieve BlockList data if(this.wrapperWidth == 0){ this.wrapperWidth = $('.block-container').outerWidth(); this.colCount = Math.round(this.wrapperWidth/this.blockWidth); $('.block').css('width', this.blockWidth); this.blockCount = document.getElementsByClassName('block').length; if(this.blockCount < this.colCount){ this.wrapperWidth = (this.blockWidth*this.blockCount) - ( (this.blockCount - 1) * this.borderWidth); this.colCount = this.blockCount; } else { this.wrapperWidth = (this.blockWidth*this.colCount) - ( (this.colCount - 1) * this.borderWidth); } $('.block-container').css('width', this.wrapperWidth); } // if wrapperWidth is already calculated than just reset block positions for( var i = 0; i < this.colCount; i++ ) this.blocks[i] = 0; this.setBlocks(); } setBlocks() { const component = this; $('.block').each(function(){ var min = Math.min.apply(Math, component.blocks); var index = $.inArray(min, component.blocks); var left = index * (component.blockWidth - component.borderWidth) - component.borderWidth; // for the first blocks that needs to overlap container border if(left == 0) left = - component.borderWidth; // start with overlap on top container border var top = min + 10 - component.borderWidth; $(this).css({ 'top' : top + 'px', 'left' : left + 'px' }); component.blocks[index] = top + this.offsetHeight; }); // set wrapper height var wrapperHeight = Math.max.apply(Math, this.blocks); wrapperHeight += this.borderWidth; // block borders $(".block-container").css("height",wrapperHeight + 'px'); } renderBlocks() { const { data } = this.props; return data.map((pin) => { return <Block {...pin} key={pin._id} loadHandler={this.throttledSetContainerWidth}/>; }); } render() { return( <div class="row"> <div class="col-sm-offset-2 col-sm-8 col-xs-offset-1 col-xs-10"> <div class="block-container"> { this.renderBlocks() } </div> </div> </div> ); } }
Dishant15/TechIntrest
frontend/react/components/BlockGrid.js
JavaScript
mit
4,139
const chalk = require('chalk'); const Sequelize = require('sequelize'); // db server constant(s) const dbName = 'relationshipVisualizer'; // +(process.env.NODE_ENV === 'testing' ? '_test' : ''); const url = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`; // notify the user we're about to do it console.log(chalk.yellow(`Opening database connection to ${url}`)) // init the db const db = new Sequelize(url, { define: { freezeTableName: true // don't go changing my table names sequelize! }, logging: false }); module.exports = db;
smanwaring/relationship-visualizer
db/db.js
JavaScript
mit
566
var system = require('system'); var args = system.args; var url = "http://"+args[1], filename = args[2]+".png", timeout = args[3], savePath = args[4], page = require('webpage').create(); //setTimeout(function(){phantom.exit();}, timeout) page.viewportSize = { width: 1200, height: 700 }; page.clipRect = { top: 0, left: 0, width: 1200, height: 700 }; var f = false; page.onLoadFinished = function(status) { console.log('Status: ' + status); setTimeout(function(){ render(page); phantom.exit(); }, 15000) }; page.onResourceReceived = function(response) { if (response.url === url && !f) { setTimeout(function(){ render(page); phantom.exit(); }, 15000) f = true } }; function render(page) { var resPath if (savePath == "") { resPath = filename } else { resPath = savePath + "/" + filename } page.render(resPath) } console.log("start get " + url) page.open(url, function() { });
zhuharev/shot
assets/rasterize.js
JavaScript
mit
936
/* globals describe, before, beforeEach, after, afterEach, it */ 'use strict'; const chai = require('chai'); const assert = chai.assert; const expect = chai.expect; chai.should(); chai.use(require('chai-things')); //http://chaijs.com/plugins/chai-things chai.use(require('chai-arrays')); describe('<%= pkgName %>', function () { before('before', function () { }); beforeEach('beforeEach', function () { }); afterEach('afterEach', function () { }); after('after', function () { }); describe('Stub test', function () { it('should have unit test', function () { assert(false, 'Please add unit tests.'); }); }); });
alykoshin/generator-mini-package
app/templates/test/index.js
JavaScript
mit
666
var _ = require("underscore"), Events = require("./Events"), querystring = require("querystring"), httpClient = require("./httpClient"), utils = require("./utils"), logger = require("config-logger"); var environments = { sandbox: { restHost: "api-sandbox.oanda.com", streamHost: "stream-sandbox.oanda.com", secure: false }, practice: { restHost: "api-fxpractice.oanda.com", streamHost: "stream-fxpractice.oanda.com" }, live: { restHost: "api-fxtrade.oanda.com", streamHost: "stream-fxtrade.oanda.com" } }; var maxRequestsPerSecond = 15, maxRequestsWarningThreshold = 1000; /* * config.environment * config.accessToken * config.username (Sandbox only) */ function OandaAdapter (config) { config.environment = config.environment || "practice"; // this.accountId = accountId; this.accessToken = config.accessToken; this.restHost = environments[config.environment].restHost; this.streamHost = environments[config.environment].streamHost; this.secure = environments[config.environment].secure; if (config.environment === "sandbox") { this.username = config.username; } this.subscriptions = {}; this._eventsBuffer = []; this._pricesBuffer = []; this._sendRESTRequest = utils.rateLimit(this._sendRESTRequest, this, 1000 / maxRequestsPerSecond, maxRequestsWarningThreshold); } Events.mixin(OandaAdapter.prototype); /* * Subscribes to events for all accounts authorized by the token */ OandaAdapter.prototype.subscribeEvents = function (listener, context) { var existingSubscriptions = this.getHandlers("event"); this.off("event", listener, context); this.on("event", listener, context); if (existingSubscriptions.length === 0) { this._streamEvents(); } }; OandaAdapter.prototype.unsubscribeEvents = function (listener, context) { this.off("event", listener, context); this._streamEvents(); }; OandaAdapter.prototype._streamEvents = function () { var subscriptionCount = this.getHandlers("event").length; if (this.eventsRequest) { this.eventsRequest.abort(); } if (subscriptionCount === 0) { return; } clearTimeout(this.eventsTimeout); this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000); this.eventsRequest = httpClient.sendRequest({ hostname: this.streamHost, method: "GET", path: "/v1/events", headers: { Authorization: "Bearer " + this.accessToken, Connection: "Keep-Alive" }, secure: this.secure }, this._onEventsResponse.bind(this), this._onEventsData.bind(this) ); }; OandaAdapter.prototype._onEventsResponse = function (error, body, statusCode) { if (statusCode !== 200) { if (body && body.disconnect) { this.trigger("message", null, "Events streaming API disconnected.\nOanda code " + body.disconnect.code + ": " + body.disconnect.message); } else { this.trigger("message", null, "Events streaming API disconnected with status " + statusCode); } } clearTimeout(this.eventsTimeout); this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000); }; OandaAdapter.prototype._onEventsData = function (data) { // Single chunks sometimes contain more than one event. Each always end with /r/n. Whole chunk therefore not JSON parsable, so must split. // Also, an event may be split accross data chunks, so must buffer. data.split(/\r\n/).forEach(function (line) { var update; if (line) { this._eventsBuffer.push(line); try { update = JSON.parse(this._eventsBuffer.join("")); } catch (error) { if (this._eventsBuffer.length <= 5) { // Wait for next line. return; } logger.error("Unable to parse Oanda events subscription update", this._eventsBuffer.join("\n"), error); this._eventsBuffer = []; return; } this._eventsBuffer = []; if (update.heartbeat) { clearTimeout(this.eventsTimeout); this.eventsTimeout = setTimeout(this._eventsHeartbeatTimeout.bind(this), 20000); return; } this.trigger("event", update); } }, this); }; OandaAdapter.prototype._eventsHeartbeatTimeout = function () { logger.warn("OandaAdapter: No heartbeat received from events stream for 20 seconds. Reconnecting."); this._streamEvents(); }; OandaAdapter.prototype.getAccounts = function (callback) { this._sendRESTRequest({ method: "GET", path: "/v1/accounts" + (this.username ? "?username=" + this.username : "") }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body.accounts) { callback(null, body.accounts); } else { callback("Unexpected accounts response"); } }); }; OandaAdapter.prototype.getAccount = function (accountId, callback) { this._sendRESTRequest({ method: "GET", path: "/v1/accounts/" + accountId }, callback); }; OandaAdapter.prototype.getInstruments = function (accountId, callback) { this._sendRESTRequest({ method: "GET", path: "/v1/instruments?accountId=" + accountId + "&fields=" + ["instrument", "displayName", "pip", "maxTradeUnits", "precision", "maxTrailingStop", "minTrailingStop", "marginRate", "halted"].join("%2C"), }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body.instruments) { callback(null, body.instruments); } else { callback("Unexpected instruments response"); } }); }; OandaAdapter.prototype.getPrice = function (symbol, callback) { var multiple = _.isArray(symbol); if (multiple) { symbol = symbol.join("%2C"); } this._sendRESTRequest({ method: "GET", path: "/v1/prices?instruments=" + symbol }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body && body.prices[0]) { callback(null, multiple ? body.prices : body.prices[0]); } else { callback("Unexpected price response for " + symbol); } }); }; OandaAdapter.prototype.subscribePrice = function (accountId, symbol, listener, context) { var existingSubscriptions = this.getHandlers("price/" + symbol); // Price stream needs an accountId to be passed for streaming prices, though prices for a connection are same anyway if (!this.streamPrices) { this.streamPrices = _.throttle(this._streamPrices.bind(this, accountId)); } this.off("price/" + symbol, listener, context); this.on("price/" + symbol, listener, context); if (existingSubscriptions.length === 0) { this.streamPrices(); } }; OandaAdapter.prototype.unsubscribePrice = function (symbol, listener, context) { this.off("price/" + symbol, listener, context); this.streamPrices(); }; // Kills rates streaming keep alive request for account and creates a new one whenever subsciption list changes. Should always be throttled. OandaAdapter.prototype._streamPrices = function (accountId) { var changed; this.priceSubscriptions = Object.keys(this.getHandlers()).reduce(function (memo, event) { var match = event.match("^price/(.+)$"); if (match) { memo.push(match[1]); } return memo; }, []).sort().join("%2C"); changed = !this.lastPriceSubscriptions || this.priceSubscriptions !== this.lastPriceSubscriptions; this.lastPriceSubscriptions = this.priceSubscriptions; if (!changed) { return; } if (this.pricesRequest) { this.pricesRequest.abort(); } if (this.priceSubscriptions === "") { return; } clearTimeout(this.pricesTimeout); this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000); this.pricesRequest = httpClient.sendRequest({ hostname: this.streamHost, method: "GET", path: "/v1/prices?accountId=" + accountId + "&instruments=" + this.priceSubscriptions, headers: { Authorization: "Bearer " + this.accessToken, Connection: "Keep-Alive" }, secure: this.secure }, this._onPricesResponse.bind(this, accountId), this._onPricesData.bind(this) ); }; OandaAdapter.prototype._onPricesResponse = function (accountId, error, body, statusCode) { if (statusCode !== 200) { if (body && body.disconnect) { this.trigger("message", accountId, "Prices streaming API disconnected.\nOanda code " + body.disconnect.code + ": " + body.disconnect.message); } else { this.trigger("message", accountId, "Prices streaming API disconnected with status " + statusCode); } } clearTimeout(this.pricesTimeout); this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000); }; OandaAdapter.prototype._onPricesData = function (data) { // Single data chunks sometimes contain more than one tick. Each always end with /r/n. Whole chunk therefore not JSON parsable, so must split. // A tick may also be split accross data chunks, so must buffer data.split(/\r\n/).forEach(function (line) { var update; if (line) { this._pricesBuffer.push(line); try { update = JSON.parse(this._pricesBuffer.join("")); } catch (error) { if (this._pricesBuffer.length <= 5) { // Wait for next update. return; } // Drop if cannot produce object after 5 updates logger.error("Unable to parse Oanda price subscription update", this._pricesBuffer.join("\n"), error); this._pricesBuffer = []; return; } this._pricesBuffer = []; if (update.heartbeat) { clearTimeout(this.pricesTimeout); this.pricesTimeout = setTimeout(this._pricesHeartbeatTimeout.bind(this), 10000); return; } if (update.tick) { update.tick.time = new Date(update.tick.time); this.trigger("price/" + update.tick.instrument, update.tick); } } }, this); }; OandaAdapter.prototype._pricesHeartbeatTimeout = function () { logger.warn("OandaAdapter: No heartbeat received from prices stream for 10 seconds. Reconnecting."); delete this.lastPriceSubscriptions; this._streamPrices(); }; /** * Get historical price information about an instrument in candlestick format as defined at * http://developer.oanda.com/rest-live/rates/#aboutCandlestickRepresentation */ OandaAdapter.prototype.getCandles = function (instrument, options, callback) { options = _.extend(options, {instrument: instrument}); this._sendRESTRequest({ method: "GET", path: "/v1/candles?" + querystring.stringify(options), headers: { Authorization: "Bearer " + this.accessToken, "X-Accept-Datetime-Format": "UNIX" } }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body && body.candles) { callback(null, body.candles); } else if (body === "") { // Body is an empty string if there are no candles to return callback(null, []); } else { callback("Unexpected candles response for " + symbol); } }); }; OandaAdapter.prototype.getOpenPositions = function (accountId, callback) { this._sendRESTRequest({ method: "GET", path: "/v1/accounts/" + accountId + "/positions" }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body && body.positions) { callback(null, body.positions); } else { callback("Unexpected response for open positions"); } }); }; OandaAdapter.prototype.getOpenTrades = function (accountId, callback) { this._sendRESTRequest({ method: "GET", path: "/v1/accounts/" + accountId + "/trades" }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body && body.trades) { callback(null, body.trades); } else { callback("Unexpected response for open trades"); } }); }; /** * @method createOrder * @param {String} accountId Required. * @param {Object} order * @param {String} order.instrument Required. Instrument to open the order on. * @param {Number} order.units Required. The number of units to open order for. * @param {String} order.side Required. Direction of the order, either ‘buy’ or ‘sell’. * @param {String} order.type Required. The type of the order ‘limit’, ‘stop’, ‘marketIfTouched’ or ‘market’. * @param {String} order.expiry Required. If order type is ‘limit’, ‘stop’, or ‘marketIfTouched’. The value specified must be in a valid datetime format. * @param {String} order.price Required. If order type is ‘limit’, ‘stop’, or ‘marketIfTouched’. The price where the order is set to trigger at. * @param {Number} order.lowerBound Optional. The minimum execution price. * @param {Number} order.upperBound Optional. The maximum execution price. * @param {Number} order.stopLoss Optional. The stop loss price. * @param {Number} order.takeProfit Optional. The take profit price. * @param {Number} order.trailingStop Optional The trailing stop distance in pips, up to one decimal place. * @param {Function} callback */ OandaAdapter.prototype.createOrder = function (accountId, order, callback) { if (!order.instrument) { return callback("'instrument' is a required field"); } if (!order.units) { return callback("'units' is a required field"); } if (!order.side) { return callback("'side' is a required field. Specify 'buy' or 'sell'"); } if (!order.type) { return callback("'type' is a required field. Specify 'market', 'marketIfTouched', 'stop' or 'limit'"); } if ((order.type !== "market") && !order.expiry) { return callback("'expiry' is a required field for order type '" + order.type + "'"); } if ((order.type !== "market") && !order.price) { return callback("'price' is a required field for order type '" + order.type + "'"); } this._sendRESTRequest({ method: "POST", path: "/v1/accounts/" + accountId + "/orders", data: order, headers: { Authorization: "Bearer " + this.accessToken, "Content-Type": "application/x-www-form-urlencoded" }, }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } callback(null, body); }); }; OandaAdapter.prototype.closeTrade = function (accountId, tradeId, callback) { this._sendRESTRequest({ method: "DELETE", path: "/v1/accounts/" + accountId + "/trades/" + tradeId }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } if (body) { callback(null, body); } else { callback("Unexpected response for open positions"); } }); }; OandaAdapter.prototype.getOrders = function (accountId, callback) { this._sendRESTRequest({ method: "GET", path: "/v1/accounts/" + accountId + "/orders", headers: { Authorization: "Bearer " + this.accessToken, "Content-Type": "application/x-www-form-urlencoded" }, }, function (error, body, statusCode) { if (error) { if (body && body.message) { logger.error("Response from Oanda", statusCode + " Error: " + body.message + " (OANDA error code " + body.code + ")"); return callback(body.message); } return callback(error); } callback(null, body); }); }; OandaAdapter.prototype._sendRESTRequest = function (request, callback) { request.hostname = this.restHost; request.headers = request.headers || { Authorization: "Bearer " + this.accessToken }; request.secure = this.secure; httpClient.sendRequest(request, callback); }; OandaAdapter.prototype.kill = function () { if (this.pricesRequest) { this.pricesRequest.abort(); } if (this.eventsRequest) { this.eventsRequest.abort(); } this.off(); }; module.exports = OandaAdapter;
naddison36/oanda-adapter
OandaAdapter.js
JavaScript
mit
19,053
var nums = []; for (var i = 0; i < 100; ++i) { nums[i] = Math.floor(Math.random() * 101); } insertionsort(nums); dispArr(nums); print(); putstr("Enter a value to count: "); var val = parseInt(readline()); var retVal = count(nums, val); print("Found " + retVal + " occurrences of " + val + ".");
jomjose/js-algorithms
queues/queues (15).js
JavaScript
mit
309
import imageContainer from '../server/api/helpers/imageContainer'; const entries = [ { html: '<img src="/img/60x30.png" alt="60x30" class="zoom" data-zoom-src="/img/60x30-original.png">', }, { html: `<div> <img src="/img/20x50.jpg"> </div> <img src="/img/40x10.svg" alt="40x10">`, }, { html: '<div>Hello, World!</div>', }, ]; describe('ImageContainer', () => { const modifiedEntries = imageContainer(entries, __dirname); it('Parses one image', () => { expect(modifiedEntries[0].html).toContain('<div class="imageContainer" style="width: 60px;">'); expect(modifiedEntries[0].html).toContain('<div style="padding-bottom: 50%">'); }); it('Parses multiple images', () => { expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 20px;">'); expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 250%">'); expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 40px;">'); expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 25%">'); }); it('Doesn’t parse things it shouldn’t', () => { expect(modifiedEntries[2].html.length).toEqual(entries[2].html.length); }); it('Doesn’t crash when passing in an empty array', () => { const emptyEntries = []; expect(emptyEntries).toEqual(imageContainer(emptyEntries)); }); });
JohanLi/johanli.com
test/imageContainer.test.js
JavaScript
mit
1,395
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser files: [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
kyleaclark/game-of-life
karma.conf.js
JavaScript
mit
1,319
/* * Reading a variable. */ if (typeof print !== 'function') { print = console.log; } function test() { function outer() { var o = 123; return function inner() { var i; var t; for (i = 0; i < 1e6; i++) { t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; } }; } var f = outer(); f(); } try { test(); } catch (e) { print(e.stack || e); throw e; }
svaarala/duktape
tests/perf/test-var-read-outerscope-closed.js
JavaScript
mit
1,264
/* * Globalize Culture id * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd. */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "id", "default", { name: "id", englishName: "Indonesian", nativeName: "Bahasa Indonesia", language: "id", numberFormat: { ",": ".", ".": ",", percent: { ",": ".", ".": "," }, currency: { decimals: 0, ",": ".", ".": ",", symbol: "Rp" } }, calendars: { standard: { firstDay: 1, days: { names: ["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"], namesAbbr: ["Minggu","Sen","Sel","Rabu","Kamis","Jumat","Sabtu"], namesShort: ["M","S","S","R","K","J","S"] }, months: { names: ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","Nopember","Desember",""], namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agust","Sep","Okt","Nop","Des",""] }, AM: null, PM: null, patterns: { d: "dd/MM/yyyy", D: "dd MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "dd MMMM yyyy H:mm", F: "dd MMMM yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } } } }); }( this ));
bevacqua/jscharting
bundle/JSC/cultures/globalize.culture.id.js
JavaScript
mit
1,780
import omit from 'lodash/omit'; import get from 'lodash/get'; import isFunction from 'lodash/isFunction'; import { bunyanLevelToRollbarLevelName } from '../common/rollbar'; // Rollbar script exposes this global immediately, whether or not its already initialized export const isGlobalRollbarConfigured = () => !!get(global, 'Rollbar'); /** * Custom rollbar stream that transports to logentries from a browser * Wortks with a global Rollbar instance that is already initialized. * Note this expects rollbar to be loaded in the head, not via an npm module. * See https://rollbar.com/docs/notifier/rollbar.js/#quick-start for details on * integrating Rollbar in client apps * * @param {String} options.token * @param {String} options.environment * @param {String} options.codeVersion */ export default function ClientRollbarLogger({ token, environment, codeVersion }) { // Rollbar may already be initialized, but thats ok // https://rollbar.com/docs/notifier/rollbar.js/configuration/ global.Rollbar.configure({ accessToken: token, environment, captureUncaught: true, captureUnhandledRejections: true, payload: { environment, javascript: { code_version: codeVersion, source_map_enabled: true, }, }, }); } /** * Transport logs to Rollbar * @param {Object} data * @returns {undefined} */ ClientRollbarLogger.prototype.write = function (data = {}) { const rollbarLevelName = bunyanLevelToRollbarLevelName(data.level); const scopeData = omit(data, ['err', 'level']); const payload = Object.assign({ level: rollbarLevelName }, scopeData); // https://rollbar.com/docs/notifier/rollbar.js/#rollbarlog const logFn = global.Rollbar[rollbarLevelName]; if (isFunction(logFn)) { logFn.call(global.Rollbar, data.msg, data.err, payload); } else { global.Rollbar.error(data.msg, data.err, payload); } };
wework/we-js-logger
src/util/client/rollbarLogger.js
JavaScript
mit
1,896
import EmberObject from '@ember/object'; import { htmlSafe } from '@ember/string'; import RSVP from 'rsvp'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, settled, find, click } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; const { resolve } = RSVP; module('Integration | Component | school session types list', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { assert.expect(19); let assessmentOption = EmberObject.create({ id: 1, name: 'formative' }); let sessionType1 = EmberObject.create({ id: 1, school: 1, title: 'not needed anymore', assessment: false, assessmentOption: resolve(null), safeCalendarColor: htmlSafe('#ffffff'), sessionCount: 2, active: false, }); let sessionType2 = EmberObject.create({ id: 2, school: 1, title: 'second', assessment: true, assessmentOption: resolve(assessmentOption), safeCalendarColor: htmlSafe('#123456'), sessionCount: 0, active: true, }); let sessionType3 = EmberObject.create({ id: 2, school: 1, title: 'first', assessment: false, assessmentOption: resolve(null), safeCalendarColor: htmlSafe('#cccccc'), sessionCount: 2, active: true, }); this.set('sessionTypes', [sessionType1, sessionType2, sessionType3]); this.set('nothing', parseInt); await render(hbs`{{school-session-types-list sessionTypes=sessionTypes manageSessionType=(action nothing) }}`); const rows = 'table tbody tr'; const firstSessionType = `${rows}:nth-of-type(1)`; const firstTitle = `${firstSessionType} td:nth-of-type(1)`; const firstSessionCount = `${firstSessionType} td:nth-of-type(2)`; const firstAssessment = `${firstSessionType} td:nth-of-type(3) svg`; const firstAssessmentOption = `${firstSessionType} td:nth-of-type(4)`; const firstColorBox = `${firstSessionType} td:nth-of-type(6) .box`; const secondSessionType = `${rows}:nth-of-type(2)`; const secondTitle = `${secondSessionType} td:nth-of-type(1)`; const secondSessionCount = `${secondSessionType} td:nth-of-type(2)`; const secondAssessment = `${secondSessionType} td:nth-of-type(3) svg`; const secondAssessmentOption = `${secondSessionType} td:nth-of-type(4)`; const secondColorBox = `${secondSessionType} td:nth-of-type(6) .box`; const thirdSessionType = `${rows}:nth-of-type(3)`; const thirdTitle = `${thirdSessionType} td:nth-of-type(1)`; const thirdSessionCount = `${thirdSessionType} td:nth-of-type(2)`; const thirdAssessment = `${thirdSessionType} td:nth-of-type(3) svg`; const thirdAssessmentOption = `${thirdSessionType} td:nth-of-type(4)`; const thirdColorBox = `${thirdSessionType} td:nth-of-type(6) .box`; assert.dom(firstTitle).hasText('first'); assert.dom(firstSessionCount).hasText('2'); assert.dom(firstAssessment).hasClass('no'); assert.dom(firstAssessment).hasClass('fa-ban'); assert.dom(firstAssessmentOption).hasText(''); assert.equal(find(firstColorBox).style.getPropertyValue('background-color').trim(), ('rgb(204, 204, 204)')); assert.dom(secondTitle).hasText('second'); assert.dom(secondSessionCount).hasText('0'); assert.dom(secondAssessment).hasClass('yes'); assert.dom(secondAssessment).hasClass('fa-check'); assert.dom(secondAssessmentOption).hasText('formative'); assert.equal(find(secondColorBox).style.getPropertyValue('background-color').trim(), ('rgb(18, 52, 86)')); assert.ok(find(thirdTitle).textContent.trim().startsWith('not needed anymore')); assert.ok(find(thirdTitle).textContent.trim().endsWith('(inactive)')); assert.dom(thirdSessionCount).hasText('2'); assert.dom(thirdAssessment).hasClass('no'); assert.dom(thirdAssessment).hasClass('fa-ban'); assert.dom(thirdAssessmentOption).hasText(''); assert.equal(find(thirdColorBox).style.getPropertyValue('background-color').trim(), ('rgb(255, 255, 255)')); }); test('clicking edit fires action', async function(assert) { assert.expect(1); let sessionType = EmberObject.create({ id: 1, school: 1, title: 'first', assessment: false, assessmentOption: resolve(null), calendarColor: '#fff' }); this.set('sessionTypes', [sessionType]); this.set('manageSessionType', sessionTypeId => { assert.equal(sessionTypeId, 1); }); await render(hbs`{{school-session-types-list sessionTypes=sessionTypes manageSessionType=(action manageSessionType) }}`); await settled(); const rows = 'table tbody tr'; const edit = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-edit`; await click(edit); }); test('clicking title fires action', async function(assert) { assert.expect(1); let sessionType = EmberObject.create({ id: 1, school: 1, title: 'first', assessment: false, assessmentOption: resolve(null), calendarColor: '#fff' }); this.set('sessionTypes', [sessionType]); this.set('manageSessionType', sessionTypeId => { assert.equal(sessionTypeId, 1); }); await render(hbs`{{school-session-types-list sessionTypes=sessionTypes manageSessionType=(action manageSessionType) }}`); await settled(); const rows = 'table tbody tr'; const title = `${rows}:nth-of-type(1) td:nth-of-type(1) a`; await click(title); }); test('session types without sessions can be deleted', async function(assert) { assert.expect(4); let unlinkedSessionType = EmberObject.create({ id: 1, school: 1, title: 'unlinked', active: true, assessment: false, assessmentOption: resolve(null), calendarColor: '#fff', sessionCount: 0, deleteRecord(){ assert.ok(true, 'was deleted'); return resolve(); } }); let linkedSessionType = EmberObject.create({ id: 1, school: 1, title: 'linked', active: true, assessment: false, assessmentOption: resolve(null), calendarColor: '#fff', sessionCount: 5, deleteRecord(){ assert.ok(true, 'was deleted'); return resolve(); } }); this.set('sessionTypes', [linkedSessionType, unlinkedSessionType]); this.set('nothing', parseInt); await render(hbs`{{school-session-types-list sessionTypes=sessionTypes manageSessionType=(action nothing) canDelete=true }}`); await settled(); const rows = 'table tbody tr'; const linkedTitle = `${rows}:nth-of-type(1) td:nth-of-type(1)`; const unlinkedTitle = `${rows}:nth-of-type(2) td:nth-of-type(1)`; const linkedTrash = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-trash.disabled`; const unlinkedTrash = `${rows}:nth-of-type(2) td:nth-of-type(7) .fa-trash.enabled`; assert.dom(linkedTitle).hasText('linked', 'linked is first'); assert.dom(unlinkedTitle).hasText('unlinked', 'unlinked is second'); assert.dom(linkedTrash).exists({ count: 1 }, 'linked has a disabled trash can'); assert.dom(unlinkedTrash).exists({ count: 1 }, 'unlinked has an enabled trash can'); }); test('clicking delete deletes the record', async function(assert) { assert.expect(2); let sessionType = EmberObject.create({ id: 1, school: 1, title: 'first', assessment: false, assessmentOption: resolve(null), calendarColor: '#fff', sessionCount: 0, deleteRecord(){ assert.ok(true, 'was deleted'); }, save(){ assert.ok(true, 'was deleted'); return resolve(); }, }); this.set('sessionTypes', [sessionType]); this.set('nothing', parseInt); await render(hbs`{{school-session-types-list sessionTypes=sessionTypes manageSessionType=(action nothing) canDelete=true }}`); await settled(); const rows = 'table tbody tr'; const trash = `${rows}:nth-of-type(1) td:nth-of-type(7) .fa-trash`; await click(trash); await settled(); }); });
djvoa12/frontend
tests/integration/components/school-session-types-list-test.js
JavaScript
mit
8,230
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // define the schema for our user model var authUserSchema = mongoose.Schema({ unique_ID : String, username : String, password : String, role : String, first_name : String, last_name : String }); // methods ====================== // generating a hash authUserSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid authUserSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.password); }; // create the model for users and expose it to our app module.exports = mongoose.model('authUser', authUserSchema);
ishwant/Auth-Server
app/models/authUser.js
JavaScript
mit
791
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var Lib = require('../../lib'); // The contour extraction is great, except it totally fails for constraints because we // need weird range loops and flipped contours instead of the usual format. This function // does some weird manipulation of the extracted pathinfo data such that it magically // draws contours correctly *as* constraints. module.exports = function(pathinfo, operation) { var i, pi0, pi1; var op0 = function(arr) { return arr.reverse(); }; var op1 = function(arr) { return arr; }; switch(operation) { case '][': case ')[': case '](': case ')(': var tmp = op0; op0 = op1; op1 = tmp; // It's a nice rule, except this definitely *is* what's intended here. /* eslint-disable: no-fallthrough */ case '[]': case '[)': case '(]': case '()': /* eslint-enable: no-fallthrough */ if(pathinfo.length !== 2) { Lib.warn('Contour data invalid for the specified inequality range operation.'); return; } // In this case there should be exactly two contour levels in pathinfo. We // simply concatenate the info into one pathinfo and flip all of the data // in one. This will draw the contour as closed. pi0 = pathinfo[0]; pi1 = pathinfo[1]; for(i = 0; i < pi0.edgepaths.length; i++) { pi0.edgepaths[i] = op0(pi0.edgepaths[i]); } for(i = 0; i < pi0.paths.length; i++) { pi0.paths[i] = op0(pi0.paths[i]); } while(pi1.edgepaths.length) { pi0.edgepaths.push(op1(pi1.edgepaths.shift())); } while(pi1.paths.length) { pi0.paths.push(op1(pi1.paths.shift())); } pathinfo.pop(); break; case '>=': case '>': if(pathinfo.length !== 1) { Lib.warn('Contour data invalid for the specified inequality operation.'); return; } // In this case there should be exactly two contour levels in pathinfo. We // simply concatenate the info into one pathinfo and flip all of the data // in one. This will draw the contour as closed. pi0 = pathinfo[0]; for(i = 0; i < pi0.edgepaths.length; i++) { pi0.edgepaths[i] = op0(pi0.edgepaths[i]); } for(i = 0; i < pi0.paths.length; i++) { pi0.paths[i] = op0(pi0.paths[i]); } break; } };
iongroup/plotly.js
src/traces/contourcarpet/convert_to_constraints.js
JavaScript
mit
2,890
module.exports = { defersToPromises : function(defers) { if(Array.isArray(defers)) { return defers.map(function(defer) { return defer && defer.promise ? defer.promise : defer; }); } var res = {}; Object.keys(defers).forEach(function(key) { res[key] = defers[key] && defers[key].promise ? defers[key].promise : defer; }); return res; } };
stenin-nikita/module-promise
test/utils/helpers.js
JavaScript
mit
518
export default (sequelize, DataTypes) => { const Product = sequelize.define('Product', { name: DataTypes.STRING, description: DataTypes.TEXT, price: DataTypes.FLOAT, releasedate: DataTypes.DATE }, { classMethods: { associate: models => { Product.belongsToMany(models.Cart, {through: 'ProductCart'}); Product.belongsToMany(models.Platform, {through: 'ProductPlatform'}); Product.belongsTo(models.SpecialEdition); } } }); return Product; };
Kennyomg/gamersonline-uni
api/models/product.js
JavaScript
mit
508
import { SET_SORT_ORDER } from '../constants/actions'; export default function (state = 'ASCENDING', action) { switch (action.type) { case SET_SORT_ORDER: return action.order; default: return state; } }
ColdForge/icebox
src/reducers/sortOrderReducer.js
JavaScript
mit
212
import mongoose from 'mongoose'; const ModelPortfolioSchema = new mongoose.Schema({ id: String, name: String, displayName: String, email: String, securities: [{ symbol: String, allocation: {type: Number, min: 0, max: 100}, }] }); ModelPortfolioSchema.add({ subGroups: [ModelPortfolioSchema], modelPortfolios: [ModelPortfolioSchema], }); export default mongoose.model('ModelPortfolio', ModelPortfolioSchema);
AlexisDeschamps/portfolio-rebalancer
server/db/mongo/models/modelPortfolio.js
JavaScript
mit
430
import React, { Component } from 'react'; class Home extends Component { render () { return ( <div> <h1>Home</h1> <p>Bienvenidos!!!</p> <pre>{` { path: '/', pathExact: true, component: Home }, { path: '/pageOne', pathExact: true, component: PageOne }, { path: '/pageTwo', pathExact: true, component: PageTwo }, { path: '/pageThree', pathExact: true, auth: true, component: PageThree, routes: [ // PAGE 3/ADD { path: '/pageThree/add', pathExact: true, auth: true, component: PageThreeAdd }, // PAGE 4 { path: '/pageFour/:id/:action', auth: true, component: PageFour } ] }, // 404 NOT FOUND { component: NotFound } `} </pre> </div> ); } } export default Home;
gabriel-lopez-lopez/dynamic-react-route
dynamic-react-router demo/src/Components/Home/index.js
JavaScript
mit
1,789
define('findScriptUrls', [], function () { return function(pattern) { var type = typeof pattern, i, tags = document.querySelectorAll("script"), matches = [], src; for (i = 0; i < tags.length; i++) { src = tags[i].src || ""; if (type === "string") { if (src.indexOf(pattern) !== -1) { matches.push(src); } } else if (pattern.test(src)) { matches.push(src); } } return matches; }; });
obogo/hummingbird
src/utils/browser/findScriptUrls.js
JavaScript
mit
538
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2015-05-11 using // generator-karma 0.8.3 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
jjp12383/Portfolio
test/karma.conf.js
JavaScript
mit
1,620
var indexSectionsWithContent = { 0: "dfrsw~", 1: "drs", 2: "dfrs~", 3: "rs", 4: "w" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "functions", 3: "variables", 4: "pages" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Functions", 3: "Variables", 4: "Pages" };
sabertazimi/hust-lab
network/webserver/docs/search/searchdata.js
JavaScript
mit
313
var pub = {}, Q, Knex; module.exports = function ($inject) { $inject = $inject || {}; Q = $inject.Q; Knex = $inject.Knex; return pub; }; pub.get = function(tableName) { var q = Q.defer(); pub.getMetadata(tableName) .then(function(relations) { q.resolve(relations[0]); }); return q.promise; }; pub.getMetadata = function(tableName) { return Knex.knex.raw('SELECT ' + 'KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, ' + 'KCU1.COLUMN_NAME AS FK_COLUMN_NAME, ' + 'KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME, ' + 'KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME, ' + 'KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME ' + 'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' + 'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 ' + 'ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG ' + 'AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA ' + 'AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME ' + 'AND KCU1.TABLE_NAME = RC.TABLE_NAME ' + 'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 ' + 'ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG ' + 'AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA ' + 'AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME ' + 'AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION ' + 'AND KCU2.TABLE_NAME = RC.REFERENCED_TABLE_NAME ' + 'WHERE kcu1.table_name = ?', tableName); };
heinzelmannchen/mysql2json
lib/relations.js
JavaScript
mit
1,911
// Compiled by ClojureScript 1.7.170 {} goog.provide('figwheel.client.file_reloading'); goog.require('cljs.core'); goog.require('goog.string'); goog.require('goog.Uri'); goog.require('goog.net.jsloader'); goog.require('cljs.core.async'); goog.require('goog.object'); goog.require('clojure.set'); goog.require('clojure.string'); goog.require('figwheel.client.utils'); figwheel.client.file_reloading.queued_file_reload; if(typeof figwheel.client.file_reloading.figwheel_meta_pragmas !== 'undefined'){ } else { figwheel.client.file_reloading.figwheel_meta_pragmas = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); } figwheel.client.file_reloading.on_jsload_custom_event = (function figwheel$client$file_reloading$on_jsload_custom_event(url){ return figwheel.client.utils.dispatch_custom_event.call(null,"figwheel.js-reload",url); }); figwheel.client.file_reloading.before_jsload_custom_event = (function figwheel$client$file_reloading$before_jsload_custom_event(files){ return figwheel.client.utils.dispatch_custom_event.call(null,"figwheel.before-js-reload",files); }); figwheel.client.file_reloading.namespace_file_map_QMARK_ = (function figwheel$client$file_reloading$namespace_file_map_QMARK_(m){ var or__16826__auto__ = (cljs.core.map_QMARK_.call(null,m)) && (typeof new cljs.core.Keyword(null,"namespace","namespace",-377510372).cljs$core$IFn$_invoke$arity$1(m) === 'string') && (((new cljs.core.Keyword(null,"file","file",-1269645878).cljs$core$IFn$_invoke$arity$1(m) == null)) || (typeof new cljs.core.Keyword(null,"file","file",-1269645878).cljs$core$IFn$_invoke$arity$1(m) === 'string')) && (cljs.core._EQ_.call(null,new cljs.core.Keyword(null,"type","type",1174270348).cljs$core$IFn$_invoke$arity$1(m),new cljs.core.Keyword(null,"namespace","namespace",-377510372))); if(or__16826__auto__){ return or__16826__auto__; } else { cljs.core.println.call(null,"Error not namespace-file-map",cljs.core.pr_str.call(null,m)); return false; } }); figwheel.client.file_reloading.add_cache_buster = (function figwheel$client$file_reloading$add_cache_buster(url){ return goog.Uri.parse(url).makeUnique(); }); figwheel.client.file_reloading.name__GT_path = (function figwheel$client$file_reloading$name__GT_path(ns){ return (goog.dependencies_.nameToPath[ns]); }); figwheel.client.file_reloading.provided_QMARK_ = (function figwheel$client$file_reloading$provided_QMARK_(ns){ return (goog.dependencies_.written[figwheel.client.file_reloading.name__GT_path.call(null,ns)]); }); figwheel.client.file_reloading.fix_node_request_url = (function figwheel$client$file_reloading$fix_node_request_url(url){ if(cljs.core.truth_(goog.string.startsWith(url,"../"))){ return clojure.string.replace.call(null,url,"../",""); } else { return [cljs.core.str("goog/"),cljs.core.str(url)].join(''); } }); figwheel.client.file_reloading.immutable_ns_QMARK_ = (function figwheel$client$file_reloading$immutable_ns_QMARK_(name){ var or__16826__auto__ = new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 9, ["svgpan.SvgPan",null,"far.out",null,"testDep.bar",null,"someprotopackage.TestPackageTypes",null,"goog",null,"an.existing.path",null,"cljs.core",null,"ns",null,"dup.base",null], null), null).call(null,name); if(cljs.core.truth_(or__16826__auto__)){ return or__16826__auto__; } else { return cljs.core.some.call(null,cljs.core.partial.call(null,goog.string.startsWith,name),new cljs.core.PersistentVector(null, 5, 5, cljs.core.PersistentVector.EMPTY_NODE, ["goog.","cljs.","clojure.","fake.","proto2."], null)); } }); figwheel.client.file_reloading.get_requires = (function figwheel$client$file_reloading$get_requires(ns){ return cljs.core.set.call(null,cljs.core.filter.call(null,(function (p1__23844_SHARP_){ return cljs.core.not.call(null,figwheel.client.file_reloading.immutable_ns_QMARK_.call(null,p1__23844_SHARP_)); }),goog.object.getKeys((goog.dependencies_.requires[figwheel.client.file_reloading.name__GT_path.call(null,ns)])))); }); if(typeof figwheel.client.file_reloading.dependency_data !== 'undefined'){ } else { figwheel.client.file_reloading.dependency_data = cljs.core.atom.call(null,new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"pathToName","pathToName",-1236616181),cljs.core.PersistentArrayMap.EMPTY,new cljs.core.Keyword(null,"dependents","dependents",136812837),cljs.core.PersistentArrayMap.EMPTY], null)); } figwheel.client.file_reloading.path_to_name_BANG_ = (function figwheel$client$file_reloading$path_to_name_BANG_(path,name){ return cljs.core.swap_BANG_.call(null,figwheel.client.file_reloading.dependency_data,cljs.core.update_in,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"pathToName","pathToName",-1236616181),path], null),cljs.core.fnil.call(null,clojure.set.union,cljs.core.PersistentHashSet.EMPTY),cljs.core.PersistentHashSet.fromArray([name], true)); }); /** * Setup a path to name dependencies map. * That goes from path -> #{ ns-names } */ figwheel.client.file_reloading.setup_path__GT_name_BANG_ = (function figwheel$client$file_reloading$setup_path__GT_name_BANG_(){ var nameToPath = goog.object.filter(goog.dependencies_.nameToPath,(function (v,k,o){ return goog.string.startsWith(v,"../"); })); return goog.object.forEach(nameToPath,((function (nameToPath){ return (function (v,k,o){ return figwheel.client.file_reloading.path_to_name_BANG_.call(null,v,k); });})(nameToPath)) ); }); /** * returns a set of namespaces defined by a path */ figwheel.client.file_reloading.path__GT_name = (function figwheel$client$file_reloading$path__GT_name(path){ return cljs.core.get_in.call(null,cljs.core.deref.call(null,figwheel.client.file_reloading.dependency_data),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"pathToName","pathToName",-1236616181),path], null)); }); figwheel.client.file_reloading.name_to_parent_BANG_ = (function figwheel$client$file_reloading$name_to_parent_BANG_(ns,parent_ns){ return cljs.core.swap_BANG_.call(null,figwheel.client.file_reloading.dependency_data,cljs.core.update_in,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"dependents","dependents",136812837),ns], null),cljs.core.fnil.call(null,clojure.set.union,cljs.core.PersistentHashSet.EMPTY),cljs.core.PersistentHashSet.fromArray([parent_ns], true)); }); /** * This reverses the goog.dependencies_.requires for looking up ns-dependents. */ figwheel.client.file_reloading.setup_ns__GT_dependents_BANG_ = (function figwheel$client$file_reloading$setup_ns__GT_dependents_BANG_(){ var requires = goog.object.filter(goog.dependencies_.requires,(function (v,k,o){ return goog.string.startsWith(k,"../"); })); return goog.object.forEach(requires,((function (requires){ return (function (v,k,_){ return goog.object.forEach(v,((function (requires){ return (function (v_SINGLEQUOTE_,k_SINGLEQUOTE_,___$1){ var seq__23849 = cljs.core.seq.call(null,figwheel.client.file_reloading.path__GT_name.call(null,k)); var chunk__23850 = null; var count__23851 = (0); var i__23852 = (0); while(true){ if((i__23852 < count__23851)){ var n = cljs.core._nth.call(null,chunk__23850,i__23852); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,k_SINGLEQUOTE_,n); var G__23853 = seq__23849; var G__23854 = chunk__23850; var G__23855 = count__23851; var G__23856 = (i__23852 + (1)); seq__23849 = G__23853; chunk__23850 = G__23854; count__23851 = G__23855; i__23852 = G__23856; continue; } else { var temp__4425__auto__ = cljs.core.seq.call(null,seq__23849); if(temp__4425__auto__){ var seq__23849__$1 = temp__4425__auto__; if(cljs.core.chunked_seq_QMARK_.call(null,seq__23849__$1)){ var c__17629__auto__ = cljs.core.chunk_first.call(null,seq__23849__$1); var G__23857 = cljs.core.chunk_rest.call(null,seq__23849__$1); var G__23858 = c__17629__auto__; var G__23859 = cljs.core.count.call(null,c__17629__auto__); var G__23860 = (0); seq__23849 = G__23857; chunk__23850 = G__23858; count__23851 = G__23859; i__23852 = G__23860; continue; } else { var n = cljs.core.first.call(null,seq__23849__$1); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,k_SINGLEQUOTE_,n); var G__23861 = cljs.core.next.call(null,seq__23849__$1); var G__23862 = null; var G__23863 = (0); var G__23864 = (0); seq__23849 = G__23861; chunk__23850 = G__23862; count__23851 = G__23863; i__23852 = G__23864; continue; } } else { return null; } } break; } });})(requires)) ); });})(requires)) ); }); figwheel.client.file_reloading.ns__GT_dependents = (function figwheel$client$file_reloading$ns__GT_dependents(ns){ return cljs.core.get_in.call(null,cljs.core.deref.call(null,figwheel.client.file_reloading.dependency_data),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"dependents","dependents",136812837),ns], null)); }); figwheel.client.file_reloading.build_topo_sort = (function figwheel$client$file_reloading$build_topo_sort(get_deps){ var get_deps__$1 = cljs.core.memoize.call(null,get_deps); var topo_sort_helper_STAR_ = ((function (get_deps__$1){ return (function figwheel$client$file_reloading$build_topo_sort_$_topo_sort_helper_STAR_(x,depth,state){ var deps = get_deps__$1.call(null,x); if(cljs.core.empty_QMARK_.call(null,deps)){ return null; } else { return topo_sort_STAR_.call(null,deps,depth,state); } });})(get_deps__$1)) ; var topo_sort_STAR_ = ((function (get_deps__$1){ return (function() { var figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_ = null; var figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___1 = (function (deps){ return figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_.call(null,deps,(0),cljs.core.atom.call(null,cljs.core.sorted_map.call(null))); }); var figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___3 = (function (deps,depth,state){ cljs.core.swap_BANG_.call(null,state,cljs.core.update_in,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [depth], null),cljs.core.fnil.call(null,cljs.core.into,cljs.core.PersistentHashSet.EMPTY),deps); var seq__23903_23910 = cljs.core.seq.call(null,deps); var chunk__23904_23911 = null; var count__23905_23912 = (0); var i__23906_23913 = (0); while(true){ if((i__23906_23913 < count__23905_23912)){ var dep_23914 = cljs.core._nth.call(null,chunk__23904_23911,i__23906_23913); topo_sort_helper_STAR_.call(null,dep_23914,(depth + (1)),state); var G__23915 = seq__23903_23910; var G__23916 = chunk__23904_23911; var G__23917 = count__23905_23912; var G__23918 = (i__23906_23913 + (1)); seq__23903_23910 = G__23915; chunk__23904_23911 = G__23916; count__23905_23912 = G__23917; i__23906_23913 = G__23918; continue; } else { var temp__4425__auto___23919 = cljs.core.seq.call(null,seq__23903_23910); if(temp__4425__auto___23919){ var seq__23903_23920__$1 = temp__4425__auto___23919; if(cljs.core.chunked_seq_QMARK_.call(null,seq__23903_23920__$1)){ var c__17629__auto___23921 = cljs.core.chunk_first.call(null,seq__23903_23920__$1); var G__23922 = cljs.core.chunk_rest.call(null,seq__23903_23920__$1); var G__23923 = c__17629__auto___23921; var G__23924 = cljs.core.count.call(null,c__17629__auto___23921); var G__23925 = (0); seq__23903_23910 = G__23922; chunk__23904_23911 = G__23923; count__23905_23912 = G__23924; i__23906_23913 = G__23925; continue; } else { var dep_23926 = cljs.core.first.call(null,seq__23903_23920__$1); topo_sort_helper_STAR_.call(null,dep_23926,(depth + (1)),state); var G__23927 = cljs.core.next.call(null,seq__23903_23920__$1); var G__23928 = null; var G__23929 = (0); var G__23930 = (0); seq__23903_23910 = G__23927; chunk__23904_23911 = G__23928; count__23905_23912 = G__23929; i__23906_23913 = G__23930; continue; } } else { } } break; } if(cljs.core._EQ_.call(null,depth,(0))){ return elim_dups_STAR_.call(null,cljs.core.reverse.call(null,cljs.core.vals.call(null,cljs.core.deref.call(null,state)))); } else { return null; } }); figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_ = function(deps,depth,state){ switch(arguments.length){ case 1: return figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___1.call(this,deps); case 3: return figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___3.call(this,deps,depth,state); } throw(new Error('Invalid arity: ' + arguments.length)); }; figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_.cljs$core$IFn$_invoke$arity$1 = figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___1; figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_.cljs$core$IFn$_invoke$arity$3 = figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR___3; return figwheel$client$file_reloading$build_topo_sort_$_topo_sort_STAR_; })() ;})(get_deps__$1)) ; var elim_dups_STAR_ = ((function (get_deps__$1){ return (function figwheel$client$file_reloading$build_topo_sort_$_elim_dups_STAR_(p__23907){ var vec__23909 = p__23907; var x = cljs.core.nth.call(null,vec__23909,(0),null); var xs = cljs.core.nthnext.call(null,vec__23909,(1)); if((x == null)){ return cljs.core.List.EMPTY; } else { return cljs.core.cons.call(null,x,figwheel$client$file_reloading$build_topo_sort_$_elim_dups_STAR_.call(null,cljs.core.map.call(null,((function (vec__23909,x,xs,get_deps__$1){ return (function (p1__23865_SHARP_){ return clojure.set.difference.call(null,p1__23865_SHARP_,x); });})(vec__23909,x,xs,get_deps__$1)) ,xs))); } });})(get_deps__$1)) ; return topo_sort_STAR_; }); figwheel.client.file_reloading.get_all_dependencies = (function figwheel$client$file_reloading$get_all_dependencies(ns){ var topo_sort_SINGLEQUOTE_ = figwheel.client.file_reloading.build_topo_sort.call(null,figwheel.client.file_reloading.get_requires); return cljs.core.apply.call(null,cljs.core.concat,topo_sort_SINGLEQUOTE_.call(null,cljs.core.set.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [ns], null)))); }); figwheel.client.file_reloading.get_all_dependents = (function figwheel$client$file_reloading$get_all_dependents(nss){ var topo_sort_SINGLEQUOTE_ = figwheel.client.file_reloading.build_topo_sort.call(null,figwheel.client.file_reloading.ns__GT_dependents); return cljs.core.reverse.call(null,cljs.core.apply.call(null,cljs.core.concat,topo_sort_SINGLEQUOTE_.call(null,cljs.core.set.call(null,nss)))); }); figwheel.client.file_reloading.unprovide_BANG_ = (function figwheel$client$file_reloading$unprovide_BANG_(ns){ var path = figwheel.client.file_reloading.name__GT_path.call(null,ns); goog.object.remove(goog.dependencies_.visited,path); goog.object.remove(goog.dependencies_.written,path); return goog.object.remove(goog.dependencies_.written,[cljs.core.str(goog.basePath),cljs.core.str(path)].join('')); }); figwheel.client.file_reloading.resolve_ns = (function figwheel$client$file_reloading$resolve_ns(ns){ return [cljs.core.str(goog.basePath),cljs.core.str(figwheel.client.file_reloading.name__GT_path.call(null,ns))].join(''); }); figwheel.client.file_reloading.addDependency = (function figwheel$client$file_reloading$addDependency(path,provides,requires){ var seq__23943 = cljs.core.seq.call(null,provides); var chunk__23944 = null; var count__23945 = (0); var i__23946 = (0); while(true){ if((i__23946 < count__23945)){ var prov = cljs.core._nth.call(null,chunk__23944,i__23946); figwheel.client.file_reloading.path_to_name_BANG_.call(null,path,prov); var seq__23947_23955 = cljs.core.seq.call(null,requires); var chunk__23948_23956 = null; var count__23949_23957 = (0); var i__23950_23958 = (0); while(true){ if((i__23950_23958 < count__23949_23957)){ var req_23959 = cljs.core._nth.call(null,chunk__23948_23956,i__23950_23958); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,req_23959,prov); var G__23960 = seq__23947_23955; var G__23961 = chunk__23948_23956; var G__23962 = count__23949_23957; var G__23963 = (i__23950_23958 + (1)); seq__23947_23955 = G__23960; chunk__23948_23956 = G__23961; count__23949_23957 = G__23962; i__23950_23958 = G__23963; continue; } else { var temp__4425__auto___23964 = cljs.core.seq.call(null,seq__23947_23955); if(temp__4425__auto___23964){ var seq__23947_23965__$1 = temp__4425__auto___23964; if(cljs.core.chunked_seq_QMARK_.call(null,seq__23947_23965__$1)){ var c__17629__auto___23966 = cljs.core.chunk_first.call(null,seq__23947_23965__$1); var G__23967 = cljs.core.chunk_rest.call(null,seq__23947_23965__$1); var G__23968 = c__17629__auto___23966; var G__23969 = cljs.core.count.call(null,c__17629__auto___23966); var G__23970 = (0); seq__23947_23955 = G__23967; chunk__23948_23956 = G__23968; count__23949_23957 = G__23969; i__23950_23958 = G__23970; continue; } else { var req_23971 = cljs.core.first.call(null,seq__23947_23965__$1); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,req_23971,prov); var G__23972 = cljs.core.next.call(null,seq__23947_23965__$1); var G__23973 = null; var G__23974 = (0); var G__23975 = (0); seq__23947_23955 = G__23972; chunk__23948_23956 = G__23973; count__23949_23957 = G__23974; i__23950_23958 = G__23975; continue; } } else { } } break; } var G__23976 = seq__23943; var G__23977 = chunk__23944; var G__23978 = count__23945; var G__23979 = (i__23946 + (1)); seq__23943 = G__23976; chunk__23944 = G__23977; count__23945 = G__23978; i__23946 = G__23979; continue; } else { var temp__4425__auto__ = cljs.core.seq.call(null,seq__23943); if(temp__4425__auto__){ var seq__23943__$1 = temp__4425__auto__; if(cljs.core.chunked_seq_QMARK_.call(null,seq__23943__$1)){ var c__17629__auto__ = cljs.core.chunk_first.call(null,seq__23943__$1); var G__23980 = cljs.core.chunk_rest.call(null,seq__23943__$1); var G__23981 = c__17629__auto__; var G__23982 = cljs.core.count.call(null,c__17629__auto__); var G__23983 = (0); seq__23943 = G__23980; chunk__23944 = G__23981; count__23945 = G__23982; i__23946 = G__23983; continue; } else { var prov = cljs.core.first.call(null,seq__23943__$1); figwheel.client.file_reloading.path_to_name_BANG_.call(null,path,prov); var seq__23951_23984 = cljs.core.seq.call(null,requires); var chunk__23952_23985 = null; var count__23953_23986 = (0); var i__23954_23987 = (0); while(true){ if((i__23954_23987 < count__23953_23986)){ var req_23988 = cljs.core._nth.call(null,chunk__23952_23985,i__23954_23987); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,req_23988,prov); var G__23989 = seq__23951_23984; var G__23990 = chunk__23952_23985; var G__23991 = count__23953_23986; var G__23992 = (i__23954_23987 + (1)); seq__23951_23984 = G__23989; chunk__23952_23985 = G__23990; count__23953_23986 = G__23991; i__23954_23987 = G__23992; continue; } else { var temp__4425__auto___23993__$1 = cljs.core.seq.call(null,seq__23951_23984); if(temp__4425__auto___23993__$1){ var seq__23951_23994__$1 = temp__4425__auto___23993__$1; if(cljs.core.chunked_seq_QMARK_.call(null,seq__23951_23994__$1)){ var c__17629__auto___23995 = cljs.core.chunk_first.call(null,seq__23951_23994__$1); var G__23996 = cljs.core.chunk_rest.call(null,seq__23951_23994__$1); var G__23997 = c__17629__auto___23995; var G__23998 = cljs.core.count.call(null,c__17629__auto___23995); var G__23999 = (0); seq__23951_23984 = G__23996; chunk__23952_23985 = G__23997; count__23953_23986 = G__23998; i__23954_23987 = G__23999; continue; } else { var req_24000 = cljs.core.first.call(null,seq__23951_23994__$1); figwheel.client.file_reloading.name_to_parent_BANG_.call(null,req_24000,prov); var G__24001 = cljs.core.next.call(null,seq__23951_23994__$1); var G__24002 = null; var G__24003 = (0); var G__24004 = (0); seq__23951_23984 = G__24001; chunk__23952_23985 = G__24002; count__23953_23986 = G__24003; i__23954_23987 = G__24004; continue; } } else { } } break; } var G__24005 = cljs.core.next.call(null,seq__23943__$1); var G__24006 = null; var G__24007 = (0); var G__24008 = (0); seq__23943 = G__24005; chunk__23944 = G__24006; count__23945 = G__24007; i__23946 = G__24008; continue; } } else { return null; } } break; } }); figwheel.client.file_reloading.figwheel_require = (function figwheel$client$file_reloading$figwheel_require(src,reload){ goog.require = figwheel$client$file_reloading$figwheel_require; if(cljs.core._EQ_.call(null,reload,"reload-all")){ var seq__24013_24017 = cljs.core.seq.call(null,figwheel.client.file_reloading.get_all_dependencies.call(null,src)); var chunk__24014_24018 = null; var count__24015_24019 = (0); var i__24016_24020 = (0); while(true){ if((i__24016_24020 < count__24015_24019)){ var ns_24021 = cljs.core._nth.call(null,chunk__24014_24018,i__24016_24020); figwheel.client.file_reloading.unprovide_BANG_.call(null,ns_24021); var G__24022 = seq__24013_24017; var G__24023 = chunk__24014_24018; var G__24024 = count__24015_24019; var G__24025 = (i__24016_24020 + (1)); seq__24013_24017 = G__24022; chunk__24014_24018 = G__24023; count__24015_24019 = G__24024; i__24016_24020 = G__24025; continue; } else { var temp__4425__auto___24026 = cljs.core.seq.call(null,seq__24013_24017); if(temp__4425__auto___24026){ var seq__24013_24027__$1 = temp__4425__auto___24026; if(cljs.core.chunked_seq_QMARK_.call(null,seq__24013_24027__$1)){ var c__17629__auto___24028 = cljs.core.chunk_first.call(null,seq__24013_24027__$1); var G__24029 = cljs.core.chunk_rest.call(null,seq__24013_24027__$1); var G__24030 = c__17629__auto___24028; var G__24031 = cljs.core.count.call(null,c__17629__auto___24028); var G__24032 = (0); seq__24013_24017 = G__24029; chunk__24014_24018 = G__24030; count__24015_24019 = G__24031; i__24016_24020 = G__24032; continue; } else { var ns_24033 = cljs.core.first.call(null,seq__24013_24027__$1); figwheel.client.file_reloading.unprovide_BANG_.call(null,ns_24033); var G__24034 = cljs.core.next.call(null,seq__24013_24027__$1); var G__24035 = null; var G__24036 = (0); var G__24037 = (0); seq__24013_24017 = G__24034; chunk__24014_24018 = G__24035; count__24015_24019 = G__24036; i__24016_24020 = G__24037; continue; } } else { } } break; } } else { } if(cljs.core.truth_(reload)){ figwheel.client.file_reloading.unprovide_BANG_.call(null,src); } else { } return goog.require_figwheel_backup_(src); }); /** * Reusable browser REPL bootstrapping. Patches the essential functions * in goog.base to support re-loading of namespaces after page load. */ figwheel.client.file_reloading.bootstrap_goog_base = (function figwheel$client$file_reloading$bootstrap_goog_base(){ if(cljs.core.truth_(COMPILED)){ return null; } else { goog.require_figwheel_backup_ = (function (){var or__16826__auto__ = goog.require__; if(cljs.core.truth_(or__16826__auto__)){ return or__16826__auto__; } else { return goog.require; } })(); goog.isProvided_ = (function (name){ return false; }); figwheel.client.file_reloading.setup_path__GT_name_BANG_.call(null); figwheel.client.file_reloading.setup_ns__GT_dependents_BANG_.call(null); goog.addDependency_figwheel_backup_ = goog.addDependency; goog.addDependency = (function() { var G__24038__delegate = function (args){ cljs.core.apply.call(null,figwheel.client.file_reloading.addDependency,args); return cljs.core.apply.call(null,goog.addDependency_figwheel_backup_,args); }; var G__24038 = function (var_args){ var args = null; if (arguments.length > 0) { var G__24039__i = 0, G__24039__a = new Array(arguments.length - 0); while (G__24039__i < G__24039__a.length) {G__24039__a[G__24039__i] = arguments[G__24039__i + 0]; ++G__24039__i;} args = new cljs.core.IndexedSeq(G__24039__a,0); } return G__24038__delegate.call(this,args);}; G__24038.cljs$lang$maxFixedArity = 0; G__24038.cljs$lang$applyTo = (function (arglist__24040){ var args = cljs.core.seq(arglist__24040); return G__24038__delegate(args); }); G__24038.cljs$core$IFn$_invoke$arity$variadic = G__24038__delegate; return G__24038; })() ; goog.constructNamespace_("cljs.user"); goog.global.CLOSURE_IMPORT_SCRIPT = figwheel.client.file_reloading.queued_file_reload; return goog.require = figwheel.client.file_reloading.figwheel_require; } }); figwheel.client.file_reloading.patch_goog_base = (function figwheel$client$file_reloading$patch_goog_base(){ if(typeof figwheel.client.file_reloading.bootstrapped_cljs !== 'undefined'){ return null; } else { figwheel.client.file_reloading.bootstrapped_cljs = (function (){ figwheel.client.file_reloading.bootstrap_goog_base.call(null); return true; })() ; } }); figwheel.client.file_reloading.reload_file_STAR_ = (function (){var pred__24042 = cljs.core._EQ_; var expr__24043 = figwheel.client.utils.host_env_QMARK_.call(null); if(cljs.core.truth_(pred__24042.call(null,new cljs.core.Keyword(null,"node","node",581201198),expr__24043))){ var path_parts = ((function (pred__24042,expr__24043){ return (function (p1__24041_SHARP_){ return clojure.string.split.call(null,p1__24041_SHARP_,/[\/\\]/); });})(pred__24042,expr__24043)) ; var sep = (cljs.core.truth_(cljs.core.re_matches.call(null,/win.*/,process.platform))?"\\":"/"); var root = clojure.string.join.call(null,sep,cljs.core.pop.call(null,cljs.core.pop.call(null,path_parts.call(null,__dirname)))); return ((function (path_parts,sep,root,pred__24042,expr__24043){ return (function (request_url,callback){ var cache_path = clojure.string.join.call(null,sep,cljs.core.cons.call(null,root,path_parts.call(null,figwheel.client.file_reloading.fix_node_request_url.call(null,request_url)))); (require.cache[cache_path] = null); return callback.call(null,(function (){try{return require(cache_path); }catch (e24045){if((e24045 instanceof Error)){ var e = e24045; figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"error","error",-978969032),[cljs.core.str("Figwheel: Error loading file "),cljs.core.str(cache_path)].join('')); figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"error","error",-978969032),e.stack); return false; } else { throw e24045; } }})()); }); ;})(path_parts,sep,root,pred__24042,expr__24043)) } else { if(cljs.core.truth_(pred__24042.call(null,new cljs.core.Keyword(null,"html","html",-998796897),expr__24043))){ return ((function (pred__24042,expr__24043){ return (function (request_url,callback){ var deferred = goog.net.jsloader.load(figwheel.client.file_reloading.add_cache_buster.call(null,request_url),{"cleanupWhenDone": true}); deferred.addCallback(((function (deferred,pred__24042,expr__24043){ return (function (){ return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [true], null)); });})(deferred,pred__24042,expr__24043)) ); return deferred.addErrback(((function (deferred,pred__24042,expr__24043){ return (function (){ return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [false], null)); });})(deferred,pred__24042,expr__24043)) ); }); ;})(pred__24042,expr__24043)) } else { return ((function (pred__24042,expr__24043){ return (function (a,b){ throw "Reload not defined for this platform"; }); ;})(pred__24042,expr__24043)) } } })(); figwheel.client.file_reloading.reload_file = (function figwheel$client$file_reloading$reload_file(p__24046,callback){ var map__24049 = p__24046; var map__24049__$1 = ((((!((map__24049 == null)))?((((map__24049.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24049.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24049):map__24049); var file_msg = map__24049__$1; var request_url = cljs.core.get.call(null,map__24049__$1,new cljs.core.Keyword(null,"request-url","request-url",2100346596)); figwheel.client.utils.debug_prn.call(null,[cljs.core.str("FigWheel: Attempting to load "),cljs.core.str(request_url)].join('')); return figwheel.client.file_reloading.reload_file_STAR_.call(null,request_url,((function (map__24049,map__24049__$1,file_msg,request_url){ return (function (success_QMARK_){ if(cljs.core.truth_(success_QMARK_)){ figwheel.client.utils.debug_prn.call(null,[cljs.core.str("FigWheel: Successfully loaded "),cljs.core.str(request_url)].join('')); return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.assoc.call(null,file_msg,new cljs.core.Keyword(null,"loaded-file","loaded-file",-168399375),true)], null)); } else { figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"error","error",-978969032),[cljs.core.str("Figwheel: Error loading file "),cljs.core.str(request_url)].join('')); return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [file_msg], null)); } });})(map__24049,map__24049__$1,file_msg,request_url)) ); }); if(typeof figwheel.client.file_reloading.reload_chan !== 'undefined'){ } else { figwheel.client.file_reloading.reload_chan = cljs.core.async.chan.call(null); } if(typeof figwheel.client.file_reloading.on_load_callbacks !== 'undefined'){ } else { figwheel.client.file_reloading.on_load_callbacks = cljs.core.atom.call(null,cljs.core.PersistentArrayMap.EMPTY); } if(typeof figwheel.client.file_reloading.dependencies_loaded !== 'undefined'){ } else { figwheel.client.file_reloading.dependencies_loaded = cljs.core.atom.call(null,cljs.core.PersistentVector.EMPTY); } figwheel.client.file_reloading.blocking_load = (function figwheel$client$file_reloading$blocking_load(url){ var out = cljs.core.async.chan.call(null); figwheel.client.file_reloading.reload_file.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"request-url","request-url",2100346596),url], null),((function (out){ return (function (file_msg){ cljs.core.async.put_BANG_.call(null,out,file_msg); return cljs.core.async.close_BANG_.call(null,out); });})(out)) ); return out; }); if(typeof figwheel.client.file_reloading.reloader_loop !== 'undefined'){ } else { figwheel.client.file_reloading.reloader_loop = (function (){var c__20950__auto__ = cljs.core.async.chan.call(null,(1)); cljs.core.async.impl.dispatch.run.call(null,((function (c__20950__auto__){ return (function (){ var f__20951__auto__ = (function (){var switch__20838__auto__ = ((function (c__20950__auto__){ return (function (state_24073){ var state_val_24074 = (state_24073[(1)]); if((state_val_24074 === (7))){ var inst_24069 = (state_24073[(2)]); var state_24073__$1 = state_24073; var statearr_24075_24095 = state_24073__$1; (statearr_24075_24095[(2)] = inst_24069); (statearr_24075_24095[(1)] = (3)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (1))){ var state_24073__$1 = state_24073; var statearr_24076_24096 = state_24073__$1; (statearr_24076_24096[(2)] = null); (statearr_24076_24096[(1)] = (2)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (4))){ var inst_24053 = (state_24073[(7)]); var inst_24053__$1 = (state_24073[(2)]); var state_24073__$1 = (function (){var statearr_24077 = state_24073; (statearr_24077[(7)] = inst_24053__$1); return statearr_24077; })(); if(cljs.core.truth_(inst_24053__$1)){ var statearr_24078_24097 = state_24073__$1; (statearr_24078_24097[(1)] = (5)); } else { var statearr_24079_24098 = state_24073__$1; (statearr_24079_24098[(1)] = (6)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (6))){ var state_24073__$1 = state_24073; var statearr_24080_24099 = state_24073__$1; (statearr_24080_24099[(2)] = null); (statearr_24080_24099[(1)] = (7)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (3))){ var inst_24071 = (state_24073[(2)]); var state_24073__$1 = state_24073; return cljs.core.async.impl.ioc_helpers.return_chan.call(null,state_24073__$1,inst_24071); } else { if((state_val_24074 === (2))){ var state_24073__$1 = state_24073; return cljs.core.async.impl.ioc_helpers.take_BANG_.call(null,state_24073__$1,(4),figwheel.client.file_reloading.reload_chan); } else { if((state_val_24074 === (11))){ var inst_24065 = (state_24073[(2)]); var state_24073__$1 = (function (){var statearr_24081 = state_24073; (statearr_24081[(8)] = inst_24065); return statearr_24081; })(); var statearr_24082_24100 = state_24073__$1; (statearr_24082_24100[(2)] = null); (statearr_24082_24100[(1)] = (2)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (9))){ var inst_24057 = (state_24073[(9)]); var inst_24059 = (state_24073[(10)]); var inst_24061 = inst_24059.call(null,inst_24057); var state_24073__$1 = state_24073; var statearr_24083_24101 = state_24073__$1; (statearr_24083_24101[(2)] = inst_24061); (statearr_24083_24101[(1)] = (11)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (5))){ var inst_24053 = (state_24073[(7)]); var inst_24055 = figwheel.client.file_reloading.blocking_load.call(null,inst_24053); var state_24073__$1 = state_24073; return cljs.core.async.impl.ioc_helpers.take_BANG_.call(null,state_24073__$1,(8),inst_24055); } else { if((state_val_24074 === (10))){ var inst_24057 = (state_24073[(9)]); var inst_24063 = cljs.core.swap_BANG_.call(null,figwheel.client.file_reloading.dependencies_loaded,cljs.core.conj,inst_24057); var state_24073__$1 = state_24073; var statearr_24084_24102 = state_24073__$1; (statearr_24084_24102[(2)] = inst_24063); (statearr_24084_24102[(1)] = (11)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24074 === (8))){ var inst_24059 = (state_24073[(10)]); var inst_24053 = (state_24073[(7)]); var inst_24057 = (state_24073[(2)]); var inst_24058 = cljs.core.deref.call(null,figwheel.client.file_reloading.on_load_callbacks); var inst_24059__$1 = cljs.core.get.call(null,inst_24058,inst_24053); var state_24073__$1 = (function (){var statearr_24085 = state_24073; (statearr_24085[(9)] = inst_24057); (statearr_24085[(10)] = inst_24059__$1); return statearr_24085; })(); if(cljs.core.truth_(inst_24059__$1)){ var statearr_24086_24103 = state_24073__$1; (statearr_24086_24103[(1)] = (9)); } else { var statearr_24087_24104 = state_24073__$1; (statearr_24087_24104[(1)] = (10)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { return null; } } } } } } } } } } } });})(c__20950__auto__)) ; return ((function (switch__20838__auto__,c__20950__auto__){ return (function() { var figwheel$client$file_reloading$state_machine__20839__auto__ = null; var figwheel$client$file_reloading$state_machine__20839__auto____0 = (function (){ var statearr_24091 = [null,null,null,null,null,null,null,null,null,null,null]; (statearr_24091[(0)] = figwheel$client$file_reloading$state_machine__20839__auto__); (statearr_24091[(1)] = (1)); return statearr_24091; }); var figwheel$client$file_reloading$state_machine__20839__auto____1 = (function (state_24073){ while(true){ var ret_value__20840__auto__ = (function (){try{while(true){ var result__20841__auto__ = switch__20838__auto__.call(null,state_24073); if(cljs.core.keyword_identical_QMARK_.call(null,result__20841__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ continue; } else { return result__20841__auto__; } break; } }catch (e24092){if((e24092 instanceof Object)){ var ex__20842__auto__ = e24092; var statearr_24093_24105 = state_24073; (statearr_24093_24105[(5)] = ex__20842__auto__); cljs.core.async.impl.ioc_helpers.process_exception.call(null,state_24073); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { throw e24092; } }})(); if(cljs.core.keyword_identical_QMARK_.call(null,ret_value__20840__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ var G__24106 = state_24073; state_24073 = G__24106; continue; } else { return ret_value__20840__auto__; } break; } }); figwheel$client$file_reloading$state_machine__20839__auto__ = function(state_24073){ switch(arguments.length){ case 0: return figwheel$client$file_reloading$state_machine__20839__auto____0.call(this); case 1: return figwheel$client$file_reloading$state_machine__20839__auto____1.call(this,state_24073); } throw(new Error('Invalid arity: ' + arguments.length)); }; figwheel$client$file_reloading$state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$0 = figwheel$client$file_reloading$state_machine__20839__auto____0; figwheel$client$file_reloading$state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$1 = figwheel$client$file_reloading$state_machine__20839__auto____1; return figwheel$client$file_reloading$state_machine__20839__auto__; })() ;})(switch__20838__auto__,c__20950__auto__)) })(); var state__20952__auto__ = (function (){var statearr_24094 = f__20951__auto__.call(null); (statearr_24094[cljs.core.async.impl.ioc_helpers.USER_START_IDX] = c__20950__auto__); return statearr_24094; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped.call(null,state__20952__auto__); });})(c__20950__auto__)) ); return c__20950__auto__; })(); } figwheel.client.file_reloading.queued_file_reload = (function figwheel$client$file_reloading$queued_file_reload(url){ return cljs.core.async.put_BANG_.call(null,figwheel.client.file_reloading.reload_chan,url); }); figwheel.client.file_reloading.require_with_callback = (function figwheel$client$file_reloading$require_with_callback(p__24107,callback){ var map__24110 = p__24107; var map__24110__$1 = ((((!((map__24110 == null)))?((((map__24110.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24110.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24110):map__24110); var file_msg = map__24110__$1; var namespace = cljs.core.get.call(null,map__24110__$1,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); var request_url = figwheel.client.file_reloading.resolve_ns.call(null,namespace); cljs.core.swap_BANG_.call(null,figwheel.client.file_reloading.on_load_callbacks,cljs.core.assoc,request_url,((function (request_url,map__24110,map__24110__$1,file_msg,namespace){ return (function (file_msg_SINGLEQUOTE_){ cljs.core.swap_BANG_.call(null,figwheel.client.file_reloading.on_load_callbacks,cljs.core.dissoc,request_url); return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.merge.call(null,file_msg,cljs.core.select_keys.call(null,file_msg_SINGLEQUOTE_,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"loaded-file","loaded-file",-168399375)], null)))], null)); });})(request_url,map__24110,map__24110__$1,file_msg,namespace)) ); return figwheel.client.file_reloading.figwheel_require.call(null,cljs.core.name.call(null,namespace),true); }); figwheel.client.file_reloading.reload_file_QMARK_ = (function figwheel$client$file_reloading$reload_file_QMARK_(p__24112){ var map__24115 = p__24112; var map__24115__$1 = ((((!((map__24115 == null)))?((((map__24115.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24115.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24115):map__24115); var file_msg = map__24115__$1; var namespace = cljs.core.get.call(null,map__24115__$1,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); var meta_pragmas = cljs.core.get.call(null,cljs.core.deref.call(null,figwheel.client.file_reloading.figwheel_meta_pragmas),cljs.core.name.call(null,namespace)); var and__16814__auto__ = cljs.core.not.call(null,new cljs.core.Keyword(null,"figwheel-no-load","figwheel-no-load",-555840179).cljs$core$IFn$_invoke$arity$1(meta_pragmas)); if(and__16814__auto__){ var or__16826__auto__ = new cljs.core.Keyword(null,"figwheel-always","figwheel-always",799819691).cljs$core$IFn$_invoke$arity$1(meta_pragmas); if(cljs.core.truth_(or__16826__auto__)){ return or__16826__auto__; } else { var or__16826__auto____$1 = new cljs.core.Keyword(null,"figwheel-load","figwheel-load",1316089175).cljs$core$IFn$_invoke$arity$1(meta_pragmas); if(cljs.core.truth_(or__16826__auto____$1)){ return or__16826__auto____$1; } else { return figwheel.client.file_reloading.provided_QMARK_.call(null,cljs.core.name.call(null,namespace)); } } } else { return and__16814__auto__; } }); figwheel.client.file_reloading.js_reload = (function figwheel$client$file_reloading$js_reload(p__24117,callback){ var map__24120 = p__24117; var map__24120__$1 = ((((!((map__24120 == null)))?((((map__24120.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24120.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24120):map__24120); var file_msg = map__24120__$1; var request_url = cljs.core.get.call(null,map__24120__$1,new cljs.core.Keyword(null,"request-url","request-url",2100346596)); var namespace = cljs.core.get.call(null,map__24120__$1,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); if(cljs.core.truth_(figwheel.client.file_reloading.reload_file_QMARK_.call(null,file_msg))){ return figwheel.client.file_reloading.require_with_callback.call(null,file_msg,callback); } else { figwheel.client.utils.debug_prn.call(null,[cljs.core.str("Figwheel: Not trying to load file "),cljs.core.str(request_url)].join('')); return cljs.core.apply.call(null,callback,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [file_msg], null)); } }); figwheel.client.file_reloading.reload_js_file = (function figwheel$client$file_reloading$reload_js_file(file_msg){ var out = cljs.core.async.chan.call(null); figwheel.client.file_reloading.js_reload.call(null,file_msg,((function (out){ return (function (url){ cljs.core.async.put_BANG_.call(null,out,url); return cljs.core.async.close_BANG_.call(null,out); });})(out)) ); return out; }); /** * Returns a chanel with one collection of loaded filenames on it. */ figwheel.client.file_reloading.load_all_js_files = (function figwheel$client$file_reloading$load_all_js_files(files){ var out = cljs.core.async.chan.call(null); var c__20950__auto___24208 = cljs.core.async.chan.call(null,(1)); cljs.core.async.impl.dispatch.run.call(null,((function (c__20950__auto___24208,out){ return (function (){ var f__20951__auto__ = (function (){var switch__20838__auto__ = ((function (c__20950__auto___24208,out){ return (function (state_24190){ var state_val_24191 = (state_24190[(1)]); if((state_val_24191 === (1))){ var inst_24168 = cljs.core.nth.call(null,files,(0),null); var inst_24169 = cljs.core.nthnext.call(null,files,(1)); var inst_24170 = files; var state_24190__$1 = (function (){var statearr_24192 = state_24190; (statearr_24192[(7)] = inst_24168); (statearr_24192[(8)] = inst_24169); (statearr_24192[(9)] = inst_24170); return statearr_24192; })(); var statearr_24193_24209 = state_24190__$1; (statearr_24193_24209[(2)] = null); (statearr_24193_24209[(1)] = (2)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24191 === (2))){ var inst_24173 = (state_24190[(10)]); var inst_24170 = (state_24190[(9)]); var inst_24173__$1 = cljs.core.nth.call(null,inst_24170,(0),null); var inst_24174 = cljs.core.nthnext.call(null,inst_24170,(1)); var inst_24175 = (inst_24173__$1 == null); var inst_24176 = cljs.core.not.call(null,inst_24175); var state_24190__$1 = (function (){var statearr_24194 = state_24190; (statearr_24194[(11)] = inst_24174); (statearr_24194[(10)] = inst_24173__$1); return statearr_24194; })(); if(inst_24176){ var statearr_24195_24210 = state_24190__$1; (statearr_24195_24210[(1)] = (4)); } else { var statearr_24196_24211 = state_24190__$1; (statearr_24196_24211[(1)] = (5)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24191 === (3))){ var inst_24188 = (state_24190[(2)]); var state_24190__$1 = state_24190; return cljs.core.async.impl.ioc_helpers.return_chan.call(null,state_24190__$1,inst_24188); } else { if((state_val_24191 === (4))){ var inst_24173 = (state_24190[(10)]); var inst_24178 = figwheel.client.file_reloading.reload_js_file.call(null,inst_24173); var state_24190__$1 = state_24190; return cljs.core.async.impl.ioc_helpers.take_BANG_.call(null,state_24190__$1,(7),inst_24178); } else { if((state_val_24191 === (5))){ var inst_24184 = cljs.core.async.close_BANG_.call(null,out); var state_24190__$1 = state_24190; var statearr_24197_24212 = state_24190__$1; (statearr_24197_24212[(2)] = inst_24184); (statearr_24197_24212[(1)] = (6)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24191 === (6))){ var inst_24186 = (state_24190[(2)]); var state_24190__$1 = state_24190; var statearr_24198_24213 = state_24190__$1; (statearr_24198_24213[(2)] = inst_24186); (statearr_24198_24213[(1)] = (3)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24191 === (7))){ var inst_24174 = (state_24190[(11)]); var inst_24180 = (state_24190[(2)]); var inst_24181 = cljs.core.async.put_BANG_.call(null,out,inst_24180); var inst_24170 = inst_24174; var state_24190__$1 = (function (){var statearr_24199 = state_24190; (statearr_24199[(9)] = inst_24170); (statearr_24199[(12)] = inst_24181); return statearr_24199; })(); var statearr_24200_24214 = state_24190__$1; (statearr_24200_24214[(2)] = null); (statearr_24200_24214[(1)] = (2)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { return null; } } } } } } } });})(c__20950__auto___24208,out)) ; return ((function (switch__20838__auto__,c__20950__auto___24208,out){ return (function() { var figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__ = null; var figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____0 = (function (){ var statearr_24204 = [null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_24204[(0)] = figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__); (statearr_24204[(1)] = (1)); return statearr_24204; }); var figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____1 = (function (state_24190){ while(true){ var ret_value__20840__auto__ = (function (){try{while(true){ var result__20841__auto__ = switch__20838__auto__.call(null,state_24190); if(cljs.core.keyword_identical_QMARK_.call(null,result__20841__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ continue; } else { return result__20841__auto__; } break; } }catch (e24205){if((e24205 instanceof Object)){ var ex__20842__auto__ = e24205; var statearr_24206_24215 = state_24190; (statearr_24206_24215[(5)] = ex__20842__auto__); cljs.core.async.impl.ioc_helpers.process_exception.call(null,state_24190); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { throw e24205; } }})(); if(cljs.core.keyword_identical_QMARK_.call(null,ret_value__20840__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ var G__24216 = state_24190; state_24190 = G__24216; continue; } else { return ret_value__20840__auto__; } break; } }); figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__ = function(state_24190){ switch(arguments.length){ case 0: return figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____0.call(this); case 1: return figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____1.call(this,state_24190); } throw(new Error('Invalid arity: ' + arguments.length)); }; figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$0 = figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____0; figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$1 = figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto____1; return figwheel$client$file_reloading$load_all_js_files_$_state_machine__20839__auto__; })() ;})(switch__20838__auto__,c__20950__auto___24208,out)) })(); var state__20952__auto__ = (function (){var statearr_24207 = f__20951__auto__.call(null); (statearr_24207[cljs.core.async.impl.ioc_helpers.USER_START_IDX] = c__20950__auto___24208); return statearr_24207; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped.call(null,state__20952__auto__); });})(c__20950__auto___24208,out)) ); return cljs.core.async.into.call(null,cljs.core.PersistentVector.EMPTY,out); }); figwheel.client.file_reloading.eval_body = (function figwheel$client$file_reloading$eval_body(p__24217,opts){ var map__24221 = p__24217; var map__24221__$1 = ((((!((map__24221 == null)))?((((map__24221.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24221.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24221):map__24221); var eval_body__$1 = cljs.core.get.call(null,map__24221__$1,new cljs.core.Keyword(null,"eval-body","eval-body",-907279883)); var file = cljs.core.get.call(null,map__24221__$1,new cljs.core.Keyword(null,"file","file",-1269645878)); if(cljs.core.truth_((function (){var and__16814__auto__ = eval_body__$1; if(cljs.core.truth_(and__16814__auto__)){ return typeof eval_body__$1 === 'string'; } else { return and__16814__auto__; } })())){ var code = eval_body__$1; try{figwheel.client.utils.debug_prn.call(null,[cljs.core.str("Evaling file "),cljs.core.str(file)].join('')); return figwheel.client.utils.eval_helper.call(null,code,opts); }catch (e24223){var e = e24223; return figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"error","error",-978969032),[cljs.core.str("Unable to evaluate "),cljs.core.str(file)].join('')); }} else { return null; } }); figwheel.client.file_reloading.expand_files = (function figwheel$client$file_reloading$expand_files(files){ var deps = figwheel.client.file_reloading.get_all_dependents.call(null,cljs.core.map.call(null,new cljs.core.Keyword(null,"namespace","namespace",-377510372),files)); return cljs.core.filter.call(null,cljs.core.comp.call(null,cljs.core.not,new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 1, ["figwheel.connect",null], null), null),new cljs.core.Keyword(null,"namespace","namespace",-377510372)),cljs.core.map.call(null,((function (deps){ return (function (n){ var temp__4423__auto__ = cljs.core.first.call(null,cljs.core.filter.call(null,((function (deps){ return (function (p1__24224_SHARP_){ return cljs.core._EQ_.call(null,new cljs.core.Keyword(null,"namespace","namespace",-377510372).cljs$core$IFn$_invoke$arity$1(p1__24224_SHARP_),n); });})(deps)) ,files)); if(cljs.core.truth_(temp__4423__auto__)){ var file_msg = temp__4423__auto__; return file_msg; } else { return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"namespace","namespace",-377510372),new cljs.core.Keyword(null,"namespace","namespace",-377510372),n], null); } });})(deps)) ,deps)); }); figwheel.client.file_reloading.sort_files = (function figwheel$client$file_reloading$sort_files(files){ if((cljs.core.count.call(null,files) <= (1))){ return files; } else { var keep_files = cljs.core.set.call(null,cljs.core.keep.call(null,new cljs.core.Keyword(null,"namespace","namespace",-377510372),files)); return cljs.core.filter.call(null,cljs.core.comp.call(null,keep_files,new cljs.core.Keyword(null,"namespace","namespace",-377510372)),figwheel.client.file_reloading.expand_files.call(null,files)); } }); figwheel.client.file_reloading.get_figwheel_always = (function figwheel$client$file_reloading$get_figwheel_always(){ return cljs.core.map.call(null,(function (p__24229){ var vec__24230 = p__24229; var k = cljs.core.nth.call(null,vec__24230,(0),null); var v = cljs.core.nth.call(null,vec__24230,(1),null); return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"namespace","namespace",-377510372),k,new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"namespace","namespace",-377510372)], null); }),cljs.core.filter.call(null,(function (p__24231){ var vec__24232 = p__24231; var k = cljs.core.nth.call(null,vec__24232,(0),null); var v = cljs.core.nth.call(null,vec__24232,(1),null); return new cljs.core.Keyword(null,"figwheel-always","figwheel-always",799819691).cljs$core$IFn$_invoke$arity$1(v); }),cljs.core.deref.call(null,figwheel.client.file_reloading.figwheel_meta_pragmas))); }); figwheel.client.file_reloading.reload_js_files = (function figwheel$client$file_reloading$reload_js_files(p__24236,p__24237){ var map__24484 = p__24236; var map__24484__$1 = ((((!((map__24484 == null)))?((((map__24484.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24484.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24484):map__24484); var opts = map__24484__$1; var before_jsload = cljs.core.get.call(null,map__24484__$1,new cljs.core.Keyword(null,"before-jsload","before-jsload",-847513128)); var on_jsload = cljs.core.get.call(null,map__24484__$1,new cljs.core.Keyword(null,"on-jsload","on-jsload",-395756602)); var reload_dependents = cljs.core.get.call(null,map__24484__$1,new cljs.core.Keyword(null,"reload-dependents","reload-dependents",-956865430)); var map__24485 = p__24237; var map__24485__$1 = ((((!((map__24485 == null)))?((((map__24485.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24485.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24485):map__24485); var msg = map__24485__$1; var files = cljs.core.get.call(null,map__24485__$1,new cljs.core.Keyword(null,"files","files",-472457450)); var figwheel_meta = cljs.core.get.call(null,map__24485__$1,new cljs.core.Keyword(null,"figwheel-meta","figwheel-meta",-225970237)); var recompile_dependents = cljs.core.get.call(null,map__24485__$1,new cljs.core.Keyword(null,"recompile-dependents","recompile-dependents",523804171)); if(cljs.core.empty_QMARK_.call(null,figwheel_meta)){ } else { cljs.core.reset_BANG_.call(null,figwheel.client.file_reloading.figwheel_meta_pragmas,figwheel_meta); } var c__20950__auto__ = cljs.core.async.chan.call(null,(1)); cljs.core.async.impl.dispatch.run.call(null,((function (c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (){ var f__20951__auto__ = (function (){var switch__20838__auto__ = ((function (c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (state_24638){ var state_val_24639 = (state_24638[(1)]); if((state_val_24639 === (7))){ var inst_24501 = (state_24638[(7)]); var inst_24500 = (state_24638[(8)]); var inst_24502 = (state_24638[(9)]); var inst_24499 = (state_24638[(10)]); var inst_24507 = cljs.core._nth.call(null,inst_24500,inst_24502); var inst_24508 = figwheel.client.file_reloading.eval_body.call(null,inst_24507,opts); var inst_24509 = (inst_24502 + (1)); var tmp24640 = inst_24501; var tmp24641 = inst_24500; var tmp24642 = inst_24499; var inst_24499__$1 = tmp24642; var inst_24500__$1 = tmp24641; var inst_24501__$1 = tmp24640; var inst_24502__$1 = inst_24509; var state_24638__$1 = (function (){var statearr_24643 = state_24638; (statearr_24643[(7)] = inst_24501__$1); (statearr_24643[(8)] = inst_24500__$1); (statearr_24643[(9)] = inst_24502__$1); (statearr_24643[(11)] = inst_24508); (statearr_24643[(10)] = inst_24499__$1); return statearr_24643; })(); var statearr_24644_24730 = state_24638__$1; (statearr_24644_24730[(2)] = null); (statearr_24644_24730[(1)] = (5)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (20))){ var inst_24542 = (state_24638[(12)]); var inst_24550 = figwheel.client.file_reloading.sort_files.call(null,inst_24542); var state_24638__$1 = state_24638; var statearr_24645_24731 = state_24638__$1; (statearr_24645_24731[(2)] = inst_24550); (statearr_24645_24731[(1)] = (21)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (27))){ var state_24638__$1 = state_24638; var statearr_24646_24732 = state_24638__$1; (statearr_24646_24732[(2)] = null); (statearr_24646_24732[(1)] = (28)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (1))){ var inst_24491 = (state_24638[(13)]); var inst_24488 = before_jsload.call(null,files); var inst_24489 = figwheel.client.file_reloading.before_jsload_custom_event.call(null,files); var inst_24490 = (function (){return ((function (inst_24491,inst_24488,inst_24489,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p1__24233_SHARP_){ return new cljs.core.Keyword(null,"eval-body","eval-body",-907279883).cljs$core$IFn$_invoke$arity$1(p1__24233_SHARP_); }); ;})(inst_24491,inst_24488,inst_24489,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24491__$1 = cljs.core.filter.call(null,inst_24490,files); var inst_24492 = cljs.core.not_empty.call(null,inst_24491__$1); var state_24638__$1 = (function (){var statearr_24647 = state_24638; (statearr_24647[(13)] = inst_24491__$1); (statearr_24647[(14)] = inst_24489); (statearr_24647[(15)] = inst_24488); return statearr_24647; })(); if(cljs.core.truth_(inst_24492)){ var statearr_24648_24733 = state_24638__$1; (statearr_24648_24733[(1)] = (2)); } else { var statearr_24649_24734 = state_24638__$1; (statearr_24649_24734[(1)] = (3)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (24))){ var state_24638__$1 = state_24638; var statearr_24650_24735 = state_24638__$1; (statearr_24650_24735[(2)] = null); (statearr_24650_24735[(1)] = (25)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (39))){ var inst_24592 = (state_24638[(16)]); var state_24638__$1 = state_24638; var statearr_24651_24736 = state_24638__$1; (statearr_24651_24736[(2)] = inst_24592); (statearr_24651_24736[(1)] = (40)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (46))){ var inst_24633 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24652_24737 = state_24638__$1; (statearr_24652_24737[(2)] = inst_24633); (statearr_24652_24737[(1)] = (31)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (4))){ var inst_24536 = (state_24638[(2)]); var inst_24537 = cljs.core.List.EMPTY; var inst_24538 = cljs.core.reset_BANG_.call(null,figwheel.client.file_reloading.dependencies_loaded,inst_24537); var inst_24539 = (function (){return ((function (inst_24536,inst_24537,inst_24538,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p1__24234_SHARP_){ var and__16814__auto__ = new cljs.core.Keyword(null,"namespace","namespace",-377510372).cljs$core$IFn$_invoke$arity$1(p1__24234_SHARP_); if(cljs.core.truth_(and__16814__auto__)){ return cljs.core.not.call(null,new cljs.core.Keyword(null,"eval-body","eval-body",-907279883).cljs$core$IFn$_invoke$arity$1(p1__24234_SHARP_)); } else { return and__16814__auto__; } }); ;})(inst_24536,inst_24537,inst_24538,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24540 = cljs.core.filter.call(null,inst_24539,files); var inst_24541 = figwheel.client.file_reloading.get_figwheel_always.call(null); var inst_24542 = cljs.core.concat.call(null,inst_24540,inst_24541); var state_24638__$1 = (function (){var statearr_24653 = state_24638; (statearr_24653[(17)] = inst_24536); (statearr_24653[(18)] = inst_24538); (statearr_24653[(12)] = inst_24542); return statearr_24653; })(); if(cljs.core.truth_(reload_dependents)){ var statearr_24654_24738 = state_24638__$1; (statearr_24654_24738[(1)] = (16)); } else { var statearr_24655_24739 = state_24638__$1; (statearr_24655_24739[(1)] = (17)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (15))){ var inst_24526 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24656_24740 = state_24638__$1; (statearr_24656_24740[(2)] = inst_24526); (statearr_24656_24740[(1)] = (12)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (21))){ var inst_24552 = (state_24638[(19)]); var inst_24552__$1 = (state_24638[(2)]); var inst_24553 = figwheel.client.file_reloading.load_all_js_files.call(null,inst_24552__$1); var state_24638__$1 = (function (){var statearr_24657 = state_24638; (statearr_24657[(19)] = inst_24552__$1); return statearr_24657; })(); return cljs.core.async.impl.ioc_helpers.take_BANG_.call(null,state_24638__$1,(22),inst_24553); } else { if((state_val_24639 === (31))){ var inst_24636 = (state_24638[(2)]); var state_24638__$1 = state_24638; return cljs.core.async.impl.ioc_helpers.return_chan.call(null,state_24638__$1,inst_24636); } else { if((state_val_24639 === (32))){ var inst_24592 = (state_24638[(16)]); var inst_24597 = inst_24592.cljs$lang$protocol_mask$partition0$; var inst_24598 = (inst_24597 & (64)); var inst_24599 = inst_24592.cljs$core$ISeq$; var inst_24600 = (inst_24598) || (inst_24599); var state_24638__$1 = state_24638; if(cljs.core.truth_(inst_24600)){ var statearr_24658_24741 = state_24638__$1; (statearr_24658_24741[(1)] = (35)); } else { var statearr_24659_24742 = state_24638__$1; (statearr_24659_24742[(1)] = (36)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (40))){ var inst_24613 = (state_24638[(20)]); var inst_24612 = (state_24638[(2)]); var inst_24613__$1 = cljs.core.get.call(null,inst_24612,new cljs.core.Keyword(null,"figwheel-no-load","figwheel-no-load",-555840179)); var inst_24614 = cljs.core.get.call(null,inst_24612,new cljs.core.Keyword(null,"not-required","not-required",-950359114)); var inst_24615 = cljs.core.not_empty.call(null,inst_24613__$1); var state_24638__$1 = (function (){var statearr_24660 = state_24638; (statearr_24660[(20)] = inst_24613__$1); (statearr_24660[(21)] = inst_24614); return statearr_24660; })(); if(cljs.core.truth_(inst_24615)){ var statearr_24661_24743 = state_24638__$1; (statearr_24661_24743[(1)] = (41)); } else { var statearr_24662_24744 = state_24638__$1; (statearr_24662_24744[(1)] = (42)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (33))){ var state_24638__$1 = state_24638; var statearr_24663_24745 = state_24638__$1; (statearr_24663_24745[(2)] = false); (statearr_24663_24745[(1)] = (34)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (13))){ var inst_24512 = (state_24638[(22)]); var inst_24516 = cljs.core.chunk_first.call(null,inst_24512); var inst_24517 = cljs.core.chunk_rest.call(null,inst_24512); var inst_24518 = cljs.core.count.call(null,inst_24516); var inst_24499 = inst_24517; var inst_24500 = inst_24516; var inst_24501 = inst_24518; var inst_24502 = (0); var state_24638__$1 = (function (){var statearr_24664 = state_24638; (statearr_24664[(7)] = inst_24501); (statearr_24664[(8)] = inst_24500); (statearr_24664[(9)] = inst_24502); (statearr_24664[(10)] = inst_24499); return statearr_24664; })(); var statearr_24665_24746 = state_24638__$1; (statearr_24665_24746[(2)] = null); (statearr_24665_24746[(1)] = (5)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (22))){ var inst_24552 = (state_24638[(19)]); var inst_24560 = (state_24638[(23)]); var inst_24556 = (state_24638[(24)]); var inst_24555 = (state_24638[(25)]); var inst_24555__$1 = (state_24638[(2)]); var inst_24556__$1 = cljs.core.filter.call(null,new cljs.core.Keyword(null,"loaded-file","loaded-file",-168399375),inst_24555__$1); var inst_24557 = (function (){var all_files = inst_24552; var res_SINGLEQUOTE_ = inst_24555__$1; var res = inst_24556__$1; return ((function (all_files,res_SINGLEQUOTE_,res,inst_24552,inst_24560,inst_24556,inst_24555,inst_24555__$1,inst_24556__$1,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p1__24235_SHARP_){ return cljs.core.not.call(null,new cljs.core.Keyword(null,"loaded-file","loaded-file",-168399375).cljs$core$IFn$_invoke$arity$1(p1__24235_SHARP_)); }); ;})(all_files,res_SINGLEQUOTE_,res,inst_24552,inst_24560,inst_24556,inst_24555,inst_24555__$1,inst_24556__$1,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24558 = cljs.core.filter.call(null,inst_24557,inst_24555__$1); var inst_24559 = cljs.core.deref.call(null,figwheel.client.file_reloading.dependencies_loaded); var inst_24560__$1 = cljs.core.filter.call(null,new cljs.core.Keyword(null,"loaded-file","loaded-file",-168399375),inst_24559); var inst_24561 = cljs.core.not_empty.call(null,inst_24560__$1); var state_24638__$1 = (function (){var statearr_24666 = state_24638; (statearr_24666[(26)] = inst_24558); (statearr_24666[(23)] = inst_24560__$1); (statearr_24666[(24)] = inst_24556__$1); (statearr_24666[(25)] = inst_24555__$1); return statearr_24666; })(); if(cljs.core.truth_(inst_24561)){ var statearr_24667_24747 = state_24638__$1; (statearr_24667_24747[(1)] = (23)); } else { var statearr_24668_24748 = state_24638__$1; (statearr_24668_24748[(1)] = (24)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (36))){ var state_24638__$1 = state_24638; var statearr_24669_24749 = state_24638__$1; (statearr_24669_24749[(2)] = false); (statearr_24669_24749[(1)] = (37)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (41))){ var inst_24613 = (state_24638[(20)]); var inst_24617 = cljs.core.comp.call(null,figwheel.client.file_reloading.name__GT_path,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); var inst_24618 = cljs.core.map.call(null,inst_24617,inst_24613); var inst_24619 = cljs.core.pr_str.call(null,inst_24618); var inst_24620 = [cljs.core.str("figwheel-no-load meta-data: "),cljs.core.str(inst_24619)].join(''); var inst_24621 = figwheel.client.utils.log.call(null,inst_24620); var state_24638__$1 = state_24638; var statearr_24670_24750 = state_24638__$1; (statearr_24670_24750[(2)] = inst_24621); (statearr_24670_24750[(1)] = (43)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (43))){ var inst_24614 = (state_24638[(21)]); var inst_24624 = (state_24638[(2)]); var inst_24625 = cljs.core.not_empty.call(null,inst_24614); var state_24638__$1 = (function (){var statearr_24671 = state_24638; (statearr_24671[(27)] = inst_24624); return statearr_24671; })(); if(cljs.core.truth_(inst_24625)){ var statearr_24672_24751 = state_24638__$1; (statearr_24672_24751[(1)] = (44)); } else { var statearr_24673_24752 = state_24638__$1; (statearr_24673_24752[(1)] = (45)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (29))){ var inst_24552 = (state_24638[(19)]); var inst_24558 = (state_24638[(26)]); var inst_24592 = (state_24638[(16)]); var inst_24560 = (state_24638[(23)]); var inst_24556 = (state_24638[(24)]); var inst_24555 = (state_24638[(25)]); var inst_24588 = figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"debug","debug",-1608172596),"Figwheel: NOT loading these files "); var inst_24591 = (function (){var all_files = inst_24552; var res_SINGLEQUOTE_ = inst_24555; var res = inst_24556; var files_not_loaded = inst_24558; var dependencies_that_loaded = inst_24560; return ((function (all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24592,inst_24560,inst_24556,inst_24555,inst_24588,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p__24590){ var map__24674 = p__24590; var map__24674__$1 = ((((!((map__24674 == null)))?((((map__24674.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24674.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24674):map__24674); var namespace = cljs.core.get.call(null,map__24674__$1,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); var meta_data = cljs.core.get.call(null,cljs.core.deref.call(null,figwheel.client.file_reloading.figwheel_meta_pragmas),cljs.core.name.call(null,namespace)); if((meta_data == null)){ return new cljs.core.Keyword(null,"not-required","not-required",-950359114); } else { if(cljs.core.truth_(meta_data.call(null,new cljs.core.Keyword(null,"figwheel-no-load","figwheel-no-load",-555840179)))){ return new cljs.core.Keyword(null,"figwheel-no-load","figwheel-no-load",-555840179); } else { return new cljs.core.Keyword(null,"not-required","not-required",-950359114); } } }); ;})(all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24592,inst_24560,inst_24556,inst_24555,inst_24588,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24592__$1 = cljs.core.group_by.call(null,inst_24591,inst_24558); var inst_24594 = (inst_24592__$1 == null); var inst_24595 = cljs.core.not.call(null,inst_24594); var state_24638__$1 = (function (){var statearr_24676 = state_24638; (statearr_24676[(16)] = inst_24592__$1); (statearr_24676[(28)] = inst_24588); return statearr_24676; })(); if(inst_24595){ var statearr_24677_24753 = state_24638__$1; (statearr_24677_24753[(1)] = (32)); } else { var statearr_24678_24754 = state_24638__$1; (statearr_24678_24754[(1)] = (33)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (44))){ var inst_24614 = (state_24638[(21)]); var inst_24627 = cljs.core.map.call(null,new cljs.core.Keyword(null,"file","file",-1269645878),inst_24614); var inst_24628 = cljs.core.pr_str.call(null,inst_24627); var inst_24629 = [cljs.core.str("not required: "),cljs.core.str(inst_24628)].join(''); var inst_24630 = figwheel.client.utils.log.call(null,inst_24629); var state_24638__$1 = state_24638; var statearr_24679_24755 = state_24638__$1; (statearr_24679_24755[(2)] = inst_24630); (statearr_24679_24755[(1)] = (46)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (6))){ var inst_24533 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24680_24756 = state_24638__$1; (statearr_24680_24756[(2)] = inst_24533); (statearr_24680_24756[(1)] = (4)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (28))){ var inst_24558 = (state_24638[(26)]); var inst_24585 = (state_24638[(2)]); var inst_24586 = cljs.core.not_empty.call(null,inst_24558); var state_24638__$1 = (function (){var statearr_24681 = state_24638; (statearr_24681[(29)] = inst_24585); return statearr_24681; })(); if(cljs.core.truth_(inst_24586)){ var statearr_24682_24757 = state_24638__$1; (statearr_24682_24757[(1)] = (29)); } else { var statearr_24683_24758 = state_24638__$1; (statearr_24683_24758[(1)] = (30)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (25))){ var inst_24556 = (state_24638[(24)]); var inst_24572 = (state_24638[(2)]); var inst_24573 = cljs.core.not_empty.call(null,inst_24556); var state_24638__$1 = (function (){var statearr_24684 = state_24638; (statearr_24684[(30)] = inst_24572); return statearr_24684; })(); if(cljs.core.truth_(inst_24573)){ var statearr_24685_24759 = state_24638__$1; (statearr_24685_24759[(1)] = (26)); } else { var statearr_24686_24760 = state_24638__$1; (statearr_24686_24760[(1)] = (27)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (34))){ var inst_24607 = (state_24638[(2)]); var state_24638__$1 = state_24638; if(cljs.core.truth_(inst_24607)){ var statearr_24687_24761 = state_24638__$1; (statearr_24687_24761[(1)] = (38)); } else { var statearr_24688_24762 = state_24638__$1; (statearr_24688_24762[(1)] = (39)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (17))){ var state_24638__$1 = state_24638; var statearr_24689_24763 = state_24638__$1; (statearr_24689_24763[(2)] = recompile_dependents); (statearr_24689_24763[(1)] = (18)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (3))){ var state_24638__$1 = state_24638; var statearr_24690_24764 = state_24638__$1; (statearr_24690_24764[(2)] = null); (statearr_24690_24764[(1)] = (4)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (12))){ var inst_24529 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24691_24765 = state_24638__$1; (statearr_24691_24765[(2)] = inst_24529); (statearr_24691_24765[(1)] = (9)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (2))){ var inst_24491 = (state_24638[(13)]); var inst_24498 = cljs.core.seq.call(null,inst_24491); var inst_24499 = inst_24498; var inst_24500 = null; var inst_24501 = (0); var inst_24502 = (0); var state_24638__$1 = (function (){var statearr_24692 = state_24638; (statearr_24692[(7)] = inst_24501); (statearr_24692[(8)] = inst_24500); (statearr_24692[(9)] = inst_24502); (statearr_24692[(10)] = inst_24499); return statearr_24692; })(); var statearr_24693_24766 = state_24638__$1; (statearr_24693_24766[(2)] = null); (statearr_24693_24766[(1)] = (5)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (23))){ var inst_24552 = (state_24638[(19)]); var inst_24558 = (state_24638[(26)]); var inst_24560 = (state_24638[(23)]); var inst_24556 = (state_24638[(24)]); var inst_24555 = (state_24638[(25)]); var inst_24563 = figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"debug","debug",-1608172596),"Figwheel: loaded these dependencies"); var inst_24565 = (function (){var all_files = inst_24552; var res_SINGLEQUOTE_ = inst_24555; var res = inst_24556; var files_not_loaded = inst_24558; var dependencies_that_loaded = inst_24560; return ((function (all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24563,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p__24564){ var map__24694 = p__24564; var map__24694__$1 = ((((!((map__24694 == null)))?((((map__24694.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24694.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24694):map__24694); var request_url = cljs.core.get.call(null,map__24694__$1,new cljs.core.Keyword(null,"request-url","request-url",2100346596)); return clojure.string.replace.call(null,request_url,goog.basePath,""); }); ;})(all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24563,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24566 = cljs.core.reverse.call(null,inst_24560); var inst_24567 = cljs.core.map.call(null,inst_24565,inst_24566); var inst_24568 = cljs.core.pr_str.call(null,inst_24567); var inst_24569 = figwheel.client.utils.log.call(null,inst_24568); var state_24638__$1 = (function (){var statearr_24696 = state_24638; (statearr_24696[(31)] = inst_24563); return statearr_24696; })(); var statearr_24697_24767 = state_24638__$1; (statearr_24697_24767[(2)] = inst_24569); (statearr_24697_24767[(1)] = (25)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (35))){ var state_24638__$1 = state_24638; var statearr_24698_24768 = state_24638__$1; (statearr_24698_24768[(2)] = true); (statearr_24698_24768[(1)] = (37)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (19))){ var inst_24542 = (state_24638[(12)]); var inst_24548 = figwheel.client.file_reloading.expand_files.call(null,inst_24542); var state_24638__$1 = state_24638; var statearr_24699_24769 = state_24638__$1; (statearr_24699_24769[(2)] = inst_24548); (statearr_24699_24769[(1)] = (21)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (11))){ var state_24638__$1 = state_24638; var statearr_24700_24770 = state_24638__$1; (statearr_24700_24770[(2)] = null); (statearr_24700_24770[(1)] = (12)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (9))){ var inst_24531 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24701_24771 = state_24638__$1; (statearr_24701_24771[(2)] = inst_24531); (statearr_24701_24771[(1)] = (6)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (5))){ var inst_24501 = (state_24638[(7)]); var inst_24502 = (state_24638[(9)]); var inst_24504 = (inst_24502 < inst_24501); var inst_24505 = inst_24504; var state_24638__$1 = state_24638; if(cljs.core.truth_(inst_24505)){ var statearr_24702_24772 = state_24638__$1; (statearr_24702_24772[(1)] = (7)); } else { var statearr_24703_24773 = state_24638__$1; (statearr_24703_24773[(1)] = (8)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (14))){ var inst_24512 = (state_24638[(22)]); var inst_24521 = cljs.core.first.call(null,inst_24512); var inst_24522 = figwheel.client.file_reloading.eval_body.call(null,inst_24521,opts); var inst_24523 = cljs.core.next.call(null,inst_24512); var inst_24499 = inst_24523; var inst_24500 = null; var inst_24501 = (0); var inst_24502 = (0); var state_24638__$1 = (function (){var statearr_24704 = state_24638; (statearr_24704[(32)] = inst_24522); (statearr_24704[(7)] = inst_24501); (statearr_24704[(8)] = inst_24500); (statearr_24704[(9)] = inst_24502); (statearr_24704[(10)] = inst_24499); return statearr_24704; })(); var statearr_24705_24774 = state_24638__$1; (statearr_24705_24774[(2)] = null); (statearr_24705_24774[(1)] = (5)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (45))){ var state_24638__$1 = state_24638; var statearr_24706_24775 = state_24638__$1; (statearr_24706_24775[(2)] = null); (statearr_24706_24775[(1)] = (46)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (26))){ var inst_24552 = (state_24638[(19)]); var inst_24558 = (state_24638[(26)]); var inst_24560 = (state_24638[(23)]); var inst_24556 = (state_24638[(24)]); var inst_24555 = (state_24638[(25)]); var inst_24575 = figwheel.client.utils.log.call(null,new cljs.core.Keyword(null,"debug","debug",-1608172596),"Figwheel: loaded these files"); var inst_24577 = (function (){var all_files = inst_24552; var res_SINGLEQUOTE_ = inst_24555; var res = inst_24556; var files_not_loaded = inst_24558; var dependencies_that_loaded = inst_24560; return ((function (all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24575,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (p__24576){ var map__24707 = p__24576; var map__24707__$1 = ((((!((map__24707 == null)))?((((map__24707.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24707.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24707):map__24707); var namespace = cljs.core.get.call(null,map__24707__$1,new cljs.core.Keyword(null,"namespace","namespace",-377510372)); var file = cljs.core.get.call(null,map__24707__$1,new cljs.core.Keyword(null,"file","file",-1269645878)); if(cljs.core.truth_(namespace)){ return figwheel.client.file_reloading.name__GT_path.call(null,cljs.core.name.call(null,namespace)); } else { return file; } }); ;})(all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24575,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24578 = cljs.core.map.call(null,inst_24577,inst_24556); var inst_24579 = cljs.core.pr_str.call(null,inst_24578); var inst_24580 = figwheel.client.utils.log.call(null,inst_24579); var inst_24581 = (function (){var all_files = inst_24552; var res_SINGLEQUOTE_ = inst_24555; var res = inst_24556; var files_not_loaded = inst_24558; var dependencies_that_loaded = inst_24560; return ((function (all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24575,inst_24577,inst_24578,inst_24579,inst_24580,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function (){ figwheel.client.file_reloading.on_jsload_custom_event.call(null,res); return cljs.core.apply.call(null,on_jsload,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [res], null)); }); ;})(all_files,res_SINGLEQUOTE_,res,files_not_loaded,dependencies_that_loaded,inst_24552,inst_24558,inst_24560,inst_24556,inst_24555,inst_24575,inst_24577,inst_24578,inst_24579,inst_24580,state_val_24639,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var inst_24582 = setTimeout(inst_24581,(10)); var state_24638__$1 = (function (){var statearr_24709 = state_24638; (statearr_24709[(33)] = inst_24575); (statearr_24709[(34)] = inst_24580); return statearr_24709; })(); var statearr_24710_24776 = state_24638__$1; (statearr_24710_24776[(2)] = inst_24582); (statearr_24710_24776[(1)] = (28)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (16))){ var state_24638__$1 = state_24638; var statearr_24711_24777 = state_24638__$1; (statearr_24711_24777[(2)] = reload_dependents); (statearr_24711_24777[(1)] = (18)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (38))){ var inst_24592 = (state_24638[(16)]); var inst_24609 = cljs.core.apply.call(null,cljs.core.hash_map,inst_24592); var state_24638__$1 = state_24638; var statearr_24712_24778 = state_24638__$1; (statearr_24712_24778[(2)] = inst_24609); (statearr_24712_24778[(1)] = (40)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (30))){ var state_24638__$1 = state_24638; var statearr_24713_24779 = state_24638__$1; (statearr_24713_24779[(2)] = null); (statearr_24713_24779[(1)] = (31)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (10))){ var inst_24512 = (state_24638[(22)]); var inst_24514 = cljs.core.chunked_seq_QMARK_.call(null,inst_24512); var state_24638__$1 = state_24638; if(inst_24514){ var statearr_24714_24780 = state_24638__$1; (statearr_24714_24780[(1)] = (13)); } else { var statearr_24715_24781 = state_24638__$1; (statearr_24715_24781[(1)] = (14)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (18))){ var inst_24546 = (state_24638[(2)]); var state_24638__$1 = state_24638; if(cljs.core.truth_(inst_24546)){ var statearr_24716_24782 = state_24638__$1; (statearr_24716_24782[(1)] = (19)); } else { var statearr_24717_24783 = state_24638__$1; (statearr_24717_24783[(1)] = (20)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (42))){ var state_24638__$1 = state_24638; var statearr_24718_24784 = state_24638__$1; (statearr_24718_24784[(2)] = null); (statearr_24718_24784[(1)] = (43)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (37))){ var inst_24604 = (state_24638[(2)]); var state_24638__$1 = state_24638; var statearr_24719_24785 = state_24638__$1; (statearr_24719_24785[(2)] = inst_24604); (statearr_24719_24785[(1)] = (34)); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { if((state_val_24639 === (8))){ var inst_24512 = (state_24638[(22)]); var inst_24499 = (state_24638[(10)]); var inst_24512__$1 = cljs.core.seq.call(null,inst_24499); var state_24638__$1 = (function (){var statearr_24720 = state_24638; (statearr_24720[(22)] = inst_24512__$1); return statearr_24720; })(); if(inst_24512__$1){ var statearr_24721_24786 = state_24638__$1; (statearr_24721_24786[(1)] = (10)); } else { var statearr_24722_24787 = state_24638__$1; (statearr_24722_24787[(1)] = (11)); } return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { return null; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } });})(c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) ; return ((function (switch__20838__auto__,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents){ return (function() { var figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__ = null; var figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____0 = (function (){ var statearr_24726 = [null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]; (statearr_24726[(0)] = figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__); (statearr_24726[(1)] = (1)); return statearr_24726; }); var figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____1 = (function (state_24638){ while(true){ var ret_value__20840__auto__ = (function (){try{while(true){ var result__20841__auto__ = switch__20838__auto__.call(null,state_24638); if(cljs.core.keyword_identical_QMARK_.call(null,result__20841__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ continue; } else { return result__20841__auto__; } break; } }catch (e24727){if((e24727 instanceof Object)){ var ex__20842__auto__ = e24727; var statearr_24728_24788 = state_24638; (statearr_24728_24788[(5)] = ex__20842__auto__); cljs.core.async.impl.ioc_helpers.process_exception.call(null,state_24638); return new cljs.core.Keyword(null,"recur","recur",-437573268); } else { throw e24727; } }})(); if(cljs.core.keyword_identical_QMARK_.call(null,ret_value__20840__auto__,new cljs.core.Keyword(null,"recur","recur",-437573268))){ var G__24789 = state_24638; state_24638 = G__24789; continue; } else { return ret_value__20840__auto__; } break; } }); figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__ = function(state_24638){ switch(arguments.length){ case 0: return figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____0.call(this); case 1: return figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____1.call(this,state_24638); } throw(new Error('Invalid arity: ' + arguments.length)); }; figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$0 = figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____0; figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__.cljs$core$IFn$_invoke$arity$1 = figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto____1; return figwheel$client$file_reloading$reload_js_files_$_state_machine__20839__auto__; })() ;})(switch__20838__auto__,c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) })(); var state__20952__auto__ = (function (){var statearr_24729 = f__20951__auto__.call(null); (statearr_24729[cljs.core.async.impl.ioc_helpers.USER_START_IDX] = c__20950__auto__); return statearr_24729; })(); return cljs.core.async.impl.ioc_helpers.run_state_machine_wrapped.call(null,state__20952__auto__); });})(c__20950__auto__,map__24484,map__24484__$1,opts,before_jsload,on_jsload,reload_dependents,map__24485,map__24485__$1,msg,files,figwheel_meta,recompile_dependents)) ); return c__20950__auto__; }); figwheel.client.file_reloading.current_links = (function figwheel$client$file_reloading$current_links(){ return Array.prototype.slice.call(document.getElementsByTagName("link")); }); figwheel.client.file_reloading.truncate_url = (function figwheel$client$file_reloading$truncate_url(url){ return clojure.string.replace_first.call(null,clojure.string.replace_first.call(null,clojure.string.replace_first.call(null,clojure.string.replace_first.call(null,cljs.core.first.call(null,clojure.string.split.call(null,url,/\?/)),[cljs.core.str(location.protocol),cljs.core.str("//")].join(''),""),".*://",""),/^\/\//,""),/[^\\/]*/,""); }); figwheel.client.file_reloading.matches_file_QMARK_ = (function figwheel$client$file_reloading$matches_file_QMARK_(p__24792,link){ var map__24795 = p__24792; var map__24795__$1 = ((((!((map__24795 == null)))?((((map__24795.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24795.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24795):map__24795); var file = cljs.core.get.call(null,map__24795__$1,new cljs.core.Keyword(null,"file","file",-1269645878)); var temp__4425__auto__ = link.href; if(cljs.core.truth_(temp__4425__auto__)){ var link_href = temp__4425__auto__; var match = clojure.string.join.call(null,"/",cljs.core.take_while.call(null,cljs.core.identity,cljs.core.map.call(null,((function (link_href,temp__4425__auto__,map__24795,map__24795__$1,file){ return (function (p1__24790_SHARP_,p2__24791_SHARP_){ if(cljs.core._EQ_.call(null,p1__24790_SHARP_,p2__24791_SHARP_)){ return p1__24790_SHARP_; } else { return false; } });})(link_href,temp__4425__auto__,map__24795,map__24795__$1,file)) ,cljs.core.reverse.call(null,clojure.string.split.call(null,file,"/")),cljs.core.reverse.call(null,clojure.string.split.call(null,figwheel.client.file_reloading.truncate_url.call(null,link_href),"/"))))); var match_length = cljs.core.count.call(null,match); var file_name_length = cljs.core.count.call(null,cljs.core.last.call(null,clojure.string.split.call(null,file,"/"))); if((match_length >= file_name_length)){ return new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"link","link",-1769163468),link,new cljs.core.Keyword(null,"link-href","link-href",-250644450),link_href,new cljs.core.Keyword(null,"match-length","match-length",1101537310),match_length,new cljs.core.Keyword(null,"current-url-length","current-url-length",380404083),cljs.core.count.call(null,figwheel.client.file_reloading.truncate_url.call(null,link_href))], null); } else { return null; } } else { return null; } }); figwheel.client.file_reloading.get_correct_link = (function figwheel$client$file_reloading$get_correct_link(f_data){ var temp__4425__auto__ = cljs.core.first.call(null,cljs.core.sort_by.call(null,(function (p__24801){ var map__24802 = p__24801; var map__24802__$1 = ((((!((map__24802 == null)))?((((map__24802.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24802.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24802):map__24802); var match_length = cljs.core.get.call(null,map__24802__$1,new cljs.core.Keyword(null,"match-length","match-length",1101537310)); var current_url_length = cljs.core.get.call(null,map__24802__$1,new cljs.core.Keyword(null,"current-url-length","current-url-length",380404083)); return (current_url_length - match_length); }),cljs.core.keep.call(null,(function (p1__24797_SHARP_){ return figwheel.client.file_reloading.matches_file_QMARK_.call(null,f_data,p1__24797_SHARP_); }),figwheel.client.file_reloading.current_links.call(null)))); if(cljs.core.truth_(temp__4425__auto__)){ var res = temp__4425__auto__; return new cljs.core.Keyword(null,"link","link",-1769163468).cljs$core$IFn$_invoke$arity$1(res); } else { return null; } }); figwheel.client.file_reloading.clone_link = (function figwheel$client$file_reloading$clone_link(link,url){ var clone = document.createElement("link"); clone.rel = "stylesheet"; clone.media = link.media; clone.disabled = link.disabled; clone.href = figwheel.client.file_reloading.add_cache_buster.call(null,url); return clone; }); figwheel.client.file_reloading.create_link = (function figwheel$client$file_reloading$create_link(url){ var link = document.createElement("link"); link.rel = "stylesheet"; link.href = figwheel.client.file_reloading.add_cache_buster.call(null,url); return link; }); figwheel.client.file_reloading.add_link_to_doc = (function figwheel$client$file_reloading$add_link_to_doc(var_args){ var args24804 = []; var len__17884__auto___24807 = arguments.length; var i__17885__auto___24808 = (0); while(true){ if((i__17885__auto___24808 < len__17884__auto___24807)){ args24804.push((arguments[i__17885__auto___24808])); var G__24809 = (i__17885__auto___24808 + (1)); i__17885__auto___24808 = G__24809; continue; } else { } break; } var G__24806 = args24804.length; switch (G__24806) { case 1: return figwheel.client.file_reloading.add_link_to_doc.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return figwheel.client.file_reloading.add_link_to_doc.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args24804.length)].join(''))); } }); figwheel.client.file_reloading.add_link_to_doc.cljs$core$IFn$_invoke$arity$1 = (function (new_link){ return (document.getElementsByTagName("head")[(0)]).appendChild(new_link); }); figwheel.client.file_reloading.add_link_to_doc.cljs$core$IFn$_invoke$arity$2 = (function (orig_link,klone){ var parent = orig_link.parentNode; if(cljs.core._EQ_.call(null,orig_link,parent.lastChild)){ parent.appendChild(klone); } else { parent.insertBefore(klone,orig_link.nextSibling); } return setTimeout(((function (parent){ return (function (){ return parent.removeChild(orig_link); });})(parent)) ,(300)); }); figwheel.client.file_reloading.add_link_to_doc.cljs$lang$maxFixedArity = 2; figwheel.client.file_reloading.distictify = (function figwheel$client$file_reloading$distictify(key,seqq){ return cljs.core.vals.call(null,cljs.core.reduce.call(null,(function (p1__24811_SHARP_,p2__24812_SHARP_){ return cljs.core.assoc.call(null,p1__24811_SHARP_,cljs.core.get.call(null,p2__24812_SHARP_,key),p2__24812_SHARP_); }),cljs.core.PersistentArrayMap.EMPTY,seqq)); }); figwheel.client.file_reloading.reload_css_file = (function figwheel$client$file_reloading$reload_css_file(p__24813){ var map__24816 = p__24813; var map__24816__$1 = ((((!((map__24816 == null)))?((((map__24816.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24816.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24816):map__24816); var f_data = map__24816__$1; var file = cljs.core.get.call(null,map__24816__$1,new cljs.core.Keyword(null,"file","file",-1269645878)); var temp__4425__auto__ = figwheel.client.file_reloading.get_correct_link.call(null,f_data); if(cljs.core.truth_(temp__4425__auto__)){ var link = temp__4425__auto__; return figwheel.client.file_reloading.add_link_to_doc.call(null,link,figwheel.client.file_reloading.clone_link.call(null,link,link.href)); } else { return null; } }); figwheel.client.file_reloading.reload_css_files = (function figwheel$client$file_reloading$reload_css_files(p__24818,files_msg){ var map__24825 = p__24818; var map__24825__$1 = ((((!((map__24825 == null)))?((((map__24825.cljs$lang$protocol_mask$partition0$ & (64))) || (map__24825.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__24825):map__24825); var opts = map__24825__$1; var on_cssload = cljs.core.get.call(null,map__24825__$1,new cljs.core.Keyword(null,"on-cssload","on-cssload",1825432318)); if(cljs.core.truth_(figwheel.client.utils.html_env_QMARK_.call(null))){ var seq__24827_24831 = cljs.core.seq.call(null,figwheel.client.file_reloading.distictify.call(null,new cljs.core.Keyword(null,"file","file",-1269645878),new cljs.core.Keyword(null,"files","files",-472457450).cljs$core$IFn$_invoke$arity$1(files_msg))); var chunk__24828_24832 = null; var count__24829_24833 = (0); var i__24830_24834 = (0); while(true){ if((i__24830_24834 < count__24829_24833)){ var f_24835 = cljs.core._nth.call(null,chunk__24828_24832,i__24830_24834); figwheel.client.file_reloading.reload_css_file.call(null,f_24835); var G__24836 = seq__24827_24831; var G__24837 = chunk__24828_24832; var G__24838 = count__24829_24833; var G__24839 = (i__24830_24834 + (1)); seq__24827_24831 = G__24836; chunk__24828_24832 = G__24837; count__24829_24833 = G__24838; i__24830_24834 = G__24839; continue; } else { var temp__4425__auto___24840 = cljs.core.seq.call(null,seq__24827_24831); if(temp__4425__auto___24840){ var seq__24827_24841__$1 = temp__4425__auto___24840; if(cljs.core.chunked_seq_QMARK_.call(null,seq__24827_24841__$1)){ var c__17629__auto___24842 = cljs.core.chunk_first.call(null,seq__24827_24841__$1); var G__24843 = cljs.core.chunk_rest.call(null,seq__24827_24841__$1); var G__24844 = c__17629__auto___24842; var G__24845 = cljs.core.count.call(null,c__17629__auto___24842); var G__24846 = (0); seq__24827_24831 = G__24843; chunk__24828_24832 = G__24844; count__24829_24833 = G__24845; i__24830_24834 = G__24846; continue; } else { var f_24847 = cljs.core.first.call(null,seq__24827_24841__$1); figwheel.client.file_reloading.reload_css_file.call(null,f_24847); var G__24848 = cljs.core.next.call(null,seq__24827_24841__$1); var G__24849 = null; var G__24850 = (0); var G__24851 = (0); seq__24827_24831 = G__24848; chunk__24828_24832 = G__24849; count__24829_24833 = G__24850; i__24830_24834 = G__24851; continue; } } else { } } break; } return setTimeout(((function (map__24825,map__24825__$1,opts,on_cssload){ return (function (){ return on_cssload.call(null,new cljs.core.Keyword(null,"files","files",-472457450).cljs$core$IFn$_invoke$arity$1(files_msg)); });})(map__24825,map__24825__$1,opts,on_cssload)) ,(100)); } else { return null; } }); //# sourceMappingURL=file_reloading.js.map?rel=1449036926031
imaximix/om-tutorials
resources/public/js/compiled/out/figwheel/client/file_reloading.js
JavaScript
mit
99,819
export default class State { constructor($rootScope) { this.$rootScope = $rootScope; this.state = []; } setData(data) { console.log('state set data', data) this.state = data; this.$rootScope.$apply(); } getData() { //console.log('state get data', state) return this.state; } }
vanzylv/youtube-dl-gui-v2
scripts/services/downloadState.js
JavaScript
mit
361
var request = require('request'); var Client = (function () { function Client() { this.options = { "url": "", "method": "GET", "bodyParams": {}, "gzip": true, "json": true }; } Client.prototype.connect = function (parent) { var config = parent.config; this.configure(config); this._connector = parent; parent.logger.trace('Connected to google custom search'); }; Client.prototype.disconnect = function (parent) { this.config = {}; this.url = ''; this._connector = parent; parent.logger.trace('Disconnected from google custom search'); }; Client.prototype.configure = function (config) { if (!config || !config.key) throw new Error('Configuration is not set.'); this.key = config.key; this.config = config; if (config.cx) this.cx = config.cx; else if (config.cref) this.cref = config.cref; if (!this.cx && !this.cref) throw new Error('You must provide either cx or cref parameter in your configuration!'); this.url = 'https://www.googleapis.com/customsearch/v1?key=' + this.key; if (this.cx) this.url += '&cx=' + this.cx; else if (this.cref) this.url += '&cref=' + this.cref; this.baseUrl = this.url; return true; }; Client.prototype.setParameters = function (v) { if (!v.where) throw "You need to set a where clause and provide a query ('q') parameter"; if (typeof v.where === 'string' || v.where instanceof String) v.where = JSON.parse(v.where); if (!v.where.q) { throw "You need to provide a query ('q') parameter in where clause."; } this._parseParameters(v); this._creteQuery(); this.url = this.baseUrl + this._query; return this; }; Client.prototype.query = function (callback) { this.options.url = this.url; return request(this.options, callback); }; Client.prototype.prepareResults = function (results, model) { var tmp_results = []; if (results && results.length) { for (var i = 0; i < results.length; i++) { var p_model = this._createIndividualModel(model, results[i]); tmp_results.push(p_model); } } return tmp_results; }; Client.prototype._creteQuery = function () { var params = this._params; var i = 0; for (var key in params) { if (i === 0) { this._query = '&' + key + '=' + params[key]; } else { this._query += '&' + key + '=' + params[key]; } i++; } return this._query; }; Client.prototype._parseParameters = function (v) { if (!v.per_page) v.where.num = 10; else v.where.num = v.per_page; if (!v.skip) v.where.start = 1; else v.where.start = v.skip; if (v.limit) v.where.num = v.limit - v.where.start; if (v.page) { v.where.start = ((v.page - 1) * v.per_page + 1); } if (v.order) v.where.sort = v.order; if (v.linkSite) v.where.linkSite = v.linkSite; if (v.lowRange) v.where.lowRange = v.lowRange; if (v.relatedSite) v.where.relatedSite = v.relatedSite; if (v.searchType) v.where.searchType = v.searchType; if (v.siteSearch) v.where.siteSearch = v.siteSearch; if (v.siteSearchFilter) v.where.siteSearchFilter = v.siteSearchFilter; this._params = v.where; return true; }; Client.prototype._createIndividualModel = function (Model, data) { var model = Model.instance(data, true); model.setPrimaryKey(data.cacheId); return model; }; return Client; })(); exports.Client = Client; //# sourceMappingURL=client.js.map
marinvvasilev/appc.googlesearch
lib/client.js
JavaScript
mit
4,155
function* generatorFn() { yield 'foo'; yield 'bar'; return 'baz'; } let generatorObject1 = generatorFn(); let generatorObject2 = generatorFn(); console.log(generatorObject1.next()); // { done: false, value: 'foo' } console.log(generatorObject2.next()); // { done: false, value: 'foo' } console.log(generatorObject2.next()); // { done: false, value: 'bar' } console.log(generatorObject1.next()); // { done: false, value: 'bar' } GeneratorYieldExample03.js
msfrisbie/pjwd-src
Chapter7IteratorsAndGenerators/Generators/InterruptingExecutionWithYield/InterruptingExecutionWithYieldExample03.js
JavaScript
mit
472
// var isWaiting = false; // var isRunning = false; // var seconds = 10; // var countdownTimer; // var finalCountdown = false; function GameTimer(game) { this.seconds = game.timelimit; this.secondPassed = function() { if (this.seconds === 0 && !game.gameOver) { game.endGame(); } else if (!game.gameOver) { this.seconds--; $("#timer_num").html(this.seconds); } } var countdownTimer = setInterval('t.secondPassed()', 1000); }
alanflorendo/syllabgl
public/js/timer.js
JavaScript
mit
457
/* global Cervus */ const material = new Cervus.materials.PhongMaterial({ requires: [ Cervus.components.Render, Cervus.components.Transform ], texture: Cervus.core.image_loader('../textures/4.png'), normal_map: Cervus.core.image_loader('../textures/normal2.jpg') }); const phong_material = new Cervus.materials.PhongMaterial({ requires: [ Cervus.components.Render, Cervus.components.Transform ] }); const game = new Cervus.core.Game({ width: window.innerWidth, height: window.innerHeight, // clear_color: 'f0f' // fps: 1 }); game.camera.get_component(Cervus.components.Move).keyboard_controlled = true; // game.camera.get_component(Cervus.components.Move).mouse_controlled = true; // By default all entities face the user. // Rotate the camera to see the scene. const camera_transform = game.camera.get_component(Cervus.components.Transform); camera_transform.position = [0, 2, 5]; camera_transform.rotate_rl(Math.PI); // game.camera.keyboard_controlled = true; const plane = new Cervus.shapes.Plane(); const plane_transform = plane.get_component(Cervus.components.Transform); const plane_render = plane.get_component(Cervus.components.Render); plane_transform.scale = [100, 1, 100]; plane_render.material = phong_material; plane_render.color = "#eeeeee"; game.add(plane); const cube = new Cervus.shapes.Box(); const cube_transform = cube.get_component(Cervus.components.Transform); const cube_render = cube.get_component(Cervus.components.Render); cube_render.material = material; cube_render.color = "#00ff00"; cube_transform.position = [0, 0.5, -1]; const group = new Cervus.core.Entity({ components: [ new Cervus.components.Transform() ] }); game.add(group); group.add(cube); // game.on('tick', () => { // group.get_component(Cervus.components.Transform).rotate_rl(16/1000); game.light.get_component(Cervus.components.Transform).position = game.camera.get_component(Cervus.components.Transform).position; });
michalbe/cervus
_example/5/game.js
JavaScript
mit
1,969
/* Zepto v1.1.4 - zepto event ajax form ie - zeptojs.com/license */ var Zepto = (function() { var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter, document = window.document, elementDisplay = {}, classCache = {}, cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, fragmentRE = /^\s*<(\w+|!)[^>]*>/, singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rootNodeRE = /^(?:body|html)$/i, capitalRE = /([A-Z])/g, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, readyRE = /complete|loaded|interactive/, simpleSelectorRE = /^[\w-]*$/, class2type = {}, toString = class2type.toString, zepto = {}, camelize, uniq, tempParent = document.createElement('div'), propMap = { 'tabindex': 'tabIndex', 'readonly': 'readOnly', 'for': 'htmlFor', 'class': 'className', 'maxlength': 'maxLength', 'cellspacing': 'cellSpacing', 'cellpadding': 'cellPadding', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'contenteditable': 'contentEditable' }, isArray = Array.isArray || function(object){ return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match, parent = element.parentNode, temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" } function isFunction(value) { return type(value) == "function" } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == "object" } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { return typeof obj.length == 'number' } function compact(array) { return filter.call(array, function(item){ return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue("display") element.parentNode.removeChild(element) display == "none" && (display = "block") elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overriden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function(){ container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. Note that `__proto__` is not supported on Internet // Explorer. This method can be overriden in plugins. zepto.Z = function(dom, selector) { dom = dom || [] dom.__proto__ = $.fn dom.selector = selector || '' return dom } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overriden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overriden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context){ return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target){ var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } args.forEach(function(arg){ extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overriden in plugins. zepto.qsa = function(element, selector){ var found, maybeID = selector[0] == '#', maybeClass = !maybeID && selector[0] == '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked isSimple = simpleSelectorRE.test(nameOnly) return (isDocument(element) && isSimple && maybeID) ? ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : (element.nodeType !== 1 && element.nodeType !== 9) ? [] : slice.call( isSimple && !maybeID ? maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = document.documentElement.contains ? function(parent, node) { return parent !== node && parent.contains(node) } : function(parent, node) { while (node && (node = node.parentNode)) if (node === parent) return true return false } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value){ var klass = node.className, svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { var num try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : !/^0/.test(value) && !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? "" : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.map = function(elements, callback){ var value, values = [], i, key if (likeArray(elements)) for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } else for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } return flatten(values) } $.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements } return elements } $.grep = function(elements, callback){ return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, indexOf: emptyArray.indexOf, concat: emptyArray.concat, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn){ return $($.map(this, function(el, i){ return fn.call(el, i, el) })) }, slice: function(){ return $(slice.apply(this, arguments)) }, ready: function(callback){ // need to check if document.body exists for IE as that browser reports // document ready when it hasn't yet created the body element if (readyRE.test(document.readyState) && document.body) callback($) else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false) return this }, get: function(idx){ return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function(){ return this.get() }, size: function(){ return this.length }, remove: function(){ return this.each(function(){ if (this.parentNode != null) this.parentNode.removeChild(this) }) }, each: function(callback){ emptyArray.every.call(this, function(el, idx){ return callback.call(el, idx, el) !== false }) return this }, filter: function(selector){ if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element){ return zepto.matches(element, selector) })) }, add: function(selector,context){ return $(uniq(this.concat($(selector,context)))) }, is: function(selector){ return this.length > 0 && zepto.matches(this[0], selector) }, not: function(selector){ var nodes=[] if (isFunction(selector) && selector.call !== undefined) this.each(function(idx){ if (!selector.call(this,idx)) nodes.push(this) }) else { var excludes = typeof selector == 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el){ if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector){ return this.filter(function(){ return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx){ return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) }, first: function(){ var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function(){ var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector){ var result, $this = this if (!selector) result = [] else if (typeof selector == 'object') result = $(selector).filter(function(){ var node = this return emptyArray.some.call($this, function(parent){ return $.contains(parent, node) }) }) else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function(){ return zepto.qsa(this, selector) }) return result }, closest: function(selector, context){ var node = this[0], collection = false if (typeof selector == 'object') collection = $(selector) while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) node = node !== context && !isDocument(node) && node.parentNode return $(node) }, parents: function(selector){ var ancestors = [], nodes = this while (nodes.length > 0) nodes = $.map(nodes, function(node){ if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) return filtered(ancestors, selector) }, parent: function(selector){ return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector){ return filtered(this.map(function(){ return children(this) }), selector) }, contents: function() { return this.map(function() { return slice.call(this.childNodes) }) }, siblings: function(selector){ return filtered(this.map(function(i, el){ return filter.call(children(el.parentNode), function(child){ return child!==el }) }), selector) }, empty: function(){ return this.each(function(){ this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property){ return $.map(this, function(el){ return el[property] }) }, show: function(){ return this.each(function(){ this.style.display == "none" && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = defaultDisplay(this.nodeName) }) }, replaceWith: function(newContent){ return this.before(newContent).remove() }, wrap: function(structure){ var func = isFunction(structure) if (this[0] && !func) var dom = $(structure).get(0), clone = dom.parentNode || this.length > 1 return this.each(function(index){ $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure){ if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure){ var func = isFunction(structure) return this.each(function(index){ var self = $(this), contents = self.contents(), dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function(){ this.parent().each(function(){ $(this).replaceWith($(this).children()) }) return this }, clone: function(){ return this.map(function(){ return this.cloneNode(true) }) }, hide: function(){ return this.css("display", "none") }, toggle: function(setting){ return this.each(function(){ var el = $(this) ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() }) }, prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html){ return 0 in arguments ? this.each(function(idx){ var originHtml = this.innerHTML $(this).empty().append( funcArg(this, html, idx, originHtml) ) }) : (0 in this ? this[0].innerHTML : null) }, text: function(text){ return 0 in arguments ? this.each(function(idx){ var newText = funcArg(this, text, idx, this.textContent) this.textContent = newText == null ? '' : ''+newText }) : (0 in this ? this[0].textContent : null) }, attr: function(name, value){ var result return (typeof name == 'string' && !(1 in arguments)) ? (!this.length || this[0].nodeType !== 1 ? undefined : (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result ) : this.each(function(idx){ if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name){ return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) }) }, prop: function(name, value){ name = propMap[name] || name return (1 in arguments) ? this.each(function(idx){ this[name] = funcArg(this, value, idx, this[name]) }) : (this[0] && this[0][name]) }, data: function(name, value){ var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() var data = (1 in arguments) ? this.attr(attrName, value) : this.attr(attrName) return data !== null ? deserializeValue(data) : undefined }, val: function(value){ return 0 in arguments ? this.each(function(idx){ this.value = funcArg(this, value, idx, this.value) }) : (this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : this[0].value) ) }, offset: function(coordinates){ if (coordinates) return this.each(function(index){ var $this = $(this), coords = funcArg(this, coordinates, index, $this.offset()), parentOffset = $this.offsetParent().offset(), props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props['position'] = 'relative' $this.css(props) }) if (!this.length) return null var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value){ if (arguments.length < 2) { var element = this[0], computedStyle = getComputedStyle(element, '') if(!element) return if (typeof property == 'string') return element.style[camelize(property)] || computedStyle.getPropertyValue(property) else if (isArray(property)) { var props = {} $.each(isArray(property) ? property: [property], function(_, prop){ props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) this.each(function(){ this.style.removeProperty(dasherize(property)) }) else css = dasherize(property) + ":" + maybeAddPx(property, value) } else { for (key in property) if (!property[key] && property[key] !== 0) this.each(function(){ this.style.removeProperty(dasherize(key)) }) else css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } return this.each(function(){ this.style.cssText += ';' + css }) }, index: function(element){ return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name){ if (!name) return false return emptyArray.some.call(this, function(el){ return this.test(className(el)) }, classRE(name)) }, addClass: function(name){ if (!name) return this return this.each(function(idx){ classList = [] var cls = className(this), newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass){ if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) }) }, removeClass: function(name){ return this.each(function(idx){ if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ classList = classList.replace(classRE(klass), " ") }) className(this, classList.trim()) }) }, toggleClass: function(name, when){ if (!name) return this return this.each(function(idx){ var $this = $(this), names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass){ (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value){ if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function(){ this.scrollTop = value } : function(){ this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value){ if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function(){ this.scrollLeft = value } : function(){ this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function(){ var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") parent = parent.offsetParent return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } }) function traverseNode(node, fun) { fun(node) for (var i = 0, len = node.childNodes.length; i < len; i++) traverseNode(node.childNodes[i], fun) } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){ // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType, nodes = $.map(arguments, function(arg) { argType = type(arg) return argType == "object" || argType == "array" || arg == null ? arg : zepto.fragment(arg) }), parent, copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target){ parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null var parentInDocument = $.contains(document.documentElement, parent) nodes.forEach(function(node){ if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() parent.insertBefore(node, target) if (parentInDocument) traverseNode(node, function(el){ if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src) window['eval'].call(window, el.innerHTML) }) }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ $(html)[operator](this) return this } }) zepto.Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto return $ })() window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto) ;(function($){ var _zid = 1, undefined, slice = Array.prototype.slice, isFunction = $.isFunction, isString = function(obj){ return typeof obj == 'string' }, handlers = {}, specialEvents={}, focusinSupported = 'onfocusin' in window, focus = { focus: 'focusin', blur: 'focusout' }, hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' } specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' function zid(element) { return element._zid || (element._zid = _zid++) } function findHandlers(element, event, fn, selector) { event = parse(event) if (event.ns) var matcher = matcherFor(event.ns) return (handlers[zid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || zid(handler.fn) === zid(fn)) && (!selector || handler.sel == selector) }) } function parse(event) { var parts = ('' + event).split('.') return {e: parts[0], ns: parts.slice(1).sort().join(' ')} } function matcherFor(ns) { return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)') } function eventCapture(handler, captureSetting) { return handler.del && (!focusinSupported && (handler.e in focus)) || !!captureSetting } function realEvent(type) { return hover[type] || (focusinSupported && focus[type]) || type } function add(element, events, fn, data, selector, delegator, capture){ var id = zid(element), set = (handlers[id] || (handlers[id] = [])) events.split(/\s/).forEach(function(event){ if (event == 'ready') return $(document).ready(fn) var handler = parse(event) handler.fn = fn handler.sel = selector // emulate mouseenter, mouseleave if (handler.e in hover) fn = function(e){ var related = e.relatedTarget if (!related || (related !== this && !$.contains(this, related))) return handler.fn.apply(this, arguments) } handler.del = delegator var callback = delegator || fn handler.proxy = function(e){ e = compatible(e) if (e.isImmediatePropagationStopped()) return e.data = data var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args)) if (result === false) e.preventDefault(), e.stopPropagation() return result } handler.i = set.length set.push(handler) if ('addEventListener' in element) element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) } function remove(element, events, fn, selector, capture){ var id = zid(element) ;(events || '').split(/\s/).forEach(function(event){ findHandlers(element, event, fn, selector).forEach(function(handler){ delete handlers[id][handler.i] if ('removeEventListener' in element) element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) }) } $.event = { add: add, remove: remove } $.proxy = function(fn, context) { var args = (2 in arguments) && slice.call(arguments, 2) if (isFunction(fn)) { var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) } proxyFn._zid = zid(fn) return proxyFn } else if (isString(context)) { if (args) { args.unshift(fn[context], fn) return $.proxy.apply(null, args) } else { return $.proxy(fn[context], fn) } } else { throw new TypeError("expected function") } } $.fn.bind = function(event, data, callback){ return this.on(event, data, callback) } $.fn.unbind = function(event, callback){ return this.off(event, callback) } $.fn.one = function(event, selector, data, callback){ return this.on(event, selector, data, callback, 1) } var returnTrue = function(){return true}, returnFalse = function(){return false}, ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/, eventMethods = { preventDefault: 'isDefaultPrevented', stopImmediatePropagation: 'isImmediatePropagationStopped', stopPropagation: 'isPropagationStopped' } function compatible(event, source) { if (source || !event.isDefaultPrevented) { source || (source = event) $.each(eventMethods, function(name, predicate) { var sourceMethod = source[name] event[name] = function(){ this[predicate] = returnTrue return sourceMethod && sourceMethod.apply(source, arguments) } event[predicate] = returnFalse }) if (source.defaultPrevented !== undefined ? source.defaultPrevented : 'returnValue' in source ? source.returnValue === false : source.getPreventDefault && source.getPreventDefault()) event.isDefaultPrevented = returnTrue } return event } function createProxy(event) { var key, proxy = { originalEvent: event } for (key in event) if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] return compatible(proxy, event) } $.fn.delegate = function(selector, event, callback){ return this.on(event, selector, callback) } $.fn.undelegate = function(selector, event, callback){ return this.off(event, selector, callback) } $.fn.live = function(event, callback){ $(document.body).delegate(this.selector, event, callback) return this } $.fn.die = function(event, callback){ $(document.body).undelegate(this.selector, event, callback) return this } $.fn.on = function(event, selector, data, callback, one){ var autoRemove, delegator, $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.on(type, selector, data, fn, one) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = data, data = selector, selector = undefined if (isFunction(data) || data === false) callback = data, data = undefined if (callback === false) callback = returnFalse return $this.each(function(_, element){ if (one) autoRemove = function(e){ remove(element, e.type, callback) return callback.apply(this, arguments) } if (selector) delegator = function(e){ var evt, match = $(e.target).closest(selector, element).get(0) if (match && match !== element) { evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element}) return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1))) } } add(element, event, callback, data, selector, delegator || autoRemove) }) } $.fn.off = function(event, selector, callback){ var $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.off(type, selector, fn) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = selector, selector = undefined if (callback === false) callback = returnFalse return $this.each(function(){ remove(this, event, callback, selector) }) } $.fn.trigger = function(event, args){ event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event) event._args = args return this.each(function(){ // items in the collection might not be DOM elements if('dispatchEvent' in this) this.dispatchEvent(event) else $(this).triggerHandler(event, args) }) } // triggers event handlers on current element just as if an event occurred, // doesn't trigger an actual event, doesn't bubble $.fn.triggerHandler = function(event, args){ var e, result this.each(function(i, element){ e = createProxy(isString(event) ? $.Event(event) : event) e._args = args e.target = element $.each(findHandlers(element, event.type || event), function(i, handler){ result = handler.proxy(e) if (e.isImmediatePropagationStopped()) return false }) }) return result } // shortcut methods for `.bind(event, fn)` for each event type ;('focusin focusout load resize scroll unload click dblclick '+ 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+ 'change select keydown keypress keyup error').split(' ').forEach(function(event) { $.fn[event] = function(callback) { return callback ? this.bind(event, callback) : this.trigger(event) } }) ;['focus', 'blur'].forEach(function(name) { $.fn[name] = function(callback) { if (callback) this.bind(name, callback) else this.each(function(){ try { this[name]() } catch(e) {} }) return this } }) $.Event = function(type, props) { if (!isString(type)) props = type, type = props.type var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]) event.initEvent(type, bubbles, true) return compatible(event) } })(Zepto) ;(function($){ var jsonpID = 0, document = window.document, key, name, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, scriptTypeRE = /^(?:text|application)\/javascript/i, xmlTypeRE = /^(?:text|application)\/xml/i, jsonType = 'application/json', htmlType = 'text/html', blankRE = /^\s*$/ // trigger a custom event and return false if it was cancelled function triggerAndReturn(context, eventName, data) { var event = $.Event(eventName) $(context).trigger(event, data) return !event.isDefaultPrevented() } // trigger an Ajax "global" event function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data) } // Number of active Ajax requests $.active = 0 function ajaxStart(settings) { if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart') } function ajaxStop(settings) { if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop') } // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable function ajaxBeforeSend(xhr, settings) { var context = settings.context if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false) return false triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]) } function ajaxSuccess(data, xhr, settings, deferred) { var context = settings.context, status = 'success' settings.success.call(context, data, status, xhr) if (deferred) deferred.resolveWith(context, [data, status, xhr]) triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]) ajaxComplete(status, xhr, settings) } // type: "timeout", "error", "abort", "parsererror" function ajaxError(error, type, xhr, settings, deferred) { var context = settings.context settings.error.call(context, xhr, type, error) if (deferred) deferred.rejectWith(context, [xhr, type, error]) triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type]) ajaxComplete(type, xhr, settings) } // status: "success", "notmodified", "error", "timeout", "abort", "parsererror" function ajaxComplete(status, xhr, settings) { var context = settings.context settings.complete.call(context, xhr, status) triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings]) ajaxStop(settings) } // Empty function, used as default callback function empty() {} $.ajaxJSONP = function(options, deferred){ if (!('type' in options)) return $.ajax(options) var _callbackName = options.jsonpCallback, callbackName = ($.isFunction(_callbackName) ? _callbackName() : _callbackName) || ('jsonp' + (++jsonpID)), script = document.createElement('script'), originalCallback = window[callbackName], responseData, abort = function(errorType) { $(script).triggerHandler('error', errorType || 'abort') }, xhr = { abort: abort }, abortTimeout if (deferred) deferred.promise(xhr) $(script).on('load error', function(e, errorType){ clearTimeout(abortTimeout) $(script).off().remove() if (e.type == 'error' || !responseData) { ajaxError(null, errorType || 'error', xhr, options, deferred) } else { ajaxSuccess(responseData[0], xhr, options, deferred) } window[callbackName] = originalCallback if (responseData && $.isFunction(originalCallback)) originalCallback(responseData[0]) originalCallback = responseData = undefined }) if (ajaxBeforeSend(xhr, options) === false) { abort('abort') return xhr } window[callbackName] = function(){ responseData = arguments } script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) document.head.appendChild(script) if (options.timeout > 0) abortTimeout = setTimeout(function(){ abort('timeout') }, options.timeout) return xhr } $.ajaxSettings = { // Default type of request type: 'GET', // Callback that is executed before request beforeSend: empty, // Callback that is executed if the request succeeds success: empty, // Callback that is executed the the server drops error error: empty, // Callback that is executed on request complete (both: error and success) complete: empty, // The context for the callbacks context: null, // Whether to trigger "global" Ajax events global: true, // Transport xhr: function () { return new window.XMLHttpRequest() }, // MIME types mapping // IIS returns Javascript as "application/x-javascript" accepts: { script: 'text/javascript, application/javascript, application/x-javascript', json: jsonType, xml: 'application/xml, text/xml', html: htmlType, text: 'text/plain' }, // Whether the request is to another domain crossDomain: false, // Default timeout timeout: 0, // Whether data should be serialized to string processData: true, // Whether the browser should be allowed to cache GET responses cache: true } function mimeToDataType(mime) { if (mime) mime = mime.split(';', 2)[0] return mime && ( mime == htmlType ? 'html' : mime == jsonType ? 'json' : scriptTypeRE.test(mime) ? 'script' : xmlTypeRE.test(mime) && 'xml' ) || 'text' } function appendQuery(url, query) { if (query == '') return url return (url + '&' + query).replace(/[&?]{1,2}/, '?') } // serialize payload and append it to the URL for GET requests function serializeData(options) { if (options.processData && options.data && $.type(options.data) != "string") options.data = $.param(options.data, options.traditional) if (options.data && (!options.type || options.type.toUpperCase() == 'GET')) options.url = appendQuery(options.url, options.data), options.data = undefined } $.ajax = function(options){ var settings = $.extend({}, options || {}), deferred = $.Deferred && $.Deferred() for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] ajaxStart(settings) if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) && RegExp.$2 != window.location.host if (!settings.url) settings.url = window.location.toString() serializeData(settings) var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url) if (hasPlaceholder) dataType = 'jsonp' if (settings.cache === false || ( (!options || options.cache !== true) && ('script' == dataType || 'jsonp' == dataType) )) settings.url = appendQuery(settings.url, '_=' + Date.now()) if ('jsonp' == dataType) { if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?') return $.ajaxJSONP(settings, deferred) } var mime = settings.accepts[dataType], headers = { }, setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] }, protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol, xhr = settings.xhr(), nativeSetHeader = xhr.setRequestHeader, abortTimeout if (deferred) deferred.promise(xhr) if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') setHeader('Accept', mime || '*/*') if (mime = settings.mimeType || mime) { if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0] xhr.overrideMimeType && xhr.overrideMimeType(mime) } if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET')) setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]) xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { xhr.onreadystatechange = empty clearTimeout(abortTimeout) var result, error = false if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) { dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type')) result = xhr.responseText try { // http://perfectionkills.com/global-eval-what-are-the-options/ if (dataType == 'script') (1,eval)(result) else if (dataType == 'xml') result = xhr.responseXML else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result) } catch (e) { error = e } if (error) ajaxError(error, 'parsererror', xhr, settings, deferred) else ajaxSuccess(result, xhr, settings, deferred) } else { ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred) } } } if (ajaxBeforeSend(xhr, settings) === false) { xhr.abort() ajaxError(null, 'abort', xhr, settings, deferred) return xhr } if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] var async = 'async' in settings ? settings.async : true xhr.open(settings.type, settings.url, async, settings.username, settings.password) for (name in headers) nativeSetHeader.apply(xhr, headers[name]) if (settings.timeout > 0) abortTimeout = setTimeout(function(){ xhr.onreadystatechange = empty xhr.abort() ajaxError(null, 'timeout', xhr, settings, deferred) }, settings.timeout) // avoid sending empty string (#319) xhr.send(settings.data ? settings.data : null) return xhr } // handle optional data/success arguments function parseArguments(url, data, success, dataType) { if ($.isFunction(data)) dataType = success, success = data, data = undefined if (!$.isFunction(success)) dataType = success, success = undefined return { url: url , data: data , success: success , dataType: dataType } } $.get = function(/* url, data, success, dataType */){ return $.ajax(parseArguments.apply(null, arguments)) } $.post = function(/* url, data, success, dataType */){ var options = parseArguments.apply(null, arguments) options.type = 'POST' return $.ajax(options) } $.getJSON = function(/* url, data, success */){ var options = parseArguments.apply(null, arguments) options.dataType = 'json' return $.ajax(options) } $.fn.load = function(url, data, success){ if (!this.length) return this var self = this, parts = url.split(/\s/), selector, options = parseArguments(url, data, success), callback = options.success if (parts.length > 1) options.url = parts[0], selector = parts[1] options.success = function(response){ self.html(selector ? $('<div>').html(response.replace(rscript, "")).find(selector) : response) callback && callback.apply(self, arguments) } $.ajax(options) return this } var escape = encodeURIComponent function serialize(params, obj, traditional, scope){ var type, array = $.isArray(obj), hash = $.isPlainObject(obj) $.each(obj, function(key, value) { type = $.type(value) if (scope) key = traditional ? scope : scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']' // handle data in serializeArray() format if (!scope && array) params.add(value.name, value.value) // recurse into nested objects else if (type == "array" || (!traditional && type == "object")) serialize(params, value, traditional, key) else params.add(key, value) }) } $.param = function(obj, traditional){ var params = [] params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) } serialize(params, obj, traditional) return params.join('&').replace(/%20/g, '+') } })(Zepto) ;(function($){ $.fn.serializeArray = function() { var result = [], el $([].slice.call(this.get(0).elements)).each(function(){ el = $(this) var type = el.attr('type') if (this.nodeName.toLowerCase() != 'fieldset' && !this.disabled && type != 'submit' && type != 'reset' && type != 'button' && ((type != 'radio' && type != 'checkbox') || this.checked)) result.push({ name: el.attr('name'), value: el.val() }) }) return result } $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } $.fn.submit = function(callback) { if (callback) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto) ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto) // Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture function swipeDirection(x1, x2, y1, y2) { return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down') } function longTap() { longTapTimeout = null if (touch.last) { touch.el.trigger('longTap') touch = {} } } function cancelLongTap() { if (longTapTimeout) clearTimeout(longTapTimeout) longTapTimeout = null } function cancelAll() { if (touchTimeout) clearTimeout(touchTimeout) if (tapTimeout) clearTimeout(tapTimeout) if (swipeTimeout) clearTimeout(swipeTimeout) if (longTapTimeout) clearTimeout(longTapTimeout) touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null touch = {} } function isPrimaryTouch(event){ return (event.pointerType == 'touch' || event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary } function isPointerEventType(e, type){ return (e.type == 'pointer'+type || e.type.toLowerCase() == 'mspointer'+type) } $(document).ready(function(){ var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType if ('MSGesture' in window) { gesture = new MSGesture() gesture.target = document.body } $(document) .bind('MSGestureEnd', function(e){ var swipeDirectionFromVelocity = e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null; if (swipeDirectionFromVelocity) { touch.el.trigger('swipe') touch.el.trigger('swipe'+ swipeDirectionFromVelocity) } }) .on('touchstart MSPointerDown pointerdown', function(e){ if((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] if (e.touches && e.touches.length === 1 && touch.x2) { // Clear out touch movement data if we have it sticking around // This can occur if touchcancel doesn't fire due to preventDefault, etc. touch.x2 = undefined touch.y2 = undefined } now = Date.now() delta = now - (touch.last || now) touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode) touchTimeout && clearTimeout(touchTimeout) touch.x1 = firstTouch.pageX touch.y1 = firstTouch.pageY if (delta > 0 && delta <= 250) touch.isDoubleTap = true touch.last = now longTapTimeout = setTimeout(longTap, longTapDelay) // adds the current touch contact for IE gesture recognition if (gesture && _isPointerType) gesture.addPointer(e.pointerId); }) .on('touchmove MSPointerMove pointermove', function(e){ if((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] cancelLongTap() touch.x2 = firstTouch.pageX touch.y2 = firstTouch.pageY deltaX += Math.abs(touch.x1 - touch.x2) deltaY += Math.abs(touch.y1 - touch.y2) }) .on('touchend MSPointerUp pointerup', function(e){ if((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return cancelLongTap() // swipe if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) swipeTimeout = setTimeout(function() { touch.el.trigger('swipe') touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2))) touch = {} }, 0) // normal tap else if ('last' in touch) // don't fire tap when delta position changed by more than 30 pixels, // for instance when moving to a point and back to origin if (deltaX < 30 && deltaY < 30) { // delay by one tick so we can cancel the 'tap' event if 'scroll' fires // ('tap' fires before 'scroll') tapTimeout = setTimeout(function() { // trigger universal 'tap' with the option to cancelTouch() // (cancelTouch cancels processing of single vs double taps for faster 'tap' response) var event = $.Event('tap') event.cancelTouch = cancelAll touch.el.trigger(event) // trigger double tap immediately if (touch.isDoubleTap) { if (touch.el) touch.el.trigger('doubleTap') touch = {} } // trigger single tap after 250ms of inactivity else { touchTimeout = setTimeout(function(){ touchTimeout = null if (touch.el) touch.el.trigger('singleTap') touch = {} }, 250) } }, 0) } else { touch = {} } deltaX = deltaY = 0 }) // when the browser window loses focus, // for example when a modal dialog is shown, // cancel all ongoing events .on('touchcancel MSPointerCancel pointercancel', cancelAll) // scrolling the window indicates intention of the user // to scroll, not tap or swipe, so cancel all ongoing events $(window).on('scroll', cancelAll) }) ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){ $.fn[eventName] = function(callback){ return this.on(eventName, callback) } }) })(Zepto)
picacure/_sandBox
photoGallery/flux/js/zepto.js
JavaScript
mit
62,392
const SELECTOR_BOOK_IMAGE = '#default > div > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.image_container > a > img'; const puppeteer = require('puppeteer'); let scrapeSite1 = async (browser) => { const page = await browser.newPage(); await page.goto('http://books.toscrape.com/'); await page.waitFor(1000); await page.click(SELECTOR_BOOK_IMAGE); await page.waitFor(2000); const result = await page.evaluate(() => { let title = document.querySelector('h1').innerText; let price = document.querySelector('.price_color').innerText; return { title, price } }); return result; } let scrape = async () => { const browser = await puppeteer.launch({ headless: false }); const result = await Promise.all([ scrapeSite1(browser), scrapeSite1(browser), scrapeSite1(browser), scrapeSite1(browser), scrapeSite1(browser) ]); await browser.close(); return result; }; scrape().then((value) => { console.log(value); // Success! });
yogendra/yogendra.me
source/_posts/2017/10/28/puppeteer-no-strings-attached/scrape-multi.js
JavaScript
mit
1,035
var five = require("../lib/johnny-five.js"); var board = new five.Board(); board.on("ready", function() { var gyro = new five.Gyroscope({ pins: ["I0", "I1"], freq: 200, extent: 4 }); gyro.on("acceleration", function(data) { console.log(data.position); }); });
januszhou/pi
node_modules/johnny-five/eg/tinkerkit-imu-gyro-accel.js
JavaScript
mit
286
// "horizontalaxis" : { // "id" : STRING, "type" : DATATYPE(number), "length" : RELLEN(1.0), "base" : POINT(-1,1), "anchor" : DOUBLE(-1), "position" : POINT(0,0), // "min" : DATAVALUEORAUTO(auto), "max" : DATAVALUEORAUTO(auto), "minposition" : RELPOS(-1.0), "maxposition" : RELPOS(1.0), "color" : COLOR(black), "linewidth" : INTEGER(1), // "tickmin" : INTEGER(-3), "tickmax" : INTEGER(3), "tickcolor" : COLOR(black), // "labels" : { // "format" : STRING, "start" : DATAVALUE(0), "angle" : DOUBLE(0), "position" : POINT, // "anchor" : POINT, "color" : COLOR(black), "spacing" : STRING, "densityfactor" : DOUBLE(1.0), // "label" : [ // { "format" : STRING, "start" : STRING, "angle" : DOUBLE, "position" : POINT, "anchor" : POINT, "spacing" : STRING, "densityfactor" : DOUBLE }, // { "format" : STRING, "start" : STRING, "angle" : DOUBLE, "position" : POINT, "anchor" : POINT, "spacing" : STRING, "densityfactor" : DOUBLE }, // ... // ] // } // "title" : { "base" : DOUBLE(0), "anchor" : POINT, "position" : POINT, "angle" : DOUBLE(0), "text" : "TITLETEXT", "font": STRING }, // "grid" : { "color" : COLOR(0xeeeeee), "visible" : BOOLEAN(false) }, // "pan" : { "allowed" : BOOLEAN(yes), "min" : DATAVALUE, "max" : DATAVALUE }, // "zoom" : { "allowed" : BOOLEAN(yes), "min" : DATAMEASURE, "max" : DATAMEASURE, "anchor" : DATAVALUE }, // "binding" : { "id" : STRING!, "min" : DATAVALUE!, "max" : DATAVALUE! } // "visible" : BOOLEAN(true) // } // these are needed so that their .parseJSON methods will be defined when called below: require('./labeler.js'); require('./axis_title.js'); require('./grid.js'); require('./pan.js'); require('./zoom.js'); var Axis = require('../../core/axis.js'), pF = require('../../util/parsingFunctions.js'), vF = require('../../util/validationFunctions.js'), uF = require('../../util/utilityFunctions.js'); var parseLabels = function (json, axis) { var spacings, labelers = axis.labelers(), Labeler = require('../../core/labeler.js'), DataValue = require('../../core/data_value.js'), i; spacings = []; if (json !== undefined) { if (json.spacing !== undefined) { spacings = vF.typeOf(json.spacing) === 'array' ? json.spacing : [ json.spacing ]; } } if (spacings.length > 0) { // If there was a spacing attr on the <labels> tag, create a new labeler for // each spacing present in it, using the other values from the <labels> tag for (i = 0; i < spacings.length; ++i) { labelers.add(Labeler.parseJSON(json, axis, undefined, spacings[i])); } } else if (json !== undefined && json.label !== undefined && json.label.length > 0) { // If there are <label> tags, parse the <labels> tag to get default values var defaults = Labeler.parseJSON(json, axis, undefined, null); // And loop over each <label> tag, creating labelers for each, splitting multiple // spacings on the same <label> tag into multiple labelers: json.label.forEach(function(e) { var spacing = []; if (e.spacing !== undefined) { spacing = vF.typeOf(e.spacing) === 'array' ? e.spacing : [ e.spacing ]; } spacing.forEach(function(s) { labelers.add( Labeler.parseJSON(e, axis, defaults, s) ); }); }); } else { // Otherwise create labelers using the default spacing, with the other values // from the <labels> tag var defaultValues = (uF.getDefaultValuesFromXSD()).horizontalaxis.labels; var defaultSpacings = axis.type() === DataValue.NUMBER ? defaultValues.defaultNumberSpacing : defaultValues.defaultDatetimeSpacing; for (i = 0; i < defaultSpacings.length; ++i) { labelers.add(Labeler.parseJSON(json, axis, undefined, defaultSpacings[i])); } } }; Axis.parseJSON = function (json, orientation, messageHandler, multigraph) { var DataValue = require('../../core/data_value.js'), Point = require('../../math/point.js'), RGBColor = require('../../math/rgb_color.js'), Displacement = require('../../math/displacement.js'), AxisTitle = require('../../core/axis_title.js'), Grid = require('../../core/grid.js'), Pan = require('../../core/pan.js'), Zoom = require('../../core/zoom.js'), AxisBinding = require('../../core/axis_binding.js'), axis = new Axis(orientation), parseAttribute = pF.parseAttribute, parseDisplacement = Displacement.parse, parseJSONPoint = function(p) { return new Point(p[0], p[1]); }, parseRGBColor = RGBColor.parse, attr, child, value; if (json) { parseAttribute(json.id, axis.id); parseAttribute(json.type, axis.type, DataValue.parseType); parseAttribute(json.length, axis.length, parseDisplacement); // // The following provides support for the deprecated "positionbase" axis attribute; // MUGL files should use the "base" attribute instead. When we're ready to remove // support for the deprecated attribute, delete this block of code: // (function () { var positionbase = json.positionbase; if (positionbase) { messageHandler.warning('Use of deprecated axis attribute "positionbase"; use "base" attribute instead'); if ((positionbase === "left") || (positionbase === "bottom")) { axis.base(new Point(-1, -1)); } else if (positionbase === "right") { axis.base(new Point(1, -1)); } else if (positionbase === "top") { axis.base(new Point(-1, 1)); } } }()); // // End of code to delete when removing support for deprecated "positionbase" // attribute. // attr = json.position; if (attr !== undefined) { if (vF.typeOf(attr) === 'array') { axis.position(parseJSONPoint(attr)); } else { // If position is not an array, and if it can be interpreted // as a number, construct the position point by interpreting that // number as an offset from the 0 location along the perpendicular // direction. if (vF.isNumberNotNaN(attr)) { if (orientation === Axis.HORIZONTAL) { axis.position(new Point(0, attr)); } else { axis.position(new Point(attr, 0)); } } else { throw new Error("axis position '"+attr+"' is of the wrong type; it should be a number or a point"); } } } // Note: we coerce the min and max values to strings here, because the "min" and "max" attrs // of the Axis object require strings. See the comments about these properties in src/core/axis.js // for a discussion of why this is the case. if ("min" in json) { axis.min(uF.coerceToString(json.min)); } if (axis.min() !== "auto") { axis.dataMin(DataValue.parse(axis.type(), axis.min())); } if ("max" in json) { axis.max(uF.coerceToString(json.max)); } if (axis.max() !== "auto") { axis.dataMax(DataValue.parse(axis.type(), axis.max())); } parseAttribute(json.pregap, axis.pregap); parseAttribute(json.postgap, axis.postgap); parseAttribute(json.anchor, axis.anchor); parseAttribute(json.base, axis.base, parseJSONPoint); parseAttribute(json.minposition, axis.minposition, parseDisplacement); parseAttribute(json.maxposition, axis.maxposition, parseDisplacement); parseAttribute(json.minoffset, axis.minoffset); parseAttribute(json.maxoffset, axis.maxoffset); parseAttribute(json.color, axis.color, parseRGBColor); parseAttribute(json.tickcolor, axis.tickcolor, parseRGBColor); parseAttribute(json.tickwidth, axis.tickwidth); parseAttribute(json.tickmin, axis.tickmin); parseAttribute(json.tickmax, axis.tickmax); parseAttribute(json.highlightstyle, axis.highlightstyle); parseAttribute(json.linewidth, axis.linewidth); if ("title" in json) { if (typeof(json.title) === 'boolean') { if (json.title) { axis.title(new AxisTitle(axis)); } else { axis.title(AxisTitle.parseJSON({}, axis)); } } else { axis.title(AxisTitle.parseJSON(json.title, axis)); } } else { axis.title(new AxisTitle(axis)); } if (json.grid) { axis.grid(Grid.parseJSON(json.grid)); } if (json.visible !== undefined) { axis.visible(json.visible); } if ("pan" in json) { axis.pan(Pan.parseJSON(json.pan, axis.type())); } if ("zoom" in json) { axis.zoom(Zoom.parseJSON(json.zoom, axis.type())); } if (json.labels) { parseLabels(json.labels, axis); } if (json.binding) { var bindingMinDataValue = DataValue.parse(axis.type(), json.binding.min), bindingMaxDataValue = DataValue.parse(axis.type(), json.binding.max); if (typeof(json.binding.id) !== "string") { throw new Error("invalid axis binding id: '" + json.binding.id + "'"); } if (! DataValue.isInstance(bindingMinDataValue)) { throw new Error("invalid axis binding min: '" + json.binding.min + "'"); } if (! DataValue.isInstance(bindingMaxDataValue)) { throw new Error("invalid axis binding max: '" + json.binding.max + "'"); } AxisBinding.findByIdOrCreateNew(json.binding.id).addAxis(axis, bindingMinDataValue, bindingMaxDataValue, multigraph); } } return axis; }; module.exports = Axis;
multigraph/js-multigraph
src/parser/json/axis.js
JavaScript
mit
10,515
version https://git-lfs.github.com/spec/v1 oid sha256:d5b913ad3304fa791ac6c6064dcecf37b157290bb0e8292e76aee05bee6dc425 size 3752
yogeshsaroya/new-cdnjs
ajax/libs/reqwest/0.2.2/reqwest.min.js
JavaScript
mit
129
/** * Filtering sensitive information */ const _ = require('lodash'); /** * reset option * @param {string|object|array} opt filter option * @param {array} filterKeys filter keys * @param {string|function} replaceChat replace chat or function * @param {boolean} recursion whether recursive , true of false */ const setOption = (option) => { let filterKeys = ['password', 'token', 'authorization']; let replaceChat = '*'; let recursion = false; if (option !== undefined) { if (typeof option === 'string') { filterKeys = [option]; } else if (option instanceof Array && option.length > 0) { filterKeys = option.filter(item => typeof item === 'string'); } else if (_.isPlainObject(option)) { const { filterKeys: fks, recursion: rcs, replaceChat: rpc } = option; recursion = !!rcs; if (fks instanceof Array && fks.length > 0) { filterKeys = fks.filter(item => typeof item === 'string'); } if (typeof rpc === 'string') { replaceChat = rpc; } else { replaceChat = '*'; } } else { console.error(new Error(`option.filter do not support ${typeof option} type !`)); } } return { filterKeys, recursion, replaceChat }; }; /** * replace by replaceChat * @param {string} param content to replace * @param {string|function} replaceChat replace chat or function */ const replace = (param, replaceChat) => { if (typeof replaceChat === 'function') { return replaceChat(param); } return param.replace(/\S/g, '*'); }; /** * filter log message by option * @param {*} message logger message * @param {object} opt filter option * @param {boolean} hit hit the fileterkeys , default false */ const filter = (message, opt, hit = false) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { const dHit = hit || filterKeys.indexOf(key) > -1; result[key] = filter(result[key], opt, dHit); // if (recursion) { // result[key] = filter(param, opt, true); // } else { // result[key] = replaceChat; // // replace the value of hit key // // eslint-disable-next-line no-return-assign // Object.keys(param).forEach(pk => (filterKeys.indexOf(pk) !== -1 ? result[key] = replaceChat : '')); // } }); return result; } else if (typeof result === 'number') { return replace(result.toString(), replaceChat); } else if (result instanceof Array && result.length > 0) { return result.map(param => filter(param, opt, hit)); } return replace(result, replaceChat); }; /** * filter log message by option do not recursion * @param {*} message logger message * @param {object} opt filter option * @param {array} opt.filterKeys filter keys * @param {string} opt.replaceChat replace chat or function */ const filterNoRecursion = (message, opt) => { const result = message; const { filterKeys, replaceChat } = opt; if (_.isPlainObject(result)) { Object.keys(result).forEach((key) => { if (filterKeys.indexOf(key) === -1) { result[key] = filterNoRecursion(result[key], opt); } else { result[key] = replaceChat; } }); return result; } else if (typeof result === 'number') { return result; } else if (result instanceof Array && result.length > 0) { return result; } return result; }; /** * filter sensitive information * @param {object} message log message * @param {*} option filter option */ const filteringSensitiveInfo = (message, option = false) => { if (!option) { return message; } if (typeof option === 'function') { return option(message); } return filterNoRecursion(message, setOption(option)); }; module.exports = { filteringSensitiveInfo, setOption, };
baijijs/logger
lib/filter.js
JavaScript
mit
3,846
describe("The ot object has a forEach method, which allows you: ", function () { it("To iterate over an array", function () { var array = [1, 2, 4, 8, 16]; var sum = 0; var sumIndex = 0; ot.forEach(array, function (value, index) { sum += value; sumIndex += index; expect(this.context).toBe(true); }, {context: true}); expect(sum).toBe(1 + 2 + 4 + 8 + 16); expect(sumIndex).toBe(1 + 2 + 3 + 4); }); it("To iterate over an object's properties", function () { var obj = { prop1: false, prop2: false, prop3: false }; ot.forEach(obj, function (value, key) { obj[key] = !value; expect(this.context).toBe(true); }, {context: true}); expect(obj.prop1).toBe(true); expect(obj.prop2).toBe(true); expect(obj.prop3).toBe(true); }); it("To iterate over user set function properties", function () { var fnWithProps = function aName() { }; fnWithProps.prop1 = false; fnWithProps.prop2 = false; fnWithProps.prop3 = false; ot.forEach(fnWithProps, function (value, key) { fnWithProps[key] = !value; expect(this.context).toBe(true); }, {context: true}); expect(fnWithProps.prop1).toBe(true); expect(fnWithProps.prop2).toBe(true); expect(fnWithProps.prop3).toBe(true); }); it("To iterate over an object with a forEach method", function () { var objectWithForEach = { forEach: function (iterator, context) { iterator.call(context, true); } }; ot.forEach(objectWithForEach, function(calledFromForEach) { expect(calledFromForEach).toBe(true); expect(this.context).toBe(true); }, {context: true}); }); });
rodyhaddad/objectTools.js
tests/specs/forEach.js
JavaScript
mit
1,933
import * as types from '../actions/types'; const search = (state = [], action) => { switch(action.type) { case types.SEARCH_INPUT_SUCCESS: return action.data; case types.SEARCH_INPUT_FAILED: return action.error.message; default: return state; } }; export default search;
communicode-source/communicode
app/reducers/search.js
JavaScript
mit
341
/** * Created by lee on 10/13/17. */ import React, { Component } from 'react'; export default class PlacesItem extends Component { constructor(props) { super(props); this.config = this.config.bind(this); this.rateStars = this.rateStars.bind(this); this.startBounce = this.startBounce.bind(this); this.endBounce = this.endBounce.bind(this); } config() { return { itemPhotoSize : { maxWidth: 80, maxHeight: 91 } } } startBounce() { this.props.place.marker.setAnimation(google.maps.Animation.BOUNCE); } endBounce() { this.props.place.marker.setAnimation(null); } // build rate starts rateStars(num) { let stars = []; for(let i = 0; i < num; i++) { stars.push( <span><img key={i} src='./assets/star.png' /></span> ) } return stars } render() { const {place} = this.props.place; const img = place.photos ? place.photos[0].getUrl(this.config().itemPhotoSize) : './assets/no_image.png'; return( <div className="item-box" onMouseOver = {this.startBounce} onMouseOut={this.endBounce}> <div className="item-text"> <strong>{place.name}</strong> { place.rating ?<p>{this.rateStars(place.rating)}<span>&nbsp;&nbsp;&nbsp;{'$'.repeat(place.price_level)}</span></p> : <p>{'$'.repeat(place.price_level)}</p> } <p id="item-address">{place.formatted_address}</p> <p>{place.opening_hours && place.opening_hours.open_now ? "Open" :"Closed"}</p> </div> <img className='item-image' src={img} /> </div> ) } }
LEEwith/google-map-react
src/components/places_item.js
JavaScript
mit
1,854
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ import path from 'path'; import webpack from 'webpack'; import CopyWebpackPlugin from 'copy-webpack-plugin'; import HtmlWebpackPlugin from 'html-webpack-plugin'; export default { context: __dirname, entry: './index.jsx', output: { path: `${__dirname}/__dev__`, publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader?includePaths[]=' + path.resolve(__dirname, './node_modules/compass-mixins/lib') ]}, ], }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new CopyWebpackPlugin([ { from: '404.html' }, { from: 'img', to: 'img' }, { from: 'fonts', to: 'fonts' } ]), new HtmlWebpackPlugin({ template: 'index.template.ejs', inject: 'body' }), ], };
uofo/reverse-archaeology
webpack.config.babel.js
JavaScript
mit
1,297
"use strict" var o = require("../../ospec/ospec") var callAsync = require("../../test-utils/callAsync") var browserMock = require("../../test-utils/browserMock") var m = require("../../render/hyperscript") var callAsync = require("../../test-utils/callAsync") var coreRenderer = require("../../render/render") var apiRedraw = require("../../api/redraw") var apiRouter = require("../../api/router") var Promise = require("../../promise/promise") o.spec("route", function() { void [{protocol: "http:", hostname: "localhost"}, {protocol: "file:", hostname: "/"}].forEach(function(env) { void ["#", "?", "", "#!", "?!", "/foo"].forEach(function(prefix) { o.spec("using prefix `" + prefix + "` starting on " + env.protocol + "//" + env.hostname, function() { var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, route o.beforeEach(function() { $window = browserMock(env) root = $window.document.body redrawService = apiRedraw($window) route = apiRouter($window, redrawService) route.prefix(prefix) }) o("throws on invalid `root` DOM node", function() { var threw = false try { route(null, '/', {'/':{view: function() {}}}) } catch (e) { threw = true } o(threw).equals(true) }) o("renders into `root`", function() { $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div") } } }) o(root.firstChild.nodeName).equals("DIV") }) o("routed mount points can redraw synchronously (#1275)", function() { var view = o.spy() $window.location.href = prefix + "/" route(root, "/", {"/":{view:view}}) o(view.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) }) o("default route doesn't break back button", function(done) { $window.location.href = "http://old.com" $window.location.href = "http://new.com" route(root, "/a", { "/a" : { view: function() { return m("div") } } }) callAsync(function() { o(root.firstChild.nodeName).equals("DIV") o(route.get()).equals("/a") $window.history.back() o($window.location.pathname).equals("/") o($window.location.hostname).equals("old.com") done() }) }) o("default route does not inherit params", function(done) { $window.location.href = "/invalid?foo=bar" route(root, "/a", { "/a" : { oninit: init, view: function() { return m("div") } } }) function init(vnode) { o(vnode.attrs.foo).equals(undefined) done() } }) o("redraws when render function is executed", function() { var onupdate = o.spy() var oninit = o.spy() $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate }) } } }) o(oninit.callCount).equals(1) redrawService.redraw() o(onupdate.callCount).equals(1) }) o("redraws on events", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: onclick, }) } } }) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) o(onclick.callCount).equals(1) o(onclick.this).equals(root.firstChild) o(onclick.args[0].type).equals("click") o(onclick.args[0].target).equals(root.firstChild) // Wrapped to give time for the rate-limited redraw to fire callAsync(function() { o(onupdate.callCount).equals(1) done() }) }) o("event handlers can skip redraw", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: function(e) { e.redraw = false }, }) } } }) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) // Wrapped to ensure no redraw fired callAsync(function() { o(onupdate.callCount).equals(0) done() }) }) o("changes location on route.link", function() { var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("a", { href: "/test", oncreate: route.link }) } }, "/test" : { view : function() { return m("div") } } }) var slash = prefix[0] === "/" ? "" : "/" o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "")) root.firstChild.dispatchEvent(e) o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test") }) o("accepts RouteResolver with onmatch that returns Component", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Component }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<Component>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve(Component) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<undefined>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve() }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<any>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve([]) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns rejected Promise", function(done) { var matchCount = 0 var renderCount = 0 var spy = o.spy() var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ return Promise.reject(new Error("error")) }, render: function(vnode) { renderCount++ return vnode }, } $window.location.href = prefix + "/test/1" route(root, "/default", { "/default" : {view: spy}, "/test/:id" : resolver }) callAsync(function() { callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(0) o(spy.callCount).equals(1) done() }) }) }) o("accepts RouteResolver without `render` method as payload", function(done) { var matchCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") return Component }, }, }) callAsync(function() { o(matchCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("changing `vnode.key` in `render` resets the component", function(done, timeout){ var oninit = o.spy() var Component = { oninit: oninit, view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id": {render: function(vnode) { return m(Component, {key: vnode.attrs.id}) }} }) callAsync(function() { o(oninit.callCount).equals(1) route.set("/def") callAsync(function() { o(oninit.callCount).equals(2) done() }) }) }) o("accepts RouteResolver without `onmatch` method as payload", function() { var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") return m(Component) }, }, }) o(root.firstChild.nodeName).equals("DIV") }) o("RouteResolver `render` does not have component semantics", function(done) { var renderCount = 0 var A = { view: function() { return m("div") } } $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { render: function(vnode) { return m("div") }, }, "/b" : { render: function(vnode) { return m("div") }, }, }) var dom = root.firstChild o(root.firstChild.nodeName).equals("DIV") route.set("/b") callAsync(function() { o(root.firstChild).equals(dom) done() }) }) o("calls onmatch and view correct number of times", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ return Component }, render: function(vnode) { renderCount++ return vnode }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) redrawService.redraw() o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("calls onmatch and view correct number of times when not onmatch returns undefined", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ }, render: function(vnode) { renderCount++ return {tag: Component} }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) redrawService.redraw() o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("onmatch can redirect to another route", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { view: function() { redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver w/ only onmatch", function(done) { var redirected = false var render = o.spy() var view = o.spy(function() {return m("div")}) $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) o(root.childNodes.length).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) }) o("onmatch can redirect to another route that has RouteResolver w/ only render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { render: function(vnode){ redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver whose onmatch resolves asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { onmatch: function() { redirected = true return new Promise(function(fulfill){ callAsync(function(){ fulfill({view: view}) }) }) } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect to another route asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { callAsync(function() {route.set("/b")}) return new Promise(function() {}) }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect w/ window.history.back()", function(done) { var render = o.spy() var component = {view: o.spy()} $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { return component }, render: function(vnode) { return vnode } }, "/b" : { onmatch: function() { $window.history.back() return new Promise(function() {}) }, render: render } }) callAsync(function() { route.set('/b') callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(component.view.callCount).equals(2) done() }) }) }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ onmatch", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { onmatch: function(vnode){ redirected = true return {view: function() {}} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { render: function(vnode){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a component", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { view: function(vnode){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("the previous view redraws while onmatch resolution is pending (#1268)", function(done) { var view = o.spy() var onmatch = o.spy(function() { return new Promise(function() {}) }) $window.location.href = prefix + "/a" route(root, "/", { "/a": {view: view}, "/b": {onmatch: onmatch} }) o(view.callCount).equals(1) o(onmatch.callCount).equals(0) route.set("/b") callAsync(function() { o(view.callCount).equals(1) o(onmatch.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) o(onmatch.callCount).equals(1) done() }) }) o("when two async routes are racing, the last one set cancels the finalization of the first", function(done) { var renderA = o.spy() var renderB = o.spy() var onmatchA = o.spy(function(){ return new Promise(function(fulfill) { setTimeout(function(){ fulfill() }, 10) }) }) $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: onmatchA, render: renderA }, "/b": { onmatch: function(){ var p = new Promise(function(fulfill) { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) setTimeout(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) fulfill() p.then(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(1) done() }) }, 20) }) return p }, render: renderB } }) callAsync(function() { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) route.set("/b") o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) }) }) o("m.route.set(m.route.get()) re-runs the resolution logic (#1180)", function(done){ var onmatch = o.spy() var render = o.spy(function() {return m("div")}) $window.location.href = prefix + "/" route(root, '/', { "/": { onmatch: onmatch, render: render } }) callAsync(function() { o(onmatch.callCount).equals(1) o(render.callCount).equals(1) route.set(route.get()) callAsync(function() { callAsync(function() { o(onmatch.callCount).equals(2) o(render.callCount).equals(2) done() }) }) }) }) o("m.route.get() returns the last fully resolved route (#1276)", function(done){ $window.location.href = prefix + "/" route(root, "/", { "/": {view: function() {}}, "/2": { onmatch: function() { return new Promise(function() {}) } } }) o(route.get()).equals("/") route.set("/2") callAsync(function() { o(route.get()).equals("/") done() }) }) o("routing with RouteResolver works more than once", function(done) { $window.location.href = prefix + "/a" route(root, '/a', { '/a': { render: function() { return m("a", "a") } }, '/b': { render: function() { return m("b", "b") } } }) route.set('/b') callAsync(function() { route.set('/a') callAsync(function() { o(root.firstChild.nodeName).equals("A") done() }) }) }) o("calling route.set invalidates pending onmatch resolution", function(done) { var rendered = false var resolved $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: function() { return new Promise(function(resolve) { callAsync(function() { callAsync(function() { resolve({view: function() {rendered = true}}) }) }) }) }, render: function(vnode) { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } } }) route.set("/b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) o("route changes activate onbeforeremove", function(done) { var spy = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onbeforeremove: spy, view: function() {} }, "/b": { view: function() {} } }) route.set("/b") callAsync(function() { o(spy.callCount).equals(1) done() }) }) o("asynchronous route.set in onmatch works", function(done) { var rendered = false, resolved route(root, "/a", { "/a": { onmatch: function() { return Promise.resolve().then(function() { route.set("/b") }) }, render: function(vnode) { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } }, }) callAsync(function() { // tick for popstate for /a callAsync(function() { // tick for promise in onmatch callAsync(function() { // tick for onpopstate for /b o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) }) o("throttles", function(done, timeout) { timeout(200) var i = 0 $window.location.href = prefix + "/" route(root, "/", { "/": {view: function(v) {i++}} }) var before = i redrawService.redraw() redrawService.redraw() redrawService.redraw() redrawService.redraw() var after = i setTimeout(function() { o(before).equals(1) // routes synchronously o(after).equals(2) // redraws synchronously o(i).equals(3) // throttles rest done() }, FRAME_BUDGET * 2) }) o("m.route.param is available outside of route handlers", function(done) { $window.location.href = prefix + "/" route(root, "/1", { "/:id" : { view : function() { o(route.param("id")).equals("1") return m("div") } } }) o(route.param("id")).equals(undefined); o(route.param()).deepEquals(undefined); callAsync(function() { o(route.param("id")).equals("1") o(route.param()).deepEquals({id:"1"}) done() }) }) }) }) }) })
jsguy/slides
resource/mithril.js-rewrite/api/tests/test-router.js
JavaScript
mit
26,809
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Math.sqrt, recommended that implementations use the approximation algorithms for IEEE 754 arithmetic contained in fdlibm es5id: 15.8.2.17_A6 description: > Checking if Math.sqrt is approximately equals to its mathematical values on the set of 64 argument values; all the sample values is calculated with LibC includes: - math_precision.js - math_isequal.js ---*/ // CHECK#1 vnum = 64; var x = new Array(); x[0] = 0.00000000000000000000; x[1] = 0.25396825396825395000; x[2] = 0.50793650793650791000; x[3] = 0.76190476190476186000; x[4] = 1.01587301587301580000; x[5] = 1.26984126984126980000; x[6] = 1.52380952380952370000; x[7] = 1.77777777777777770000; x[8] = 2.03174603174603160000; x[9] = 2.28571428571428560000; x[10] = 2.53968253968253950000; x[11] = 2.79365079365079350000; x[12] = 3.04761904761904740000; x[13] = 3.30158730158730140000; x[14] = 3.55555555555555540000; x[15] = 3.80952380952380930000; x[16] = 4.06349206349206330000; x[17] = 4.31746031746031720000; x[18] = 4.57142857142857120000; x[19] = 4.82539682539682510000; x[20] = 5.07936507936507910000; x[21] = 5.33333333333333300000; x[22] = 5.58730158730158700000; x[23] = 5.84126984126984090000; x[24] = 6.09523809523809490000; x[25] = 6.34920634920634890000; x[26] = 6.60317460317460280000; x[27] = 6.85714285714285680000; x[28] = 7.11111111111111070000; x[29] = 7.36507936507936470000; x[30] = 7.61904761904761860000; x[31] = 7.87301587301587260000; x[32] = 8.12698412698412650000; x[33] = 8.38095238095238140000; x[34] = 8.63492063492063440000; x[35] = 8.88888888888888930000; x[36] = 9.14285714285714230000; x[37] = 9.39682539682539720000; x[38] = 9.65079365079365030000; x[39] = 9.90476190476190510000; x[40] = 10.15873015873015800000; x[41] = 10.41269841269841300000; x[42] = 10.66666666666666600000; x[43] = 10.92063492063492100000; x[44] = 11.17460317460317400000; x[45] = 11.42857142857142900000; x[46] = 11.68253968253968200000; x[47] = 11.93650793650793700000; x[48] = 12.19047619047619000000; x[49] = 12.44444444444444500000; x[50] = 12.69841269841269800000; x[51] = 12.95238095238095300000; x[52] = 13.20634920634920600000; x[53] = 13.46031746031746000000; x[54] = 13.71428571428571400000; x[55] = 13.96825396825396800000; x[56] = 14.22222222222222100000; x[57] = 14.47619047619047600000; x[58] = 14.73015873015872900000; x[59] = 14.98412698412698400000; x[60] = 15.23809523809523700000; x[61] = 15.49206349206349200000; x[62] = 15.74603174603174500000; x[63] = 16.00000000000000000000; var y = new Array(); y[0] = 0.00000000000000000000; y[1] = 0.50395263067896967000; y[2] = 0.71269664509979835000; y[3] = 0.87287156094396945000; y[4] = 1.00790526135793930000; y[5] = 1.12687233963802200000; y[6] = 1.23442679969673530000; y[7] = 1.33333333333333330000; y[8] = 1.42539329019959670000; y[9] = 1.51185789203690880000; y[10] = 1.59363814577919150000; y[11] = 1.67142178807468980000; y[12] = 1.74574312188793890000; y[13] = 1.81702705031799170000; y[14] = 1.88561808316412670000; y[15] = 1.95180014589706640000; y[16] = 2.01581052271587870000; y[17] = 2.07784992659727900000; y[18] = 2.13808993529939520000; y[19] = 2.19667858946110380000; y[20] = 2.25374467927604400000; y[21] = 2.30940107675850290000; y[22] = 2.36374736114111530000; y[23] = 2.41687191246657520000; y[24] = 2.46885359939347060000; y[25] = 2.51976315339484810000; y[26] = 2.56966429775848400000; y[27] = 2.61861468283190830000; y[28] = 2.66666666666666650000; y[29] = 2.71386797119523940000; y[30] = 2.76026223736941700000; y[31] = 2.80588949764880670000; y[32] = 2.85078658039919340000; y[33] = 2.89498745782298350000; y[34] = 2.93852354676981160000; y[35] = 2.98142396999971960000; y[36] = 3.02371578407381760000; y[37] = 3.06542417893925380000; y[38] = 3.10657265339049320000; y[39] = 3.14718316987777280000; y[40] = 3.18727629155838300000; y[41] = 3.22687130401855570000; y[42] = 3.26598632371090410000; y[43] = 3.30463839483761390000; y[44] = 3.34284357614937950000; y[45] = 3.38061701891406630000; y[46] = 3.41797303712883060000; y[47] = 3.45492517089848670000; y[48] = 3.49148624377587780000; y[49] = 3.52766841475278750000; y[50] = 3.56348322549899170000; y[51] = 3.59894164336974940000; y[52] = 3.63405410063598340000; y[53] = 3.66883053033489940000; y[54] = 3.70328039909020570000; y[55] = 3.73741273720925400000; y[56] = 3.77123616632825340000; y[57] = 3.80475892484536750000; y[58] = 3.83798889135426350000; y[59] = 3.87093360626696680000; y[60] = 3.90360029179413280000; y[61] = 3.93599587043272870000; y[62] = 3.96812698209517300000; y[63] = 4.00000000000000000000; var val; for (i = 0; i < vnum; i++) { val = Math.sqrt(x[i]); if (!isEqual(val, y[i])) { $ERROR("\nx = " + x[i] + "\nlibc.sqrt(x) = " + y[i] + "\nMath.sqrt(x) = " + Math.sqrt(x[i]) + "\nMath.abs(libc.sqrt(x) - Math.sqrt(x)) > " + prec + "\n\n"); } }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Math/sqrt/S15.8.2.17_A6.js
JavaScript
mit
4,964
import http from "http"; import express from "express"; import cors from "cors"; import morgan from "morgan"; import bodyParser from "body-parser"; import initializeDb from "./db"; import middleware from "./middleware"; import api from "./api"; import config from "config"; //we load the db location from the JSON files let app = express(); app.server = http.createServer(app); //don't show the log when it is test if (process.env.NODE_ENV !== "test") { // logger app.use(morgan("dev")); } // 3rd party middleware app.use( cors({ exposedHeaders: config.corsHeaders }) ); app.use( bodyParser.json({ limit: config.bodyLimit }) ); const dbOptions = { useMongoClient: true }; // connect to db initializeDb(config.dbURI, dbOptions, () => { // internal middleware app.use(middleware({ config })); // api router app.use("/api", api({ config })); app.server.listen(process.env.PORT || config.port, () => { console.log(`Started on port ${app.server.address().port}`); }); }); export default app;
Hackstr/my-express-boilerplate
src/index.js
JavaScript
mit
1,034
'use strict'; var gulp = require('gulp'); var autoprefixer = require('jstransformer')(require('jstransformer-stylus')); var autoprefixer = require('autoprefixer-stylus'); var browserSync = require('browser-sync').create(); var changed = require('gulp-changed'); var concat = require('gulp-concat'); var cssbeautify = require('gulp-cssbeautify'); var csscomb = require('gulp-csscomb'); var csso = require('gulp-csso'); var data = require('gulp-data'); var del = require('del'); var filter = require('gulp-filter'); var flatten = require('gulp-flatten'); var gulpZip = require('gulp-zip'); var gulpif = require('gulp-if'); var gutil = require('gulp-util'); var htmlPrettify = require('gulp-prettify'); var imagemin = require('gulp-imagemin'); var imageminPngquant = require('imagemin-pngquant'); var imageminSvgo = require('imagemin-svgo'); var include = require('gulp-include'); var jade = require('gulp-jade'); var jadeInheritance = require('gulp-jade-inheritance'); var path = require('path'); var plumber = require('gulp-plumber'); var rename = require('gulp-rename'); var runSequence = require('run-sequence'); var rupture = require('rupture'); var stylus = require('gulp-stylus'); var svgSymbols = require('gulp-svg-symbols'); var uglify = require('gulp-uglify'); var watch = require('gulp-watch'); var gcmq = require('gulp-combine-mq'); // Error handler for gulp-plumber var errorHandler = function (err) { gutil.log([(err.name + ' in ' + err.plugin).bold.red, '', err.message, ''].join('\n')); if (gutil.env.beep) { gutil.beep(); } this.emit('end'); }; // Print object in console var debugObj = function (obj) { var util = require('util'); console.log(util.inspect(obj, {showHidden: false, depth: null})); }; // Read file and return object var getData = function getData (file) { var dataEntry; var data; var dataTmp; var fs = require('fs'); try { dataEntry = fs.readFileSync(file, 'utf8'); } catch (er) { dataEntry = false; } dataTmp = '{' + dataEntry + '}'; if (dataEntry) { // eval('data = {' + dataEntry + '}'); data = JSON.parse(dataTmp); } else { data = '{}'; } return data; }; var correctNumber = function correctNumber(number) { return number < 10 ? '0' + number : number; }; // Return timestamp var getDateTime = function getDateTime() { var now = new Date(); var year = now.getFullYear(); var month = correctNumber(now.getMonth() + 1); var day = correctNumber(now.getDate()); var hours = correctNumber(now.getHours()); var minutes = correctNumber(now.getMinutes()); return year + '-' + month + '-' + day + '-' + hours + minutes; }; // Plugins options var options = { del: [ 'dest', 'tmp' ], plumber: { errorHandler: errorHandler }, browserSync: { server: { baseDir: './dest' } }, stylus: { use: [ rupture(), autoprefixer({ browsers: ['last 2 version', '> 1%', 'safari 5', 'ie 8', 'ie 7', 'opera 12.1', 'ios 6', 'android 4'], cascade: false }) ] }, cssbeautify: { indent: '\t', autosemicolon: true }, jade: { pretty: '\t' }, htmlPrettify: { "unformatted": ["pre", "code"], "indent_with_tabs": true, "preserve_newlines": true, "brace_style": "expand", "end_with_newline": true }, svgSymbols: { title: false, id: '%f', className: '%f', templates: [ path.join(__dirname, 'source/static/styles/components/icons-template.styl'), 'default-svg' ] }, imagemin: { optimizationLevel: 3, progressive: true, interlaced: true, svgoPlugins: [{removeViewBox: false}], use: [ imageminPngquant(), imageminSvgo() ] } }; gulp.task('cleanup', function (cb) { return del(options.del, cb); }); gulp.task('browser-sync', function() { return browserSync.init(options.browserSync); }); gulp.task('bs-reload', function (cb) { browserSync.reload(); }); gulp.task('combine-modules-styles', function (cb) { return gulp.src(['**/*.styl', '!**/_*.styl'], {cwd: 'source/modules'}) .pipe(plumber(options.plumber)) .pipe(concat('modules.styl')) .pipe(gulp.dest('tmp')); }); gulp.task('compile-styles', function (cb) { return gulp.src(['*.styl', '!_*.styl'], {cwd: 'source/static/styles'}) .pipe(plumber(options.plumber)) .pipe(stylus(options.stylus)) .pipe(gcmq({beautify: false})) .pipe(cssbeautify(options.cssbeautify)) .pipe(csscomb()) .pipe(gulp.dest('dest/css')) .pipe(csso()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dest/css')) .pipe(browserSync.stream()); }); gulp.task('combine-modules-data', function (cb) { return gulp.src(['**/*.js', '!**/_*.js'], {cwd: 'source/modules/*/data'}) .pipe(plumber(options.plumber)) .pipe(concat('data.js', { newLine: ',\n\n' })) .pipe(gulp.dest('tmp')); }); gulp.task('compile-pages', function (cb) { return gulp.src(['**/*.jade', '!**/_*.jade'], {cwd: 'source/pages'}) .pipe(plumber(options.plumber)) .pipe(data(getData('tmp/data.js'))) .pipe(jade(options.jade)) .pipe(htmlPrettify(options.htmlPrettify)) .pipe(gulp.dest('dest')); }); gulp.task('copy-modules-img', function (cb) { return gulp.src('**/*.{jpg,gif,svg,png}', {cwd: 'source/modules/*/assets'}) .pipe(plumber(options.plumber)) .pipe(changed('dest/img')) .pipe(imagemin(options.imagemin)) .pipe(flatten()) .pipe(gulp.dest('dest/img')); }); gulp.task('combine-modules-scripts', function (cb) { return gulp.src(['*.js', '!_*.js'], {cwd: 'source/modules/*'}) .pipe(plumber(options.plumber)) .pipe(concat('modules.js', { newLine: '\n\n' })) .pipe(gulp.dest('tmp')); }); gulp.task('copy-assets', function (cb) { var imageFilter = filter('**/*.{jpg,gif,svg,png}', {restore: true}); var scriptsFilter = filter(['**/*.js', '!**/*.min.js'], {restore: true}); var stylesFilter = filter(['**/*.css', '!**/*.min.css'], {restore: true}); return gulp.src(['**/*.*', '!**/_*.*'], {cwd: 'source/static/assets'}) .pipe(plumber(options.plumber)) .pipe(changed('dest')) // Minify images .pipe(imageFilter) .pipe(changed('dest')) .pipe(imagemin(options.imagemin)) .pipe(imageFilter.restore) // Minify JavaScript files .pipe(scriptsFilter) .pipe(gulp.dest('dest')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(scriptsFilter.restore) // Minify css .pipe(stylesFilter) .pipe(csso()) .pipe(rename({suffix: '.min'})) .pipe(stylesFilter.restore) // Copy other files .pipe(gulp.dest('dest')); }); gulp.task('combine-scripts', function (cb) { return gulp.src(['*.js', '!_*.js'], {cwd: 'source/static/scripts'}) .pipe(plumber(options.plumber)) .pipe(include()) .pipe(gulp.dest('dest/js')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dest/js')); }); gulp.task('combine-svg-icons', function (cb) { return gulp.src(['**/*.svg', '!**/_*.svg'], {cwd: 'source/static/icons'}) .pipe(plumber(options.plumber)) .pipe(imagemin(options.imagemin)) .pipe(svgSymbols(options.svgSymbols)) .pipe(gulpif(/\.styl$/, gulp.dest('tmp'))) .pipe(gulpif(/\.svg$/, rename('icons.svg'))) .pipe(gulpif(/\.svg$/, gulp.dest('dest/img'))); }); gulp.task('build-zip', function() { var datetime = '-' + getDateTime(); var zipName = 'dist' + datetime + '.zip'; return gulp.src('dest/**/*') .pipe(gulpZip(zipName)) .pipe(gulp.dest('zip')); }); gulp.task('build-html', function (cb) { return runSequence( 'combine-modules-data', 'compile-pages', cb ); }); gulp.task('build-css', function (cb) { return runSequence( 'combine-modules-styles', 'compile-styles', cb ); }); gulp.task('build-js', function (cb) { return runSequence( 'combine-modules-scripts', 'combine-scripts', cb ); }); gulp.task('build', function (cb) { return runSequence( 'cleanup', 'combine-svg-icons', [ 'build-html', 'copy-modules-img', 'copy-assets', 'build-css', 'build-js' ], cb ); }); gulp.task('zip', function (cb) { return runSequence( 'build', 'build-zip', cb ); }); gulp.task('develop', function (cb) { return runSequence( 'build', 'browser-sync', cb ); }); gulp.task('dev', ['develop'], function (cb) { // Modules, pages watch('source/**/*.jade', function() { return runSequence('compile-pages', browserSync.reload); }); // Modules data watch('source/modules/*/data/*.js', function() { return runSequence('build-html', browserSync.reload); }); // Static styles watch('source/static/styles/**/*.styl', function() { // return runSequence('compile-styles'); gulp.start('compile-styles'); }); // Modules styles watch('source/modules/**/*.styl', function() { // return runSequence('build-css'); gulp.start('build-css'); }); // Static scripts watch('source/static/scripts/**/*.js', function() { return runSequence('combine-scripts', browserSync.reload); }); // Modules scripts watch('source/modules/*/*.js', function() { return runSequence('build-js', browserSync.reload); }); // Modules images watch('source/modules/*/assets/**/*.{jpg,gif,svg,png}', function() { return runSequence('copy-modules-img', browserSync.reload); }); // Static files watch('source/static/assets/**/*', function() { return runSequence('copy-assets', browserSync.reload); }); // Svg icons watch('source/static/icons/**/*.svg', function() { return runSequence('combine-svg-icons', browserSync.reload); }); });
cloud00/fast-front
gulpfile.js
JavaScript
mit
9,271
import Ember from 'ember'; import PaginatedScrollViewMixin from 'kowa/mixins/paginated-scroll-view'; var PaginatedScrollBox = Ember.View.extend(PaginatedScrollViewMixin); export default PaginatedScrollBox;
aymerick/kowa-client
app/views/paginated-scroll-box.js
JavaScript
mit
208
import clearSuggestedActions from './actions/clearSuggestedActions'; import connect from './actions/connect'; import createStore, { withDevTools as createStoreWithDevTools } from './createStore'; import disconnect from './actions/disconnect'; import dismissNotification from './actions/dismissNotification'; import emitTypingIndicator from './actions/emitTypingIndicator'; import markActivity from './actions/markActivity'; import postActivity from './actions/postActivity'; import sendEvent from './actions/sendEvent'; import sendFiles from './actions/sendFiles'; import sendMessage from './actions/sendMessage'; import sendMessageBack from './actions/sendMessageBack'; import sendPostBack from './actions/sendPostBack'; import setDictateInterims from './actions/setDictateInterims'; import setDictateState from './actions/setDictateState'; import setLanguage from './actions/setLanguage'; import setNotification from './actions/setNotification'; import setSendBox from './actions/setSendBox'; import setSendTimeout from './actions/setSendTimeout'; import setSendTypingIndicator from './actions/setSendTypingIndicator'; import startDictate from './actions/startDictate'; import startSpeakingActivity from './actions/startSpeakingActivity'; import stopDictate from './actions/stopDictate'; import stopSpeakingActivity from './actions/stopSpeakingActivity'; import submitSendBox from './actions/submitSendBox'; import * as ActivityClientState from './constants/ActivityClientState'; import * as DictateState from './constants/DictateState'; const Constants = { ActivityClientState, DictateState }; const version = process.env.npm_package_version; export { clearSuggestedActions, connect, Constants, createStore, createStoreWithDevTools, disconnect, dismissNotification, emitTypingIndicator, markActivity, postActivity, sendEvent, sendFiles, sendMessage, sendMessageBack, sendPostBack, setDictateInterims, setDictateState, setLanguage, setNotification, setSendBox, setSendTimeout, setSendTypingIndicator, startDictate, startSpeakingActivity, stopDictate, stopSpeakingActivity, submitSendBox, version };
billba/botchat
packages/core/src/index.js
JavaScript
mit
2,160
var assert = require('assert'); var listXf = require('./helpers/listXf'); var R = require('..'); describe('any', function() { var odd = function(n) {return n % 2 === 1;}; var T = function() {return true;}; var intoArray = R.into([]); it('returns true if any element satisfies the predicate', function() { assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 11, 12]), true); }); it('returns false if all elements fails to satisfy the predicate', function() { assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 12]), false); }); it('returns true into array if any element satisfies the predicate', function() { assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 11, 12]), [true]); }); it('returns false if all elements fails to satisfy the predicate', function() { assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 12]), [false]); }); it('works with more complex objects', function() { var people = [{first: 'Paul', last: 'Grenier'}, {first:'Mike', last: 'Hurley'}, {first: 'Will', last: 'Klein'}]; var alliterative = function(person) {return person.first.charAt(0) === person.last.charAt(0);}; assert.strictEqual(R.any(alliterative, people), false); people.push({first: 'Scott', last: 'Sauyet'}); assert.strictEqual(R.any(alliterative, people), true); }); it('can use a configurable function', function() { var teens = [{name: 'Alice', age: 14}, {name: 'Betty', age: 18}, {name: 'Cindy', age: 17}]; var atLeast = function(age) {return function(person) {return person.age >= age;};}; assert.strictEqual(R.any(atLeast(16), teens), true, 'Some can legally drive'); assert.strictEqual(R.any(atLeast(21), teens), false, 'None can legally drink'); }); it('returns false for an empty list', function() { assert.strictEqual(R.any(T, []), false); }); it('returns false into array for an empty list', function() { assert.deepEqual(intoArray(R.any(T), []), [false]); }); it('dispatches when given a transformer in list position', function() { assert.deepEqual(R.any(odd, listXf), { any: false, f: odd, xf: listXf }); }); it('is automatically curried', function() { var count = 0; var test = function(n) {count++; return odd(n);}; assert(R.any(test)([2, 4, 6, 7, 8, 10]) === true); }); });
megawac/ramda
test/any.js
JavaScript
mit
2,480
module.exports = function (options, suite, test, expect, teardown) { require('./integration.expressions')(options, suite, test, expect, teardown); suite('tribe.storage.integration.' + options.type, function () { var storage = require('tribe.storage'), db; test("basic store and retrieve", function () { return open(['p1', 'p2'], [ { p1: 1, p2: 'test' }, { p1: 2, p2: 'test2' } ]) .then(function (container) { return container.retrieve({ p: 'p1', v: 1 }); }) .then(function (rows) { expect(rows.length).to.equal(1); expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' }); }); }); test("multiple key index store and retrieve", function () { return open([['p1', 'p2']], [ { p1: 'test', p2: 1 }, { p1: 'test', p2: 2 }, { p1: 'test', p2: 3 }, { p1: 'test2', p2: 2 }, ]) .then(function (container) { return container.retrieve([{ p: 'p1', v: 'test' }, { p: 'p2', o: '>=', v: 2 }]); }) .then(function (rows) { expect(rows.length).to.equal(2); }); }); // this was originally done by sorting the index. this won't work with indexeddb as order is significant // we can store some metadata about index order and apply expression components in the correct order. todo. //test("multiple key order does not need to match expression order", function () { // return open([['p1', 'p2']], [{ p1: 'test', p2: 1 }]) // .then(function (container) { // return container.retrieve([{ p: 'p2', v: 1 }, { p: 'p1', v: 'test' }]); // }) // .then(function (rows) { // expect(rows.length).to.equal(1); // }); //}); test("complex object store and retrieve", function () { return open([['p1.p2', 'p3']], [ { p1: { p2: 'test' }, p3: 1 }, { p1: { p2: 'test' }, p3: 1 }, { p1: { p2: 'test2' }, p3: 1 } ]) .then(function (container) { return container.retrieve([{ p: 'p1.p2', v: 'test' }, { p: 'p3', v: 1 }]); }) .then(function (rows) { expect(rows.length).to.equal(2); }); }); test("keyPath can be queried when autoIncrement is set", function () { return open([], [ { p2: 'test' }, { p2: 'test2' } ], 'p1', true) .then(function (container) { return container.retrieve({ p: 'p1', v: 1 }); }) .then(function (rows) { expect(rows.length).to.equal(1); expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' }); }); }); test("keyPath can be queried when autoIncrement is not set", function () { return open([], [ { p1: 3, p2: 'test' }, { p1: 4, p2: 'test2' } ], 'p1', false) .then(function (container) { return container.retrieve({ p: 'p1', v: 3 }); }) .then(function (rows) { expect(rows.length).to.equal(1); expect(rows[0]).to.deep.equal({ p1: 3, p2: 'test' }); }); }); test("keyPath can be queried with indexes", function () { return open(['p2'], [ { p1: 1, p2: 'test' }, { p1: 2, p2: 'test2' } ], 'p1') .then(function (container) { return container.retrieve([{ p: 'p1', v: 1 }, { p: 'p2', v: 'test' }]); }) .then(function (rows) { expect(rows.length).to.equal(1); expect(rows[0]).to.deep.equal({ p1: 1, p2: 'test' }); }); }); test("store operation returns entity with autoIncrement keyPath property set", function () { return open([], [], 'id', true) .then(function (container) { return container.store({}); }) .then(function (updatedEntity) { expect(updatedEntity).to.deep.equal({ id: 1 }); }); }); test("multiple store operation returns entities with autoIncrement keyPath property set", function () { return open([], [], 'id', true) .then(function (container) { return container.store([{}, {}]); }) .then(function (updatedEntity) { expect(updatedEntity).to.deep.equal([{ id: 1 }, { id: 2 }]); }); }); test("stored entity has autoIncrement keyPath property set", function () { var container; return open([], [], 'id', true) .then(function (db) { container = db; return container.store({}); }) .then(function () { return container.retrieve({ p: 'id', v: 1 }); }) .then(function (entities) { expect(entities.length).to.equal(1); expect(entities[0]).to.deep.equal({ id: 1 }); }); }); test("store operation replaces entities with matching keys", function () { var entity; return open([], [{ p1: 1, p2: 'test' }], 'p1') .then(function (provider) { entity = provider; return entity.store({ p1: 1, p2: 'test2' }); }) .then(function () { return entity.retrieve({ p: 'p1', v: 1 }); }) .then(function (entities) { expect(entities.length).to.equal(1); expect(entities[0].p2).to.equal('test2'); }); }); test("single property indexes can be specified and requested as arrays or individually", function () { var container; return open(['p1', ['p2']], [ { p1: 1, p2: 1 }, { p1: 2, p2: 2 } ]) .then(function (result) { container = result; return container.retrieve({ p: 'p1', v: 2 }); }) .then(function (results) { expect(results.length).to.equal(1); }) .then(function (result) { return container.retrieve([{ p: 'p1', v: 2 }]); }) .then(function (results) { expect(results.length).to.equal(1); }) .then(function (result) { return container.retrieve({ p: 'p2', v: 2 }); }) .then(function (results) { expect(results.length).to.equal(1); }) .then(function (result) { return container.retrieve([{ p: 'p2', v: 2 }]); }) .then(function (results) { expect(results.length).to.equal(1); }); }); test("retrieve sorts by index properties", function () { var container; return open([['p1', 'p2.value'], ['p2.value', 'p1']], [ { p1: 4, p2: { value: 1 } }, { p1: 3, p2: { value: 2 } }, { p1: 1, p2: { value: 1 } }, { p1: 2, p2: { value: 2 } } ]) .then(function (result) { container = result; return container.retrieve([{ p: 'p1', o: '>', v: 0 }, { p: 'p2.value', o: '>', v: 0 }]); }) .then(function (results) { expect(results).to.deep.equal([ { p1: 1, p2: { value: 1 } }, { p1: 2, p2: { value: 2 } }, { p1: 3, p2: { value: 2 } }, { p1: 4, p2: { value: 1 } } ]); return container.retrieve([{ p: 'p2.value', o: '>', v: 0 }, { p: 'p1', o: '>', v: 0 }]); }) .then(function (results) { expect(results).to.deep.equal([ { p1: 1, p2: { value: 1 } }, { p1: 4, p2: { value: 1 } }, { p1: 2, p2: { value: 2 } }, { p1: 3, p2: { value: 2 } } ]); }); }); test("clear deletes all entities", function () { var container; return open(['p1'], [{ p1: 1, p2: 1 }]) .then(function (result) { container = result; container.clear(); }) .then(function () { return container.retrieve({ p: 'p1', v: 1 }); }) .then(function (messages) { expect(messages.length).to.equal(0); }); }); function open(indexes, entities, keyPath, autoIncrement) { var entity; return storage.open([{ name: 'test', indexes: indexes, keyPath: keyPath, autoIncrement: autoIncrement }], options) .then(function (provider) { db = provider; entity = provider.entity('test'); return entity.store(entities); }) .then(function () { return entity; }); } teardown(function () { db.close(); }); }); };
danderson00/tribe.storage
tests/integration.js
JavaScript
mit
10,388
"use strict"; var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.alts = alts; exports.timeout = timeout; exports.pipelineAsync = pipelineAsync; // Enforces order resolution on resulting channel // This might need to be the default behavior, though that requires more thought exports.order = order; Object.defineProperty(exports, "__esModule", { value: true }); var _channelsJs = require("./channels.js"); var Channel = _channelsJs.Channel; var Transactor = _channelsJs.Transactor; var AltsTransactor = (function (_Transactor) { function AltsTransactor(offer, commitCb) { _classCallCheck(this, AltsTransactor); _get(Object.getPrototypeOf(AltsTransactor.prototype), "constructor", this).call(this, offer); this.commitCb = commitCb; } _inherits(AltsTransactor, _Transactor); _createClass(AltsTransactor, { commit: { value: function commit() { this.commitCb(); return _get(Object.getPrototypeOf(AltsTransactor.prototype), "commit", this).call(this); } } }); return AltsTransactor; })(Transactor); function alts(race) { var outCh = new Channel(); var transactors = race.map(function (cmd) { var tx = undefined; if (Array.isArray(cmd)) { var _cmd; (function () { _cmd = _slicedToArray(cmd, 2); var ch = _cmd[0]; var val = _cmd[1]; tx = new AltsTransactor(val, function () { transactors.forEach(function (h) { return h.active = false; }); }); ch.fill(val, tx).deref(function () { outCh.fill([val, ch]).deref(function () { return outCh.close(); }); }); })(); } else { tx = new AltsTransactor(true, function () { transactors.forEach(function (h) { return h.active = false; }); }); cmd.drain(tx).deref(function (val) { outCh.fill([val, cmd]).deref(function () { return outCh.close(); }); }); } return tx; }); return outCh; } function timeout(ms) { var ch = new Channel(); setTimeout(function () { ch.close(); }, ms); return ch; } function pipelineAsync(inch, converter, outch) { var shouldCloseDownstream = arguments[3] === undefined ? false : arguments[3]; function take(val) { if (val !== null) { Promise.resolve(converter(val)).then(function (converted) { outch.put(converted).then(function (didPut) { if (didPut) { inch.take().then(take); } }); }); } else if (shouldCloseDownstream) { outch.close(); } } inch.take().then(take); } function order(inch, sizeOrBuf) { var outch = new Channel(sizeOrBuf); function drain() { inch.take().then(function (val) { if (val === null) { outch.close(); } else { outch.put(val).then(drain); } }); } drain(); return outch; } //# sourceMappingURL=utils.js.map
nhusher/js-channels
dist/node/utils.js
JavaScript
mit
4,823
const mutations = { SET_ACTIVE_TAB(state, tab){ state.activeTab = tab; }, SET_DATA_ACTIVE_TAB(state, tab){ state.hubActiveTab = tab; }, SET_PROXY_STATE(state, proxy){ state.proxy_switch = proxy; }, SET_INIT_INFO(state, info){ _.extend(state, info); } }; export default mutations;
NSFA/ysfplatform
src/store/mutations.js
JavaScript
mit
313
// home page exports.index = function(req, res){ res.render('index', { title: 'B O X L A N D' }); };
Thomas-Elder/bo-xy
server/controllers/indexController.js
JavaScript
mit
102
'use strict'; /** * Module dependencies. */ var express = require('express'), mean = require('meanio'), consolidate = require('consolidate'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), helpers = require('view-helpers'), config = require('./config'), expressValidator = require('express-validator'), appPath = process.cwd(), fs = require('fs'), assetmanager = require('assetmanager'); module.exports = function(app, passport, db) { app.set('showStackError', true); // Prettify HTML app.locals.pretty = true; // cache=memory or swig dies in NODE_ENV=production app.locals.cache = 'memory'; // Should be placed before express.static // To ensure that all assets and data are compressed (utilize bandwidth) app.use(express.compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, // Levels are specified in a range of 0 to 9, where-as 0 is // no compression and 9 is best compression, but slowest level: 9 })); // Only use logger for development environment if (process.env.NODE_ENV === 'development') { app.use(express.logger('dev')); } // assign the template engine to .html files app.engine('html', consolidate[config.templateEngine]); // set .html as the default extension app.set('view engine', 'html'); // Set views path, template engine and default layout app.set('views', config.root + '/server/views'); // Enable jsonp app.enable('jsonp callback'); app.configure(function() { // The cookieParser should be above session app.use(express.cookieParser()); // Request body parsing middleware should be above methodOverride app.use(express.urlencoded()); app.use(express.json()); app.use(expressValidator()); app.use(express.methodOverride()); // Import your asset file var assets = require('./assets.json'); assetmanager.init({ js: assets.js, css: assets.css, debug: (process.env.NODE_ENV !== 'production'), webroot: 'public/public' }); // Add assets to local variables app.use(function(req, res, next) { res.locals({ assets: assetmanager.assets }); next(); }); // Express/Mongo session storage app.use(express.session({ secret: config.sessionSecret, store: new mongoStore({ db: db.connection.db, collection: config.sessionCollection }) })); // Dynamic helpers app.use(helpers(config.app.name)); // Use passport session app.use(passport.initialize()); app.use(passport.session()); //mean middleware from modules before routes app.use(mean.chainware.before); // Connect flash for flash messages app.use(flash()); // Routes should be at the last app.use(app.router); // Setting the fav icon and static folder app.use(express.favicon()); app.use('/public', express.static(config.root + '/public')); app.get('/modules/aggregated.js', function(req, res) { res.setHeader('content-type', 'text/javascript'); res.send(mean.aggregated.js); }); app.get('/modules/aggregated.css', function(req, res) { res.setHeader('content-type', 'text/css'); res.send(mean.aggregated.css); }); mean.events.on('modulesFound', function() { mean.modules.forEach(function(module) { app.use('/' + module.name, express.static(config.root + '/node_modules/' + module.name + '/public')); }); bootstrapRoutes(); //mean middlware from modules after routes app.use(mean.chainware.after); // Assume "not found" in the error msgs is a 404. this is somewhat // silly, but valid, you can do whatever you like, set properties, // use instanceof etc. app.use(function(err, req, res, next) { // Treat as 404 if (~err.message.indexOf('not found')) return next(); // Log it console.error(err.stack); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }); }); }); }); function bootstrapRoutes() { var routes_path = appPath + '/server/routes'; var walk = function(path) { fs.readdirSync(path).forEach(function(file) { var newPath = path + '/' + file; var stat = fs.statSync(newPath); if (stat.isFile()) { if (/(.*)\.(js$|coffee$)/.test(file)) { require(newPath)(app, passport); } // We skip the app/routes/middlewares directory as it is meant to be // used and shared by routes as further middlewares and is not a // route by itself } else if (stat.isDirectory() && file !== 'middlewares') { walk(newPath); } }); }; walk(routes_path); } };
tmcelreath/meanCity
server/config/express.js
JavaScript
mit
5,758
// ReplProbe.js (c) 2010-2013 Loren West and other contributors // May be freely distributed under the MIT license. // For further details and documentation: // http://lorenwest.github.com/monitor-min (function(root){ // Module loading - this runs server-side only var Monitor = root.Monitor || require('../Monitor'), _ = Monitor._, Probe = Monitor.Probe, REPL = require('repl'), Stream = require('stream'), util = require('util'), events = require('events'), ChildProcess = require('child_process'); // Statics var CONSOLE_PROMPT = '> '; var NEW_REPL = (typeof REPL.disableColors === 'undefined'); /** * A probe based Read-Execute-Print-Loop console for node.js processes * * @class ReplProbe * @extends Probe * @constructor * @param initParams {Object} Probe initialization parameters * @param initParams.uniqueInstance - Usually specified to obtain a unique REPL probe instance * @param model {Object} Monitor data model elements * @param model.output {String} Last (current) REPL output line * @param model.sequence {Integer} Increasing sequence number - to enforce unique line output */ var ReplProbe = Monitor.ReplProbe = Probe.extend({ probeClass: 'Repl', description: 'A socket.io based Read-Execute-Print-Loop console for node.js processes.', defaults: { // This assures output events are sent, even if the // data is the same as the prior output. sequence: 0, output: '' }, initialize: function(attributes, options){ var t = this; Probe.prototype.initialize.apply(t, arguments); // Don't send change events before connected process.nextTick(function(){ t.stream = new ReplStream(t); if (NEW_REPL) { t.repl = require('repl').start({ prompt: CONSOLE_PROMPT, input: t.stream, output: t.stream }); } else { t.repl = REPL.start(CONSOLE_PROMPT, t.stream); } t.htmlConsole = new HtmlConsole(t); t.shellCmd = null; t.repl.context.console = t.htmlConsole; }); }, /** * Send output to the terminal * * This forces the change event even if the last output is the same * as this output. * * @protected * @method output * @param str {String} String to output to the repl console */ _output: function(str) { var t = this; t.set({ output: str, sequence: t.get('sequence') + 1 }); }, /** * Release any resources consumed by this probe. * * Stop the REPL console. Consoles live 1-1 with a UI counterpart, so stop * requests exit the underlying repl console. If the probe is re-started it * will get a new repl stream and console. * * @method release */ release: function(){ var t = this; t.stream = null; t.repl = null; }, /** * Process an autocomplete request from the client * * @method autocomplete * @param {Object} params Named parameters * @param {Function(error, returnParams)} callback Callback function */ autocomplete_control: function(params, callback) { var t = this; if (typeof(params) !== 'string' || params.length < 1) { callback("Autocomplete paramter must be a nonzero string"); } // Forward to the completion mechanism if it can be completed if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) { t.repl.complete(params, callback); } else { // Return a no-op autocomplete callback(null, [[],'']); } }, /** * Handle user input from the console line * * @method input * @param {Object} params Named parameters * @param {Function(error, returnParams)} callback Callback function */ input_control: function(params, callback) { var t = this; if (params === '.break' && t.shellCmd) { t.shellCmd.kill(); } if (NEW_REPL) { t.stream.emit('data', params + "\n"); } else { t.stream.emit('data', params); } return callback(null); }, /** * Execute a shell command * * @method sh * @param {Object} params Named parameters * @param {Function(error, returnParams)} callback Callback function */ sh_control: function(params, callback) { var t = this; return callback(null, t._runShellCmd(params)); }, /** * Run a shell command and emit the output to the browser. * * @private * @method _runShellCmd * @param {String} command - The shell command to invoke */ _runShellCmd: function(command) { var t = this; t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) { if (err) { var outstr = 'exit'; if (err.code) { outstr += ' (' + err.code + ')'; } if (err.signal) { outstr += ' ' + err.signal; } t._output(outstr); return null; } if (stdout.length) { t._output(stdout); } if (stderr.length) { t._output(stderr); } t.shellCmd = null; t._output(CONSOLE_PROMPT); }); return null; } }); // Define an internal stream class for the probe var ReplStream = function(probe){ var t = this; t.probe = probe; events.EventEmitter.call(t); if (t.setEncoding) { t.setEncoding('utf8'); } }; util.inherits(ReplStream, events.EventEmitter); // util.inherits(ReplStream, require('stream')); ReplStream.prototype.readable = true; ReplStream.prototype.writable = true; ['pause','resume','destroySoon','pipe', 'end'] .forEach(function(fnName){ ReplStream.prototype[fnName] = function(){ console.log("REPL Stream function unexpected: " + fnName); }; }); ['resume'] .forEach(function(fnName){ ReplStream.prototype[fnName] = function(){ // Handled }; }); ReplStream.prototype.write = function(data) { var t = this; t.probe._output(data); }; ReplStream.prototype.destroy = function(data) { var t = this; console.log("REPL stream destroy " + t.probe.get('id')); t.probe.stop(); }; // Define format if it's not in util. var formatRegExp = /%[sdj]/g; var format = util.format || function (f) { if (typeof f !== 'string') { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(util.inspect(arguments[i])); } return objects.join(' '); } var j = 1; var args = arguments; var str = String(f).replace(formatRegExp, function(x) { switch (x) { case '%s': return String(args[j++]); case '%d': return Number(args[j++]); case '%j': return JSON.stringify(args[j++]); default: return x; } }); for (var len = args.length, x = args[j]; j < len; x = args[++j]) { if (x === null || typeof x !== 'object') { str += ' ' + x; } else { str += ' ' + util.inspect(x); } } return str; }; // Re-define the console so it goes to the HTML window var HtmlConsole = function(probe){ this.probe = probe; }; HtmlConsole.prototype.log = function(msg) { this.probe._output(format.apply(this, arguments)); }; HtmlConsole.prototype.info = HtmlConsole.prototype.log; HtmlConsole.prototype.warn = HtmlConsole.prototype.log; HtmlConsole.prototype.error = HtmlConsole.prototype.log; HtmlConsole.prototype.dir = function(object) { this.probe._output(util.inspect(object)); }; var times = {}; HtmlConsole.prototype.time = function(label) { times[label] = Date.now(); }; HtmlConsole.prototype.timeEnd = function(label) { var duration = Date.now() - times[label]; this.log('%s: %dms', label, duration); }; }(this));
lorenwest/monitor-min
lib/probes/ReplProbe.js
JavaScript
mit
7,982