<commit_before>const webpackConfig = require('./webpack.config.js')
const webpackProdConfig = require('./webpack.prod.config.js')

/* eslint global-require: "off" */
module.exports = function exports(grunt) {
  // Project configuration.
  grunt.initConfig({
    autoprefixer: {
      options: {
        browsers: ['last 2 versions', 'ie >= 9', 'and_chr >= 2.3']
      },
      your_target: {
        src: 'temp/css/*.css'
      }
    },
    browserSync: {
      dev: {
        bsFiles: {
          src: ['dist/', 'source/templates/']
        },
        options: {
          open: false,
          proxy: 'localhost:4000',
          reloadDelay: 2000
        }
      }
    },
    clean: {
      dist: 'dist',
      temp: 'temp'
    },
    concurrent: {
      dev: {
        tasks: ['nodemon', 'watch', 'browserSync'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    copy: {
      css: {
        files: [
          {
            expand: true,
            cwd: 'source/static/css',
            src: ['**'],
            dest: 'temp/css'
          }
        ]
      },
      content: {
        files: [
          {
            expand: true,
            cwd: 'source/static/content',
            src: ['**'],
            dest: 'dist/content'
          }
        ]
      },
      html: {
        files: [
          {
            expand: true,
            cwd: 'source/static/html',
            src: ['**'],
            dest: 'dist/html'
          }
        ]
      },
      images: {
        files: [
          {
            expand: true,
            cwd: 'source/static/images',
            src: ['**'],
            dest: 'dist/images'
          }
        ]
      }
    },
    cssmin: {
      target: {
        files: [{
          src: 'temp/css/*.css',
          dest: 'dist/css/main.min.css'
        }]
      }
    },
    nodemon: {
      dev: {
        script: 'server/index.js',
        options: {
          exec: 'babel-node',
          env: {
            PORT: '4000'
          }
        }
      }
    },
    sass: {
      dist: {
        files: {
          'temp/css/main.css': 'source/sass/main.scss'
        }
      }
    },
    uglify: {
      my_target: {
        files: {
          'dist/scripts/bundle.min.js': ['temp/scripts/bundle.js']
        }
      }
    },
    webpack: {
      dev: webpackConfig,
      prod: webpackProdConfig
    },

    // Watch for any changes and call associated task
    watch: {
      options: {
        event: ['changed', 'added', 'deleted']
      },
      css: {
        files: ['source/static/css/*.css', 'source/sass/**/*.scss'],
        tasks: ['sass', 'copy:css', 'autoprefixer',
          'cssmin', 'clean:temp']
      },
      static: {
        files: 'source/static/**/*',
        tasks: ['copy']
      },
      scripts: {
        files: ['source/scripts/**/*'],
        tasks: ['webpack:dev', 'clean:temp']
      }
    }
  })

  // Load plugins
  grunt.loadNpmTasks('grunt-contrib-clean')
  grunt.loadNpmTasks('grunt-contrib-copy')
  grunt.loadNpmTasks('grunt-contrib-cssmin')
  grunt.loadNpmTasks('grunt-contrib-sass')
  grunt.loadNpmTasks('grunt-contrib-uglify')
  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-autoprefixer')
  grunt.loadNpmTasks('grunt-browser-sync')
  grunt.loadNpmTasks('grunt-concurrent')
  grunt.loadNpmTasks('grunt-nodemon')
  grunt.loadNpmTasks('grunt-webpack')

  // Default task
  grunt.registerTask('default', ['sass', 'copy', 'webpack:dev', 'autoprefixer',
    'cssmin', 'clean:temp', 'concurrent'])

  // Load concurrent tasks without initial build
  grunt.registerTask('start', ['concurrent'])

  // Production build
  grunt.registerTask('buildProd', ['clean:dist', 'sass', 'copy', 'webpack:prod',
    'autoprefixer', 'cssmin', 'uglify', 'clean:temp'])

  // Production build
  grunt.registerTask('buildDev', ['clean:dist', 'sass', 'copy', 'webpack:prod',
    'autoprefixer', 'cssmin', 'uglify', 'clean:temp'])

  // Wipe dist and then watch
  grunt.registerTask('cleanWatch', ['clean:dist', 'default'])
}
<commit_msg>No uglify on dev<commit_after>const webpackConfig = require('./webpack.config.js')
const webpackProdConfig = require('./webpack.prod.config.js')

/* eslint global-require: "off" */
module.exports = function exports(grunt) {
  // Project configuration.
  grunt.initConfig({
    autoprefixer: {
      options: {
        browsers: ['last 2 versions', 'ie >= 9', 'and_chr >= 2.3']
      },
      your_target: {
        src: 'temp/css/*.css'
      }
    },
    browserSync: {
      dev: {
        bsFiles: {
          src: ['dist/', 'source/templates/']
        },
        options: {
          open: false,
          proxy: 'localhost:4000',
          reloadDelay: 2000
        }
      }
    },
    clean: {
      dist: 'dist',
      temp: 'temp'
    },
    concurrent: {
      dev: {
        tasks: ['nodemon', 'watch', 'browserSync'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    copy: {
      css: {
        files: [
          {
            expand: true,
            cwd: 'source/static/css',
            src: ['**'],
            dest: 'temp/css'
          }
        ]
      },
      content: {
        files: [
          {
            expand: true,
            cwd: 'source/static/content',
            src: ['**'],
            dest: 'dist/content'
          }
        ]
      },
      html: {
        files: [
          {
            expand: true,
            cwd: 'source/static/html',
            src: ['**'],
            dest: 'dist/html'
          }
        ]
      },
      images: {
        files: [
          {
            expand: true,
            cwd: 'source/static/images',
            src: ['**'],
            dest: 'dist/images'
          }
        ]
      }
    },
    cssmin: {
      target: {
        files: [{
          src: 'temp/css/*.css',
          dest: 'dist/css/main.min.css'
        }]
      }
    },
    nodemon: {
      dev: {
        script: 'server/index.js',
        options: {
          exec: 'babel-node',
          env: {
            PORT: '4000'
          }
        }
      }
    },
    sass: {
      dist: {
        files: {
          'temp/css/main.css': 'source/sass/main.scss'
        }
      }
    },
    uglify: {
      my_target: {
        files: {
          'dist/scripts/bundle.min.js': ['temp/scripts/bundle.js']
        }
      }
    },
    webpack: {
      dev: webpackConfig,
      prod: webpackProdConfig
    },

    // Watch for any changes and call associated task
    watch: {
      options: {
        event: ['changed', 'added', 'deleted']
      },
      css: {
        files: ['source/static/css/*.css', 'source/sass/**/*.scss'],
        tasks: ['sass', 'copy:css', 'autoprefixer',
          'cssmin', 'clean:temp']
      },
      static: {
        files: 'source/static/**/*',
        tasks: ['copy']
      },
      scripts: {
        files: ['source/scripts/**/*'],
        tasks: ['webpack:dev', 'clean:temp']
      }
    }
  })

  // Load plugins
  grunt.loadNpmTasks('grunt-contrib-clean')
  grunt.loadNpmTasks('grunt-contrib-copy')
  grunt.loadNpmTasks('grunt-contrib-cssmin')
  grunt.loadNpmTasks('grunt-contrib-sass')
  grunt.loadNpmTasks('grunt-contrib-uglify')
  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-autoprefixer')
  grunt.loadNpmTasks('grunt-browser-sync')
  grunt.loadNpmTasks('grunt-concurrent')
  grunt.loadNpmTasks('grunt-nodemon')
  grunt.loadNpmTasks('grunt-webpack')

  // Default task
  grunt.registerTask('default', ['sass', 'copy', 'webpack:dev', 'autoprefixer',
    'cssmin', 'clean:temp', 'concurrent'])

  // Load concurrent tasks without initial build
  grunt.registerTask('start', ['concurrent'])

  // Production build
  grunt.registerTask('buildProd', ['clean:dist', 'sass', 'copy', 'webpack:prod',
    'autoprefixer', 'cssmin', 'uglify', 'clean:temp'])

  // Production build
  grunt.registerTask('buildDev', ['clean:dist', 'sass', 'copy', 'webpack:prod',
    'autoprefixer', 'cssmin', 'clean:temp'])

  // Wipe dist and then watch
  grunt.registerTask('cleanWatch', ['clean:dist', 'default'])
}
<|endoftext|>


<commit_before>module.exports = function(grunt)
{

    'use strict';

    var async = require('async');
    var exec = require('child_process').exec;
    var fs = require('fs');
    var manifest = eval('(' + fs.readFileSync('app.nw/package.json', {encoding: 'utf8'}) + ')');
    var source_app = '/Applications/node-webkit.app';
    var app_name = 'namagic.app'; // No capital letters allowed ? Makes the app crash when signed
    var identity = 'LK7U6U8DZ4' // @todo move this elsewhere
    var bundle_id = manifest.bundle_identifier;

    /**
     * Runs the app
     * Use the "--dev" option to enable toolbars and debug
     */
    grunt.registerTask('run', function()
    {
        setDevMode(grunt.option('dev') === true);
        var done = this.async();
        var child = exec(source_app + 'app.nw');
        child.stdout.on('data', grunt.log.write);
        child.stderr.on('data', grunt.log.write);
        child.on('close', done);
    });

    /**
     * Builds the app
     */
    grunt.registerTask('build', function()
    {
        var done = this.async();
        setDevMode(false);
        var series = [
            function(callback)
            {
                grunt.log.writeln('Cleaning...');
                exec('rm -r .mas; mkdir .mas', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Creating empty application...');
                exec('cp -r ' + source_app + ' .mas/' + app_name, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing plist...');
                var plist = fs.readFileSync('assets/plist/info.plist', {encoding: 'utf8'});
                for (var property in manifest)
                {
                    var regex = new RegExp('{{' + property + '}}', 'g');
                    plist = plist.replace(regex, manifest[property]);
                }
                fs.writeFile('.mas/' + app_name + '/Contents/Info.plist', plist, {encoding: 'utf8'}, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing icon...');
                exec('cp assets/icns/icon.icns .mas/' + app_name + '/Contents/Resources/nw.icns', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Updating helpers...');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app');
                callback();
            },
            function(callback)
            {
                grunt.log.writeln('Installing app files...');
                exec('cp -r app.nw .mas/' + app_name + '/Contents/Resources', callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Signs the app
     */
    grunt.registerTask('sign', function()
    {
        var done = this.async();
        var series = [
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper EH.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper NP.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing app...');
                exec(signCommand('assets/entitlements/parent.plist', '.mas/' + app_name), callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Gets a codesign command
     * @param entitlement_path
     * @param app_path
     */
    function signCommand(entitlement_path, app_path)
    {
        return 'codesign --deep -s ' + identity + ' -i ' + bundle_id + ' --entitlements ' + entitlement_path + ' "' + app_path + '"';
    }

    /**
     * Updates the Info.plist file of the needed helper app
     * @param helper_path
     */
    function updateHelperPlist(helper_path)
    {
        var plist = fs.readFileSync(helper_path + '/Contents/Info.plist', {encoding: 'utf8'});
        plist = plist.replace(/<key>CFBundleIdentifier<\/key>[^\/]*\/string>/g, '<key>CFBundleIdentifier<\/key>\n	<string>' + bundle_id + '</string>');
        fs.writeFileSync(helper_path + '/Contents/Info.plist', plist, {encoding: 'utf8'});
    }

    /**
     * Toggles dev mode
     * @param enable
     */
    function setDevMode(enable)
    {
        grunt.file.write('./app.nw/.dev', enable ? '1' : '0', {encoding: 'utf8'});
    }

};<commit_msg>Fixes run task<commit_after>module.exports = function(grunt)
{

    'use strict';

    var async = require('async');
    var exec = require('child_process').exec;
    var fs = require('fs');
    var manifest = eval('(' + fs.readFileSync('app.nw/package.json', {encoding: 'utf8'}) + ')');
    var source_app = '/Applications/node-webkit.app';
    var app_name = 'namagic.app'; // No capital letters allowed ? Makes the app crash when signed
    var identity = 'LK7U6U8DZ4' // @todo move this elsewhere
    var bundle_id = manifest.bundle_identifier;

    /**
     * Runs the app
     * Use the "--dev" option to enable toolbars and debug
     */
    grunt.registerTask('run', function()
    {
        setDevMode(grunt.option('dev') === true);
        var done = this.async();
        var child = exec(source_app + '/Contents/MacOS/node-webkit app.nw');
        child.stdout.on('data', grunt.log.write);
        child.stderr.on('data', grunt.log.write);
        child.on('close', done);
    });

    /**
     * Builds the app
     */
    grunt.registerTask('build', function()
    {
        var done = this.async();
        setDevMode(false);
        var series = [
            function(callback)
            {
                grunt.log.writeln('Cleaning...');
                exec('rm -r .mas; mkdir .mas', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Creating empty application...');
                exec('cp -r ' + source_app + ' .mas/' + app_name, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing plist...');
                var plist = fs.readFileSync('assets/plist/info.plist', {encoding: 'utf8'});
                for (var property in manifest)
                {
                    var regex = new RegExp('{{' + property + '}}', 'g');
                    plist = plist.replace(regex, manifest[property]);
                }
                fs.writeFile('.mas/' + app_name + '/Contents/Info.plist', plist, {encoding: 'utf8'}, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing icon...');
                exec('cp assets/icns/icon.icns .mas/' + app_name + '/Contents/Resources/nw.icns', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Updating helpers...');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app');
                callback();
            },
            function(callback)
            {
                grunt.log.writeln('Installing app files...');
                exec('cp -r app.nw .mas/' + app_name + '/Contents/Resources', callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Signs the app
     */
    grunt.registerTask('sign', function()
    {
        var done = this.async();
        var series = [
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper EH.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper NP.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing app...');
                exec(signCommand('assets/entitlements/parent.plist', '.mas/' + app_name), callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Gets a codesign command
     * @param entitlement_path
     * @param app_path
     */
    function signCommand(entitlement_path, app_path)
    {
        return 'codesign --deep -s ' + identity + ' -i ' + bundle_id + ' --entitlements ' + entitlement_path + ' "' + app_path + '"';
    }

    /**
     * Updates the Info.plist file of the needed helper app
     * @param helper_path
     */
    function updateHelperPlist(helper_path)
    {
        var plist = fs.readFileSync(helper_path + '/Contents/Info.plist', {encoding: 'utf8'});
        plist = plist.replace(/<key>CFBundleIdentifier<\/key>[^\/]*\/string>/g, '<key>CFBundleIdentifier<\/key>\n	<string>' + bundle_id + '</string>');
        fs.writeFileSync(helper_path + '/Contents/Info.plist', plist, {encoding: 'utf8'});
    }

    /**
     * Toggles dev mode
     * @param enable
     */
    function setDevMode(enable)
    {
        grunt.file.write('./app.nw/.dev', enable ? '1' : '0', {encoding: 'utf8'});
    }

};<|endoftext|>


<commit_before>d3.sankey = function() {
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [],
      sinksRight = true;

  sankey.nodeWidth = function(_) {
    if (!arguments.length) return nodeWidth;
    nodeWidth = +_;
    return sankey;
  };

  sankey.nodePadding = function(_) {
    if (!arguments.length) return nodePadding;
    nodePadding = +_;
    return sankey;
  };

  sankey.nodes = function(_) {
    if (!arguments.length) return nodes;
    nodes = _;
    return sankey;
  };

  sankey.links = function(_) {
    if (!arguments.length) return links;
    links = _;
    return sankey;
  };

  sankey.size = function(_) {
    if (!arguments.length) return size;
    size = _;
    return sankey;
  };

 sankey.sinksRight = function (_) {
    if (!arguments.length) return sinksRight;
    sinksRight = _;
    return sankey;
 };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    computeLinkDepths();
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  // SVG path data generator, to be used as "d" attribute on "path" element selection.
  sankey.link = function() {
    var curvature = .5;

    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3.interpolateNumber(x0, x1),
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0 = d.source.y + d.sy + d.dy / 2,
          y1 = d.target.y + d.ty + d.dy / 2;
      return "M" + x0 + "," + y0
           + "C" + x2 + "," + y0
           + " " + x3 + "," + y1
           + " " + x1 + "," + y1;
    }

    link.curvature = function(_) {
      if (!arguments.length) return curvature;
      curvature = +_;
      return link;
    };

    return link;
  };

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      // Links that have this node as source.
      node.sourceLinks = [];
      // Links that have this node as target.
      node.targetLinks = [];
    });
    links.forEach(function(link) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") source = link.source = nodes[link.source];
      if (typeof target === "number") target = link.target = nodes[link.target];
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    nodes.forEach(function(node) {
      node.value = Math.max(
        d3.sum(node.sourceLinks, value),
        d3.sum(node.targetLinks, value)
      );
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    // Work from left to right.
    // Keep updating the breath (x-position) of nodes that are target of recently updated nodes.
    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          if (nextNodes.indexOf(link.target) < 0) {
            nextNodes.push(link.target);
          }
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    // Optionally move pure sinks always to the right.
    if (sinksRight) {
      moveSinksRight(x);
    }

    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
      }
    });
  }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  // Compute the depth (y-position) for each node.
  function computeNodeDepths(iterations) {
    // Group nodes by breath.
    var nodesByBreadth = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    //
    initializeNodeDepth();
    resolveCollisions();
    for (var alpha = 1; iterations > 0; --iterations) {
      relaxRightToLeft(alpha *= .99);
      resolveCollisions();
      relaxLeftToRight(alpha);
      resolveCollisions();
    }

    function initializeNodeDepth() {
      // Calculate vertical scaling factor.
      var ky = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function relaxLeftToRight(alpha) {
      nodesByBreadth.forEach(function(nodes, breadth) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            // Value-weighted average of the y-position of source node centers linked to this node.
            var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedSource(link) {
        return center(link.source) * link.value;
      }
    }

    function relaxRightToLeft(alpha) {
      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            // Value-weighted average of the y-positions of target nodes linked to this node.
            var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedTarget(link) {
        return center(link.target) * link.value;
      }
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; ++i) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) node.y += dy;
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; --i) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) node.y -= dy;
            y0 = node.y;
          }
        }
      });
    }

    function ascendingDepth(a, b) {
      return a.y - b.y;
    }
  }

  // Compute y-offset of the source endpoint (sy) and target endpoints (ty) of links,
  // relative to the source/target node's y-position.
  function computeLinkDepths() {
    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });

    function ascendingSourceDepth(a, b) {
      return a.source.y - b.source.y;
    }

    function ascendingTargetDepth(a, b) {
      return a.target.y - b.target.y;
    }
  }

  // Y-position of the middle of a node.
  function center(node) {
    return node.y + node.dy / 2;
  }

  // Value property accessor.
  function value(x) {
    return x.value;
  }

  return sankey;
};
<commit_msg>Fixes #2: Layout algorithm optimisation: take link depth into account instead of whole node size<commit_after>d3.sankey = function() {
  var sankey = {},
      nodeWidth = 24,
      nodePadding = 8,
      size = [1, 1],
      nodes = [],
      links = [],
      sinksRight = true;

  sankey.nodeWidth = function(_) {
    if (!arguments.length) return nodeWidth;
    nodeWidth = +_;
    return sankey;
  };

  sankey.nodePadding = function(_) {
    if (!arguments.length) return nodePadding;
    nodePadding = +_;
    return sankey;
  };

  sankey.nodes = function(_) {
    if (!arguments.length) return nodes;
    nodes = _;
    return sankey;
  };

  sankey.links = function(_) {
    if (!arguments.length) return links;
    links = _;
    return sankey;
  };

  sankey.size = function(_) {
    if (!arguments.length) return size;
    size = _;
    return sankey;
  };

 sankey.sinksRight = function (_) {
    if (!arguments.length) return sinksRight;
    sinksRight = _;
    return sankey;
 };

  sankey.layout = function(iterations) {
    computeNodeLinks();
    computeNodeValues();
    computeNodeBreadths();
    computeNodeDepths(iterations);
    return sankey;
  };

  sankey.relayout = function() {
    computeLinkDepths();
    return sankey;
  };

  // SVG path data generator, to be used as "d" attribute on "path" element selection.
  sankey.link = function() {
    var curvature = .5;

    function link(d) {
      var x0 = d.source.x + d.source.dx,
          x1 = d.target.x,
          xi = d3.interpolateNumber(x0, x1),
          x2 = xi(curvature),
          x3 = xi(1 - curvature),
          y0 = d.source.y + d.sy + d.dy / 2,
          y1 = d.target.y + d.ty + d.dy / 2;
      return "M" + x0 + "," + y0
           + "C" + x2 + "," + y0
           + " " + x3 + "," + y1
           + " " + x1 + "," + y1;
    }

    link.curvature = function(_) {
      if (!arguments.length) return curvature;
      curvature = +_;
      return link;
    };

    return link;
  };

  // Populate the sourceLinks and targetLinks for each node.
  // Also, if the source and target are not objects, assume they are indices.
  function computeNodeLinks() {
    nodes.forEach(function(node) {
      // Links that have this node as source.
      node.sourceLinks = [];
      // Links that have this node as target.
      node.targetLinks = [];
    });
    links.forEach(function(link) {
      var source = link.source,
          target = link.target;
      if (typeof source === "number") source = link.source = nodes[link.source];
      if (typeof target === "number") target = link.target = nodes[link.target];
      source.sourceLinks.push(link);
      target.targetLinks.push(link);
    });
  }

  // Compute the value (size) of each node by summing the associated links.
  function computeNodeValues() {
    nodes.forEach(function(node) {
      node.value = Math.max(
        d3.sum(node.sourceLinks, value),
        d3.sum(node.targetLinks, value)
      );
    });
  }

  // Iteratively assign the breadth (x-position) for each node.
  // Nodes are assigned the maximum breadth of incoming neighbors plus one;
  // nodes with no incoming links are assigned breadth zero, while
  // nodes with no outgoing links are assigned the maximum breadth.
  function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    // Work from left to right.
    // Keep updating the breath (x-position) of nodes that are target of recently updated nodes.
    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          if (nextNodes.indexOf(link.target) < 0) {
            nextNodes.push(link.target);
          }
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    // Optionally move pure sinks always to the right.
    if (sinksRight) {
      moveSinksRight(x);
    }

    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }

  function moveSourcesRight() {
    nodes.forEach(function(node) {
      if (!node.targetLinks.length) {
        node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
      }
    });
  }

  function moveSinksRight(x) {
    nodes.forEach(function(node) {
      if (!node.sourceLinks.length) {
        node.x = x - 1;
      }
    });
  }

  function scaleNodeBreadths(kx) {
    nodes.forEach(function(node) {
      node.x *= kx;
    });
  }

  // Compute the depth (y-position) for each node.
  function computeNodeDepths(iterations) {
    // Group nodes by breath.
    var nodesByBreadth = d3.nest()
        .key(function(d) { return d.x; })
        .sortKeys(d3.ascending)
        .entries(nodes)
        .map(function(d) { return d.values; });

    //
    initializeNodeDepth();
    resolveCollisions();
    computeLinkDepths();
    for (var alpha = 1; iterations > 0; --iterations) {
      relaxRightToLeft(alpha *= .99);
      resolveCollisions();
      computeLinkDepths();
      relaxLeftToRight(alpha);
      resolveCollisions();
      computeLinkDepths();
    }

    function initializeNodeDepth() {
      // Calculate vertical scaling factor.
      var ky = d3.min(nodesByBreadth, function(nodes) {
        return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
      });

      nodesByBreadth.forEach(function(nodes) {
        nodes.forEach(function(node, i) {
          node.y = i;
          node.dy = node.value * ky;
        });
      });

      links.forEach(function(link) {
        link.dy = link.value * ky;
      });
    }

    function relaxLeftToRight(alpha) {
      nodesByBreadth.forEach(function(nodes, breadth) {
        nodes.forEach(function(node) {
          if (node.targetLinks.length) {
            // Value-weighted average of the y-position of source node centers linked to this node.
            var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedSource(link) {
        return (link.source.y + link.sy + link.dy / 2) * link.value;
      }
    }

    function relaxRightToLeft(alpha) {
      nodesByBreadth.slice().reverse().forEach(function(nodes) {
        nodes.forEach(function(node) {
          if (node.sourceLinks.length) {
            // Value-weighted average of the y-positions of target nodes linked to this node.
            var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
            node.y += (y - center(node)) * alpha;
          }
        });
      });

      function weightedTarget(link) {
        return (link.target.y + link.ty + link.dy / 2) * link.value;
      }
    }

    function resolveCollisions() {
      nodesByBreadth.forEach(function(nodes) {
        var node,
            dy,
            y0 = 0,
            n = nodes.length,
            i;

        // Push any overlapping nodes down.
        nodes.sort(ascendingDepth);
        for (i = 0; i < n; ++i) {
          node = nodes[i];
          dy = y0 - node.y;
          if (dy > 0) node.y += dy;
          y0 = node.y + node.dy + nodePadding;
        }

        // If the bottommost node goes outside the bounds, push it back up.
        dy = y0 - nodePadding - size[1];
        if (dy > 0) {
          y0 = node.y -= dy;

          // Push any overlapping nodes back up.
          for (i = n - 2; i >= 0; --i) {
            node = nodes[i];
            dy = node.y + node.dy + nodePadding - y0;
            if (dy > 0) node.y -= dy;
            y0 = node.y;
          }
        }
      });
    }

    function ascendingDepth(a, b) {
      return a.y - b.y;
    }
  }

  // Compute y-offset of the source endpoint (sy) and target endpoints (ty) of links,
  // relative to the source/target node's y-position.
  function computeLinkDepths() {
    nodes.forEach(function(node) {
      node.sourceLinks.sort(ascendingTargetDepth);
      node.targetLinks.sort(ascendingSourceDepth);
    });
    nodes.forEach(function(node) {
      var sy = 0, ty = 0;
      node.sourceLinks.forEach(function(link) {
        link.sy = sy;
        sy += link.dy;
      });
      node.targetLinks.forEach(function(link) {
        link.ty = ty;
        ty += link.dy;
      });
    });

    function ascendingSourceDepth(a, b) {
      return a.source.y - b.source.y;
    }

    function ascendingTargetDepth(a, b) {
      return a.target.y - b.target.y;
    }
  }

  // Y-position of the middle of a node.
  function center(node) {
    return node.y + node.dy / 2;
  }

  // Value property accessor.
  function value(x) {
    return x.value;
  }

  return sankey;
};
<|endoftext|>


<commit_before>/*global module */
module.exports = function (grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        distDir: "dist",
        distName: "pact-js-dsl",
        srcDir: "src",
        clean: ['<%= dest %>'],
        concat: {
            dist: {
                src: ['<%= srcDir %>/*.js'],
                dest: '<%= distDir %>/<%= distName %>.js'

            }
        },
        karma: {
            pact: {
                configFile: 'example/karma.conf.js',
                singleRun: false
            }
        },
        shell: {
            pact: {
                command: 'echo run pact tests; cd ./pact_tests; ./pact.sh 1234',
                options: {
                    stdout: true,
                    failOnError: true
                }
            }
        },
    });

    require("load-grunt-tasks")(grunt);
    grunt.registerTask('test', ['shell:pact']);

    grunt.registerTask('package', ['concat']);

};
<commit_msg>fixing the git conflicts<commit_after>/*global module */
module.exports = function (grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        distDir: "dist",
        distName: "pact-js-dsl",
        srcDir: "src",
        clean: ['<%= dest %>'],
        concat: {
            dist: {
                src: ['<%= srcDir %>/*.js'],
                dest: '<%= distDir %>/<%= distName %>.js'

            }
        },
        karma: {
            pact: {
                configFile: 'example/karma.conf.js',
                singleRun: false
            }
        },
        shell: {
            pact: {
                command: 'echo run pact tests; cd ./pact_tests; ./pact.sh 1234',
                options: {
                    stdout: true,
                    failOnError: true
                }
            }
        },
    });

    require("load-grunt-tasks")(grunt);
    grunt.registerTask('test', ['shell:pact']);
    grunt.registerTask('package', ['concat']);
};
<|endoftext|>


<commit_before>// Given two strings s and t, write a function to determine if t is an anagram of s.
// For example,

// s = "anagram", t = "nagaram", return true.
// s = "rat", t = "car", return false.

// Note:
// You may assume the string contains only lowercase alphabets.

<commit_msg>change<commit_after>// Given two strings s and t, write a function to determine if t is an anagram of s.
// For example,

// s = "anagram", t = "nagaram", return true.
// s = "rat", t = "car", return false.

// Note:
// You may assume the string contains only lowercase alphabets.

// Hash table – O(n) time, O(1) space
// To examine if t is a rearrangement of s, we can count occurrences of each letter in the two strings and compare them.
// Since both s and t contain only letters from a-z, a simple counter table of size 26 is suffice.

// Do we need two counter tables for comparison? Actually no,
// because we could increment the counter for each letter in s and decrement the counter for each letter in t,
// then check if the counter reaches back to zero.

function isAnagram(s, t) {
    if (s.length() !=== t.length()){

    } return false;
    var counter = new int[26];
    for (int i = 0; i < s.length(); i++) {
        counter[s.charAt(i) - 'a']++;
        counter[t.charAt(i) - 'a']--;
    };
    for (int count : counter) {
        if (count != 0) return false;
    };
    return true;
}

// Sorting – O(n log n) time, O(1) space
// An anagram is produced by rearranging the letters of s into t.
// Therefore, if t is an anagram of s, sorting both strings will result in two identical strings.
// Furthermore, if s and t have different lengths, t must not be an anagram of s and we can return early.

var isAnagram = function(s, t) {
    if (s.length !== t.length){
      return false;
    }
    s = s.split("").sort().join("");
    t = t.split("").sort().join("");
    return (s === t);
};

// Complexity analysis: Assume that n is the length of s,
// sorting costs O(n log n) and comparing two strings costs O(n).
// Sorting time dominates and the overall time complexity is O(n log n).

<|endoftext|>


<commit_before>var buffer = [];
var mark = -1;
var lastChr = "";

consonents = {
// key : [character, mahaprana, sanyaka]
    z : [0xda4, 0x00, 0x00],
	Z : [0xda5, 0x00, 0x00],
	w : [0xdca, 0x00, 0x00],
	W : [0x200c, 0x00, 0x00],
	r : [0xdbb, 0x00, 0x00],
	R : [0xdbb, 0x00, 0x00],
	t : [0xdad, 0xdae, 0x00],
	T : [0xda7, 0xda8, 0x00],
	y : [0xdba, 0x00, 0x00],
	Y : [0xdba, 0x00, 0x00],
	p : [0xdb4, 0xdb5, 0x00],
	P : [0xdb5, 0xdb5, 0x00],
	s : [0xdc3, 0xdc2, 0x00],
	S : [0xdc1, 0xdc2, 0x00],
	d : [0xdaf, 0xdb0, 0xdb3],
	D : [0xda9, 0xdaa, 0xdac],
	f : [0xdc6, 0x00, 0x00],
	F : [0xdc6, 0x00, 0x00],
	g : [0xd9c, 0xd9d, 0xd9f],
	G : [0xd9f, 0xd9d, 0x00],
	h : [0xdc4, 0xd83, 0x00],
	H : [0xdc4, 0x00, 0x00],
	j : [0xda2, 0xda3, 0xda6],
	J : [0xda3, 0xda3, 0xda6],
	k : [0xd9a, 0xd9b, 0x00],
	K : [0xd9b, 0xd9b, 0x00],
	l : [0xdbd, 0x00, 0x00],
	L : [0xdc5, 0x00, 0x00],
	x : [0xd82, 0x00, 0x00],
	X : [0xd9e, 0x00, 0x00],
	c : [0xda0, 0xda1, 0x00],
	C : [0xda1, 0xda1, 0x00],
	v : [0xdc0, 0x00, 0x00],
	b : [0xdb6, 0xdb7, 0xdb9],
	B : [0xdb7, 0xdb7, 0xdb9],
	n : [0xdb1, 0x00, 0xd82],
	N : [0xdab, 0x00, 0xd9e],
	m : [0xdb8, 0x00, 0x00],
	M : [0xdb9, 0x00, 0x00]
}

vowels = {
// key : [single0, double0, single1, double1]
    a : [0xd85, 0xd86, 0xdcf, 0xdcf],
	A : [0xd87, 0xd88, 0xdd0, 0xdd1],
	q : [0xd87, 0xd88, 0xdd0, 0xdd1],
	e : [0xd91, 0xd92, 0xdd9, 0xdda],
	E : [0xd91, 0xd92, 0xdd9, 0xdda],
	i : [0xd89, 0xd8a, 0xdd2, 0xdd3],
	I : [0xd93, 0x00, 0xddb, 0xddb],
	o : [0xd94, 0xd95, 0xddc, 0xddd],
	O : [0xd96, 0x00, 0xdde, 0xddf],
	u : [0xd8b, 0xd8c, 0xdd4, 0xdd6],
	U : [0xd8d, 0xd8e, 0xdd8, 0xdf2],
	V : [0xd8f, 0xd90, 0xd8f, 0xd90]
}

function isAlphabetical(charCode)
{
    if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true
    } else {
        return false
    }
}

function isVowel(charCode)
{
    /* A E I O U V
       a e i o u q */
    var vowelCodes = ["65", "69", "73", "79", "85", "86",
                       "97", "101", "105", "111", "117", "113"];
    for(var i=0;i<vowelCodes.length;i++){
        if(vowelCodes[i]==charCode){return true};
    }
    return false;
}

function isConsonent(charCode)
{
    if (isAlphabetical(charCode) && ! isVowel(charCode)){return true;}
    return false;
}

function transform(e)
{
    var shiftflag = false
    if (!e) var e = window.event; //for IE

    if (e.which != 8 && e.which != 13 && e.keyCode != 16){
        inputBox = document.getElementById('sayuraInput');
        inputBox.value = inputBox.value.slice(0, - 1);
        inputBox.value += lastChr;
    }
}

function sayura(e)
{
    if (e.which == 8){
        buffer.pop();
        if (mark != -1) mark--;
        return;
    }

    if (!e) var e = window.event; //for IE
    inputBox = document.getElementById('sayuraInput');
    var value = e.charCode;

    if (isAlphabetical(value)) {
        var chr = String.fromCharCode(value);
        buffer.push(value);
        mark++;

        if(isVowel(value)){
            if(buffer.length == 0 || !isAlphabetical(buffer[mark-1])){
                lastChr = String.fromCharCode(vowels[chr][0]);
            } else if(isConsonent(buffer[mark-1])){
                lastChr = String.fromCharCode(vowels[chr][2]);
            } else if(value == buffer[mark-1] && isConsonent(buffer[mark-2])){
                inputBox.value = inputBox.value.slice(0, -1);
                lastChr = String.fromCharCode(vowels[chr][3]);
            } else if(value == buffer[mark-1]){
                inputBox.value = inputBox.value.slice(0, -1);
                lastChr = String.fromCharCode(vowels[chr][1]);
            }

        } else {
            if(value == 71 && isConsonent(buffer[mark-1])){
                //sanyaka
                inputBox.value = inputBox.value.slice(0, -1);
                prevChar = String.fromCharCode(buffer[mark-1]);
                lastChr = String.fromCharCode(consonents[prevChar][2]);
            } else if((value == 72 || value == 102) && isConsonent(buffer[mark-1])){
                inputBox.value = inputBox.value.slice(0, -1);
                //mahaprana
                prevChar = String.fromCharCode(buffer[mark-1]);
                lastChr = String.fromCharCode(consonents[prevChar][1]);
            } else if((value == 82 || value == 89) && isConsonent(buffer[mark-1])){
                //add al-kirima, zero width joiner and r/y for rakaransaya/yansaya
                lastChr = String.fromCharCode(0xdca, 0x200d, consonents[chr][0]);
            } else if(value == 87 && isConsonent(buffer[mark-1])){
                //zero width joiner, al-kirima for bandi-akuru
                lastChr = String.fromCharCode(0x200d, 0xdca);
            } else {
                lastChr = String.fromCharCode(consonents[chr][0]);
            }
        }

    } else if (e.charCode != 0){
        lastChr = String.fromCharCode(value);
        buffer.push(String.fromCharCode(value));
        mark++;
    }
}

function load()
{
    var input = document.getElementById("sayuraInput");
    input.addEventListener("keypress", sayura, false);
    input.addEventListener("keyup", transform, false);
}

document.addEventListener("DOMContentLoaded", load, false);
<commit_msg>Removes troubles with non-text inputs.<commit_after>var buffer = [];
var mark = -1;
var lastChr = "";

consonents = {
// key : [character, mahaprana, sanyaka]
    z : [0xda4, 0x00, 0x00],
	Z : [0xda5, 0x00, 0x00],
	w : [0xdca, 0x00, 0x00],
	W : [0x200c, 0x00, 0x00],
	r : [0xdbb, 0x00, 0x00],
	R : [0xdbb, 0x00, 0x00],
	t : [0xdad, 0xdae, 0x00],
	T : [0xda7, 0xda8, 0x00],
	y : [0xdba, 0x00, 0x00],
	Y : [0xdba, 0x00, 0x00],
	p : [0xdb4, 0xdb5, 0x00],
	P : [0xdb5, 0xdb5, 0x00],
	s : [0xdc3, 0xdc2, 0x00],
	S : [0xdc1, 0xdc2, 0x00],
	d : [0xdaf, 0xdb0, 0xdb3],
	D : [0xda9, 0xdaa, 0xdac],
	f : [0xdc6, 0x00, 0x00],
	F : [0xdc6, 0x00, 0x00],
	g : [0xd9c, 0xd9d, 0xd9f],
	G : [0xd9f, 0xd9d, 0x00],
	h : [0xdc4, 0xd83, 0x00],
	H : [0xdc4, 0x00, 0x00],
	j : [0xda2, 0xda3, 0xda6],
	J : [0xda3, 0xda3, 0xda6],
	k : [0xd9a, 0xd9b, 0x00],
	K : [0xd9b, 0xd9b, 0x00],
	l : [0xdbd, 0x00, 0x00],
	L : [0xdc5, 0x00, 0x00],
	x : [0xd82, 0x00, 0x00],
	X : [0xd9e, 0x00, 0x00],
	c : [0xda0, 0xda1, 0x00],
	C : [0xda1, 0xda1, 0x00],
	v : [0xdc0, 0x00, 0x00],
	b : [0xdb6, 0xdb7, 0xdb9],
	B : [0xdb7, 0xdb7, 0xdb9],
	n : [0xdb1, 0x00, 0xd82],
	N : [0xdab, 0x00, 0xd9e],
	m : [0xdb8, 0x00, 0x00],
	M : [0xdb9, 0x00, 0x00]
}

vowels = {
// key : [single0, double0, single1, double1]
    a : [0xd85, 0xd86, 0xdcf, 0xdcf],
	A : [0xd87, 0xd88, 0xdd0, 0xdd1],
	q : [0xd87, 0xd88, 0xdd0, 0xdd1],
	e : [0xd91, 0xd92, 0xdd9, 0xdda],
	E : [0xd91, 0xd92, 0xdd9, 0xdda],
	i : [0xd89, 0xd8a, 0xdd2, 0xdd3],
	I : [0xd93, 0x00, 0xddb, 0xddb],
	o : [0xd94, 0xd95, 0xddc, 0xddd],
	O : [0xd96, 0x00, 0xdde, 0xddf],
	u : [0xd8b, 0xd8c, 0xdd4, 0xdd6],
	U : [0xd8d, 0xd8e, 0xdd8, 0xdf2],
	V : [0xd8f, 0xd90, 0xd8f, 0xd90]
}

function isAlphabetical(charCode)
{
    if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true
    } else {
        return false
    }
}

function isVowel(charCode)
{
    /* A E I O U V
       a e i o u q */
    var vowelCodes = ["65", "69", "73", "79", "85", "86",
                       "97", "101", "105", "111", "117", "113"];
    for(var i=0;i<vowelCodes.length;i++){
        if(vowelCodes[i]==charCode){return true};
    }
    return false;
}

function isConsonent(charCode)
{
    if (isAlphabetical(charCode) && ! isVowel(charCode)){return true;}
    return false;
}

function transform(e)
{
    if (!e) var e = window.event; //for IE

    if (e.which < 65 || e.which > 90) { return; }

    if (!e.charCode && !e.ctrlKey){
        inputBox = document.getElementById('sayuraInput');
        inputBox.value = inputBox.value.slice(0, - 1);
        inputBox.value += lastChr;
    }
}

function sayura(e)
{
    if (!e) var e = window.event; //for IE
    if (e.which == 8){
        buffer.pop();
        if (mark != -1) mark--;
        return;
    }

    if (e.ctrlKey) { return; }

    inputBox = document.getElementById('sayuraInput');
    var value = e.charCode;

    if (isAlphabetical(value)) {
        var chr = String.fromCharCode(value);
        buffer.push(value);
        mark++;

        if(isVowel(value)){
            if(buffer.length == 0 || !isAlphabetical(buffer[mark-1])){
                lastChr = String.fromCharCode(vowels[chr][0]);
            } else if(isConsonent(buffer[mark-1])){
                lastChr = String.fromCharCode(vowels[chr][2]);
            } else if(value == buffer[mark-1] && isConsonent(buffer[mark-2])){
                inputBox.value = inputBox.value.slice(0, -1);
                lastChr = String.fromCharCode(vowels[chr][3]);
            } else if(value == buffer[mark-1]){
                inputBox.value = inputBox.value.slice(0, -1);
                lastChr = String.fromCharCode(vowels[chr][1]);
            }

        } else {
            if(value == 71 && isConsonent(buffer[mark-1])){
                //sanyaka
                inputBox.value = inputBox.value.slice(0, -1);
                prevChar = String.fromCharCode(buffer[mark-1]);
                lastChr = String.fromCharCode(consonents[prevChar][2]);
            } else if((value == 72 || value == 102) && isConsonent(buffer[mark-1])){
                inputBox.value = inputBox.value.slice(0, -1);
                //mahaprana
                prevChar = String.fromCharCode(buffer[mark-1]);
                lastChr = String.fromCharCode(consonents[prevChar][1]);
            } else if((value == 82 || value == 89) && isConsonent(buffer[mark-1])){
                //add al-kirima, zero width joiner and r/y for rakaransaya/yansaya
                lastChr = String.fromCharCode(0xdca, 0x200d, consonents[chr][0]);
            } else if(value == 87 && isConsonent(buffer[mark-1])){
                //zero width joiner, al-kirima for bandi-akuru
                lastChr = String.fromCharCode(0x200d, 0xdca);
            } else {
                lastChr = String.fromCharCode(consonents[chr][0]);
            }
        }

    } else if (e.charCode != 0){
        lastChr = String.fromCharCode(value);
        buffer.push(String.fromCharCode(value));
        mark++;
    }
}

function load()
{
    var input = document.getElementById("sayuraInput");
    input.addEventListener("keypress", sayura, false);
    input.addEventListener("keyup", transform, false);
}

document.addEventListener("DOMContentLoaded", load, false);
<|endoftext|>


<commit_before>var parserx      = require('parse-regexp')

module.exports = function (schema) {
  if('function' == schema)
    return schema

  var rules = []
  for (var p in schema) {
    rules.push({rx: parserx(p) || p, fn: schema[p]})
  }

  function match (key) {
    for (var i in rules) {
      var r = rules[i]
      var m = key.match(r.rx)
      if(m && m.index === 0)
        return r.fn
    }
  }

  match.schema = schema
  match.rules = rules

  return match
}
<commit_msg>check typeof function<commit_after>var parserx      = require('parse-regexp')

module.exports = function (schema) {
  if('function' == typeof schema)
    return schema

  var rules = []
  for (var p in schema) {
    rules.push({rx: parserx(p) || p, fn: schema[p]})
  }

  function match (key) {
    for (var i in rules) {
      var r = rules[i]
      var m = key.match(r.rx)
      if(m && m.index === 0)
        return r.fn
    }
  }

  match.schema = schema
  match.rules = rules

  return match
}
<|endoftext|>


<commit_before>var debug = require('debug')('dataset:schema');
var _ = require('underscore');
var bson = require('bson');
var util = require('util');
var stream = require('stream');

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

// random data
var chance = require('chance').Chance();
var faker = require('faker');

function Schema (sc) {
  if (!(this instanceof Schema)) return new Schema(sc);
  stream.Readable.call(this, {objectMode: true});
  this._document = new Document(sc, this);
  // this._context = new Context(this); // should not call Schema's context
  this._state = { // serve as global state
    counter: []
  };
}
util.inherits(Schema, stream.Readable);

Schema.prototype.getRoot = function () {
  return this;
};

Schema.prototype.next = function () {
  return this._document.next();
};

Schema.prototype._read = function (n) {
  this.push(this._document.read(n));
};

// doc must be an object or an array of object
function Document (document, parent) {
  if (!(this instanceof Document)) return new Document(document, parent);
  stream.Readable.call(this, {objectMode: true});
  this._parent = parent;
  this._context = new Context(this);
  this._array = Array.isArray(document);
  this._currVal = {};
  this._children = {};
  var doc = this._array ? document[0] : document;

  for (var name in doc) {
    var data = doc[name];
    if ((Array.isArray(data) && typeof data[0] === 'object') ||
        (typeof data === 'object' && !Array.isArray(data))) {
       this._children[name] = new Document(data, this);
    } else {
       this._children[name] = new Field(data, this);
    }
    (function (method) {
      var child = this._children[method];
      Object.defineProperty(this._currVal, method, {
        enumerable: true,
        get: function () {
          if (typeof child._currVal === 'undefined') {
            return child.next();
          }
          return child._currVal;
        }
      });
    }).call(this, name);
  }
}
util.inherits(Document, stream.Readable);

Document.prototype.getRoot = function () {
  return this._parent.getRoot();
};

Document.prototype._produce = function () {
  this._clean();
  var data = {};
  for (var name in this._children) {
    data[name] = this._children[name].next();
  }
  return data;
};

Document.prototype.next = function () {
  if (this._array) {
    var data = [];
    for (var i = _.random(1, 3); i > 0; i--) {
      data.push(this._produce());
    }
    return data;
  } else {
    return this._produce();
  }
};

Document.prototype._clean = function () {
  for (var child in this._children) {
    this._children[child]._clean();
  }
};

Document.prototype._read = function (n) {
  this.push(this.next());
};

// field must be string or an array of string
function Field (field, parent) {
  if (!(this instanceof Field)) return new Field(field, parent);
  debug('building field', field);
  stream.Readable.call(this, {objectMode: true});
  this._parent = parent;
  this._prevVal = undefined;
  this._currVal = undefined;

  if (Array.isArray(field)) {
    this._array = true;
    this._field = field[0];
  } else {
    this._array = false;
    this._field = field;
  }

  if (typeof this._field !== 'string') {
    var self = this;
    this._compiled = function () { return self._field; };
  } else {
    this._compiled = _.template(this._field);
  }
}
util.inherits(Field, stream.Readable);

Field.prototype.getRoot = function () {
  return this._parent.getRoot();
};

Field.prototype._clean = function () {
  this._prevVal = this._currVal;
  this._currVal = undefined;
};
Field.prototype._produce = function () {
  this._parent._context._state = {};
  var res = this._compiled.call(this._parent._currVal, this._parent._context);
  var alt = this._parent._context._state.override;
  return (typeof alt === 'undefined') ? res : alt;
};

Field.prototype.next = function () {
  if (typeof this._currVal !== 'undefined') return this._currVal;
  var data;
  if (this._array) {
    data = [];
    for (var i = _.random(1, 3); i > 0; i--) {
      data.push(this._produce());
    }
  } else if (typeof this._field !== 'string') {
    data = this._field;
  } else {
    data = this._produce();
  }
  return (this._currVal = data);
};

Document.prototype._read = function (n) {
  this.push(this.next());
};

// object that will pass into _.template
function Context (host) {
  if (!(this instanceof Context)) return new Context(host);

  this._state = {
    override: undefined // if present, used to override the template output
  };
  this.util = {
    sample: _.sample
  };

  // need to add security feature
  this.chance = chance;
  this.faker = faker;

  // utility methods
  // this._host = host;
  this.counter = function (id, start, step) {
    id = id || 0; // though id=0 is false, does not matter
    var counter = host.getRoot()._state.counter; //pointer
    if (typeof counter[id] === 'undefined') {
      return (counter[id] = start || 0);
    }
    return (counter[id] += (step || 1));
  };

}

// all supported data types
Context.prototype.Double = function (i) {
  this._state.override = Number(i);
};
Context.prototype.Boolean = function (b) {
  this._state.override = Boolean(b);
};
Context.prototype.String = function (s) {
  this._state.override = String(s);
};
Context.prototype.Date = function (d) {
  this._state.override = new Date(d);
};
Context.prototype.NumberLong = function (i) {
  this._state.override = new bson.Long(i);
};
Context.prototype.MinKey = function () {
  this._state.override = new bson.MinKey();
};
Context.prototype.MaxKey = function () {
  this._state.override = new bson.MaxKey();
};
Context.prototype.Timestamp = function () {
  this._state.override = new bson.Timestamp();
};
Context.prototype.ObjectID = function (i) {
  this._state.override = new bson.ObjectId(i);
};

module.exports = Schema;
<commit_msg>configurable array<commit_after>var debug = require('debug')('dataset:schema');
var _ = require('underscore');
var bson = require('bson');
var util = require('util');
var stream = require('stream');

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

// random data
var chance = require('chance').Chance();
var faker = require('faker');

// parse the user array
function demuxArray (array) {
  if (!Array.isArray(array) || array.length === 0) {
    return {
      isArray: false
    };
  }
  var num = function () { return _.random(1, 3); };
  if (array.length > 1) {
    var userNum = _.first(array);
    if (typeof userNum === 'number') {
      num = function () { return userNum; };
    } else {
      num = function () { return Number(_.template(userNum)()); };
    }
  }
  return {
    isArray: true,
    num: num
  };
}

function Schema (sc) {
  if (!(this instanceof Schema)) return new Schema(sc);
  stream.Readable.call(this, {objectMode: true});
  this._document = new Document(sc, this);
  // this._context = new Context(this); // should not call Schema's context
  this._state = { // serve as global state
    counter: []
  };
}
util.inherits(Schema, stream.Readable);

Schema.prototype.getRoot = function () {
  return this;
};

Schema.prototype.next = function () {
  return this._document.next();
};

Schema.prototype._read = function (n) {
  this.push(this._document.read(n));
};

// doc must be an object or an array of object
function Document (document, parent) {
  if (!(this instanceof Document)) return new Document(document, parent);
  stream.Readable.call(this, {objectMode: true});
  this._parent = parent;
  this._context = new Context(this);
  this._currVal = {};
  this._children = {};

  this._arrayConfig = demuxArray(document);
  var doc = this._arrayConfig.isArray ? _.last(document) : document;
  for (var name in doc) {
    var data = doc[name];
    if ((Array.isArray(data) && typeof data[0] === 'object') ||
        (typeof data === 'object' && !Array.isArray(data))) {
       this._children[name] = new Document(data, this);
    } else {
       this._children[name] = new Field(data, this);
    }
    (function (method) {
      var child = this._children[method];
      Object.defineProperty(this._currVal, method, {
        enumerable: true,
        get: function () {
          if (typeof child._currVal === 'undefined') {
            return child.next();
          }
          return child._currVal;
        }
      });
    }).call(this, name);
  }
}
util.inherits(Document, stream.Readable);

Document.prototype.getRoot = function () {
  return this._parent.getRoot();
};

Document.prototype._produce = function () {
  this._clean();
  var data = {};
  for (var name in this._children) {
    data[name] = this._children[name].next();
  }
  return data;
};

Document.prototype.next = function () {
  if (this._arrayConfig.isArray) {
    var data = [];
    for (var i = this._arrayConfig.num(); i > 0; i--) {
      data.push(this._produce());
    }
    return data;
  } else {
    return this._produce();
  }
};

Document.prototype._clean = function () {
  for (var child in this._children) {
    this._children[child]._clean();
  }
};

Document.prototype._read = function (n) {
  this.push(this.next());
};

// field must be string or an array of string
function Field (field, parent) {
  if (!(this instanceof Field)) return new Field(field, parent);
  debug('building field', field);
  stream.Readable.call(this, {objectMode: true});
  this._parent = parent;
  this._prevVal = undefined;
  this._currVal = undefined;
  this._arrayConfig = demuxArray(field);
  this._field = this._arrayConfig.isArray ? _.last(field) : field;

  if (typeof this._field !== 'string') {
    var self = this;
    this._compiled = function () { return self._field; };
  } else {
    this._compiled = _.template(this._field);
  }
}
util.inherits(Field, stream.Readable);

Field.prototype.getRoot = function () {
  return this._parent.getRoot();
};

Field.prototype._clean = function () {
  this._prevVal = this._currVal;
  this._currVal = undefined;
};
Field.prototype._produce = function () {
  this._parent._context._state = {};
  var res = this._compiled.call(this._parent._currVal, this._parent._context);
  var alt = this._parent._context._state.override;
  return (typeof alt === 'undefined') ? res : alt;
};

Field.prototype.next = function () {
  if (typeof this._currVal !== 'undefined') return this._currVal;
  var data;
  if (this._arrayConfig.isArray) {
    data = [];
    for (var i = this._arrayConfig.num(); i > 0; i--) {
      data.push(this._produce());
    }
  } else if (typeof this._field !== 'string') {
    data = this._field;
  } else {
    data = this._produce();
  }
  return (this._currVal = data);
};

Document.prototype._read = function (n) {
  this.push(this.next());
};

// object that will pass into _.template
function Context (host) {
  if (!(this instanceof Context)) return new Context(host);

  this._state = {
    override: undefined // if present, used to override the template output
  };
  this.util = {
    sample: _.sample
  };

  // need to add security feature
  this.chance = chance;
  this.faker = faker;

  // utility methods
  // this._host = host;
  this.counter = function (id, start, step) {
    id = id || 0; // though id=0 is false, does not matter
    var counter = host.getRoot()._state.counter; //pointer
    if (typeof counter[id] === 'undefined') {
      return (counter[id] = start || 0);
    }
    return (counter[id] += (step || 1));
  };

}

// all supported data types
Context.prototype.Double = function (i) {
  this._state.override = Number(i);
};
Context.prototype.Boolean = function (b) {
  this._state.override = Boolean(b);
};
Context.prototype.String = function (s) {
  this._state.override = String(s);
};
Context.prototype.Date = function (d) {
  this._state.override = new Date(d);
};
Context.prototype.NumberLong = function (i) {
  this._state.override = new bson.Long(i);
};
Context.prototype.MinKey = function () {
  this._state.override = new bson.MinKey();
};
Context.prototype.MaxKey = function () {
  this._state.override = new bson.MaxKey();
};
Context.prototype.Timestamp = function () {
  this._state.override = new bson.Timestamp();
};
Context.prototype.ObjectID = function (i) {
  this._state.override = new bson.ObjectId(i);
};

module.exports = Schema;
<|endoftext|>


<commit_before>const Promise   = require('bluebird'),
      puppeteer = require('puppeteer')

const handlePopup = async (target) => {

  const popup = await target.page()
  await popup.waitFor('#encses', { timeout: 10000 })
  const encses = await popup.$('#encses')
  encses.getProperty('value').then(v => v.jsonValue())
}

const handleResponse = async (response) => {
  const body = await response.buffer()
  const text = await response.text()
  console.log({
    body: body,
    text: text,
    headers: response.headers,
    request: response.request
  })
}

const scrape = module.exports = async (url, id, pass) => {

  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()

  await page.goto(url)
  await page.waitFor('#bLogin', { timeout: 10000 })

  page.on('response', handleResponse)
  browser.on('targetcreated', handlePopup)
  await page.type('#login', id)
  await page.type('#password', pass)
  await page.click('#bLogin')

  // const [_0, _1, popup] = await browser.pages()
  // const encses = await popup.$('#encses')
  // encses.getProperty('value').then(v => v.jsonValue().then(console.log))

  // await popup.setViewport({ width: 1000, height: 700 })
  // await popup.waitFor('a[data-nav="sfgradebook001.w"]', { timeout: 10000 })
  // await popup.click('a[data-nav="sfgradebook001.w"]')
  // await page.click('#bLogin')
  // await browser.close()
}<commit_msg>Spaghetti code version of querying<commit_after>const Promise   = require('bluebird')
const puppeteer = require('puppeteer')

const request = (lR, origin, encses) => {
  const req = new XMLHttpRequest()
	let info = lR
    .slice(4, -5)
    .split('^')

	req.open('POST', origin, false)
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	req.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

  req.send([
    `action=viewGradeInfoDialog`,
    `&gridCount=1`,
    `&fromHttp=yes`,
    `&stuId=${info[4]}`,
    `&entityId=004`,
    `&corNumId=72270`,
    `&track=0`,
    `&section=01`,
    `&gbId=1633625`,
    `&bucket=TERM+6`,
    `&subjectId=`,
    `&dialogLevel=1`,
    `&isEoc=no`,
    `&ishttp=true`,
    `&sessionid=${info[1]}%15${info[2]}`,
    `&encses=${encses}`,
    `&dwd=${info[0]}`,
    `&wfaacl=${info[2]}`
  ].join(''))

  return req.response
}

const scrape = module.exports = async (url, id, pass) => {

  let loginResponse, referer, encses

  const handlePopup = async (target) => {

    const popup = await target.page()
    await popup.waitFor('#encses', { timeout: 10000 })
    encsesDOM = await popup.$('#encses')
    encses = await encsesDOM.getProperty('value').then(v => v.jsonValue())
    console.log(loginResponse, referer, encses)
    console.log(await popup.evaluate(request, loginResponse, referer, encses))
  }

  const handleResponse = async (response) => {

    const text = await response.text()
    const req = await response.request()
    if (text.substring(0, 4) === '<li>') {

      loginResponse = text
      referer = [...req.headers.referer.split('/').slice(0, -1), 'httploader.p?file=sfgradebook001.w'].join('/')
    }
  }

  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()

  await page.goto(url)
  await page.waitFor('#bLogin', { timeout: 10000 })

  page.on('response', handleResponse)
  browser.on('targetcreated', handlePopup)
  await page.type('#login', id)
  await page.type('#password', pass)
  await page.click('#bLogin')

  // await popup.setViewport({ width: 1000, height: 700 })
  // await popup.waitFor('a[data-nav="sfgradebook001.w"]', { timeout: 10000 })
  // await popup.click('a[data-nav="sfgradebook001.w"]')
  // await page.click('#bLogin')
  // await browser.close()
}<|endoftext|>


<commit_before>var dictionary;
var dictionary_spanish;
var textarea;
$(document).ready(function(){

    jQuery.get('dictionary.txt', function(data) {
        dictionary = data.split("\n");
    });
    jQuery.get('spanish.txt', function(data) {
        dictionary_spanish = data.split("\n");
    });

});

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str) && strArray[j].indexOf(str) == 0) return j;
    }
    return -1;
}

function CallMethod() {
    textarea = $("#uh").val().split("\n");
    var defType = $("input[name='def']:checked").val();
    var langType = $("input[name='lang']:checked").val();

    for (var i = 0; i < textarea.length; i++) {
        var word = textarea[i].toUpperCase();
        //alert(word);
        var index = searchStringInArray(word, dictionary);

        if (index != -1) {

            var entry = "";
            var startIndex = index;

            while (1) // finding startIndex
            {
                if (dictionary[startIndex].indexOf("Defn") >= 0)
                    break;

                startIndex++;
            }

            var tempIndex = startIndex;

            while (1) {
                //alert(dictionary[tempIndex]);
                if (dictionary[tempIndex] == dictionary[tempIndex].toUpperCase()) {
                    if (defType == "all" && dictionary[tempIndex][1])
                        break;
                    else if (defType == "first")
                        break;
                }

                entry += dictionary[tempIndex];
                tempIndex++;
            }

            //alert(entry);

            textarea[i] += '	' + entry.replace("Defn:", "");
        }
        else
            textarea[i] += '	no definition found :(';

        //alert(entry);
    }

    //$("#uh").val('');
    $("#output").empty();

    for (var j = 0; j < textarea.length; j++) // outputting results
    {
        //$("#uh").val($("#uh").val() + textarea[j]);
        $("#output").append("
" + textarea[j] + "
");
        }

    alert("Set generated!");
}<commit_msg>spanish translator complete!<commit_after>var dictionary;
var dictionary_spanish;
var textarea;
$(document).ready(function(){

    jQuery.get('dictionary.txt', function(data) {
        dictionary = data.split("\n");
    });
    jQuery.get('spanish.txt', function(data) {
        dictionary_spanish = data.split("\n");
    });

});

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str) && strArray[j].indexOf(str) == 0) return j;
    }
    return -1;
}

function CallMethod() {
    textarea = $("#uh").val().split("\n");
    var defType = $("input[name='def']:checked").val();
    var langType = $("input[name='lang']:checked").val();

    for (var i = 0; i < textarea.length; i++) {
        var word = textarea[i].toUpperCase();
        //alert(word);
        if (langType == "eng") {
            var index = searchStringInArray(word, dictionary);

            if (index != -1) {

                var entry = "";
                var startIndex = index;

                while (1) // finding startIndex
                {
                    if (dictionary[startIndex].indexOf("Defn") >= 0)
                        break;

                    startIndex++;
                }

                var tempIndex = startIndex;

                while (1) {
                    //alert(dictionary[tempIndex]);
                    if (dictionary[tempIndex] == dictionary[tempIndex].toUpperCase()) {
                        if (defType == "all" && dictionary[tempIndex][1])
                            break;
                        else if (defType == "first")
                            break;
                    }

                    entry += dictionary[tempIndex];
                    tempIndex++;
                }

                //alert(entry);

                textarea[i] += '	' + entry.replace("Defn:", "");
            }
            else
                textarea[i] += '	no definition found :(';
        }
        else if (langType == "spa")
        {
            word = word.toLowerCase();
            //alert(word);
            var index = searchStringInArray(word, dictionary_spanish);

            if (index != -1)
                textarea[i] += '	' + dictionary_spanish[index].replace(word, "");
            else
                textarea[i] += '	no translation found :(';
        }

        //alert(entry);
    }

    //$("#uh").val('');
    $("#output").empty();

    for (var j = 0; j < textarea.length; j++) // outputting results
    {
        //$("#uh").val($("#uh").val() + textarea[j]);
        $("#output").append("
" + textarea[j] + "
");
        }

    alert("Set generated!");
}<|endoftext|>