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 |
|---|---|---|---|---|---|
/**
* This animation class is a mixin.
*
* Ext.util.Animate provides an API for the creation of animated transitions of properties and styles.
* This class is used as a mixin and currently applied to {@link Ext.dom.Element}, {@link Ext.CompositeElement},
* {@link Ext.draw.sprite.Sprite}, {@link Ext.draw.sprite.Composite}, and {@link Ext.Component}. Note that Components
* have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and
* opacity (color, paddings, and margins can not be animated).
*
* ## Animation Basics
*
* All animations require three things - `easing`, `duration`, and `to` (the final end value for each property)
* you wish to animate. Easing and duration are defaulted values specified below.
* Easing describes how the intermediate values used during a transition will be calculated.
* {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration.
* You may use the defaults for easing and duration, but you must always set a
* {@link Ext.fx.Anim#to to} property which is the end value for all animations.
*
* Popular element 'to' configurations are:
*
* - opacity
* - x
* - y
* - color
* - height
* - width
*
* Popular sprite 'to' configurations are:
*
* - translation
* - path
* - scale
* - stroke
* - rotation
*
* The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in
* milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve
* used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}.
*
* For example, a simple animation to fade out an element with a default easing and duration:
*
* var p1 = Ext.get('myElementId');
*
* p1.animate({
* to: {
* opacity: 0
* }
* });
*
* To make this animation fade out in a tenth of a second:
*
* var p1 = Ext.get('myElementId');
*
* p1.animate({
* duration: 100,
* to: {
* opacity: 0
* }
* });
*
* ## Animation Queues
*
* By default all animations are added to a queue which allows for animation via a chain-style API.
* For example, the following code will queue 4 animations which occur sequentially (one right after the other):
*
* p1.animate({
* to: {
* x: 500
* }
* }).animate({
* to: {
* y: 150
* }
* }).animate({
* to: {
* backgroundColor: '#f00' //red
* }
* }).animate({
* to: {
* opacity: 0
* }
* });
*
* You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all
* subsequent animations for the specified target will be run concurrently (at the same time).
*
* p1.syncFx(); //this will make all animations run at the same time
*
* p1.animate({
* to: {
* x: 500
* }
* }).animate({
* to: {
* y: 150
* }
* }).animate({
* to: {
* backgroundColor: '#f00' //red
* }
* }).animate({
* to: {
* opacity: 0
* }
* });
*
* This works the same as:
*
* p1.animate({
* to: {
* x: 500,
* y: 150,
* backgroundColor: '#f00' //red
* opacity: 0
* }
* });
*
* The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any
* currently running animations and clear any queued animations.
*
* ## Animation Keyframes
*
* You can also set up complex animations with {@link Ext.fx.Anim#keyframes keyframes} which follow the
* CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites.
* The previous example can be written with the following syntax:
*
* p1.animate({
* duration: 1000, //one second total
* keyframes: {
* 25: { //from 0 to 250ms (25%)
* x: 0
* },
* 50: { //from 250ms to 500ms (50%)
* y: 0
* },
* 75: { //from 500ms to 750ms (75%)
* backgroundColor: '#f00' //red
* },
* 100: { //from 750ms to 1sec
* opacity: 0
* }
* }
* });
*
* ## Animation Events
*
* Each animation you create has events for {@link Ext.fx.Anim#beforeanimate beforeanimate},
* {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}.
* Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which
* fires for each keyframe in your animation.
*
* All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events.
*
* startAnimate: function() {
* var p1 = Ext.get('myElementId');
* p1.animate({
* duration: 100,
* to: {
* opacity: 0
* },
* listeners: {
* beforeanimate: function() {
* // Execute my custom method before the animation
* this.myBeforeAnimateFn();
* },
* afteranimate: function() {
* // Execute my custom method after the animation
* this.myAfterAnimateFn();
* },
* scope: this
* });
* },
* myBeforeAnimateFn: function() {
* // My custom logic
* },
* myAfterAnimateFn: function() {
* // My custom logic
* }
*
* Due to the fact that animations run asynchronously, you can determine if an animation is currently
* running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation}
* method. This method will return false if there are no active animations or return the currently
* running {@link Ext.fx.Anim} instance.
*
* In this example, we're going to wait for the current animation to finish, then stop any other
* queued animations before we fade our element's opacity to 0:
*
* var curAnim = p1.getActiveAnimation();
* if (curAnim) {
* curAnim.on('afteranimate', function() {
* p1.stopAnimation();
* p1.animate({
* to: {
* opacity: 0
* }
* });
* });
* }
*/
Ext.define('Ext.util.Animate', {
mixinId: 'animate',
requires: [
'Ext.fx.Manager',
'Ext.fx.Anim'
],
isAnimate: true,
/**
* Performs custom animation on this object.
*
* This method is applicable to both the {@link Ext.Component Component} class and the {@link Ext.draw.sprite.Sprite Sprite}
* class. It performs animated transitions of certain properties of this object over a specified timeline.
*
* ### Animating a {@link Ext.Component Component}
*
* When animating a Component, the following properties may be specified in `from`, `to`, and `keyframe` objects:
*
* - `x` - The Component's page X position in pixels.
*
* - `y` - The Component's page Y position in pixels
*
* - `left` - The Component's `left` value in pixels.
*
* - `top` - The Component's `top` value in pixels.
*
* - `width` - The Component's `width` value in pixels.
*
* - `height` - The Component's `height` value in pixels.
*
* The following property may be set on the animation config root:
*
* - `dynamic` - Specify as true to update the Component's layout (if it is a Container) at every frame of the animation.
* *Use sparingly as laying out on every intermediate size change is an expensive operation.*
*
* For example, to animate a Window to a new size, ensuring that its internal layout and any shadow is correct:
*
* myWindow = Ext.create('Ext.window.Window', {
* title: 'Test Component animation',
* width: 500,
* height: 300,
* layout: {
* type: 'hbox',
* align: 'stretch'
* },
* items: [{
* title: 'Left: 33%',
* margin: '5 0 5 5',
* flex: 1
* }, {
* title: 'Left: 66%',
* margin: '5 5 5 5',
* flex: 2
* }]
* });
* myWindow.show();
* myWindow.header.el.on('click', function() {
* myWindow.animate({
* to: {
* width: (myWindow.getWidth() == 500) ? 700 : 500,
* height: (myWindow.getHeight() == 300) ? 400 : 300
* }
* });
* });
*
* For performance reasons, by default, the internal layout is only updated when the Window reaches its final `"to"`
* size. If dynamic updating of the Window's child Components is required, then configure the animation with
* `dynamic: true` and the two child items will maintain their proportions during the animation.
*
* @param {Object} config Configuration for {@link Ext.fx.Anim}.
* Note that the {@link Ext.fx.Anim#to to} config is required.
* @return {Object} this
*/
animate: function(animObj) {
var me = this;
if (Ext.fx.Manager.hasFxBlock(me.id)) {
return me;
}
Ext.fx.Manager.queueFx(new Ext.fx.Anim(me.anim(animObj)));
return this;
},
/**
* @private
* Process the passed fx configuration.
*/
anim: function(config) {
if (!Ext.isObject(config)) {
return (config) ? {} : false;
}
var me = this;
if (config.stopAnimation) {
me.stopAnimation();
}
Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
return Ext.apply({
target: me,
paused: true
}, config);
},
/**
* @private
* Get animation properties
*/
getAnimationProps: function() {
var me = this,
layout = me.layout;
return layout && layout.animate ? layout.animate : {};
},
/**
* Stops any running effects and clears this object's internal effects queue if it contains any additional effects
* that haven't started yet.
* @deprecated 4.0 Replaced by {@link #stopAnimation}
* @return {Ext.dom.Element} The Element
* @method
*/
stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'),
/**
* Stops any running effects and clears this object's internal effects queue if it contains any additional effects
* that haven't started yet.
* @return {Ext.dom.Element} The Element
*/
stopAnimation: function() {
Ext.fx.Manager.stopAnimation(this.id);
return this;
},
/**
* Ensures that all effects queued after syncFx is called on this object are run concurrently. This is the opposite
* of {@link #sequenceFx}.
* @return {Object} this
*/
syncFx: function() {
Ext.fx.Manager.setFxDefaults(this.id, {
concurrent: true
});
return this;
},
/**
* Ensures that all effects queued after sequenceFx is called on this object are run in sequence. This is the
* opposite of {@link #syncFx}.
* @return {Object} this
*/
sequenceFx: function() {
Ext.fx.Manager.setFxDefaults(this.id, {
concurrent: false
});
return this;
},
/**
* @deprecated 4.0 Replaced by {@link #getActiveAnimation}
* @inheritdoc Ext.util.Animate#getActiveAnimation
* @method
*/
hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'),
/**
* Returns the current animation if this object has any effects actively running or queued, else returns false.
* @return {Ext.fx.Anim/Boolean} Anim if element has active effects, else false
*/
getActiveAnimation: function() {
return Ext.fx.Manager.getActiveAnimation(this.id);
}
});
| san4osq/bindformext | ext/classic/classic/src/util/Animate.js | JavaScript | mit | 12,401 |
/**
* Created by Dennis on 08/11/16.
*/
/*
* action types
*/
export const KNOWLEDGEBASE_CHANGE = 'KNOWLEDGEBASE_CHANGE'
/*
* other constants
*/
/*
* action creators
*/
export function setKnowledgebase(k){
return function (dispatch) {
dispatch({type: KNOWLEDGEBASE_CHANGE, knowledgebase: k});
}
}
| WDAqua/frontEnd | src/actions/knowledgebase.js | JavaScript | mit | 317 |
import Component from '@ember/component';
import layout from '../templates/components/slds-dropdown-item';
export default Component.extend({
layout,
tagName: '',
clicked: null,
actions: {
clicked(handler, next) {
if (handler) {
handler(next);
}
}
}
});
| jonnii/ember-cli-lightning-design-system | addon/components/slds-dropdown-item.js | JavaScript | mit | 293 |
/**
* Internationalization / Localization Settings
* (sails.config.i18n)
*
* If your app will touch people from all over the world, i18n (or internationalization)
* may be an important part of your international strategy.
*
*
* For more information, check out:
* http://links.sailsjs.org/docs/config/i18n
*/
module.exports.i18n = {
// Which locales are supported?
locales: ['en', 'es', 'fr', 'de'],
objectNotation: true
};
| davesag/sails-i18n-example | config/i18n.js | JavaScript | mit | 442 |
var searchData=
[
['m_5fcontent',['m_content',['../class_message.html#a93ebdb6d1f8da485353a83bf72b6eeb7',1,'Message']]],
['m_5fdisplay_5fsize',['m_display_size',['../class_thread_list.html#a40884e201bc524b54e2f0bea7b867f68',1,'ThreadList']]],
['m_5fhead',['m_head',['../class_message.html#a96e95c41fb7e3ce7b6306737ff7b4c5a',1,'Message']]],
['m_5fid',['m_id',['../class_message.html#ab8306aee687fa159eff881a771399572',1,'Message::m_id()'],['../class_thread.html#aadc6842ff8ad6f73bc6e09f326d51a5f',1,'Thread::m_id()']]],
['m_5fid_5fto_5fthread',['m_id_to_thread',['../class_thread_list.html#aef0577b05198bc63a497b8f911ae027c',1,'ThreadList']]],
['m_5flogger',['m_logger',['../class_message.html#aaee0cd94e6c464030a99102d67f47e34',1,'Message::m_logger()'],['../class_thread.html#aae2a38e770394c7e75c44a1c8ccc9c18',1,'Thread::m_logger()'],['../class_thread_list.html#abf184dece6392417ab7f41bb2db49775',1,'ThreadList::m_logger()']]],
['m_5fmessages',['m_messages',['../class_thread.html#a10c656c0fc31e653551bb36dd91efdc8',1,'Thread']]],
['m_5fthreads',['m_threads',['../class_thread_list.html#ac353501c80de153aaf6beb130052fa35',1,'ThreadList']]]
];
| seven-qi/ThreadedMessengerCpp | html/search/variables_0.js | JavaScript | mit | 1,160 |
import Setting from '../models/setting';
import KhongDau from 'khong-dau';
export function getSettings(req, res) {
Setting.find({ disable: false }).exec((err, settings) => {
if(err) {
res.json({ settings: [] });
} else {
res.json({ settings });
}
})
}
| tranphong001/BIGVN | server/controllers/setting.controller.js | JavaScript | mit | 281 |
/**
* @fileOverview first_run.js shows the necessary navigation and
* design elements to be integrated into the privly-applications
* bundle.
*/
/**
* Initialize the applications by showing and hiding the proper
* elements.
*/
function init() {
// Set the nav bar to the proper domain
privlyNetworkService.initializeNavigation();
privlyNetworkService.initPrivlyService(
privlyNetworkService.contentServerDomain(),
privlyNetworkService.showLoggedInNav,
privlyNetworkService.showLoggedOutNav
);
$("#messages").hide();
$("#form").show();
// Show a preview of the tooltip to the user
$("#tooltip").append(Privly.glyph.getGlyphDOM())
.show()
.append("<br/><br/><p>This is your Privly Glyph</p>");
}
// Initialize the application
document.addEventListener('DOMContentLoaded', init);
| SummerWish/privly-applications | Pages/js/first_run.js | JavaScript | mit | 848 |
require("./46.js");
require("./93.js");
require("./186.js");
require("./372.js");
module.exports = 373; | skeiter9/javascript-para-todo_demo | webapp/node_modules/webpack/benchmark/fixtures/373.js | JavaScript | mit | 103 |
var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
var bname = event.name.replace(/\W/g, '');
bname = bname.charAt(0).toUpperCase() + bname.slice(1);
dynamodb.updateItem({
"TableName": "baby-names",
"Key" : {
name : bname
},
"UpdateExpression" : "SET votes = votes + :a",
"ExpressionAttributeValues" : {
":a" : 1
}
}, function(err, data) {
if (err) {
context.done('error putting item into dynamodb failed: '+err);
} else {
console.log('success: '+JSON.stringify(data, null, ' '));
context.done();
}
});
}; | ScreamingHawk/milk-server-baby | babyNameUpvote.js | JavaScript | mit | 686 |
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? "source-map" : false,
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve("./polyfills"), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: "static/js/[name].[chunkhash:8].js",
chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.relative(paths.appSrc, info.absoluteResourcePath).replace(/\\/g, "/")
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ["node_modules", paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
"react-native": "react-native-web"
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
]
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve("eslint")
},
loader: require.resolve("eslint-loader")
}
],
include: paths.appSrc
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]"
}
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve("babel-loader"),
options: {
compact: true
}
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: {
loader: require.resolve("style-loader"),
options: {
hmr: false
}
},
use: [
{
loader: require.resolve("css-loader"),
options: {
importLoaders: 1,
minimize: true,
modules: true,
localIdentName:
"[path][name]__[local]--[hash:base64:5]",
sourceMap: shouldUseSourceMap,
camelCase: "dashes"
}
},
{
loader: require.resolve("postcss-loader"),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: "postcss",
plugins: () => [
require("postcss-flexbugs-fixes"),
autoprefixer({
browsers: [
">1%",
"last 4 versions",
"Firefox ESR",
"not ie < 9" // React doesn't support IE8 anyway
],
flexbox: "no-2009"
})
],
sourceMap: true
}
},
{
loader: require.resolve("sass-loader"),
options: {
sourceMap: true,
data: `@import "${
paths.appSrc
}/config/_variables.scss";`
}
}
]
},
extractTextPluginOptions
)
)
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// "file" loader makes sure assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve("file-loader"),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.js$/, /\.html$/, /\.json$/],
options: {
name: "static/media/[name].[hash:8].[ext]"
}
}
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
]
}
]
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false
},
mangle: {
safari10: true
},
output: {
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebookincubator/create-react-app/issues/2488
ascii_only: true
},
sourceMap: shouldUseSourceMap
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: "asset-manifest.json"
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: "service-worker.js",
logger(message) {
if (message.indexOf("Total precache size is") === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf("Skipping static resource") === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + "/index.html",
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/]
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty"
}
};
| plusbeauxjours/nomadgram | frontend/config/webpack.config.prod.js | JavaScript | mit | 15,891 |
'use strict';
// Author: ThemeREX.com
// user-interface-buttons.html scripts
//
(function($) {
"use strict";
// Init Theme Core
Core.init();
// Init Demo JS
Demo.init();
// Init Ladda Plugin
Ladda.bind('.ladda-button', {
timeout: 2000
});
// Simulate loading progress on buttons with ".ladda-button" class
Ladda.bind('.progress-button', {
callback: function(instance) {
var progress = 0;
var interval = setInterval(function() {
progress = Math.min(progress + Math.random() * 0.1, 1);
instance.setProgress(progress);
if (progress === 1) {
instance.stop();
clearInterval(interval);
}
}, 200);
}
});
})(jQuery);
| matthiassb/sorbet | resources/assets/js/pages/user-interface-buttons.js | JavaScript | mit | 864 |
'use strict';
// Teams controller
angular.module('teams').controller('TeamsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Teams', 'Players', '$filter',
function($scope, $stateParams, $location, Authentication, Teams, Players, $filter) {
$scope.authentication = Authentication;
// Create new Team
$scope.create = function() {
// Create new Team object
var team = new Teams ({
name: this.name
});
// Redirect after save
team.$save(function(response) {
$location.path('teams/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Team
$scope.remove = function(team) {
if ( team ) {
team.$remove();
for (var i in $scope.teams) {
if ($scope.teams [i] === team) {
$scope.teams.splice(i, 1);
}
}
} else {
$scope.team.$remove(function() {
$location.path('teams');
});
}
};
// Update existing Team
$scope.update = function() {
var team = $scope.team;
team.$update(function() {
$location.path('teams/' + team._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Teams
$scope.find = function() {
$scope.teams = Teams.query();
};
// Find existing Team
$scope.findOne = function() {
$scope.team = Teams.get({
teamId: $stateParams.teamId
});
$scope.players = Players.query({
'team': $stateParams.teamId
});
};
}
]); | nithinreddygaddam/ScoreNow | public/modules/teams/controllers/teams.client.controller.js | JavaScript | mit | 1,559 |
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: ["error", { allow: ["log"] }] */
const gulp = require('gulp');
const modifyFile = require('gulp-modify-file');
const path = require('path');
const rollup = require('rollup');
const buble = require('rollup-plugin-buble');
const replace = require('rollup-plugin-replace');
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const vue = require('rollup-plugin-vue');
function buildKs(cb) {
const env = process.env.NODE_ENV || 'development';
const target = process.env.TARGET || 'universal';
const buildPath = env === 'development' ? './build' : './packages';
let f7VuePath = path.resolve(__dirname, `../${buildPath}/vue/framework7-vue.esm.js`);
let f7Path = path.resolve(__dirname, `../${buildPath}/core/framework7.esm.bundle`);
if (process.platform.indexOf('win') === 0) {
f7VuePath = f7VuePath.replace(/\\/g, '/');
f7Path = f7Path.replace(/\\/g, '/');
}
gulp.src('./kitchen-sink/vue/index.html')
.pipe(modifyFile((content) => {
if (env === 'development') {
return content
.replace('../../packages/core/css/framework7.min.css', '../../build/core/css/framework7.css')
.replace('../../packages/core/js/framework7.min.js', '../../build/core/js/framework7.js');
}
return content
.replace('../../build/core/css/framework7.css', '../../packages/core/css/framework7.min.css')
.replace('../../build/core/js/framework7.js', '../../packages/core/js/framework7.min.js');
}))
.pipe(gulp.dest('./kitchen-sink/vue'));
rollup.rollup({
input: './kitchen-sink/vue/src/app.js',
plugins: [
replace({
delimiters: ['', ''],
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.TARGET': JSON.stringify(target),
"'framework7-vue'": () => `'${f7VuePath}'`,
"'framework7/framework7.esm.bundle'": () => `'${f7Path}'`,
}),
resolve({ jsnext: true }),
commonjs(),
vue(),
buble({
objectAssign: 'Object.assign',
}),
],
onwarn(warning, warn) {
const ignore = ['EVAL'];
if (warning.code && ignore.indexOf(warning.code) >= 0) {
return;
}
warn(warning);
},
}).then(bundle => bundle.write({
format: 'umd',
name: 'app',
strict: true,
sourcemap: false,
file: './kitchen-sink/vue/js/app.js',
})).then(() => {
if (cb) cb();
}).catch((err) => {
console.log(err);
if (cb) cb();
});
}
module.exports = buildKs;
| AdrianV/Framework7 | scripts/build-ks-vue.js | JavaScript | mit | 2,621 |
import {expect} from 'chai';
import {camel_case} from '../src';
describe('CamelCase', () => {
it('should be exists.', () => {
expect(camel_case).to.be.exists;
});
it('should convert helloThere to HelloThere.', () => {
expect(camel_case('helloThere')).to.be.equals('HelloThere');
});
it('should convert i_am_a_robot to IAmARobot.', () => {
expect(camel_case('i_am_a_robot')).to.be.equals('IAmARobot');
});
}); | indianajone/strcaser | test/CamelCase.js | JavaScript | mit | 464 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _base = require('./base');
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var config = {
appEnv: 'test' // don't remove the appEnv property here
};
exports.default = Object.freeze(Object.assign(_base2.default, config)); | GGGGino/react-event-layer | lib/config/test.js | JavaScript | mit | 403 |
import React from 'react'
import ColorWheel from './ColorWheel.jsx'
React.render(<ColorWheel title='ColorWheel' />, document.querySelector('#color-wheel'))
| naush/simple-slice-example | entry.js | JavaScript | mit | 157 |
const uAPI = require('../../index');
const config = require('../../test/testconfig');
const AirService = uAPI.createAirService(
{
auth: config,
debug: 2,
production: false,
}
);
const AirServiceQuiet = uAPI.createAirService(
{
auth: config,
production: false,
}
);
const requestPTC = 'ADT';
const shop_params = {
legs: [
{
from: 'LOS',
to: 'IST',
departureDate: '2019-06-18',
},
{
from: 'IST',
to: 'LOS',
departureDate: '2019-06-21',
},
],
passengers: {
[requestPTC]: 1,
},
cabins: ['Economy'],
requestId: 'test',
};
AirServiceQuiet.shop(shop_params)
.then((results) => {
const forwardSegments = results['0'].directions['0']['0'].segments;
const backSegments = results['0'].directions['1']['0'].segments;
const farerules_params = {
segments: forwardSegments.concat(backSegments),
passengers: shop_params.passengers,
long: true,
requestId: 'test',
};
return AirService.fareRules(farerules_params);
})
.then(
(res) => {
console.log(JSON.stringify(res));
},
err => console.error(err)
).catch((err) => {
console.error(err);
});
| Travelport-Ukraine/uapi-json | examples/Air/fareRules.js | JavaScript | mit | 1,202 |
var objc = require('../')
objc.dlopen('/System/Library/Frameworks/AppKit.framework/AppKit');
NSApplication = objc.objc_getClass('NSApplication');
console.log(NSApplication);
var sharedApplication = objc.sel_registerName('sharedApplication');
var app = objc.objc_msgSend(NSApplication, sharedApplication);
console.log(app);
| TooTallNate/node-objc | tests/test2.js | JavaScript | mit | 326 |
/*
*
Elfenben - Javascript using tree syntax!
This is the compiler written in javascipt
*
*/
var version = "1.0.16",
banner = "// Generated by Elfenben v" + version + "\n",
isWhitespace = /\s/,
isFunction = /^function\b/,
validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/,
noReturn = /^var\b|^set\b|^throw\b/,
isHomoiconicExpr = /^#args-if\b|^#args-shift\b|^#args-second\b/,
noSemiColon = false,
indentSize = 4,
indent = -indentSize,
keywords = {},
macros = {},
errors = [],
include_dirs = [__dirname + "/../includes", "includes"],
fs,
path,
SourceNode = require('source-map').SourceNode
if (typeof window === "undefined") {
fs = require('fs')
path = require('path')
}
if (!String.prototype.repeat) {
String.prototype.repeat = function(num) {
return new Array(num + 1).join(this)
}
}
var parse = function(code, filename) {
code = "(" + code + ")"
var length = code.length,
pos = 1,
lineno = 1,
colno = 1,
token_begin_colno = 1
var parser = function() {
var tree = [],
token = "",
isString = false,
isSingleString = false,
isJSArray = 0,
isJSObject = 0,
isListComplete = false,
isComment = false,
isRegex = false,
isEscape = false,
handleToken = function() {
if (token) {
tree.push(new SourceNode(lineno, token_begin_colno - 1, filename, token, token))
token = ""
}
}
tree._line = lineno
tree._filename = filename
while (pos < length) {
var c = code.charAt(pos)
pos++
colno++
if (c == "\n") {
lineno++
colno = 1
if (isComment) {
isComment = false
}
}
if (isComment) {
continue
}
if (isEscape) {
isEscape = false
token += c
continue
}
// strings
if (c == '"' || c == '`') {
isString = !isString
token += c
continue
}
if (isString) {
if (c === "\n") {
token += "\\n"
} else {
if (c === "\\") {
isEscape = true
}
token += c
}
continue
}
if (c == "'") {
isSingleString = !isSingleString
token += c
continue
}
if (isSingleString) {
token += c
continue
}
// data types
if (c == '[') {
isJSArray++
token += c
continue
}
if (c == ']') {
if (isJSArray === 0) {
handleError(4, tree._line, tree._filename)
}
isJSArray--
token += c
continue
}
if (isJSArray) {
token += c
continue
}
if (c == '{') {
isJSObject++
token += c
continue
}
if (c == '}') {
if (isJSObject === 0) {
handleError(6, tree._line, tree._filename)
}
isJSObject--
token += c
continue
}
if (isJSObject) {
token += c
continue
}
if (c == ";") {
isComment = true
continue
}
// regex
// regex in function position with first char " " is a prob. Use \s instead.
if (c === "/" && !(tree.length === 0 && token.length === 0 && isWhitespace.test(code.charAt(pos)))) {
isRegex = !isRegex
token += c
continue
}
if (isRegex) {
if (c === "\\") {
isEscape = true
}
token += c
continue
}
if (c == "(") {
handleToken() // catch e.g. "blah("
token_begin_colno = colno
tree.push(parser())
continue
}
if (c == ")") {
isListComplete = true
handleToken()
token_begin_colno = colno
break
}
if (isWhitespace.test(c)) {
if (c == '\n')
lineno--
handleToken()
if (c == '\n')
lineno++
token_begin_colno = colno
continue
}
token += c
}
if (isString) handleError(3, tree._line, tree._filename)
if (isRegex) handleError(14, tree._line, tree._filename)
if (isSingleString) handleError(3, tree._line, tree._filename)
if (isJSArray > 0) handleError(5, tree._line, tree._filename)
if (isJSObject > 0) handleError(7, tree._line, tree._filename)
if (!isListComplete) handleError(8, tree._line, tree._filename)
return tree
}
var ret = parser()
if (pos < length) {
handleError(10)
}
return ret
}
var handleExpressions = function(exprs) {
indent += indentSize
var ret = new SourceNode(),
l = exprs.length,
indentstr = " ".repeat(indent)
exprs.forEach(function(expr, i, exprs) {
var exprName,
tmp = null,
r = ""
if (Array.isArray(expr)) {
exprName = expr[0].name
if (exprName === "include")
ret.add(handleExpression(expr))
else
tmp = handleExpression(expr)
} else {
tmp = expr
}
if (i === l - 1 && indent) {
if (!noReturn.test(exprName)) r = "return "
}
if (tmp) {
var endline = noSemiColon ? "\n" : ";\n"
noSemiColon = false
ret.add([indentstr + r, tmp, endline])
}
})
indent -= indentSize
return ret
}
var handleExpression = function(expr) {
if (!expr || !expr[0]) {
return null
}
var command = expr[0].name
if (macros[command]) {
expr = macroExpand(expr)
if (Array.isArray(expr)) {
return handleExpression(expr)
} else {
return expr
}
}
if (typeof command === "string") {
if (keywords[command]) {
return keywords[command](expr)
}
if (command.charAt(0) === ".") {
var ret = new SourceNode()
ret.add(Array.isArray(expr[1]) ? handleExpression(expr[1]) : expr[1])
ret.prepend("(")
ret.add([")", expr[0]])
return ret
}
}
handleSubExpressions(expr)
var fName = expr[0]
if (!fName) {
handleError(1, expr._line)
}
if (isFunction.test(fName))
fName = new SourceNode(null, null, null, ['(', fName, ')'])
exprNode = new SourceNode (null, null, null, expr.slice(1)).join(",")
return new SourceNode (null, null, null, [fName, "(", exprNode, ")"])
}
var handleSubExpressions = function(expr) {
expr.forEach(function(value, i, t) {
if (Array.isArray(value)) t[i] = handleExpression(value)
})
}
var macroExpand = function(tree) {
var command = tree[0].name,
template = macros[command]["template"],
code = macros[command]["code"],
replacements = {}
for (var i = 0; i < template.length; i++) {
if (template[i].name == "rest...") {
replacements["~rest..."] = tree.slice(i + 1)
} else {
if (tree.length === i + 1) {
// we are here if any macro arg is not set
handleError(12, tree._line, tree._filename, command)
}
replacements["~" + template[i].name] = tree[i + 1]
}
}
var replaceCode = function(source) {
var ret = []
ret._line = tree._line
ret._filename = tree._filename
// Handle homoiconic expressions in macro
var expr_name = source[0] ? source[0].name : ""
if (isHomoiconicExpr.test(expr_name)) {
var replarray = replacements["~" + source[1].name]
if (expr_name === "#args-shift") {
if (!Array.isArray(replarray)) {
handleError(13, tree._line, tree._filename, command)
}
var argshift = replarray.shift()
if (typeof argshift === "undefined") {
handleError(12, tree._line, tree._filename, command)
}
return argshift
}
if (expr_name === "#args-second") {
if (!Array.isArray(replarray)) {
handleError(13, tree._line, tree._filename, command)
}
var argsecond = replarray.splice(1, 1)[0]
if (typeof argsecond === "undefined") {
handleError(12, tree._line, tree._filename, command)
}
return argsecond
}
if (expr_name === "#args-if") {
if (!Array.isArray(replarray)) {
handleError(13, tree._line, tree._filename, command)
}
if (replarray.length) {
return replaceCode(source[2])
} else if (source[3]) {
return replaceCode(source[3])
} else {
return
}
}
}
for (var i = 0; i < source.length; i++) {
if (Array.isArray(source[i])) {
var replcode = replaceCode(source[i])
if (typeof replcode !== "undefined") {
ret.push(replcode)
}
} else {
var token = source[i],
tokenbak = token,
isATSign = false
if (token.name.indexOf("@") >= 0) {
isATSign = true
tokenbak = new SourceNode(token.line, token.column, token.source, token.name.replace("@", ""), token.name.replace("@", ""))
}
if (replacements[tokenbak.name]) {
var repl = replacements[tokenbak.name]
if (isATSign || tokenbak.name == "~rest...") {
for (var j = 0; j < repl.length; j++) {
ret.push(repl[j])
}
} else {
ret.push(repl)
}
} else {
ret.push(token)
}
}
}
return ret
}
return replaceCode(code)
}
var handleCompOperator = function(arr) {
if (arr.length < 3) handleError(0, arr._line)
handleSubExpressions(arr)
if (arr[0] == "=") arr[0] = "==="
if (arr[0] == "!=") arr[0] = "!=="
var op = arr.shift()
var ret = new SourceNode()
for (i = 0; i < arr.length - 1; i++)
ret.add (new SourceNode (null, null, null, [arr[i], " ", op, " ", arr[i + 1]]))
ret.join (' && ')
ret.prepend('(')
ret.add(')')
return ret
}
var handleArithOperator = function(arr) {
if (arr.length < 3) handleError(0, arr._line)
handleSubExpressions(arr)
var op = new SourceNode()
op.add([" ", arr.shift(), " "])
var ret = new SourceNode()
ret.add(arr)
ret.join (op)
ret.prepend("(")
ret.add(")")
return ret
}
var handleLogicalOperator = handleArithOperator
var handleVariableDeclarations = function(arr, varKeyword){
if (arr.length < 3) handleError(0, arr._line, arr._filename)
if (arr.length > 3) {
indent += indentSize
}
handleSubExpressions(arr)
var ret = new SourceNode ()
ret.add(varKeyword + " ")
for (var i = 1; i < arr.length; i = i + 2) {
if (i > 1) {
ret.add(",\n" + " ".repeat(indent))
}
if (!validName.test(arr[i])) handleError(9, arr._line, arr._filename)
ret.add([arr[i], ' = ', arr[i + 1]])
}
if (arr.length > 3) {
indent -= indentSize
}
return ret
}
keywords["var"] = function(arr) {
return handleVariableDeclarations(arr, "var")
}
keywords["const"] = function(arr) {
return handleVariableDeclarations(arr, "const")
}
keywords["let"] = function(arr) {
return handleVariableDeclarations(arr, "let")
}
keywords["new"] = function(arr) {
if (arr.length < 2) handleError(0, arr._line, arr._filename)
var ret = new SourceNode()
ret.add(handleExpression(arr.slice(1)))
ret.prepend ("new ")
return ret
}
keywords["throw"] = function(arr) {
if (arr.length != 2) handleError(0, arr._line, arr._filename)
var ret = new SourceNode()
ret.add(Array.isArray(arr[1]) ? handleExpression(arr[1]) : arr[1])
ret.prepend("(function(){throw ")
ret.add(";})()")
return ret
}
keywords["set"] = function(arr) {
if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename)
if (arr.length == 4) {
arr[1] = (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2]) + "[" + arr[1] + "]"
arr[2] = arr[3]
}
return new SourceNode(null, null, null,
[arr[1], " = ", (Array.isArray(arr[2]) ? handleExpression(arr[2]) : arr[2])])
}
keywords["function"] = function(arr) {
var ret
var fName, fArgs, fBody
if (arr.length < 2) handleError(0, arr._line, arr._filename)
if(Array.isArray(arr[1])) {
// an anonymous function
fArgs = arr[1]
fBody = arr.slice(2)
}
else if(!Array.isArray(arr[1]) && Array.isArray(arr[2])) {
// a named function
fName = arr[1]
fArgs = arr[2]
fBody = arr.slice(3)
}
else
handleError(0, arr._line)
ret = new SourceNode(null, null, null, fArgs)
ret.join(",")
ret.prepend("function" + (fName ? " " + fName.name : "") + "(")
ret.add([") {\n",handleExpressions(fBody),
" ".repeat(indent), "}"])
if(fName)
noSemiColon = true
return ret
}
keywords["try"] = function(arr) {
if (arr.length < 3) handleError(0, arr._line, arr._filename)
var c = arr.pop(),
ind = " ".repeat(indent),
ret = new SourceNode()
ret.add(["(function() {\n" + ind +
"try {\n", handleExpressions(arr.slice(1)), "\n" +
ind + "} catch (e) {\n" +
ind + "return (", (Array.isArray(c) ? handleExpression(c) : c), ")(e);\n" +
ind + "}\n" + ind + "})()"])
return ret
}
keywords["if"] = function(arr) {
if (arr.length < 3 || arr.length > 4) handleError(0, arr._line, arr._filename)
indent += indentSize
handleSubExpressions(arr)
var ret = new SourceNode()
ret.add(["(", arr[1], " ?\n" +
" ".repeat(indent), arr[2], " :\n" +
" ".repeat(indent), (arr[3] || "undefined"), ")"])
indent -= indentSize
return ret
}
keywords["get"] = function(arr) {
if (arr.length != 3) handleError(0, arr._line, arr._filename)
handleSubExpressions(arr)
return new SourceNode(null, null, null, [arr[2], "[", arr[1], "]"])
}
keywords["str"] = function(arr) {
if (arr.length < 2) handleError(0, arr._line, arr._filename)
handleSubExpressions(arr)
var ret = new SourceNode()
ret.add(arr.slice(1))
ret.join (",")
ret.prepend("[")
ret.add("].join('')")
return ret
}
keywords["array"] = function(arr) {
var ret = new SourceNode()
if (arr.length == 1) {
ret.add("[]")
return ret
}
indent += indentSize
handleSubExpressions(arr)
ret.add("[\n" + " ".repeat(indent))
for (var i = 1; i < arr.length; ++i) {
if (i > 1) {
ret.add(",\n" + " ".repeat(indent))
}
ret.add(arr[i])
}
indent -= indentSize
ret.add("\n" + " ".repeat(indent) + "]")
return ret
}
keywords["object"] = function(arr) {
var ret = new SourceNode()
if (arr.length == 1) {
ret.add("{}")
return ret
}
indent += indentSize
handleSubExpressions(arr)
ret.add("{\n" + " ".repeat(indent))
for (var i = 1; i < arr.length; i = i + 2) {
if (i > 1) {
ret.add(",\n" + " ".repeat(indent))
}
ret.add([arr[i], ': ', arr[i + 1]])
}
indent -= indentSize
ret.add("\n" + " ".repeat(indent) + "}")
return ret
}
var includeFile = (function () {
var included = []
return function(filename) {
if (included.indexOf(filename) !== -1) return ""
included.push(filename)
var code = fs.readFileSync(filename)
var tree = parse(code, filename)
return handleExpressions(tree)
}
})()
keywords["include"] = function(arr) {
if (arr.length != 2) handleError(0, arr._line, arr._filename)
indent -= indentSize
var filename = arr[1].name
if (typeof filename === "string")
filename = filename.replace(/["']/g, "")
var found = false;
include_dirs.concat([path.dirname(arr._filename)])
.forEach(function(prefix) {
if (found) { return; }
try {
filename = fs.realpathSync(prefix + '/' +filename)
found = true;
} catch (err) { }
});
if (!found) {
handleError(11, arr._line, arr._filename)
}
var ret = new SourceNode()
ret = includeFile(filename)
indent += indentSize
return ret
}
keywords["javascript"] = function(arr) {
if (arr.length != 2) handleError(0, arr._line, arr._filename)
noSemiColon = true
arr[1].replaceRight(/"/g, '')
return arr[1]
}
keywords["macro"] = function(arr) {
if (arr.length != 4) handleError(0, arr._line, arr._filename)
macros[arr[1].name] = {template: arr[2], code: arr[3]}
return ""
}
keywords["+"] = handleArithOperator
keywords["-"] = handleArithOperator
keywords["*"] = handleArithOperator
keywords["/"] = handleArithOperator
keywords["%"] = handleArithOperator
keywords["="] = handleCompOperator
keywords["!="] = handleCompOperator
keywords[">"] = handleCompOperator
keywords[">="] = handleCompOperator
keywords["<"] = handleCompOperator
keywords["<="] = handleCompOperator
keywords["||"] = handleLogicalOperator
keywords["&&"] = handleLogicalOperator
keywords["!"] = function(arr) {
if (arr.length != 2) handleError(0, arr._line, arr._filename)
handleSubExpressions(arr)
return "(!" + arr[1] + ")"
}
var handleError = function(no, line, filename, extra) {
throw new Error(errors[no] +
((extra) ? " - " + extra : "") +
((line) ? "\nLine no " + line : "") +
((filename) ? "\nFile " + filename : ""))
}
errors[0] = "Syntax Error"
errors[1] = "Empty statement"
errors[2] = "Invalid characters in function name"
errors[3] = "End of File encountered, unterminated string"
errors[4] = "Closing square bracket, without an opening square bracket"
errors[5] = "End of File encountered, unterminated array"
errors[6] = "Closing curly brace, without an opening curly brace"
errors[7] = "End of File encountered, unterminated javascript object '}'"
errors[8] = "End of File encountered, unterminated parenthesis"
errors[9] = "Invalid character in var name"
errors[10] = "Extra chars at end of file. Maybe an extra ')'."
errors[11] = "Cannot Open include File"
errors[12] = "Invalid no of arguments to "
errors[13] = "Invalid Argument type to "
errors[14] = "End of File encountered, unterminated regular expression"
var _compile = function(code, filename, withSourceMap, a_include_dirs) {
indent = -indentSize
if (a_include_dirs)
include_dirs = a_include_dirs
var tree = parse(code, filename)
var outputNode = handleExpressions(tree)
outputNode.prepend(banner)
if (withSourceMap) {
var outputFilename = path.basename(filename, '.elf') + '.js'
var sourceMapFile = outputFilename + '.map'
var output = outputNode.toStringWithSourceMap({
file: outputFilename
});
fs.writeFileSync(sourceMapFile, output.map)
return output.code + "\n//# sourceMappingURL=" + path.relative(path.dirname(filename), sourceMapFile);
} else
return outputNode.toString()
}
exports.version = version
exports._compile = _compile
exports.parseWithSourceMap = function(code, filename) {
var tree = parse(code, filename)
var outputNode = handleExpressions(tree)
outputNode.prepend(banner)
return outputNode.toStringWithSourceMap();
}
| Nappa9693/elfenben | lib/ls.js | JavaScript | mit | 21,053 |
/**
* Created by Dennis Schwartz on 16/12/15.
*/
var THREE = require('three');
var TrackballControls = require('three.trackball');
var OrthographicTrackballControls = require('three.orthographictrackball');
var Layouts = require('./layouts');
var Fixed = Layouts.connectedMultilayer;
var ForceDirectedLayered = Layouts.independentMultilayer;
var Manual = Layouts.manual;
var R = require('ramda');
var Defaults = require('./defaults');
function Graphics ( state ) {
var stable = false;
var maxWeight = state.elements.maxWeight;
// Attach the current three instance to the state
state.THREE = THREE;
/*
Create the three.js canvas/WebGL renderer
*/
state.renderer = createRenderer( state.visEl );
state.scene = new THREE.Scene();
createCamera( state );
/*
Create Layout with elements in state
*/
var layout = createLayout( state );
/*
Layouts specify renderers and UI builders
*/
var nodeRenderer = layout.nodeRenderer;
//var linkRenderer = layout.linkRenderer;
/**
* This sets the default node rendering function
*/
//var linkRenderer = function ( link ) {
// console.log(link);
// console.log(state.elements.elements[link.from]);
//
// var from = nodeUI[link.from.substring(2)];
// var to = nodeUI[link.to.substring(2)];
// link.geometry.vertices[0].set(from.position.x,
// from.position.y,
// from.position.z);
// link.geometry.vertices[1].set(to.position.x,
// to.position.y,
// to.position.z);
// link.geometry.verticesNeedUpdate = true;
//};
var nodeUIBuilder = layout.nodeUIBuilder;
var linkUIBuilder = layout.linkUIBuilder;
/*
Create ui (look) of every element and add it to the element object
*/
var nodes = state.elements.nodelayers; // TODO: Save only IDs in these lists
var edges = state.elements.edges;
nodes.forEach(function (n) {
createNodeUI(state.elements.elements['nl' + n.data.id]);
});
edges.forEach(function (e) {
var toID = e.data.target.substring(2);
var fromID = e.data.source.substring(2);
var link = state.elements.elements[ 'e' + fromID + toID ];
createLinkUI(link);
});
console.log(state);
/*
Create controls if set
*/
/**
* Create the UI for each node-layer in the network and add them to the scene
* @param node
*/
function createNodeUI(node) {
if (!node.ui) {
node.ui = nodeUIBuilder(node);
console.log('hello!');
node.position = layout.getNodePosition(node);
var layers = R.map(function (i) { return i.data['id'] }, state.elements.layers);
node.position.z = layers.indexOf('l' + node.data['layer']) * state.interLayerDistance;
}
state.scene.add(node.ui);
//console.log("added");
//console.log(node.ui);
}
/**
* Create the UI for each link and add it to the scene
* @param link
*/
function createLinkUI(link) {
if (!link.ui) {
var from = link.data['source'];
var to = link.data['target'];
link.ui = linkUIBuilder(link);
link.ui.from = from;
link.ui.to = to;
}
state.scene.add(link.ui);
}
/**
* This is the main Animation loop calling requestAnimationFrame on window
* which in turn calls back to this function
*/
function run () {
//if ( stop ) return;
window.requestAnimationFrame( run );
if (!stable) {
stable = layout.step();
}
renderFrame ();
state.controls.update ();
}
/**
* Create three.js state
* @param state
* @returns {THREE.PerspectiveCamera}
*/
function createCamera ( state ) {
var container = state.renderer.domElement;
var camera;
var controls;
if ( state.cameraType === 'orthographic' ) {
// Create camera
camera = new THREE.OrthographicCamera( container.width / 2,
container.width / -2,
container.height / 2,
container.height / -2, 1, 1000 );
camera.position.x = 200;
camera.position.y = 100;
camera.position.z = 300;
camera.lookAt(state.scene.position);
// Create corresponding controls if necessary
if ( state.zoomingEnabled ) controls = new OrthographicTrackballControls(camera, state.renderer.domElement);
} else { // Default case
camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 30000);
if ( state.zoomingEnabled ) controls = new TrackballControls(camera, state.renderer.domElement);
}
camera.position.z = 400;
state.camera = camera;
if (state.zoomingEnabled) {
controls.panSpeed = 0.8;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.addEventListener('change', renderFrame);
state.controls = controls;
}
}
/**
* This function calculates and sets
* the current position of each ui-element each frame.
*/
function renderFrame() {
//Alternative version
nodes.forEach(function ( node ) {
var n = state.elements.elements[ 'nl' + node.data.id ];
nodeRenderer( n );
});
if ( state.directed ) {
var arrowScale = 0.25;
edges.forEach(function ( edge ) {
var toID = edge.data.target.substring(2);
var fromID = edge.data.source.substring(2);
var link = state.elements.elements[ 'e' + fromID + toID ];
var from = state.elements.elements[ edge.data.source ];
var to = state.elements.elements[ edge.data.target ];
var newSourcePos = new THREE.Vector3(from.ui.position.x,
from.ui.position.y,
from.ui.position.z);
var newTargetPos = new THREE.Vector3(to.ui.position.x,
to.ui.position.y,
to.ui.position.z);
var arrowVec = newTargetPos.clone().sub(newSourcePos);
// targetPos + norm(neg(arrowVec)) * (nodesize / 2)
var nodeRadVec = arrowVec.clone().negate().normalize().multiplyScalar(state.nodesize || 6);
var cursor = newTargetPos.clone().add(nodeRadVec); // point
link.ui.geometry.vertices[0].set(cursor.x, cursor.y, cursor.z);
link.ui.geometry.vertices[3].set(cursor.x, cursor.y, cursor.z);
cursor.add(nodeRadVec.multiplyScalar(1.5)); //arrowHeadBase
var arrowHeadBase = cursor.clone();
var flanker = nodeRadVec.clone().cross(new THREE.Vector3(0,0,1)).multiplyScalar(arrowScale);
var w = link.data.weight || 1;
var factor = 1;
if ( maxWeight === 0 ) {
factor = .6 - (.6 / (w + .1));
} else {
if ( state.normalisation === 'log' ) {
factor = 0.6 * ( Math.log(w) / Math.log(maxWeight) );
} else {
factor = 0.6 * ( w / maxWeight );
}
}
var ribboner = flanker.clone().multiplyScalar(factor);
var flank1 = cursor.clone().add(flanker); //flank 1
link.ui.geometry.vertices[1].set(flank1.x, flank1.y, flank1.z);
flanker.add(flanker.negate().multiplyScalar(arrowScale * 2));
cursor.add(flanker); //flank 2
link.ui.geometry.vertices[2].set(cursor.x, cursor.y, cursor.z);
// Move to Ribbon 1
cursor = arrowHeadBase.clone().add(ribboner);
link.ui.geometry.vertices[4].set(cursor.x, cursor.y, cursor.z);
// Move to Ribbon 2
cursor = arrowHeadBase.clone().add(ribboner.negate());
link.ui.geometry.vertices[5].set(cursor.x, cursor.y, cursor.z);
var temp = newTargetPos.clone().add(newSourcePos).divideScalar(2);
// Move to source
// RibbonSrc1
cursor = newSourcePos.clone().add(ribboner).add(nodeRadVec.negate().multiplyScalar(1.3));
link.ui.geometry.vertices[6].set(cursor.x, cursor.y, cursor.z);
// RibbonSrc2
cursor = newSourcePos.clone().add(ribboner.negate()).add(nodeRadVec);
link.ui.geometry.vertices[7].set(cursor.x, cursor.y, cursor.z);
link.ui.material.color.set(0x000000);
//link.ui.material.transparent = true;
//link.ui.material.opacity = 0.4;
link.ui.geometry.verticesNeedUpdate = true;
//link.ui.geometry.elementsNeedUpdate = true;
//var distance = newSourcePos.distanceTo(newTargetPos);
//var position = newTargetPos.clone().add(newSourcePos).divideScalar(2);
//var orientation = new THREE.Matrix4();//a new orientation matrix to offset pivot
//var offsetRotation = new THREE.Matrix4();//a matrix to fix pivot rotation
//var offsetPosition = new THREE.Matrix4();//a matrix to fix pivot position
//orientation.lookAt(newSourcePos, newTargetPos, new THREE.Vector3(0,1,0));
//offsetRotation.makeRotationX(HALF_PI);//rotate 90 degs on X
//orientation.multiply(offsetRotation);//combine orientation with rotation transformations
//var cylinder = link.ui.geometry;//new THREE.CylinderGeometry(1.2,1.2,distance,1,1,false);
////cylinder.applyMatrix(orientation);
//link.ui.scale.y = distance;
//link.ui.geometry = cylinder;
//link.ui.position.set(position.x, position.y, position.z);
//console.log("After");
//console.log(link.ui);
});
} else {
edges.forEach(function ( edge ) {
var toID = edge.data.target.substring(2);
var fromID = edge.data.source.substring(2);
var link = state.elements.elements[ 'e' + fromID + toID ];
var from = state.elements.elements[ edge.data.source ];
var to = state.elements.elements[ edge.data.target ];
link.ui.geometry.vertices[0].set(from.ui.position.x,
from.ui.position.y,
from.ui.position.z);
link.ui.geometry.vertices[1].set(to.ui.position.x,
to.ui.position.y,
to.ui.position.z);
link.ui.geometry.verticesNeedUpdate = true;
});
}
state.renderer.render(state.scene, state.camera);
}
function rebuildUI () {
//Object.keys(nodeUI).forEach(function (nodeId) {
// scene.remove(nodeUI[nodeId]);
//});
//nodeUI = {};
//
//Object.keys(linkUI).forEach(function (linkId) {
// scene.remove(linkUI[linkId]);
//});
//linkUI = {};
//
//
//network.get( 'nodes' ).forEach(function (n) {
// createNodeUI(n);
//});
//network.get( 'edges' ).forEach(function (e) {
// createLinkUI(e);
//});
// Remove old UI
nodes.forEach(function (n) {
var node = state.elements.elements['nl' + n.data.id];
state.scene.remove(node.ui);
node.ui = undefined;
});
edges.forEach(function (e) {
var toID = e.data.target.substring(2);
var fromID = e.data.source.substring(2);
var link = state.elements.elements[ 'e' + fromID + toID ];
state.scene.remove(link.ui);
link.ui = undefined;
});
// Create new UI
nodes.forEach(function (n) {
createNodeUI(state.elements.elements['nl' + n.data.id]);
});
edges.forEach(function (e) {
var toID = e.data.target.substring(2);
var fromID = e.data.source.substring(2);
var link = state.elements.elements[ 'e' + fromID + toID ];
createLinkUI(link);
});
}
/**
* Check if the given Layout was already instantiated or is only a name.
* If a name -> create new Layout
* @param state
* @returns {*}
*/
function createLayout ( state ) {
var input = state.layout;
input = input === undefined ? 'ForceDirectedLayered' : input.name;
network = state.elements;
console.log(state);
if ( typeof input === 'string' ) {
var layout;
if ( input === 'Fixed' ) {
console.log(state.physicsSettings);
return new Fixed( network, state );
}
if ( input === 'ForceDirectedLayered' ) {
return new ForceDirectedLayered( network, state );
}
if ( input === 'ForceDirected' ) {
return new ForceDirected(network, settings);
}
if ( input === 'Manual' ) {
return new Manual( state.elements );
}
} else if ( input ) {
return input;
}
throw new Error ( "The layout " + input + " could not be created!" );
}
return {
THREE: THREE,
run: run,
resetStable: function () {
stable = false;
layout.resetStable();
},
/**
* You can set the nodeUIBuilder function yourself
* allowing for custom UI settings
* @param callback
*/
setNodeUI: function (callback) {
nodeUIBuilder = callback;
rebuildUI();
return this;
},
/**
* You can set the nodeUIBuilder function yourself
* allowing for custom UI settings
* @param callback
*/
setLinkUI: function (callback) {
linkUIBuilder = callback;
rebuildUI();
return this;
}
};
/**
* Create the three.js renderer
* @param container
* @returns {*}
*/
function createRenderer ( container ) {
var webGlSupport = webgl_detect();
var renderer = webGlSupport ? new THREE.WebGLRenderer( { container: container, antialias: true } ) : new THREE.CanvasRenderer( container );
var width = container.clientWidth || window.innerWidth;
var height = container.clientHeight || window.innerHeight;
renderer.setSize( width, height );
renderer.setClearColor( 0xffffff, 1 );
console.log(renderer);
if ( container ) {
container.appendChild( renderer.domElement );
} else {
document.body.appendChild( renderer.domElement );
}
return renderer;
}
/**
* http://stackoverflow.com/questions/11871077/proper-way-to-detect-webgl-support
* @param return_context
* @returns {*}
*/
function webgl_detect(return_context) {
if (!!window.WebGLRenderingContext) {
var canvas = document.createElement("canvas"),
names = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"],
context = false;
for(var i=0;i<4;i++) {
try {
context = canvas.getContext(names[i]);
if (context && typeof context.getParameter == "function") {
// WebGL is enabled
if (return_context) {
// return WebGL object if the function's argument is present
return {name:names[i], gl:context};
}
// else, return just true
return true;
}
} catch(e) {}
}
// WebGL is supported, but disabled
return false;
}
// WebGL not supported
return false;
}
}
module.exports = Graphics;
| DennisSchwartz/biojs-vis-munavi | lib/graphics.js | JavaScript | mit | 16,458 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({zoom:"P\u0159ibl\u00ed\u017eit na",next:"Dal\u0161\u00ed prvek",previous:"P\u0159edchoz\u00ed prvek",close:"Zav\u0159\u00edt",dock:"Ukotvit",undock:"Zru\u0161it ukotven\u00ed",menu:"Nab\u00eddka",untitled:"Bez n\u00e1zvu",pageText:"{index} z {total}",selectedFeature:"Vybran\u00fd prvek",selectedFeatures:"{total} v\u00fdsledk\u016f",loading:"Na\u010d\u00edt\u00e1n\u00ed",collapse:"Sbalit",expand:"Rozbalit"}); | ycabon/presentations | 2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/widgets/Popup/nls/cs/Popup.js | JavaScript | mit | 575 |
const minimatch = require( "minimatch" );
const webpack = require( "webpack" );
const _ = require( "lodash" );
module.exports = function( options ) {
function isMatchingModule( mod ) {
return mod.resource && _.some( options.paths, path => minimatch( mod.resource, path ) );
}
return new webpack.optimize.CommonsChunkPlugin( {
name: options.name,
filename: options.filename,
minChunks: isMatchingModule
} );
};
| LeanKit-Labs/nonstop-index-ui | tasks/tools/pathChunkingPlugin.js | JavaScript | mit | 424 |
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var ID = {};
ID.uuid = function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
// A more performant, but slightly bulkier, RFC4122v4 solution. We boost performance
// by minimizing calls to random()
ID.uuidFast = function() {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i==23) {
uuid[i] = '-';
} else if (i==14) {
uuid[i] = '4';
} else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
// A more compact, but less performant, RFC4122v4 solution:
ID.uuidCompact = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
module.exports = ID; | blackjk3/react-form-builder | src/UUID.js | JavaScript | mit | 1,663 |
// ==UserScript==
// @name mineAI
// @namespace minesAI
// @include http://minesweeperonline.com/#beginner-night
// @version 1
// @required http://localhost:8000/convnetjs.js
// @grant none
// ==/UserScript==
// Load the library.
var D = document;
var appTarg = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
var jsNode = D.createElement ('script');
jsNode.src = 'http://localhost:8000/convnetjs.js';
jsNode.addEventListener ("load", initConvNetJsOnDelay, false);
appTarg.appendChild (jsNode);
// Allow some time for the library to initialize after loading.
function initConvNetJsOnDelay () {
setTimeout (initConvNetJs, 666);
}
// Call the library's start-up function, if any. Note needed use of unsafeWindow.
function initConvNetJs () {
// species a 2-layer neural network with one hidden layer of 20 neurons
var layer_defs = [];
// ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images
// then the first two dimensions (sx, sy) will always be kept at size 1
layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2});
// declare 4 neurons, followed by ReLU (rectified linear unit non-linearity)
layer_defs.push({type:'fc', num_neurons:4, activation:'relu'});
// 3 more for good measure
layer_defs.push({type:'fc', num_neurons:3, activation:'relu'});
// declare the linear classifier on top of the previous hidden layer
layer_defs.push({type:'softmax', num_classes:2});
// defined our net with unsafeWindow for use in GreaseMonkey
var net = new unsafeWindow.convnetjs.Net();
// create our net with layers as defined above
net.makeLayers(layer_defs);
// define trainer
var trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, l2_decay:0.001});
// define inputs (XOR)
var t1 = new convnetjs.Vol([0, 0]); // class 0
var t2 = new convnetjs.Vol([0, 1]); // class 1
var t3 = new convnetjs.Vol([1, 0]); // class 1
var t4 = new convnetjs.Vol([1, 1]); // class 0
// train for 1000 iterations with corresponding classes
for (var i = 0; i < 1000; i++) {
trainer.train(t1, 0);
trainer.train(t2, 1);
trainer.train(t3, 1);
trainer.train(t4, 0);
}
// learned probability
var prob00 = net.forward(t1);
var prob01 = net.forward(t2);
var prob10 = net.forward(t3);
var prob11 = net.forward(t4);
// log probability
console.log('p(0 | 00): ' + prob00.w[0] + ", p(1 | 00): " + prob00.w[1]);
console.log('p(0 | 01): ' + prob01.w[0] + ", p(1 | 01): " + prob01.w[1]);
console.log('p(0 | 10): ' + prob10.w[0] + ", p(1 | 10): " + prob10.w[1]);
console.log('p(0 | 11): ' + prob11.w[0] + ", p(1 | 11): " + prob11.w[1]);
}
alert("Done"); | cirquit/Personal-Repository | JS/minesweeper/minesweeperNN.js | JavaScript | mit | 2,855 |
var test = require('tst')
var assert = require('assert')
var noise = require('..')
test('white noise', () => {
assert(typeof noise.white() === 'function')
})
test('pink noise', () => {
assert(typeof noise.pink() === 'function')
})
test('brown noise', () => {
assert(typeof noise.pink() === 'function')
})
| oramics/dsp-kit | packages/noise/test/test.js | JavaScript | mit | 314 |
define(function () { 'use strict';
({
get foo () {
console.log( 'effect' );
return {};
}
}).foo.bar;
({
get foo () {
return {};
}
}).foo.bar.baz;
({
get foo () {
console.log( 'effect' );
return () => {};
}
}).foo();
({
get foo () {
return () => console.log( 'effect' );
}
}).foo();
({
get foo () {
console.log( 'effect' );
return () => () => {};
}
}).foo()();
({
get foo () {
return () => () => console.log( 'effect' );
}
}).foo()();
});
| corneliusweig/rollup | test/form/samples/getter-return-values/_expected/amd.js | JavaScript | mit | 503 |
import {module, inject, createRootFactory} from '../mocks';
describe('solPopmenu directive', function () {
let $compile;
let $rootScope;
let createRoot;
let rootEl;
beforeEach(module('karma.templates'));
beforeEach(module('ui-kit'));
beforeEach(inject((_$compile_, _$rootScope_) => {
$compile = _$compile_;
$rootScope = _$rootScope_;
createRoot = createRootFactory($compile);
let html = '<div><sol-popmenu icon="list">tranclusion</sol-popmenu></div>';
rootEl = createRoot(html, $rootScope);
}));
it('should replace the element', () => {
let menu = rootEl.find('.popmenu-popup .popmenu-content');
expect(rootEl).not.toContainElement('sol-popmenu');
});
it('should transclude content inside a ".popmenu-popup .popmenu-content" element', () => {
let menu = rootEl.find('.popmenu-popup .popmenu-content');
expect(menu).toHaveText('tranclusion');
});
it('should add "fa fa-<icon>" class on toggler according to icon attribute', () => {
let toggler = rootEl.find('.popmenu-toggler');
expect(toggler).toHaveClass('fa fa-list');
});
it('should toggle the "closed" class on .popmenu once the .popmenu-toggler clicked', () => {
let menu = rootEl.find('.popmenu');
let toggler = rootEl.find('.popmenu-toggler');
expect(menu).not.toHaveClass('closed');
toggler.click();
toggler.click();
$rootScope.$digest();
expect(menu).toHaveClass('closed');
});
it('contains a .popmenu-toggler element', () => {
let html = '<div><sol-popmenu></sol-popmenu></div>';
let rootEl = createRoot(html, $rootScope);
expect(rootEl).toContainElement('.popmenu-toggler');
});
it('contains a .popmenu element', () => {
let html = '<div><sol-popmenu></sol-popmenu></div>';
let rootEl = createRoot(html, $rootScope);
expect(rootEl).toContainElement('.popmenu');
});
});
| Tudmotu/solarizd | src/test/ui-kit/sol-popmenu.js | JavaScript | mit | 2,050 |
import React from 'react'
import Button from 'components/Button'
import Flex from 'components/Flex'
import { Explanation, TextStep, Buttons } from '../styles'
import explanation from 'images/bearing-explanation.svg'
export class Step extends React.Component {
render () {
return (
<TextStep>
<div>
<h2>Thanks!</h2>
<p>
If it’s clear which way the camera is pointing, you can go to the next
step and try marking the direction and angle of the view of the image.
</p>
<p>
<Explanation alt='Camera and target' title='Camera and target' src={explanation} />
</p>
</div>
<Buttons>
<Flex justifyContent='flex-end'>
<Button onClick={this.props.skip} type='skip'>Skip</Button>
<Button onClick={this.props.next} type='submit'>Continue</Button>
</Flex>
</Buttons>
</TextStep>
)
}
}
export default Step
| nypl-spacetime/where | app/containers/Steps/BearingIntroduction/index.js | JavaScript | mit | 985 |
export { default } from './ElectronOriginalWordmark'
| fpoumian/react-devicon | src/components/electron/original-wordmark/index.js | JavaScript | mit | 53 |
'use-strict';
var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm'];
var allLocations = [];
var theTable = document.getElementById('pike');
var el = document.getElementById('moreStores');
// var hourlyTotals = [];
// contructor for the Cookie Stores
function CookieStore(locationName, minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer) {
this.locationName = locationName;
this.minCustomersPerHour = minCustomersPerHour;
this.maxCustomersPerHour = maxCustomersPerHour;
this.avgCookiesPerCustomer = avgCookiesPerCustomer;
this.customersEachHour = [];
this.cookiesEachHour = [];
this.totalDaily = 0;
this.calcCustomersThisHour();
this.calcCookiesThisHour();
allLocations.push(this);
}
// creates total for customers each hour
CookieStore.prototype.calcCustomersThisHour = function() {
var reference = [];
for (var i = 0; i < hours.length; i++) {
var numberCustomersPerHour = Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour;
reference.push(numberCustomersPerHour);
}
this.customersEachHour = reference;
return numberCustomersPerHour;
};
// Creates total for daily cookie sales
CookieStore.prototype.calcCookiesThisHour = function() {
for (var j = 0; j < hours.length; j++) {
var totalCookieSales = Math.ceil(this.customersEachHour[j] * this.avgCookiesPerCustomer);
this.cookiesEachHour.push(totalCookieSales);
this.totalDaily += this.cookiesEachHour[j];
}
this.cookiesEachHour.push(this.totalDaily);
};
// creates table elements
function makeElement(type, content, parent){
// create
var newEl = document.createElement(type);
// content
newEl.textContent = content;
// append
parent.appendChild(newEl);
}
// Push hours to table header
var renderHeader = function() {
var trEL = document.createElement('tr');
var thEL = document.createElement('th');
thEL.textContent = 'Locations';
trEL.appendChild(thEL);
for (var i = 0; i < hours.length; i++) {
var thEL = document.createElement('th');
thEL.textContent = hours[i];
trEL.appendChild(thEL);
}
thEL = document.createElement('th');
thEL.textContent = 'Daily';
trEL.appendChild(thEL);
theTable.appendChild(trEL);
};
// Push totals to TD's in DOM
CookieStore.prototype.render = function() {
var trEL = document.createElement('tr');
var tdEL = document.createElement('td');
tdEL.textContent = this.locationName;
trEL.appendChild(tdEL);
for (var i = 0; i < hours.length + 1; i++) {
var tdEL = document.createElement('td');
tdEL.textContent = this.cookiesEachHour[i];
trEL.appendChild(tdEL);
}
theTable.appendChild(trEL);
};
// Footer TOTALLLLL
function renderFooter() {
var trEL = document.createElement('tr');
var thEL = document.createElement('th');
thEL.textContent = 'Total';
trEL.appendChild(thEL);
var totalOfTotals = 0;
var hourlyTotal = 0;
for (var i = 0; i < hours.length; i++) {
hourlyTotal = 0;
for (var j = 0; j < allLocations.length; j++) {
hourlyTotal += allLocations[j].cookiesEachHour[i];
totalOfTotals += allLocations[j].cookiesEachHour[i];
}
thEL = document.createElement('th');
thEL.textContent = hourlyTotal;
trEL.appendChild(thEL);
}
thEL = document.createElement('th');
thEL.textContent = totalOfTotals;
trEL.appendChild(thEL);
theTable.appendChild(trEL);
};
// passing new stores to the cookie store constructor
var pikePlace = new CookieStore('Pike Place Market', 23, 65, 6.3);
var seaTac = new CookieStore('Seatac', 3, 24, 1.2);
var seattleCenter = new CookieStore('Seattle Center', 11, 38, 3.7);
var capitolHill = new CookieStore('Capitol Hill', 20, 38, 2.3);
var alki = new CookieStore('Alki', 2, 16, 4.6);
// Renders the table
function renderTable(){
theTable.innerHTML = '';
renderHeader();
for (i = 0; i < allLocations.length; i++) {
allLocations[i].render();
}
renderFooter();
}
renderTable();
// Handler for listener
function handleStoreSubmit(event) {
event.preventDefault();
var newStoreLocation = event.target.storeLocation.value;
var minCustomers = parseInt(event.target.minCustomers.value);
var maxCustomers = parseInt(event.target.maxCustomers.value);
var avgCookie = parseFloat(event.target.avgCookiesSold.value);
console.log('go here');
// prevent empty
if(!newStoreLocation || !minCustomers || !maxCustomers || !avgCookie){
return alert('All fields must have a value');
}
//validate by type
if (typeof minCustomers !== 'number') {
return alert('Min customers must be a number');
}
// ignore case on store names
for(var i = 0; i < allLocations.length; i++){
if(newStoreLocation === allLocations[i].locationName) {
allLocations[i].minCustomersPerHour = minCustomers;
allLocations[i].maxCustomersPerHour = maxCustomers;
allLocations[i].avgCookiesPerCustomer = avgCookie;
clearForm();
allLocations[i].totalDaily = 0;
allLocations[i].customersEachHour = [];
allLocations[i].cookiesEachHour = [];
allLocations[i].calcCustomersThisHour();
allLocations[i].calcCookiesThisHour();
console.log('A match was found at index', allLocations[i]);
renderTable();
return;
}
}
new CookieStore(newStoreLocation, minCustomers, maxCustomers, avgCookie);
function clearForm(){
event.target.storeLocation.value = null;
event.target.minCustomers.value = null;
event.target.maxCustomers.value = null;
event.target.avgCookiesSold.value = null;
}
clearForm();
// for(var i = allLocations.length - 1; i < allLocations.length; i++){
// allLocations[i].render();
// }
renderTable();
};
// Listener code
el.addEventListener('submit', handleStoreSubmit);
| ianwaites/fish-cookies | JS/app.js | JavaScript | mit | 5,853 |
var express = require('express');
var router = express.Router();
// Play a game from the DB
router.get('/games', function (req, res) {
res.render('games', data);
});
module.exports = router; | jrburga/jsvgdl | routes/games.js | JavaScript | mit | 193 |
import React from 'react';
import ReactTouchPosition from '../../../dist/ReactTouchPosition';
import TouchPositionLabel from './TouchPositionLabel';
import OnPositionChangedLabel from './OnPositionChangedLabel';
import InstructionsLabel from './InstructionsLabel';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
isPositionOutside: true,
touchPosition: {
x: 0,
y: 0,
}
}
}
render() {
return (
<div className="example-container">
<ReactTouchPosition {...{
className: 'example',
onPositionChanged: ({ isPositionOutside, touchPosition }) => {
this.setState({
isPositionOutside,
touchPosition
});
},
shouldDecorateChildren: false
}}>
<TouchPositionLabel />
<InstructionsLabel />
</ReactTouchPosition>
<OnPositionChangedLabel {...this.state} />
</div>
);
}
}
| ethanselzer/react-touch-position | example/src/components/ShouldDecorateChildren.js | JavaScript | mit | 1,244 |
/**
* React Starter Kit for Firebase
* https://github.com/kriasoft/react-firebase-starter
* Copyright (c) 2015-present Kriasoft | MIT License
*/
import { graphql } from 'graphql';
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
import schema from './schema';
import { Context } from './context';
export function createRelay(req) {
function fetchQuery(operation, variables, cacheConfig) {
return graphql({
schema,
source: operation.text,
contextValue: new Context(req),
variableValues: variables,
operationName: operation.name,
}).then(payload => {
// Passes the raw payload up to the caller (see src/router.js).
// This is needed in order to hydrate/de-hydrate that
// data on the client during the initial page load.
cacheConfig.payload = payload;
return payload;
});
}
const recordSource = new RecordSource();
const store = new Store(recordSource);
const network = Network.create(fetchQuery);
return new Environment({ store, network });
}
| kriasoft/react-static-boilerplate | src/server/relay.js | JavaScript | mit | 1,061 |
import { Feature } from 'core/feature';
import * as toolkitHelper from 'helpers/toolkit';
export class TargetBalanceWarning extends Feature {
constructor() {
super();
}
shouldInvoke() {
return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1;
}
invoke() {
$('.budget-table-row.is-sub-category').each((index, element) => {
const emberId = element.id;
const viewData = toolkitHelper.getEmberView(emberId).data;
const { subCategory } = viewData;
if (subCategory.get('goalType') === ynab.constants.SubCategoryGoalType.TargetBalance) {
const available = viewData.get('available');
const targetBalance = subCategory.get('targetBalance');
const currencyElement = $('.budget-table-cell-available .user-data.currency', element);
if (available < targetBalance && !currencyElement.hasClass('cautious')) {
if (currencyElement.hasClass('positive')) {
currencyElement.removeClass('positive');
}
currencyElement.addClass('cautious');
}
}
});
}
observe(changedNodes) {
if (!this.shouldInvoke()) return;
if (changedNodes.has('budget-table-cell-available-div user-data')) {
this.invoke();
}
}
onRouteChanged() {
if (!this.shouldInvoke()) return;
this.invoke();
}
}
| egens/toolkit-for-ynab | sauce/features/budget/target-balance-warning/index.js | JavaScript | mit | 1,342 |
angular.module('kindly.requests').directive('request', function() {
return {
restrict: 'E',
replace: true,
scope: {
request: '='
},
controller: function($scope) {
$scope.is = function(medium) {
return $scope.request.medium === medium;
};
},
templateUrl: 'requests/_request.html'
};
});
| jsvana/WouldYouKindly | app/assets/javascripts/requests/request.directive.js | JavaScript | mit | 344 |
/**
* @license Copyright (c) 2013, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* A card entity.
*/
define([ 'framework/entity/base_entity' ],
function(BaseEntity)
{
/**
* Constructor.
* @param rawObject (optional)
* The raw object to create the entity with.
*/
var Card = function(rawObject)
{
this.name = null;
this.color = null;
BaseEntity.call(this, rawObject);
return this;
};
Card.prototype = new BaseEntity();
BaseEntity.generateProperties(Card);
// The card rarities.
Card.RARITY = {};
Card.RARITY.MYTHIC = 'M';
Card.RARITY.RARE = 'R';
Card.RARITY.UNCOMMON = 'U';
Card.RARITY.COMMON = 'C';
Card.RARITY.LAND = 'L';
return Card;
}); | DragonDTG/vex | lib/public/static/scripts/domain/entity/card.js | JavaScript | mit | 715 |
import Ember from 'ember';
import ObjectProxyMixin from '../mixins/object';
export default Ember.ObjectProxy.extend(ObjectProxyMixin, {
_storageType: 'session'
});
| DanielJRaine/employee-forms-auth | node_modules/ember-local-storage/addon/session/object.js | JavaScript | mit | 167 |
class Auth {
isAuthenticate () {
return this.getToken() !== null
}
setToken (token) {
window.localStorage.setItem('access_token', token)
}
getToken () {
return window.localStorage.getItem('access_token')
}
removeToken () {
window.localStorage.removeItem('access_token')
}
}
export default new Auth()
| dvt32/cpp-journey | Java/Uni-Ruse/Web Components - Spring Boot & React (Master's Degree)/forum_frontend/src/services/Auth.js | JavaScript | mit | 336 |
'use strict'
// import Device from './Device'
let Device = require('./Device').Device
module.exports = {
Device: Device
}
| swissglider/node-red-device-framework | core/runtime/devices/index.js | JavaScript | mit | 125 |
(function (window, $, _, Concrete) {
'use strict';
/**
* Area object, used for managing areas
* @param {jQuery} elem The area's HTML element
* @param {EditMode} edit_mode The EditMode instance
*/
var Area = Concrete.Area = function Area(elem, edit_mode) {
this.init.apply(this, _(arguments).toArray());
};
Area.prototype = {
init: function areaInit(elem, edit_mode) {
var my = this;
elem.data('Concrete.area', my);
Concrete.createGetterSetters.call(my, {
id: elem.data('area-id'),
active: true,
blockTemplate: _(elem.children('script[role=area-block-wrapper]').html()).template(),
elem: elem,
totalBlocks: 0,
enableGridContainer: elem.data('area-enable-grid-container'),
handle: elem.data('area-handle'),
dragAreas: [],
blocks: [],
editMode: edit_mode,
maximumBlocks: parseInt(elem.data('maximumBlocks'), 10),
blockTypes: elem.data('accepts-block-types').split(' '),
blockContainer: elem.children('.ccm-area-block-list')
});
my.id = my.getId();
my.setTotalBlocks(0); // we also need to update the DOM which this does.
},
/**
* Handle unbinding.
*/
destroy: function areaDestroy() {
var my = this;
if (my.getAttr('menu')) {
my.getAttr('menu').destroy();
}
my.reset();
},
reset: function areaReset() {
var my = this;
_(my.getDragAreas()).each(function (drag_area) {
drag_area.destroy();
});
_(my.getBlocks()).each(function (block) {
block.destroy();
});
my.setBlocks([]);
my.setDragAreas([]);
my.setTotalBlocks(0);
},
bindEvent: function areaBindEvent(event, handler) {
return Concrete.EditMode.prototype.bindEvent.apply(this, _(arguments).toArray());
},
scanBlocks: function areaScanBlocks() {
var my = this, type, block;
my.reset();
my.addDragArea(null);
$('div.ccm-block-edit[data-area-id=' + my.getId() + ']', this.getElem()).each(function () {
var me = $(this), handle = me.data('block-type-handle');
if (handle === 'core_area_layout') {
type = Concrete.Layout;
} else {
type = Concrete.Block;
}
block = new type(me, my);
my.addBlock(block);
});
},
getBlockByID: function areaGetBlockByID(bID) {
var my = this;
return _.findWhere(my.getBlocks(), {id: bID});
},
getMenuElem: function areaGetMenuElem() {
var my = this;
return $('[data-area-menu=area-menu-a' + my.getId() + ']');
},
bindMenu: function areaBindMenu() {
var my = this,
elem = my.getElem(),
totalBlocks = my.getTotalBlocks(),
$menuElem = my.getMenuElem(),
menuHandle;
if (totalBlocks > 0) {
menuHandle = '#area-menu-footer-' + my.getId();
} else {
menuHandle = 'div[data-area-menu-handle=' + my.getId() + ']';
}
if (my.getAttr('menu')) {
my.getAttr('menu').destroy();
}
var menu_config = {
'handle': menuHandle,
'highlightClassName': 'ccm-area-highlight',
'menuActiveClass': 'ccm-area-highlight',
'menu': $('[data-area-menu=' + elem.attr('data-launch-area-menu') + ']')
};
if (my.getElem().hasClass('ccm-global-area')) {
menu_config.menuActiveClass += " ccm-global-area-highlight";
menu_config.highlightClassName += " ccm-global-area-highlight";
}
my.setAttr('menu', new ConcreteMenu(elem, menu_config));
$menuElem.find('a[data-menu-action=add-inline]')
.off('click.edit-mode')
.on('click.edit-mode', function (e) {
// we are going to place this at the END of the list.
var dragAreaLastBlock = false;
_.each(my.getBlocks(), function (block) {
dragAreaLastBlock = block;
});
Concrete.event.fire('EditModeBlockAddInline', {
area: my,
cID: CCM_CID,
btID: $(this).data('block-type-id'),
arGridMaximumColumns: $(this).attr('data-area-grid-maximum-columns'),
event: e,
dragAreaBlock: dragAreaLastBlock,
btHandle: $(this).data('block-type-handle')
});
return false;
});
$menuElem.find('a[data-menu-action=edit-container-layout]')
.off('click.edit-mode')
.on('click.edit-mode', function (e) {
// we are going to place this at the END of the list.
var $link = $(this);
var bID = parseInt($(this).attr('data-container-layout-block-id'));
var editor = Concrete.getEditMode();
var block = _.findWhere(editor.getBlocks(), {id: bID});
Concrete.event.fire('EditModeBlockEditInline', {
block: block,
arGridMaximumColumns: $link.attr('data-area-grid-maximum-columns'),
event: e
});
return false;
});
$menuElem.find('a[data-menu-action=edit-area-design]')
.off('click.edit-mode')
.on('click.edit-mode', function (e) {
e.preventDefault();
ConcreteToolbar.disable();
my.getElem().addClass('ccm-area-inline-edit-disabled');
var postData = {
'arHandle': my.getHandle(),
'cID': CCM_CID
};
my.bindEvent('EditModeExitInline', function (e) {
Concrete.event.unsubscribe(e);
my.getEditMode().destroyInlineEditModeToolbars();
});
$.ajax({
type: 'GET',
url: CCM_DISPATCHER_FILENAME + '/ccm/system/dialogs/area/design',
data: postData,
success: function (r) {
var $container = my.getElem();
my.getEditMode().loadInlineEditModeToolbars($container, r);
$.fn.dialog.hideLoader();
}
});
});
},
/**
* Add block to area
* @param {Block} block block to add
* @param {Block} sub_block The block that should be above the added block
* @return {Boolean} Success, always true
*/
addBlock: function areaAddBlock(block, sub_block) {
var my = this;
if (sub_block) {
return this.addBlockToIndex(block, _(my.getBlocks()).indexOf(sub_block) + 1);
}
return this.addBlockToIndex(block, my.getBlocks().length);
},
setTotalBlocks: function (totalBlocks) {
this.setAttr('totalBlocks', totalBlocks);
this.getElem().attr('data-total-blocks', totalBlocks);
},
/**
* Add to specific index, pipes to addBlock
* @param {Block} block Block to add
* @param {int} index Index to add to
* @return {Boolean} Success, always true
*/
addBlockToIndex: function areaAddBlockToIndex(block, index) {
var totalBlocks = this.getTotalBlocks(),
blocks = this.getBlocks(),
totalHigherBlocks = totalBlocks - index;
block.setArea(this);
this.setTotalBlocks(totalBlocks + 1);
// any blocks with indexes higher than this one need to have them incremented
if (totalHigherBlocks > 0) {
var updateBlocksArray = [];
for (var i = 0; i < blocks.length; i++) {
if (i >= index) {
updateBlocksArray[i + 1] = blocks[i];
} else {
updateBlocksArray[i] = blocks[i];
}
}
updateBlocksArray[index] = block;
this.setBlocks(updateBlocksArray);
} else {
this.getBlocks()[index] = block;
}
this.addDragArea(block);
// ensure that the DOM attributes are correct
block.getElem().attr("data-area-id", this.getId());
return true;
},
/**
* Remove block from area
* @param {Block} block The block to remove.
* @return {Boolean} Success, always true.
*/
removeBlock: function areaRemoveBlock(block) {
var my = this, totalBlocks = my.getTotalBlocks();
block.getContainer().remove();
my.setBlocks(_(my.getBlocks()).without(block));
my.setTotalBlocks(totalBlocks - 1);
var drag_area = _.first(_(my.getDragAreas()).filter(function (drag_area) {
return drag_area.getBlock() === block;
}));
if (drag_area) {
drag_area.getElem().remove();
my.setDragAreas(_(my.getDragAreas()).without(drag_area));
}
if (!my.getTotalBlocks()) {
// we have to destroy the old menu and create it anew
my.bindMenu();
}
return true;
},
/**
* Add a drag area
* @param {Block} block The block to add this area below.
* @return {DragArea} The added DragArea
*/
addDragArea: function areaAddDragArea(block) {
var my = this, elem, drag_area;
if (!block) {
if (my.getDragAreas().length) {
throw new Error('No block supplied');
}
elem = $('<div class="ccm-area-drag-area"/>');
drag_area = new Concrete.DragArea(elem, my, block);
my.getBlockContainer().prepend(elem);
} else {
elem = $('<div class="ccm-area-drag-area"/>');
drag_area = new Concrete.DragArea(elem, my, block);
block.getContainer().after(elem);
}
my.getDragAreas().push(drag_area);
return drag_area;
},
/**
* Find the contending DragArea's
* @param {Pep} pep The Pep object from the event.
* @param {Block|Stack} block The Block object from the event.
* @return {Array} Array of all drag areas that are capable of accepting the block.
*/
contendingDragAreas: function areaContendingDragAreas(pep, block) {
var my = this, max_blocks = my.getMaximumBlocks();
if (block instanceof Concrete.Stack || block.getHandle() === 'core_stack_display') {
return _(my.getDragAreas()).filter(function (drag_area) {
return drag_area.isContender(pep, block);
});
} else if ((max_blocks > 0 && my.getBlocks().length >= max_blocks) || !_(my.getBlockTypes()).contains(block.getHandle())) {
return [];
}
return _(my.getDragAreas()).filter(function (drag_area) {
return drag_area.isContender(pep, block);
});
}
};
}(window, jQuery, _, Concrete));
| victorli/cms | concrete/js/build/core/app/edit-mode/area.js | JavaScript | mit | 12,327 |
//= require active_admin/base
//= require jquery.nested-fields
//= require chosen-jquery
//= require bootstrap
//= require bootstrap-wysihtml5
//= require ./active_tweaker
| atongen/active_tweaker | app/assets/javascripts/active_tweaker/index.js | JavaScript | mit | 172 |
import '../../../../css/rpt/styles.global.css';
import styles from '../../../css/rpt/styles.css';
import React, { Component, PropTypes } from 'react';
import 'react-widgets/lib/less/react-widgets.less';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Multiselect from 'react-widgets/lib/Multiselect';
import { FormGroup,FormControl,HelpBlock,Checkbox,ControlLabel,Label,Row,Col,ListGroup,ListGroupItem,Panel,Table,Button,Glyphicon,ButtonGroup,ButtonToolbar} from 'react-bootstrap';
import { ButtonInput } from 'react-bootstrap';
import * as STATE from "../../../actions/rpt/production/State.js"
var dateFormat = require('dateformat');
var Moment = require('moment');
var momentLocalizer = require('react-widgets/lib/localizers/moment');
var classNames = require('classnames');
momentLocalizer(Moment);
export default class POWithReceiversDateRange extends React.Component {
static propTypes = {
ProdRpt: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
test:this.test.bind(this)
};
if ('development'==process.env.NODE_ENV) {
}
}
test(dt,dateStart,dateEnd){
console.log(`dt: ${dt}`);
var dtStart = dateFormat(new Date(dt), "mm-dd-yyyy hh:MM:ss");
if ('development'==process.env.NODE_ENV) {
console.log(`dtStart=>${dtStart}`);
}
var dtStartFmt = dateFormat(new Date(dateStart), "mm-dd-yyyy hh:MM:ss");
if ('development'==process.env.NODE_ENV) {
console.log(`dtStartFmt=>${dtStartFmt}`);
}
var dtEndFmt = dateFormat(new Date(dateEnd), "mm-dd-yyyy hh:MM:ss");
if ('development'==process.env.NODE_ENV) {
console.log(`dtEndFmt=>${dtEndFmt}`);
}
}
render() {
var runAndBackBtn;
if(STATE.POWITHRECEIVERS_DATE_RANGE_NOT_READY==this.props.Rpt.state){
runAndBackBtn =
<Row>
<Col xs={4} > </Col>
<Col xs={1}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" disabled>Run</Button></Col>
<Col xs={1} > </Col>
<Col xs={2}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col>
<Col xs={3}> </Col>
</Row>
}else{
runAndBackBtn =
<Row>
<Col xs={4} > </Col>
<Col xs={2}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" >Run</Button></Col>
<Col xs={1}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col>
<Col xs={3}> </Col>
</Row>
}
var pageNoClass = classNames(
'pagination','hidden-xs', 'pull-left'
);
var dateHeader;
var dateStyle;
if(this.props.ProdRpt.openPOWithReceivers.dateHeader.valid){
dateHeader=<h3 style={{textAlign:'center'}}>{this.props.ProdRpt.poWithReceivers.dateHeader.text}</h3>
dateStyle='default';
}else{
dateHeader=<h3 style={{textAlign:'center',color:'red !important'}}>{this.props.ProdRpt.openPOWithReceivers.dateHeader.text}</h3>
dateStyle='danger';
}
return (
<div>
<Panel bsStyle={dateStyle} header={dateHeader}>
<Row>
<Col xs={1} >
<h1 style={{marginTop:0}}><Label bsStyle="primary">Start</Label></h1>
</Col>
<Col xs={8} xsOffset={1} style={{}}>
<DateTimePicker
onChange={(name,value)=>{
this.state.test(name,this.props.ProdRpt.poWithReceivers.dateStart,this.props.ProdRpt.openPOWithReceivers.dateEnd);
this.props.setPOWithReceiversDateStart(name);
this.props.poWithReceiversDateRange();
}}
defaultValue={this.props.ProdRpt.openPOWithReceivers.dateStart} />
</Col>
</Row>
<Row>
<Col xs={1}>
<h1 style={{marginTop:0}}><Label bsStyle="primary">End</Label></h1>
</Col>
<Col xs={8} xsOffset={1}>
<DateTimePicker
onChange={(name,value)=>{
this.props.setPOWithReceiversDateEnd(name);
this.props.poWithReceiversDateRange();
}}
defaultValue={this.props.ProdRpt.poWithReceivers.dateEnd} />
</Col>
</Row>
</Panel>
{runAndBackBtn}
</div>
);
}
}
| robogroves/ebp | app/components/rpt/production/POWithReceivers/poWithReceiversDateRange.js | JavaScript | mit | 4,407 |
/*! Pushy - v0.9.1 - 2013-9-16
* Pushy is a responsive off-canvas navigation menu using CSS transforms & transitions.
* https://github.com/christophery/pushy/
* by Christopher Yee */
$(window).load(function () {
var e = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
e = true
}
if (e == false) {
menuBtn = $('.menu-btn-left') //css classes to toggle the menu
} else {
menuBtn = $('.menu-btn-left, .pushy a') //css classes to toggle the menu
}
$(function() {
var pushy = $('.pushy'), //menu css class
body = $('body'),
container = $('#wrapper'), //container css class
container2 = $('section#home'), //container css class
push = $('.push-left'), //css class to add pushy capability
siteOverlay = $('.site-overlay'), //site overlay
pushyClass = "pushy-left pushy-open-left", //menu position & menu open class
pushyActiveClass = "pushy-active", //css class to toggle site overlay
containerClass = "container-push-left", //container open class
pushClass = "push-push-left", //css class to add pushy capability
//menuBtn = $('.menu-btn-left'), //css classes to toggle the menu
menuSpeed = 200, //jQuery fallback menu speed
menuWidth = pushy.width() + "px"; //jQuery fallback menu width
function togglePushy(){
body.toggleClass(pushyActiveClass); //toggle site overlay
pushy.toggleClass(pushyClass);
container.toggleClass(containerClass);
container2.toggleClass(containerClass);
push.toggleClass(pushClass); //css class to add pushy capability
}
function openPushyFallback(){
body.addClass(pushyActiveClass);
pushy.animate({left: "0px"}, menuSpeed);
container.animate({left: menuWidth}, menuSpeed);
push.animate({left: menuWidth}, menuSpeed); //css class to add pushy capability
}
function closePushyFallback(){
body.removeClass(pushyActiveClass);
pushy.animate({left: "-" + menuWidth}, menuSpeed);
container.animate({left: "0px"}, menuSpeed);
push.animate({left: "0px"}, menuSpeed); //css class to add pushy capability
}
if(Modernizr.csstransforms3d){
//toggle menu
menuBtn.click(function() {
togglePushy();
});
//close menu when clicking site overlay
siteOverlay.click(function(){
togglePushy();
});
}else{
//jQuery fallback
pushy.css({left: "-" + menuWidth}); //hide menu by default
container.css({"overflow-x": "hidden"}); //fixes IE scrollbar issue
//keep track of menu state (open/close)
var state = true;
//toggle menu
menuBtn.click(function() {
if (state) {
openPushyFallback();
state = false;
} else {
closePushyFallback();
state = true;
}
});
//close menu when clicking site overlay
siteOverlay.click(function(){
if (state) {
openPushyFallback();
state = false;
} else {
closePushyFallback();
state = true;
}
});
}
});
}); | ChekHub/chekhub.github.io | js/pushy_left.js | JavaScript | mit | 2,897 |
/* eslint-env mocha */
/* eslint-disable func-names, prefer-arrow-callback */
import mainContent from '../pageobjects/main-content.page';
import sideNav from '../pageobjects/side-nav.page';
describe.skip('emoji', ()=> {
it('opens general', ()=> {
sideNav.openChannel('general');
});
it('opens emoji menu', ()=> {
mainContent.emojiBtn.click();
});
describe('render', ()=> {
it('should show the emoji picker menu', ()=> {
mainContent.emojiPickerMainScreen.isVisible().should.be.true;
});
it('click the emoji picker people tab', ()=> {
mainContent.emojiPickerPeopleIcon.click();
});
it('should show the emoji picker people tab', ()=> {
mainContent.emojiPickerPeopleIcon.isVisible().should.be.true;
});
it('should show the emoji picker nature tab', ()=> {
mainContent.emojiPickerNatureIcon.isVisible().should.be.true;
});
it('should show the emoji picker food tab', ()=> {
mainContent.emojiPickerFoodIcon.isVisible().should.be.true;
});
it('should show the emoji picker activity tab', ()=> {
mainContent.emojiPickerActivityIcon.isVisible().should.be.true;
});
it('should show the emoji picker travel tab', ()=> {
mainContent.emojiPickerTravelIcon.isVisible().should.be.true;
});
it('should show the emoji picker objects tab', ()=> {
mainContent.emojiPickerObjectsIcon.isVisible().should.be.true;
});
it('should show the emoji picker symbols tab', ()=> {
mainContent.emojiPickerSymbolsIcon.isVisible().should.be.true;
});
it('should show the emoji picker flags tab', ()=> {
mainContent.emojiPickerFlagsIcon.isVisible().should.be.true;
});
it('should show the emoji picker custom tab', ()=> {
mainContent.emojiPickerCustomIcon.isVisible().should.be.true;
});
it('should show the emoji picker change tone button', ()=> {
mainContent.emojiPickerChangeTone.isVisible().should.be.true;
});
it('should show the emoji picker search bar', ()=> {
mainContent.emojiPickerFilter.isVisible().should.be.true;
});
it('send a smile emoji', ()=> {
mainContent.emojiSmile.click();
});
it('the value on the message input should be the same as the emoji clicked', ()=> {
mainContent.messageInput.getValue().should.equal(':smile:');
});
it('send the emoji', ()=> {
mainContent.addTextToInput(' ');
mainContent.sendBtn.click();
});
it('the value on the message should be the same as the emoji clicked', ()=> {
mainContent.lastMessage.getText().should.equal('😄');
});
it('adds emoji text to the message input', ()=> {
mainContent.addTextToInput(':smile');
});
it('should show the emoji popup bar', ()=> {
mainContent.messagePopUp.isVisible().should.be.true;
});
it('the emoji popup bar title should be emoji', ()=> {
mainContent.messagePopUpTitle.getText().should.equal('Emoji');
});
it('should show the emoji popup bar items', ()=> {
mainContent.messagePopUpItems.isVisible().should.be.true;
});
it('click the first emoji on the popup list', ()=> {
mainContent.messagePopUpFirstItem.click();
});
it('the value on the message input should be the same as the emoji clicked', ()=> {
mainContent.messageInput.getValue().should.equal(':smile:');
});
it('send the emoji', ()=> {
mainContent.sendBtn.click();
});
it('the value on the message should be the same as the emoji clicked', ()=> {
mainContent.lastMessage.getText().should.equal('😄');
});
});
});
| karlprieb/Rocket.Chat | tests/steps/5-emoji.js | JavaScript | mit | 3,445 |
module.exports = function(config) {
config.set({
basePath: './',
frameworks: ['systemjs', 'jasmine'],
systemjs: {
configFile: 'config.js',
config: {
paths: {
"*": null,
"src/*": "src/*",
"typescript": "node_modules/typescript/lib/typescript.js",
"systemjs": "node_modules/systemjs/dist/system.js",
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js'
},
packages: {
'test/unit': {
defaultExtension: 'ts'
},
'src': {
defaultExtension: 'ts'
}
},
transpiler: 'typescript'
},
serveFiles: [
'src/**/*.ts',
'jspm_packages/**/*.js'
]
},
files: [
'test/unit/*.spec.ts'
],
exclude: [],
preprocessors: { },
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| gautamsi/aurelia-OfficeUIFabric | sample/karma.conf.js | JavaScript | mit | 1,159 |
import React, { useState } from 'react';
import { UncontrolledAlert } from 'reactstrap';
import Alert from '../../../src/Alert';
export const AlertFadelessExample = (props) => {
const [visible, setVisible] = useState(true);
const onDismiss = () => setVisible(false);
return (
<div>
<Alert color="primary" isOpen={visible} toggle={onDismiss} fade={false}>
I am a primary alert and I can be dismissed without animating!
</Alert>
</div>
);
}
export function UncontrolledAlertFadelessExample() {
return (
<div>
<UncontrolledAlert color="info" fade={false}>
I am an alert and I can be dismissed without animating!
</UncontrolledAlert>
</div>
);
}
| reactstrap/reactstrap | stories/examples/AlertFadeless.js | JavaScript | mit | 716 |
/*jshint browser: true, strict: true, undef: true */
/*global define: false */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else {
// browser global
window.classie = classie;
}
Modernizr.addTest('csstransformspreserve3d', function () {
var prop = Modernizr.prefixed('transformStyle');
var val = 'preserve-3d';
var computedStyle;
if(!prop) return false;
prop = prop.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
Modernizr.testStyles('#modernizr{' + prop + ':' + val + ';}', function (el, rule) {
computedStyle = window.getComputedStyle ? getComputedStyle(el, null).getPropertyValue(prop) : '';
});
return (computedStyle === val);
});
var support = {
transitions : Modernizr.csstransitions,
preserve3d : Modernizr.csstransformspreserve3d
},
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ];
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function shuffleMArray( marray ) {
var arr = [], marrlen = marray.length, inArrLen = marray[0].length;
for(var i = 0; i < marrlen; i++) {
arr = arr.concat( marray[i] );
}
// shuffle 2 d array
arr = shuffleArr( arr );
// to 2d
var newmarr = [], pos = 0;
for( var j = 0; j < marrlen; j++ ) {
var tmparr = [];
for( var k = 0; k < inArrLen; k++ ) {
tmparr.push( arr[ pos ] );
pos++;
}
newmarr.push( tmparr );
}
return newmarr;
}
function shuffleArr( array ) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Photostack( el, options ) {
this.el = el;
this.inner = this.el.querySelector( 'div' );
this.allItems = [].slice.call( this.inner.children );
this.allItemsCount = this.allItems.length;
if( !this.allItemsCount ) return;
this.items = [].slice.call( this.inner.querySelectorAll( 'figure:not([data-dummy])' ) );
this.itemsCount = this.items.length;
// index of the current photo
this.current = 0;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
Photostack.prototype.options = {};
Photostack.prototype._init = function() {
this.currentItem = this.items[ this.current ];
this._addNavigation();
this._getSizes();
this._initEvents();
}
Photostack.prototype._addNavigation = function() {
// add nav dots
this.nav = document.createElement( 'nav' )
var inner = '';
for( var i = 0; i < this.itemsCount; ++i ) {
inner += '<span></span>';
}
this.nav.innerHTML = inner;
this.el.appendChild( this.nav );
this.navDots = [].slice.call( this.nav.children );
}
Photostack.prototype._initEvents = function() {
var self = this,
beforeStep = classie.hasClass( this.el, 'photostack-start' ),
open = function() {
var setTransition = function() {
if( support.transitions ) {
classie.addClass( self.el, 'photostack-transition' );
}
}
if( beforeStep ) {
this.removeEventListener( 'click', open );
classie.removeClass( self.el, 'photostack-start' );
setTransition();
}
else {
self.openDefault = true;
setTimeout( setTransition, 25 );
}
self.started = true;
self._showPhoto( self.current );
};
if( beforeStep ) {
this._shuffle();
this.el.addEventListener( 'click', open );
}
else {
open();
}
this.navDots.forEach( function( dot, idx ) {
dot.addEventListener( 'click', function() {
// rotate the photo if clicking on the current dot
if( idx === self.current ) {
self._rotateItem();
}
else {
// if the photo is flipped then rotate it back before shuffling again
var callback = function() { self._showPhoto( idx ); }
if( self.flipped ) {
self._rotateItem( callback );
}
else {
callback();
}
}
} );
} );
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
}
Photostack.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resize();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 100 );
}
Photostack.prototype._resize = function() {
var self = this, callback = function() { self._shuffle( true ); }
this._getSizes();
if( this.started && this.flipped ) {
this._rotateItem( callback );
}
else {
callback();
}
}
Photostack.prototype._showPhoto = function( pos ) {
if( this.isShuffling ) {
return false;
}
this.isShuffling = true;
// if there is something behind..
if( classie.hasClass( this.currentItem, 'photostack-flip' ) ) {
this._removeItemPerspective();
classie.removeClass( this.navDots[ this.current ], 'flippable' );
}
classie.removeClass( this.navDots[ this.current ], 'current' );
classie.removeClass( this.currentItem, 'photostack-current' );
// change current
this.current = pos;
this.currentItem = this.items[ this.current ];
classie.addClass( this.navDots[ this.current ], 'current' );
// if there is something behind..
if( this.currentItem.querySelector( '.photostack-back' ) ) {
// nav dot gets class flippable
classie.addClass( this.navDots[ pos ], 'flippable' );
}
// shuffle a bit
this._shuffle();
}
// display items (randomly)
Photostack.prototype._shuffle = function( resize ) {
var iter = resize ? 1 : this.currentItem.getAttribute( 'data-shuffle-iteration' ) || 1;
if( iter <= 0 || !this.started || this.openDefault ) { iter = 1; }
// first item is open by default
if( this.openDefault ) {
// change transform-origin
classie.addClass( this.currentItem, 'photostack-flip' );
this.openDefault = false;
this.isShuffling = false;
}
var overlapFactor = .5,
// lines & columns
lines = Math.ceil(this.sizes.inner.width / (this.sizes.item.width * overlapFactor) ),
columns = Math.ceil(this.sizes.inner.height / (this.sizes.item.height * overlapFactor) ),
// since we are rounding up the previous calcs we need to know how much more we are adding to the calcs for both x and y axis
addX = lines * this.sizes.item.width * overlapFactor + this.sizes.item.width/2 - this.sizes.inner.width,
addY = columns * this.sizes.item.height * overlapFactor + this.sizes.item.height/2 - this.sizes.inner.height,
// we will want to center the grid
extraX = addX / 2,
extraY = addY / 2,
// max and min rotation angles
maxrot = 35, minrot = -35,
self = this,
// translate/rotate items
moveItems = function() {
--iter;
// create a "grid" of possible positions
var grid = [];
// populate the positions grid
for( var i = 0; i < columns; ++i ) {
var col = grid[ i ] = [];
for( var j = 0; j < lines; ++j ) {
var xVal = j * (self.sizes.item.width * overlapFactor) - extraX,
yVal = i * (self.sizes.item.height * overlapFactor) - extraY,
olx = 0, oly = 0;
if( self.started && iter === 0 ) {
var ol = self._isOverlapping( { x : xVal, y : yVal } );
if( ol.overlapping ) {
olx = ol.noOverlap.x;
oly = ol.noOverlap.y;
var r = Math.floor( Math.random() * 3 );
switch(r) {
case 0 : olx = 0; break;
case 1 : oly = 0; break;
}
}
}
col[ j ] = { x : xVal + olx, y : yVal + oly };
}
}
// shuffle
grid = shuffleMArray(grid);
var l = 0, c = 0, cntItemsAnim = 0;
self.allItems.forEach( function( item, i ) {
// pick a random item from the grid
if( l === lines - 1 ) {
c = c === columns - 1 ? 0 : c + 1;
l = 1;
}
else {
++l
}
var randXPos = Math.floor( Math.random() * lines ),
randYPos = Math.floor( Math.random() * columns ),
gridVal = grid[c][l-1],
translation = { x : gridVal.x, y : gridVal.y },
onEndTransitionFn = function() {
++cntItemsAnim;
if( support.transitions ) {
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
if( cntItemsAnim === self.allItemsCount ) {
if( iter > 0 ) {
moveItems.call();
}
else {
// change transform-origin
classie.addClass( self.currentItem, 'photostack-flip' );
// all done..
self.isShuffling = false;
if( typeof self.options.callback === 'function' ) {
self.options.callback( self.currentItem );
}
}
}
};
if(self.items.indexOf(item) === self.current && self.started && iter === 0) {
self.currentItem.style.WebkitTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
self.currentItem.style.msTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
self.currentItem.style.transform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
// if there is something behind..
if( self.currentItem.querySelector( '.photostack-back' ) ) {
self._addItemPerspective();
}
classie.addClass( self.currentItem, 'photostack-current' );
}
else {
item.style.WebkitTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
item.style.msTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
item.style.transform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
}
if( self.started ) {
if( support.transitions ) {
item.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}
} );
};
moveItems.call();
}
Photostack.prototype._getSizes = function() {
this.sizes = {
inner : { width : this.inner.offsetWidth, height : this.inner.offsetHeight },
item : { width : this.currentItem.offsetWidth, height : this.currentItem.offsetHeight }
};
// translation values to center an item
this.centerItem = { x : this.sizes.inner.width / 2 - this.sizes.item.width / 2, y : this.sizes.inner.height / 2 - this.sizes.item.height / 2 };
}
Photostack.prototype._isOverlapping = function( itemVal ) {
var dxArea = this.sizes.item.width + this.sizes.item.width / 3, // adding some extra avoids any rotated item to touch the central area
dyArea = this.sizes.item.height + this.sizes.item.height / 3,
areaVal = { x : this.sizes.inner.width / 2 - dxArea / 2, y : this.sizes.inner.height / 2 - dyArea / 2 },
dxItem = this.sizes.item.width,
dyItem = this.sizes.item.height;
if( !(( itemVal.x + dxItem ) < areaVal.x ||
itemVal.x > ( areaVal.x + dxArea ) ||
( itemVal.y + dyItem ) < areaVal.y ||
itemVal.y > ( areaVal.y + dyArea )) ) {
// how much to move so it does not overlap?
// move left / or move right
var left = Math.random() < 0.5,
randExtraX = Math.floor( Math.random() * (dxItem/4 + 1) ),
randExtraY = Math.floor( Math.random() * (dyItem/4 + 1) ),
noOverlapX = left ? (itemVal.x - areaVal.x + dxItem) * -1 - randExtraX : (areaVal.x + dxArea) - (itemVal.x + dxItem) + dxItem + randExtraX,
noOverlapY = left ? (itemVal.y - areaVal.y + dyItem) * -1 - randExtraY : (areaVal.y + dyArea) - (itemVal.y + dyItem) + dyItem + randExtraY;
return {
overlapping : true,
noOverlap : { x : noOverlapX, y : noOverlapY }
}
}
return {
overlapping : false
}
}
Photostack.prototype._addItemPerspective = function() {
classie.addClass( this.el, 'photostack-perspective' );
}
Photostack.prototype._removeItemPerspective = function() {
classie.removeClass( this.el, 'photostack-perspective' );
classie.removeClass( this.currentItem, 'photostack-flip' );
}
Photostack.prototype._rotateItem = function( callback ) {
if( classie.hasClass( this.el, 'photostack-perspective' ) && !this.isRotating && !this.isShuffling ) {
this.isRotating = true;
var self = this, onEndTransitionFn = function() {
if( support.transitions && support.preserve3d ) {
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
self.isRotating = false;
if( typeof callback === 'function' ) {
callback();
}
};
if( this.flipped ) {
classie.removeClass( this.navDots[ this.current ], 'flip' );
if( support.preserve3d ) {
this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)';
this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)';
}
else {
classie.removeClass( this.currentItem, 'photostack-showback' );
}
}
else {
classie.addClass( this.navDots[ this.current ], 'flip' );
if( support.preserve3d ) {
this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)';
this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)';
}
else {
classie.addClass( this.currentItem, 'photostack-showback' );
}
}
this.flipped = !this.flipped;
if( support.transitions && support.preserve3d ) {
this.currentItem.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}
}
// add to global namespace
window.Photostack = Photostack;
var initPhotoSwipeFromDOM = function (gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function (el) {
var thumbElements = el.childNodes
, numNodes = thumbElements.length
, items = []
, figureEl
, linkEl
, size
, item;
for (var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if (figureEl.nodeType !== 1 || figureEl.nodeName.toUpperCase() !== 'FIGURE') {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href')
, w: parseInt(size[0], 10)
, h: parseInt(size[1], 10)
};
if (figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if (linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && (fn(el) ? el : closest(el.parentNode, fn));
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function (e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function (el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE' && classie.hasClass( el, 'photostack-current' ) );
});
if (!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
var clickedGallery = clickedListItem.parentNode
, childNodes = clickedListItem.parentNode.childNodes
, numChildNodes = childNodes.length
, nodeIndex = 0
, index;
for (var i = 0; i < numChildNodes; i++) {
if (childNodes[i].nodeType !== 1) {
continue;
}
if (childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if (index >= 0) {
// open PhotoSwipe if valid index found
openPhotoSwipe(index, clickedGallery);
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function () {
var hash = window.location.hash.substring(1)
, params = {};
if (hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if (!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if (pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if (params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function (index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0]
, gallery
, options
, items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid')
, getThumbBoundsFn: function (index) {
// See Options -> getThumbBoundsFn section of documentation for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop
, rect = thumbnail.getBoundingClientRect();
return {
x: rect.left
, y: rect.top + pageYScroll
, w: rect.width
};
}
};
// PhotoSwipe opened from URL
if (fromURL) {
if (options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for (var j = 0; j < items.length; j++) {
if (items[j].pid == index) {
options.index = j;
break;
}
}
}
else {
// in URL indexes start from 1
options.index = parseInt(index, 10) - 1;
}
}
else {
options.index = parseInt(index, 10);
}
// exit if index not found
if (isNaN(options.index)) {
return;
}
if (disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll(gallerySelector);
for (var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i + 1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if (hashData.pid && hashData.gid) {
openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
}
};
// execute above function
initPhotoSwipeFromDOM('.photostack-container');
})( window );
| fauzie/fauzie.github.io | src/js/photostack.js | JavaScript | mit | 20,955 |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var platform_browser_1 = require('@angular/platform-browser');
var forms_1 = require('@angular/forms');
var app_component_1 = require('./app.component');
var people_service_1 = require('./people.service');
var people_list_component_1 = require('./people-list.component');
var person_details_component_1 = require('./person-details.component');
var person_component_1 = require('./+person/person.component');
var http_1 = require('@angular/http');
var angular_datatables_module_1 = require('./shared/modules/datatables/angular-datatables/angular-datatables.module');
var app_routes_1 = require('./app.routes');
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
imports: [platform_browser_1.BrowserModule, app_routes_1.routing, forms_1.FormsModule, http_1.HttpModule, angular_datatables_module_1.DataTablesModule],
declarations: [app_component_1.AppComponent, people_list_component_1.PeopleListComponent, person_details_component_1.PersonDetailsComponent, person_component_1.PersonComponent],
bootstrap: [app_component_1.AppComponent],
providers: [people_service_1.PeopleService]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map | VinhNT23/Angular2Demo1 | app/app.module.js | JavaScript | mit | 2,170 |
import { div } from '../core/dom-api';
import { urls } from '../urls';
const commentsSort = (a, b) => {
if (a.time < b.time) return -1;
if (a.time > b.time) return 1;
return 0;
};
const commentElement = (data) => {
let replies = data && data.comments && data.comments.length && data.comments
.sort(commentsSort)
.map(item => commentElement(item));
return`<div class="comment">
<div class="details">
<div class="user">${data.user}</div>
<div class="time">${data.time_ago}</div>
</div>
<div class="content">
${data.content}
</div>
${replies ? replies.join('') : ''}
</div>`;
};
const commentsElement = (comments) => {
return `<div class="comments">${comments.length && comments.sort(commentsSort).map(data => commentElement(data)).join('')}</div>`;
};
export const CommentsView = (props) => {
let template;
let data;
let timeoutId;
const loadData = () => {
fetch(urls.item(props.routeParams.id))
.then(res => res.json())
.then(res => {
data = res;
render();
});
};
function createTemplate() {
let hasComments = data.comments.length;
let commentsContent = commentsElement(data.comments);
let url = data.url;
url = url.indexOf('item') === 0 ? '/' + url : url;
// Set the title
document.querySelector('title').innerText = `${data.title} | Vanilla Hacker News PWA`;
// Clear timeout
if (timeoutId) clearTimeout(timeoutId);
return div({
className: 'item-view'
}, `
<a class="title" href="${url}" target="_blank">
<h1>${data.title}<span>↗</span></h1>
</a>
<div class="subtitle ${data.type}">
<div class="user">${data.user}</div>
<div class="time-ago">${data.time_ago}</div>
<div class="stars">${data.points} <span>★</span></div>
</div>
<div class="content">
${data.content || 'No content'}
</div>
<div class="comments">
<div class="subtitle">${hasComments ? 'Comments' : 'No coments'}</div>
${commentsContent}
</div>
`);
}
function createFirstTemplate() {
const firstTemplate = div({
className: 'item-view'
}, '<div class="content-loading">Loading content</div>');
timeoutId = setTimeout(() => {
firstTemplate.querySelector('.content-loading').innerHTML += '<br/>...<br/>Looks like it takes longer than expected';
scheduleLongerTimeout(firstTemplate);
}, 1e3);
return firstTemplate;
}
function scheduleLongerTimeout(el) {
timeoutId = setTimeout(() => {
el.querySelector('.content-loading').innerHTML += '</br>...<br/>It\'s been over 2 seconds now, content should be arriving soon';
}, 1500);
}
function render() {
if (!!template.parentElement) {
let newTemplate = createTemplate();
template.parentElement.replaceChild(newTemplate, template);
template = newTemplate;
}
}
template = createFirstTemplate();
loadData();
return template;
}; | cristianbote/hnpwa-vanilla | public/views/comments-view.js | JavaScript | mit | 3,407 |
'use strict';
var assert = require('assert');
var resource = require('../resource');
exports.Person = resource.create('Person', {api: 'person', version: 2})
.extend({
flag: function(options){
return this.constructor.post('/people/' + this.id + '/flag', options);
}
},
{
find: function(options){
options = options || {};
assert(options.email, 'An email must be provided');
return this.get('/people/find', options);
}
});
| clearbit/clearbit-node | src/enrichment/person.js | JavaScript | mit | 473 |
var opn = require('opn');
console.log('打开二维码...')
// Opens the image in the default image viewer
opn('static/img/qr.jpg').then(() => {
console.log('关闭二维码!')
}); | doterlin/wechat-robot | src/lib/open.js | JavaScript | mit | 185 |
//= require "dep3-1-1.js, dep3.js" | marcbaechinger/resolve | specs/samples/dep3-1.js | JavaScript | mit | 34 |
function init_map(field_id) {
//console.log(field_id);
}
/*acf.fields.address = acf.field.extend({
type: 'address',
$el: null,
$input: null,
status: '', // '', 'loading', 'ready'
geocoder: false,
map: false,
maps: {},
pending: $(),
actions: {
'ready': 'initialize'
},
initialize: function () {
console.log('init');
}
});*/
(function ($) {
function initialize_field($el) {
console.log('init hook');
console.log($el);
initMap($el);
}
if (typeof acf.add_action !== 'undefined') {
/*
* ready append (ACF5)
*
* These are 2 events which are fired during the page load
* ready = on page load similar to $(document).ready()
* append = on new DOM elements appended via repeater field
*
* @type event
* @date 20/07/13
*
* @param $el (jQuery selection) the jQuery element which contains the ACF fields
* @return n/a
*/
acf.add_action('ready append', function ($el) {
// search $el for fields of type 'FIELD_NAME'
acf.get_fields({type: 'address'}, $el).each(function () {
initialize_field($(this));
});
});
} else {
/*
* acf/setup_fields (ACF4)
*
* This event is triggered when ACF adds any new elements to the DOM.
*
* @type function
* @since 1.0.0
* @date 01/01/12
*
* @param event e: an event object. This can be ignored
* @param Element postbox: An element which contains the new HTML
*
* @return n/a
*/
$(document).on('acf/setup_fields', function (e, postbox) {
$(postbox).find('.field[data-field_type="address"]').each(function () {
initialize_field($(this));
});
});
}
function initMap($mapElement) {
ymaps.ready(function () {
/**
* Массив сохраняемых данных
*
* address - краткий адрес, без города
* addressFull - полный адрес, с городом
* coordinates - координаты адреса
* coordinatesMetro - координаты ближайшей станции метро
* metroDist - расстояние до ближайшей станции метро (в метрах)
* addressMetro - адрес ближайшей станции метро
* addressMetroFull - полный адрес ближайшей станции метро
* metroLine - ближайшая линия метро, формат line_{number}
*
* @type {{}}
*/
var field = {};
/**
* Центр карты и координаты метки по умолчанию
* @type {number[]}
*/
var centerMap = [55.753994, 37.622093];
/**
* Карта
* @type {undefined}
*/
var addressMap = undefined;
/**
* Метка
* @type {ymaps.GeoObject}
*/
var geoPoint = new ymaps.GeoObject({
geometry: {
type: "Point",
coordinates: centerMap
}
}, {
preset: 'islands#blackStretchyIcon',
draggable: true
});
geoPoint.events.add('dragend', function () {
changeLocation();
});
/**
* Кнопка определения местоположения
* @type {GeolocationButton}
*/
var geolocationButton = new GeolocationButton({
data: {
image: btn.img,
title: 'Определить местоположение'
},
geolocationOptions: {
enableHighAccuracy: true,
noPlacemark: false,
point: geoPoint,
afterSearch: function () {
changeLocation()
}
}
}, {
selectOnClick: false
});
/**
* Строка поиска адреса
* @type {ymaps.control.SearchControl}
*/
var searchControl = new ymaps.control.SearchControl({
noPlacemark: true
});
searchControl.events.add('resultselect', function (e) {
var index = e.get("resultIndex");
var result = searchControl.getResult(index);
result.then(function (res) {
var geo = res.geometry.getCoordinates();
geoPoint.geometry.setCoordinates(geo);
changeLocation();
});
});
/**
* Кнопка для поиска ближайшего метро
* @type {Button}
*/
var button = new ymaps.control.Button({
data: {
image: btn.metro,
title: 'Найти ближайшее метро'
}
}, {
selectOnClick: false
});
button.events.add('click', function () {
findMetro();
});
/**
* Поиск ближайшего метро
*/
function findMetro() {
ymaps.geocode(field.coordinates, {
kind: 'metro',
results: 1
}).then(function (res) {
if (res.geoObjects.getLength()) {
var m0 = res.geoObjects.get(0);
var coords = m0.geometry.getCoordinates();
field.coordinatesMetro = coords;
var dist = ymaps.coordSystem.geo.getDistance(field.coordinates, coords);
field.metroDist = Math.round(dist).toFixed(0);
res.geoObjects.options.set('preset', 'twirl#metroMoscowIcon');
addressMap.geoObjects.add(res.geoObjects);
var getObject = res.geoObjects.get(0);
field.addressMetro = getObject.properties.get('name');
field.addressMetroFull = getObject.properties.get('text').replace('Россия,', '').trim();
$('.metro-row').show();
$('input[name="metro"]').val(field.addressMetro);
$('input[name="metro_full"]').val(field.addressMetroFull);
$('input[name="metro_dist"]').val(field.metroDist);
var metroLine = colorMetro(field.addressMetroFull);
if (metroLine != undefined)
field.metroLine = metroLine;
}
});
}
/**
* Событие при смене координат
*/
function changeLocation() {
var coord = geoPoint.geometry.getCoordinates();
field.coordinates = coord;
ymaps.geocode(coord).then(function (res) {
var getObject = res.geoObjects.get(0);
field.address = getObject.properties.get('name');
field.addressFull = getObject.properties.get('text').replace('Россия,', '').trim();
updateField();
});
}
/**
* Обновление полей с адресом
*/
function updateField() {
$('input[name="address"]').val(field.address);
$('input[name="address_full"]').val(field.addressFull);
}
/**
* Загрузка данных
*/
function loadField() {
//field = JSON.parse($('#acf-address-input').val());
updateField();
var loadCoord = (field.coordinates != undefined) ? field.coordinates : centerMap;
var loadZoom = (field.zoom != undefined) ? field.zoom : 10;
geoPoint.geometry.setCoordinates(loadCoord);
addressMap.setCenter(loadCoord);
addressMap.setZoom(loadZoom);
if (field.addressMetro != undefined || field.addressMetroFull != undefined) {
$('.metro-row').show();
$('input[name="metro"]').val(field.addressMetro);
$('input[name="metro_full"]').val(field.addressMetroFull);
$('input[name="metro_dist"]').val(field.metroDist);
}
}
/**
* Возвращает номер линии метро
*
* @param metro
* @returns {*}
*/
function colorMetro(metro) {
var metroArray = metro.split(',');
if (metroArray.length >= 3) {
metro = metroArray[2].replace('линия', '').trim();
} else
return undefined;
var moscowMetro = {};
moscowMetro['Сокольническая'] = 'line_1';
moscowMetro['Замоскворецкая'] = 'line_2';
moscowMetro['Арбатско-Покровская'] = 'line_3';
moscowMetro['Филёвская'] = 'line_4';
moscowMetro['Кольцевая'] = 'line_5';
moscowMetro['Калужско-Рижская'] = 'line_6';
moscowMetro['Таганско-Краснопресненская'] = 'line_7';
moscowMetro['Калининско-Солнцевская'] = 'line_8';
moscowMetro['Калининская'] = 'line_8';
moscowMetro['Серпуховско-Тимирязевская'] = 'line_9';
moscowMetro['Люблинско-Дмитровская'] = 'line_10';
moscowMetro['Каховская'] = 'line_11';
moscowMetro['Бутовская'] = 'line_12';
return moscowMetro[metro];
}
$('.address-btn-cancel').click(function () {
tb_remove();
});
$('#address-btn-ok').click(function () {
$('#acf-address-input').val(JSON.stringify(field));
$('#acf-address-display').val(field.addressFull);
tb_remove();
});
$('#acf-address-btn').click(function () {
if (addressMap != undefined)
addressMap.destroy();
addressMap = new ymaps.Map($mapElement, {
center: centerMap,
zoom: 9,
behaviors: ['default', 'scrollZoom']
});
addressMap.events.add('boundschange', function (e) {
var zoom = e.get("newZoom");
field.zoom = zoom;
});
addressMap.controls
.add(geolocationButton, {top: 5, left: 100})
.add('zoomControl')
.add('typeSelector', {top: 5, right: 5})
.add(button, {top: 5, left: 65})
.add(searchControl, {top: 5, left: 200});
addressMap.geoObjects.add(geoPoint);
loadField();
});
$('#acf-address-clear').click(function () {
field = {};
$('.metro-row').hide();
$('#acf-address-display').val('');
$('#acf-address-display').val('');
$('input[name="metro"]').val('');
$('input[name="metro_full"]').val('');
$('input[name="metro_dist"]').val('');
});
$('#acf-address-display').click(function () {
$('#acf-address-btn').trigger('click');
});
field = JSON.parse($('#acf-address-input').val());
$('#acf-address-display').val(field.addressFull);
});
}
})(jQuery); | constlab/acf-address | js/acf-address.js | JavaScript | mit | 13,011 |
// flow-typed signature: 02c97f596f96a486574f8fb0fd727a55
// flow-typed version: <<STUB>>/eslint-config-google_v0.14.0/flow_v0.108.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-config-google'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'eslint-config-google' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'eslint-config-google/index' {
declare module.exports: $Exports<'eslint-config-google'>;
}
declare module 'eslint-config-google/index.js' {
declare module.exports: $Exports<'eslint-config-google'>;
}
| knitjs/knit | flow-typed/npm/eslint-config-google_vx.x.x.js | JavaScript | mit | 918 |
import { combineReducers } from 'redux'
import userInfo from './userInfo'
import userFeed from './userFeed'
import popularFeed from './popularFeed'
export default combineReducers({
userInfo,
userFeed,
popularFeed
}) | anzorb/pumpapp | src/reducers/index.js | JavaScript | mit | 222 |
/*
comment
*/
var g = 1, i = 2, j = 2/*
*//1+g+"\/*"/i, x = 3,
a = 2/1/g, b = (i)/i/i/*
*/, s = 'aaa\
bbb\
ccc'; var z = 1; | polygonplanet/Chiffon | tests/fixtures/tokenize/loc/test-0002.js | JavaScript | mit | 127 |
const matcher = require('../lib/matcher');
describe('Matcher', () => {
describe('path', () => {
let mock;
let request;
beforeEach(() => {
mock = {
request: {
path: '/test'
}
};
request = {
originalUrl: '/test?blah=test',
path: '/test'
};
});
test('should return true if request path exactly matches mock request path', () => {
expect(matcher.path(mock, request)).toBe(true);
});
test('should return true if request path matches mock request greedy path', () => {
mock.request.path = '/test/*';
request.path = '/test/anything';
expect(matcher.path(mock, request)).toBe(true);
});
test('should return true if request path matches mock request named path', () => {
mock.request.path = '/test/:named/end';
request.path = '/test/anything/end';
expect(matcher.path(mock, request)).toBe(true);
});
test('should return false if request path does not match mock request named path', () => {
mock.request.path = '/test/:named/end';
request.path = '/this/will/never/match';
expect(matcher.path(mock, request)).toBe(false);
});
});
describe('headers', () => {
let mock;
let request;
beforeEach(() => {
mock = {
request: {
headers: {
test: 'this'
}
}
};
request = {
headers: {
test: 'this'
}
};
});
test('should return true if request headers exactly match mock request headers', () => {
expect(matcher.headers(mock, request)).toBe(true);
});
test('should return true if request headers contain the mock request headers', () => {
request.headers.another = 'glah';
expect(matcher.headers(mock, request)).toBe(true);
});
test('should return false if request headers do not match the mock request header values', () => {
request.headers = {
test: 'nope'
};
expect(matcher.headers(mock, request)).toBe(false);
});
test('should return false if request headers do not contain the mock request header values', () => {
request.headers = {
another: 'header'
};
expect(matcher.headers(mock, request)).toBe(false);
});
});
describe('query', () => {
let mock;
let request;
beforeEach(() => {
mock = {
request: {
query: {
test: 'this'
}
}
};
request = {
query: {
test: 'this'
}
};
});
test('should return true if mock has no query specified', () => {
delete mock.request.query;
expect(matcher.query(mock, request)).toBe(true);
});
test('should return true if mock has empty query specified', () => {
delete mock.request.query.test;
expect(matcher.query(mock, request)).toBe(true);
});
test('should return true if request query exactly match mock request query', () => {
expect(matcher.query(mock, request)).toBe(true);
});
test('should return true if request query contain the mock request query', () => {
request.query.another = 'glah';
expect(matcher.query(mock, request)).toBe(true);
});
test('should return false if request query does not match the mock request header values', () => {
request.query = {
test: 'nope'
};
expect(matcher.query(mock, request)).toBe(false);
});
test('should return false if request query does not contain the mock request header values', () => {
request.query = {
another: 'header'
};
expect(matcher.query(mock, request)).toBe(false);
});
test('RegExp - should return true if request query matches', () => {
mock.request.query.email = {
type: 'regex',
value: '.*?@bar\.com'
};
request.query = {
test: 'this',
email: 'foo@bar.com'
};
expect(matcher.query(mock, request)).toBe(true);
});
});
describe('body', () => {
let mock;
let request;
beforeEach(() => {
mock = {
request: {
body: {
test: 'this'
}
}
};
request = {
body: {
test: 'this'
}
};
});
test('should return true if request body exactly match mock request body', () => {
expect(matcher.body(mock, request)).toBe(true);
});
test('should return true if request body contain the mock request body', () => {
request.body.another = 'glah';
expect(matcher.body(mock, request)).toBe(true);
});
test('should return false if request body does not match the mock request header values', () => {
request.body = {
test: 'nope'
};
expect(matcher.body(mock, request)).toBe(false);
});
test('should return false if request body does not contain the mock request header values', () => {
request.body = {
another: 'field'
};
expect(matcher.body(mock, request)).toBe(false);
});
});
});
| alexnaish/mockercinno | test/matcher.spec.js | JavaScript | mit | 4,660 |
module.exports = { prefix: 'far', iconName: 'arrow-alt-square-up', icon: [448, 512, [], "f353", "M244 384h-40c-6.6 0-12-5.4-12-12V256h-67c-10.7 0-16-12.9-8.5-20.5l99-99c4.7-4.7 12.3-4.7 17 0l99 99c7.6 7.6 2.2 20.5-8.5 20.5h-67v116c0 6.6-5.4 12-12 12zM448 80v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V80c0-26.5 21.5-48 48-48h352c26.5 0 48 21.5 48 48zm-48 346V86c0-3.3-2.7-6-6-6H54c-3.3 0-6 2.7-6 6v340c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"] }; | dolare/myCMS | static/fontawesome5/fontawesome-pro-5.0.2/fontawesome-pro-5.0.2/advanced-options/use-with-node-js/fontawesome-pro-regular/faArrowAltSquareUp.js | JavaScript | mit | 450 |
import React, { Component } from "react";
import formatter from "../formatter";
const labelStyle = { fg: "magenta", bold: true };
class RequestBreakdown extends Component {
scroll(amount) {
// nope
}
render() {
const { respTime, sqlTime, renderingTime } = this.props.data;
return (
<box top={0} height="100%-2" left={0} width="100%-2">
<box top={1} height={1} left={0} width={19} content=" Response Time : " style={labelStyle} />
<box top={1} height={1} left={19} width="100%-19" content={formatter.ms(respTime)} />
<box top={2} height={1} left={0} width={29} content=" ===========================" />
<box top={3} height={1} left={0} width={19} content=" SQL Time : " style={labelStyle} />
<box top={3} height={1} left={19} width="100%-19" content={formatter.ms(sqlTime)} />
<box top={4} height={1} left={0} width={19} content=" Rendering Time : " style={labelStyle} />
<box top={4} height={1} left={19} width="100%-19" content={formatter.ms(renderingTime)} />
<box top={5} height={1} left={0} width={19} content=" Others : " style={labelStyle} />
<box top={5} height={1} left={19} width="100%-19" content={formatter.ms(respTime - sqlTime - renderingTime)} />
</box>
);
}
}
export default RequestBreakdown;
| y-takey/rails-dashboard | src/components/RequestBreakdown.js | JavaScript | mit | 1,341 |
const DrawCard = require('../../drawcard.js');
const { CardTypes } = require('../../Constants');
class AsakoTsuki extends DrawCard {
setupCardAbilities(ability) {
this.reaction({
title: 'Honor a scholar character',
when: {
onClaimRing: event => event.conflict && event.conflict.hasElement('water')
},
target: {
cardType: CardTypes.Character,
cardCondition: card => card.hasTrait('scholar'),
gameAction: ability.actions.honor()
}
});
}
}
AsakoTsuki.id = 'asako-tsuki';
module.exports = AsakoTsuki;
| jeremylarner/ringteki | server/game/cards/02.6-MotE/AsakoTsuki.js | JavaScript | mit | 648 |
import DndStatus from 'ringcentral-integration/modules/Presence/dndStatus';
import i18n from './i18n';
export function getPresenceStatusName(
presenceStatus,
dndStatus,
currentLocale,
) {
if (dndStatus === DndStatus.doNotAcceptAnyCalls) {
return i18n.getString(dndStatus, currentLocale);
}
return i18n.getString(presenceStatus, currentLocale);
}
| ringcentral/ringcentral-js-widget | packages/ringcentral-widgets/lib/getPresenceStatusName/index.js | JavaScript | mit | 363 |
"use strict";
const bunyan = require("bunyan")
, bformat = require("bunyan-format")
, config = require("config")
;
const log_level = process.env.LOG_LEVEL || (config.has('app.log_level') ? config.get('app.log_level') : "info");
const formatOut = bformat({ outputMode: "short" , })
, logger = bunyan.createLogger({
name: "pepp",
streams: [
{
level: log_level,
stream: formatOut
}/*,
{
level: 'info',
// log ERROR and above to a file
path: './output/test.log'
}*/
]
});
module.exports = logger;
| haganbt/pepp | lib/helpers/logger.js | JavaScript | mit | 611 |
module.exports = function(grunt) {
grunt.initConfig({
// insert the bower files in your index.html
wiredep: {
target: {
src: 'index.html'
}
}
});
grunt.loadNpmTasks('grunt-wiredep');
grunt.registerTask('default', ['wiredep']);
}; | marcosflorencio/angular-materializecss-autocomplete | Gruntfile.js | JavaScript | mit | 269 |
const test = require('tape')
const MinHeap = require('./MinHeap')
test('find returns null in empty heap', assert => {
const heap = new MinHeap()
assert.equal(heap.findMin(), null)
assert.end()
})
test('length is 0 in empty heap', assert => {
const heap = new MinHeap()
assert.equal(heap.length, 0)
assert.end()
})
test('length is updated when items added', assert => {
const heap = new MinHeap()
heap.insert(1)
heap.insert(2)
heap.insert(10)
assert.equal(heap.length, 3)
assert.end()
})
test('length is updated when items removed', assert => {
const heap = new MinHeap()
heap.insert(1)
heap.insert(2)
heap.insert(10)
heap.extractMin()
heap.extractMin()
assert.equal(heap.length, 1)
assert.end()
})
test('min item is replaced with given item', assert => {
const heap = new MinHeap()
heap.insert(1)
heap.insert(2)
heap.insert(3)
assert.equal(heap.findMin(), 1)
assert.equal(heap.length, 3)
heap.replace(4)
assert.equal(heap.findMin(), 2)
assert.equal(heap.length, 3)
assert.equal(heap.extractMin(), 2)
assert.equal(heap.extractMin(), 3)
assert.equal(heap.extractMin(), 4)
assert.end()
})
test('find returns min item from heap', assert => {
const heap = new MinHeap()
heap.insert(3)
heap.insert(1)
heap.insert(10)
assert.equal(heap.length, 3)
assert.equal(heap.findMin(), 1)
assert.equal(heap.length, 3)
assert.end()
})
test('extract returns min item from heap', assert => {
const heap = new MinHeap()
heap.insert(9)
heap.insert(8)
heap.insert(7)
heap.insert(6)
heap.insert(5)
heap.insert(4)
heap.insert(3)
heap.insert(2)
heap.insert(2)
heap.insert(2)
heap.insert(1)
assert.equal(heap.extractMin(), 1)
assert.equal(heap.extractMin(), 2)
assert.equal(heap.extractMin(), 2)
assert.equal(heap.extractMin(), 2)
assert.equal(heap.extractMin(), 3)
assert.equal(heap.extractMin(), 4)
assert.equal(heap.extractMin(), 5)
assert.equal(heap.extractMin(), 6)
assert.equal(heap.extractMin(), 7)
assert.equal(heap.extractMin(), 8)
assert.equal(heap.extractMin(), 9)
assert.equal(heap.extractMin(), null)
assert.equal(heap.extractMin(), null)
assert.end()
})
test('heap can be iterated', assert => {
const heap = new MinHeap()
heap.insert(5)
heap.insert(0)
heap.insert(3)
heap.insert(2)
heap.insert(4)
heap.insert(1)
assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5])
assert.end()
})
test('heap is created from given array', assert => {
const input = [5, 6, 3, 1, 2, 0, 4]
const heap = new MinHeap(input)
assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5, 6])
assert.deepEqual(input, [5, 6, 3, 1, 2, 0, 4]) // input data should not be modified
assert.end()
})
test('sort random data with heap', assert => {
const input = []
for (let i = 0; i < 1e5; i++) {
const item = Math.floor(Math.random() * 1e4)
input.push(item)
}
const heap = new MinHeap(input)
assert.deepEqual([...heap], input.sort((a, b) => a - b))
assert.end()
})
| ayastreb/cs101 | src/DataStructures/MinHeap.test.js | JavaScript | mit | 3,005 |
let fs = require('fs');
let path = require('path');
let moviesData = require('../config/database');
module.exports = (req, res) => {
if(req.headers.statusheader === "Full") {
fs.readFile("./views/status.html", (err, data) => {
if(err) {
console.log(err);
res.writeHead(404);
res.write('404 Not Found');
res.end();
}
res.writeHead(200, {
'Content-Type': 'text/html'
});
let imagesCount = moviesData.getMovies().length;
data = data.toString().replace('{content}', `There are currently ${imagesCount} images.`);
res.write(data);
res.end();
})
} else {
return true;
}
} | Martotko/JS-Web | ExpressJS/03.Exercises-NodeJS-Web-Server-Development-Tools/handlers/statusHeader.js | JavaScript | mit | 780 |
/* --- AUTOGENERATED FILE -----------------------------
* If you make changes to this file delete this comment.
* Otherwise the file may be overwritten in the future.
* --------------------------------------------------- */
const { mergeLocMatchGroups } = require('../lib/matching/utils');
const { regexMatchLocs } = require('../lib/matching/regexMatch');
const allSetSrc = {
type: 'website',
url: 'https://resources.allsetlearning.com/chinese/grammar/ASGTYJ3E',
name: 'AllSet Chinese Grammar Wiki',
};
module.exports = {
id: 'budanErqie',
structures: [
'Subj. + 不但 + Adj. / Verb, 而且 + Adj. / Verb',
'Subj. + 不但 + Adj. / Verb, 而且 + Adj. / Verb',
'不但 + Subj. 1 + Adj. / Verb, 而且 + Subj. 2 + Adj. / Verb',
],
description:
'"不但⋯⋯,而且⋯⋯" (bùdàn..., érqiě...) is a very commonly used pattern that indicates "not only, ... but also...."',
sources: [allSetSrc],
match: sentence =>
mergeLocMatchGroups([regexMatchLocs(sentence.text, /(不但)[^而且]+(而且)/)]),
examples: [
{
zh: '这种菜不但好吃,而且有营养。',
en: 'This kind of vegetable is not only delicious, but nutritious as well.',
src: allSetSrc,
},
{
zh: '她不但聪明,而且很努力。',
en: 'She is not only smart, but also very hard-working.',
src: allSetSrc,
},
{
zh: '他不但做完了,而且做得非常好。',
en: 'Not only did he finish, but he also did it extremely well.',
src: allSetSrc,
},
{
zh: '我不但会做饭,而且会洗衣服。',
en: 'Not only can I cook, but I can also do the laundry.',
src: allSetSrc,
},
{
zh: '不但我会做饭,而且我妹妹也会做饭。',
en: 'Not only can I cook, but my little sister can as well.',
src: allSetSrc,
},
],
};
| chanind/cn-grammar-matcher | src/patterns/budanErqiePattern.js | JavaScript | mit | 1,886 |
/**
* js-borschik-include
* ===================
*
* Собирает *js*-файлы инклудами борщика, сохраняет в виде `?.js`.
* Технология нужна, если в исходных *js*-файлах используются инклуды борщика.
*
* В последствии, получившийся файл `?.js` следует раскрывать с помощью технологии `borschik`.
*
* **Опции**
*
* * *String* **target** — Результирующий таргет. Обязательная опция.
* * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов
* (его предоставляет технология `files`). По умолчанию — `?.files`.
* * *String[]* **sourceSuffixes** — суффиксы файлов, по которым строится files-таргет. По умолчанию — ['js'].
*
* **Пример**
*
* ```javascript
* nodeConfig.addTechs([
* [ require('enb-borschik/techs/js-borschik-include') ],
* [ require('enb-borschik/techs/borschik'), {
* source: '?.js',
* target: '_?.js'
* } ]);
* ]);
* ```
*/
module.exports = require('enb/lib/build-flow').create()
.name('js-borschik-include')
.target('target', '?.js')
.useFileList(['js'])
.builder(function (files) {
var node = this.node;
return files.map(function (file) {
return '/*borschik:include:' + node.relativePath(file.fullname) + '*/';
}).join('\n');
})
.createTech();
| zlebnik/enb-borschik | techs/js-borschik-include.js | JavaScript | mit | 1,671 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z"
}), 'OfflinePinSharp'); | AlloyTeam/Nuclear | components/icon/esm/offline-pin-sharp.js | JavaScript | mit | 279 |
import * as actions from './actions'
describe('App actions', () => {
it('selectTerm should create SELECT_TERM action', () => {
expect(actions.selectTerm('term')).toEqual({
type: 'SELECT_TERM',
term: 'term'
})
})
it('startFetch should create START_FETCH action', () => {
expect(actions.startFetch()).toEqual({
type: 'START_FETCH',
isBusy: true
})
})
it('fetchTerm calls RECEIVE_ERROR on complete lookup failure', () => {
let failingLookup = (url, settings, onDone ) => { throw "Error" };
let conceptNet = { lookup: failingLookup };
let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") };
actions.getIsA(dispatch, conceptNet, "next term");
})
it('fetchTerm calls RECEIVE_ERROR on lookup returning error to onDone', () => {
let errorLookup = (url, settings, onDone ) => { onDone("Error", null) };
let conceptNet = { lookup: errorLookup };
let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") };
actions.getIsA(dispatch, conceptNet, "next term");
})
it('fetchTerm calls RECEIVE_RESPONSE on lookup returning results to onDone', () => {
let successLookup = (url, settings, onDone ) => { onDone(null, {'edges': []}) };
let conceptNet = { lookup: successLookup };
let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_RESPONSE") };
actions.getIsA(dispatch, conceptNet, "next term");
})
})
| AlexanderAA/conceptnet | src/actions/actions.spec.js | JavaScript | mit | 1,444 |
/**
* @version: 1.0.1
* @author: Dan Grossman http://www.dangrossman.info/
* @date: 2012-08-20
* @copyright: Copyright (c) 2012 Dan Grossman. All rights reserved.
* @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0
* @website: http://www.improvely.com/
*/
!function ($) {
var DateRangePicker = function (element, options, cb) {
var hasOptions = typeof options == 'object'
var localeObject;
//state
this.startDate = Date.today();
this.endDate = Date.today();
this.minDate = false;
this.maxDate = false;
this.changed = false;
this.ranges = {};
this.opens = 'right';
this.cb = function () { };
this.format = 'MM/dd/yyyy';
this.separator = ' - ';
this.showWeekNumbers = false;
this.buttonClasses = ['btn-primary'];
this.locale = {
applyLabel: 'Apply',
fromLabel: 'From',
toLabel: 'To',
weekLabel: 'W',
customRangeLabel: 'Custom Range',
daysOfWeek: Date.CultureInfo.shortestDayNames,
monthNames: Date.CultureInfo.monthNames,
firstDay: 0
};
localeObject = this.locale;
this.leftCalendar = {
month: Date.today().set({ day: 1, month: this.startDate.getMonth(), year: this.startDate.getFullYear() }),
calendar: Array()
};
this.rightCalendar = {
month: Date.today().set({ day: 1, month: this.endDate.getMonth(), year: this.endDate.getFullYear() }),
calendar: Array()
};
// by default, the daterangepicker element is placed at the bottom of HTML body
this.parentEl = 'body';
//element that triggered the date range picker
this.element = $(element);
if (this.element.hasClass('pull-right'))
this.opens = 'left';
if (this.element.is('input')) {
this.element.on({
click: $.proxy(this.show, this),
focus: $.proxy(this.show, this)
});
} else {
this.element.on('click', $.proxy(this.show, this));
}
if (hasOptions) {
if(typeof options.locale == 'object') {
$.each(localeObject, function (property, value) {
localeObject[property] = options.locale[property] || value;
});
}
}
var DRPTemplate = '<div class="daterangepicker dropdown-menu">' +
'<div class="calendar left"></div>' +
'<div class="calendar right"></div>' +
'<div class="ranges">' +
'<div class="range_inputs">' +
'<div>' +
'<label for="daterangepicker_start">' + this.locale.fromLabel + '</label>' +
'<input class="input-mini form-control" type="text" name="daterangepicker_start" value="" disabled="disabled" />' +
'</div>' +
'<div>' +
'<label for="daterangepicker_end">' + this.locale.toLabel + '</label>' +
'<input class="input-mini form-control" type="text" name="daterangepicker_end" value="" disabled="disabled" />' +
'</div>' +
'<button class="btn btn-small" disabled="disabled">' + this.locale.applyLabel + '</button>' +
'</div>' +
'</div>' +
'</div>';
this.parentEl = (hasOptions && options.parentEl && $(options.parentEl)) || $(this.parentEl);
//the date range picker
this.container = $(DRPTemplate).appendTo(this.parentEl);
if (hasOptions) {
if (typeof options.format == 'string')
this.format = options.format;
if (typeof options.separator == 'string')
this.separator = options.separator;
if (typeof options.startDate == 'string')
this.startDate = Date.parse(options.startDate, this.format);
if (typeof options.endDate == 'string')
this.endDate = Date.parse(options.endDate, this.format);
if (typeof options.minDate == 'string')
this.minDate = Date.parse(options.minDate, this.format);
if (typeof options.maxDate == 'string')
this.maxDate = Date.parse(options.maxDate, this.format);
if (typeof options.startDate == 'object')
this.startDate = options.startDate;
if (typeof options.endDate == 'object')
this.endDate = options.endDate;
if (typeof options.minDate == 'object')
this.minDate = options.minDate;
if (typeof options.maxDate == 'object')
this.maxDate = options.maxDate;
if (typeof options.ranges == 'object') {
for (var range in options.ranges) {
var start = options.ranges[range][0];
var end = options.ranges[range][1];
if (typeof start == 'string')
start = Date.parse(start);
if (typeof end == 'string')
end = Date.parse(end);
// If we have a min/max date set, bound this range
// to it, but only if it would otherwise fall
// outside of the min/max.
if (this.minDate && start < this.minDate)
start = this.minDate;
if (this.maxDate && end > this.maxDate)
end = this.maxDate;
// If the end of the range is before the minimum (if min is set) OR
// the start of the range is after the max (also if set) don't display this
// range option.
if ((this.minDate && end < this.minDate) || (this.maxDate && start > this.maxDate))
{
continue;
}
this.ranges[range] = [start, end];
}
var list = '<ul>';
for (var range in this.ranges) {
list += '<li>' + range + '</li>';
}
list += '<li>' + this.locale.customRangeLabel + '</li>';
list += '</ul>';
this.container.find('.ranges').prepend(list);
}
// update day names order to firstDay
if (typeof options.locale == 'object') {
if (typeof options.locale.firstDay == 'number') {
this.locale.firstDay = options.locale.firstDay;
var iterator = options.locale.firstDay;
while (iterator > 0) {
this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
iterator--;
}
}
}
if (typeof options.opens == 'string')
this.opens = options.opens;
if (typeof options.showWeekNumbers == 'boolean') {
this.showWeekNumbers = options.showWeekNumbers;
}
if (typeof options.buttonClasses == 'string') {
this.buttonClasses = [options.buttonClasses];
}
if (typeof options.buttonClasses == 'object') {
this.buttonClasses = options.buttonClasses;
}
}
//apply CSS classes to buttons
var c = this.container;
$.each(this.buttonClasses, function (idx, val) {
c.find('button').addClass(val);
});
if (this.opens == 'right') {
//swap calendar positions
var left = this.container.find('.calendar.left');
var right = this.container.find('.calendar.right');
left.removeClass('left').addClass('right');
right.removeClass('right').addClass('left');
}
if (typeof options == 'undefined' || typeof options.ranges == 'undefined')
this.container.find('.calendar').show();
if (typeof cb == 'function')
this.cb = cb;
this.container.addClass('opens' + this.opens);
//event listeners
this.container.on('mousedown', $.proxy(this.mousedown, this));
this.container.find('.calendar').on('click', '.prev', $.proxy(this.clickPrev, this));
this.container.find('.calendar').on('click', '.next', $.proxy(this.clickNext, this));
this.container.find('.ranges').on('click', 'button', $.proxy(this.clickApply, this));
this.container.find('.calendar').on('click', 'td.available', $.proxy(this.clickDate, this));
this.container.find('.calendar').on('mouseenter', 'td.available', $.proxy(this.enterDate, this));
this.container.find('.calendar').on('mouseleave', 'td.available', $.proxy(this.updateView, this));
this.container.find('.ranges').on('click', 'li', $.proxy(this.clickRange, this));
this.container.find('.ranges').on('mouseenter', 'li', $.proxy(this.enterRange, this));
this.container.find('.ranges').on('mouseleave', 'li', $.proxy(this.updateView, this));
this.element.on('keyup', $.proxy(this.updateFromControl, this));
this.updateView();
this.updateCalendars();
};
DateRangePicker.prototype = {
constructor: DateRangePicker,
mousedown: function (e) {
e.stopPropagation();
e.preventDefault();
},
updateView: function () {
this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() });
this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() });
this.container.find('input[name=daterangepicker_start]').val(this.startDate.toString(this.format));
this.container.find('input[name=daterangepicker_end]').val(this.endDate.toString(this.format));
if (this.startDate.equals(this.endDate) || this.startDate.isBefore(this.endDate)) {
this.container.find('button').removeAttr('disabled');
} else {
this.container.find('button').attr('disabled', 'disabled');
}
},
updateFromControl: function () {
if (!this.element.is('input')) return;
var dateString = this.element.val().split(this.separator);
var start = Date.parseExact(dateString[0], this.format);
var end = Date.parseExact(dateString[1], this.format);
if (start == null || end == null) return;
if (end.isBefore(start)) return;
this.startDate = start;
this.endDate = end;
this.updateView();
this.cb(this.startDate, this.endDate);
this.updateCalendars();
},
notify: function () {
this.updateView();
if (this.element.is('input')) {
this.element.val(this.startDate.toString(this.format) + this.separator + this.endDate.toString(this.format));
}
this.cb(this.startDate, this.endDate);
},
move: function () {
var parentOffset = {
top: this.parentEl.offset().top - this.parentEl.scrollTop(),
left: this.parentEl.offset().left - this.parentEl.scrollLeft()
};
if (this.opens == 'left') {
this.container.css({
top: this.element.offset().top + this.element.outerHeight(),
right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left,
left: 'auto'
});
} else {
this.container.css({
top: this.element.offset().top + this.element.outerHeight(),
left: this.element.offset().left - parentOffset.left,
right: 'auto'
});
}
},
show: function (e) {
this.container.show();
this.move();
if (e) {
e.stopPropagation();
e.preventDefault();
}
this.changed = false;
$(document).on('mousedown', $.proxy(this.hide, this));
},
hide: function (e) {
this.container.hide();
$(document).off('mousedown', this.hide);
if (this.changed) {
this.changed = false;
this.notify();
}
},
enterRange: function (e) {
var label = e.target.innerHTML;
if (label == this.locale.customRangeLabel) {
this.updateView();
} else {
var dates = this.ranges[label];
this.container.find('input[name=daterangepicker_start]').val(dates[0].toString(this.format));
this.container.find('input[name=daterangepicker_end]').val(dates[1].toString(this.format));
}
},
clickRange: function (e) {
var label = e.target.innerHTML;
if (label == this.locale.customRangeLabel) {
this.container.find('.calendar').show();
} else {
var dates = this.ranges[label];
this.startDate = dates[0];
this.endDate = dates[1];
this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() });
this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() });
this.updateCalendars();
this.changed = true;
this.container.find('.calendar').hide();
this.hide();
}
},
clickPrev: function (e) {
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add({ months: -1 });
} else {
this.rightCalendar.month.add({ months: -1 });
}
this.updateCalendars();
},
clickNext: function (e) {
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add({ months: 1 });
} else {
this.rightCalendar.month.add({ months: 1 });
}
this.updateCalendars();
},
enterDate: function (e) {
var title = $(e.target).attr('title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].toString(this.format));
} else {
this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].toString(this.format));
}
},
clickDate: function (e) {
var title = $(e.target).attr('title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
startDate = this.leftCalendar.calendar[row][col];
endDate = this.endDate;
} else {
startDate = this.startDate;
endDate = this.rightCalendar.calendar[row][col];
}
cal.find('td').removeClass('active');
if (startDate.equals(endDate) || startDate.isBefore(endDate)) {
$(e.target).addClass('active');
if (!startDate.equals(this.startDate) || !endDate.equals(this.endDate))
this.changed = true;
this.startDate = startDate;
this.endDate = endDate;
}
this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() });
this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() });
this.updateCalendars();
},
clickApply: function (e) {
this.hide();
},
updateCalendars: function () {
this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.getMonth(), this.leftCalendar.month.getFullYear());
this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.getMonth(), this.rightCalendar.month.getFullYear());
this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.endDate));
this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate));
},
buildCalendar: function (month, year) {
var firstDay = Date.today().set({ day: 1, month: month, year: year });
var lastMonth = firstDay.clone().add(-1).day().getMonth();
var lastYear = firstDay.clone().add(-1).day().getFullYear();
var daysInMonth = Date.getDaysInMonth(year, month);
var daysInLastMonth = Date.getDaysInMonth(lastYear, lastMonth);
var dayOfWeek = firstDay.getDay();
//initialize a 6 rows x 7 columns array for the calendar
var calendar = Array();
for (var i = 0; i < 6; i++) {
calendar[i] = Array();
}
//populate the calendar with date objects
var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
if (startDay > daysInLastMonth)
startDay -= 7;
if (dayOfWeek == this.locale.firstDay)
startDay = daysInLastMonth - 6;
var curDate = Date.today().set({ day: startDay, month: lastMonth, year: lastYear });
for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = curDate.clone().add(1).day()) {
if (i > 0 && col % 7 == 0) {
col = 0;
row++;
}
calendar[row][col] = curDate;
}
return calendar;
},
renderCalendar: function (calendar, selected, minDate, maxDate) {
var html = '<table class="table-condensed">';
html += '<thead>';
html += '<tr>';
// add empty cell for week number
if (this.showWeekNumbers)
html += '<th></th>';
if (!minDate || minDate < calendar[1][1])
{
html += '<th class="prev available"><i class="icon-arrow-left"></i></th>';
}
else
{
html += '<th></th>';
}
html += '<th colspan="5" style="width: auto">' + this.locale.monthNames[calendar[1][1].getMonth()] + calendar[1][1].toString(" yyyy") + '</th>';
if (!maxDate || maxDate > calendar[1][1])
{
html += '<th class="next available"><i class="icon-arrow-right"></i></th>';
}
else
{
html += '<th></th>';
}
html += '</tr>';
html += '<tr>';
// add week number label
if (this.showWeekNumbers)
html += '<th class="week">' + this.locale.weekLabel + '</th>';
$.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
html += '<th>' + dayOfWeek + '</th>';
});
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for (var row = 0; row < 6; row++) {
html += '<tr>';
// add week number
if (this.showWeekNumbers)
html += '<td class="week">' + calendar[row][0].getWeek() + '</td>';
for (var col = 0; col < 7; col++) {
var cname = 'available ';
cname += (calendar[row][col].getMonth() == calendar[1][1].getMonth()) ? '' : 'off';
// Normalise the time so the comparison won't fail
selected.setHours(0,0,0,0);
if ( (minDate && calendar[row][col] < minDate) || (maxDate && calendar[row][col] > maxDate))
{
cname = 'off disabled';
}
else if (calendar[row][col].equals(selected))
{
cname += 'active';
}
var title = 'r' + row + 'c' + col;
html += '<td class="' + cname + '" title="' + title + '">' + calendar[row][col].getDate() + '</td>';
}
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
return html;
}
};
$.fn.daterangepicker = function (options, cb) {
this.each(function() {
var el = $(this);
if (!el.data('daterangepicker'))
el.data('daterangepicker', new DateRangePicker(el, options, cb));
});
return this;
};
} (window.jQuery);
| bernatixer/QUEDEM.CAT | assets/bootstrap-daterangepicker/daterangepicker.js | JavaScript | mit | 22,195 |
/**
* This module is used to create different point distributions that can be
* turned into different tile sets when made into a graph format. There are
* various different distributions that can be used to create interesting
* tile patterns when turned into a voronoi diagram.
*
* @class PointDistribution
*/
"use strict";
import Poisson from "poisson-disk-sample";
import Vector from "../geometry/Vector";
import Rectangle from "../geometry/Rectangle";
import Rand from "./Rand";
/**
* Creates a random distribution of points in a particular bounding box
* with a particular average distance between points.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @param {number} [seed=null] If specified use a local seed for creating the point
* distribution. Otherwise, use the current global seed for generation
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function random(bbox, d, seed = null) {
const rng = seed ? new Rand(seed) : Rand;
const nPoints = bbox.area / (d * d);
let points = [];
for (let i = 0; i < nPoints; i++) {
points.push(rng.vector(bbox));
}
return points;
}
/**
* Creates a square grid like distribution of points in a particular bounding
* box with a particular distance between points.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function square(bbox, d) {
const dx = d / 2;
const dy = dx;
let points = [];
for (let y = 0; y < bbox.height; y += d) {
for (let x = 0; x < bbox.width; x += d) {
points.push(new Vector(dx + x, dy + y));
}
}
return points;
}
/**
* Creates a square grid like distribution of points in a particular bounding
* box with a particular distance between points. The grid has also been
* slightly purturbed or jittered so that the distribution is not completely
* even.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @param {number} amm The ammount of jitter that has been applied to the grid
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function squareJitter(bbox, d, amm) {
return square(bbox, d).map(v => Rand.jitter(v, amm));
}
/**
* Creates a uniform hexagonal distribution of points in a particular bounding
* box with a particular distance between points. The hexagons can also be
* specified to have a particular width or height as well as creating hexagons
* that have "pointy" tops or "flat" tops. By default it makes flat tops.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @param {boolean} [flatTop=true] Create hecagons with flat tops by default.
* Otherwise go with the pointy top hexagons.
* @param {number} w The width of the hexagon tiles
* @param {number} h The height of the hexagon tiles
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function hexagon(bbox, d, flatTop = true, w, h) {
// Need to allow for the change of height and width
// Running into "Uncaught Voronoi.closeCells() > this makes no sense!"
const dx = d / 2;
const dy = dx;
let points = [];
const altitude = Math.sqrt(3) / 2 * d;
var N = Math.sqrt(bbox.area / (d * d));
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
points.push(new Vector((0.5 + x) / N * bbox.width,
(0.25 + 0.5 * x % 2 + y) / N * bbox.height));
// points.push(new Vector((y % 2) * dx + x * d + dx, y * d + dy)); // Pointy Top
// points.push(new Vector(x * d, (x % 2) * dx + y * d)); // Flat Top
}
}
return points;
}
/**
* Creates a blue noise distribution of points in a particular bounding box
* with a particular average distance between points. This is done by
* creating a grid system and picking a random point in each grid. This has
* the effect of creating a less random distribution of points. The second
* parameter m determins the spacing between points in the grid. This ensures
* that no two points are in the same grid.
*
* @summary Create a jittered grid based random blue noise point distribution.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @param {number} [seed=null] If specified use a local seed for creating the point
* distribution. Otherwise, use the current global seed for generation
* @param {number} [m=0] Maximum distance away from the edge of the grid that a
* point can be placed. This acts to increase the padding between points.
* This makes the noise less random. This number must be smaller than d.
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function jitteredGrid(bbox, d, seed = null, m = 0) {
const rng = seed ? new Rand(seed) : Rand;
let points = [];
let pointBox;
for (let y = 0; y < bbox.height - d; y += d) {
for (let x = 0; x < bbox.width - d; x += d) {
// Local bbox for the point to generate in
const boxPos = new Vector(x - d + m, y - d + m);
pointBox = new Rectangle(boxPos, x - m, y - m);
points.push(rng.vector(pointBox));
}
}
return points;
}
/**
* Creates a poisson, or blue noise distribution of points in a particular
* bounding box with a particular average distance between points. This is
* done by using poisson disk sampling which tries to create points so that the
* distance between neighbors is as close to a fixed number (the distance d)
* as possible. This algorithm is implemented using the poisson dart throwing
* algorithm.
*
* @summary Create a blue noise distribution of points using poisson disk
* sampling.
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @returns {Vector[]} The list of randomly distributed points
*
* @see {@link https://www.jasondavies.com/poisson-disc/}
* @see {@link https://github.com/jeffrey-hearn/poisson-disk-sample}
* @memberof PointDistribution
*/
export function poisson(bbox, d) {
var sampler = new Poisson(bbox.width, bbox.height, d, d);
var solution = sampler.sampleUntilSolution();
var points = solution.map(point => Vector.add(new Vector(point), bbox.position));
return points;
}
/**
* Creates a blue noise distribution of points in a particular bounding box
* with a particular average distance between points. This is done by using
* recursive wang tiles to create this distribution of points.
*
* @summary Not Implemented Yet
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function recursiveWang(bbox, d) {
throw "Error: Not Implemented";
}
/**
* Creates a circular distribution of points in a particular bounding box
* with a particular average distance between points.
*
* @summary Not Implemented Yet
*
* @export
* @param {Rectangle} bbox The bounding box to create the points in
* @param {number} d Average distance between points
* @returns {Vector[]} The list of randomly distributed points
* @memberof PointDistribution
*/
export function circular(bbox, d) {
throw "Error: Not Implemented";
} | Evelios/Atum | src/utilities/PointDistribution.js | JavaScript | mit | 7,914 |
'use strict';
angular.module('refugeesApp')
.controller('SettingsController', function ($scope, Principal, Auth, Language, $translate) {
$scope.success = null;
$scope.error = null;
Principal.identity().then(function(account) {
$scope.settingsAccount = copyAccount(account);
});
$scope.save = function () {
Auth.updateAccount($scope.settingsAccount).then(function() {
$scope.error = null;
$scope.success = 'OK';
Principal.identity(true).then(function(account) {
$scope.settingsAccount = copyAccount(account);
});
Language.getCurrent().then(function(current) {
if ($scope.settingsAccount.langKey !== current) {
$translate.use($scope.settingsAccount.langKey);
}
});
}).catch(function() {
$scope.success = null;
$scope.error = 'ERROR';
});
};
/**
* Store the "settings account" in a separate variable, and not in the shared "account" variable.
*/
var copyAccount = function (account) {
return {
activated: account.activated,
email: account.email,
firstName: account.firstName,
langKey: account.langKey,
lastName: account.lastName,
login: account.login
}
}
});
| hubek/Refugees | src/main/webapp/scripts/app/account/settings/settings.controller.js | JavaScript | mit | 1,537 |
var UTIL = require('./util');
var ShadowNode;
module.exports = ShadowNode = function(patch,options){
this.shadow = options.shadow;
this.native = options.native;
this.elem = new patch.type(this);
this.elem.props = patch.props;
this.elem.props.children = patch.children;
this.elem.state = this.elem.getInitialState ? this.elem.getInitialState() : {};
this.elem.componentWillMount();
this.render();
this.elem.componentDidMount();
};
var proto = ShadowNode.prototype;
Object.defineProperty(proto,'parent',{
get : function(){
return this.native.parent;
}
});
proto.setPatch = function(patch){
var oldProps = this.elem.props;
this.elem._isUpdating = true;
var newProps = patch.props;
newProps.children = patch.children;
this.elem.componentWillRecieveProps(newProps);
this.elem.props = newProps;
this.elem.componentDidRecieveProps(oldProps);
this.update();
};
proto.update = function(){
// This is called by set state and by props updating
this.elem.componentWillUpdate();
this.render();
this.elem.componentWillUpdate();
};
proto.remove = function(){
this.elem.componentWillUnmount();
this.destroyed = true;
if (this.figure){
return this.figure.remove();
}
this.shadow = void 0;
this.figure = void 0;
this.native = void 0;
this.elem.componentDidUnmount();
};
proto.render = function(){
var newPatch = this.elem.render();
var lastPatch = this.lastPatch;
this.lastPatch = newPatch;
if (!lastPatch && !newPatch) return;
if (UTIL.isNative(newPatch)){
if (this.figure){
this.figure.remove();
this.figure = void 0;
}
this.native.shadowTail = this;
return this.native.setPatch(newPatch);
}
if (UTIL.differentTypes(lastPatch,newPatch)){
if (this.figure) this.figure.remove();
this.figure = new ShadowNode(newPatch,{
shadow : this,native : this.native
});
return this.figure;
}
if (UTIL.differentPatch(lastPatch,newPatch)){
// component will update
this.figure.setPatch(newPatch);
// component did update
}
};
| guisouza/tEmbO | src/render/ShadowNode.js | JavaScript | mit | 2,061 |
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var videoWorksSchema = new Schema ({
title: {
type: String
},
directedBy: {
type: [String]
},
editedBy: {
type: [String]
},
cast: {
type: [String]
},
videoUrl: {
type: String
},
copyright: {
type: String
},
workInfo: {
type: String
},
coverImageUrl: {
type: String
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('videoWorks', videoWorksSchema);
| joshm101/blackwashed_portfolio | modules/video-works/server/models/video-works.server.models.js | JavaScript | mit | 527 |
'use strict';
module.exports = {
extends: ['./index',
'./rules/imports',
'./rules/frontend',
'./rules/vue'].map(require.resolve).concat(['plugin:vue/recommended']),
parser: 'vue-eslint-parser',
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module',
ecmaVersion: 2017,
ecmaFeatures: {
jsx: true,
experimentalObjectRestSpread: true,
},
},
rules: {
// this two doesn't work in vue
'import/no-named-as-default': 'off',
'import/no-named-as-default-member': 'off',
},
};
| AfterShip/eslint-config-aftership | vue.js | JavaScript | mit | 508 |
import React, {PropTypes} from 'react';
import { Link, IndexLink } from 'react-router';
// import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap';
class Header extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id="container" className="link_box">
<div id="itemA"></div>
<div id="itemB">
<Link to="/">
<img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/>
</Link>
</div>
<div id="itemC">
<Link to="/">
<img src=" http://cdn.dscount.com/images_2016/top/btn_dscoupon02.jpg" alt="dscount"/>
</Link>
</div>
<div id="itemD"></div>
<div id="itemE">
<Link to="" >ログイン</Link>
</div>
<div id="itemF">
<Link to="/signup">会員登録</Link>
</div>
<div id="itemG">
<a href="#" >マイページ{" "}▼</a>
</div>
<div id="itemH">
<a href="#" >お客様センター{" "}▼</a>
</div>
<div id="itemI">
<a href="#" >
<span className="glyphicon glyphicon-shopping-cart">(0)</span>
</a>
</div>
<div id="itemJ">
<a href="#" >
<span className="glyphicon glyphicon-heart">(1)</span>
</a>
</div>
<form id="itemK">
<div className="field">
<button className="drop-down-btn" type="button" id="search">総合検索{" "}▼</button>
<input className="header-search-input" type="text" id="searchterm" placeholder=" what do you want ?" />
<button className="search-submit" type="button" id="search">
<span className="glyphicon glyphicon-search"></span>
</button>
</div>
</form>
<div id="itemL"></div>
</div>
);
}
}
export default Header;
| masakiando/dscount | src/components/common/Header.js | JavaScript | mit | 1,959 |
//ButtonTable is a very very special case, because I am still not sure why it is a table :-)
// alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time.
// we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from AbstractTable
//button field is only a data structure that is stored under buttons collection
var ButtonField = function (nam, label, actionName)
{
this.name = nam;
this.label = label;
this.actionName = actionName;
};
var ButtonPanel = function ()
{
this.name = null;
this.P2 = null;
this.renderingOption = null;
this.buttons = new Object(); //collection of buttonFields
};
ButtonPanel.prototype.setData = function (dc)
{
var data = dc.grids[this.name];
if (data.length <= 1)
{
if (this.renderingOption == 'nextToEachOther')
{
this.P2.hideOrShowPanels([this.name], 'none');
}
else
{
var listName = this.name + 'ButtonList';
var buttonList = this.P2.doc.getElementById(listName);
//should we do the following or just say buttonList.innerHTML = ''
while (buttonList.options.length)
{
buttonList.remove(0);
}
}
return;
}
data = this.transposeIfRequired(data);
//possible that it was hidden earlier.. Let us show it first
this.P2.hideOrShowPanels([this.name], '');
if (this.renderingOption == 'nextToEachOther')
this.enableButtons(data);
else
this.buildDropDown(data);
};
//enable/disable buttons in a button panel based on data received from server
ButtonPanel.prototype.enableButtons = function (data)
{
var doc = this.P2.doc;
var n = data.length;
if (n <= 1) return;
//if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes
var hasFlag = data[0].length > 1;
//for convenience, get the buttons into a collection indexed by name
var btnsToEnable = {};
for (var i = 1; i < n; i++)
{
var row = data[i];
if (hasFlag)
{
var flag = row[1];
if (!flag || flag == '0')
continue;
}
btnsToEnable[row[0]] = true;
}
//now let us go thru each button, and hide or who it
for (var btnName in this.buttons)
{
var ele = doc.getElementById(btnName);
if (!ele)
{
debug('Design Error: Button panel ' + this.name + ' has not produced a DOM element with name ' + btnName);
continue;
}
ele.style.display = btnsToEnable[btnName] ? '' : 'none';
}
};
ButtonPanel.prototype.buildDropDown = function (data)
{
var flag;
var doc = this.P2.doc;
var ele = doc.getElementById(this.name + 'ButtonList');
if (!ele)
{
debug('DESIGN ERROR: Button Panel ' + this.name + ' has not produced a drop-down boc with name = ' + this.Name + 'ButtonList');
return;
}
//zap options first
ele.innerHTML = '';
//that took away the first one also. Add a blank option
var option = doc.createElement('option');
ele.appendChild(option);
//this.buttons has all the button names defined for this panel with value = 'disabled'
// i.e. this.buttons['button1'] = 'disabled';
// for the rows that are in data, mark them as enabled.
var n = data.length;
if (n <= 1) return;
if ((n == 2) && (data[0].length > 1))
{
var hasFlag = data[0].length > 1;
for (var i = 0; i < data[0].length; i++)
{
if (hasFlag)
{
flag = data[1][i];
if (!flag || flag == '0')
continue;
}
var btnName = data[0][i];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
else
{
var hasFlag = data[0].length > 1;
for (var i = 1; i < n; i++)
{
if (hasFlag)
{
flag = data[i][1];
if (!flag || flag == '0')
continue;
}
var btnName = data[i][0];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
};
//Standard way of getting data from server is a grid with first row as header row and rest a data rows.
//But it is possible that server may send button names in first row, and optional second row as enable flag.
//We detect the second case, and transpose the grid, so that a common logic can be used.
ButtonPanel.prototype.transposeIfRequired = function (data)
{
//we need to transpose only if we have one or two rows
var nbrRows = data && data.length;
if (!nbrRows || nbrRows > 2)
return data;
var row = data[0];
var nbrCols = row.length;
if (!nbrCols)
return data;
//We make a simple assumption, that the label for last column can not clash with the name of a button.
if (!this.buttons[row[nbrCols - 1]])
return data;
//we transpose the grid, with an empty header row
var newData = null;
if (data.length == 1) //button name only
{
newData = [['']];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i]]);
}
else
{
//button name with enable flag
newData = [['', '']];
var row1 = data[1];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i], row1[i]]);
}
return newData;
};
| ExilantTechnologies/ExilityCore-5.0.0-ExampleProject | WebContent/exilityClient/js/api/features/tableButton.js | JavaScript | mit | 6,354 |
/*
function Canvas(paper, props){
var
props = $.extend(true, {
"x" : 0,
"y" : 0,
"width" : "100%",
"height" : "100%"
}, (props || {})),
_scale = 1,
_translateX = 0,
_translateY = 0,
self = this,
lx = 0,
ly = 0,
ox = 0,
oy = 0,
canvasBg = paper.rect(props.x, props.y, props.width, props.height),
canvas = paper.group(),
elements = []
;
var
moveFnc = function(dx, dy){
lx = dx * (1 / _scale) + ox;
ly = dy * (1 / _scale) + oy;
self.setTranslate(lx, ly);
},
startFnc = function(){
var transform = canvasBg.transform();
for(var i = 0; i < transform.length; i++){
if(transform[i][0].toLowerCase() === "t"){
ox = parseInt(transform[i][1]) * _scale;
oy = parseInt(transform[i][2]) * _scale;
}
}
},
endFnc = function(){
ox = lx;
oy = ly;
},
applyTransform = function(){
canvas.transform("s" + _scale + "t" + _translateX + "," + _translateY);
canvasBg.transform("s" + _scale + "t" + _translateX + "," + _translateY);
}
;
this.add = function(el){
canvas.add(el.getObj());
elements.push(el);
return this;
};
this.setTranslate = function(x, y){
_translateX = x;
_translateY = y;
applyTransform();
return this;
};
this.getTranslate = function(){
return {
"x" : _translateX,
"y" : _translateY
};
};
this.setScale = function(s, onEachElement){
_scale = s;
applyTransform();
if(onEachElement){
for(var i = 0; i < elements.length; i++){
onEachElement(elements[i], s);
}
}
return this;
};
this.getScale = function(){
return _scale;
};
this.getProps = function(){
return props;
};
canvasBg.attr({
"fill" : "rgba(255, 255, 0, .5)",
"stroke" : "#000000",
"stroke-width" : 1
});
this
.setTranslate(0, 0)
.setScale(1)
;
canvasBg.drag(moveFnc, startFnc, endFnc);
}
*/ | meszaros-lajos-gyorgy/meszaros-lajos-gyorgy.github.io | logica/js/class/Canvas.js | JavaScript | mit | 1,852 |
/*
* Copyright (c) 2014 airbug inc. http://airbug.com
*
* bugpack-registry may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------
var buildbug = require("buildbug");
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var buildProject = buildbug.buildProject;
var buildProperties = buildbug.buildProperties;
var buildScript = buildbug.buildScript;
var buildTarget = buildbug.buildTarget;
var enableModule = buildbug.enableModule;
var parallel = buildbug.parallel;
var series = buildbug.series;
var targetTask = buildbug.targetTask;
//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------
var aws = enableModule("aws");
var bugpack = enableModule('bugpack');
var bugunit = enableModule('bugunit');
var core = enableModule('core');
var lintbug = enableModule("lintbug");
var nodejs = enableModule('nodejs');
var uglifyjs = enableModule("uglifyjs");
//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------
var name = "bugpack-registry";
var version = "0.1.7";
var dependencies = {
bugpack: "0.2.2"
};
//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------
buildProperties({
name: name,
version: version
});
buildProperties({
node: {
packageJson: {
name: "{{name}}",
version: "{{version}}",
description: "Registry builder for the bugpack package loader",
main: "./scripts/bugpack-registry-node.js",
author: "Brian Neisler <brian@airbug.com>",
dependencies: dependencies,
repository: {
type: "git",
url: "https://github.com/airbug/bugpack.git"
},
bugs: {
url: "https://github.com/airbug/bugpack/issues"
},
licenses: [
{
type : "MIT",
url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE"
}
]
},
sourcePaths: [
"../buganno/libraries/buganno/js/src",
"../bugcore/libraries/bugcore/js/src",
"../bugfs/libraries/bugfs/js/src",
"../bugmeta/libraries/bugmeta/js/src",
"./libraries/bugpack-registry/js/src"
],
scriptPaths: [
"../buganno/libraries/buganno/js/scripts",
"./projects/bugpack-registry-node/js/scripts"
],
readmePath: "./README.md",
unitTest: {
packageJson: {
name: "{{name}}-test",
version: "{{version}}",
main: "./scripts/bugpack-registry-node.js",
dependencies: dependencies,
scripts: {
test: "node ./test/scripts/bugunit-run.js"
}
},
sourcePaths: [
"../bugdouble/libraries/bugdouble/js/src",
"../bugunit/libraries/bugunit/js/src",
"../bugyarn/libraries/bugyarn/js/src"
],
scriptPaths: [
"../bugunit/libraries/bugunit/js/scripts"
],
testPaths: [
"../buganno/libraries/buganno/js/test",
"../bugcore/libraries/bugcore/js/test",
"../bugfs/libraries/bugfs/js/test",
"../bugmeta/libraries/bugmeta/js/test",
"./libraries/bugpack-registry/js/test"
]
}
},
lint: {
targetPaths: [
"."
],
ignorePatterns: [
".*\\.buildbug$",
".*\\.bugunit$",
".*\\.git$",
".*node_modules$"
]
}
});
//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------
// Clean BuildTarget
//-------------------------------------------------------------------------------
buildTarget("clean").buildFlow(
targetTask("clean")
);
// Local BuildTarget
//-------------------------------------------------------------------------------
buildTarget("local").buildFlow(
series([
targetTask("clean"),
targetTask('lint', {
properties: {
targetPaths: buildProject.getProperty("lint.targetPaths"),
ignores: buildProject.getProperty("lint.ignorePatterns"),
lintTasks: [
"cleanupExtraSpacingAtEndOfLines",
"ensureNewLineEnding",
"indentEqualSignsForPreClassVars",
"orderBugpackRequires",
"orderRequireAnnotations",
"updateCopyright"
]
}
}),
parallel([
series([
targetTask("createNodePackage", {
properties: {
packageJson: buildProject.getProperty("node.packageJson"),
packagePaths: {
"./": [buildProject.getProperty("node.readmePath")],
"./lib": buildProject.getProperty("node.sourcePaths").concat(
buildProject.getProperty("node.unitTest.sourcePaths")
),
"./scripts": buildProject.getProperty("node.scriptPaths").concat(
buildProject.getProperty("node.unitTest.scriptPaths")
),
"./test": buildProject.getProperty("node.unitTest.testPaths")
}
}
}),
targetTask('generateBugPackRegistry', {
init: function(task, buildProject, properties) {
var nodePackage = nodejs.findNodePackage(
buildProject.getProperty("node.packageJson.name"),
buildProject.getProperty("node.packageJson.version")
);
task.updateProperties({
sourceRoot: nodePackage.getBuildPath()
});
}
}),
targetTask("packNodePackage", {
properties: {
packageName: "{{node.packageJson.name}}",
packageVersion: "{{node.packageJson.version}}"
}
}),
targetTask('startNodeModuleTests', {
init: function(task, buildProject, properties) {
var packedNodePackage = nodejs.findPackedNodePackage(
buildProject.getProperty("node.packageJson.name"),
buildProject.getProperty("node.packageJson.version")
);
task.updateProperties({
modulePath: packedNodePackage.getFilePath()
});
}
}),
targetTask("s3PutFile", {
init: function(task, buildProject, properties) {
var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
buildProject.getProperty("node.packageJson.version"));
task.updateProperties({
file: packedNodePackage.getFilePath(),
options: {
acl: 'public-read',
encrypt: true
}
});
},
properties: {
bucket: "{{local-bucket}}"
}
})
])
])
])
).makeDefault();
// Prod BuildTarget
//-------------------------------------------------------------------------------
buildTarget("prod").buildFlow(
series([
targetTask("clean"),
targetTask('lint', {
properties: {
targetPaths: buildProject.getProperty("lint.targetPaths"),
ignores: buildProject.getProperty("lint.ignorePatterns"),
lintTasks: [
"cleanupExtraSpacingAtEndOfLines",
"ensureNewLineEnding",
"indentEqualSignsForPreClassVars",
"orderBugpackRequires",
"orderRequireAnnotations",
"updateCopyright"
]
}
}),
parallel([
//Create test bugpack-registry package
series([
targetTask('createNodePackage', {
properties: {
packageJson: buildProject.getProperty("node.unitTest.packageJson"),
packagePaths: {
"./": [buildProject.getProperty("node.readmePath")],
"./lib": buildProject.getProperty("node.sourcePaths").concat(
buildProject.getProperty("node.unitTest.sourcePaths")
),
"./scripts": buildProject.getProperty("node.scriptPaths").concat(
buildProject.getProperty("node.unitTest.scriptPaths")
),
"./test": buildProject.getProperty("node.unitTest.testPaths")
}
}
}),
targetTask('generateBugPackRegistry', {
init: function(task, buildProject, properties) {
var nodePackage = nodejs.findNodePackage(
buildProject.getProperty("node.unitTest.packageJson.name"),
buildProject.getProperty("node.unitTest.packageJson.version")
);
task.updateProperties({
sourceRoot: nodePackage.getBuildPath()
});
}
}),
targetTask('packNodePackage', {
properties: {
packageName: "{{node.unitTest.packageJson.name}}",
packageVersion: "{{node.unitTest.packageJson.version}}"
}
}),
targetTask('startNodeModuleTests', {
init: function(task, buildProject, properties) {
var packedNodePackage = nodejs.findPackedNodePackage(
buildProject.getProperty("node.unitTest.packageJson.name"),
buildProject.getProperty("node.unitTest.packageJson.version")
);
task.updateProperties({
modulePath: packedNodePackage.getFilePath(),
checkCoverage: true
});
}
})
]),
// Create production bugpack-registry package
series([
targetTask('createNodePackage', {
properties: {
packageJson: buildProject.getProperty("node.packageJson"),
packagePaths: {
"./": [buildProject.getProperty("node.readmePath")],
"./lib": buildProject.getProperty("node.sourcePaths"),
"./scripts": buildProject.getProperty("node.scriptPaths")
}
}
}),
targetTask('generateBugPackRegistry', {
init: function(task, buildProject, properties) {
var nodePackage = nodejs.findNodePackage(
buildProject.getProperty("node.packageJson.name"),
buildProject.getProperty("node.packageJson.version")
);
task.updateProperties({
sourceRoot: nodePackage.getBuildPath()
});
}
}),
targetTask('packNodePackage', {
properties: {
packageName: "{{node.packageJson.name}}",
packageVersion: "{{node.packageJson.version}}"
}
}),
targetTask("s3PutFile", {
init: function(task, buildProject, properties) {
var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
buildProject.getProperty("node.packageJson.version"));
task.updateProperties({
file: packedNodePackage.getFilePath(),
options: {
acl: 'public-read',
encrypt: true
}
});
},
properties: {
bucket: "{{prod-deploy-bucket}}"
}
}),
targetTask('npmConfigSet', {
properties: {
config: buildProject.getProperty("npmConfig")
}
}),
targetTask('npmAddUser'),
targetTask('publishNodePackage', {
properties: {
packageName: "{{node.packageJson.name}}",
packageVersion: "{{node.packageJson.version}}"
}
})
])
])
])
);
//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------
buildScript({
dependencies: [
"bugcore",
"bugflow",
"bugfs"
],
script: "./lintbug.js"
});
| airbug/bugpack-registry | buildbug.js | JavaScript | mit | 15,072 |
export default function(that) {
return !isNaN(that.curValue) && that.curValue%1===0;
}
| c0defre4k/vue-form-2 | lib/validation/rules/integer.js | JavaScript | mit | 89 |
'use strict';
angular.module('core').controller('SidebarController', ['$scope', 'Authentication',
function($scope, Authentication) {
$scope.authentication = Authentication;
}
]);
| Jean2bob/Gathering-mean-0.4 | modules/core/client/controllers/sidebar.client.controller.js | JavaScript | mit | 196 |
import superagent from 'superagent';
import config from '../config';
const { NODE_ENV } = process.env;
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__ || NODE_ENV === 'production') {
return `${config.apiHost}/v1${adjustedPath}`
}
return '/api' + adjustedPath;
}
export default class ApiClient {
constructor() {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
// if (__SERVER__ && req.get('cookie')) {
// request.set('cookie', req.get('cookie'));
// }
if (data) {
request.send(data);
}
if (__CLIENT__ && window.localStorage.authToken) {
request.set('authorization', window.localStorage.authToken)
}
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
/*
* There's a V8 bug where, when using Babel, exporting classes with only
* constructors sometimes fails. Until it's patched, this is a solution to
* "ApiClient is not defined" from issue #14.
* https://github.com/erikras/react-redux-universal-hot-example/issues/14
*
* Relevant Babel bug (but they claim it's V8): https://phabricator.babeljs.io/T2455
*
* Remove it at your own risk.
*/
empty() {}
}
| OKNoah/slipstream | src/helpers/ApiClient.js | JavaScript | mit | 1,542 |
version https://git-lfs.github.com/spec/v1
oid sha256:bd24e43ef20f9f9e3c711e3d54df98d049591993ab374dbc14fbe801ba528183
size 10061
| yogeshsaroya/new-cdnjs | ajax/libs/rimg/1.5.0/rimg.min.js | JavaScript | mit | 130 |
module.exports = {
snowboy: {
models: {
file: "node_modules/snowboy/resources/snowboy.umdl",
sensitivity: "0.5",
hotwords: "snowboy"
},
detector: {
resource: "node_modules/snowboy/resources/common.res",
audioGain: 2.0
}
}
};
| joyarzun/speeech | src/defaultConfig.js | JavaScript | mit | 275 |
var jshint = require('jshint').JSHINT,
colors = require('colors');
module.exports = function(code) {
var options = {
devel: true,
node: true,
predef: ['expect', 'done'],
undef: true
},
isValid = jshint(code, options);
if (!isValid) {
var errorsByLineNumber = {};
jshint.errors.map(function(error) {
errorsByLineNumber[error.line] = error.reason;
});
code.split('\n').forEach(function(line, index) {
var lineNumber = index + 1;
if (errorsByLineNumber[lineNumber]) {
line = line.yellow + '\t' + ('// ERROR: ' + errorsByLineNumber[lineNumber]).red
}
console.log(line);
});
}
return isValid;
};
| cymen/literate-jasmine | src/linter.js | JavaScript | mit | 697 |
/**
* ghostHunter - 0.4.0
* Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me)
* MIT Licensed
* @license
*/
(function( $ ) {
/* Include the Lunr library */
var lunr=require('./lunr.min.js');
//This is the main plugin definition
$.fn.ghostHunter = function( options ) {
//Here we use jQuery's extend to set default values if they weren't set by the user
var opts = $.extend( {}, $.fn.ghostHunter.defaults, options );
if( opts.results )
{
pluginMethods.init( this , opts );
return pluginMethods;
}
};
$.fn.ghostHunter.defaults = {
resultsData : false,
onPageLoad : true,
onKeyUp : false,
result_template : "<a href='{{link}}'><p><h2>{{title}}</h2><h4>{{prettyPubDate}}</h4></p></a>",
info_template : "<p>Number of posts found: {{amount}}</p>",
displaySearchInfo : true,
zeroResultsInfo : true,
before : false,
onComplete : false,
includepages : false,
filterfields : false
};
var prettyDate = function(date) {
var d = new Date(date);
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear();
};
var pluginMethods = {
isInit : false,
init : function( target , opts ){
var that = this;
this.target = target;
this.results = opts.results;
this.blogData = {};
this.result_template = opts.result_template;
this.info_template = opts.info_template;
this.zeroResultsInfo = opts.zeroResultsInfo;
this.displaySearchInfo = opts.displaySearchInfo;
this.before = opts.before;
this.onComplete = opts.onComplete;
this.includepages = opts.includepages;
this.filterfields = opts.filterfields;
//This is where we'll build the index for later searching. It's not a big deal to build it on every load as it takes almost no space without data
this.index = lunr(function () {
this.field('title', {boost: 10})
this.field('description')
this.field('link')
this.field('plaintext', {boost: 5})
this.field('pubDate')
this.field('tag')
this.ref('id')
});
if ( opts.onPageLoad ) {
function miam () {
that.loadAPI();
}
window.setTimeout(miam, 1);
} else {
target.focus(function(){
that.loadAPI();
});
}
target.closest("form").submit(function(e){
e.preventDefault();
that.find(target.val());
});
if( opts.onKeyUp ) {
target.keyup(function() {
that.find(target.val());
});
}
},
loadAPI : function(){
if(this.isInit) return false;
/* Here we load all of the blog posts to the index.
This function will not call on load to avoid unnecessary heavy
operations on a page if a visitor never ends up searching anything. */
var index = this.index,
blogData = this.blogData;
obj = {limit: "all", include: "tags", formats:["plaintext"]};
if ( this.includepages ){
obj.filter="(page:true,page:false)";
}
$.get(ghost.url.api('posts',obj)).done(function(data){
searchData = data.posts;
searchData.forEach(function(arrayItem){
var tag_arr = arrayItem.tags.map(function(v) {
return v.name; // `tag` object has an `name` property which is the value of tag. If you also want other info, check API and get that property
})
if(arrayItem.meta_description == null) { arrayItem.meta_description = '' };
var category = tag_arr.join(", ");
if (category.length < 1){
category = "undefined";
}
var parsedData = {
id : String(arrayItem.id),
title : String(arrayItem.title),
description : String(arrayItem.meta_description),
plaintext : String(arrayItem.plaintext),
pubDate : String(arrayItem.created_at),
tag : category,
featureImage : String(arrayItem.feature_image),
link : String(arrayItem.url)
}
parsedData.prettyPubDate = prettyDate(parsedData.pubDate);
var tempdate = prettyDate(parsedData.pubDate);
index.add(parsedData)
blogData[arrayItem.id] = {
title: arrayItem.title,
description: arrayItem.meta_description,
pubDate: tempdate,
featureImage: arrayItem.feature_image,
link: arrayItem.url
};
});
});
this.isInit = true;
},
find : function(value){
var searchResult = this.index.search(value);
var results = $(this.results);
var resultsData = [];
results.empty();
if(this.before) {
this.before();
};
if(this.zeroResultsInfo || searchResult.length > 0)
{
if(this.displaySearchInfo) results.append(this.format(this.info_template,{"amount":searchResult.length}));
}
for (var i = 0; i < searchResult.length; i++)
{
var lunrref = searchResult[i].ref;
var postData = this.blogData[lunrref];
results.append(this.format(this.result_template,postData));
resultsData.push(postData);
}
if(this.onComplete) {
this.onComplete(resultsData);
};
},
clear : function(){
$(this.results).empty();
this.target.val("");
},
format : function (t, d) {
return t.replace(/{{([^{}]*)}}/g, function (a, b) {
var r = d[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
}
}
})( jQuery );
| rkalis/roscasper | assets/ghostHunter/src/ghosthunter-nodependency.js | JavaScript | mit | 5,344 |
import React, {
PropTypes,
} from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';
const styles = StyleSheet.create({
all: {
paddingHorizontal: 10,
paddingVertical: 5,
},
text: {
fontSize: 12,
color: '#666',
},
});
function ListItemTitle(props) {
return (
<View style={styles.all}>
<Text
style={styles.text}
>
{props.text}
</Text>
</View>
);
}
ListItemTitle.propTypes = {
text: PropTypes.string,
};
ListItemTitle.defaultProps = {
text: '',
};
export default ListItemTitle;
| dragonwong/rnx-ui | Example/src/component/List/ListItemTitle/index.js | JavaScript | mit | 576 |
import axios from 'axios';
import {getAuthInfo} from './firebase-service';
import {VIANCA, CHAN, TOPA, IBA_COLOMBIA} from './service-store';
export const ERROR_RESULT = 'ERROR';
export const RESERVED_RESULT = 'R';
export const INSUFICIENT_RESULT = 'I';
export const NOT_FOUND_RESULT = 'NF';
export function submitReserve(reserve, airlineCode) {
let _this = this;
let apiUrl = getAirlineUrl(airlineCode);
reserve.token = getAuthInfo().idToken;
return axios.post(apiUrl, reserve).then(result => {
if (!result.message) {
console.error("No \"message\" attribute in result: ", result)
return ERROR_RESULT;
}
return result.message;
}).catch(error => console.log(error));
}
function getAirlineUrl(airlineCode) {
switch (airlineCode) {
case VIANCA.code:
return VIANCA.submitReserveUrl;
case CHAN.code:
return CHAN.submitReserveUrl;
case TOPA.code:
return TOPA.submitReserveUrl;
case IBA_COLOMBIA.code:
return IBA_COLOMBIA.submitReserveUrl;
default:
}
}
export function searchForReserve(apiUrl) {
let _this = this;
let url = apiUrl + '?token=' + getAuthInfo().idToken; // + getToken();
return axios.get(url);
}
export function submitAllReserveSearch() {
console.log('Fetching reserve searchs');
let viancaResult = searchForReserve(VIANCA.fetchReserves);
let chanResult = searchForReserve(CHAN.fetchReserves);
let topaResult = searchForReserve(TOPA.fetchReserves);
let ibaResult = searchForReserve(IBA_COLOMBIA.fetchReserves);
let mergedResults = axios.all([viancaResult, chanResult, topaResult, ibaResult]);
return mergedResults;
}
| camilosampedro/desvolar-web | src/service/reserve-service.js | JavaScript | mit | 1,631 |
import { DESCRIPTORS, LITTLE_ENDIAN } from '../helpers/constants';
if (DESCRIPTORS) QUnit.test('Int32 conversions', assert => {
const int32array = new Int32Array(1);
const uint8array = new Uint8Array(int32array.buffer);
const dataview = new DataView(int32array.buffer);
function viewFrom(it) {
return new DataView(new Uint8Array(it).buffer);
}
function toString(it) {
return it === 0 && 1 / it === -Infinity ? '-0' : it;
}
const data = [
[0, 0, [0, 0, 0, 0]],
[-0, 0, [0, 0, 0, 0]],
[1, 1, [1, 0, 0, 0]],
[-1, -1, [255, 255, 255, 255]],
[1.1, 1, [1, 0, 0, 0]],
[-1.1, -1, [255, 255, 255, 255]],
[1.9, 1, [1, 0, 0, 0]],
[-1.9, -1, [255, 255, 255, 255]],
[127, 127, [127, 0, 0, 0]],
[-127, -127, [129, 255, 255, 255]],
[128, 128, [128, 0, 0, 0]],
[-128, -128, [128, 255, 255, 255]],
[255, 255, [255, 0, 0, 0]],
[-255, -255, [1, 255, 255, 255]],
[255.1, 255, [255, 0, 0, 0]],
[255.9, 255, [255, 0, 0, 0]],
[256, 256, [0, 1, 0, 0]],
[32767, 32767, [255, 127, 0, 0]],
[-32767, -32767, [1, 128, 255, 255]],
[32768, 32768, [0, 128, 0, 0]],
[-32768, -32768, [0, 128, 255, 255]],
[65535, 65535, [255, 255, 0, 0]],
[65536, 65536, [0, 0, 1, 0]],
[65537, 65537, [1, 0, 1, 0]],
[65536.54321, 65536, [0, 0, 1, 0]],
[-65536.54321, -65536, [0, 0, 255, 255]],
[2147483647, 2147483647, [255, 255, 255, 127]],
[-2147483647, -2147483647, [1, 0, 0, 128]],
[2147483648, -2147483648, [0, 0, 0, 128]],
[-2147483648, -2147483648, [0, 0, 0, 128]],
[2147483649, -2147483647, [1, 0, 0, 128]],
[-2147483649, 2147483647, [255, 255, 255, 127]],
[4294967295, -1, [255, 255, 255, 255]],
[4294967296, 0, [0, 0, 0, 0]],
[4294967297, 1, [1, 0, 0, 0]],
[9007199254740991, -1, [255, 255, 255, 255]],
[-9007199254740991, 1, [1, 0, 0, 0]],
[9007199254740992, 0, [0, 0, 0, 0]],
[-9007199254740992, 0, [0, 0, 0, 0]],
[9007199254740994, 2, [2, 0, 0, 0]],
[-9007199254740994, -2, [254, 255, 255, 255]],
[Infinity, 0, [0, 0, 0, 0]],
[-Infinity, 0, [0, 0, 0, 0]],
[-1.7976931348623157e+308, 0, [0, 0, 0, 0]],
[1.7976931348623157e+308, 0, [0, 0, 0, 0]],
[5e-324, 0, [0, 0, 0, 0]],
[-5e-324, 0, [0, 0, 0, 0]],
[NaN, 0, [0, 0, 0, 0]],
];
for (const [value, conversion, little] of data) {
const big = little.slice().reverse();
const representation = LITTLE_ENDIAN ? little : big;
int32array[0] = value;
assert.same(int32array[0], conversion, `Int32Array ${ toString(value) } -> ${ toString(conversion) }`);
assert.arrayEqual(uint8array, representation, `Int32Array ${ toString(value) } -> [${ representation }]`);
dataview.setInt32(0, value);
assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }) -> [${ big }]`);
assert.same(viewFrom(big).getInt32(0), conversion, `dataview{${ big }}.getInt32(0) -> ${ toString(conversion) }`);
dataview.setInt32(0, value, false);
assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }, false) -> [${ big }]`);
assert.same(viewFrom(big).getInt32(0, false), conversion, `dataview{${ big }}.getInt32(0, false) -> ${ toString(conversion) }`);
dataview.setInt32(0, value, true);
assert.arrayEqual(uint8array, little, `dataview.setInt32(0, ${ toString(value) }, true) -> [${ little }]`);
assert.same(viewFrom(little).getInt32(0, true), conversion, `dataview{${ little }}.getInt32(0, true) -> ${ toString(conversion) }`);
}
});
| zloirock/core-js | tests/tests/es.typed.conversions.int32.js | JavaScript | mit | 3,535 |
/**
* NOTE: We are in the process of migrating these tests to Mocha. If you are
* adding a new test, consider creating a new spec file in mocha_tests/
*/
var async = require('../lib/async');
if (!Function.prototype.bind) {
Function.prototype.bind = function (thisArg) {
var args = Array.prototype.slice.call(arguments, 1);
var self = this;
return function () {
self.apply(thisArg, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
function eachIterator(args, x, callback) {
setTimeout(function(){
args.push(x);
callback();
}, x*25);
}
function forEachOfIterator(args, value, key, callback) {
setTimeout(function(){
args.push(key, value);
callback();
}, value*25);
}
function mapIterator(call_order, x, callback) {
setTimeout(function(){
call_order.push(x);
callback(null, x*2);
}, x*25);
}
function filterIterator(x, callback) {
setTimeout(function(){
callback(x % 2);
}, x*25);
}
function detectIterator(call_order, x, callback) {
setTimeout(function(){
call_order.push(x);
callback(x == 2);
}, x*25);
}
function eachNoCallbackIterator(test, x, callback) {
test.equal(x, 1);
callback();
test.done();
}
function forEachOfNoCallbackIterator(test, x, key, callback) {
test.equal(x, 1);
test.equal(key, "a");
callback();
test.done();
}
function getFunctionsObject(call_order) {
return {
one: function(callback){
setTimeout(function(){
call_order.push(1);
callback(null, 1);
}, 125);
},
two: function(callback){
setTimeout(function(){
call_order.push(2);
callback(null, 2);
}, 200);
},
three: function(callback){
setTimeout(function(){
call_order.push(3);
callback(null, 3,3);
}, 50);
}
};
}
function isBrowser() {
return (typeof process === "undefined") ||
(process + "" !== "[object process]"); // browserify
}
exports['applyEach'] = function (test) {
test.expect(5);
var call_order = [];
var one = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('one');
cb(null, 1);
}, 100);
};
var two = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('two');
cb(null, 2);
}, 50);
};
var three = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('three');
cb(null, 3);
}, 150);
};
async.applyEach([one, two, three], 5, function (err) {
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, ['two', 'one', 'three']);
test.done();
});
};
exports['applyEachSeries'] = function (test) {
test.expect(5);
var call_order = [];
var one = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('one');
cb(null, 1);
}, 100);
};
var two = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('two');
cb(null, 2);
}, 50);
};
var three = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('three');
cb(null, 3);
}, 150);
};
async.applyEachSeries([one, two, three], 5, function (err) {
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, ['one', 'two', 'three']);
test.done();
});
};
exports['applyEach partial application'] = function (test) {
test.expect(4);
var call_order = [];
var one = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('one');
cb(null, 1);
}, 100);
};
var two = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('two');
cb(null, 2);
}, 50);
};
var three = function (val, cb) {
test.equal(val, 5);
setTimeout(function () {
call_order.push('three');
cb(null, 3);
}, 150);
};
async.applyEach([one, two, three])(5, function (err) {
if (err) throw err;
test.same(call_order, ['two', 'one', 'three']);
test.done();
});
};
exports['seq'] = function (test) {
test.expect(5);
var add2 = function (n, cb) {
test.equal(n, 3);
setTimeout(function () {
cb(null, n + 2);
}, 50);
};
var mul3 = function (n, cb) {
test.equal(n, 5);
setTimeout(function () {
cb(null, n * 3);
}, 15);
};
var add1 = function (n, cb) {
test.equal(n, 15);
setTimeout(function () {
cb(null, n + 1);
}, 100);
};
var add2mul3add1 = async.seq(add2, mul3, add1);
add2mul3add1(3, function (err, result) {
if (err) {
return test.done(err);
}
test.ok(err === null, err + " passed instead of 'null'");
test.equal(result, 16);
test.done();
});
};
exports['seq error'] = function (test) {
test.expect(3);
var testerr = new Error('test');
var add2 = function (n, cb) {
test.equal(n, 3);
setTimeout(function () {
cb(null, n + 2);
}, 50);
};
var mul3 = function (n, cb) {
test.equal(n, 5);
setTimeout(function () {
cb(testerr);
}, 15);
};
var add1 = function (n, cb) {
test.ok(false, 'add1 should not get called');
setTimeout(function () {
cb(null, n + 1);
}, 100);
};
var add2mul3add1 = async.seq(add2, mul3, add1);
add2mul3add1(3, function (err) {
test.equal(err, testerr);
test.done();
});
};
exports['seq binding'] = function (test) {
test.expect(4);
var testcontext = {name: 'foo'};
var add2 = function (n, cb) {
test.equal(this, testcontext);
setTimeout(function () {
cb(null, n + 2);
}, 50);
};
var mul3 = function (n, cb) {
test.equal(this, testcontext);
setTimeout(function () {
cb(null, n * 3);
}, 15);
};
var add2mul3 = async.seq(add2, mul3);
add2mul3.call(testcontext, 3, function (err, result) {
if (err) {
return test.done(err);
}
test.equal(this, testcontext);
test.equal(result, 15);
test.done();
});
};
exports['seq without callback'] = function (test) {
test.expect(2);
var testcontext = {name: 'foo'};
var add2 = function (n, cb) {
test.equal(this, testcontext);
setTimeout(function () {
cb(null, n + 2);
}, 50);
};
var mul3 = function () {
test.equal(this, testcontext);
setTimeout(function () {
test.done();
}, 15);
};
var add2mul3 = async.seq(add2, mul3);
add2mul3.call(testcontext, 3);
};
exports['auto'] = function(test){
var callOrder = [];
async.auto({
task1: ['task2', function(callback){
setTimeout(function(){
callOrder.push('task1');
callback();
}, 25);
}],
task2: function(callback){
setTimeout(function(){
callOrder.push('task2');
callback();
}, 50);
},
task3: ['task2', function(callback){
callOrder.push('task3');
callback();
}],
task4: ['task1', 'task2', function(callback){
callOrder.push('task4');
callback();
}],
task5: ['task2', function(callback){
setTimeout(function(){
callOrder.push('task5');
callback();
}, 0);
}],
task6: ['task2', function(callback){
callOrder.push('task6');
callback();
}]
},
function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(callOrder, ['task2','task6','task3','task5','task1','task4']);
test.done();
});
};
exports['auto concurrency'] = function (test) {
var concurrency = 2;
var runningTasks = [];
var makeCallback = function(taskName) {
return function(callback) {
runningTasks.push(taskName);
setTimeout(function(){
// Each task returns the array of running tasks as results.
var result = runningTasks.slice(0);
runningTasks.splice(runningTasks.indexOf(taskName), 1);
callback(null, result);
});
};
};
async.auto({
task1: ['task2', makeCallback('task1')],
task2: makeCallback('task2'),
task3: ['task2', makeCallback('task3')],
task4: ['task1', 'task2', makeCallback('task4')],
task5: ['task2', makeCallback('task5')],
task6: ['task2', makeCallback('task6')]
}, concurrency, function(err, results){
Object.keys(results).forEach(function(taskName) {
test.ok(results[taskName].length <= concurrency);
});
test.done();
});
};
exports['auto petrify'] = function (test) {
var callOrder = [];
async.auto({
task1: ['task2', function (callback) {
setTimeout(function () {
callOrder.push('task1');
callback();
}, 100);
}],
task2: function (callback) {
setTimeout(function () {
callOrder.push('task2');
callback();
}, 200);
},
task3: ['task2', function (callback) {
callOrder.push('task3');
callback();
}],
task4: ['task1', 'task2', function (callback) {
callOrder.push('task4');
callback();
}]
},
function (err) {
if (err) throw err;
test.same(callOrder, ['task2', 'task3', 'task1', 'task4']);
test.done();
});
};
exports['auto results'] = function(test){
var callOrder = [];
async.auto({
task1: ['task2', function(callback, results){
test.same(results.task2, 'task2');
setTimeout(function(){
callOrder.push('task1');
callback(null, 'task1a', 'task1b');
}, 25);
}],
task2: function(callback){
setTimeout(function(){
callOrder.push('task2');
callback(null, 'task2');
}, 50);
},
task3: ['task2', function(callback, results){
test.same(results.task2, 'task2');
callOrder.push('task3');
callback(null);
}],
task4: ['task1', 'task2', function(callback, results){
test.same(results.task1, ['task1a','task1b']);
test.same(results.task2, 'task2');
callOrder.push('task4');
callback(null, 'task4');
}]
},
function(err, results){
test.same(callOrder, ['task2','task3','task1','task4']);
test.same(results, {task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'});
test.done();
});
};
exports['auto empty object'] = function(test){
async.auto({}, function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.done();
});
};
exports['auto error'] = function(test){
test.expect(1);
async.auto({
task1: function(callback){
callback('testerror');
},
task2: ['task1', function(callback){
test.ok(false, 'task2 should not be called');
callback();
}],
task3: function(callback){
callback('testerror2');
}
},
function(err){
test.equals(err, 'testerror');
});
setTimeout(test.done, 100);
};
exports['auto no callback'] = function(test){
async.auto({
task1: function(callback){callback();},
task2: ['task1', function(callback){callback(); test.done();}]
});
};
exports['auto concurrency no callback'] = function(test){
async.auto({
task1: function(callback){callback();},
task2: ['task1', function(callback){callback(); test.done();}]
}, 1);
};
exports['auto error should pass partial results'] = function(test) {
async.auto({
task1: function(callback){
callback(false, 'result1');
},
task2: ['task1', function(callback){
callback('testerror', 'result2');
}],
task3: ['task2', function(){
test.ok(false, 'task3 should not be called');
}]
},
function(err, results){
test.equals(err, 'testerror');
test.equals(results.task1, 'result1');
test.equals(results.task2, 'result2');
test.done();
});
};
// Issue 24 on github: https://github.com/caolan/async/issues#issue/24
// Issue 76 on github: https://github.com/caolan/async/issues#issue/76
exports['auto removeListener has side effect on loop iterator'] = function(test) {
async.auto({
task1: ['task3', function(/*callback*/) { test.done(); }],
task2: ['task3', function(/*callback*/) { /* by design: DON'T call callback */ }],
task3: function(callback) { callback(); }
});
};
// Issue 410 on github: https://github.com/caolan/async/issues/410
exports['auto calls callback multiple times'] = function(test) {
if (isBrowser()) {
// node only test
test.done();
return;
}
var finalCallCount = 0;
var domain = require('domain').create();
domain.on('error', function (e) {
// ignore test error
if (!e._test_error) {
return test.done(e);
}
});
domain.run(function () {
async.auto({
task1: function(callback) { callback(null); },
task2: ['task1', function(callback) { callback(null); }]
},
// Error throwing final callback. This should only run once
function() {
finalCallCount++;
var e = new Error("An error");
e._test_error = true;
throw e;
});
});
setTimeout(function () {
test.equal(finalCallCount, 1,
"Final auto callback should only be called once"
);
test.done();
}, 10);
};
exports['auto calls callback multiple times with parallel functions'] = function(test) {
test.expect(1);
async.auto({
task1: function(callback) { setTimeout(callback,0,"err"); },
task2: function(callback) { setTimeout(callback,0,"err"); }
},
// Error throwing final callback. This should only run once
function(err) {
test.equal(err, "err");
test.done();
});
};
// Issue 462 on github: https://github.com/caolan/async/issues/462
exports['auto modifying results causes final callback to run early'] = function(test) {
async.auto({
task1: function(callback, results){
results.inserted = true;
callback(null, 'task1');
},
task2: function(callback){
setTimeout(function(){
callback(null, 'task2');
}, 50);
},
task3: function(callback){
setTimeout(function(){
callback(null, 'task3');
}, 100);
}
},
function(err, results){
test.equal(results.inserted, true);
test.ok(results.task3, 'task3');
test.done();
});
};
// Issue 263 on github: https://github.com/caolan/async/issues/263
exports['auto prevent dead-locks due to inexistant dependencies'] = function(test) {
test.throws(function () {
async.auto({
task1: ['noexist', function(callback){
callback(null, 'task1');
}]
});
}, Error);
test.done();
};
// Issue 263 on github: https://github.com/caolan/async/issues/263
exports['auto prevent dead-locks due to cyclic dependencies'] = function(test) {
test.throws(function () {
async.auto({
task1: ['task2', function(callback){
callback(null, 'task1');
}],
task2: ['task1', function(callback){
callback(null, 'task2');
}]
});
}, Error);
test.done();
};
// Issue 306 on github: https://github.com/caolan/async/issues/306
exports['retry when attempt succeeds'] = function(test) {
var failed = 3;
var callCount = 0;
var expectedResult = 'success';
function fn(callback) {
callCount++;
failed--;
if (!failed) callback(null, expectedResult);
else callback(true); // respond with error
}
async.retry(fn, function(err, result){
test.ok(err === null, err + " passed instead of 'null'");
test.equal(callCount, 3, 'did not retry the correct number of times');
test.equal(result, expectedResult, 'did not return the expected result');
test.done();
});
};
exports['retry when all attempts succeeds'] = function(test) {
var times = 3;
var callCount = 0;
var error = 'ERROR';
var erroredResult = 'RESULT';
function fn(callback) {
callCount++;
callback(error + callCount, erroredResult + callCount); // respond with indexed values
}
async.retry(times, fn, function(err, result){
test.equal(callCount, 3, "did not retry the correct number of times");
test.equal(err, error + times, "Incorrect error was returned");
test.equal(result, erroredResult + times, "Incorrect result was returned");
test.done();
});
};
exports['retry fails with invalid arguments'] = function(test) {
test.throws(function() {
async.retry("");
});
test.throws(function() {
async.retry();
});
test.throws(function() {
async.retry(function() {}, 2, function() {});
});
test.done();
};
exports['retry with interval when all attempts succeeds'] = function(test) {
var times = 3;
var interval = 500;
var callCount = 0;
var error = 'ERROR';
var erroredResult = 'RESULT';
function fn(callback) {
callCount++;
callback(error + callCount, erroredResult + callCount); // respond with indexed values
}
var start = new Date().getTime();
async.retry({ times: times, interval: interval}, fn, function(err, result){
var now = new Date().getTime();
var duration = now - start;
test.ok(duration > (interval * (times -1)), 'did not include interval');
test.equal(callCount, 3, "did not retry the correct number of times");
test.equal(err, error + times, "Incorrect error was returned");
test.equal(result, erroredResult + times, "Incorrect result was returned");
test.done();
});
};
exports['retry as an embedded task'] = function(test) {
var retryResult = 'RETRY';
var fooResults;
var retryResults;
async.auto({
foo: function(callback, results){
fooResults = results;
callback(null, 'FOO');
},
retry: async.retry(function(callback, results) {
retryResults = results;
callback(null, retryResult);
})
}, function(err, results){
test.equal(results.retry, retryResult, "Incorrect result was returned from retry function");
test.equal(fooResults, retryResults, "Incorrect results were passed to retry function");
test.done();
});
};
exports['retry as an embedded task with interval'] = function(test) {
var start = new Date().getTime();
var opts = {times: 5, interval: 100};
async.auto({
foo: function(callback){
callback(null, 'FOO');
},
retry: async.retry(opts, function(callback) {
callback('err');
})
}, function(){
var duration = new Date().getTime() - start;
var expectedMinimumDuration = (opts.times -1) * opts.interval;
test.ok(duration >= expectedMinimumDuration, "The duration should have been greater than " + expectedMinimumDuration + ", but was " + duration);
test.done();
});
};
exports['waterfall'] = {
'basic': function(test){
test.expect(7);
var call_order = [];
async.waterfall([
function(callback){
call_order.push('fn1');
setTimeout(function(){callback(null, 'one', 'two');}, 0);
},
function(arg1, arg2, callback){
call_order.push('fn2');
test.equals(arg1, 'one');
test.equals(arg2, 'two');
setTimeout(function(){callback(null, arg1, arg2, 'three');}, 25);
},
function(arg1, arg2, arg3, callback){
call_order.push('fn3');
test.equals(arg1, 'one');
test.equals(arg2, 'two');
test.equals(arg3, 'three');
callback(null, 'four');
},
function(arg4, callback){
call_order.push('fn4');
test.same(call_order, ['fn1','fn2','fn3','fn4']);
callback(null, 'test');
}
], function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.done();
});
},
'empty array': function(test){
async.waterfall([], function(err){
if (err) throw err;
test.done();
});
},
'non-array': function(test){
async.waterfall({}, function(err){
test.equals(err.message, 'First argument to waterfall must be an array of functions');
test.done();
});
},
'no callback': function(test){
async.waterfall([
function(callback){callback();},
function(callback){callback(); test.done();}
]);
},
'async': function(test){
var call_order = [];
async.waterfall([
function(callback){
call_order.push(1);
callback();
call_order.push(2);
},
function(callback){
call_order.push(3);
callback();
},
function(){
test.same(call_order, [1,2,3]);
test.done();
}
]);
},
'error': function(test){
test.expect(1);
async.waterfall([
function(callback){
callback('error');
},
function(callback){
test.ok(false, 'next function should not be called');
callback();
}
], function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
},
'multiple callback calls': function(test){
var call_order = [];
var arr = [
function(callback){
call_order.push(1);
// call the callback twice. this should call function 2 twice
callback(null, 'one', 'two');
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
call_order.push(2);
callback(null, arg1, arg2, 'three');
},
function(arg1, arg2, arg3, callback){
call_order.push(3);
callback(null, 'four');
},
function(/*arg4*/){
call_order.push(4);
arr[3] = function(){
call_order.push(4);
test.same(call_order, [1,2,2,3,3,4,4]);
test.done();
};
}
];
async.waterfall(arr);
},
'call in another context': function(test) {
if (isBrowser()) {
// node only test
test.done();
return;
}
var vm = require('vm');
var sandbox = {
async: async,
test: test
};
var fn = "(" + (function () {
async.waterfall([function (callback) {
callback();
}], function (err) {
if (err) {
return test.done(err);
}
test.done();
});
}).toString() + "())";
vm.runInNewContext(fn, sandbox);
}
};
exports['parallel'] = function(test){
var call_order = [];
async.parallel([
function(callback){
setTimeout(function(){
call_order.push(1);
callback(null, 1);
}, 50);
},
function(callback){
setTimeout(function(){
call_order.push(2);
callback(null, 2);
}, 100);
},
function(callback){
setTimeout(function(){
call_order.push(3);
callback(null, 3,3);
}, 25);
}
],
function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [3,1,2]);
test.same(results, [1,2,[3,3]]);
test.done();
});
};
exports['parallel empty array'] = function(test){
async.parallel([], function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(results, []);
test.done();
});
};
exports['parallel error'] = function(test){
async.parallel([
function(callback){
callback('error', 1);
},
function(callback){
callback('error2', 2);
}
],
function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 100);
};
exports['parallel no callback'] = function(test){
async.parallel([
function(callback){callback();},
function(callback){callback(); test.done();},
]);
};
exports['parallel object'] = function(test){
var call_order = [];
async.parallel(getFunctionsObject(call_order), function(err, results){
test.equals(err, null);
test.same(call_order, [3,1,2]);
test.same(results, {
one: 1,
two: 2,
three: [3,3]
});
test.done();
});
};
// Issue 10 on github: https://github.com/caolan/async/issues#issue/10
exports['paralel falsy return values'] = function (test) {
function taskFalse(callback) {
async.nextTick(function() {
callback(null, false);
});
}
function taskUndefined(callback) {
async.nextTick(function() {
callback(null, undefined);
});
}
function taskEmpty(callback) {
async.nextTick(function() {
callback(null);
});
}
function taskNull(callback) {
async.nextTick(function() {
callback(null, null);
});
}
async.parallel(
[taskFalse, taskUndefined, taskEmpty, taskNull],
function(err, results) {
test.equal(results.length, 4);
test.strictEqual(results[0], false);
test.strictEqual(results[1], undefined);
test.strictEqual(results[2], undefined);
test.strictEqual(results[3], null);
test.done();
}
);
};
exports['parallel limit'] = function(test){
var call_order = [];
async.parallelLimit([
function(callback){
setTimeout(function(){
call_order.push(1);
callback(null, 1);
}, 50);
},
function(callback){
setTimeout(function(){
call_order.push(2);
callback(null, 2);
}, 100);
},
function(callback){
setTimeout(function(){
call_order.push(3);
callback(null, 3,3);
}, 25);
}
],
2,
function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [1,3,2]);
test.same(results, [1,2,[3,3]]);
test.done();
});
};
exports['parallel limit empty array'] = function(test){
async.parallelLimit([], 2, function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(results, []);
test.done();
});
};
exports['parallel limit error'] = function(test){
async.parallelLimit([
function(callback){
callback('error', 1);
},
function(callback){
callback('error2', 2);
}
],
1,
function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 100);
};
exports['parallel limit no callback'] = function(test){
async.parallelLimit([
function(callback){callback();},
function(callback){callback(); test.done();},
], 1);
};
exports['parallel limit object'] = function(test){
var call_order = [];
async.parallelLimit(getFunctionsObject(call_order), 2, function(err, results){
test.equals(err, null);
test.same(call_order, [1,3,2]);
test.same(results, {
one: 1,
two: 2,
three: [3,3]
});
test.done();
});
};
exports['parallel call in another context'] = function(test) {
if (isBrowser()) {
// node only test
test.done();
return;
}
var vm = require('vm');
var sandbox = {
async: async,
test: test
};
var fn = "(" + (function () {
async.parallel([function (callback) {
callback();
}], function (err) {
if (err) {
return test.done(err);
}
test.done();
});
}).toString() + "())";
vm.runInNewContext(fn, sandbox);
};
exports['parallel does not continue replenishing after error'] = function (test) {
var started = 0;
var arr = [
funcToCall,
funcToCall,
funcToCall,
funcToCall,
funcToCall,
funcToCall,
funcToCall,
funcToCall,
funcToCall,
];
var delay = 10;
var limit = 3;
var maxTime = 10 * arr.length;
function funcToCall(callback) {
started ++;
if (started === 3) {
return callback(new Error ("Test Error"));
}
setTimeout(function(){
callback();
}, delay);
}
async.parallelLimit(arr, limit, function(){});
setTimeout(function(){
test.equal(started, 3);
test.done();
}, maxTime);
};
exports['series'] = {
'series': function(test){
var call_order = [];
async.series([
function(callback){
setTimeout(function(){
call_order.push(1);
callback(null, 1);
}, 25);
},
function(callback){
setTimeout(function(){
call_order.push(2);
callback(null, 2);
}, 50);
},
function(callback){
setTimeout(function(){
call_order.push(3);
callback(null, 3,3);
}, 15);
}
],
function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(results, [1,2,[3,3]]);
test.same(call_order, [1,2,3]);
test.done();
});
},
'empty array': function(test){
async.series([], function(err, results){
test.equals(err, null);
test.same(results, []);
test.done();
});
},
'error': function(test){
test.expect(1);
async.series([
function(callback){
callback('error', 1);
},
function(callback){
test.ok(false, 'should not be called');
callback('error2', 2);
}
],
function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 100);
},
'no callback': function(test){
async.series([
function(callback){callback();},
function(callback){callback(); test.done();},
]);
},
'object': function(test){
var call_order = [];
async.series(getFunctionsObject(call_order), function(err, results){
test.equals(err, null);
test.same(results, {
one: 1,
two: 2,
three: [3,3]
});
test.same(call_order, [1,2,3]);
test.done();
});
},
'call in another context': function(test) {
if (isBrowser()) {
// node only test
test.done();
return;
}
var vm = require('vm');
var sandbox = {
async: async,
test: test
};
var fn = "(" + (function () {
async.series([function (callback) {
callback();
}], function (err) {
if (err) {
return test.done(err);
}
test.done();
});
}).toString() + "())";
vm.runInNewContext(fn, sandbox);
},
// Issue 10 on github: https://github.com/caolan/async/issues#issue/10
'falsy return values': function (test) {
function taskFalse(callback) {
async.nextTick(function() {
callback(null, false);
});
}
function taskUndefined(callback) {
async.nextTick(function() {
callback(null, undefined);
});
}
function taskEmpty(callback) {
async.nextTick(function() {
callback(null);
});
}
function taskNull(callback) {
async.nextTick(function() {
callback(null, null);
});
}
async.series(
[taskFalse, taskUndefined, taskEmpty, taskNull],
function(err, results) {
test.equal(results.length, 4);
test.strictEqual(results[0], false);
test.strictEqual(results[1], undefined);
test.strictEqual(results[2], undefined);
test.strictEqual(results[3], null);
test.done();
}
);
}
};
exports['iterator'] = function(test){
var call_order = [];
var iterator = async.iterator([
function(){call_order.push(1);},
function(arg1){
test.equals(arg1, 'arg1');
call_order.push(2);
},
function(arg1, arg2){
test.equals(arg1, 'arg1');
test.equals(arg2, 'arg2');
call_order.push(3);
}
]);
iterator();
test.same(call_order, [1]);
var iterator2 = iterator();
test.same(call_order, [1,1]);
var iterator3 = iterator2('arg1');
test.same(call_order, [1,1,2]);
var iterator4 = iterator3('arg1', 'arg2');
test.same(call_order, [1,1,2,3]);
test.equals(iterator4, undefined);
test.done();
};
exports['iterator empty array'] = function(test){
var iterator = async.iterator([]);
test.equals(iterator(), undefined);
test.equals(iterator.next(), undefined);
test.done();
};
exports['iterator.next'] = function(test){
var call_order = [];
var iterator = async.iterator([
function(){call_order.push(1);},
function(arg1){
test.equals(arg1, 'arg1');
call_order.push(2);
},
function(arg1, arg2){
test.equals(arg1, 'arg1');
test.equals(arg2, 'arg2');
call_order.push(3);
}
]);
var fn = iterator.next();
var iterator2 = fn('arg1');
test.same(call_order, [2]);
iterator2('arg1','arg2');
test.same(call_order, [2,3]);
test.equals(iterator2.next(), undefined);
test.done();
};
exports['each'] = function(test){
var args = [];
async.each([1,3,2], eachIterator.bind(this, args), function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, [1,2,3]);
test.done();
});
};
exports['each extra callback'] = function(test){
var count = 0;
async.each([1,3,2], function(val, callback) {
count++;
callback();
test.throws(callback);
if (count == 3) {
test.done();
}
});
};
exports['each empty array'] = function(test){
test.expect(1);
async.each([], function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['each empty array, with other property on the array'] = function(test){
test.expect(1);
var myArray = [];
myArray.myProp = "anything";
async.each(myArray, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['each error'] = function(test){
test.expect(1);
async.each([1,2,3], function(x, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};
exports['each no callback'] = function(test){
async.each([1], eachNoCallbackIterator.bind(this, test));
};
exports['forEach alias'] = function (test) {
test.strictEqual(async.each, async.forEach);
test.done();
};
exports['forEachOf'] = function(test){
var args = [];
async.forEachOf({ a: 1, b: 2 }, forEachOfIterator.bind(this, args), function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, ["a", 1, "b", 2]);
test.done();
});
};
exports['forEachOf - instant resolver'] = function(test){
test.expect(1);
var args = [];
async.forEachOf({ a: 1, b: 2 }, function(x, k, cb) {
args.push(k, x);
cb();
}, function(){
// ensures done callback isn't called before all items iterated
test.same(args, ["a", 1, "b", 2]);
test.done();
});
};
exports['forEachOf empty object'] = function(test){
test.expect(1);
async.forEachOf({}, function(value, key, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err) {
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['forEachOf empty array'] = function(test){
test.expect(1);
async.forEachOf([], function(value, key, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err) {
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['forEachOf error'] = function(test){
test.expect(1);
async.forEachOf({ a: 1, b: 2 }, function(value, key, callback) {
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};
exports['forEachOf no callback'] = function(test){
async.forEachOf({ a: 1 }, forEachOfNoCallbackIterator.bind(this, test));
};
exports['eachOf alias'] = function(test){
test.equals(async.eachOf, async.forEachOf);
test.done();
};
exports['forEachOf with array'] = function(test){
var args = [];
async.forEachOf([ "a", "b" ], forEachOfIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, [0, "a", 1, "b"]);
test.done();
});
};
exports['eachSeries'] = function(test){
var args = [];
async.eachSeries([1,3,2], eachIterator.bind(this, args), function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, [1,3,2]);
test.done();
});
};
exports['eachSeries empty array'] = function(test){
test.expect(1);
async.eachSeries([], function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['eachSeries array modification'] = function(test) {
test.expect(1);
var arr = [1, 2, 3, 4];
async.eachSeries(arr, function (x, callback) {
async.setImmediate(callback);
}, function () {
test.ok(true, 'should call callback');
});
arr.pop();
arr.splice(0, 1);
setTimeout(test.done, 50);
};
// bug #782. Remove in next major release
exports['eachSeries single item'] = function (test) {
test.expect(1);
var sync = true;
async.eachSeries([1], function (i, cb) {
cb(null);
}, function () {
test.ok(sync, "callback not called on same tick");
});
sync = false;
test.done();
};
// bug #782. Remove in next major release
exports['eachSeries single item'] = function (test) {
test.expect(1);
var sync = true;
async.eachSeries([1], function (i, cb) {
cb(null);
}, function () {
test.ok(sync, "callback not called on same tick");
});
sync = false;
test.done();
};
exports['eachSeries error'] = function(test){
test.expect(2);
var call_order = [];
async.eachSeries([1,2,3], function(x, callback){
call_order.push(x);
callback('error');
}, function(err){
test.same(call_order, [1]);
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};
exports['eachSeries no callback'] = function(test){
async.eachSeries([1], eachNoCallbackIterator.bind(this, test));
};
exports['eachLimit'] = function(test){
var args = [];
var arr = [0,1,2,3,4,5,6,7,8,9];
async.eachLimit(arr, 2, function(x,callback){
setTimeout(function(){
args.push(x);
callback();
}, x*5);
}, function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, arr);
test.done();
});
};
exports['eachLimit empty array'] = function(test){
test.expect(1);
async.eachLimit([], 2, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['eachLimit limit exceeds size'] = function(test){
var args = [];
var arr = [0,1,2,3,4,5,6,7,8,9];
async.eachLimit(arr, 20, eachIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, arr);
test.done();
});
};
exports['eachLimit limit equal size'] = function(test){
var args = [];
var arr = [0,1,2,3,4,5,6,7,8,9];
async.eachLimit(arr, 10, eachIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, arr);
test.done();
});
};
exports['eachLimit zero limit'] = function(test){
test.expect(1);
async.eachLimit([0,1,2,3,4,5], 0, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['eachLimit error'] = function(test){
test.expect(2);
var arr = [0,1,2,3,4,5,6,7,8,9];
var call_order = [];
async.eachLimit(arr, 3, function(x, callback){
call_order.push(x);
if (x === 2) {
callback('error');
}
}, function(err){
test.same(call_order, [0,1,2]);
test.equals(err, 'error');
});
setTimeout(test.done, 25);
};
exports['eachLimit no callback'] = function(test){
async.eachLimit([1], 1, eachNoCallbackIterator.bind(this, test));
};
exports['eachLimit synchronous'] = function(test){
var args = [];
var arr = [0,1,2];
async.eachLimit(arr, 5, function(x,callback){
args.push(x);
callback();
}, function(err){
if (err) throw err;
test.same(args, arr);
test.done();
});
};
exports['eachLimit does not continue replenishing after error'] = function (test) {
var started = 0;
var arr = [0,1,2,3,4,5,6,7,8,9];
var delay = 10;
var limit = 3;
var maxTime = 10 * arr.length;
async.eachLimit(arr, limit, function(x, callback) {
started ++;
if (started === 3) {
return callback(new Error ("Test Error"));
}
setTimeout(function(){
callback();
}, delay);
}, function(){});
setTimeout(function(){
test.equal(started, 3);
test.done();
}, maxTime);
};
exports['forEachSeries alias'] = function (test) {
test.strictEqual(async.eachSeries, async.forEachSeries);
test.done();
};
exports['forEachOfSeries'] = function(test){
var args = [];
async.forEachOfSeries({ a: 1, b: 2 }, forEachOfIterator.bind(this, args), function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, [ "a", 1, "b", 2 ]);
test.done();
});
};
exports['forEachOfSeries empty object'] = function(test){
test.expect(1);
async.forEachOfSeries({}, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['forEachOfSeries error'] = function(test){
test.expect(2);
var call_order = [];
async.forEachOfSeries({ a: 1, b: 2 }, function(value, key, callback){
call_order.push(value, key);
callback('error');
}, function(err){
test.same(call_order, [ 1, "a" ]);
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};
exports['forEachOfSeries no callback'] = function(test){
async.forEachOfSeries({ a: 1 }, forEachOfNoCallbackIterator.bind(this, test));
};
exports['forEachOfSeries with array'] = function(test){
var args = [];
async.forEachOfSeries([ "a", "b" ], forEachOfIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, [ 0, "a", 1, "b" ]);
test.done();
});
};
exports['eachOfLimit alias'] = function(test){
test.equals(async.eachOfLimit, async.forEachOfLimit);
test.done();
};
exports['eachOfSeries alias'] = function(test){
test.equals(async.eachOfSeries, async.forEachOfSeries);
test.done();
};
exports['forEachLimit alias'] = function (test) {
test.strictEqual(async.eachLimit, async.forEachLimit);
test.done();
};
exports['forEachOfLimit'] = function(test){
var args = [];
var obj = { a: 1, b: 2, c: 3, d: 4 };
async.forEachOfLimit(obj, 2, function(value, key, callback){
setTimeout(function(){
args.push(value, key);
callback();
}, value * 5);
}, function(err){
test.ok(err === null, err + " passed instead of 'null'");
test.same(args, [ 1, "a", 2, "b", 3, "c", 4, "d" ]);
test.done();
});
};
exports['forEachOfLimit empty object'] = function(test){
test.expect(1);
async.forEachOfLimit({}, 2, function(value, key, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['forEachOfLimit limit exceeds size'] = function(test){
var args = [];
var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
async.forEachOfLimit(obj, 10, forEachOfIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, [ "a", 1, "b", 2, "c", 3, "d", 4, "e", 5 ]);
test.done();
});
};
exports['forEachOfLimit limit equal size'] = function(test){
var args = [];
var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
async.forEachOfLimit(obj, 5, forEachOfIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, [ "a", 1, "b", 2, "c", 3, "d", 4, "e", 5 ]);
test.done();
});
};
exports['forEachOfLimit zero limit'] = function(test){
test.expect(1);
async.forEachOfLimit({ a: 1, b: 2 }, 0, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};
exports['forEachOfLimit error'] = function(test){
test.expect(2);
var obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
var call_order = [];
async.forEachOfLimit(obj, 3, function(value, key, callback){
call_order.push(value, key);
if (value === 2) {
callback('error');
}
}, function(err){
test.same(call_order, [ 1, "a", 2, "b" ]);
test.equals(err, 'error');
});
setTimeout(test.done, 25);
};
exports['forEachOfLimit no callback'] = function(test){
async.forEachOfLimit({ a: 1 }, 1, forEachOfNoCallbackIterator.bind(this, test));
};
exports['forEachOfLimit synchronous'] = function(test){
var args = [];
var obj = { a: 1, b: 2 };
async.forEachOfLimit(obj, 5, forEachOfIterator.bind(this, args), function(err){
if (err) throw err;
test.same(args, [ "a", 1, "b", 2 ]);
test.done();
});
};
exports['forEachOfLimit with array'] = function(test){
var args = [];
var arr = [ "a", "b" ];
async.forEachOfLimit(arr, 1, forEachOfIterator.bind(this, args), function (err) {
if (err) throw err;
test.same(args, [ 0, "a", 1, "b" ]);
test.done();
});
};
exports['map'] = {
'basic': function(test){
var call_order = [];
async.map([1,3,2], mapIterator.bind(this, call_order), function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [1,2,3]);
test.same(results, [2,6,4]);
test.done();
});
},
'map original untouched': function(test){
var a = [1,2,3];
async.map(a, function(x, callback){
callback(null, x*2);
}, function(err, results){
test.same(results, [2,4,6]);
test.same(a, [1,2,3]);
test.done();
});
},
'map without main callback': function(test){
var a = [1,2,3];
var r = [];
async.map(a, function(x, callback){
r.push(x);
callback(null);
if (r.length >= a.length) {
test.same(r, a);
test.done();
}
});
},
'map error': function(test){
test.expect(1);
async.map([1,2,3], function(x, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
},
'map undefined array': function(test){
test.expect(2);
async.map(undefined, function(x, callback){
callback();
}, function(err, result){
test.equals(err, null);
test.same(result, []);
});
setTimeout(test.done, 50);
},
'map object': function (test) {
async.map({a: 1, b: 2, c: 3}, function (val, callback) {
callback(null, val * 2);
}, function (err, result) {
if (err) throw err;
test.equals(Object.prototype.toString.call(result), '[object Object]');
test.same(result, {a: 2, b: 4, c: 6});
test.done();
});
},
'mapSeries': function(test){
var call_order = [];
async.mapSeries([1,3,2], mapIterator.bind(this, call_order), function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [1,3,2]);
test.same(results, [2,6,4]);
test.done();
});
},
'mapSeries error': function(test){
test.expect(1);
async.mapSeries([1,2,3], function(x, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
},
'mapSeries undefined array': function(test){
test.expect(2);
async.mapSeries(undefined, function(x, callback){
callback();
}, function(err, result){
test.equals(err, null);
test.same(result, []);
});
setTimeout(test.done, 50);
},
'mapSeries object': function (test) {
async.mapSeries({a: 1, b: 2, c: 3}, function (val, callback) {
callback(null, val * 2);
}, function (err, result) {
if (err) throw err;
test.same(result, {a: 2, b: 4, c: 6});
test.done();
});
},
'mapLimit': function(test){
var call_order = [];
async.mapLimit([2,4,3], 2, mapIterator.bind(this, call_order), function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [2,4,3]);
test.same(results, [4,8,6]);
test.done();
});
},
'mapLimit empty array': function(test){
test.expect(1);
async.mapLimit([], 2, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
},
'mapLimit undefined array': function(test){
test.expect(2);
async.mapLimit(undefined, 2, function(x, callback){
callback();
}, function(err, result){
test.equals(err, null);
test.same(result, []);
});
setTimeout(test.done, 50);
},
'mapLimit limit exceeds size': function(test){
var call_order = [];
async.mapLimit([0,1,2,3,4,5,6,7,8,9], 20, mapIterator.bind(this, call_order), function(err, results){
test.same(call_order, [0,1,2,3,4,5,6,7,8,9]);
test.same(results, [0,2,4,6,8,10,12,14,16,18]);
test.done();
});
},
'mapLimit limit equal size': function(test){
var call_order = [];
async.mapLimit([0,1,2,3,4,5,6,7,8,9], 10, mapIterator.bind(this, call_order), function(err, results){
test.same(call_order, [0,1,2,3,4,5,6,7,8,9]);
test.same(results, [0,2,4,6,8,10,12,14,16,18]);
test.done();
});
},
'mapLimit zero limit': function(test){
test.expect(2);
async.mapLimit([0,1,2,3,4,5], 0, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err, results){
test.same(results, []);
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
},
'mapLimit error': function(test){
test.expect(2);
var arr = [0,1,2,3,4,5,6,7,8,9];
var call_order = [];
async.mapLimit(arr, 3, function(x, callback){
call_order.push(x);
if (x === 2) {
callback('error');
}
}, function(err){
test.same(call_order, [0,1,2]);
test.equals(err, 'error');
});
setTimeout(test.done, 25);
},
'mapLimit does not continue replenishing after error': function (test) {
var started = 0;
var arr = [0,1,2,3,4,5,6,7,8,9];
var delay = 10;
var limit = 3;
var maxTime = 10 * arr.length;
async.mapLimit(arr, limit, function(x, callback) {
started ++;
if (started === 3) {
return callback(new Error ("Test Error"));
}
setTimeout(function(){
callback();
}, delay);
}, function(){});
setTimeout(function(){
test.equal(started, 3);
test.done();
}, maxTime);
}
};
exports['reduce'] = function(test){
var call_order = [];
async.reduce([1,2,3], 0, function(a, x, callback){
call_order.push(x);
callback(null, a + x);
}, function(err, result){
test.ok(err === null, err + " passed instead of 'null'");
test.equals(result, 6);
test.same(call_order, [1,2,3]);
test.done();
});
};
exports['reduce async with non-reference memo'] = function(test){
async.reduce([1,3,2], 0, function(a, x, callback){
setTimeout(function(){callback(null, a + x);}, Math.random()*100);
}, function(err, result){
test.equals(result, 6);
test.done();
});
};
exports['reduce error'] = function(test){
test.expect(1);
async.reduce([1,2,3], 0, function(a, x, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};
exports['inject alias'] = function(test){
test.equals(async.inject, async.reduce);
test.done();
};
exports['foldl alias'] = function(test){
test.equals(async.foldl, async.reduce);
test.done();
};
exports['reduceRight'] = function(test){
var call_order = [];
var a = [1,2,3];
async.reduceRight(a, 0, function(a, x, callback){
call_order.push(x);
callback(null, a + x);
}, function(err, result){
test.equals(result, 6);
test.same(call_order, [3,2,1]);
test.same(a, [1,2,3]);
test.done();
});
};
exports['foldr alias'] = function(test){
test.equals(async.foldr, async.reduceRight);
test.done();
};
exports['transform implictly determines memo if not provided'] = function(test){
async.transform([1,2,3], function(memo, x, v, callback){
memo.push(x + 1);
callback();
}, function(err, result){
test.same(result, [2, 3, 4]);
test.done();
});
};
exports['transform async with object memo'] = function(test){
test.expect(2);
async.transform([1,3,2], {}, function(memo, v, k, callback){
setTimeout(function() {
memo[k] = v;
callback();
});
}, function(err, result) {
test.equals(err, null);
test.same(result, {
0: 1,
1: 3,
2: 2
});
test.done();
});
};
exports['transform iterating object'] = function(test){
test.expect(2);
async.transform({a: 1, b: 3, c: 2}, function(memo, v, k, callback){
setTimeout(function() {
memo[k] = v + 1;
callback();
});
}, function(err, result) {
test.equals(err, null);
test.same(result, {a: 2, b: 4, c: 3});
test.done();
});
};
exports['transform error'] = function(test){
async.transform([1,2,3], function(a, v, k, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
test.done();
});
};
exports['filter'] = function(test){
async.filter([3,1,2], filterIterator, function(results){
test.same(results, [3,1]);
test.done();
});
};
exports['filter original untouched'] = function(test){
var a = [3,1,2];
async.filter(a, function(x, callback){
callback(x % 2);
}, function(results){
test.same(results, [3,1]);
test.same(a, [3,1,2]);
test.done();
});
};
exports['filterSeries'] = function(test){
async.filterSeries([3,1,2], filterIterator, function(results){
test.same(results, [3,1]);
test.done();
});
};
exports['select alias'] = function(test){
test.equals(async.select, async.filter);
test.done();
};
exports['selectSeries alias'] = function(test){
test.equals(async.selectSeries, async.filterSeries);
test.done();
};
exports['reject'] = function(test){
test.expect(1);
async.reject([3,1,2], filterIterator, function(results){
test.same(results, [2]);
test.done();
});
};
exports['reject original untouched'] = function(test){
test.expect(2);
var a = [3,1,2];
async.reject(a, function(x, callback){
callback(x % 2);
}, function(results){
test.same(results, [2]);
test.same(a, [3,1,2]);
test.done();
});
};
exports['rejectSeries'] = function(test){
test.expect(1);
async.rejectSeries([3,1,2], filterIterator, function(results){
test.same(results, [2]);
test.done();
});
};
function testLimit(test, arr, limitFunc, limit, iter, done) {
var args = [];
limitFunc(arr, limit, function(x) {
args.push(x);
iter.apply(this, arguments);
}, function() {
test.same(args, arr);
if (done) done.apply(this, arguments);
else test.done();
});
}
exports['rejectLimit'] = function(test) {
test.expect(2);
testLimit(test, [5, 4, 3, 2, 1], async.rejectLimit, 2, function(v, next) {
next(v % 2);
}, function(x) {
test.same(x, [4, 2]);
test.done();
});
};
exports['filterLimit'] = function(test) {
test.expect(2);
testLimit(test, [5, 4, 3, 2, 1], async.filterLimit, 2, function(v, next) {
next(v % 2);
}, function(x) {
test.same(x, [5, 3, 1]);
test.done();
});
};
exports['some true'] = function(test){
test.expect(1);
async.some([3,1,2], function(x, callback){
setTimeout(function(){callback(x === 1);}, 0);
}, function(result){
test.equals(result, true);
test.done();
});
};
exports['some false'] = function(test){
test.expect(1);
async.some([3,1,2], function(x, callback){
setTimeout(function(){callback(x === 10);}, 0);
}, function(result){
test.equals(result, false);
test.done();
});
};
exports['some early return'] = function(test){
test.expect(1);
var call_order = [];
async.some([1,2,3], function(x, callback){
setTimeout(function(){
call_order.push(x);
callback(x === 1);
}, x*25);
}, function(){
call_order.push('callback');
});
setTimeout(function(){
test.same(call_order, [1,'callback',2,3]);
test.done();
}, 100);
};
exports['someLimit true'] = function(test){
async.someLimit([3,1,2], 2, function(x, callback){
setTimeout(function(){callback(x === 2);}, 0);
}, function(result){
test.equals(result, true);
test.done();
});
};
exports['someLimit false'] = function(test){
async.someLimit([3,1,2], 2, function(x, callback){
setTimeout(function(){callback(x === 10);}, 0);
}, function(result){
test.equals(result, false);
test.done();
});
};
exports['every true'] = function(test){
async.everyLimit([3,1,2], 1, function(x, callback){
setTimeout(function(){callback(x > 1);}, 0);
}, function(result){
test.equals(result, true);
test.done();
});
};
exports['everyLimit false'] = function(test){
async.everyLimit([3,1,2], 2, function(x, callback){
setTimeout(function(){callback(x === 2);}, 0);
}, function(result){
test.equals(result, false);
test.done();
});
};
exports['everyLimit short-circuit'] = function(test){
test.expect(2);
var calls = 0;
async.everyLimit([3,1,2], 1, function(x, callback){
calls++;
callback(x === 1);
}, function(result){
test.equals(result, false);
test.equals(calls, 1);
test.done();
});
};
exports['someLimit short-circuit'] = function(test){
test.expect(2);
var calls = 0;
async.someLimit([3,1,2], 1, function(x, callback){
calls++;
callback(x === 1);
}, function(result){
test.equals(result, true);
test.equals(calls, 2);
test.done();
});
};
exports['any alias'] = function(test){
test.equals(async.any, async.some);
test.done();
};
exports['every true'] = function(test){
test.expect(1);
async.every([1,2,3], function(x, callback){
setTimeout(function(){callback(true);}, 0);
}, function(result){
test.equals(result, true);
test.done();
});
};
exports['every false'] = function(test){
test.expect(1);
async.every([1,2,3], function(x, callback){
setTimeout(function(){callback(x % 2);}, 0);
}, function(result){
test.equals(result, false);
test.done();
});
};
exports['every early return'] = function(test){
test.expect(1);
var call_order = [];
async.every([1,2,3], function(x, callback){
setTimeout(function(){
call_order.push(x);
callback(x === 1);
}, x*25);
}, function(){
call_order.push('callback');
});
setTimeout(function(){
test.same(call_order, [1,2,'callback',3]);
test.done();
}, 100);
};
exports['all alias'] = function(test){
test.equals(async.all, async.every);
test.done();
};
exports['detect'] = function(test){
test.expect(2);
var call_order = [];
async.detect([3,2,1], detectIterator.bind(this, call_order), function(result){
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function(){
test.same(call_order, [1,2,'callback',3]);
test.done();
}, 100);
};
exports['detect - mulitple matches'] = function(test){
test.expect(2);
var call_order = [];
async.detect([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function(){
test.same(call_order, [1,2,'callback',2,2,3]);
test.done();
}, 100);
};
exports['detectSeries'] = function(test){
test.expect(2);
var call_order = [];
async.detectSeries([3,2,1], detectIterator.bind(this, call_order), function(result){
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function(){
test.same(call_order, [3,2,'callback']);
test.done();
}, 200);
};
exports['detectSeries - multiple matches'] = function(test){
test.expect(2);
var call_order = [];
async.detectSeries([3,2,2,1,2], detectIterator.bind(this, call_order), function(result){
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function(){
test.same(call_order, [3,2,'callback']);
test.done();
}, 200);
};
exports['detectSeries - ensure stop'] = function (test) {
test.expect(1);
async.detectSeries([1, 2, 3, 4, 5], function (num, cb) {
if (num > 3) throw new Error("detectSeries did not stop iterating");
cb(num === 3);
}, function (result) {
test.equals(result, 3);
test.done();
});
};
exports['detectLimit'] = function(test){
test.expect(2);
var call_order = [];
async.detectLimit([3, 2, 1], 2, detectIterator.bind(this, call_order), function(result) {
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function() {
test.same(call_order, [2, 'callback', 3]);
test.done();
}, 100);
};
exports['detectLimit - multiple matches'] = function(test){
test.expect(2);
var call_order = [];
async.detectLimit([3,2,2,1,2], 2, detectIterator.bind(this, call_order), function(result){
call_order.push('callback');
test.equals(result, 2);
});
setTimeout(function(){
test.same(call_order, [2, 'callback', 3]);
test.done();
}, 100);
};
exports['detectLimit - ensure stop'] = function (test) {
test.expect(1);
async.detectLimit([1, 2, 3, 4, 5], 2, function (num, cb) {
if (num > 4) throw new Error("detectLimit did not stop iterating");
cb(num === 3);
}, function (result) {
test.equals(result, 3);
test.done();
});
};
exports['sortBy'] = function(test){
test.expect(2);
async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){
setTimeout(function(){callback(null, x.a);}, 0);
}, function(err, result){
test.ok(err === null, err + " passed instead of 'null'");
test.same(result, [{a:1},{a:6},{a:15}]);
test.done();
});
};
exports['sortBy inverted'] = function(test){
test.expect(1);
async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){
setTimeout(function(){callback(null, x.a*-1);}, 0);
}, function(err, result){
test.same(result, [{a:15},{a:6},{a:1}]);
test.done();
});
};
exports['sortBy error'] = function(test){
test.expect(1);
var error = new Error('asdas');
async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){
async.setImmediate(function(){
callback(error);
});
}, function(err){
test.equal(err, error);
test.done();
});
};
exports['apply'] = function(test){
test.expect(6);
var fn = function(){
test.same(Array.prototype.slice.call(arguments), [1,2,3,4]);
};
async.apply(fn, 1, 2, 3, 4)();
async.apply(fn, 1, 2, 3)(4);
async.apply(fn, 1, 2)(3, 4);
async.apply(fn, 1)(2, 3, 4);
async.apply(fn)(1, 2, 3, 4);
test.equals(
async.apply(function(name){return 'hello ' + name;}, 'world')(),
'hello world'
);
test.done();
};
// generates tests for console functions such as async.log
var console_fn_tests = function(name){
if (typeof console !== 'undefined') {
exports[name] = function(test){
test.expect(5);
var fn = function(arg1, callback){
test.equals(arg1, 'one');
setTimeout(function(){callback(null, 'test');}, 0);
};
var fn_err = function(arg1, callback){
test.equals(arg1, 'one');
setTimeout(function(){callback('error');}, 0);
};
var _console_fn = console[name];
var _error = console.error;
console[name] = function(val){
test.equals(val, 'test');
test.equals(arguments.length, 1);
console.error = function(val){
test.equals(val, 'error');
console[name] = _console_fn;
console.error = _error;
test.done();
};
async[name](fn_err, 'one');
};
async[name](fn, 'one');
};
exports[name + ' with multiple result params'] = function(test){
test.expect(1);
var fn = function(callback){callback(null,'one','two','three');};
var _console_fn = console[name];
var called_with = [];
console[name] = function(x){
called_with.push(x);
};
async[name](fn);
test.same(called_with, ['one','two','three']);
console[name] = _console_fn;
test.done();
};
}
// browser-only test
exports[name + ' without console.' + name] = function(test){
if (typeof window !== 'undefined') {
var _console = window.console;
window.console = undefined;
var fn = function(callback){callback(null, 'val');};
var fn_err = function(callback){callback('error');};
async[name](fn);
async[name](fn_err);
window.console = _console;
}
test.done();
};
};
exports['times'] = {
'times': function(test) {
test.expect(2);
async.times(5, function(n, next) {
next(null, n);
}, function(err, results) {
test.ok(err === null, err + " passed instead of 'null'");
test.same(results, [0,1,2,3,4]);
test.done();
});
},
'times 3': function(test){
test.expect(1);
var args = [];
async.times(3, function(n, callback){
setTimeout(function(){
args.push(n);
callback();
}, n * 25);
}, function(err){
if (err) throw err;
test.same(args, [0,1,2]);
test.done();
});
},
'times 0': function(test){
test.expect(1);
async.times(0, function(n, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
if (err) throw err;
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
},
'times error': function(test){
test.expect(1);
async.times(3, function(n, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
},
'timesSeries': function(test){
test.expect(2);
var call_order = [];
async.timesSeries(5, function(n, callback){
setTimeout(function(){
call_order.push(n);
callback(null, n);
}, 100 - n * 10);
}, function(err, results){
test.same(call_order, [0,1,2,3,4]);
test.same(results, [0,1,2,3,4]);
test.done();
});
},
'timesSeries error': function(test){
test.expect(1);
async.timesSeries(5, function(n, callback){
callback('error');
}, function(err){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
},
'timesLimit': function(test){
test.expect(7);
var limit = 2;
var running = 0;
async.timesLimit(5, limit, function (i, next) {
running++;
test.ok(running <= limit && running > 0, running);
setTimeout(function () {
running--;
next(null, i * 2);
}, (3 - i) * 10);
}, function(err, results){
test.ok(err === null, err + " passed instead of 'null'");
test.same(results, [0, 2, 4, 6, 8]);
test.done();
});
}
};
console_fn_tests('log');
console_fn_tests('dir');
/*console_fn_tests('info');
console_fn_tests('warn');
console_fn_tests('error');*/
exports['nextTick'] = function(test){
test.expect(1);
var call_order = [];
async.nextTick(function(){call_order.push('two');});
call_order.push('one');
setTimeout(function(){
test.same(call_order, ['one','two']);
test.done();
}, 50);
};
exports['nextTick in the browser'] = function(test){
if (!isBrowser()) {
// skip this test in node
return test.done();
}
test.expect(1);
var call_order = [];
async.nextTick(function(){call_order.push('two');});
call_order.push('one');
setTimeout(function(){
test.same(call_order, ['one','two']);
}, 50);
setTimeout(test.done, 100);
};
exports['noConflict - node only'] = function(test){
if (!isBrowser()) {
// node only test
test.expect(3);
var fs = require('fs');
var vm = require('vm');
var filename = __dirname + '/../lib/async.js';
fs.readFile(filename, function(err, content){
if(err) return test.done();
var s = vm.createScript(content, filename);
var s2 = vm.createScript(
content + 'this.async2 = this.async.noConflict();',
filename
);
var sandbox1 = {async: 'oldvalue'};
s.runInNewContext(sandbox1);
test.ok(sandbox1.async);
var sandbox2 = {async: 'oldvalue'};
s2.runInNewContext(sandbox2);
test.equals(sandbox2.async, 'oldvalue');
test.ok(sandbox2.async2);
test.done();
});
}
else test.done();
};
exports['concat'] = function(test){
test.expect(3);
var call_order = [];
var iterator = function (x, cb) {
setTimeout(function(){
call_order.push(x);
var r = [];
while (x > 0) {
r.push(x);
x--;
}
cb(null, r);
}, x*25);
};
async.concat([1,3,2], iterator, function(err, results){
test.same(results, [1,2,1,3,2,1]);
test.same(call_order, [1,2,3]);
test.ok(err === null, err + " passed instead of 'null'");
test.done();
});
};
exports['concat error'] = function(test){
test.expect(1);
var iterator = function (x, cb) {
cb(new Error('test error'));
};
async.concat([1,2,3], iterator, function(err){
test.ok(err);
test.done();
});
};
exports['concatSeries'] = function(test){
test.expect(3);
var call_order = [];
var iterator = function (x, cb) {
setTimeout(function(){
call_order.push(x);
var r = [];
while (x > 0) {
r.push(x);
x--;
}
cb(null, r);
}, x*25);
};
async.concatSeries([1,3,2], iterator, function(err, results){
test.same(results, [1,3,2,1,2,1]);
test.same(call_order, [1,3,2]);
test.ok(err === null, err + " passed instead of 'null'");
test.done();
});
};
exports['until'] = function (test) {
test.expect(4);
var call_order = [];
var count = 0;
async.until(
function () {
call_order.push(['test', count]);
return (count == 5);
},
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function (err, result) {
test.ok(err === null, err + " passed instead of 'null'");
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['test', 0],
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5],
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doUntil'] = function (test) {
test.expect(4);
var call_order = [];
var count = 0;
async.doUntil(
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function () {
call_order.push(['test', count]);
return (count == 5);
},
function (err, result) {
test.ok(err === null, err + " passed instead of 'null'");
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5]
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doUntil callback params'] = function (test) {
test.expect(3);
var call_order = [];
var count = 0;
async.doUntil(
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function (c) {
call_order.push(['test', c]);
return (c == 5);
},
function (err, result) {
if (err) throw err;
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5]
]);
test.equals(count, 5);
test.done();
}
);
};
exports['whilst'] = function (test) {
test.expect(4);
var call_order = [];
var count = 0;
async.whilst(
function () {
call_order.push(['test', count]);
return (count < 5);
},
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function (err, result) {
test.ok(err === null, err + " passed instead of 'null'");
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['test', 0],
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5],
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doWhilst'] = function (test) {
test.expect(4);
var call_order = [];
var count = 0;
async.doWhilst(
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function () {
call_order.push(['test', count]);
return (count < 5);
},
function (err, result) {
test.ok(err === null, err + " passed instead of 'null'");
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5]
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doWhilst callback params'] = function (test) {
test.expect(3);
var call_order = [];
var count = 0;
async.doWhilst(
function (cb) {
call_order.push(['iterator', count]);
count++;
cb(null, count);
},
function (c) {
call_order.push(['test', c]);
return (c < 5);
},
function (err, result) {
if (err) throw err;
test.equals(result, 5, 'last result passed through');
test.same(call_order, [
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5]
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doWhilst - error'] = function (test) {
test.expect(1);
var error = new Error('asdas');
async.doWhilst(
function (cb) {
cb(error);
},
function () {},
function (err) {
test.equal(err, error);
test.done();
}
);
};
exports['during'] = function (test) {
var call_order = [];
var count = 0;
async.during(
function (cb) {
call_order.push(['test', count]);
cb(null, count < 5);
},
function (cb) {
call_order.push(['iterator', count]);
count++;
cb();
},
function (err) {
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [
['test', 0],
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5],
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doDuring'] = function (test) {
var call_order = [];
var count = 0;
async.doDuring(
function (cb) {
call_order.push(['iterator', count]);
count++;
cb();
},
function (cb) {
call_order.push(['test', count]);
cb(null, count < 5);
},
function (err) {
test.ok(err === null, err + " passed instead of 'null'");
test.same(call_order, [
['iterator', 0], ['test', 1],
['iterator', 1], ['test', 2],
['iterator', 2], ['test', 3],
['iterator', 3], ['test', 4],
['iterator', 4], ['test', 5],
]);
test.equals(count, 5);
test.done();
}
);
};
exports['doDuring - error test'] = function (test) {
test.expect(1);
var error = new Error('asdas');
async.doDuring(
function (cb) {
cb(error);
},
function () {},
function (err) {
test.equal(err, error);
test.done();
}
);
};
exports['doDuring - error iterator'] = function (test) {
test.expect(1);
var error = new Error('asdas');
async.doDuring(
function (cb) {
cb(null);
},
function (cb) {
cb(error);
},
function (err) {
test.equal(err, error);
test.done();
}
);
};
exports['whilst optional callback'] = function (test) {
var counter = 0;
async.whilst(
function () { return counter < 2; },
function (cb) {
counter++;
cb();
}
);
test.equal(counter, 2);
test.done();
};
exports['queue'] = {
'queue': function (test) {
test.expect(17);
var call_order = [],
delays = [160,80,240,80];
// worker1: --1-4
// worker2: -2---3
// order of completion: 2,1,4,3
var q = async.queue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
callback('error', 'arg');
}, delays.splice(0,1)[0]);
}, 2);
q.push(1, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 1);
call_order.push('callback ' + 1);
});
q.push(2, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 2);
call_order.push('callback ' + 2);
});
q.push(3, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 3);
});
q.push(4, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 4);
});
test.equal(q.length(), 4);
test.equal(q.concurrency, 2);
q.drain = function () {
test.same(call_order, [
'process 2', 'callback 2',
'process 1', 'callback 1',
'process 4', 'callback 4',
'process 3', 'callback 3'
]);
test.equal(q.concurrency, 2);
test.equal(q.length(), 0);
test.done();
};
},
'default concurrency': function (test) {
test.expect(17);
var call_order = [],
delays = [160,80,240,80];
// order of completion: 1,2,3,4
var q = async.queue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
callback('error', 'arg');
}, delays.splice(0,1)[0]);
});
q.push(1, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 3);
call_order.push('callback ' + 1);
});
q.push(2, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 2);
call_order.push('callback ' + 2);
});
q.push(3, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 1);
call_order.push('callback ' + 3);
});
q.push(4, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 4);
});
test.equal(q.length(), 4);
test.equal(q.concurrency, 1);
q.drain = function () {
test.same(call_order, [
'process 1', 'callback 1',
'process 2', 'callback 2',
'process 3', 'callback 3',
'process 4', 'callback 4'
]);
test.equal(q.concurrency, 1);
test.equal(q.length(), 0);
test.done();
};
},
'zero concurrency': function(test){
test.expect(1);
test.throws(function () {
async.queue(function (task, callback) {
callback(null, task);
}, 0);
});
test.done();
},
'error propagation': function(test){
test.expect(1);
var results = [];
var q = async.queue(function (task, callback) {
callback(task.name === 'foo' ? new Error('fooError') : null);
}, 2);
q.drain = function() {
test.deepEqual(results, ['bar', 'fooError']);
test.done();
};
q.push({name: 'bar'}, function (err) {
if(err) {
results.push('barError');
return;
}
results.push('bar');
});
q.push({name: 'foo'}, function (err) {
if(err) {
results.push('fooError');
return;
}
results.push('foo');
});
},
// The original queue implementation allowed the concurrency to be changed only
// on the same event loop during which a task was added to the queue. This
// test attempts to be a more robust test.
// Start with a concurrency of 1. Wait until a leter event loop and change
// the concurrency to 2. Wait again for a later loop then verify the concurrency.
// Repeat that one more time by chaning the concurrency to 5.
'changing concurrency': function (test) {
test.expect(3);
var q = async.queue(function(task, callback){
setTimeout(function(){
callback();
}, 100);
}, 1);
for(var i = 0; i < 50; i++){
q.push('');
}
q.drain = function(){
test.done();
};
setTimeout(function(){
test.equal(q.concurrency, 1);
q.concurrency = 2;
setTimeout(function(){
test.equal(q.running(), 2);
q.concurrency = 5;
setTimeout(function(){
test.equal(q.running(), 5);
}, 500);
}, 500);
}, 500);
},
'push without callback': function (test) {
test.expect(1);
var call_order = [],
delays = [160,80,240,80];
// worker1: --1-4
// worker2: -2---3
// order of completion: 2,1,4,3
var q = async.queue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
callback('error', 'arg');
}, delays.splice(0,1)[0]);
}, 2);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
setTimeout(function () {
test.same(call_order, [
'process 2',
'process 1',
'process 4',
'process 3'
]);
test.done();
}, 800);
},
'push with non-function': function (test) {
test.expect(1);
var q = async.queue(function () {}, 1);
test.throws(function () {
q.push({}, 1);
});
test.done();
},
'unshift': function (test) {
test.expect(1);
var queue_order = [];
var q = async.queue(function (task, callback) {
queue_order.push(task);
callback();
}, 1);
q.unshift(4);
q.unshift(3);
q.unshift(2);
q.unshift(1);
setTimeout(function () {
test.same(queue_order, [ 1, 2, 3, 4 ]);
test.done();
}, 100);
},
'too many callbacks': function (test) {
test.expect(1);
var q = async.queue(function (task, callback) {
callback();
test.throws(function() {
callback();
});
test.done();
}, 2);
q.push(1);
},
'bulk task': function (test) {
test.expect(9);
var call_order = [],
delays = [160,80,240,80];
// worker1: --1-4
// worker2: -2---3
// order of completion: 2,1,4,3
var q = async.queue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
callback('error', task);
}, delays.splice(0,1)[0]);
}, 2);
q.push( [1,2,3,4], function (err, arg) {
test.equal(err, 'error');
call_order.push('callback ' + arg);
});
test.equal(q.length(), 4);
test.equal(q.concurrency, 2);
setTimeout(function () {
test.same(call_order, [
'process 2', 'callback 2',
'process 1', 'callback 1',
'process 4', 'callback 4',
'process 3', 'callback 3'
]);
test.equal(q.concurrency, 2);
test.equal(q.length(), 0);
test.done();
}, 800);
},
'idle': function(test) {
test.expect(7);
var q = async.queue(function (task, callback) {
// Queue is busy when workers are running
test.equal(q.idle(), false);
callback();
}, 1);
// Queue is idle before anything added
test.equal(q.idle(), true);
q.unshift(4);
q.unshift(3);
q.unshift(2);
q.unshift(1);
// Queue is busy when tasks added
test.equal(q.idle(), false);
q.drain = function() {
// Queue is idle after drain
test.equal(q.idle(), true);
test.done();
};
},
'pause': function(test) {
test.expect(3);
var call_order = [],
task_timeout = 100,
pause_timeout = 300,
resume_timeout = 500,
tasks = [ 1, 2, 3, 4, 5, 6 ],
elapsed = (function () {
var start = (new Date()).valueOf();
return function () {
return Math.round(((new Date()).valueOf() - start) / 100) * 100;
};
})();
var q = async.queue(function (task, callback) {
call_order.push('process ' + task);
call_order.push('timeout ' + elapsed());
callback();
});
function pushTask () {
var task = tasks.shift();
if (!task) { return; }
setTimeout(function () {
q.push(task);
pushTask();
}, task_timeout);
}
pushTask();
setTimeout(function () {
q.pause();
test.equal(q.paused, true);
}, pause_timeout);
setTimeout(function () {
q.resume();
test.equal(q.paused, false);
}, resume_timeout);
setTimeout(function () {
test.same(call_order, [
'process 1', 'timeout 100',
'process 2', 'timeout 200',
'process 3', 'timeout 500',
'process 4', 'timeout 500',
'process 5', 'timeout 500',
'process 6', 'timeout 600'
]);
test.done();
}, 800);
},
'pause in worker with concurrency': function(test) {
test.expect(1);
var call_order = [];
var q = async.queue(function (task, callback) {
if (task.isLongRunning) {
q.pause();
setTimeout(function () {
call_order.push(task.id);
q.resume();
callback();
}, 500);
}
else {
call_order.push(task.id);
callback();
}
}, 10);
q.push({ id: 1, isLongRunning: true});
q.push({ id: 2 });
q.push({ id: 3 });
q.push({ id: 4 });
q.push({ id: 5 });
setTimeout(function () {
test.same(call_order, [1, 2, 3, 4, 5]);
test.done();
}, 1000);
},
'pause with concurrency': function(test) {
test.expect(4);
var call_order = [],
task_timeout = 100,
pause_timeout = 50,
resume_timeout = 300,
tasks = [ 1, 2, 3, 4, 5, 6 ],
elapsed = (function () {
var start = (new Date()).valueOf();
return function () {
return Math.round(((new Date()).valueOf() - start) / 100) * 100;
};
})();
var q = async.queue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
call_order.push('timeout ' + elapsed());
callback();
}, task_timeout);
}, 2);
q.push(tasks);
setTimeout(function () {
q.pause();
test.equal(q.paused, true);
}, pause_timeout);
setTimeout(function () {
q.resume();
test.equal(q.paused, false);
}, resume_timeout);
setTimeout(function () {
test.equal(q.running(), 2);
}, resume_timeout + 10);
setTimeout(function () {
test.same(call_order, [
'process 1', 'timeout 100',
'process 2', 'timeout 100',
'process 3', 'timeout 400',
'process 4', 'timeout 400',
'process 5', 'timeout 500',
'process 6', 'timeout 500'
]);
test.done();
}, 800);
},
'start paused': function (test) {
test.expect(2);
var q = async.queue(function (task, callback) {
setTimeout(function () {
callback();
}, 40);
}, 2);
q.pause();
q.push([1, 2, 3]);
setTimeout(function () {
q.resume();
}, 5);
setTimeout(function () {
test.equal(q.tasks.length, 1);
test.equal(q.running(), 2);
q.resume();
}, 15);
q.drain = function () {
test.done();
};
},
'kill': function (test) {
test.expect(1);
var q = async.queue(function (task, callback) {
setTimeout(function () {
test.ok(false, "Function should never be called");
callback();
}, 300);
}, 1);
q.drain = function() {
test.ok(false, "Function should never be called");
};
q.push(0);
q.kill();
setTimeout(function() {
test.equal(q.length(), 0);
test.done();
}, 600);
},
'events': function(test) {
test.expect(4);
var calls = [];
var q = async.queue(function(task, cb) {
// nop
calls.push('process ' + task);
async.setImmediate(cb);
}, 10);
q.concurrency = 3;
q.saturated = function() {
test.ok(q.length() == 3, 'queue should be saturated now');
calls.push('saturated');
};
q.empty = function() {
test.ok(q.length() === 0, 'queue should be empty now');
calls.push('empty');
};
q.drain = function() {
test.ok(
q.length() === 0 && q.running() === 0,
'queue should be empty now and no more workers should be running'
);
calls.push('drain');
test.same(calls, [
'saturated',
'process foo',
'process bar',
'process zoo',
'foo cb',
'process poo',
'bar cb',
'empty',
'process moo',
'zoo cb',
'poo cb',
'moo cb',
'drain'
]);
test.done();
};
q.push('foo', function () {calls.push('foo cb');});
q.push('bar', function () {calls.push('bar cb');});
q.push('zoo', function () {calls.push('zoo cb');});
q.push('poo', function () {calls.push('poo cb');});
q.push('moo', function () {calls.push('moo cb');});
},
'empty': function(test) {
test.expect(2);
var calls = [];
var q = async.queue(function(task, cb) {
// nop
calls.push('process ' + task);
async.setImmediate(cb);
}, 3);
q.drain = function() {
test.ok(
q.length() === 0 && q.running() === 0,
'queue should be empty now and no more workers should be running'
);
calls.push('drain');
test.same(calls, [
'drain'
]);
test.done();
};
q.push([]);
},
'saturated': function (test) {
test.expect(1);
var saturatedCalled = false;
var q = async.queue(function(task, cb) {
async.setImmediate(cb);
}, 2);
q.saturated = function () {
saturatedCalled = true;
};
q.drain = function () {
test.ok(saturatedCalled, "saturated not called");
test.done();
};
setTimeout(function () {
q.push(['foo', 'bar', 'baz', 'moo']);
}, 10);
},
'started': function(test) {
test.expect(2);
var q = async.queue(function(task, cb) {
cb(null, task);
});
test.equal(q.started, false);
q.push([]);
test.equal(q.started, true);
test.done();
}
};
exports['priorityQueue'] = {
'priorityQueue': function (test) {
test.expect(17);
var call_order = [];
// order of completion: 2,1,4,3
var q = async.priorityQueue(function (task, callback) {
call_order.push('process ' + task);
callback('error', 'arg');
}, 1);
q.push(1, 1.4, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 2);
call_order.push('callback ' + 1);
});
q.push(2, 0.2, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 3);
call_order.push('callback ' + 2);
});
q.push(3, 3.8, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 3);
});
q.push(4, 2.9, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 1);
call_order.push('callback ' + 4);
});
test.equal(q.length(), 4);
test.equal(q.concurrency, 1);
q.drain = function () {
test.same(call_order, [
'process 2', 'callback 2',
'process 1', 'callback 1',
'process 4', 'callback 4',
'process 3', 'callback 3'
]);
test.equal(q.concurrency, 1);
test.equal(q.length(), 0);
test.done();
};
},
'concurrency': function (test) {
test.expect(17);
var call_order = [],
delays = [160,80,240,80];
// worker1: --2-3
// worker2: -1---4
// order of completion: 1,2,3,4
var q = async.priorityQueue(function (task, callback) {
setTimeout(function () {
call_order.push('process ' + task);
callback('error', 'arg');
}, delays.splice(0,1)[0]);
}, 2);
q.push(1, 1.4, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 2);
call_order.push('callback ' + 1);
});
q.push(2, 0.2, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 1);
call_order.push('callback ' + 2);
});
q.push(3, 3.8, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 3);
});
q.push(4, 2.9, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(q.length(), 0);
call_order.push('callback ' + 4);
});
test.equal(q.length(), 4);
test.equal(q.concurrency, 2);
q.drain = function () {
test.same(call_order, [
'process 1', 'callback 1',
'process 2', 'callback 2',
'process 3', 'callback 3',
'process 4', 'callback 4'
]);
test.equal(q.concurrency, 2);
test.equal(q.length(), 0);
test.done();
};
}
};
exports['cargo'] = {
'cargo': function (test) {
test.expect(19);
var call_order = [],
delays = [160, 160, 80];
// worker: --12--34--5-
// order of completion: 1,2,3,4,5
var c = async.cargo(function (tasks, callback) {
setTimeout(function () {
call_order.push('process ' + tasks.join(' '));
callback('error', 'arg');
}, delays.shift());
}, 2);
c.push(1, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(c.length(), 3);
call_order.push('callback ' + 1);
});
c.push(2, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(c.length(), 3);
call_order.push('callback ' + 2);
});
test.equal(c.length(), 2);
// async push
setTimeout(function () {
c.push(3, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(c.length(), 1);
call_order.push('callback ' + 3);
});
}, 60);
setTimeout(function () {
c.push(4, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(c.length(), 1);
call_order.push('callback ' + 4);
});
test.equal(c.length(), 2);
c.push(5, function (err, arg) {
test.equal(err, 'error');
test.equal(arg, 'arg');
test.equal(c.length(), 0);
call_order.push('callback ' + 5);
});
}, 120);
setTimeout(function () {
test.same(call_order, [
'process 1 2', 'callback 1', 'callback 2',
'process 3 4', 'callback 3', 'callback 4',
'process 5' , 'callback 5'
]);
test.equal(c.length(), 0);
test.done();
}, 800);
},
'without callback': function (test) {
test.expect(1);
var call_order = [],
delays = [160,80,240,80];
// worker: --1-2---34-5-
// order of completion: 1,2,3,4,5
var c = async.cargo(function (tasks, callback) {
setTimeout(function () {
call_order.push('process ' + tasks.join(' '));
callback('error', 'arg');
}, delays.shift());
}, 2);
c.push(1);
setTimeout(function () {
c.push(2);
}, 120);
setTimeout(function () {
c.push(3);
c.push(4);
c.push(5);
}, 180);
setTimeout(function () {
test.same(call_order, [
'process 1',
'process 2',
'process 3 4',
'process 5'
]);
test.done();
}, 800);
},
'bulk task': function (test) {
test.expect(7);
var call_order = [],
delays = [120,40];
// worker: -123-4-
// order of completion: 1,2,3,4
var c = async.cargo(function (tasks, callback) {
setTimeout(function () {
call_order.push('process ' + tasks.join(' '));
callback('error', tasks.join(' '));
}, delays.shift());
}, 3);
c.push( [1,2,3,4], function (err, arg) {
test.equal(err, 'error');
call_order.push('callback ' + arg);
});
test.equal(c.length(), 4);
setTimeout(function () {
test.same(call_order, [
'process 1 2 3', 'callback 1 2 3',
'callback 1 2 3', 'callback 1 2 3',
'process 4', 'callback 4',
]);
test.equal(c.length(), 0);
test.done();
}, 800);
},
'drain once': function (test) {
test.expect(1);
var c = async.cargo(function (tasks, callback) {
callback();
}, 3);
var drainCounter = 0;
c.drain = function () {
drainCounter++;
};
for(var i = 0; i < 10; i++){
c.push(i);
}
setTimeout(function(){
test.equal(drainCounter, 1);
test.done();
}, 500);
},
'drain twice': function (test) {
test.expect(1);
var c = async.cargo(function (tasks, callback) {
callback();
}, 3);
var loadCargo = function(){
for(var i = 0; i < 10; i++){
c.push(i);
}
};
var drainCounter = 0;
c.drain = function () {
drainCounter++;
};
loadCargo();
setTimeout(loadCargo, 500);
setTimeout(function(){
test.equal(drainCounter, 2);
test.done();
}, 1000);
},
'events': function(test) {
test.expect(4);
var calls = [];
var q = async.cargo(function(task, cb) {
// nop
calls.push('process ' + task);
async.setImmediate(cb);
}, 1);
q.concurrency = 3;
q.saturated = function() {
test.ok(q.length() == 3, 'cargo should be saturated now');
calls.push('saturated');
};
q.empty = function() {
test.ok(q.length() === 0, 'cargo should be empty now');
calls.push('empty');
};
q.drain = function() {
test.ok(
q.length() === 0 && q.running() === 0,
'cargo should be empty now and no more workers should be running'
);
calls.push('drain');
test.same(calls, [
'saturated',
'process foo',
'process bar',
'process zoo',
'foo cb',
'process poo',
'bar cb',
'empty',
'process moo',
'zoo cb',
'poo cb',
'moo cb',
'drain'
]);
test.done();
};
q.push('foo', function () {calls.push('foo cb');});
q.push('bar', function () {calls.push('bar cb');});
q.push('zoo', function () {calls.push('zoo cb');});
q.push('poo', function () {calls.push('poo cb');});
q.push('moo', function () {calls.push('moo cb');});
},
'expose payload': function (test) {
test.expect(5);
var called_once = false;
var cargo= async.cargo(function(tasks, cb) {
if (!called_once) {
test.equal(cargo.payload, 1);
test.ok(tasks.length === 1, 'should start with payload = 1');
} else {
test.equal(cargo.payload, 2);
test.ok(tasks.length === 2, 'next call shold have payload = 2');
}
called_once = true;
setTimeout(cb, 25);
}, 1);
cargo.drain = function () {
test.done();
};
test.equals(cargo.payload, 1);
cargo.push([1, 2, 3]);
setTimeout(function () {
cargo.payload = 2;
}, 15);
}
};
exports['memoize'] = {
'memoize': function (test) {
test.expect(5);
var call_order = [];
var fn = function (arg1, arg2, callback) {
async.setImmediate(function () {
call_order.push(['fn', arg1, arg2]);
callback(null, arg1 + arg2);
});
};
var fn2 = async.memoize(fn);
fn2(1, 2, function (err, result) {
test.ok(err === null, err + " passed instead of 'null'");
test.equal(result, 3);
fn2(1, 2, function (err, result) {
test.equal(result, 3);
fn2(2, 2, function (err, result) {
test.equal(result, 4);
test.same(call_order, [['fn',1,2], ['fn',2,2]]);
test.done();
});
});
});
},
'maintains asynchrony': function (test) {
test.expect(3);
var call_order = [];
var fn = function (arg1, arg2, callback) {
call_order.push(['fn', arg1, arg2]);
async.setImmediate(function () {
call_order.push(['cb', arg1, arg2]);
callback(null, arg1 + arg2);
});
};
var fn2 = async.memoize(fn);
fn2(1, 2, function (err, result) {
test.equal(result, 3);
fn2(1, 2, function (err, result) {
test.equal(result, 3);
async.nextTick(memoize_done);
call_order.push('tick3');
});
call_order.push('tick2');
});
call_order.push('tick1');
function memoize_done() {
var async_call_order = [
['fn',1,2], // initial async call
'tick1', // async caller
['cb',1,2], // async callback
// ['fn',1,2], // memoized // memoized async body
'tick2', // handler for first async call
// ['cb',1,2], // memoized // memoized async response body
'tick3' // handler for memoized async call
];
test.same(call_order, async_call_order);
test.done();
}
},
'unmemoize': function(test) {
test.expect(4);
var call_order = [];
var fn = function (arg1, arg2, callback) {
call_order.push(['fn', arg1, arg2]);
async.setImmediate(function () {
callback(null, arg1 + arg2);
});
};
var fn2 = async.memoize(fn);
var fn3 = async.unmemoize(fn2);
fn3(1, 2, function (err, result) {
test.equal(result, 3);
fn3(1, 2, function (err, result) {
test.equal(result, 3);
fn3(2, 2, function (err, result) {
test.equal(result, 4);
test.same(call_order, [['fn',1,2], ['fn',1,2], ['fn',2,2]]);
test.done();
});
});
});
},
'unmemoize a not memoized function': function(test) {
test.expect(1);
var fn = function (arg1, arg2, callback) {
callback(null, arg1 + arg2);
};
var fn2 = async.unmemoize(fn);
fn2(1, 2, function(err, result) {
test.equal(result, 3);
});
test.done();
},
'error': function (test) {
test.expect(1);
var testerr = new Error('test');
var fn = function (arg1, arg2, callback) {
callback(testerr, arg1 + arg2);
};
async.memoize(fn)(1, 2, function (err) {
test.equal(err, testerr);
});
test.done();
},
'multiple calls': function (test) {
test.expect(3);
var fn = function (arg1, arg2, callback) {
test.ok(true);
setTimeout(function(){
callback(null, arg1, arg2);
}, 10);
};
var fn2 = async.memoize(fn);
fn2(1, 2, function(err, result) {
test.equal(result, 1, 2);
});
fn2(1, 2, function(err, result) {
test.equal(result, 1, 2);
test.done();
});
},
'custom hash function': function (test) {
test.expect(2);
var testerr = new Error('test');
var fn = function (arg1, arg2, callback) {
callback(testerr, arg1 + arg2);
};
var fn2 = async.memoize(fn, function () {
return 'custom hash';
});
fn2(1, 2, function (err, result) {
test.equal(result, 3);
fn2(2, 2, function (err, result) {
test.equal(result, 3);
test.done();
});
});
},
'manually added memo value': function (test) {
test.expect(1);
var fn = async.memoize(function() {
test(false, "Function should never be called");
});
fn.memo["foo"] = ["bar"];
fn("foo", function(val) {
test.equal(val, "bar");
test.done();
});
}
};
exports['ensureAsync'] = {
'defer sync functions': function (test) {
test.expect(6);
var sync = true;
async.ensureAsync(function (arg1, arg2, cb) {
test.equal(arg1, 1);
test.equal(arg2, 2);
cb(null, 4, 5);
})(1, 2, function (err, arg4, arg5) {
test.equal(err, null);
test.equal(arg4, 4);
test.equal(arg5, 5);
test.ok(!sync, 'callback called on same tick');
test.done();
});
sync = false;
},
'do not defer async functions': function (test) {
test.expect(6);
var sync = false;
async.ensureAsync(function (arg1, arg2, cb) {
test.equal(arg1, 1);
test.equal(arg2, 2);
async.setImmediate(function () {
sync = true;
cb(null, 4, 5);
sync = false;
});
})(1, 2, function (err, arg4, arg5) {
test.equal(err, null);
test.equal(arg4, 4);
test.equal(arg5, 5);
test.ok(sync, 'callback called on next tick');
test.done();
});
},
'double wrapping': function (test) {
test.expect(6);
var sync = true;
async.ensureAsync(async.ensureAsync(function (arg1, arg2, cb) {
test.equal(arg1, 1);
test.equal(arg2, 2);
cb(null, 4, 5);
}))(1, 2, function (err, arg4, arg5) {
test.equal(err, null);
test.equal(arg4, 4);
test.equal(arg5, 5);
test.ok(!sync, 'callback called on same tick');
test.done();
});
sync = false;
}
};
exports['constant'] = function (test) {
test.expect(5);
var f = async.constant(42, 1, 2, 3);
f(function (err, value, a, b, c) {
test.ok(!err);
test.ok(value === 42);
test.ok(a === 1);
test.ok(b === 2);
test.ok(c === 3);
test.done();
});
};
exports['asyncify'] = {
'asyncify': function (test) {
var parse = async.asyncify(JSON.parse);
parse("{\"a\":1}", function (err, result) {
test.ok(!err);
test.ok(result.a === 1);
test.done();
});
},
'asyncify null': function (test) {
var parse = async.asyncify(function() {
return null;
});
parse("{\"a\":1}", function (err, result) {
test.ok(!err);
test.ok(result === null);
test.done();
});
},
'variable numbers of arguments': function (test) {
async.asyncify(function (x, y, z) {
test.ok(arguments.length === 3);
test.ok(x === 1);
test.ok(y === 2);
test.ok(z === 3);
})(1, 2, 3, function () {});
test.done();
},
'catch errors': function (test) {
async.asyncify(function () {
throw new Error("foo");
})(function (err) {
test.ok(err);
test.ok(err.message === "foo");
test.done();
});
},
'dont catch errors in the callback': function (test) {
try {
async.asyncify(function () {})(function (err) {
if (err) {
return test.done(new Error("should not get an error here"));
}
throw new Error("callback error");
});
} catch (e) {
test.ok(e.message === "callback error");
test.done();
}
},
'promisified': [
'native-promise-only',
'bluebird',
'es6-promise',
'rsvp'
].reduce(function(promises, name) {
if (isBrowser()) {
// node only test
return;
}
var Promise = require(name);
if (typeof Promise.Promise === 'function') {
Promise = Promise.Promise;
}
promises[name] = {
'resolve': function(test) {
var promisified = function(argument) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(argument + " resolved");
}, 15);
});
};
async.asyncify(promisified)("argument", function (err, value) {
if (err) {
return test.done(new Error("should not get an error here"));
}
test.ok(value === "argument resolved");
test.done();
});
},
'reject': function(test) {
var promisified = function(argument) {
return new Promise(function (resolve, reject) {
reject(argument + " rejected");
});
};
async.asyncify(promisified)("argument", function (err) {
test.ok(err);
test.ok(err.message === "argument rejected");
test.done();
});
}
};
return promises;
}, {})
};
| Kikobeats/async | test/test-async.js | JavaScript | mit | 119,151 |
/**
* Runs a webserver and socket server for visualizating interactions with TJBot
*/
var ip = require('ip');
var express = require("express")
var config = require('./config.js')
var path = require("path")
var app = express();
var http = require('http');
var exports = module.exports = {};
// routes
var routes = require('./routes/index');
var server = http.createServer(app).listen(config.webServerNumber, function() {
var addr = server.address();
console.log('Dashboard running at : http://' + ip.address() + ':' + addr.port);
});
var bodyParser = require('body-parser');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// parse application/json
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.use(express.static('public'));
app.use('/', routes);
var WebSocket = require('ws');
var wss = new WebSocket.Server({
server
});
var clients = new Map();
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
});
clients.set(ws._socket._handle.fd, ws);
//clients.push({id: ws._socket._handle.fd , client: });
// ws.send('something ......');
var hold = ws;
ws.on('close', function close() {
console.log("closing ");
// clients.delete(ws._socket._handle.fd);
});
});
var sendEvent = function(data) {
console.log("Number of connectd clients", clients.size)
for (var [key, client] of clients) {
//console.log(key + ' = sending');
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data))
} else {
clients.delete(key);
}
}
}
exports.sendEvent = sendEvent;
exports.wss = wss
| victordibia/tjdashboard | server.js | JavaScript | mit | 1,711 |
import 'webrtc-adapter/out/adapter.js';
import EventEmitter from 'events';
var configuration = {
iceServers: [
{urls: "stun:stun.l.google.com:19302"},
{urls: "turn:numb.viagenie.ca", credential: "w0kkaw0kka", username: "paul.sachs%40influitive.com"}
]
};
export default class FirePeer extends EventEmitter {
constructor(firebaseRef, userId, isMuted, isVideoMuted){
super();
this.firebaseRef = firebaseRef;
this.userRef = firebaseRef.child(userId);
this.userId = userId;
this.eventHandlers = {};
this.options = { audio: true, video: true };
this.connections = {};
// Stores mediastreams with the key being the id of the target peer
this.mediaStreams = {};
this.isMutedRef = this.userRef.child("isMuted");
this.isVideoMutedRef = this.userRef.child("isVideoMuted");
this.offersRef = this.userRef.child("offers");
this.answersRef = this.userRef.child("answers");
this.userRef.onDisconnect().remove();
this.isMuted = isMuted;
this.isVideoMuted = isVideoMuted;
this.isMutedRef.set(this.isMuted);
this.isVideoMutedRef.set(this.isVideoMuted);
this.offersRef.on("child_added", (snapshot) => {
const data = snapshot.val();
const incomingPeerId = snapshot.key();
this.acceptOffer(incomingPeerId, data).then(()=>{
// Delete the offer once accepted.
this.offersRef.child(incomingPeerId).set(null);
});
});
this.answersRef.on("child_added", (snapshot) => {
const data = snapshot.val();
const incomingPeerId = snapshot.key();
this.handleAnswer(incomingPeerId, data).then(()=>{
// Delete the offer once accepted.
this.answersRef.child(incomingPeerId).set(null);
});
});
this.firebaseRef.on("child_removed", (snapshot) => {
const peerId = snapshot.key();
if (this.userId == peerId) {
this.handleDisconnect();
}
});
this.isMutedRef.on("value", this.handleIsMuted);
this.isVideoMutedRef.on("value", this.handleIsVideoMuted);
}
connect = (peerId) => {
if (this.connections[peerId] && this.connections[peerId].signalingState != 'closed') {
console.log('Could send offer, already have connection');
return;
}
const connection = new RTCPeerConnection(configuration);
this.connections[peerId] = connection;
this.onaddstream = this.handleAddStream;
// place an offer on the room.
const media = this.getPeerMedia();
return media.then((mediaStream)=> {
connection.addStream(mediaStream);
this.emit('stream_added', { stream: mediaStream, isSelf: true});
this.mediaStreams[peerId] = mediaStream;
return connection.createOffer();
}).then((desc)=> {
return connection.setLocalDescription(desc);
}).then(() => {
const desc = connection.localDescription;
this.firebaseRef.child(peerId).child("offers").child(this.userId)
.set(JSON.stringify(desc.sdp));
this.emit('sent_offer', peerId, desc);
}).catch(this.handleError);
};
disconnectFrom = (peerId) => {
if(this.connections[peerId]) {
this.connections[peerId].close();
}
};
mute = (mute) => {
this.isMutedRef.set(mute);
};
muteVideo = (mute) => {
this.isVideoMutedRef.set(mute);
};
disconnect = () => {
this.userRef.remove();
};
// Private:
handleDisconnect = () => {
for (let key of Object.keys(this.connections)) {
this.connections[key].close();
}
}
getPeerMedia = () => {
const media = navigator.mediaDevices.getUserMedia(
{ audio: !this.isMuted, video: !this.isVideoMuted}
);
return media;
};
handleAddStream = (event) => {
this.emit('stream_added', { stream: event.stream, isSelf: false});
};
acceptOffer = (peerId, offer) => {
if (this.connections[peerId] && this.connections[peerId].signalingState != 'closed') {
console.log('Could not accept offer, already have connection');
return;
}
const connection = new RTCPeerConnection(configuration);
this.connections[peerId] = connection;
// place an offer on the room.
const media = this.getPeerMedia();
const remote_descr = new RTCSessionDescription();
remote_descr.type = "offer";
remote_descr.sdp = JSON.parse(offer);
return media.then((mediaStream)=> {
connection.addStream(mediaStream);
this.emit('stream_added', { stream: mediaStream, isSelf: true});
this.mediaStreams[peerId] = mediaStream;
return connection.setRemoteDescription(remote_descr);
}).then(()=> {
return connection.createAnswer();
}).then((answer) => {
return connection.setLocalDescription(answer);
}).then(()=> {
const answer = connection.localDescription;
this.firebaseRef.child(peerId).child("answers").child(this.userId)
.set(JSON.stringify(answer.sdp));
this.emit('accepted_offer', peerId, answer);
}).catch(this.handleError);
};
handleAnswer = (peerId, answer) => {
const remote_descr = new RTCSessionDescription();
remote_descr.type = "answer";
remote_descr.sdp = JSON.parse(answer);
return this.connections[peerId].setRemoteDescription(remote_descr).then(() => {
this.emit('handled_answer', peerId, answer);
}).catch(this.handleError);
};
handleError = (error) => {
console.error("FirePeer: ");
console.error(error);
};
handleIsMuted = (snapshot) => {
this.isMuted = snapshot.val();
for (const peerId of Object.keys(this.mediaStreams)) {
const stream = this.mediaStreams[peerId];
const audioTracks = stream.getAudioTracks();
for (const audioTrack of audioTracks) {
audioTrack.enabled = !this.isMuted;
}
}
this.emit("muted", this.isMuted);
};
handleIsVideoMuted = (snapshot) => {
this.isVideoMuted = snapshot.val();
for (const peerId of Object.keys(this.mediaStreams)) {
const stream = this.mediaStreams[peerId];
const videoTracks = stream.getVideoTracks();
for (const videoTrack of videoTracks) {
videoTrack.enabled = !this.isVideoMuted;
}
}
this.emit("video_muted", this.isVideoMuted);
};
logInfo = () => {
for (const peerId of Object.keys(this.mediaStreams)) {
const stream = this.mediaStreams[peerId];
console.log(peerId);
console.log("----");
console.log("stream:");
console.log(stream);
console.log("audioTracks:");
console.log(stream.getAudioTracks());
console.log("videoTracks:");
console.log(stream.getVideoTracks());
console.log("----");
}
}
}
| psachs21/lillywood | src/utilities/FirePeer.js | JavaScript | mit | 6,680 |
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.Mars || (g.Mars = {})).React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Component for rendering data container
*/
var DataManagerContainer = function (_React$Component) {
_inherits(DataManagerContainer, _React$Component);
function DataManagerContainer(props, context) {
_classCallCheck(this, DataManagerContainer);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(DataManagerContainer).call(this, props, context));
_this.state = { result: {} };
_this.query = props.component.getQuery(props.variables);
_this.query.on('update', _this._handleDataChanges.bind(_this));
_this._executeQuery();
return _this;
}
_createClass(DataManagerContainer, [{
key: '_executeQuery',
value: function _executeQuery() {
var _this2 = this;
this._resolved = false;
this.query.execute().then(function (result) {
_this2._resolved = true;
_this2.setState({ result: result });
});
}
}, {
key: '_handleDataChanges',
value: function _handleDataChanges(result) {
if (this._resolved) {
this.setState({ result: result });
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.query.stop();
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.query.updateVariables(nextProps);
}
}, {
key: 'renderLoading',
value: function renderLoading() {
return this.props.renderLoading();
}
}, {
key: 'render',
value: function render() {
var Component = this.props.component; // eslint-disable-line
return this._resolved ? _react2.default.createElement(Component, _extends({}, this.props, this.state.result)) : this.renderLoading();
}
}]);
return DataManagerContainer;
}(_react2.default.Component);
DataManagerContainer.defaultProps = {
renderLoading: function renderLoading() {
return null;
}
};
exports.default = DataManagerContainer;
},{"react":undefined}],2:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _forEach = require('fast.js/forEach');
var _forEach2 = _interopRequireDefault(_forEach);
var _map2 = require('fast.js/map');
var _map3 = _interopRequireDefault(_map2);
var _keys2 = require('fast.js/object/keys');
var _keys3 = _interopRequireDefault(_keys2);
var _marsdb = require('marsdb');
var _invariant = require('invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _utils = require('./utils');
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* ExecutionContext is used to track changes of variables
* and cursors and cleanup listeners on parent cursor changes.
* It also provides a method to run a function "in context":
* while function running, `ExecutionContext.getCurrentContext()`
* returning the context.
*/
var ExecutionContext = function (_EventEmitter) {
_inherits(ExecutionContext, _EventEmitter);
function ExecutionContext() {
var variables = arguments.length <= 0 || arguments[0] === undefined ? new Map() : arguments[0];
_classCallCheck(this, ExecutionContext);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ExecutionContext).call(this));
_this.variables = variables;
_this.emitCleanup = _this.emitCleanup.bind(_this);
return _this;
}
/**
* Adds a cleanup event listener and return a funtion
* for removing listener.
* @param {Function} fn
* @return {Function}
*/
_createClass(ExecutionContext, [{
key: 'addCleanupListener',
value: function addCleanupListener(fn) {
var _this2 = this;
this.on('cleanup', fn);
return function () {
return _this2.removeListener('cleanup', fn);
};
}
/**
* Emits cleanup event. Given argument indicates the source
* of the event. If it is `false`, then the event will be
* interprated as "went from upper context".
* @param {Boolean} isRoot
*/
}, {
key: 'emitCleanup',
value: function emitCleanup() {
var isRoot = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
this.emit('cleanup', isRoot);
}
/**
* Creates a child context, that have the same map of variables.
* Set context cleanup listener for propagating the event to the child.
* Return child context object.
* @return {ExecutionContext}
*/
}, {
key: 'createChildContext',
value: function createChildContext() {
var newContext = new ExecutionContext(this.variables);
var stopper = this.addCleanupListener(function (isRoot) {
newContext.emitCleanup(false);
if (!isRoot) {
stopper();
}
});
return newContext;
}
/**
* Execute given function "in context": set the context
* as globally active with saving of previous active context,
* and execute a function. While function executing
* `ExecutionContext.getCurrentContext()` will return the context.
* At the end of the execution it puts previous context back.
* @param {Function} fn
*/
}, {
key: 'withinContext',
value: function withinContext(fn) {
var prevContext = ExecutionContext.getCurrentContext();
ExecutionContext.__currentContext = this;
try {
return fn();
} finally {
ExecutionContext.__currentContext = prevContext;
}
}
/**
* By given container class get variables from
* the context and merge it with given initial values
* and variables mapping. Return the result of the merge.
* @param {Class} containerClass
* @param {OBject} initVars
* @param {Object} mapVars
* @return {Object}
*/
}, {
key: 'getVariables',
value: function getVariables(containerClass) {
var initVars = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var mapVars = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var prepareVariables = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];
var contextVars = this.variables.get(containerClass);
if (!contextVars) {
contextVars = {};
this.variables.set(containerClass, contextVars);
}
for (var k in initVars) {
if (contextVars[k] === undefined) {
if (mapVars[k] !== undefined) {
(0, _invariant2.default)(utils._isProperty(mapVars[k]), 'You can pass to a mapping only parent variables');
contextVars[k] = mapVars[k];
} else {
contextVars[k] = utils._createProperty(initVars[k]);
}
}
}
if (prepareVariables && !contextVars.promise) {
Object.defineProperty(contextVars, 'promise', {
value: Promise.resolve(prepareVariables(contextVars)),
configurable: true
});
}
return contextVars;
}
/**
* Track changes of given variable and regenerate value
* on change. It also listen to context cleanup event
* for stop variable change listeners
* @param {Property} prop
* @param {Object} vars
* @param {Function} valueGenerator
*/
}, {
key: 'trackVariablesChange',
value: function trackVariablesChange(prop, vars, valueGenerator) {
var _this3 = this;
var updater = function updater() {
_this3.emitCleanup();
if (prop.promise && prop.promise.stop) {
prop.promise.stop();
}
var nextValue = _this3.withinContext(function () {
return valueGenerator(vars);
});
if (utils._isCursor(nextValue)) {
_this3.trackCursorChange(prop, nextValue);
prop.emitChange();
} else if (!utils._isProperty(nextValue)) {
prop(nextValue);
} else {
// Variables tracking must be used only vhen valueGenerator
// returns a Cursor or any type except Property.
throw new Error('Next value can\'t be a property');
}
};
var varTrackers = (0, _map3.default)((0, _keys3.default)(vars), function (k) {
return vars[k].addChangeListener(updater);
});
var stopper = this.addCleanupListener(function (isRoot) {
if (!isRoot) {
(0, _forEach2.default)(varTrackers, function (stop) {
return stop();
});
stopper();
}
});
}
/**
* Observe given cursor for changes and set new
* result in given property. Also tracks context
* cleanup event for stop observers
* @param {Property} prop
* @param {Cursor} cursor
*/
}, {
key: 'trackCursorChange',
value: function trackCursorChange(prop, cursor) {
var _this4 = this;
if (prop.removeCursorTracker) {
prop.removeCursorTracker();
}
var observer = function observer(result) {
if (Array.isArray(result)) {
result = (0, _map3.default)(result, function (x) {
return utils._createPropertyWithContext(x, _this4);
});
}
prop(result);
};
cursor.on('cursorChanged', this.emitCleanup);
prop.promise = cursor.observe(observer);
prop.removeCursorTracker = function () {
cursor.removeListener('cursorChanged', _this4.emitCleanup);
prop.promise.stop();
};
var stopper = this.addCleanupListener(function (isRoot) {
if (!isRoot) {
prop.removeCursorTracker();
stopper();
}
});
}
/**
* Returns a current active context, set by `withinContext`
* @return {ExecutionContext}
*/
}], [{
key: 'getCurrentContext',
value: function getCurrentContext() {
return ExecutionContext.__currentContext;
}
}]);
return ExecutionContext;
}(_marsdb.EventEmitter);
exports.default = ExecutionContext;
},{"./utils":5,"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"invariant":16,"marsdb":undefined}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _keys2 = require('fast.js/object/keys');
var _keys3 = _interopRequireDefault(_keys2);
var _forEach = require('fast.js/forEach');
var _forEach2 = _interopRequireDefault(_forEach);
var _map2 = require('fast.js/map');
var _map3 = _interopRequireDefault(_map2);
var _marsdb = require('marsdb');
var _invariant = require('invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _ExecutionContext = require('./ExecutionContext');
var _ExecutionContext2 = _interopRequireDefault(_ExecutionContext);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* By given frgments object, varialbes and containerClass
* creates a query executor.
* It will execute each fragment of fragments object and
* return a promise, that will be resolved when all fragments
* is filled with data.
*
* Container class is an object with one static function – `getFragment`,
* that must return a property function. By all properties constructed
* a Promise that resolved when all `prop.promise` resolved.
*
* The class extends `EventEmitter`.Only one event may be emitted – `update`.
* The event emitted when query data is updated. With event is arrived an object
* of proprties for each fragment.
*/
var QueryExecutor = function (_EventEmitter) {
_inherits(QueryExecutor, _EventEmitter);
function QueryExecutor(fragments, initVarsOverride, containerClass, prepareVariables) {
_classCallCheck(this, QueryExecutor);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(QueryExecutor).call(this));
_this.containerClass = containerClass;
_this.fragmentNames = (0, _keys3.default)(fragments);
_this.initVarsOverride = initVarsOverride;
_this.context = new _ExecutionContext2.default();
_this.variables = _this.context.getVariables(containerClass, initVarsOverride, {}, prepareVariables);
_this._handleDataChanges = (0, _marsdb.debounce)(_this._handleDataChanges.bind(_this), 1000 / 60, 5);
return _this;
}
/**
* Change a batch size of updater.
* Btach size is a number of changes must be happen
* in debounce interval to force execute debounced
* function (update a result, in our case)
*
* @param {Number} batchSize
* @return {CursorObservable}
*/
_createClass(QueryExecutor, [{
key: 'batchSize',
value: function batchSize(_batchSize) {
this._handleDataChanges.updateBatchSize(_batchSize);
return this;
}
/**
* Change debounce wait time of the updater
* @param {Number} waitTime
* @return {CursorObservable}
*/
}, {
key: 'debounce',
value: function debounce(waitTime) {
this._handleDataChanges.updateWait(waitTime);
return this;
}
/**
* Execute the query and return a Promise, that resolved
* when all props will be filled with data.
* If query already executing it just returns a promise
* for currently executing query.
* @return {Promise}
*/
}, {
key: 'execute',
value: function execute() {
var _this2 = this;
if (!this._execution) {
(function () {
_this2.result = {};
_this2.context.withinContext(function () {
(0, _forEach2.default)(_this2.fragmentNames, function (k) {
_this2.result[k] = _this2.containerClass.getFragment(k);
});
});
var updater = function updater() {
_this2._execution = _this2._handleDataChanges();
};
_this2._stoppers = (0, _map3.default)(_this2.fragmentNames, function (k) {
return _this2.result[k].addChangeListener(updater);
});
updater();
})();
}
return this._execution;
}
/**
* Stops query executing and listening for changes.
* Returns a promise resolved when query stopped.
* @return {Promise}
*/
}, {
key: 'stop',
value: function stop() {
var _this3 = this;
(0, _invariant2.default)(this._execution, 'stop(...): query is not executing');
// Remove all update listeners synchronously to avoid
// updates of old data
this.removeAllListeners();
return this._execution.then(function () {
(0, _forEach2.default)(_this3._stoppers, function (stop) {
return stop();
});
_this3.context.emitCleanup();
_this3._execution = null;
});
}
/**
* Update top level variables of the query by setting
* values in variable props from given object. If field
* exists in a given object and not exists in variables map
* then it will be ignored.
* @param {Object} nextProps
* @return {Promise} resolved when variables updated
*/
}, {
key: 'updateVariables',
value: function updateVariables(nextProps) {
var _this4 = this;
(0, _invariant2.default)(this._execution, 'updateVariables(...): query is not executing');
return this._execution.then(function () {
var updated = false;
(0, _forEach2.default)(nextProps, function (prop, k) {
if (_this4.variables[k] && _this4.variables[k]() !== prop) {
_this4.variables[k](prop);
updated = true;
}
});
return updated;
});
}
/**
* The method is invoked when some of fragment's property is updated.
* It emits an `update` event only when all `prop.promise` is resolved.
*/
}, {
key: '_handleDataChanges',
value: function _handleDataChanges() {
var _this5 = this;
var nextPromises = (0, _map3.default)(this.fragmentNames, function (k) {
return _this5.result[k].promise;
});
var resultPromise = Promise.all(nextPromises).then(function () {
if (_this5._resultPromise === resultPromise) {
_this5.emit('update', _this5.result);
}
return _this5.result;
}, function (error) {
_this5.emit('error', error);
return _this5.result;
});
this._resultPromise = resultPromise;
return this._resultPromise;
}
}]);
return QueryExecutor;
}(_marsdb.EventEmitter);
exports.default = QueryExecutor;
},{"./ExecutionContext":2,"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"invariant":16,"marsdb":undefined}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createContainer;
var _keys2 = require('fast.js/object/keys');
var _keys3 = _interopRequireDefault(_keys2);
var _assign2 = require('fast.js/object/assign');
var _assign3 = _interopRequireDefault(_assign2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _invariant = require('invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _ExecutionContext = require('./ExecutionContext');
var _ExecutionContext2 = _interopRequireDefault(_ExecutionContext);
var _QueryExecutor = require('./QueryExecutor');
var _QueryExecutor2 = _interopRequireDefault(_QueryExecutor);
var _utils = require('./utils');
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* High-order data container creator
* @param {Component} Component
* @param {Object} options.fragments
* @param {Object} options.initVars
* @return {Component}
*/
function createContainer(Component, _ref) {
var _ref$fragments = _ref.fragments;
var fragments = _ref$fragments === undefined ? {} : _ref$fragments;
var _ref$initialVariables = _ref.initialVariables;
var initialVariables = _ref$initialVariables === undefined ? {} : _ref$initialVariables;
var _ref$prepareVariables = _ref.prepareVariables;
var prepareVariables = _ref$prepareVariables === undefined ? null : _ref$prepareVariables;
var componentName = Component.displayName || Component.name;
var containerName = 'Mars(' + componentName + ')';
var fragmentKeys = (0, _keys3.default)(fragments);
var Container = function (_React$Component) {
_inherits(Container, _React$Component);
function Container() {
_classCallCheck(this, Container);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Container).apply(this, arguments));
}
_createClass(Container, [{
key: 'render',
value: function render() {
var variables = this.props[fragmentKeys[0]].context.getVariables(Container);
return _react2.default.createElement(Component, _extends({}, this.props, { variables: variables }));
}
}], [{
key: 'getFragment',
value: function getFragment(name, mapping) {
var initVarsOverride = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var parentContext = arguments[3];
parentContext = parentContext || _ExecutionContext2.default.getCurrentContext();
(0, _invariant2.default)(parentContext, 'getFragment(...): must be invoked within some context');
var childContext = parentContext.createChildContext();
var fragment = fragments[name];
var initVars = (0, _assign3.default)({}, initialVariables, initVarsOverride);
var vars = childContext.getVariables(Container, initVars, mapping, prepareVariables);
(0, _invariant2.default)(typeof fragment === 'function' || (typeof fragment === 'undefined' ? 'undefined' : _typeof(fragment)) === 'object', 'getFragment(...): a fragment must be a function or an object');
if ((typeof fragment === 'undefined' ? 'undefined' : _typeof(fragment)) === 'object') {
return utils._getJoinFunction(Container, fragment, vars, childContext);
} else {
return utils._getFragmentValue(Container, fragment, vars, childContext);
}
}
}, {
key: 'getQuery',
value: function getQuery() {
var initVarsOverride = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var initVars = (0, _assign3.default)({}, initialVariables, initVarsOverride);
return new _QueryExecutor2.default(fragments, initVars, Container, prepareVariables);
}
}]);
return Container;
}(_react2.default.Component);
Container.displayName = containerName;
return Container;
}
},{"./ExecutionContext":2,"./QueryExecutor":3,"./utils":5,"fast.js/object/assign":12,"fast.js/object/keys":14,"invariant":16,"react":undefined}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.noop = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports._isProperty = _isProperty;
exports._isCursor = _isCursor;
exports._getFragmentValue = _getFragmentValue;
exports._getJoinFunction = _getJoinFunction;
exports._createProperty = _createProperty;
exports._createPropertyWithContext = _createPropertyWithContext;
var _forEach = require('fast.js/forEach');
var _forEach2 = _interopRequireDefault(_forEach);
var _map2 = require('fast.js/map');
var _map3 = _interopRequireDefault(_map2);
var _keys2 = require('fast.js/object/keys');
var _keys3 = _interopRequireDefault(_keys2);
var _marsdb = require('marsdb');
var _CursorObservable = require('marsdb/dist/CursorObservable');
var _CursorObservable2 = _interopRequireDefault(_CursorObservable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Internals
var _propertyVersionId = 0;
var noop = exports.noop = function noop() {}; // eslint-disable-line
/**
* Return true if given value is a property
* @param {Object} val
* @return {Boolean}
*/
function _isProperty(val) {
return typeof val === 'function' && !!val.isProperty;
}
/**
* Return true if given value is a CursorObservable
* @param {OBject} val
* @return {Boolean}
*/
function _isCursor(val) {
return val instanceof _CursorObservable2.default;
}
/**
* Return a property, that updated when value
* of fragment changed or variable changed. It do nothing
* if generated value is already a property (just returns
* the property).
*
* @param {Class} containerClass
* @param {Function} valueGenerator
* @param {Object} vars
* @param {ExecutionContext} context
* @return {Property}
*/
function _getFragmentValue(containerClass, valueGenerator, vars, context) {
var _createFragmentProp = function _createFragmentProp() {
var value = context.withinContext(function () {
return valueGenerator(vars);
});
var prop = undefined;
if (_isProperty(value)) {
prop = value;
} else {
prop = _createPropertyWithContext(null, context);
if (_isCursor(value)) {
context.trackCursorChange(prop, value);
} else {
prop(value);
}
context.trackVariablesChange(prop, vars, valueGenerator);
}
return prop;
};
if (vars.promise) {
var _ret = function () {
var proxyProp = _createPropertyWithContext(null, context);
proxyProp.promise = vars.promise.then(function () {
var fragProp = _createFragmentProp();
if (fragProp() !== null) {
proxyProp.emitChange();
}
proxyProp.proxyTo(fragProp);
return fragProp.promise;
});
return {
v: proxyProp
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
} else {
return _createFragmentProp();
}
}
/**
* Return a function that join the result of given joinObj.
* @param {Class} containerClass
* @param {Object} joinObj
* @param {Object} vars
* @param {ExecutionContext} context
* @return {Function}
*/
function _getJoinFunction(containerClass, joinObj, vars, context) {
var joinObjKeys = (0, _keys3.default)(joinObj);
return function (doc) {
var updated = arguments.length <= 1 || arguments[1] === undefined ? noop : arguments[1];
if ((typeof doc === 'undefined' ? 'undefined' : _typeof(doc)) === 'object' && doc !== null) {
return (0, _map3.default)(joinObjKeys, function (k) {
if (doc[k] === undefined) {
var _ret2 = function () {
var valueGenerator = function valueGenerator(opts) {
return joinObj[k](doc, opts);
};
var prop = _getFragmentValue(containerClass, valueGenerator, vars, context);
doc[k] = prop;
return {
v: Promise.resolve(prop.promise).then(function (res) {
var changeStopper = prop.addChangeListener(updated);
var cleanStopper = context.addCleanupListener(function (isRoot) {
if (!isRoot) {
cleanStopper();
changeStopper();
}
});
return res;
})
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
});
}
};
}
/**
* Creates a getter-setter property function.
* The function returns current value if called without
* arguments. If first argument passed then it sets new
* value and returns new value.
*
* On set of a new value it emits a change event. You can
* listen on a change event by calling `addChangeListener`
* which adds a change event handler that returns a function
* for stopping listening.
*
* A property also have a `version` field. It's a unique value
* across all active properties. A version is changed when
* property have changed before emitting change event.
*
* @param {Mixed} initValue
* @return {Property}
*/
function _createProperty(initValue) {
var emitter = new _marsdb.EventEmitter();
var store = initValue;
var proxyProp = null;
var prop = function prop() {
if (proxyProp) {
return proxyProp.apply(null, arguments);
} else {
if (arguments.length > 0) {
store = arguments[0];
if (arguments.length === 1) {
prop.emitChange();
}
}
return store;
}
};
prop.emitChange = function () {
prop.version = ++_propertyVersionId;
emitter.emit('change');
};
prop.addChangeListener = function (func) {
emitter.on('change', func);
return function () {
emitter.removeListener('change', func);
};
};
prop.proxyTo = function (toProp) {
proxyProp = toProp;
Object.defineProperty(prop, 'version', {
get: function get() {
return toProp.version;
},
set: function set(newValue) {
return toProp.version = newValue;
}
});
prop.addChangeListener = toProp.addChangeListener;
prop.emitChange = toProp.emitChange;
(0, _forEach2.default)(emitter.listeners('change'), function (cb) {
return toProp.addChangeListener(cb);
});
emitter = toProp.__emitter;
store = null;
};
prop.version = ++_propertyVersionId;
prop.isProperty = true;
prop.__emitter = emitter;
return prop;
}
/**
* Create a property that holds given value and context.
* @param {Mixed} value
* @param {ExecutionContext} context
* @return {Property}
*/
function _createPropertyWithContext(value, context) {
var nextProp = _createProperty(value);
nextProp.context = context;
return nextProp;
}
},{"fast.js/forEach":9,"fast.js/map":11,"fast.js/object/keys":14,"marsdb":undefined,"marsdb/dist/CursorObservable":undefined}],6:[function(require,module,exports){
var createContainer = require('./dist/createContainer').default;
var DataManagerContainer = require('./dist/DataManagerContainer').default;
module.exports = {
__esModule: true,
createContainer: createContainer,
DataManagerContainer: DataManagerContainer
};
},{"./dist/DataManagerContainer":1,"./dist/createContainer":4}],7:[function(require,module,exports){
'use strict';
var bindInternal3 = require('../function/bindInternal3');
/**
* # For Each
*
* A fast `.forEach()` implementation.
*
* @param {Array} subject The array (or array-like) to iterate over.
* @param {Function} fn The visitor function.
* @param {Object} thisContext The context for the visitor.
*/
module.exports = function fastForEach (subject, fn, thisContext) {
var length = subject.length,
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
i;
for (i = 0; i < length; i++) {
iterator(subject[i], i, subject);
}
};
},{"../function/bindInternal3":10}],8:[function(require,module,exports){
'use strict';
var bindInternal3 = require('../function/bindInternal3');
/**
* # Map
*
* A fast `.map()` implementation.
*
* @param {Array} subject The array (or array-like) to map over.
* @param {Function} fn The mapper function.
* @param {Object} thisContext The context for the mapper.
* @return {Array} The array containing the results.
*/
module.exports = function fastMap (subject, fn, thisContext) {
var length = subject.length,
result = new Array(length),
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
i;
for (i = 0; i < length; i++) {
result[i] = iterator(subject[i], i, subject);
}
return result;
};
},{"../function/bindInternal3":10}],9:[function(require,module,exports){
'use strict';
var forEachArray = require('./array/forEach'),
forEachObject = require('./object/forEach');
/**
* # ForEach
*
* A fast `.forEach()` implementation.
*
* @param {Array|Object} subject The array or object to iterate over.
* @param {Function} fn The visitor function.
* @param {Object} thisContext The context for the visitor.
*/
module.exports = function fastForEach (subject, fn, thisContext) {
if (subject instanceof Array) {
return forEachArray(subject, fn, thisContext);
}
else {
return forEachObject(subject, fn, thisContext);
}
};
},{"./array/forEach":7,"./object/forEach":13}],10:[function(require,module,exports){
'use strict';
/**
* Internal helper to bind a function known to have 3 arguments
* to a given context.
*/
module.exports = function bindInternal3 (func, thisContext) {
return function (a, b, c) {
return func.call(thisContext, a, b, c);
};
};
},{}],11:[function(require,module,exports){
'use strict';
var mapArray = require('./array/map'),
mapObject = require('./object/map');
/**
* # Map
*
* A fast `.map()` implementation.
*
* @param {Array|Object} subject The array or object to map over.
* @param {Function} fn The mapper function.
* @param {Object} thisContext The context for the mapper.
* @return {Array|Object} The array or object containing the results.
*/
module.exports = function fastMap (subject, fn, thisContext) {
if (subject instanceof Array) {
return mapArray(subject, fn, thisContext);
}
else {
return mapObject(subject, fn, thisContext);
}
};
},{"./array/map":8,"./object/map":15}],12:[function(require,module,exports){
'use strict';
/**
* Analogue of Object.assign().
* Copies properties from one or more source objects to
* a target object. Existing keys on the target object will be overwritten.
*
* > Note: This differs from spec in some important ways:
* > 1. Will throw if passed non-objects, including `undefined` or `null` values.
* > 2. Does not support the curious Exception handling behavior, exceptions are thrown immediately.
* > For more details, see:
* > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
*
*
*
* @param {Object} target The target object to copy properties to.
* @param {Object} source, ... The source(s) to copy properties from.
* @return {Object} The updated target object.
*/
module.exports = function fastAssign (target) {
var totalArgs = arguments.length,
source, i, totalKeys, keys, key, j;
for (i = 1; i < totalArgs; i++) {
source = arguments[i];
keys = Object.keys(source);
totalKeys = keys.length;
for (j = 0; j < totalKeys; j++) {
key = keys[j];
target[key] = source[key];
}
}
return target;
};
},{}],13:[function(require,module,exports){
'use strict';
var bindInternal3 = require('../function/bindInternal3');
/**
* # For Each
*
* A fast object `.forEach()` implementation.
*
* @param {Object} subject The object to iterate over.
* @param {Function} fn The visitor function.
* @param {Object} thisContext The context for the visitor.
*/
module.exports = function fastForEachObject (subject, fn, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
key, i;
for (i = 0; i < length; i++) {
key = keys[i];
iterator(subject[key], key, subject);
}
};
},{"../function/bindInternal3":10}],14:[function(require,module,exports){
'use strict';
/**
* Object.keys() shim for ES3 environments.
*
* @param {Object} obj The object to get keys for.
* @return {Array} The array of keys.
*/
module.exports = typeof Object.keys === "function" ? Object.keys : /* istanbul ignore next */ function fastKeys (obj) {
var keys = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
},{}],15:[function(require,module,exports){
'use strict';
var bindInternal3 = require('../function/bindInternal3');
/**
* # Map
*
* A fast object `.map()` implementation.
*
* @param {Object} subject The object to map over.
* @param {Function} fn The mapper function.
* @param {Object} thisContext The context for the mapper.
* @return {Object} The new object containing the results.
*/
module.exports = function fastMapObject (subject, fn, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
result = {},
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
i, key;
for (i = 0; i < length; i++) {
key = keys[i];
result[key] = iterator(subject[key], key, subject);
}
return result;
};
},{"../function/bindInternal3":10}],16:[function(require,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if ("production" !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
},{}]},{},[6])(6)
}); | c58/marsdb-react | build/marsdb.react.js | JavaScript | mit | 44,498 |
module.exports = LoadsModels
const resolve = require.resolve
function LoadsModels (models) {
const load = models.load.bind(models)
/*
load(
require('./create_root_portfolio.js'),
{ uri: resolve('./create_root_portfolio.js'), id: 'portfolios/root' }
)
*/
}
| stylish/stylish | packages/skypager-template-plugin/src/models/index.js | JavaScript | mit | 277 |
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
module: {
preLoaders: [
{
test: /\.tsx?$/,
exclude: /(node_modules)/,
loader: 'source-map'
}
],
loaders: [{
test: /\.scss$/,
include: /src/,
loaders: [
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputStyle=expanded'
]},{
test: /\.tsx?$/,
loaders: [
'babel',
'ts-loader'
],
include: path.join(__dirname, 'app')
}]
},
resolve: {
extensions: ["", ".webpack.js", ".web.js", ".js", ".ts", ".tsx"]
}
};
| onybo/webpack-react-typescript-demo | material-ui/webpack.config.prod.js | JavaScript | mit | 1,184 |
window.esdocSearchIndex = [
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupaddsampledatas.js~advencedfilterargmanagercategorygroupaddsampledatas",
"variable/index.html#static-variable-AdvencedFilterArgManagerCategoryGroupAddSampleDatas",
"<span>AdvencedFilterArgManagerCategoryGroupAddSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupeditsampledatas.js~advencedfilterargmanagercategorygroupeditsampledatas",
"variable/index.html#static-variable-AdvencedFilterArgManagerCategoryGroupEditSampleDatas",
"<span>AdvencedFilterArgManagerCategoryGroupEditSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorymovesampledatas.js~advencedfilterargmanagercategorymovesampledatas",
"variable/index.html#static-variable-AdvencedFilterArgManagerCategoryMoveSampleDatas",
"<span>AdvencedFilterArgManagerCategoryMoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategoryremovesampledatas.js~advencedfilterargmanagercategoryremovesampledatas",
"variable/index.html#static-variable-AdvencedFilterArgManagerCategoryRemoveSampleDatas",
"<span>AdvencedFilterArgManagerCategoryRemoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagerreadsampledatas.js~advencedfilterargmanagerreadsampledatas",
"variable/index.html#static-variable-AdvencedFilterArgManagerReadSampleDatas",
"<span>AdvencedFilterArgManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/advencedfiltermanager/advencedfiltermanagerreadsampledatas.js~advencedfiltermanagerreadsampledatas",
"variable/index.html#static-variable-AdvencedFilterManagerReadSampleDatas",
"<span>AdvencedFilterManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/userdashboard/src/components/advencedfilterquickviewer/advencedfilterquickviewersampledatas.js~advencedfilterquickviewersampledatas",
"variable/index.html#static-variable-AdvencedFilterQuickViewerSampleDatas",
"<span>AdvencedFilterQuickViewerSampleDatas</span> <span class=\"search-result-import-path\">./git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/categorylistmanager/categorylistmanagerreadsampledatas.js~categorylistmanagerreadsampledatas",
"variable/index.html#static-variable-CategoryListManagerReadSampleDatas",
"<span>CategoryListManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerloginsampledatas.js~loginmanagerloginsampledatas",
"variable/index.html#static-variable-LoginManagerLoginSampleDatas",
"<span>LoginManagerLoginSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerlogoutsampledatas.js~loginmanagerlogoutsampledatas",
"variable/index.html#static-variable-LoginManagerLogoutSampleDatas",
"<span>LoginManagerLogoutSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js</span>",
"variable"
],
[
"./git/uicontentsmanager/src/components/networkswitcher/networkswitchersampledatas.js~networkswitchersampledatas",
"variable/index.html#static-variable-NetworkSwitcherSampleDatas",
"<span>NetworkSwitcherSampleDatas</span> <span class=\"search-result-import-path\">./git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js</span>",
"variable"
],
[
"./git/userdashboard/src/components/networkswitcher/networkswitchersampledatas.js~networkswitchersampledatas",
"variable/index.html#static-variable-NetworkSwitcherSampleDatas",
"<span>NetworkSwitcherSampleDatas</span> <span class=\"search-result-import-path\">./git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanageraddsampledatas.js~projectmanageraddsampledatas",
"variable/index.html#static-variable-ProjectManagerAddSampleDatas",
"<span>ProjectManagerAddSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerciuploadsampledatas.js~projectmanagerciuploadsampledatas",
"variable/index.html#static-variable-ProjectManagerCiUploadSampleDatas",
"<span>ProjectManagerCiUploadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerreadsampledatas.js~projectmanagerreadsampledatas",
"variable/index.html#static-variable-ProjectManagerReadSampleDatas",
"<span>ProjectManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerremovesampledatas.js~projectmanagerremovesampledatas",
"variable/index.html#static-variable-ProjectManagerRemoveSampleDatas",
"<span>ProjectManagerRemoveSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerthumbnailuploadsampledatas.js~projectmanagerthumbnailuploadsampledatas",
"variable/index.html#static-variable-ProjectManagerThumbnailUploadSampleDatas",
"<span>ProjectManagerThumbnailUploadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerclearsampledatas.js~querystatemanagerclearsampledatas",
"variable/index.html#static-variable-QueryStateManagerClearSampleDatas",
"<span>QueryStateManagerClearSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerreadsampledatas.js~querystatemanagerreadsampledatas",
"variable/index.html#static-variable-QueryStateManagerReadSampleDatas",
"<span>QueryStateManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerupdatesampledatas.js~querystatemanagerupdatesampledatas",
"variable/index.html#static-variable-QueryStateManagerUpdateSampleDatas",
"<span>QueryStateManagerUpdateSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerdeletesampledatas.js~usermanagerdeletesampledatas",
"variable/index.html#static-variable-UserManagerDeleteSampleDatas",
"<span>UserManagerDeleteSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagernewsampledatas.js~usermanagernewsampledatas",
"variable/index.html#static-variable-UserManagerNewSampleDatas",
"<span>UserManagerNewSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerreadsampledatas.js~usermanagerreadsampledatas",
"variable/index.html#static-variable-UserManagerReadSampleDatas",
"<span>UserManagerReadSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js</span>",
"variable"
],
[
"./git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerupdatesampledatas.js~usermanagerupdatesampledatas",
"variable/index.html#static-variable-UserManagerUpdateSampleDatas",
"<span>UserManagerUpdateSampleDatas</span> <span class=\"search-result-import-path\">./git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js</span>",
"variable"
],
[
"builtinexternal/ecmascriptexternal.js~array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~arraybuffer",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~ArrayBuffer",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~boolean",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Boolean",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~dataview",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~DataView",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~date",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Date",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~error",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Error",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~evalerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~EvalError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~float32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Float32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~float64array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Float64Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~function",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Function",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~generator",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Generator",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~generatorfunction",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~GeneratorFunction",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~infinity",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Infinity",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int16array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int16Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~int8array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Int8Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~internalerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~InternalError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~json",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~JSON",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~map",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Map",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~nan",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~NaN",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~number",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Number",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~object",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Object",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~promise",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Promise",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~proxy",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Proxy",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~rangeerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~RangeError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~referenceerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~ReferenceError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~reflect",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Reflect",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~regexp",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~RegExp",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~set",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Set",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~string",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~String",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~symbol",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Symbol",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~syntaxerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~SyntaxError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~typeerror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~TypeError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~urierror",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~URIError",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint16array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint16Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint32array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint32Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint8array",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint8Array",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~uint8clampedarray",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~Uint8ClampedArray",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~weakmap",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~WeakMap",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~weakset",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~WeakSet",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~boolean",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~boolean",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~function",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~function",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~null",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~null",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~number",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~number",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~object",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~object",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~string",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~string",
"external"
],
[
"builtinexternal/ecmascriptexternal.js~undefined",
"external/index.html",
"BuiltinExternal/ECMAScriptExternal.js~undefined",
"external"
],
[
"builtinexternal/webapiexternal.js~audiocontext",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~AudioContext",
"external"
],
[
"builtinexternal/webapiexternal.js~canvasrenderingcontext2d",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~CanvasRenderingContext2D",
"external"
],
[
"builtinexternal/webapiexternal.js~documentfragment",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~DocumentFragment",
"external"
],
[
"builtinexternal/webapiexternal.js~element",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Element",
"external"
],
[
"builtinexternal/webapiexternal.js~event",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Event",
"external"
],
[
"builtinexternal/webapiexternal.js~node",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~Node",
"external"
],
[
"builtinexternal/webapiexternal.js~nodelist",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~NodeList",
"external"
],
[
"builtinexternal/webapiexternal.js~xmlhttprequest",
"external/index.html",
"BuiltinExternal/WebAPIExternal.js~XMLHttpRequest",
"external"
],
[
"git/resourcecreator/src/components/widgets/cores/widget000/widget000sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget000/Widget000SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget000/Widget000SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget000typea/widget000typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget000TypeA/Widget000TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget000TypeA/Widget000TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget001/widget001sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget001/Widget001SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget001/Widget001SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget001typea/widget001typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget001TypeA/Widget001TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget001TypeA/Widget001TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget002/widget002sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget002/Widget002SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget003/widget003sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget003/Widget003SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget003/Widget003SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget004/widget004sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget004/Widget004SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget004/Widget004SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget008/widget008sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget008/Widget008SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget008/Widget008SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget009/widget009sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget009/Widget009SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget009/Widget009SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget009typea/widget009typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget009TypeA/Widget009TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget009TypeA/Widget009TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget010/widget010sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget010/Widget010SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget010/Widget010SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget028/widget028sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget028/Widget028SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget028/Widget028SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget030/widget030sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget030/Widget030SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget030/Widget030SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget031/widget031sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget031/Widget031SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget031/Widget031SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget031typea/widget031typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget031TypeA/Widget031TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget031TypeA/Widget031TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget032/widget032sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget032/Widget032SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget032/Widget032SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget032typea/widget032typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget032TypeA/Widget032TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget032TypeA/Widget032TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget033/widget033sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget033/Widget033SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget033/Widget033SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget033typea/widget033typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeA/Widget033TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeA/Widget033TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget033typeb/widget033typebsampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeB/Widget033TypeBSampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget033TypeB/Widget033TypeBSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget034/widget034sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget034/Widget034SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget034/Widget034SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget034typea/widget034typeasampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeA/Widget034TypeASampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeA/Widget034TypeASampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget034typeb/widget034typebsampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeB/Widget034TypeBSampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget034TypeB/Widget034TypeBSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget035/widget035sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget035/Widget035SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget035/Widget035SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget040/widget040sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget040/Widget040SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget040/Widget040SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget041/widget041sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget041/Widget041SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget041/Widget041SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget042/widget042sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget042/Widget042SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget042/Widget042SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/components/widgets/cores/widget043/widget043sampledatas.js",
"file/git/resourcecreator/src/Components/Widgets/Cores/Widget043/Widget043SampleDatas.js.html",
"git/resourcecreator/src/Components/Widgets/Cores/Widget043/Widget043SampleDatas.js",
"file"
],
[
"git/resourcecreator/src/redux/projectsampledatas.js",
"file/git/resourcecreator/src/Redux/projectSampleDatas.js.html",
"git/resourcecreator/src/Redux/projectSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupaddsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupAddSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorygroupeditsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryGroupEditSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategorymovesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryMoveSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagercategoryremovesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerCategoryRemoveSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfilterargmanager/advencedfilterargmanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterArgManager/AdvencedFilterArgManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/advencedfiltermanager/advencedfiltermanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/AdvencedFilterManager/AdvencedFilterManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/categorylistmanager/categorylistmanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/CategoryListManager/CategoryListManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerloginsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLoginSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/loginmanager/loginmanagerlogoutsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/LoginManager/LoginManagerLogoutSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanageraddsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerAddSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerciuploadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerCiUploadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerremovesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerRemoveSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/projectmanager/projectmanagerthumbnailuploadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/ProjectManager/ProjectManagerThumbnailUploadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerclearsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerClearSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/querystatemanager/querystatemanagerupdatesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/QueryStateManager/QueryStateManagerUpdateSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerdeletesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerDeleteSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagernewsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerNewSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerreadsampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerReadSampleDatas.js",
"file"
],
[
"git/resourcecreator/src/utils/commonmanagers/usermanager/usermanagerupdatesampledatas.js",
"file/git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js.html",
"git/resourcecreator/src/Utils/CommonManagers/UserManager/UserManagerUpdateSampleDatas.js",
"file"
],
[
"git/uicontentsmanager/src/components/networkswitcher/networkswitchersampledatas.js",
"file/git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js.html",
"git/uicontentsmanager/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js",
"file"
],
[
"git/userdashboard/src/components/advencedfilterquickviewer/advencedfilterquickviewersampledatas.js",
"file/git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js.html",
"git/userdashboard/src/Components/AdvencedFilterQuickViewer/AdvencedFilterQuickViewerSampleDatas.js",
"file"
],
[
"git/userdashboard/src/components/detailplayer/detailplayersampledatas.js",
"file/git/userdashboard/src/Components/DetailPlayer/DetailPlayerSampleDatas.js.html",
"git/userdashboard/src/Components/DetailPlayer/DetailPlayerSampleDatas.js",
"file"
],
[
"git/userdashboard/src/components/networkswitcher/networkswitchersampledatas.js",
"file/git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js.html",
"git/userdashboard/src/Components/NetworkSwitcher/NetworkSwitcherSampleDatas.js",
"file"
]
] | shoveller/shoveller.github.com | jsonSpec/script/search_index.js | JavaScript | mit | 37,160 |
import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import {
mySyncHistoryWithStore,
default as createStore
} from './store/createStore'
import AppContainer from './containers/AppContainer'
import injectTapEventPlugin from 'react-tap-event-plugin';
// ========================================================
// Browser History Setup
// ========================================================
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
})
// ========================================================
// Store and History Instantiation
// ========================================================
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState, browserHistory)
const history = mySyncHistoryWithStore(browserHistory, store)
// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEBUG__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = (routerKey = null) => {
const routes = require('./routes/index').default(store)
// TODO, uncomment this before production
// injectTapEventPlugin()
ReactDOM.render(
<AppContainer
store={store}
history={history}
routes={routes}
routerKey={routerKey}
/>,
MOUNT_NODE
)
}
// Enable HMR and catch runtime errors in RedBox
// This code is excluded from production bundle
if (__DEV__ && module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp(Math.random())
} catch (error) {
renderError(error)
}
}
module.hot.accept(['./routes/index'], () => render())
}
// ========================================================
// Go!
// ========================================================
render()
| theosherry/mx_pl | src/main.js | JavaScript | mit | 2,563 |
var beep = require('../beep.js');
beep(3); | JayrAlencar/node-beep | test/app.js | JavaScript | mit | 42 |
var github = require('octonode');
var _ = require('lodash');
module.exports = {
name:'action',
description:'A command to show recent activity for all members of your org',
example:'bosco action',
cmd:cmd
}
function cmd(bosco) {
getActivity(bosco);
}
function getActivity(bosco) {
var client = github.client(bosco.config.get('github:authToken'));
client.get('/orgs/tes/members', {}, function (err, status, body) {
if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); }
_.each(body, function(event) {
console.dir(event);
showUser(bosco, event);
});
});
}
function showUser(bosco, user) {
var client = github.client(bosco.config.get('github:authToken'));
client.get('/users/' + user + '/events', {}, function (err, status, body) {
if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); }
_.each(body, function(event) {
var data = [user, event.type, event.repo.name, event.created_at];
console.dir(data.join(', '));
});
});
}
| tomgco/bosco | commands/action.js | JavaScript | mit | 1,100 |
/**
* constants.js
*/
// TODO: update these to better colors
var SHIELD_COLOR = vec4.fromValues(0.0, 0.0, 1.0, 1.0);
var ARMOR_COLOR = vec4.fromValues(0.0, 1.0, 0.0, 1.0);
var HULL_COLOR = vec4.fromValues(1.0, 0.0, 1.0, 1.0);
| bcforres/stararena2 | js/constants.js | JavaScript | mit | 229 |