<commit_before>let symbols = {};

function symbol(id, prefix, infix, power=0) {
    let sym = symbols[id];
    if (!sym) {
        sym = symbols[id] = {
            id: id,
            prefix: prefix || (t => null),
            infix: infix || (l => {
                throw 'missing operator'
            }),
            power: power
        };
    }
    return sym;
}

function node(head, args, x) {
    return [head, {x: x}].concat(args);
}

function literal(ids) {
    return ids.map(i => {
        return symbol(i, t => node(i, [t.value], t.line));
    });
}

function infix(power, ids, right=false) {
    return (Array.isArray(ids) ? ids : [ids]).map(i => {
        return symbol(
            i,
            null,
            (l, t, ts) => {
                let exp = expression(ts, right ? power - 1 : power);
                return node(i, [l, exp], t.line);
            },
            power
        );
    });
}

function infixR(power, ids) {
    return infix(power, ids, true);
}

function getArgs(tokens, end) {
    let token = tokens[0], arg = [], args = [];
    while (token) {
        if ([';', 'newline'].indexOf(token.type) > -1) {
            tokens.shift();
        } else if ([end, ','].indexOf(token.type) > -1) {
            tokens.shift();
            if (arg.length != 0) {
                args.push(arg.length == 1 ? arg[0] : ['do'].concat(arg));
                arg = [];
            }
            if (token.type == end) {
                return args;
            }
        } else {
            arg.push(expression(tokens));
        }
        token = tokens[0];
    }
}

function container(power, start, end, $0, $1, $2) {
    return symbol(
        start,
        (t, ts) => {
            let args = getArgs(ts, end);
            if (args.filter(n => n[0] != ':').length == 0) {
                return $0(t, args);
            }
            return $1(t, args);
        },
        (l, t, ts) => $2(l, t, getArgs(ts, end)),
        power
    );
}

literal(['#', 'boolean', 'name', 'number', 'string']);
symbol('regex', t => node('regex', t.value.split('`').slice(1), t.line));
infix(18, '.');
container(18, '[', ']',
    (t, args) => node('OrderedMap', args, t.line),
    (t, args) => node('List', args. t.line),
    (l, t, args) => node('at', [l].concat(args), t.line)
);
container(18, '{', '}',
    (t, args) => node('HashMap', args, t.line),
    (t, args) => node('function', args, t.line)
);
container(17, '(', ')',
    (t, args) => node('object', args, t.line),
    (t, args) => args.length == 1 ? args[0] : node('Array', args, t.line),
    (l, t, args) => node(l, args, t.line)
);
infix(13, ['+', '-']);
infix(10, ['==', '!=']);
infix(7, '&');
infix(6, '|');
infixR(4, '?');
symbol(' ', null, (l, t, ts) => {
    let exp = expression(ts, 3.5);
    if (exp[0][2] == 'name') {
        return [exp, l];
    }
    exp.splice(2, 0, l);
    return exp;
}, 3.5);
infixR(3, ['=', ':=', '+=', '-=']);
infixR(2, ':');

function expression(tokens, power=0) {
    let token = tokens.shift();
    let sym = symbol(token.type);
    let left = sym.prefix(token, tokens);
    while (tokens[0] && power < symbol(tokens[0].type).power) {
        token = tokens.shift();
        sym = symbol(token.type);
        left = sym.infix(left, token, tokens);
    }
    return left;
}

export default function parse(tokens) {
    let ast = [];
    while (tokens[0]) {
        if ([';', 'newline'].indexOf(tokens[0].type) > -1) {
            tokens.shift();
        } else {
            ast.push(expression(tokens));
        }
    }
    return ast;
}
<commit_msg>fixed Array<commit_after>let symbols = {};

function symbol(id, prefix, infix, power=0) {
    let sym = symbols[id];
    if (!sym) {
        sym = symbols[id] = {
            id: id,
            prefix: prefix || (t => null),
            infix: infix || (l => {
                throw 'missing operator'
            }),
            power: power
        };
    }
    return sym;
}

function node(head, args, x) {
    return [head, {x: x}].concat(args);
}

function literal(ids) {
    return ids.map(i => {
        return symbol(i, t => node(i, [t.value], t.line));
    });
}

function infix(power, ids, right=false) {
    return (Array.isArray(ids) ? ids : [ids]).map(i => {
        return symbol(
            i,
            null,
            (l, t, ts) => {
                let exp = expression(ts, right ? power - 1 : power);
                return node(i, [l, exp], t.line);
            },
            power
        );
    });
}

function infixR(power, ids) {
    return infix(power, ids, true);
}

function getArgs(tokens, end) {
    let token = tokens[0], arg = [], args = [];
    while (token) {
        if ([';', 'newline'].indexOf(token.type) > -1) {
            tokens.shift();
        } else if ([end, ','].indexOf(token.type) > -1) {
            tokens.shift();
            if (arg.length != 0) {
                args.push(arg.length == 1 ? arg[0] : ['do'].concat(arg));
                arg = [];
            }
            if (token.type == end) {
                return args;
            }
        } else {
            arg.push(expression(tokens));
        }
        token = tokens[0];
    }
}

function container(power, start, end, $0, $1, $2) {
    return symbol(
        start,
        (t, ts) => {
            let args = getArgs(ts, end);
            if (args.length > 0 && args.filter(n => n[0] != ':').length == 0) {
                return $0(t, args);
            }
            return $1(t, args);
        },
        (l, t, ts) => $2(l, t, getArgs(ts, end)),
        power
    );
}

literal(['#', 'boolean', 'name', 'number', 'string']);
symbol('regex', t => node('regex', t.value.split('`').slice(1), t.line));
infix(18, '.');
container(18, '[', ']',
    (t, args) => node('OrderedMap', args, t.line),
    (t, args) => node('List', args. t.line),
    (l, t, args) => node('at', [l].concat(args), t.line)
);
container(18, '{', '}',
    (t, args) => node('HashMap', args, t.line),
    (t, args) => node('function', args, t.line)
);
container(17, '(', ')',
    (t, args) => node('object', args, t.line),
    (t, args) => args.length == 1 ? args[0] : node('Array', args, t.line),
    (l, t, args) => node(l, args, t.line)
);
infix(13, ['+', '-']);
infix(10, ['==', '!=']);
infix(7, '&');
infix(6, '|');
infixR(4, '?');
symbol(' ', null, (l, t, ts) => {
    let exp = expression(ts, 3.5);
    if (exp[0][2] == 'name') {
        return [exp, l];
    }
    exp.splice(2, 0, l);
    return exp;
}, 3.5);
infixR(3, ['=', ':=', '+=', '-=']);
infixR(2, ':');

function expression(tokens, power=0) {
    let token = tokens.shift();
    let sym = symbol(token.type);
    let left = sym.prefix(token, tokens);
    while (tokens[0] && power < symbol(tokens[0].type).power) {
        token = tokens.shift();
        sym = symbol(token.type);
        left = sym.infix(left, token, tokens);
    }
    return left;
}

export default function parse(tokens) {
    let ast = [];
    while (tokens[0]) {
        if ([';', 'newline'].indexOf(tokens[0].type) > -1) {
            tokens.shift();
        } else {
            ast.push(expression(tokens));
        }
    }
    return ast;
}
<|endoftext|>


<commit_before>const rewire     = require('rewire');
const proxyquire = require('proxyquire');

switch (process.argv[2]) {
    // The "start" script is run during development mode
    case 'start':
        rewireModule('react-scripts/scripts/start.js', loadCustomizer('../webpack.config.dev.extension'));
        break;

    // The "build" script is run to produce a production bundle
    case 'build':
        rewireModule('react-scripts/scripts/build.js', loadCustomizer('../webpack.config.prod.extension'));
        break;

	// The "test" script runs all the tests with Jest
    case 'test':
        let customizer = loadCustomizer('../webpack.config.testing.extension');
        proxyquire('react-scripts/scripts/test.js', {
            // When test.js asks for '../utils/createJestConfig' it will get this instead:
            '../utils/createJestConfig': (...args) => {
                // Use the existing createJestConfig function to create a config, then pass
                // it through the customizer
                var createJestConfig = require('react-scripts/utils/createJestConfig');
                return customizer(createJestConfig(...args));
            }
        });
        break;

	default:
        console.log('custom-config only supports "start", "build", and "test" options.');
        process.exit(-1);
}

// Attempt to load the given module and return null if it fails.
function loadCustomizer(module) {
    try {
        return require(module);
    } catch (e) {
        if (e.code !== "MODULE_NOT_FOUND") throw e;
    }

    // If the module doesn't exist, return a
    // noop that simply returns the config it's given.
    return config => config;
}

function rewireModule(modulePath, customizer) {
    // Load the module with `rewire`, which allows modifying the
    // script's internal variables.
    //let defaults = rewire(modulePath);

    // Reach into the module, grab its global 'config' variable,
    // pass it through the customizer function, and then set it back.
    // 'config' is Create React App's built-in Webpack config.
    /*let config = defaults.__get__('config');
    config = customizer(Object.assign({}, config));
    defaults.__set__('config', config);*/

    proxyquire.noCallThru()(modulePath, {
        '../config/webpack.config.dev': (() => {
            var defaults = rewire(modulePath);
            var config = defaults.__get__('config');
            //console.log('config:', config);
            return customizer(Object.assign({}, config));
        })()
    });
}
<commit_msg>update custom-config.js<commit_after>const rewire     = require('rewire');
const proxyquire = require('proxyquire');

switch (process.argv[2]) {
    // The "start" script is run during development mode
    case 'start':
        rewireModule('react-scripts/scripts/start.js', loadCustomizer('../webpack.config.dev.extension'));
        break;

    // The "build" script is run to produce a production bundle
    case 'build':
        rewireModule('react-scripts/scripts/build.js', loadCustomizer('../webpack.config.prod.extension'));
        break;

	// The "test" script runs all the tests with Jest
    case 'test':
        let customizer = loadCustomizer('../webpack.config.testing.extension');
        proxyquire('react-scripts/scripts/test.js', {
            // When test.js asks for '../utils/createJestConfig' it will get this instead:
            '../utils/createJestConfig': (...args) => {
                // Use the existing createJestConfig function to create a config, then pass
                // it through the customizer
                var createJestConfig = require('react-scripts/utils/createJestConfig');
                return customizer(createJestConfig(...args));
            }
        });
        break;

	default:
        console.log('custom-config only supports "start", "build", and "test" options.');
        process.exit(-1);
}

