<commit_before>/*
 * Build file for the web application.
 * Executed by 'gulp'
 */

/*
 * Libraries required
 */
var gulp = require('gulp'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    map = require('vinyl-map'),
    jshint = require('gulp-jshint'),
    cleanCss = require('gulp-clean-css'),
    ngAnnotate = require('gulp-ng-annotate'),
    fs = require('fs'),
    path = require('path'),
    size = require('gulp-size'),
    uri = require('URIjs'),
    s = require('underscore.string'),
    hawtio = require('hawtio-node-backend'),
    childProc = require('child_process'),
    logger = require('js-logger')

// Load all the gulp plugins
var plugins = gulpLoadPlugins({});

// Grab the content of package.json
var pkg = require('./package.json');

// Configure some regularly used config variables
var config = {
    main: '.',
    app: {
        name: 'app',
        root: 'app/',
        js: 'app/**/*.js',
        less: 'app/**/content/**/*.less',
        html: ['app/**/*.html'],
        templateModule: pkg.name + '-app-templates',
    },
    plugins: {
        name: 'plugins',
        root: 'plugins/',
        js: 'plugins/**/*.js',
        less: 'plugins/**/content/**/*.less',
        html: ['plugins/**/*.html'],
        templateModule: pkg.name + '-templates',
    },
    css: 'styles.css',
    libFiles: 'libs/**/*.{png,gif,jpg,svg,woff,woff2,eot,ttf,otf,css}',
    releaseDest: 'target/site'
};

/*
 * Task for automatically inserting dependencies
 * into the index.html file when they are installed
 * by bower.
 *
 * == Disabled by annotation comments removed ==
 * Seems some css, js paths are getting removed, eg.
 * patternfly and bootstrap
 *
 * See https://www.npmjs.com/package/wiredep
 */
gulp.task('bower', function () {
    return gulp.src('index.html')
        .pipe(wiredep({}))
        .pipe(gulp.dest('.'));
});

/*
 * Task for checking js syntax in source file
 */
gulp.task('jshint', function () {
    return gulp.src([config.app.js, config.plugins.js])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

/*
 * Task that finds all .less files and converts
 * then into a single .css file at css/styles.css
 */
gulp.task('less', function () {
    gulp.src([config.app.less, config.plugins.less])
        .pipe(plugins.less({
            paths: [path.join(__dirname, 'less', 'includes')]
        }))
        .pipe(plugins.concat(config.css))
        .pipe(gulp.dest('css'));
});

/*
 * Task that finds all html files being used as
 * angular templates, concatenates them into
 * a single angular module which adds them to
 * the internal angular template cache.
 *
 * This is performance efficient since it avoids
 * downloading multiple html files but also
 * necessary since the hawtio-template-cache
 * requires these files to be in the cache.
 */
gulp.task('plugin-templates', function () {
    return gulp.src(config.plugins.html)
        .pipe(plugins.angularTemplatecache({
            filename: config.templateModule + '.js',
            root: config.plugins.root,
            standalone: true,
            module: config.plugins.templateModule,
            templateFooter: '}]); hawtioPluginLoader.addModule("' + config.plugins.templateModule + '");'
        }))
        .pipe(gulp.dest(config.plugins.name));
});

gulp.task('app-templates', function () {
    return gulp.src(config.app.html)
        .pipe(plugins.angularTemplatecache({
            filename: config.app.templateModule + '.js',
            root: config.app.root,
            standalone: true,
            module: config.app.templateModule,
            templateFooter: '}]); hawtioPluginLoader.addModule("' + config.app.templateModule + '");'
        }))
        .pipe(gulp.dest(config.app.name));
});

/*
 * Task to watch files likely to be modified
 * and call other tasks if they do change.
 */
gulp.task('watch', ['build'], function () {
    plugins.watch(['libs/**/*.{js, css}', 'index.html',
                            config.app.root + '**/*.{js, less, html}',
                            config.plugins.root + '**/*.{js, less, html}',
                            '!' + config.plugins.root + config.plugins.templateModule + '.js',
                            '!' + config.app.root + config.app.templateModule + '.js'
                         ], function () {
                            gulp.start('reload', ['jshint', 'less', 'plugin-templates', 'app-templates']);
                         });
});

/*
 * Task to bring up a hawtio-node-backend
 * server that serves out the project's source
 * for testing and developing.
 */
gulp.task('connect', ['watch'], function () {
    hawtio.setConfig({
        logLevel: logger.DEBUG,
        port: 2772,
        fallback: 'index.html',
        staticAssets: [{
            path: '/vdb-bench',
            dir: '.'
    }],
        liveReload: {
            enabled: true
        }
    });

    hawtio.listen(function (server) {
        var host = server.address().address;
        var port = server.address().port;
        console.log("hawtio node backend started from gulp file at ", host, ":", port);
    });
});

/*
 * Task to reload the hawtio-node-backend
 * server.
 */
gulp.task('reload', function () {
    gulp.src('.')
        .pipe(hawtio.reload());
});

/*
 * === For production build ===
 *
 * Task to copy all non-source files
 * to the release destination.
 */
gulp.task('site-files', function () {
    // Copy images and lib artifacts to site
    return gulp.src(['favicon.ico', 'img/**',
                            config.app.root + '**/content/img/**',
                            config.plugins.root + '**/content/img/**',
                            config.libFiles], {
            base: '.'
        })
        .pipe(plugins.debug({
            title: 'site files'
        }))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * === For production build ===
 *
 * Task to minify/uglify source files
 * to compress files for quicker download.
 *
 * cleanCss(): minify css
 * uglify(): uglifies js
 * ngAnnotate(): ensures all angular injections are explicit
 */
gulp.task('usemin', ['site-files'], function () {
    //
    // minifies both the css and js located in the
    // index file
    //
    return gulp.src('index.html')
        .pipe(plugins.usemin({
            css: [plugins.cleanCss(), 'concat'],
            libsJs: [plugins.uglify(), plugins.rev()],
            pluginsJs: [plugins.ngAnnotate(), plugins.uglify(), plugins.rev()],
            appJs: [plugins.ngAnnotate(), plugins.uglify(), plugins.rev()]
        }))
        .pipe(plugins.debug({
            title: 'usemin'
        }))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * Task to move any old index.html files
 * to 404.html
 */
gulp.task('site', ['usemin'], function () {
    return gulp.src('target/site/index.html')
        .pipe(plugins.rename('404.html'))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * Task to run a Rest test server.
 */
gulp.task('test-server', function (cb) {
    function fork() {
        var spawn = childProc.spawn;
        var spawned = spawn('node', ['dev-server/server.js']);

        spawned.stdout.on('data', function (data) {
            console.log('' + data);
        });

        spawned.stderr.on('data', function (data) {
            console.log('err: ' + data);
        });

        return spawned;
    }

    var proc = fork();
    plugins.watch(['dev-server/**/*'], function () {
        if (proc) {
            proc.kill();
            proc = fork();
        }
    });
});

/*
 * Task to be executed by maven.
 * Builds the project for release deployment
 * in target directory.
 */
gulp.task('mvn', ['build', 'site']);

/*
 * Task to build the project
 */
gulp.task('build', ['bower', 'jshint', 'less', 'app-templates', 'plugin-templates']);

/*
 * Task to build, launch the Rest test server and
 * bring up the application using the hawtio-node-backend
 */
gulp.task('default', ['test-server', 'connect']);<commit_msg>Fixes configuration error in gulp build system<commit_after>/*
 * Build file for the web application.
 * Executed by 'gulp'
 */

/*
 * Libraries required
 */
var gulp = require('gulp'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    map = require('vinyl-map'),
    jshint = require('gulp-jshint'),
    cleanCss = require('gulp-clean-css'),
    ngAnnotate = require('gulp-ng-annotate'),
    fs = require('fs'),
    path = require('path'),
    size = require('gulp-size'),
    uri = require('URIjs'),
    s = require('underscore.string'),
    hawtio = require('hawtio-node-backend'),
    childProc = require('child_process'),
    logger = require('js-logger')

// Load all the gulp plugins
var plugins = gulpLoadPlugins({});

// Grab the content of package.json
var pkg = require('./package.json');

// Configure some regularly used config variables
var config = {
    main: '.',
    app: {
        name: 'app',
        root: 'app/',
        js: 'app/**/*.js',
        less: 'app/**/content/**/*.less',
        html: ['app/**/*.html'],
        templateModule: pkg.name + '-app-templates',
    },
    plugins: {
        name: 'plugins',
        root: 'plugins/',
        js: 'plugins/**/*.js',
        less: 'plugins/**/content/**/*.less',
        html: ['plugins/**/*.html'],
        templateModule: pkg.name + '-templates',
    },
    css: 'styles.css',
    libFiles: 'libs/**/*.{png,gif,jpg,svg,woff,woff2,eot,ttf,otf,css}',
    releaseDest: 'target/site'
};

/*
 * Task for automatically inserting dependencies
 * into the index.html file when they are installed
 * by bower.
 *
 * == Disabled by annotation comments removed ==
 * Seems some css, js paths are getting removed, eg.
 * patternfly and bootstrap
 *
 * See https://www.npmjs.com/package/wiredep
 */
gulp.task('bower', function () {
    return gulp.src('index.html')
        .pipe(wiredep({}))
        .pipe(gulp.dest('.'));
});

/*
 * Task for checking js syntax in source file
 */
gulp.task('jshint', function () {
    return gulp.src([config.app.js, config.plugins.js])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

/*
 * Task that finds all .less files and converts
 * then into a single .css file at css/styles.css
 */
gulp.task('less', function () {
    gulp.src([config.app.less, config.plugins.less])
        .pipe(plugins.less({
            paths: [path.join(__dirname, 'less', 'includes')]
        }))
        .pipe(plugins.concat(config.css))
        .pipe(gulp.dest('css'));
});

/*
 * Task that finds all html files being used as
 * angular templates, concatenates them into
 * a single angular module which adds them to
 * the internal angular template cache.
 *
 * This is performance efficient since it avoids
 * downloading multiple html files but also
 * necessary since the hawtio-template-cache
 * requires these files to be in the cache.
 */
gulp.task('plugin-templates', function () {
    return gulp.src(config.plugins.html)
        .pipe(plugins.angularTemplatecache({
            filename: config.plugins.templateModule + '.js',
            root: config.plugins.root,
            standalone: true,
            module: config.plugins.templateModule,
            templateFooter: '}]); hawtioPluginLoader.addModule("' + config.plugins.templateModule + '");'
        }))
        .pipe(gulp.dest(config.plugins.name));
});

gulp.task('app-templates', function () {
    return gulp.src(config.app.html)
        .pipe(plugins.angularTemplatecache({
            filename: config.app.templateModule + '.js',
            root: config.app.root,
            standalone: true,
            module: config.app.templateModule,
            templateFooter: '}]); hawtioPluginLoader.addModule("' + config.app.templateModule + '");'
        }))
        .pipe(gulp.dest(config.app.name));
});

/*
 * Task to watch files likely to be modified
 * and call other tasks if they do change.
 */
gulp.task('watch', ['build'], function () {
    plugins.watch(['libs/**/*.{js, css}', 'index.html',
                            config.app.root + '**/*.{js, less, html}',
                            config.plugins.root + '**/*.{js, less, html}',
                            '!' + config.plugins.root + config.plugins.templateModule + '.js',
                            '!' + config.app.root + config.app.templateModule + '.js'
                         ], function () {
                            gulp.start('reload', ['jshint', 'less', 'plugin-templates', 'app-templates']);
                         });
});

/*
 * Task to bring up a hawtio-node-backend
 * server that serves out the project's source
 * for testing and developing.
 */
gulp.task('connect', ['watch'], function () {
    hawtio.setConfig({
        logLevel: logger.DEBUG,
        port: 2772,
        fallback: 'index.html',
        staticAssets: [{
            path: '/vdb-bench',
            dir: '.'
    }],
        liveReload: {
            enabled: true
        }
    });

    hawtio.listen(function (server) {
        var host = server.address().address;
        var port = server.address().port;
        console.log("hawtio node backend started from gulp file at ", host, ":", port);
    });
});

/*
 * Task to reload the hawtio-node-backend
 * server.
 */
gulp.task('reload', function () {
    gulp.src('.')
        .pipe(hawtio.reload());
});

/*
 * === For production build ===
 *
 * Task to copy all non-source files
 * to the release destination.
 */
gulp.task('site-files', function () {
    // Copy images and lib artifacts to site
    return gulp.src(['favicon.ico', 'img/**',
                            config.app.root + '**/content/img/**',
                            config.plugins.root + '**/content/img/**',
                            config.libFiles], {
            base: '.'
        })
        .pipe(plugins.debug({
            title: 'site files'
        }))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * === For production build ===
 *
 * Task to minify/uglify source files
 * to compress files for quicker download.
 *
 * cleanCss(): minify css
 * uglify(): uglifies js
 * ngAnnotate(): ensures all angular injections are explicit
 */
gulp.task('usemin', ['site-files'], function () {
    //
    // minifies both the css and js located in the
    // index file
    //
    return gulp.src('index.html')
        .pipe(plugins.usemin({
            css: [plugins.cleanCss(), 'concat'],
            libsJs: [plugins.uglify(), plugins.rev()],
            pluginsJs: [plugins.ngAnnotate(), plugins.uglify(), plugins.rev()],
            appJs: [plugins.ngAnnotate(), plugins.uglify(), plugins.rev()]
        }))
        .pipe(plugins.debug({
            title: 'usemin'
        }))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * Task to move any old index.html files
 * to 404.html
 */
gulp.task('site', ['usemin'], function () {
    return gulp.src('target/site/index.html')
        .pipe(plugins.rename('404.html'))
        .pipe(gulp.dest(config.releaseDest));
});

/*
 * Task to run a Rest test server.
 */
gulp.task('test-server', function (cb) {
    function fork() {
        var spawn = childProc.spawn;
        var spawned = spawn('node', ['dev-server/server.js']);

        spawned.stdout.on('data', function (data) {
            console.log('' + data);
        });

        spawned.stderr.on('data', function (data) {
            console.log('err: ' + data);
        });

        return spawned;
    }

    var proc = fork();
    plugins.watch(['dev-server/**/*'], function () {
        if (proc) {
            proc.kill();
            proc = fork();
        }
    });
});

/*
 * Task to be executed by maven.
 * Builds the project for release deployment
 * in target directory.
 */
gulp.task('mvn', ['build', 'site']);

/*
 * Task to build the project
 */
gulp.task('build', ['bower', 'jshint', 'less', 'app-templates', 'plugin-templates']);

/*
 * Task to build, launch the Rest test server and
 * bring up the application using the hawtio-node-backend
 */
gulp.task('default', ['test-server', 'connect']);<|endoftext|>


<commit_before>$(document).ready(function(){

  var exampleGraphs = [
  // {
  //   "info": {
  //     "title": "contextfree to gif",
  //     "author": "forresto",
  //     "description": "contextfree to animated gif",
  //     "url": "contextfree"
  //   },
  //   "nodes": [
  //     {
  //       "src": "/modules/contextfree.html",
  //       "x": 128,
  //       "y": 45,
  //       "w": 343,
  //       "h": 524,
  //       "id": 1
  //     },
  //     {
  //       "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
  //       "x": 622,
  //       "y": 43,
  //       "w": 357,
  //       "h": 285,
  //       "id": 3,
  //       "state": {
  //         "delay": 200,
  //         "quality": 75
  //       }
  //     },
  //     {
  //       "src": "http://forresto.github.com/meemoo-modules/imgur.html",
  //       "x": 625,
  //       "y": 398,
  //       "w": 357,
  //       "h": 297,
  //       "id": 5,
  //       "state": {
  //         "title": "meemoo/cam2gif image share",
  //         "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/cam2gif"
  //       }
  //     }
  //   ],
  //   "edges": []
  // },
  {
    "info": {
      "title": "cam to gif",
      "author": "forresto",
      "description": "webcam to animated gif",
      "url": "cam2gif"
    },
    "nodes": [
      {
        "src": "/camcanvas/onionskin.html",
        "x": 128,
        "y": 45,
        "w": 343,
        "h": 280,
        "id": 1,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 622,
        "y": 43,
        "w": 357,
        "h": 285,
        "id": 3,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 625,
        "y": 398,
        "w": 357,
        "h": 297,
        "id": 5,
        "state": {
          "title": "meemoo/cam2gif image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/cam2gif"
        }
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          3,
          "gif"
        ],
        "target": [
          5,
          "dataurl"
        ],
        "color": "#F4F328"
      }
    ]
  },
  {
    "info": {
      "title": "cam to canvas",
      "author": "forresto",
      "description": "webcam to canvas",
      "url": "cam"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-modules/metronome.html",
        "x": 205,
        "y": 43,
        "w": 200,
        "h": 100,
        "id": 1,
        "state": {
          "bpm": 60
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2canvas.html",
        "x": 608,
        "y": 43,
        "w": 339,
        "h": 516,
        "id": 2,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/reflow.html",
        "x": 199,
        "y": 245,
        "w": 256,
        "h": 297,
        "id": 3
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "beat"
        ],
        "target": [
          2,
          "capture"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          2,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#FD8603"
      }
    ]
  },
  {
    "info": {
      "title": "cam to glitch",
      "author": "forresto",
      "description": "webcam to jpg to glitch",
      "url": "glitch"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-modules/metronome.html",
        "x": 139,
        "y": 45,
        "w": 200,
        "h": 100,
        "id": 1,
        "state": {
          "bpm": 150
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2jpg.html",
        "x": 581,
        "y": 49,
        "w": 339,
        "h": 283,
        "id": 2,
        "state": {
          "quality": 20,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-jpgglitch/index.html",
        "x": 138,
        "y": 220,
        "w": 339,
        "h": 262,
        "id": 4
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/img2canvas.html",
        "x": 282,
        "y": 559,
        "w": 116,
        "h": 98,
        "id": 5
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/reflow.html",
        "x": 646,
        "y": 398,
        "w": 256,
        "h": 297,
        "id": 3
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "beat"
        ],
        "target": [
          2,
          "capture"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          2,
          "jpg"
        ],
        "target": [
          4,
          "jpg"
        ],
        "color": "#FD8603"
      },
      {
        "source": [
          5,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#F4F328"
      },
      {
        "source": [
          4,
          "jpg"
        ],
        "target": [
          5,
          "dataurl"
        ],
        "color": "#00DA3C"
      }
    ]
  },
  {
    info: {
      title: "processing dot js",
      author: "forresto",
      description: "processing to reflow",
      url: "processing"
    },
    nodes: [
      {
        id: 1,
        src: "http://forresto.github.com/meemoo-modules/metronome.html",
        "x":130,"y":47,"w":230,"h":110,
        state: { bpm: 140, start: true }
      },
      {
        id: 3,
        src: "http://forresto.github.com/meemoo-modules/processing.html",
        "x":148,"y":246,"w":308,"h":348,
        state: {
          processingcode: "void setup() { size(300, 300); colorMode(HSB, 360, 100, 300); noStroke(); background(0); } \n void mousePressed () { fill(random(360), 180, 300); triangle(random(width), random(height), 100, 100, 200, 200);}"
        }
      },
      {
        id: 4,
        src: "http://forresto.github.com/meemoo-modules/reflow.html",
        "x":630,"y":88,"w":449,"h":199
      },
      {
        id: 5,
        src: "http://forresto.github.com/meemoo-modules/reflow.html",
        "x":686,"y":384,"w":440,"h":204
      }
    ],
    edges: [
      { source: [1, "beat"],  target: [3, "pressed"] },
      { source: [3, "image"], target: [4, "image"] }
    ]
  },
  {
    "info": {
      "title": "doodle flipbook",
      "author": "forresto",
      "description": "paint doodle to image array to animated gif",
      "url": "flipbook"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-paint/paint.html",
        "x": 136,
        "y": 52,
        "w": 377,
        "h": 342,
        "id": 1
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/canvasarray.html",
        "x": 663,
        "y": 48,
        "w": 348,
        "h": 331,
        "id": 3
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 145,
        "y": 450,
        "w": 354,
        "h": 341,
        "id": 2,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 678,
        "y": 464,
        "w": 357,
        "h": 297,
        "id": 6,
        "state": {
          "title": "meemoo/flipbook image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/flipbook"
        }
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#00CBE7"
      },
      {
        "source": [
          3,
          "image"
        ],
        "target": [
          2,
          "image"
        ],
        "color": "#00DA3C"
      },
      {
        "source": [
          2,
          "gif"
        ],
        "target": [
          6,
          "dataurl"
        ],
        "color": "#DF151A"
      }
    ]
  },
  {
    "info": {
      "title": "cam doodle",
      "author": "forresto",
      "description": "webcam to processing doodle to animated gif",
      "url": "camdoodle"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2canvas.html",
        "x": 126,
        "y": 43,
        "w": 342,
        "h": 283,
        "id": 4,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-paint/paint.html",
        "x": 634,
        "y": 53,
        "w": 377,
        "h": 342,
        "id": 1
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 135,
        "y": 395,
        "w": 354,
        "h": 341,
        "id": 2,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 652,
        "y": 456,
        "w": 357,
        "h": 297,
        "id": 6,
        "state": {
          "title": "meemoo/camdoodle image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/camdoodle"
        }
      }
    ],
    "edges": [
      {
        "source": [
          4,
          "image"
        ],
        "target": [
          1,
          "image"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          2,
          "image"
        ],
        "color": "#FD8603"
      },
      {
        "source": [
          2,
          "gif"
        ],
        "target": [
          6,
          "dataurl"
        ],
        "color": "#F4F328"
      }
    ]
  }

  ];

  // Default example
  window.Iframework.showGraph(exampleGraphs[0]);

  // Router
  var IframeworkRouter = Backbone.Router.extend({

    routes: {
      "/example/:url": "loadExample" // #/example/url
    },

    loadExample: function(url) {
      for (var i=0; i<exampleGraphs.length; i++) {
        if (exampleGraphs[i]["info"]["url"] === url) {
          Iframework.showGraph(exampleGraphs[i]);
          document.title = "meemoo/"+url;
          return;
        }
      }
    }

  });
  Iframework.router = new IframeworkRouter();
  Backbone.history.start();

  // Make example links:
  var exampleLinks = "examples: "
  for (var i=0; i<exampleGraphs.length; i++) {
    var url = exampleGraphs[i]["info"]["url"];
    if (url) {
      exampleLinks += ''+url+' ';
    }
  }
  $("footer").append(exampleLinks);

});<commit_msg>bugfix: full url<commit_after>$(document).ready(function(){

  var exampleGraphs = [
  // {
  //   "info": {
  //     "title": "contextfree to gif",
  //     "author": "forresto",
  //     "description": "contextfree to animated gif",
  //     "url": "contextfree"
  //   },
  //   "nodes": [
  //     {
  //       "src": "/modules/contextfree.html",
  //       "x": 128,
  //       "y": 45,
  //       "w": 343,
  //       "h": 524,
  //       "id": 1
  //     },
  //     {
  //       "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
  //       "x": 622,
  //       "y": 43,
  //       "w": 357,
  //       "h": 285,
  //       "id": 3,
  //       "state": {
  //         "delay": 200,
  //         "quality": 75
  //       }
  //     },
  //     {
  //       "src": "http://forresto.github.com/meemoo-modules/imgur.html",
  //       "x": 625,
  //       "y": 398,
  //       "w": 357,
  //       "h": 297,
  //       "id": 5,
  //       "state": {
  //         "title": "meemoo/cam2gif image share",
  //         "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/cam2gif"
  //       }
  //     }
  //   ],
  //   "edges": []
  // },
  {
    "info": {
      "title": "cam to gif",
      "author": "forresto",
      "description": "webcam to animated gif",
      "url": "cam2gif"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/onionskin.html",
        "x": 128,
        "y": 45,
        "w": 343,
        "h": 280,
        "id": 1,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 622,
        "y": 43,
        "w": 357,
        "h": 285,
        "id": 3,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 625,
        "y": 398,
        "w": 357,
        "h": 297,
        "id": 5,
        "state": {
          "title": "meemoo/cam2gif image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/cam2gif"
        }
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          3,
          "gif"
        ],
        "target": [
          5,
          "dataurl"
        ],
        "color": "#F4F328"
      }
    ]
  },
  {
    "info": {
      "title": "cam to canvas",
      "author": "forresto",
      "description": "webcam to canvas",
      "url": "cam"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-modules/metronome.html",
        "x": 205,
        "y": 43,
        "w": 200,
        "h": 100,
        "id": 1,
        "state": {
          "bpm": 60
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2canvas.html",
        "x": 608,
        "y": 43,
        "w": 339,
        "h": 516,
        "id": 2,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/reflow.html",
        "x": 199,
        "y": 245,
        "w": 256,
        "h": 297,
        "id": 3
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "beat"
        ],
        "target": [
          2,
          "capture"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          2,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#FD8603"
      }
    ]
  },
  {
    "info": {
      "title": "cam to glitch",
      "author": "forresto",
      "description": "webcam to jpg to glitch",
      "url": "glitch"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-modules/metronome.html",
        "x": 139,
        "y": 45,
        "w": 200,
        "h": 100,
        "id": 1,
        "state": {
          "bpm": 150
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2jpg.html",
        "x": 581,
        "y": 49,
        "w": 339,
        "h": 283,
        "id": 2,
        "state": {
          "quality": 20,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-jpgglitch/index.html",
        "x": 138,
        "y": 220,
        "w": 339,
        "h": 262,
        "id": 4
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/img2canvas.html",
        "x": 282,
        "y": 559,
        "w": 116,
        "h": 98,
        "id": 5
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/reflow.html",
        "x": 646,
        "y": 398,
        "w": 256,
        "h": 297,
        "id": 3
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "beat"
        ],
        "target": [
          2,
          "capture"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          2,
          "jpg"
        ],
        "target": [
          4,
          "jpg"
        ],
        "color": "#FD8603"
      },
      {
        "source": [
          5,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#F4F328"
      },
      {
        "source": [
          4,
          "jpg"
        ],
        "target": [
          5,
          "dataurl"
        ],
        "color": "#00DA3C"
      }
    ]
  },
  {
    info: {
      title: "processing dot js",
      author: "forresto",
      description: "processing to reflow",
      url: "processing"
    },
    nodes: [
      {
        id: 1,
        src: "http://forresto.github.com/meemoo-modules/metronome.html",
        "x":130,"y":47,"w":230,"h":110,
        state: { bpm: 140, start: true }
      },
      {
        id: 3,
        src: "http://forresto.github.com/meemoo-modules/processing.html",
        "x":148,"y":246,"w":308,"h":348,
        state: {
          processingcode: "void setup() { size(300, 300); colorMode(HSB, 360, 100, 300); noStroke(); background(0); } \n void mousePressed () { fill(random(360), 180, 300); triangle(random(width), random(height), 100, 100, 200, 200);}"
        }
      },
      {
        id: 4,
        src: "http://forresto.github.com/meemoo-modules/reflow.html",
        "x":630,"y":88,"w":449,"h":199
      },
      {
        id: 5,
        src: "http://forresto.github.com/meemoo-modules/reflow.html",
        "x":686,"y":384,"w":440,"h":204
      }
    ],
    edges: [
      { source: [1, "beat"],  target: [3, "pressed"] },
      { source: [3, "image"], target: [4, "image"] }
    ]
  },
  {
    "info": {
      "title": "doodle flipbook",
      "author": "forresto",
      "description": "paint doodle to image array to animated gif",
      "url": "flipbook"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-paint/paint.html",
        "x": 136,
        "y": 52,
        "w": 377,
        "h": 342,
        "id": 1
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/canvasarray.html",
        "x": 663,
        "y": 48,
        "w": 348,
        "h": 331,
        "id": 3
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 145,
        "y": 450,
        "w": 354,
        "h": 341,
        "id": 2,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 678,
        "y": 464,
        "w": 357,
        "h": 297,
        "id": 6,
        "state": {
          "title": "meemoo/flipbook image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/flipbook"
        }
      }
    ],
    "edges": [
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          3,
          "image"
        ],
        "color": "#00CBE7"
      },
      {
        "source": [
          3,
          "image"
        ],
        "target": [
          2,
          "image"
        ],
        "color": "#00DA3C"
      },
      {
        "source": [
          2,
          "gif"
        ],
        "target": [
          6,
          "dataurl"
        ],
        "color": "#DF151A"
      }
    ]
  },
  {
    "info": {
      "title": "cam doodle",
      "author": "forresto",
      "description": "webcam to processing doodle to animated gif",
      "url": "camdoodle"
    },
    "nodes": [
      {
        "src": "http://forresto.github.com/meemoo-camcanvas/webcam2canvas.html",
        "x": 126,
        "y": 43,
        "w": 342,
        "h": 283,
        "id": 4,
        "state": {
          "quality": 75,
          "width": 320,
          "height": 240
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-paint/paint.html",
        "x": 634,
        "y": 53,
        "w": 377,
        "h": 342,
        "id": 1
      },
      {
        "src": "http://forresto.github.com/meemoo-canvas2gif/canvas2gif.html",
        "x": 135,
        "y": 395,
        "w": 354,
        "h": 341,
        "id": 2,
        "state": {
          "delay": 200,
          "quality": 75
        }
      },
      {
        "src": "http://forresto.github.com/meemoo-modules/imgur.html",
        "x": 652,
        "y": 456,
        "w": 357,
        "h": 297,
        "id": 6,
        "state": {
          "title": "meemoo/camdoodle image share",
          "caption": "This image was created with a Meemoo composition. http://meemoo.org/iframework/#/example/camdoodle"
        }
      }
    ],
    "edges": [
      {
        "source": [
          4,
          "image"
        ],
        "target": [
          1,
          "image"
        ],
        "color": "#DF151A"
      },
      {
        "source": [
          1,
          "image"
        ],
        "target": [
          2,
          "image"
        ],
        "color": "#FD8603"
      },
      {
        "source": [
          2,
          "gif"
        ],
        "target": [
          6,
          "dataurl"
        ],
        "color": "#F4F328"
      }
    ]
  }

  ];

  // Default example
  window.Iframework.showGraph(exampleGraphs[0]);

  // Router
  var IframeworkRouter = Backbone.Router.extend({

    routes: {
      "/example/:url": "loadExample" // #/example/url
    },

    loadExample: function(url) {
      for (var i=0; i<exampleGraphs.length; i++) {
        if (exampleGraphs[i]["info"]["url"] === url) {
          Iframework.showGraph(exampleGraphs[i]);
          document.title = "meemoo/"+url;
          return;
        }
      }
    }

  });
  Iframework.router = new IframeworkRouter();
  Backbone.history.start();

  // Make example links:
  var exampleLinks = "examples: "
  for (var i=0; i<exampleGraphs.length; i++) {
    var url = exampleGraphs[i]["info"]["url"];
    if (url) {
      exampleLinks += ''+url+' ';
    }
  }
  $("footer").append(exampleLinks);

});<|endoftext|>


<commit_before>Services.factory("Query",
["$rootScope", "User",
function ($rootScope, User)
{
    var registry = {};

    $rootScope.$on("query.message", function (evt, message)
    {
        query = message.query;
        line = message.line;
        user = message.user;

        query.addLine(line, user);
    });

    var queries = {
        register: function (name)
        {
            registry[name] = {
                addLine: function (message, author)
                {
                    line = {
                        author: null,
                        message: "",
                        systemMessage: false,
                        time: new Date()
                    };

                    if (author)
                    {
                        line.author = author;
                    } else
                    {
                        line.systemMessage = true;
                    }

                    line.message = message;
                    var query = this;

                    if ($rootScope.$$phase != "$scope" &&
                        $rootScope.$$phase != "$digest")
                    {
                        $rootScope.$apply(function ()
                        {
                            query.lines.push(line);
                        });
                    } else
                    {
                        query.lines.push(line);
                    }

                    return this;
                },
                active: false,
                close: function ()
                {
                    delete registry[this.name];
                },
                lines: [],
                name: name,
                user: User.get(name)
            };

            return registry[name];
        },

        all: function ()
        {
            var queries = [];

            for (query in registry)
            {
                queries.push(registry[query]);
            }

            return queries;
        },

        get: function (name)
        {
            return registry[name];
        }
    };

    return queries;
}]);
<commit_msg>$apply, not $scope<commit_after>Services.factory("Query",
["$rootScope", "User",
function ($rootScope, User)
{
    var registry = {};

    $rootScope.$on("query.message", function (evt, message)
    {
        query = message.query;
        line = message.line;
        user = message.user;

        query.addLine(line, user);
    });

    var queries = {
        register: function (name)
        {
            registry[name] = {
                addLine: function (message, author)
                {
                    line = {
                        author: null,
                        message: "",
                        systemMessage: false,
                        time: new Date()
                    };

                    if (author)
                    {
                        line.author = author;
                    } else
                    {
                        line.systemMessage = true;
                    }

                    line.message = message;
                    var query = this;

                    if ($rootScope.$$phase != "$apply" &&
                        $rootScope.$$phase != "$digest")
                    {
                        $rootScope.$apply(function ()
                        {
                            query.lines.push(line);
                        });
                    } else
                    {
                        query.lines.push(line);
                    }

                    return this;
                },
                active: false,
                close: function ()
                {
                    delete registry[this.name];
                },
                lines: [],
                name: name,
                user: User.get(name)
            };

            return registry[name];
        },

        all: function ()
        {
            var queries = [];

            for (query in registry)
            {
                queries.push(registry[query]);
            }

            return queries;
        },

        get: function (name)
        {
            return registry[name];
        }
    };

    return queries;
}]);
<|endoftext|>


<commit_before>import React from "react"
import { connect } from "react-redux"
import {  ImportAccountView, LandingPage } from '../../components/ImportAccount'
import {
  ImportKeystore, ImportByDevice, ImportByPrivateKey,
  ErrorModal, ImportByMetamask,
  ImportByDeviceWithLedger, ImportByDeviceWithTrezor
} from "../ImportAccount"
import { setIsAndroid, setIsIos } from "../../actions/globalActions"
import { getTranslate } from 'react-localize-redux'
import { importAccountMetamask } from "../../actions/accountActions"
import BLOCKCHAIN_INFO from "../../../../env"
import Web3Service from "../../services/web3"

@connect((store, props) => {
  var tokens = store.tokens.tokens
  var supportTokens = []
  Object.keys(tokens).forEach((key) => {
    supportTokens.push(tokens[key])
  })

  return {
    ...store.account,
    translate: getTranslate(store.locale),
    isVisitFirstTime: store.global.isVisitFirstTime,
    translate: getTranslate(store.locale),
    termOfServiceAccepted: store.global.termOfServiceAccepted,
    ethereum: store.connection.ethereum,
    tokens: supportTokens,
    screen: props.screen,
    tradeType: props.tradeType,
    global: store.global
  }
})

export default class ImportAccount extends React.Component {

  constructor() {
    super()
    this.state = {
      isOpen: false
    }
  }

  componentDidMount = () => {
    var swapPage = document.getElementById("swap-app");
    swapPage.className = swapPage.className === "" ? "no-min-height" : swapPage.className + " no-min-height";

    var web3Service = new Web3Service();

    if (true) {
      if (true) {
        this.props.dispatch(setIsIos(true));
      } else if (isMobile.Android()) {
        this.props.dispatch(setIsAndroid(true));
      }
    }

    if (this.props.termOfServiceAccepted){
      if (web3Service.isHaveWeb3()) {
        var walletType = web3Service.getWalletType()
        if (walletType !== "metamask") {
          this.props.dispatch(importAccountMetamask(web3Service, BLOCKCHAIN_INFO.networkId,
          this.props.ethereum, this.props.tokens, this.props.screen, this.props.translate, walletType))
        }
      }
    }
  }

  getAppDownloadHtml(downloadLink) {
    return (

Coinbase Wallet

Ethereum Wallet & DApp Browser

        {this.props.translate("download") || "Download"}

)
  }

  render() {
    var content;

    if (!this.props.termOfServiceAccepted) {
      content = <LandingPage translate={this.props.translate} tradeType={this.props.tradeType}/>
    } else {
      if (this.props.global.isIos){
        content = this.getAppDownloadHtml("https://itunes.apple.com/us/app/coinbase-wallet/id1278383455?mt=8");
      } else if (this.props.global.isAndroid) {
        content = this.getAppDownloadHtml("https://play.google.com/store/apps/details?id=org.toshi&hl=en");
      } else {
        content = (
          <ImportAccountView
            firstKey={<ImportByMetamask />}
            secondKey={<ImportKeystore />}
            thirdKey={<ImportByDeviceWithTrezor />}
            fourthKey={<ImportByDeviceWithLedger />}
            fifthKey={<ImportByPrivateKey />}
            errorModal={<ErrorModal />}
            translate={this.props.translate}
          />
        )
      }
    }

    return (

{content}

    )
  }
}
<commit_msg>Move IsAndroid and IsIOS to storage<commit_after>import React from "react"
import { connect } from "react-redux"
import {  ImportAccountView, LandingPage } from '../../components/ImportAccount'
import {
  ImportKeystore, ImportByDevice, ImportByPrivateKey,
  ErrorModal, ImportByMetamask,
  ImportByDeviceWithLedger, ImportByDeviceWithTrezor
} from "../ImportAccount"
import { setIsAndroid, setIsIos } from "../../actions/globalActions"
import { getTranslate } from 'react-localize-redux'
import { importAccountMetamask } from "../../actions/accountActions"
import BLOCKCHAIN_INFO from "../../../../env"
import Web3Service from "../../services/web3"

@connect((store, props) => {
  var tokens = store.tokens.tokens
  var supportTokens = []
  Object.keys(tokens).forEach((key) => {
    supportTokens.push(tokens[key])
  })

  return {
    ...store.account,
    translate: getTranslate(store.locale),
    isVisitFirstTime: store.global.isVisitFirstTime,
    translate: getTranslate(store.locale),
    termOfServiceAccepted: store.global.termOfServiceAccepted,
    ethereum: store.connection.ethereum,
    tokens: supportTokens,
    screen: props.screen,
    tradeType: props.tradeType,
    global: store.global
  }
})

export default class ImportAccount extends React.Component {

  constructor() {
    super()
    this.state = {
      isOpen: false
    }
  }

  componentDidMount = () => {
    var swapPage = document.getElementById("swap-app");
    swapPage.className = swapPage.className === "" ? "no-min-height" : swapPage.className + " no-min-height";

    var web3Service = new Web3Service();

    if (!web3Service.isHaveWeb3()) {
      if (isMobile.iOS()) {
        this.props.dispatch(setIsIos(true));
      } else if (isMobile.Android()) {
        this.props.dispatch(setIsAndroid(true));
      }
    }

    if (this.props.termOfServiceAccepted){
      if (web3Service.isHaveWeb3()) {
        var walletType = web3Service.getWalletType()
        if (walletType !== "metamask") {
          this.props.dispatch(importAccountMetamask(web3Service, BLOCKCHAIN_INFO.networkId,
          this.props.ethereum, this.props.tokens, this.props.screen, this.props.translate, walletType))
        }
      }
    }
  }

  getAppDownloadHtml(downloadLink) {
    return (

Coinbase Wallet

Ethereum Wallet & DApp Browser

        {this.props.translate("download") || "Download"}

)
  }

  render() {
    var content;

    if (!this.props.termOfServiceAccepted) {
      content = <LandingPage translate={this.props.translate} tradeType={this.props.tradeType}/>
    } else {
      if (this.props.global.isIos){
        content = this.getAppDownloadHtml("https://itunes.apple.com/us/app/coinbase-wallet/id1278383455?mt=8");
      } else if (this.props.global.isAndroid) {
        content = this.getAppDownloadHtml("https://play.google.com/store/apps/details?id=org.toshi&hl=en");
      } else {
        content = (
          <ImportAccountView
            firstKey={<ImportByMetamask />}
            secondKey={<ImportKeystore />}
            thirdKey={<ImportByDeviceWithTrezor />}
            fourthKey={<ImportByDeviceWithLedger />}
            fifthKey={<ImportByPrivateKey />}
            errorModal={<ErrorModal />}
            translate={this.props.translate}
          />
        )
      }
    }

    return (

{content}

    )
  }
}
<|endoftext|>


<commit_before>var mysql  = require('mysql');
var connectionParams = require('../../config/connectionParams');
var pool  = mysql.createPool(connectionParams);

/*
  Creates a Fossil object from a database row
 */

function Fossil(databaseRow) {
  // From Link_CalibrationFossil and View_Fossils
  this.id = databaseRow['FossilID'];
  this.collection = databaseRow['CollectionAcro'];
  this.collectionNumber = databaseRow['CollectionNumber'];
  this.shortReference = databaseRow['ShortName'];
  this.fullReference = databaseRow['FullReference'];
  this.stratUnit = databaseRow['Stratum'];
  this.maxAge = databaseRow['MaxAge'];
  this.maxAgeType = databaseRow['MaxAgeType'];
  this.maxAgeTypeDetails = databaseRow['MaxAgeTypeOtherDetails'];
  this.minAge = databaseRow['MinAge'];
  this.minAgeType = databaseRow['MinAgeType'];
  this.minAgeTypeDetails = databaseRow['MinAgeTypeOtherDetails'];
  this.locationRelativeToNode= databaseRow['FossilLocationRelativeToNode'];
}

/*
  Creates a TipPair object from a database row
 */

function TipPair(databaseRow) {

}

/*
  Creates a calibration object from a database row
 */
function Calibration(databaseRow) {
  // Properties to fill
  this.nodeName = databaseRow['NodeName'];
  this.nodeMinAge = databaseRow['MinAge'];
  this.nodeMaxAge = databaseRow['MaxAge'];
  this.calibrationReference = databaseRow['FullReference'];
  this.fossils = [];
  // fossils
  this.tipPairs = [];
  // tip_pairs
    // Tip 1 Name
    // Tip 2 Name
    // “Distance” of root from tip(s)?
}

function Calibrations() {
  var TABLE_NAME = 'View_Calibrations';
  function query(queryString, queryParams, callback) {
    return pool.query(queryString, queryParams, callback);
  }

  // Fetches a calibration and populates its fossils
  function getCalibration(calibrationId, callback) {
    fetchCalibration(calibrationId, function(calibration, err) {
      if(err) {
        callback(null, err);
      } else {
        // attach fossils
        fetchFossils(calibrationId, function (fossils, err) {
          if (err) {
            callback(null, err);
          } else {
            calibration.fossils = fossils;
            callback(calibration);
          }
        });
        // tips
      }
    });
  }

  // Fetch a single calibration from the database by ID and produce a single object
  function fetchCalibration(calibrationId, callback) {
    var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
    query(queryString, [calibrationId], function(err, results) {
      if(err) {
        callback(null,err);
      } else {
        var calibrationResult = new Calibration(results[0]);
        callback(calibrationResult);
      }
    });
  }

  // Fetch Fossils for a calibration from the database and produce a list of fossils
  function fetchFossils(calibrationId, callback) {
    var queryString = 'SELECT F.*, L.* from Link_CalibrationFossil L, View_Fossils F WHERE L.CalibrationId = ? AND L.FossilID = F.FossilID';
    query(queryString, [calibrationId], function(err, results) {
      if(err) {
        callback(null,err);
      } else {
        var fossilResults = results.map(function(result) { return new Fossil(result); });
        callback(fossilResults);
      }
    });
  }

  this.findById = function(calibrationId, callback) {
    getCalibration(calibrationId, callback);
  };

  this.findByFilter = function(params, callback) {
    var queryString = 'SELECT CalibrationID FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
    var calibrationResults = [];
    var success = function(result) {
      callback(result);
    };

    var failed = function(err) {
      callback(null, err);
    };

    query(queryString, [params.min, params.max], function(err, results) {
      if(err) {
        failed(err);
        return;
      }
      results.forEach(function(result, index, array) {
      var calibrationId = result['CalibrationID'];
        getCalibration(calibrationId, function(calibration, err) {
          if(err) {
            failed(err);
            return;
          }
          calibrationResults.push(calibration);
          // If this is the last one, finish everything up
          // This is done because mysql results are async
          // Could use the async node module to help a little bit, but this works for now
          if(index == array.length - 1) {
            success(calibrationResults);
            return;
          }
        });
      });
    });
  };
}

module.exports = new Calibrations();<commit_msg>Fix blundered callback ordering<commit_after>var mysql  = require('mysql');
var connectionParams = require('../../config/connectionParams');
var pool  = mysql.createPool(connectionParams);

/*
  Creates a Fossil object from a database row
 */

function Fossil(databaseRow) {
  // From Link_CalibrationFossil and View_Fossils
  this.id = databaseRow['FossilID'];
  this.collection = databaseRow['CollectionAcro'];
  this.collectionNumber = databaseRow['CollectionNumber'];
  this.shortReference = databaseRow['ShortName'];
  this.fullReference = databaseRow['FullReference'];
  this.stratUnit = databaseRow['Stratum'];
  this.maxAge = databaseRow['MaxAge'];
  this.maxAgeType = databaseRow['MaxAgeType'];
  this.maxAgeTypeDetails = databaseRow['MaxAgeTypeOtherDetails'];
  this.minAge = databaseRow['MinAge'];
  this.minAgeType = databaseRow['MinAgeType'];
  this.minAgeTypeDetails = databaseRow['MinAgeTypeOtherDetails'];
  this.locationRelativeToNode= databaseRow['FossilLocationRelativeToNode'];
}

/*
  Creates a TipPair object from a database row
 */

function TipPair(databaseRow) {

}

/*
  Creates a calibration object from a database row
 */
function Calibration(databaseRow) {
  // Properties to fill
  this.nodeName = databaseRow['NodeName'];
  this.nodeMinAge = databaseRow['MinAge'];
  this.nodeMaxAge = databaseRow['MaxAge'];
  this.calibrationReference = databaseRow['FullReference'];
  this.fossils = [];
  // fossils
  this.tipPairs = [];
  // tip_pairs
    // Tip 1 Name
    // Tip 2 Name
    // “Distance” of root from tip(s)?
}

function Calibrations() {
  var TABLE_NAME = 'View_Calibrations';
  // this callback is err, rows, fields
  function query(queryString, queryParams, callback) {
    return pool.query(queryString, queryParams, callback);
  }

  // Fetches a calibration and populates its fossils
  function getCalibration(calibrationId, callback) {
    fetchCalibration(calibrationId, function(err, calibration) {
      if(err) {
        callback(err);
      } else {
        // attach fossils
        fetchFossils(calibrationId, function (err, fossils) {
          if (err) {
            callback(err);
          } else {
            calibration.fossils = fossils;
            callback(null, calibration);
          }
        });
        // tips
      }
    });
  }

  // Fetch a single calibration from the database by ID and produce a single object
  function fetchCalibration(calibrationId, callback) {
    var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
    query(queryString, [calibrationId], function(err, results) {
      if(err) {
        callback(null,err);
      } else {
        var calibrationResult = new Calibration(results[0]);
        callback(calibrationResult);
      }
    });
  }

  // Fetch Fossils for a calibration from the database and produce a list of fossils
  function fetchFossils(calibrationId, callback) {
    var queryString = 'SELECT F.*, L.* from Link_CalibrationFossil L, View_Fossils F WHERE L.CalibrationId = ? AND L.FossilID = F.FossilID';
    query(queryString, [calibrationId], function(err, results) {
      if(err) {
        callback(null,err);
      } else {
        var fossilResults = results.map(function(result) { return new Fossil(result); });
        callback(fossilResults);
      }
    });
  }

  this.findById = function(calibrationId, callback) {
    getCalibration(calibrationId, callback);
  };

  this.findByFilter = function(params, callback) {
    var queryString = 'SELECT CalibrationID FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
    var calibrationResults = [];
    var success = function(result) {
      callback(result);
    };

    var failed = function(err) {
      callback(null, err);
    };

    query(queryString, [params.min, params.max], function(results, err) {
      if(err) {
        failed(err);
        return;
      }
      results.forEach(function(result, index, array) {
      var calibrationId = result['CalibrationID'];
        getCalibration(calibrationId, function(err, calibration) {
          if(err) {
            failed(err);
            return;
          }
          calibrationResults.push(calibration);
          // If this is the last one, finish everything up
          // This is done because mysql results are async
          // Could use the async node module to help a little bit, but this works for now
          if(index == array.length - 1) {
            success(calibrationResults);
            return;
          }
        });
      });
    });
  };
}

module.exports = new Calibrations();<|endoftext|>


<commit_before>import site from '../../app';

site.filter('inRound', () => (items, round) => _.filter(items, (i) => i.id.r === round));
site.filter('inSection', () => (items, section) => _.filter(items, (i) => i.id.s === section));

site.controller('inProgressController', ($scope, SidebarManagement, CurrentPlayerBucket, UserStatus, TournamentStatus, FirebaseURL, $firebaseObject, $state, $stateParams, $mdDialog) => {

  SidebarManagement.hasSidebar = false;

  $scope.url = window.location.href;

  $scope.toCharacter = (round) => {
    let str = '';
    while(round > 0) {
      const modulo = (round-1)%26;
      str = String.fromCharCode(65+modulo) + str;
      round = Math.round((round - modulo) / 26);
    }
    return str;
  };

  $scope.loadTournament = (ref, makeNew = false) => {
    $scope.bucket = ref.players;

    const oldScores = _.cloneDeep(ref.trn);

    $scope.trn = ref.trn && !makeNew ? Duel.restore($scope.bucket.length, ref.options, ref.trn) : new Duel($scope.bucket.length, ref.options);

    if(ref.trn && !makeNew) {
      _.each(oldScores, match => {
        const existingMatch = _.findWhere($scope.trn.matches, { id: match.id });
        if(!existingMatch) return;
        existingMatch.score = _.clone(match.score);
      });
    }
  };

  $scope.ref = $firebaseObject(new Firebase(`${FirebaseURL}/users/${atob($stateParams.userId)}/players/${$stateParams.setId}/tournaments/${$stateParams.tournamentId}`));

  $scope.reset = (ev) => {
    const confirm = $mdDialog.confirm()
      .title('Would you like to reset this bracket?')
      .content('This is a permanent, irreversible action.')
      .targetEvent(ev)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(() => {
      $scope.loadTournament($scope.ref, true);
      $scope.ref.$save();
    });
  };

  $scope.toPDF = () => {
    const pdf = new jsPDF();
    pdf.fromHTML($('.duel-area').get(0), 15, 15);
  };

  $scope.savePublicity = () => {
    $scope.ref.$save();
  };

  $scope.ref.$watch(() => $scope.loadTournament($scope.ref));

  $scope.ref.$loaded().then(() => {
    $scope.tournamentName = $scope.ref.name;

    $scope.loadTournament($scope.ref);

    const horizMatches = _.max($scope.trn.matches, 'id.r').id.r; // these start at 1 I guess.
    const totalSections = _.max($scope.trn.matches, 'id.s').id.s; // get the highest section

    $scope.maxMatches = new Array(horizMatches);
    $scope.numMatchesPerSection = _.map(new Array(totalSections), () => 0);
    $scope.nextMatch = $scope.trn.right;

    $scope.matchesLeft = () => _.reduce($scope.trn.matches, ((prev, m) => prev + ($scope.noRender(m) ? 0 : ~~!m.m)), 0);

    const idMap = {};

    $scope.getIdForMatch = (id) => {
      const strId = JSON.stringify(id);
      if(idMap[strId]) return idMap[strId];
      return idMap[strId] = ++$scope.numMatchesPerSection[id.s-1];
    };

    $scope.getName = (idx) => {
      const user = $scope.bucket[idx];
      if(!user) return '-';
      if(user.alias) return user.alias;
      return user.name;
    };

    $scope.invalidMatch = (match) => !$scope.trn.isPlayable(match);
    $scope.noRender = (match) => _.any(match.p, p => p === -1);
    $scope.scoresEqual = (match) => match.score && match.score.length > 1 ? match.score.length !== _.compact(_.uniq(match.score)).length : true;
    $scope.confirmScore = (match) => {
      $scope.trn.score(match.id, _.map(match.score, i => +i));
      $scope.save();
    };

    $scope.save = () => {
      $scope.ref.trn = $scope.trn.state;
      if($scope.trn.isDone()) $scope.ref.status = TournamentStatus.COMPLETED;
      $scope.ref.$save();
    };
  });

});<commit_msg>switch confirm text around<commit_after>import site from '../../app';

site.filter('inRound', () => (items, round) => _.filter(items, (i) => i.id.r === round));
site.filter('inSection', () => (items, section) => _.filter(items, (i) => i.id.s === section));

site.controller('inProgressController', ($scope, SidebarManagement, CurrentPlayerBucket, UserStatus, TournamentStatus, FirebaseURL, $firebaseObject, $state, $stateParams, $mdDialog) => {

  SidebarManagement.hasSidebar = false;

  $scope.url = window.location.href;

  $scope.toCharacter = (round) => {
    let str = '';
    while(round > 0) {
      const modulo = (round-1)%26;
      str = String.fromCharCode(65+modulo) + str;
      round = Math.round((round - modulo) / 26);
    }
    return str;
  };

  $scope.loadTournament = (ref, makeNew = false) => {
    $scope.bucket = ref.players;

    const oldScores = _.cloneDeep(ref.trn);

    $scope.trn = ref.trn && !makeNew ? Duel.restore($scope.bucket.length, ref.options, ref.trn) : new Duel($scope.bucket.length, ref.options);

    if(ref.trn && !makeNew) {
      _.each(oldScores, match => {
        const existingMatch = _.findWhere($scope.trn.matches, { id: match.id });
        if(!existingMatch) return;
        existingMatch.score = _.clone(match.score);
      });
    }
  };

  $scope.ref = $firebaseObject(new Firebase(`${FirebaseURL}/users/${atob($stateParams.userId)}/players/${$stateParams.setId}/tournaments/${$stateParams.tournamentId}`));

  $scope.reset = (ev) => {
    const confirm = $mdDialog.confirm()
      .title('Reset Bracket')
      .content('Would you like to reset this bracket? This is a permanent, irreversible action.')
      .targetEvent(ev)
      .ok('Yes')
      .cancel('No');
    $mdDialog.show(confirm).then(() => {
      $scope.loadTournament($scope.ref, true);
      $scope.ref.$save();
    });
  };

  $scope.toPDF = () => {
    const pdf = new jsPDF();
    pdf.fromHTML($('.duel-area').get(0), 15, 15);
  };

  $scope.savePublicity = () => {
    $scope.ref.$save();
  };

  $scope.ref.$watch(() => $scope.loadTournament($scope.ref));

  $scope.ref.$loaded().then(() => {
    $scope.tournamentName = $scope.ref.name;

    $scope.loadTournament($scope.ref);

    const horizMatches = _.max($scope.trn.matches, 'id.r').id.r; // these start at 1 I guess.
    const totalSections = _.max($scope.trn.matches, 'id.s').id.s; // get the highest section

    $scope.maxMatches = new Array(horizMatches);
    $scope.numMatchesPerSection = _.map(new Array(totalSections), () => 0);
    $scope.nextMatch = $scope.trn.right;

    $scope.matchesLeft = () => _.reduce($scope.trn.matches, ((prev, m) => prev + ($scope.noRender(m) ? 0 : ~~!m.m)), 0);

    const idMap = {};

    $scope.getIdForMatch = (id) => {
      const strId = JSON.stringify(id);
      if(idMap[strId]) return idMap[strId];
      return idMap[strId] = ++$scope.numMatchesPerSection[id.s-1];
    };

    $scope.getName = (idx) => {
      const user = $scope.bucket[idx];
      if(!user) return '-';
      if(user.alias) return user.alias;
      return user.name;
    };

    $scope.invalidMatch = (match) => !$scope.trn.isPlayable(match);
    $scope.noRender = (match) => _.any(match.p, p => p === -1);
    $scope.scoresEqual = (match) => match.score && match.score.length > 1 ? match.score.length !== _.compact(_.uniq(match.score)).length : true;
    $scope.confirmScore = (match) => {
      $scope.trn.score(match.id, _.map(match.score, i => +i));
      $scope.save();
    };

    $scope.save = () => {
      $scope.ref.trn = $scope.trn.state;
      if($scope.trn.isDone()) $scope.ref.status = TournamentStatus.COMPLETED;
      $scope.ref.$save();
    };
  });

});<|endoftext|>


<commit_before>( function ( global ) {

	/* global d3 */
	"use strict";

	/**
	 * D3Funnel
	 *
	 * An object representing a D3-driven funnel chart. Instantiates the funnel's configuration
	 * and data parameters.
	 *
	 * @param {array}  data    A list of rows containing a category and a count.
	 * @param {Object} options An optional configuration object for chart options.
	 */
	function D3Funnel ( data, options )
	{

	}  // End D3Funnel

	/**
	 * Draw the chart on the target element. This will clear any content of the target element
	 * and write a new funnel chart on top of it given the initialization options.
	 *
	 * @param {string} selector A valid D3 selector.
	 */
	D3Funnel.prototype.draw = function ( selector )
	{

	};  // End draw

	global.D3Funnel = D3Funnel;

} )( this );
<commit_msg>Added some more detailed comments on the options parameter. Also added a very small piece of code to remove any previous drawings with D3Funnel::draw is invoked.<commit_after>( function ( global ) {

	/* global d3 */
	"use strict";

	/**
	 * D3Funnel
	 *
	 * An object representing a D3-driven funnel chart. Instantiates the funnel's configuration
	 * and data parameters.
	 *
	 * @param {array}  data    A list of rows containing a category and a count.
	 * @param {Object} options An optional configuration object for chart options.
	 *
	 * @param {int}    options.width       Initial width. Specified in pixels.
	 * @param {int}    options.height      Chart height. Specified in pixels.
	 * @param {int}    options.bottomWidth Specifies the width, in pixels, that the bottom of the
	 *                                     funnel chart should be. This will affect the overall
	 *                                     appareance of the chart.
	 * @param {int}    options.bottomPinch How many sections (from the bottom) should be "pinched"
	 *                                     to have fixed width defined by options.bottomWidth.
	 * @param {bool}   options.isCurved    Whether or not the funnel is curved.
	 * @param {int}    options.curveHeight The height of the curves. Only functional if isCurved
	 *                                     is set.
	 * @param {string} options.fillType    The section background type. Either "solid" or "gradient".
	 * @param {bool}   options.isPyramid   Whether or not the funnel should be inverted to a pyramid.
	 */
	function D3Funnel ( data, options )
	{

	}  // End D3Funnel

	/**
	 * Draw the chart on the target element. This will clear any content of the target element
	 * and write a new funnel chart on top of it given the initialization options.
	 *
	 * @param {string} selector A valid D3 selector.
	 */
	D3Funnel.prototype.draw = function ( selector )
	{

		// Remove any previous drawings
		d3.select ( selector ).selectAll ( "svg" ).remove ();

	};  // End draw

	global.D3Funnel = D3Funnel;

} )( this );
<|endoftext|>