// Attempt to load the given module and return null if it fails.
function loadCustomizer(module) {
    try {
        return require(module);
    } catch (e) {
        if (e.code !== "MODULE_NOT_FOUND") throw e;
    }

    // If the module doesn't exist, return a
    // noop that simply returns the config it's given.
    return config => config;
}

function rewireModule(modulePath, customizer) {
    // Load the module with `rewire`, which allows modifying the
    // script's internal variables.
    //let defaults = rewire(modulePath);

    // Reach into the module, grab its global 'config' variable,
    // pass it through the customizer function, and then set it back.
    // 'config' is Create React App's built-in Webpack config.
    /*let config = defaults.__get__('config');
    config = customizer(Object.assign({}, config));
    defaults.__set__('config', config);*/

    const patching = () => {
        var defaults = rewire(modulePath);
        var config = defaults.__get__('config');
        return customizer(Object.assign({}, config));
    };

    proxyquire.noCallThru()(modulePath, {
        '../config/webpack.config.dev':  patching(),
        '../config/webpack.config.prod': patching()
    });
}
<|endoftext|>


<commit_before>ar path = require('path'),
    _ = require('lodash');

module.exports = function(task, args) {
  var name = 'imgix-app',
      ngName = 'imgix.app',
      appBase = '.',

      // Server numbers count up from here, per-environment
      baseServerPort = 9870,

      // Template for banner that goes atop all compiled assets
      banner = '/* ' + name + ' - Built: ' + Date.now() + ' */\n',
      allEnvs = ['dev', 'test', 'prod'],
      env,
      isProd,
      appSrcBase,
      appTestBase,
      appDestBase;

  // Set environment based on task and args passed in
  if (/^test/.test(task)) {
    env = 'test';
  } else if (args.env && _.includes(allEnvs, args.env)) {
    env = args.test;
  } else {
    env = 'dev';
  }

  isProd = (env === 'prod');

  // Base paths for src and dest files
  appSrcBase = path.join(appBase, 'app');
  appDestBase = path.join(appBase, '.' + env + '_srv');
  appTestBase = path.join(appBase, 'test');

  return {
    name: name,
    ngModule: ngName,
    destPath: appDestBase,

    // The components object tells web-tools which gulp tasks to set up and how
    appAssets: {
        js: {
            src: [
                path.join(appSrcBase, 'base', '**', '*.js'),
                path.join(appSrcBase, '**', '*.js'),
                '!' + path.join('**', 'test.*.js'),
                '!' + path.join('**', 'test-data.*.js')
              ],
            dest: path.join(appDestBase, 'scripts'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourcemaps: isProd,
                concatName: name + '.js',
                banner: banner
              }
          },
        templates: {
            src: [
                path.join(appSrcBase, '**', '*.tmpl')
              ],
            dest: path.join(appDestBase, 'scripts'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourcemaps: isProd,
                concatName: name + '.tmpl.js',
                banner: banner,
                ngHtml2JsOptions: {
                    moduleName: ngName
                  }
              }
          },
        css: {
            src: [
                path.join(appSrcBase, 'base', '**', '*.css'),
                path.join(appSrcBase, '**', '*.css')
              ],
            dest: path.join(appDestBase, 'styles'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourcemaps: isProd,
                concatName: name + '.css',
                banner: banner,
                pluginOptions: {
                    'postcss-import': {
                        path: [
                            path.join(appBase, 'base', 'styles')
                          ]
                      }
                  }
              }
          },
        svg: {
            src: [
                path.join(appSrcBase, 'static', 'svg', '**', '*.svg')
              ],
            dest: path.join(appDestBase, 'svg'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                concatName: name + '.svg'
              }
          },
        partials: {
            src: [
                path.join(appSrcBase, 'partials', '*.html')
              ],
            build: true,
            buildOptions: {
                doMinify: false, // No need to ever minify here, since minifying the whole page will take care of it
                processOptions: {
                    environment: env,
                  }
              }
          },
        html: {
            src: [
                path.join(appSrcBase, '*.html')
              ],
            dest: appDestBase,
            build: true,
            buildOptions: {
                doMinify: isProd,
                doInject: true,
                injectOptions: {
                    ignorePath: appDestBase
                  },
                processOptions: {
                    environment: env,
                  }
              },
            appAssetDependencies: [
                'js',
                'templates',
                'css',
                'svg',
                'partials'
              ],
            extAssetDependencies: [
                'js',
                'css',
                'svg',
                'partials'
              ]
          },
        misc: {
            src: [
                path.join(appSrcBase, 'static', 'misc', '**', '*.*')
              ],
            dest: appDestBase
          }
      },

    extAssets: {
        js: {
            build: true,
            buildOptions: {
                doCheck: false,
                doMinify: isProd,
                doConcat: isProd,
                doBanner: false,
                doVersioning: isProd,
                doSourcemaps: isProd,
                concatName: 'libs.js'
              },
            dest: path.join(appDestBase, 'scripts', 'libs')
          },
        css: {
            build: true,
            buildOptions: {
                doCheck: false,
                doMinify: isProd,
                doConcat: isProd,
                doBanner: false,
                doVersioning: isProd,
                doSourcemaps: isProd,
                concatName: 'libs.css'
              },
            dest: path.join(appDestBase, 'styles', 'libs')
          },
        svg: {},
        partials: {
            filter: path.join('**', '*.html')
          },
        fonts: {
            filter: [
                '*.woff2',
                '*.woff',
                '*.ttf'
              ],
            dest: path.join(appDestBase, 'fonts')
          }
      },

    bower: {
        json: path.join(appBase, 'bower.json'),
        components: path.join(appBase, 'bower_components')
      },

    server: {
        port: baseServerPort + allEnvs.indexOf(env),
        hostname: 'localhost',
        root: appDestBase,
        ssl: true,
        key: path.join(appBase, 'dev_certs', 'key.pem'),
        cert: path.join(appBase, 'dev_certs', 'cert.pem')
      },

    unitTests: {
        src: [
            path.join(appSrcBase, '**', 'test.*.js')
          ],
        karmaOptions: {
            browsers: ['Chrome', 'Firefox', 'Safari'],
            ngHtml2JsPreprocessor: {
                moduleName: ngName
              }
          }
      },

    integrationTests: {
        src: [
            path.join(appTestBase, '**', 'spec.*.js')
          ],
        browser: 'Firefox',
        eyeballOptions: {
            screenshotRoot: appTestBase,
            widths: [320, 480, 640, 768, 1024]
          }
      },

    deployment: {
        jumpServer: 'server.ex.imgix.com',
        loko: {
            package: 'imgix-app-deploy'
          },
        ansible: {
            configFile: 'this_app.yml'
          },
        repository: {
            url: 'git@github.com:zebrafishlabs/imgix-app',
            branch: 'master'
          }
      }
  };
}
<commit_msg>Fix a typo in example config file<commit_after>ar path = require('path'),
    _ = require('lodash');

module.exports = function(task, args) {
  var name = 'imgix-app',
      ngName = 'imgix.app',
      appBase = '.',

      // Server numbers count up from here, per-environment
      baseServerPort = 9870,

      // Template for banner that goes atop all compiled assets
      banner = '/* ' + name + ' - Built: ' + Date.now() + ' */\n',
      allEnvs = ['dev', 'test', 'prod'],
      env,
      isProd,
      appSrcBase,
      appTestBase,
      appDestBase;

  // Set environment based on task and args passed in
  if (/^test/.test(task)) {
    env = 'test';
  } else if (args.env && _.includes(allEnvs, args.env)) {
    env = args.test;
  } else {
    env = 'dev';
  }

  isProd = (env === 'prod');

  // Base paths for src and dest files
  appSrcBase = path.join(appBase, 'app');
  appDestBase = path.join(appBase, '.' + env + '_srv');
  appTestBase = path.join(appBase, 'test');

  return {
    name: name,
    ngModule: ngName,
    destPath: appDestBase,

    // The components object tells web-tools which gulp tasks to set up and how
    appAssets: {
        js: {
            src: [
                path.join(appSrcBase, 'base', '**', '*.js'),
                path.join(appSrcBase, '**', '*.js'),
                '!' + path.join('**', 'test.*.js'),
                '!' + path.join('**', 'test-data.*.js')
              ],
            dest: path.join(appDestBase, 'scripts'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourceMaps: isProd,
                concatName: name + '.js',
                banner: banner
              }
          },
        templates: {
            src: [
                path.join(appSrcBase, '**', '*.tmpl')
              ],
            dest: path.join(appDestBase, 'scripts'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourceMaps: isProd,
                concatName: name + '.tmpl.js',
                banner: banner,
                ngHtml2JsOptions: {
                    moduleName: ngName
                  }
              }
          },
        css: {
            src: [
                path.join(appSrcBase, 'base', '**', '*.css'),
                path.join(appSrcBase, '**', '*.css')
              ],
            dest: path.join(appDestBase, 'styles'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                doConcat: isProd,
                doBanner: isProd,
                doVersioning: isProd,
                doSourceMaps: isProd,
                concatName: name + '.css',
                banner: banner,
                pluginOptions: {
                    'postcss-import': {
                        path: [
                            path.join(appBase, 'base', 'styles')
                          ]
                      }
                  }
              }
          },
        svg: {
            src: [
                path.join(appSrcBase, 'static', 'svg', '**', '*.svg')
              ],
            dest: path.join(appDestBase, 'svg'),
            build: true,
            buildOptions: {
                doMinify: isProd,
                concatName: name + '.svg'
              }
          },
        partials: {
            src: [
                path.join(appSrcBase, 'partials', '*.html')
              ],
            build: true,
            buildOptions: {
                doMinify: false, // No need to ever minify here, since minifying the whole page will take care of it
                processOptions: {
                    environment: env,
                  }
              }
          },
        html: {
            src: [
                path.join(appSrcBase, '*.html')
              ],
            dest: appDestBase,
            build: true,
            buildOptions: {
                doMinify: isProd,
                doInject: true,
                injectOptions: {
                    ignorePath: appDestBase
                  },
                processOptions: {
                    environment: env,
                  }
              },
            appAssetDependencies: [
                'js',
                'templates',
                'css',
                'svg',
                'partials'
              ],
            extAssetDependencies: [
                'js',
                'css',
                'svg',
                'partials'
              ]
          },
        misc: {
            src: [
                path.join(appSrcBase, 'static', 'misc', '**', '*.*')
              ],
            dest: appDestBase
          }
      },

    extAssets: {
        js: {
            build: true,
            buildOptions: {
                doCheck: false,
                doMinify: isProd,
                doConcat: isProd,
                doBanner: false,
                doVersioning: isProd,
                doSourceMaps: isProd,
                concatName: 'libs.js'
              },
            dest: path.join(appDestBase, 'scripts', 'libs')
          },
        css: {
            build: true,
            buildOptions: {
                doCheck: false,
                doMinify: isProd,
                doConcat: isProd,
                doBanner: false,
                doVersioning: isProd,
                doSourceMaps: isProd,
                concatName: 'libs.css'
              },
            dest: path.join(appDestBase, 'styles', 'libs')
          },
        svg: {},
        partials: {
            filter: path.join('**', '*.html')
          },
        fonts: {
            filter: [
                '*.woff2',
                '*.woff',
                '*.ttf'
              ],
            dest: path.join(appDestBase, 'fonts')
          }
      },

    bower: {
        json: path.join(appBase, 'bower.json'),
        components: path.join(appBase, 'bower_components')
      },

    server: {
        port: baseServerPort + allEnvs.indexOf(env),
        hostname: 'localhost',
        root: appDestBase,
        ssl: true,
        key: path.join(appBase, 'dev_certs', 'key.pem'),
        cert: path.join(appBase, 'dev_certs', 'cert.pem')
      },

    unitTests: {
        src: [
            path.join(appSrcBase, '**', 'test.*.js')
          ],
        karmaOptions: {
            browsers: ['Chrome', 'Firefox', 'Safari'],
            ngHtml2JsPreprocessor: {
                moduleName: ngName
              }
          }
      },

    integrationTests: {
        src: [
            path.join(appTestBase, '**', 'spec.*.js')
          ],
        browser: 'Firefox',
        eyeballOptions: {
            screenshotRoot: appTestBase,
            widths: [320, 480, 640, 768, 1024]
          }
      },

    deployment: {
        jumpServer: 'server.ex.imgix.com',
        loko: {
            package: 'imgix-app-deploy'
          },
        ansible: {
            configFile: 'this_app.yml'
          },
        repository: {
            url: 'git@github.com:zebrafishlabs/imgix-app',
            branch: 'master'
          }
      }
  };
}
<|endoftext|>


<commit_before>/**
 *
 * @licstart  The following is the entire license notice for the JavaScript code in this file.
 *
 * Melinda related modules for recordLoader
 *
 * Copyright (c) 2015-2016 University Of Helsinki (The National Library Of Finland)
 *
 * This file is part of record-loader-melinda
 *
 * record-loader-melinda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this file.
 *
 **/

/* istanbul ignore next: umd wrapper */
(function (root, factory) {

    'use strict';

    if (typeof define === 'function' && define.amd) {
        define([
	    'es6-polyfills/lib/promise',
	    'loglevel',
	    'jjv',
	    'jjve',
	    'marc-record-js',
	    'record-loader-json/lib/processors/match/json-similarity',
	    'json-similarity/resources/spec-schema'
	], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(
	    require('es6-polyfills/lib/promise'),
	    require('loglevel'),
	    require('jjv'),
	    require('jjve'),
	    require('marc-record-js'),
	    require('record-loader-json/lib/processors/match/json-similarity'),
	    require('json-similarity/resources/spec-schema')
	);
    }

}(this, factory));

function factory(Promise, log, jjv, jjve, MarcRecord, protoFactory, schema)
{

    'use strict';

    return function(parameters)
    {

	var record_store, logger, converter, proto, fn_run_proto, fn_set_converter_proto, fn_set_logger_proto;

	proto = protoFactory(parameters);
	fn_run_proto = proto.run;
	fn_set_converter_proto = proto.setConverter;
	fn_set_logger_proto = proto.setLogger;

	proto.setConverter = function(converter_arg)
	{
	    converter = converter_arg;
	    fn_set_converter_proto({
		convert: function(record)
		{
		    return record.record.toJsonObject();
		}
	    });
	};

	proto.setLogger = function(logger_arg)
	{
	    logger = logger_arg;
	    fn_set_logger_proto(logger);
	};

	proto.setRecordStore = function(record_store_arg)
	{
	    record_store = record_store_arg;
	};

	proto.findMatchCandidates = function(record)
	{
	    return record_store.read(record.recordStoreHost, 1).then(function(found_records) {
		return found_records.map(function(found_record) {
		    return found_record.toJsonObject();
		});
	    });
	};

	proto.run = function(record)
	{

	    logger.debug('Finding matches for input record ' + record.record.get(/^001$/)[0].value);

	    return fn_run_proto(record).then(function(results) {
		return results.map(function(value, index) {
		    if (index === 0) {
			return {
			    record: value,
			    recordStoreHost: record.recordStoreHost
			};
		    } else {
			return value.map(function(obj) {
			    return new MarcRecord(obj);
			});
		    }
		});
	    });

	};

	return proto;

    };

}

<commit_msg>Map additional results without modifications<commit_after>/**
 *
 * @licstart  The following is the entire license notice for the JavaScript code in this file.
 *
 * Melinda related modules for recordLoader
 *
 * Copyright (c) 2015-2016 University Of Helsinki (The National Library Of Finland)
 *
 * This file is part of record-loader-melinda
 *
 * record-loader-melinda is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this file.
 *
 **/

/* istanbul ignore next: umd wrapper */
(function (root, factory) {

    'use strict';

    if (typeof define === 'function' && define.amd) {
        define([
	    'es6-polyfills/lib/promise',
	    'loglevel',
	    'jjv',
	    'jjve',
	    'marc-record-js',
	    'record-loader-json/lib/processors/match/json-similarity',
	    'json-similarity/resources/spec-schema'
	], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(
	    require('es6-polyfills/lib/promise'),
	    require('loglevel'),
	    require('jjv'),
	    require('jjve'),
	    require('marc-record-js'),
	    require('record-loader-json/lib/processors/match/json-similarity'),
	    require('json-similarity/resources/spec-schema')
	);
    }

}(this, factory));

function factory(Promise, log, jjv, jjve, MarcRecord, protoFactory, schema)
{

    'use strict';

    return function(parameters)
    {

	var record_store, logger, converter, proto, fn_run_proto, fn_set_converter_proto, fn_set_logger_proto;

	proto = protoFactory(parameters);
	fn_run_proto = proto.run;
	fn_set_converter_proto = proto.setConverter;
	fn_set_logger_proto = proto.setLogger;

	proto.setConverter = function(converter_arg)
	{
	    converter = converter_arg;
	    fn_set_converter_proto({
		convert: function(record)
		{
		    return record.record.toJsonObject();
		}
	    });
	};

	proto.setLogger = function(logger_arg)
	{
	    logger = logger_arg;
	    fn_set_logger_proto(logger);
	};

	proto.setRecordStore = function(record_store_arg)
	{
	    record_store = record_store_arg;
	};

	proto.findMatchCandidates = function(record)
	{
	    return record_store.read(record.recordStoreHost, 1).then(function(found_records) {
		return found_records.map(function(found_record) {
		    return found_record.toJsonObject();
		});
	    });
	};

	proto.run = function(record)
	{

	    logger.debug('Finding matches for input record ' + record.record.get(/^001$/)[0].value);

	    return fn_run_proto(record).then(function(results) {
		return results.map(function(value, index) {
		    switch (index) {
		    case 0:
			return {
			    record: value,
			    recordStoreHost: record.recordStoreHost
			};
		    case 1:
			return value.map(function(obj) {
			    return new MarcRecord(obj);
			});
		    default:
			return value;
		    }
		});
	    });

	};

	return proto;

    };

}

<|endoftext|>


<commit_before>/*global angular:true */
angular.module('allure.controllers', [])
    .controller('GraphCtrl', function($scope, testcases, status) {
        "use strict";
        $scope.testcases = testcases.testCases;
        $scope.statistic = {
            passed: 0, canceled: 0, failed: 0, broken: 0, pending: 0,
            total: $scope.testcases.length
        };
        $scope.testcases.forEach(function(testcase) {
            $scope.statistic[testcase.status.toLowerCase()]++;
        });
        $scope.testsPassed = ($scope.statistic.failed + $scope.statistic.broken) === 0;
        $scope.chartData = status.all.map(function(statusName) {
            var value = $scope.statistic[statusName.toLowerCase()];
            return {
                name: statusName.toLowerCase(),
                value: value,
                part: value/$scope.statistic.total
            };
        }, this);
    })

    .controller('TimelineCtrl', function($scope, $state, data) {
        "use strict";
        $scope.isState = function(statename) {
            return $state.is(statename);
        };
        $scope.openTestcase = function(testcase) {
            $state.go('timeline.testcase', {testcaseUid: testcase.uid});
        };
        $scope.hosts = data.hosts;
        $scope.allCases = $scope.hosts.reduce(function(result, host) {
            return host.threads.reduce(function(result, thread) {
                return result.concat(thread.testCases);
            }, result);
        }, []);
        $scope.startTime = $scope.allCases.reduce(function(min, testcase) {
            return Math.min(min, testcase.time.start);
        }, Number.POSITIVE_INFINITY);
        $scope.allCases.forEach(function(testcase) {
            testcase.time.start -= $scope.startTime;
            testcase.time.stop -= $scope.startTime;
        });
        $scope.timeRange = [0, $scope.allCases.reduce(function(max, testcase) {
            return Math.max(max, testcase.time.stop)
        }, Number.NEGATIVE_INFINITY)]
    })

    .controller('NavbarCtrl', function($scope, $window, $http, $storage, $translate) {
        'use strict';
        function browserLanguage() {
            return $window.navigator.language && $window.navigator.language.split('-').shift()
        }
        var locale = $storage('locale');
        $scope.setLang = function(langKey) {
            $scope.selectedLang = langKey.locale;
            $translate.use($scope.selectedLang);
            locale.setItem('lang', $scope.selectedLang)
        };

        $scope.langs = [{
            name: "ENG" ,
            locale: "en"
        }, {
            name: "РУС",
            locale: "ru"
        }];
        $scope.selectedLang = locale.getItem('lang') || browserLanguage() || 'en';
        $translate.use($scope.selectedLang);

        $http.get('data/report.json').then(function(response) {
            $scope.report = response.data;
        });
    })

    .controller('TabsController', function($scope, $state, $storage) {
        'use strict';
        var settings = $storage('settings');

        $scope.isCollapsed = function() {
            return settings.getItem('collapsed');
        };

        $scope.toggleCollapsed = function() {
            settings.setItem('collapsed', !$scope.isCollapsed());
        };

        if($scope.isCollapsed() == undefined) {
            $scope.toggleCollapsed();
        }

        $scope.isCurrent = function(state) {
            return $state.includes(state);
        };
    });
<commit_msg>fix - uncollapsed icons by default<commit_after>/*global angular:true */
angular.module('allure.controllers', [])
    .controller('GraphCtrl', function($scope, testcases, status) {
        "use strict";
        $scope.testcases = testcases.testCases;
        $scope.statistic = {
            passed: 0, canceled: 0, failed: 0, broken: 0, pending: 0,
            total: $scope.testcases.length
        };
        $scope.testcases.forEach(function(testcase) {
            $scope.statistic[testcase.status.toLowerCase()]++;
        });
        $scope.testsPassed = ($scope.statistic.failed + $scope.statistic.broken) === 0;
        $scope.chartData = status.all.map(function(statusName) {
            var value = $scope.statistic[statusName.toLowerCase()];
            return {
                name: statusName.toLowerCase(),
                value: value,
                part: value/$scope.statistic.total
            };
        }, this);
    })

    .controller('TimelineCtrl', function($scope, $state, data) {
        "use strict";
        $scope.isState = function(statename) {
            return $state.is(statename);
        };
        $scope.openTestcase = function(testcase) {
            $state.go('timeline.testcase', {testcaseUid: testcase.uid});
        };
        $scope.hosts = data.hosts;
        $scope.allCases = $scope.hosts.reduce(function(result, host) {
            return host.threads.reduce(function(result, thread) {
                return result.concat(thread.testCases);
            }, result);
        }, []);
        $scope.startTime = $scope.allCases.reduce(function(min, testcase) {
            return Math.min(min, testcase.time.start);
        }, Number.POSITIVE_INFINITY);
        $scope.allCases.forEach(function(testcase) {
            testcase.time.start -= $scope.startTime;
            testcase.time.stop -= $scope.startTime;
        });
        $scope.timeRange = [0, $scope.allCases.reduce(function(max, testcase) {
            return Math.max(max, testcase.time.stop)
        }, Number.NEGATIVE_INFINITY)]
    })

    .controller('NavbarCtrl', function($scope, $window, $http, $storage, $translate) {
        'use strict';
        function browserLanguage() {
            return $window.navigator.language && $window.navigator.language.split('-').shift()
        }
        var locale = $storage('locale');
        $scope.setLang = function(langKey) {
            $scope.selectedLang = langKey.locale;
            $translate.use($scope.selectedLang);
            locale.setItem('lang', $scope.selectedLang)
        };

        $scope.langs = [{
            name: "ENG" ,
            locale: "en"
        }, {
            name: "РУС",
            locale: "ru"
        }];
        $scope.selectedLang = locale.getItem('lang') || browserLanguage() || 'en';
        $translate.use($scope.selectedLang);

        $http.get('data/report.json').then(function(response) {
            $scope.report = response.data;
        });
    })

    .controller('TabsController', function($scope, $state, $storage) {
        'use strict';
        var settings = $storage('settings');

        $scope.isCollapsed = function() {
            return settings.getItem('collapsed');
        };

        $scope.toggleCollapsed = function() {
            settings.setItem('collapsed', !$scope.isCollapsed());
        };

        $scope.isCurrent = function(state) {
            return $state.includes(state);
        };
    });
<|endoftext|>


<commit_before>import React from 'react';

const About = () =>

    Hey! Thanks for using this example. If you like it, consider starring the repo :))

;

export default About;
<commit_msg>chore(about): Description about app - Write concise description of the application - Delivers #147402837<commit_after>import React from 'react';

const About = () =>

    DocManager is an electronic document management system that helps you manage your
    documents for easy sharing and accessing.
    It offers features such as creating, editing, restricting and sharing your personal documents.

;

export default About;
<|endoftext|>


<commit_before>var REGEX_NUMBER = /^(\-?[0-9]+|0[xX][0-9A-Fa-f]+)$/;
var REGEX_NUMBER_RANGE = /^([0-9]+|0[xX][0-9A-Fa-f]+)[ ]*\-[ ]*([0-9]+|0[xX][0-9A-Fa-f]+)$/;

const MIN = 0;
const MAX = 16777216;
const PARTITION_SIZE = 128;
const FILE_SIZE = 2048;
const FOLDER_DEPTH = 3;
const PARTITION_PADDING = 8;
const BASE_PATH = "http://127.0.0.1/output/"

var repDict = {};
var reqLock = false;
var reqQueue = [];

function leftpad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }
function rightpad(str,l,c) {return str+Array(l-str.toString().length+1).join(c||" ")}

function getFilePath(number) {
  var n = Math.floor(number / FILE_SIZE) * FILE_SIZE;

  var path = "out_" + leftpad(n, PARTITION_PADDING) + ".tsv";

  var mod = FILE_SIZE;
  for(var i = 0; i < FOLDER_DEPTH; i++) {
      mod *= PARTITION_SIZE;
      n = Math.floor(n / mod) * mod;
      path = n + "/" + path;
  }

  return BASE_PATH + path;
}

function parseData(data) {
    data.split('\n').forEach(function(line) {
        var split = line.split('\t');
        if (split.length != 2) return;

        repDict[parseInt(split[0], 16)] = split[1];
    }, this);
}

function work(command, term) {
    if (command.trim() == '') {
        term.echo("");
    } else if (command === 'help') {
        runHelp(term);
    } else if (command === 'clear') {
        term.clear();
    } else if (command === 'download') {
        window.open('https://www.mikescher.com/programs/view/BefunUtils', '_self');
    } else if (command === 'source') {
        window.open('https://github.com/Mikescher/BefunRep', '_self');
    } else if (command.match(REGEX_NUMBER)) {
       runRep(term, parseInt(command), false)
    } else if (command.match(REGEX_NUMBER_RANGE)) {
       runRepRange(term, parseInt(command.split('-')[0].trim()), parseInt(command.split('-')[1].trim()))
    } else {
       term.error('Command "' + command + '" not recognized. Try entering "help"');
    }
}

function runHelp(term) {
  term.echo(" ");
  term.echo("   ==========");
  term.echo("    BefunRep");
  term.echo("   ==========");
  term.echo(" ");
  term.echo("A common problem in befunge is writing literals for large numbers (with the least amount of code).");
  term.echo("BefunRep is a program by me (https://www.mikescher.de) that calculates representations for a big range of numbers.");
  term.echo("These calculations can take a while and are then saved in a binary file (called 'safe').");
  term.echo("For convenience I calculated the numbers from " + MIN + " to " + MAX + " and commited them to github (https://github.com/Mikescher/Befunge_Number_Representations).");
  term.echo("This is nothing more than a simple interface to get them.");
  term.echo("For bigger projects its probably advicable to download the files or better yet create a own safe with the newest BefunRep version (type the command 'source')");
  term.echo(" ");
  term.echo("BefunRep is part of the BefunUtils tool package for Befunge-93 development by me (Mikescher)");
  term.echo(" ");
  term.echo("Special thanks to:");
  term.echo("  - 'jcubic' for his jQuery terminal plugin");
  term.echo("  - 'github' for hosting all my crap");
}

function runRepRange(term, start, end) {
    if (end - start < 0 || end-start > 128) {
        term.error("You can maximally request 128 items at once");
        return;
    }

    if (start < MIN || end > MAX) {
        term.error("The numbers are not in the range of the precalculated safe ("+MIN+" - " + MAX + ")");
        term.error("You can download BefunRep and generate you own (bigger) safe");
        term.error("Enter 'download' to download the binary or 'source' to view the repository with the up-to-date code");
        return;
    }

    for (var i = start; i <= end; i++) {
        runRep(term, i, true);
    }
}

function runRep(term, number, ext) {

    if (number in repDict) {
        if (ext) term.echo(rightpad(number, 10, " ") + " => " + repDict[number]); else term.echo(repDict[number]);

        var next = reqQueue.shift();
        if (next !== undefined) next();

        return;
    }

    if (number < MIN || number > MAX) {
        term.error("The number is not in the range of the precalculated safe ("+MIN+" - " + MAX + ")");
        term.error("You can download BefunRep and generate you own (bigger) safe");
        term.error("Enter 'download' to download the binary or 'source' to view the repository with the up-to-date code");

        var next = reqQueue.shift();
        if (next !== undefined) next();

        return;
    }

    var fp = getFilePath(number);

    if (reqLock) {
        reqQueue.push(function() {runRep(term, number, ext)});
        return;
    }

    reqLock = true;
    jQuery.get(fp, undefined, function(data)
    {
        parseData(data);
        if (ext) term.echo(rightpad(number, 10, " ") + " => " + repDict[number]); else term.echo(repDict[number]);
    },
    "text").fail(function(jqXHR, textStatus)
    {
        term.error("Could not get data from " + fp);
        term.error(textStatus);
    })
    .always(function()
    {
        reqLock = false;
        var next = reqQueue.shift();
        if (next !== undefined) next();
    });
}

var config = {
    greetings: 'This is the online interface for BefunRep'+'\n'+
               'Enter a number to see a (nearly) optimal befunge-93 representation'+'\n'+
               'All values are loaded from this repository: https://github.com/Mikescher/Befunge_Number_Representations'+'\n'+
               'Enter "help" for more information',
    name: 'befunrep_online',
    prompt: 'bef93> '
}

function init($, undefined) {
    $('#befterminal').terminal(work, config);
}

jQuery(init);<commit_msg>[BefunRepTerminal] fix BASE_PATH<commit_after>var REGEX_NUMBER = /^(\-?[0-9]+|0[xX][0-9A-Fa-f]+)$/;
var REGEX_NUMBER_RANGE = /^([0-9]+|0[xX][0-9A-Fa-f]+)[ ]*\-[ ]*([0-9]+|0[xX][0-9A-Fa-f]+)$/;

const MIN = 0;
const MAX = 16777216;
const PARTITION_SIZE = 128;
const FILE_SIZE = 2048;
const FOLDER_DEPTH = 3;
const PARTITION_PADDING = 8;
//const BASE_PATH = "http://cors.io/?u=https://github.com/Mikescher/Befunge_Number_Representations/blob/master/output/"
const BASE_PATH = "https://github.com/Mikescher/Befunge_Number_Representations/blob/master/output/"

var repDict = {};
var reqLock = false;
var reqQueue = [];

function leftpad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }
function rightpad(str,l,c) {return str+Array(l-str.toString().length+1).join(c||" ")}

function getFilePath(number) {
  var n = Math.floor(number / FILE_SIZE) * FILE_SIZE;

  var path = "out_" + leftpad(n, PARTITION_PADDING) + ".tsv";

  var mod = FILE_SIZE;
  for(var i = 0; i < FOLDER_DEPTH; i++) {
      mod *= PARTITION_SIZE;
      n = Math.floor(n / mod) * mod;
      path = n + "/" + path;
  }

  return BASE_PATH + path;
}

function parseData(data) {
    data.split('\n').forEach(function(line) {
        var split = line.split('\t');
        if (split.length != 2) return;

        repDict[parseInt(split[0], 16)] = split[1];
    }, this);
}

function work(command, term) {
    if (command.trim() == '') {
        term.echo("");
    } else if (command === 'help') {
        runHelp(term);
    } else if (command === 'clear') {
        term.clear();
    } else if (command === 'download') {
        window.open('https://www.mikescher.com/programs/view/BefunUtils', '_self');
    } else if (command === 'source') {
        window.open('https://github.com/Mikescher/BefunRep', '_self');
    } else if (command.match(REGEX_NUMBER)) {
       runRep(term, parseInt(command), false)
    } else if (command.match(REGEX_NUMBER_RANGE)) {
       runRepRange(term, parseInt(command.split('-')[0].trim()), parseInt(command.split('-')[1].trim()))
    } else {
       term.error('Command "' + command + '" not recognized. Try entering "help"');
    }
}

function runHelp(term) {
  term.echo(" ");
  term.echo("   ==========");
  term.echo("    BefunRep");
  term.echo("   ==========");
  term.echo(" ");
  term.echo("A common problem in befunge is writing literals for large numbers (with the least amount of code).");
  term.echo("BefunRep is a program by me (https://www.mikescher.de) that calculates representations for a big range of numbers.");
  term.echo("These calculations can take a while and are then saved in a binary file (called 'safe').");
  term.echo("For convenience I calculated the numbers from " + MIN + " to " + MAX + " and commited them to github (https://github.com/Mikescher/Befunge_Number_Representations).");
  term.echo("This is nothing more than a simple interface to get them.");
  term.echo("For bigger projects its probably advicable to download the files or better yet create a own safe with the newest BefunRep version (type the command 'source')");
  term.echo(" ");
  term.echo("BefunRep is part of the BefunUtils tool package for Befunge-93 development by me (Mikescher)");
  term.echo(" ");
  term.echo("Special thanks to:");
  term.echo("  - 'jcubic' for his jQuery terminal plugin");
  term.echo("  - 'github' for hosting all my crap");
}

function runRepRange(term, start, end) {
    if (end - start < 0 || end-start > 128) {
        term.error("You can maximally request 128 items at once");
        return;
    }

    if (start < MIN || end > MAX) {
        term.error("The numbers are not in the range of the precalculated safe ("+MIN+" - " + MAX + ")");
        term.error("You can download BefunRep and generate you own (bigger) safe");
        term.error("Enter 'download' to download the binary or 'source' to view the repository with the up-to-date code");
        return;
    }

    for (var i = start; i <= end; i++) {
        runRep(term, i, true);
    }
}

function runRep(term, number, ext) {

    if (number in repDict) {
        if (ext) term.echo(rightpad(number, 10, " ") + " => " + repDict[number]); else term.echo(repDict[number]);

        var next = reqQueue.shift();
        if (next !== undefined) next();

        return;
    }

    if (number < MIN || number > MAX) {
        term.error("The number is not in the range of the precalculated safe ("+MIN+" - " + MAX + ")");
        term.error("You can download BefunRep and generate you own (bigger) safe");
        term.error("Enter 'download' to download the binary or 'source' to view the repository with the up-to-date code");

        var next = reqQueue.shift();
        if (next !== undefined) next();

        return;
    }

    var fp = getFilePath(number);

    if (reqLock) {
        reqQueue.push(function() {runRep(term, number, ext)});
        return;
    }

    reqLock = true;
    jQuery.get(fp, undefined, function(data)
    {
        parseData(data);
        if (ext) term.echo(rightpad(number, 10, " ") + " => " + repDict[number]); else term.echo(repDict[number]);
    },
    "text").fail(function(jqXHR, textStatus)
    {
        term.error("Could not get data from " + fp);
        term.error(textStatus);
    })
    .always(function()
    {
        reqLock = false;
        var next = reqQueue.shift();
        if (next !== undefined) next();
    });
}

var config = {
    greetings: 'This is the online interface for BefunRep'+'\n'+
               'Enter a number to see a (nearly) optimal befunge-93 representation'+'\n'+
               'All values are loaded from this repository: https://github.com/Mikescher/Befunge_Number_Representations'+'\n'+
               'Enter "help" for more information',
    name: 'befunrep_online',
    prompt: 'bef93> '
}

function init($, undefined) {
    $('#befterminal').terminal(work, config);
}

jQuery(init);<|endoftext|>


<commit_before>// Llamados al endpoint de carga de datos iniciales+
function CargarDatos() {
    $.ajax({
        method: "GET",
        url: "/parametros/abreviaturas/ajax"
    })
        .done(function (data) {
            var iterador = data;
            delete iterador.metaData;
            var trHTML = '';
            $.each(iterador, function (i, abreviData) {
                for (i = 0; i < data.rows.length; i++) {
                    trHTML += '
' +
                        '' + data.rows[i][0] + '	' +
                        '' + data.rows[i][1] + '	' +
                        '' +

                        '
' +
                        '' +
                        ' Editar ' +
                        '' +
                        ' Eliminar ' +
                        '
' +
                        '
' +
                        '	' +
                        '
';
                }
            });

            $('#resultados').empty().append(trHTML);

            if (App.isAngularJsApp() === false) {
                TableDatatablesManaged.init();
            }
        });
}

function GuardarModal() {
    swal({
            title:"Abreviatura Actualizada",
            message: "",
            type:"success",
            confirmButtonClass: "btn-warning",
            confirmButtonText: "Cancelar",
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonClass: "btn-success",
            cancelButtonText: "OK"
        },
        function(isConfirm){
            if (isConfirm) {
                window.location.href = "/parametros/abreviaturas/edit";
            }else{
                window.location.href = "/parametros/abreviaturas";
            }
        });
}

function CancelarModal() {
    swal({
            title:"Sin Modificaciones",
            message: "",
            type:"warning",
            confirmButtonClass: "btn-success",
            confirmButtonText: "OK",
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonClass: "btn-warning",
            cancelButtonText: "Cerrar"
        },
        function(isConfirm){
            if (isConfirm) {
                window.location.href = "/parametros/abreviaturas";
            }
        });
}

function CargarDatos() {
    $.ajax({
        method: "GET",
        url: "/parametros/abreviaturas/ajax"
    })
        .done(function (data) {
            var iterador = data;
            delete iterador.metaData;
            var trHTML = '';
            $.each(iterador, function (i, abreviData) {
                for (i = 0; i < data.rows.length; i++) {
                    trHTML += '
' +
                        '' + data.rows[i][0] + '	' +
                        '' + data.rows[i][1] + '	' +
                        '' +

                        '
' +
                        '' +
                        ' Editar ' +
                        '' +
                        ' Eliminar ' +
                        '
' +
                        '
' +
                        '	' +
                        '
';
                }
            });

            $('#resultados').empty().append(trHTML);

            if (App.isAngularJsApp() === false) {
                TableDatatablesManaged.init();
            }
        });
}

<commit_msg>new methods<commit_after>// Llamados al endpoint de carga de datos iniciales+
function CargarDatos() {
    $.ajax({
        method: "GET",
        url: "/parametros/abreviaturas/ajax"
    })
        .done(function (data) {
            var iterador = data;
            delete iterador.metaData;
            var trHTML = '';
            $.each(iterador, function (i, abreviData) {
                for (i = 0; i < data.rows.length; i++) {
                    trHTML += '
' +
                        '' + data.rows[i][0] + '	' +
                        '' + data.rows[i][1] + '	' +
                        '' +

                        '
' +
                        '' +
                        ' Editar ' +
                        '' +
                        ' Eliminar ' +
                        '
' +
                        '
' +
                        '	' +
                        '
';
                }
            });

            $('#resultados').empty().append(trHTML);

            if (App.isAngularJsApp() === false) {
                TableDatatablesManaged.init();
            }
        });
}

function NuevoModal() {
    swal({
            title:"Crear una nueva abreviatura",
            message: "",
            type:"success",
            confirmButtonClass: "btn-success",
            confirmButtonText: "Crear",
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonClass: "btn-warning",
            cancelButtonText: "Cancelar"
        },
        function(isConfirm){
            if (isConfirm) {
                CrearDatos();
            }else{
                window.location.href = "/parametros/abreviaturas";
            }
        });
}

function GuardarModal() {
    swal({
            title:"Abreviatura Actualizada",
            message: "",
            type:"success",
            confirmButtonClass: "btn-success",
            confirmButtonText: "Actualizar",
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonClass: "btn-warning",
            cancelButtonText: "Cancelar"
        },
        function(isConfirm){
            if (isConfirm) {
                ActualizarDatos();
            }else{
                window.location.href = "/parametros/abreviaturas";
            }
        });
}

function CancelarModal() {
    swal({
            title:"Sin Modificaciones",
            message: "",
            type:"warning",
            confirmButtonClass: "btn-success",
            confirmButtonText: "OK",
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonClass: "btn-warning",
            cancelButtonText: "Cerrar"
        },
        function(isConfirm){
            if (isConfirm) {
                window.location.href = "/parametros/abreviaturas";
            }
        });
}

function CrearDatos() {
    var id = $.trim($("#idabre").val());
    var value = $.trim($("#abre").val());
    $.ajax({
        method: "POST",
        url: "/parametros/abreviaturas/crear/ajax",
        data : {"idabreviatura" : id, "abreviatura" : value}
    })
        .done(function (data) {
            swal({
                    title:"Abreviatura creada correctemente!",
                    type:"success",
                    confirmButtonClass: "btn-success",
                    confirmButtonText: "OK",
                    closeOnConfirm: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        location.reload();
                    }
                });
        })
        .fail(function (err) {
            swal("Error creando la abreviatura", "error");
        });
}

function ActualizarDatos() {
    var id = $.trim($("#idabre").val());
    var value = $.trim($("#abre").val());
    $.ajax({
        method: "POST",
        url: "/parametros/abreviaturas/actualizar/ajax",
        data : {"idabreviatura" : id, "abreviatura" : value}
    })
        .done(function (data) {
            swal({
                    title:"Abreviatura actualizada correctemente!",
                    type:"success",
                    confirmButtonClass: "btn-success",
                    confirmButtonText: "OK",
                    closeOnConfirm: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        location.reload();
                    }
                });
        })
        .fail(function (err) {
            swal("Error actualizando la abreviatura", "error");
        });
}

<|endoftext|>


<commit_before>var Client                = require('castv2-client').Client;
var DefaultMediaReceiver  = require('castv2-client').DefaultMediaReceiver;
var mdns                  = require('mdns');

/**
  * Serve Stdin through a HTTP server
  * @param opts - Server configuration
  * @param opts.host - The name of the user.
  * @param opts.port - The email of the user.
  * @param opts.image - The name of the user.
  * @param opts.title - The email of the user.
  */
function launchChromecastStreamingApp(opts) {
  opts = opts || {};

  // Fallback to default configuration
  var host = opts.host || '0.0.0.0';
  var port = opts.port || 8080;
  var image = opts.image || '';
  var title = opts.title || 'Pipecast';

  var browser = mdns.createBrowser(mdns.tcp('googlecast'));

  browser.on('serviceUp', function(service) {
    console.log('found device "%s" at %s:%d', service.name, service.addresses[0], service.port);
    ondeviceup(service.addresses[0]);
    browser.stop();
  });

  browser.start();

  function ondeviceup(host) {

    var client = new Client();

    client.connect(host, function() {
      console.log('connected, launching app ...');

      client.launch(DefaultMediaReceiver, function(err, player) {
        var media = {
          // URL to any mp4, webm, mp3 or jpg file with the proper contentType.
          contentId: 'http://' + host + ':' + port,
          contentType: 'video/mp4',
          streamType: 'BUFFERED', // or LIVE

          // Title and cover displayed while buffering
          metadata: {
            type: 0,
            metadataType: 0,
            title: title,
            images: [
              { url: image }
            ]
          }
        };

        player.on('status', function(status) {
          console.log('status broadcast playerState=%s', status.playerState);
        });

        console.log('app "%s" launched, loading media %s ...', player.session.displayName, media.contentId);

        player.load(media, { autoplay: true }, function(err, status) {
          console.log('media loaded playerState=%s', status.playerState);
        });
      });
    });

    client.on('error', function(err) {
      console.log('Error: %s', err.message);
      client.close();
    });
  }
}

module.exports = launchChromecastStreamingApp;

<commit_msg>Add documentation and sensible defaults<commit_after>var Client                = require('castv2-client').Client;
var DefaultMediaReceiver  = require('castv2-client').DefaultMediaReceiver;
var mdns                  = require('mdns');

/**
  * Serve Stdin through a HTTP server
  * See: https://github.com/thibauts/node-castv2#usage
  *
  * @param opts - Server configuration
  * @param [opts.host=0.0.0.0] - Address to accept connections on
  * @param [opts.port=8080] - Port to listen on
  * @param [opts.image=...] - Image to show while buffering
  * @param [opts.title=Pipecast] - Name of the sender app
  */
function launchChromecastStreamingApp(opts) {
  opts = opts || {};

  // Fallback to default configuration
  var host = opts.host || '0.0.0.0';
  var port = opts.port || 8080;
  var image = opts.image || 'https://placeholdit.imgix.net/~text?txtsize=107&txt=Pipecast&w=1280&h=720';
  var title = opts.title || 'Pipecast';

  var browser = mdns.createBrowser(mdns.tcp('googlecast'));

  browser.on('serviceUp', function(service) {
    console.log('found device "%s" at %s:%d', service.name, service.addresses[0], service.port);
    ondeviceup(service.addresses[0]);
    browser.stop();
  });

  browser.start();

  function ondeviceup(host) {

    var client = new Client();

    client.connect(host, function() {
      console.log('connected, launching app ...');

      client.launch(DefaultMediaReceiver, function(err, player) {
        var media = {
          // URL to any mp4, webm, mp3 or jpg file with the proper contentType.
          contentId: 'http://' + host + ':' + port,
          contentType: 'video/mp4',
          streamType: 'BUFFERED', // or LIVE

          // Title and cover displayed while buffering
          metadata: {
            type: 0,
            metadataType: 0,
            title: title,
            images: [
              { url: image }
            ]
          }
        };

        player.on('status', function(status) {
          console.log('status broadcast playerState=%s', status.playerState);
        });

        console.log('app "%s" launched, loading media %s ...', player.session.displayName, media.contentId);

        player.load(media, { autoplay: true }, function(err, status) {
          console.log('media loaded playerState=%s', status.playerState);
        });
      });
    });

    client.on('error', function(err) {
      console.log('Error: %s', err.message);
      client.close();
    });
  }
}

module.exports = launchChromecastStreamingApp;

<|endoftext|>


<commit_before>// The file is defined type.
//
// @author Seven Du <shiweidu@outlook.com>
// @homepage http://medz.cn
// ---------------------------------------

// The const is defined update user data type.
export const USER_UPDATE = 'user/update';

// The const is defined delete user data type.
export const USER_DELETE = 'user/delete';
<commit_msg>增加更新状态树type。<commit_after>// The file is defined type.
//
// @author Seven Du <shiweidu@outlook.com>
// @homepage http://medz.cn
// ---------------------------------------

// The const is defined update user data type.
export const USER_UPDATE = 'user/update';

// The const is defined delete user data type.
export const USER_DELETE = 'user/delete';

// Defined [settings/site].
export const SETTINGS_SITE_UPDATE = 'settings/site/UPDATE';
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as SingleRestaurantActionCreators from './actions';
import cssModules from 'react-css-modules';
import styles from './index.module.scss';

class SingleRestaurant extends Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    const {
      restaurantId,
    } = this.props.location.query;
    const {
      restaurants,
    } = this.props;
    this.state = {
      selectedRestaurant: restaurants.filter(i =>
        i.id === restaurantId
      )[0],
    };
    this.handleLoadingReviews = this.handleLoadingReviews.bind(this);
    this.handleSubmitReview = this.handleSubmitReview.bind(this);
  }
  componentDidMount() {
    this.handleLoadingReviews();
  }
  handleLoadingReviews() {
    const {
      actions,
    } = this.props;
    const {
      selectedRestaurant,
    } = this.state;
    if (selectedRestaurant !== null || typeof selectedRestaurant !== 'undefined') {
      const {
        id,
      } = selectedRestaurant;
      actions.loadReviews(id);
    } else {
      const error = new Error('The selected Restaurant cannot be found.');
      actions.reviewsErrors([error]);
    }
  }
  handleSubmitReview(review) {
    const {
      actions,
    } = this.props;
    actions.submitReview(review);
  }
  render() {
    const {
      selectedRestaurant,
    } = this.state;
    return (

        {selectedRestaurant ?

            {selectedRestaurant}

        :

No Restaurant Found

        }

    );
  }
}

SingleRestaurant.propTypes = {
  reviews: PropTypes.array,
  errors: PropTypes.array,
  isLoading: PropTypes.bool.isRequired,
  restaurants: PropTypes.array.isRequired,
  location: PropTypes.object.isRequired,
  actions: PropTypes.object.isRequired,
};

// mapStateToProps :: {State} -> {Props}
const mapStateToProps = (state) => ({
  reviews: state.singleRestaurant.reviews,
  errors: state.singleRestaurant.errors,
  isLoading: state.singleRestaurant.isLoading,
  restaurants: state.restaurants.items,
});

// mapDispatchToProps :: Dispatch -> {Action}
const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(
    SingleRestaurantActionCreators,
    dispatch
  ),
});

const Container = cssModules(SingleRestaurant, styles);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Container);
<commit_msg>Feat: add props to single restaurant container<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as SingleRestaurantActionCreators from './actions';
import cssModules from 'react-css-modules';
import styles from './index.module.scss';

class SingleRestaurant extends Component {
  constructor(props) {
    super(props);
    const {
      restaurantId,
    } = this.props.location.query;
    const {
      restaurants,
    } = this.props;
    this.state = {
      selectedRestaurant: restaurants.filter(i =>
        i.id === restaurantId
      )[0],
    };
    this.handleLoadingReviews = this.handleLoadingReviews.bind(this);
    this.handleSubmitReview = this.handleSubmitReview.bind(this);
  }
  componentDidMount() {
    this.handleLoadingReviews();
  }
  handleLoadingReviews() {
    const {
      actions,
    } = this.props;
    const {
      selectedRestaurant,
    } = this.state;
    if (selectedRestaurant !== null || typeof selectedRestaurant !== 'undefined') {
      const {
        id,
      } = selectedRestaurant;
      actions.loadReviews(id);
    } else {
      const error = new Error('The selected Restaurant cannot be found.');
      actions.reviewsErrors([error]);
    }
  }
  handleSubmitReview(review) {
    const {
      actions,
    } = this.props;
    actions.submitReview(review);
  }
  render() {
    const {
      selectedRestaurant,
    } = this.state;
    return (

        {selectedRestaurant ?

            {selectedRestaurant}

        :

No Restaurant Found

        }

    );
  }
}

SingleRestaurant.propTypes = {
  reviews: PropTypes.array,
  errors: PropTypes.array,
  isLoading: PropTypes.bool.isRequired,
  restaurants: PropTypes.array.isRequired,
  location: PropTypes.object.isRequired,
  actions: PropTypes.object.isRequired,
};

// mapStateToProps :: {State} -> {Props}
const mapStateToProps = (state) => ({
  reviews: state.singleRestaurant.reviews,
  errors: state.singleRestaurant.errors,
  isLoading: state.singleRestaurant.isLoading,
  restaurants: state.restaurants.items,
});

// mapDispatchToProps :: Dispatch -> {Action}
const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(
    SingleRestaurantActionCreators,
    dispatch
  ),
});

const Container = cssModules(SingleRestaurant, styles);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Container);
<|endoftext|>


<commit_before>var billLengths = {
  AUD: {
    5: 130,
    10: 137,
    20: 144,
    50: 151,
    100: 158
  },
  BBD: {
    2: 150,
    5: 150,
    10: 150,
    20: 150,
    50: 150,
    100: 150
  },
  CAD: {
    5: 152,
    10: 152,
    20: 152,
    50: 152,
    100: 152
  },
  DKK: {
    50: 125,
    100: 135,
    200: 145,
    500: 155,
    1000: 165
  },
  EUR: {
    5: 120,
    10: 127,
    20: 133,
    50: 140,
    100: 147,
    200: 153,
    500: 160
  },
  GBP: {
    5: 135,
    10: 142,
    20: 149,
    50: 156
  },
  HKD: {
    10: 134,
    20: 143,
    50: 148,
    100: 153,
    500: 158,
    1000: 163
  },
  HUF: {
    200: 154,
    500: 154,
    1000: 154,
    2000: 154,
    5000: 154,
    10000: 154,
    20000: 154
  },
  JMD: {
    50: 145,
    100: 145,
    500: 145,
    1000: 145,
    5000: 145
  },
  JPY: {
    1000: 150,
    2000: 154,
    5000: 156,
    10000: 160
  },
  KZT: {
    200: 126,
    500: 130,
    1000: 134,
    2000: 139,
    5000: 144,
    10000: 155,
    20000: 155
  },
  MYR: {
    1: 120,
    5: 135,
    10: 140,
    20: 145,
    50: 145,
    100: 150
  },
  TWD: {
    100: 145,
    200: 150,
    500: 155,
    1000: 160,
    2000: 165
  },
  UAH: {
    1: 118,
    2: 118,
    5: 118,
    10: 124,
    20: 130,
    50: 136,
    100: 142,
    200: 148,
    500: 154
  },
  USD: {
    1: 156,
    5: 156,
    10: 156,
    20: 156,
    50: 156,
    100: 156
  },
  VND: {
    10000: 132,
    20000: 136,
    50000: 140,
    100000: 144,
    200000: 148,
    500000: 152
  }
}

module.exports = {
  billLengths: billLengths
}
<commit_msg>Add ILS<commit_after>var billLengths = {
  AUD: {
    5: 130,
    10: 137,
    20: 144,
    50: 151,
    100: 158
  },
  BBD: {
    2: 150,
    5: 150,
    10: 150,
    20: 150,
    50: 150,
    100: 150
  },
  CAD: {
    5: 152,
    10: 152,
    20: 152,
    50: 152,
    100: 152
  },
  DKK: {
    50: 125,
    100: 135,
    200: 145,
    500: 155,
    1000: 165
  },
  EUR: {
    5: 120,
    10: 127,
    20: 133,
    50: 140,
    100: 147,
    200: 153,
    500: 160
  },
  GBP: {
    5: 135,
    10: 142,
    20: 149,
    50: 156
  },
  HKD: {
    10: 134,
    20: 143,
    50: 148,
    100: 153,
    500: 158,
    1000: 163
  },
  HUF: {
    200: 154,
    500: 154,
    1000: 154,
    2000: 154,
    5000: 154,
    10000: 154,
    20000: 154
  },
  ILS: {
    20: 129,
    50: 136,
    100: 143,
    200: 150
  },
  JMD: {
    50: 145,
    100: 145,
    500: 145,
    1000: 145,
    5000: 145
  },
  JPY: {
    1000: 150,
    2000: 154,
    5000: 156,
    10000: 160
  },
  KZT: {
    200: 126,
    500: 130,
    1000: 134,
    2000: 139,
    5000: 144,
    10000: 155,
    20000: 155
  },
  MYR: {
    1: 120,
    5: 135,
    10: 140,
    20: 145,
    50: 145,
    100: 150
  },
  TWD: {
    100: 145,
    200: 150,
    500: 155,
    1000: 160,
    2000: 165
  },
  UAH: {
    1: 118,
    2: 118,
    5: 118,
    10: 124,
    20: 130,
    50: 136,
    100: 142,
    200: 148,
    500: 154
  },
  USD: {
    1: 156,
    5: 156,
    10: 156,
    20: 156,
    50: 156,
    100: 156
  },
  VND: {
    10000: 132,
    20000: 136,
    50000: 140,
    100000: 144,
    200000: 148,
    500000: 152
  }
}

module.exports = {
  billLengths: billLengths
}
<|endoftext|>


<commit_before>export {
  default,
  injectLayout,
} from '@html-next/flexi-layouts/helpers/-inject-layout';
<commit_msg>fix export<commit_after>export { default } from '@html-next/flexi-layouts/helpers/-inject-layout';
<|endoftext|>


<commit_before>/*
 * Haptics.js (http://hapticsjs.org/)
 * Copyright (c) Shantanu Bala (http://sbala.org/) 2014
 * Direct questions to: shantanu@sbala.org
 * Available under the MIT License.
 */

"use strict";

(function (global) {
    var Haptics = {},
        enabled,
        currentRecording,
        navigatorVibrate,
        log,
        navigator;

    navigator = global.navigator;

    // a console.log wrapper for debugging
    log = function () {
        // store logs to an array for reference
        log.history = log.history || [];
        log.history.push(arguments);

        if (global.console) {
            global.console.log(Array.prototype.slice.call(arguments));
        }
    };

    // used for timeouts that 'accomplish nothing' in a pattern
    function emptyFunc() {
        log("Executed emptyFunc, which does nothing.");
    }

    // check for navigator variables from different vendors
    navigatorVibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;

    enabled = !!navigatorVibrate;

    // calls to navigatorVibrate always bound to global navigator object
    function vibrate() {
        if (enabled) {
            // vibrate will not work unless bound to navigator global
            navigatorVibrate.apply(navigator, arguments);
            return true;
        }

        // log instead of actually vibrating device if disabled
        log(arguments);
        return false;
    }

    // execute two functions timed using the provided durations
    function executeSequence(durations, currentFunc, nextFunc) {
        var d = durations.shift();
        nextFunc = nextFunc || currentFunc;

        currentFunc(d);

        if (durations.length === 0) {
            return true; // finished executing sequence
        }

        // handle remaining durations
        return global.setTimeout(function () {
            // swap order of next and currentFunc
            return executeSequence(durations, nextFunc, currentFunc);
        }, d);
    }

    // create a pattern function from a duration sequence
    function createSequenceFunc(durations) {
        var sum = 0, i = 0, len;
        for (i = 0, len = durations.length; i < len; i += 1) {
            sum += durations[i];
        }

        return function (duration) {
            var d = duration / sum,
                newVibration = [],
                j,
                len2;

            for (j = 0, len2 = durations.length; j < len2; j += 1) {
                newVibration.push(durations[j] * d);
            }

            Haptics.vibrate(newVibration);
        };
    }

    // create a single pattern function from a sequence of functions
    function concatenatePatternFuncs() {
        var funcs = arguments,
            len = arguments.length;

        return function (duration) {
            var i = 0,
                d = duration / len;

            function executeCurrentFunc() {
                funcs[i](d);
            }

            for (i = 0; i < len; i += 1) {
                global.setTimeout(executeCurrentFunc, d);
            }
        };
    }

    // a way to quickly create/compose new tactile animations
    function patternFactory() {
        var len,
            j,
            newPattern,
            funcs = arguments; // each argument is a pattern being combined

        len = funcs.length;

        for (j = 0; j < len; j += 1) {
            if (typeof funcs[j] !== "function") {
                funcs[j] = createSequenceFunc(funcs[j]);
            }
        }

        newPattern = concatenatePatternFuncs(funcs);

        return function (args) {
            if (typeof args === "number") {
                newPattern(args);
            } else {
                executeSequence(args, newPattern, emptyFunc);
            }
        };
    }

    // create a sequencing pattern function
    function createPattern(func) {
        if (arguments.length > 1) {
            func = patternFactory.apply(this, arguments);
        } else if (func && typeof func !== "function" && func.length) {
            func = createSequenceFunc(func);
        } else if (func && typeof func !== "function") {
            return null;
        }

        function newSequence(args) {
            if (typeof args === "number") {
                func(args);
            } else {
                executeSequence(args, func, emptyFunc);
            }
        }

        return newSequence;
    }

    // handle click/touch event
    function onRecord(e) {
        e.preventDefault();
        currentRecording.push(new Date());
    }
    // begin recording a sequence of taps/clicks
    function record() {
        currentRecording = [];
        global.addEventListener("touchstart", onRecord, false);
        global.addEventListener("touchend", onRecord, false);
        global.addEventListener("mousedown", onRecord, false);
        global.addEventListener("mouseup", onRecord, false);
    }
    // complete a recording of a sequence of taps/clicks
    function finish() {
        log(currentRecording);
        global.removeEventListener("touchstart", onRecord);
        global.removeEventListener("touchend", onRecord);
        global.removeEventListener("mousedown", onRecord);
        global.removeEventListener("mouseup", onRecord);

        if (currentRecording.length % 2 !== 0) {
            currentRecording.push(new Date());
        }

        var vibrationPattern = [],
            i,
            j,
            len;

        for (i = 0, len = currentRecording.length; i < len; i += 2) {
            j = i + 1;

            if (j >= len) {
                break;
            }

            vibrationPattern.push(currentRecording[j] - currentRecording[i]);
        }

        return vibrationPattern;
    }

    // EFFECTS: Fade In
    function vibrateFadeIn(duration) {
        var pulses = [],
            d,
            i;

        if (duration < 100) {
            pulses = duration;
        } else {
            d = duration / 100;
            for (i = 1; i <= 10; i += 1) {
                pulses.push(i * d);
                if (i < 10) {
                    pulses.push((10 - i) * d);
                }
            }
        }
        vibrate(pulses);
    }

    // EFFECTS: Fade Out
    function vibrateFadeOut(duration) {
        var pulses = [],
            d,
            i;

        if (duration < 100) {
            pulses = duration;
        } else {
            d = duration / 100;
            for (i = 1; i <= 10; i += 1) {
                pulses.push(i * d);
                if (i < 10) {
                    pulses.push((10 - i) * d);
                }
            }
            pulses.reverse();
        }
        vibrate(pulses);
    }

    // EFFECTS: notification
    function vibrateNotification(duration) {
        var pause, dot, dash;
        pause = duration / 27;
        dot = 2 * pause;
        dash = 3 * pause;
        vibrate([dot, pause, dot, pause, dot, pause * 2, dash, pause, dash, pause * 2, dot, pause, dot, pause, dot]);
    }

    // EFFECTS: heartbeat
    function vibrateHeartbeat(duration) {
        var pause, dot, dash;
        dot = duration / 60;
        pause = dot * 2;
        dash = dot * 24;
        vibrate([dot, pause, dash, pause * 2, dash, pause * 2, dot]);
    }

    // EFFECTS: clunk
    function vibrateClunk(duration) {
        var pause, dot, dash;
        dot = duration * 4 / 22;
        pause = dot * 2;
        dash = dot / 2 * 5;
        vibrate([dot, pause, dash]);
    }

    // EFFECTS: PWM
    function vibratePWM(duration, on, off) {
        var pattern = [on];
        duration -= on;

        while (duration > 0) {
            duration -= off;
            duration -= on;
            pattern.push(off);
            pattern.push(on);
        }

        vibrate(pattern);
    }

    function pwm(args, on, off) {
        var newVibratePWM;
        if (typeof args === "number") {
            vibratePWM(args, on, off);
        } else {
            newVibratePWM = function (d) {
                vibratePWM(d, on, off);
            };
            executeSequence(args, newVibratePWM, emptyFunc);
        }
    }

    // a way to quickly create new PWM intensity functions
    function createPatternPWM(on, off) {
        return function (args) {
            pwm(args, on, off);
        };
    }

    // expose local functions to global API
    Haptics.enabled = enabled;
    Haptics.record = record;
    Haptics.finish = finish;
    Haptics.fadeIn = createPattern(vibrateFadeIn);
    Haptics.fadeOut = createPattern(vibrateFadeOut);
    Haptics.notification = createPattern(vibrateNotification);
    Haptics.heartbeat = createPattern(vibrateHeartbeat);
    Haptics.clunk = createPattern(vibrateClunk);
    Haptics.pwm = pwm;
    Haptics.createPatternPWM = createPatternPWM;
    Haptics.createPattern = createPattern;
    Haptics.vibrate = vibrate;

    // set global object
    global.Haptics = Haptics;
}(this));
<commit_msg>modified header comment<commit_after>/*
 * Haptics.js - http://hapticsjs.org/
 * Copyright (c) Shantanu Bala 2014
 * Direct questions to shantanu@sbala.org
 * Haptics.js can be freely distributed under the MIT License.
 */

"use strict";

(function (global) {
    var Haptics = {},
        enabled,
        currentRecording,
        navigatorVibrate,
        log,
        navigator;

    navigator = global.navigator;

    // a console.log wrapper for debugging
    log = function () {
        // store logs to an array for reference
        log.history = log.history || [];
        log.history.push(arguments);

        if (global.console) {
            global.console.log(Array.prototype.slice.call(arguments));
        }
    };

    // used for timeouts that 'accomplish nothing' in a pattern
    function emptyFunc() {
        log("Executed emptyFunc, which does nothing.");
    }

    // check for navigator variables from different vendors
    navigatorVibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;

    enabled = !!navigatorVibrate;

    // calls to navigatorVibrate always bound to global navigator object
    function vibrate() {
        if (enabled) {
            // vibrate will not work unless bound to navigator global
            navigatorVibrate.apply(navigator, arguments);
            return true;
        }

        // log instead of actually vibrating device if disabled
        log(arguments);
        return false;
    }

    // execute two functions timed using the provided durations
    function executeSequence(durations, currentFunc, nextFunc) {
        var d = durations.shift();
        nextFunc = nextFunc || currentFunc;

        currentFunc(d);

        if (durations.length === 0) {
            return true; // finished executing sequence
        }

        // handle remaining durations
        return global.setTimeout(function () {
            // swap order of next and currentFunc
            return executeSequence(durations, nextFunc, currentFunc);
        }, d);
    }

    // create a pattern function from a duration sequence
    function createSequenceFunc(durations) {
        var sum = 0, i = 0, len;
        for (i = 0, len = durations.length; i < len; i += 1) {
            sum += durations[i];
        }

        return function (duration) {
            var d = duration / sum,
                newVibration = [],
                j,
                len2;

            for (j = 0, len2 = durations.length; j < len2; j += 1) {
                newVibration.push(durations[j] * d);
            }

            Haptics.vibrate(newVibration);
        };
    }

    // create a single pattern function from a sequence of functions
    function concatenatePatternFuncs() {
        var funcs = arguments,
            len = arguments.length;

        return function (duration) {
            var i = 0,
                d = duration / len;

            function executeCurrentFunc() {
                funcs[i](d);
            }

            for (i = 0; i < len; i += 1) {
                global.setTimeout(executeCurrentFunc, d);
            }
        };
    }

    // a way to quickly create/compose new tactile animations
    function patternFactory() {
        var len,
            j,
            newPattern,
            funcs = arguments; // each argument is a pattern being combined

        len = funcs.length;

        for (j = 0; j < len; j += 1) {
            if (typeof funcs[j] !== "function") {
                funcs[j] = createSequenceFunc(funcs[j]);
            }
        }

        newPattern = concatenatePatternFuncs(funcs);

        return function (args) {
            if (typeof args === "number") {
                newPattern(args);
            } else {
                executeSequence(args, newPattern, emptyFunc);
            }
        };
    }

    // create a sequencing pattern function
    function createPattern(func) {
        if (arguments.length > 1) {
            func = patternFactory.apply(this, arguments);
        } else if (func && typeof func !== "function" && func.length) {
            func = createSequenceFunc(func);
        } else if (func && typeof func !== "function") {
            return null;
        }

        function newSequence(args) {
            if (typeof args === "number") {
                func(args);
            } else {
                executeSequence(args, func, emptyFunc);
            }
        }

        return newSequence;
    }

    // handle click/touch event
    function onRecord(e) {
        e.preventDefault();
        currentRecording.push(new Date());
    }
    // begin recording a sequence of taps/clicks
    function record() {
        currentRecording = [];
        global.addEventListener("touchstart", onRecord, false);
        global.addEventListener("touchend", onRecord, false);
        global.addEventListener("mousedown", onRecord, false);
        global.addEventListener("mouseup", onRecord, false);
    }
    // complete a recording of a sequence of taps/clicks
    function finish() {
        log(currentRecording);
        global.removeEventListener("touchstart", onRecord);
        global.removeEventListener("touchend", onRecord);
        global.removeEventListener("mousedown", onRecord);
        global.removeEventListener("mouseup", onRecord);

        if (currentRecording.length % 2 !== 0) {
            currentRecording.push(new Date());
        }

        var vibrationPattern = [],
            i,
            j,
            len;

        for (i = 0, len = currentRecording.length; i < len; i += 2) {
            j = i + 1;

            if (j >= len) {
                break;
            }

            vibrationPattern.push(currentRecording[j] - currentRecording[i]);
        }

        return vibrationPattern;
    }

    // EFFECTS: Fade In
    function vibrateFadeIn(duration) {
        var pulses = [],
            d,
            i;

        if (duration < 100) {
            pulses = duration;
        } else {
            d = duration / 100;
            for (i = 1; i <= 10; i += 1) {
                pulses.push(i * d);
                if (i < 10) {
                    pulses.push((10 - i) * d);
                }
            }
        }
        vibrate(pulses);
    }

    // EFFECTS: Fade Out
    function vibrateFadeOut(duration) {
        var pulses = [],
            d,
            i;

        if (duration < 100) {
            pulses = duration;
        } else {
            d = duration / 100;
            for (i = 1; i <= 10; i += 1) {
                pulses.push(i * d);
                if (i < 10) {
                    pulses.push((10 - i) * d);
                }
            }
            pulses.reverse();
        }
        vibrate(pulses);
    }

    // EFFECTS: notification
    function vibrateNotification(duration) {
        var pause, dot, dash;
        pause = duration / 27;
        dot = 2 * pause;
        dash = 3 * pause;
        vibrate([dot, pause, dot, pause, dot, pause * 2, dash, pause, dash, pause * 2, dot, pause, dot, pause, dot]);
    }

    // EFFECTS: heartbeat
    function vibrateHeartbeat(duration) {
        var pause, dot, dash;
        dot = duration / 60;
        pause = dot * 2;
        dash = dot * 24;
        vibrate([dot, pause, dash, pause * 2, dash, pause * 2, dot]);
    }

    // EFFECTS: clunk
    function vibrateClunk(duration) {
        var pause, dot, dash;
        dot = duration * 4 / 22;
        pause = dot * 2;
        dash = dot / 2 * 5;
        vibrate([dot, pause, dash]);
    }

    // EFFECTS: PWM
    function vibratePWM(duration, on, off) {
        var pattern = [on];
        duration -= on;

        while (duration > 0) {
            duration -= off;
            duration -= on;
            pattern.push(off);
            pattern.push(on);
        }

        vibrate(pattern);
    }

    function pwm(args, on, off) {
        var newVibratePWM;
        if (typeof args === "number") {
            vibratePWM(args, on, off);
        } else {
            newVibratePWM = function (d) {
                vibratePWM(d, on, off);
            };
            executeSequence(args, newVibratePWM, emptyFunc);
        }
    }

    // a way to quickly create new PWM intensity functions
    function createPatternPWM(on, off) {
        return function (args) {
            pwm(args, on, off);
        };
    }

    // expose local functions to global API
    Haptics.enabled = enabled;
    Haptics.record = record;
    Haptics.finish = finish;
    Haptics.fadeIn = createPattern(vibrateFadeIn);
    Haptics.fadeOut = createPattern(vibrateFadeOut);
    Haptics.notification = createPattern(vibrateNotification);
    Haptics.heartbeat = createPattern(vibrateHeartbeat);
    Haptics.clunk = createPattern(vibrateClunk);
    Haptics.pwm = pwm;
    Haptics.createPatternPWM = createPatternPWM;
    Haptics.createPattern = createPattern;
    Haptics.vibrate = vibrate;

    // set global object
    global.Haptics = Haptics;
}(this));
<|endoftext|>


<commit_before>module.exports = {
  'framework': 'mocha',
  'test_page': 'tests/index.html?hidepassed',
  'disable_watching': true,
  'launch_in_ci': [
    'PhantomJS'
  ],
  'launch_in_dev': [
    'Firefox'
  ],
  'launchers': {
    'slimerjs': {
      'command': 'slimerjs slimerjs-launcher.js <url>',
      'protocol': 'browser'
    }
  }
}
<commit_msg>Target Firefox for ci as well<commit_after>module.exports = {
  'framework': 'mocha',
  'test_page': 'tests/index.html?hidepassed',
  'disable_watching': true,
  'launch_in_ci': [
    'PhantomJS',
    'Firefox'
  ],
  'launch_in_dev': [
    'Firefox'
  ],
  'launchers': {
    'slimerjs': {
      'command': 'slimerjs slimerjs-launcher.js <url>',
      'protocol': 'browser'
    }
  }
}
<|endoftext|>