<commit_before>module.exports = function(grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  var config = require('./config');
  var styleguide = require('sc5-styleguide');
  var path = require('path');
  var wiredep = require('wiredep');
  var cors_proxy = require('cors-anywhere');

  var gulp = require('gulp');
  // registering promisies for gulp...
  require("any-promise/register")("bluebird");
  var sass = require('gulp-sass');
  var bless = require('gulp-bless');
  var sourcemaps = require('gulp-sourcemaps');
  var concat = require('gulp-concat');
  var replace = require('gulp-replace');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'quality', 'docs', 'images'],
    jshint: {
      options: {
        undef: false,
        strict: false,
        '-W030': true,
        unused: false,
        passfail: true,
        reporter: 'checkstyle',
        reporterOutput: 'quality/js/checkstyle-results.xml'
      },
      all: [config.app.src + '/webapp/public/js/**/*.js']
    },
    sasslint: {
      src: [
        path.join(config.app.src,'**/*.scss'),
        '!**/ng-grid.scss'
      ],
      options: {
        bench: false,
        config: '.sasslint.json'
      }
    },
    watch: {
      files: config.app.src + '/**/*',
      tasks: ['copy', 'concat', 'sass', 'replace'],
      options: {
        spawn: false
      }
    },
    uglify: {
      options: {
        mangle: false,
        beautify: true,
        report: 'min',
        preserveComments: false
      },
      files: {
        cwd: config.app.dest + '/public/',
        src: ['**/*.js'],
        dest: config.app.dest + '/public/',
        expand: true,
        flatten: false
      }
    },
    connect: {
      server: {
        options: {
          keepalive: true,
          debug: true,
          port: 9000,
          base: config.app.dest
        }
      }
    },
    karma: {
      unit: {
        configFile: 'karma.config.js'
      }
    },
    replace: {
      serverurl: {
        src: [config.app.dest + '/public/**/*.js'],
        overwrite: true,
        replacements: [{
          from: '@@OPENLMIS_SERVER_URL',
          to: makeURL('openlmisServerURL')
        },{
          from: '@@AUTH_SERVICE_URL',
          to: makeURL('authServiceURL')
        },{
          from: '@@REQUISITION_SERVICE_URL',
          to: makeURL('requisitionServiceURL')
        }]
      }
    },
    concat: {
      js: {
        options: {
          sourceMap: true
        },
        src: function(){
          var appFiles = [
            // Base files
            config.app.src + '/webapp/public/js/shared/util.js',
            config.app.src + '/webapp/public/js/shared/*.js',
            config.app.src + '/webapp/public/js/shared/services/services.js',
            config.app.src + '/webapp/public/js/shared/**/*.js',
            // Module registration
            config.app.src + '/webapp/public/**/module/*.js',
            config.app.src + '/webapp/public/**/*.module.js',
            // Special file types....
            config.app.src + '/webapp/public/**/*.config.js',
            config.app.src + '/webapp/public/**/*.routes.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Everything else
            config.app.src + '/webapp/public/**/*.js',
            '!' + config.app.src + '/**/*.spec.js',
            '!' + config.app.src + '/webapp/public/app.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Run time
            // NEED file to declare openlmis-app
            config.app.src + '/webapp/public/app.js',
            config.app.src + '/webapp/public/app.routes.js'
          ];
          // hack to make jquery load first
          return [
              'bower_components/jquery/dist/jquery.js',
              'bower_components/jquery-ui/jquery-ui.js'
            ].concat(
              wiredep().js,
              [
                'vendor/ng-grid-2.0.7.min.js',
                'vendor/base2.js'
              ],
              appFiles
            );
        }(),
        dest: config.app.dest + '/public/openlmis.js'
      }
    },
    copy: {
      main: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/',
            src: ['*'],
            dest: config.app.dest + '/public',
            filter: 'isFile'
          }
        ],
      },
      images: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/images/',
            src: ['**'],
            dest: config.app.dest + '/public/images'
          }
        ],
      },
      img: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: config.app.src + '/webapp/public/lib/',
            src: ['**/img/**'],
            dest: config.app.dest + '/public/img'
          }
        ],
      },
      fonts: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/fonts/',
            src: ['**'],
            dest: config.app.dest + '/public/fonts'
          }
        ],
      },
      pages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: ['**/**.html'],
            dest: config.app.dest + '/public'
          }
        ],
      },
      messages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['messages_*.json'],
            dest: config.app.dest + '/public/messages'
          }
        ]
      },
      credentials: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['auth_server_client.json'],
            dest: config.app.dest + '/public/credentials'
          }
        ]
      },
      fontAwesomeFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: '*',
            dest: path.join(config.app.dest, 'public/fonts')
          }
        ]
      },
      uiGridFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/angular-ui-grid/',
            src: [
              'ui-grid.eot',
              'ui-grid.svg',
              'ui-grid.ttf',
              'ui-grid.woff'
            ],
            dest: config.app.dest + '/public/fonts'
          }
        ]
      }
    },
    gulp: {
      'styleguide-generate': function() {
        return gulp.src([
                        path.join(config.styleguide.src,"**/*.scss"),
                        "!"+path.join(config.styleguide.src,"**/scss/*.scss")
                        ])
          .pipe(styleguide.generate({
            title: 'OpenLMIS Styleguide',
            appRoot: '/styleguide',
            //extraHead: '<link rel="stylesheet" type="text/css" href="/openlmis-requisition-refUI/docs/body.css"/>',
            //disableHtml5Mode: true,
            overviewPath: './overview.md'
          }))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-applystyles': function() {
        return gulp.src([
                  path.join(config.app.dest,"/public/openlmis*.css")
                  ])
          .pipe(styleguide.applyStyles())
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-fonts': function() {
        return gulp.src([
            path.join(config.app.dest, "public/fonts/*"),
          ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"fonts")));
      },
      'styleguide-png': function() {
        return gulp.src([
                    config.app.dest + "/public/images/*",
                    config.app.dest + "/public/images/*"
                   ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"images")));
      },
      'sass': function(){
   var includePaths = [
        config.app.src,
        'bower_components/font-awesome/scss',
        'bower_components/bootstrap-sass/assets/stylesheets'
    ];

    var bowerCss = wiredep().css;
    var bowerSass = wiredep().scss;

    var files = [].concat(
      [
        path.join(config.app.src, "**/*variables.scss"),
        path.join(config.app.src, "**/*.variables.scss")
      ],
      bowerSass,
      bowerCss,
      [
        path.join(config.app.src, "/**/variables.scss"),
        path.join(config.app.src, "/**/*mixins.scss"),
        path.join(config.app.src, "/**/*.mixins.scss"),
        path.join(config.app.src, '**/*.css'),
        path.join(config.app.src, '**/*.scss'),
        "!" + path.join(config.app.src, "webapp/public/scss/*")
      ]);

    var outputStyle = "expanded";
    if(grunt.option('production')) outputStyle = "compressed";

    return gulp.src(files)
   .pipe(sourcemaps.init())
    .pipe(concat({
      path:'openlmis.scss'
    }))
    .pipe(sass({
      includePaths: includePaths,
      outputStyle: outputStyle,
    }))
    .pipe(sourcemaps.write())
    .pipe(concat('openlmis.css'))
    .pipe(replace('../','')) // remove non-relative strings
    //Replace UI-Grid font paths
    .pipe(replace('ui-grid.eot','fonts/ui-grid.eot'))
    .pipe(replace('ui-grid.ttf','fonts/ui-grid.ttf'))
    .pipe(replace('ui-grid.woff','fonts/ui-grid.woff'))
    .pipe(replace('ui-grid.svg','fonts/ui-grid.svg'))
    .pipe(bless())
    .pipe(gulp.dest(
      path.join(config.app.dest, "public")
    ));
      }
    }
  });

  grunt.registerTask('sass', ['gulp:sass']);

  function makeURL(key){
    if (!key) {
      return false;
    }
    var url = grunt.option(key) || config[key];
    if (grunt.option('addProxyService') && url && url.substr(0,4).toLowerCase() == "http") {
      return 'http://127.0.0.1:3030/' + url;
    } else {
      return url;
    }
  }

  grunt.registerTask('serve:proxy', 'Start proxy server', function(){
    var host = '127.0.0.1';
    var port = 3030;

    if (grunt.option('addProxyService')){
      grunt.log.writeln('starting proxy server at ' + host + ':' + port);
      cors_proxy.createServer().listen(port, host);
    }
  });

  grunt.registerTask('serve', ['serve:proxy', 'connect:server']);

  var buildTasks = ['clean', 'copy', 'concat', 'sass', 'replace'];
  var styleguideTasks = ['gulp:styleguide-generate', 'gulp:styleguide-png', 'gulp:styleguide-fonts', 'gulp:styleguide-applystyles'];

  if(grunt.option('production')) buildTasks.push('uglify');
  if(grunt.option('test')) buildTasks.push('karma:unit');
  if(grunt.option('styleguide')) buildTasks = buildTasks.concat(styleguideTasks);
  grunt.registerTask('build', buildTasks);

  grunt.registerTask('check', ['clean', 'jshint', 'sasslint']);

  grunt.registerTask('styleguide', ['build'].concat(styleguideTasks));
};
<commit_msg>OLMIS-1163: Remove duplicated file from concat<commit_after>module.exports = function(grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  var config = require('./config');
  var styleguide = require('sc5-styleguide');
  var path = require('path');
  var wiredep = require('wiredep');
  var cors_proxy = require('cors-anywhere');

  var gulp = require('gulp');
  // registering promisies for gulp...
  require("any-promise/register")("bluebird");
  var sass = require('gulp-sass');
  var bless = require('gulp-bless');
  var sourcemaps = require('gulp-sourcemaps');
  var concat = require('gulp-concat');
  var replace = require('gulp-replace');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'quality', 'docs', 'images'],
    jshint: {
      options: {
        undef: false,
        strict: false,
        '-W030': true,
        unused: false,
        passfail: true,
        reporter: 'checkstyle',
        reporterOutput: 'quality/js/checkstyle-results.xml'
      },
      all: [config.app.src + '/webapp/public/js/**/*.js']
    },
    sasslint: {
      src: [
        path.join(config.app.src,'**/*.scss'),
        '!**/ng-grid.scss'
      ],
      options: {
        bench: false,
        config: '.sasslint.json'
      }
    },
    watch: {
      files: config.app.src + '/**/*',
      tasks: ['copy', 'concat', 'sass', 'replace'],
      options: {
        spawn: false
      }
    },
    uglify: {
      options: {
        mangle: false,
        beautify: true,
        report: 'min',
        preserveComments: false
      },
      files: {
        cwd: config.app.dest + '/public/',
        src: ['**/*.js'],
        dest: config.app.dest + '/public/',
        expand: true,
        flatten: false
      }
    },
    connect: {
      server: {
        options: {
          keepalive: true,
          debug: true,
          port: 9000,
          base: config.app.dest
        }
      }
    },
    karma: {
      unit: {
        configFile: 'karma.config.js'
      }
    },
    replace: {
      serverurl: {
        src: [config.app.dest + '/public/**/*.js'],
        overwrite: true,
        replacements: [{
          from: '@@OPENLMIS_SERVER_URL',
          to: makeURL('openlmisServerURL')
        },{
          from: '@@AUTH_SERVICE_URL',
          to: makeURL('authServiceURL')
        },{
          from: '@@REQUISITION_SERVICE_URL',
          to: makeURL('requisitionServiceURL')
        }]
      }
    },
    concat: {
      js: {
        options: {
          sourceMap: true
        },
        src: function(){
          var appFiles = [
            // Base files
            config.app.src + '/webapp/public/js/shared/util.js',
            config.app.src + '/webapp/public/js/shared/*.js',
            config.app.src + '/webapp/public/js/shared/services/services.js',
            config.app.src + '/webapp/public/js/shared/**/*.js',
            // Module registration
            config.app.src + '/webapp/public/**/module/*.js',
            config.app.src + '/webapp/public/**/*.module.js',
            // Special file types....
            config.app.src + '/webapp/public/**/*.config.js',
            config.app.src + '/webapp/public/**/*.routes.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Everything else
            config.app.src + '/webapp/public/**/*.js',
            '!' + config.app.src + '/**/*.spec.js',
            '!' + config.app.src + '/webapp/public/app.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Run time
            // NEED file to declare openlmis-app
            config.app.src + '/webapp/public/app.js',
            config.app.src + '/webapp/public/app.routes.js'
          ];
          // hack to make jquery load first
          return [
              'bower_components/jquery/dist/jquery.js',
              'bower_components/jquery-ui/jquery-ui.js'
            ].concat(
              wiredep().js,
              [
                'vendor/ng-grid-2.0.7.min.js',
                'vendor/base2.js'
              ],
              appFiles
            );
        }(),
        dest: config.app.dest + '/public/openlmis.js'
      }
    },
    copy: {
      main: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/',
            src: ['*'],
            dest: config.app.dest + '/public',
            filter: 'isFile'
          }
        ],
      },
      images: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/images/',
            src: ['**'],
            dest: config.app.dest + '/public/images'
          }
        ],
      },
      img: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: config.app.src + '/webapp/public/lib/',
            src: ['**/img/**'],
            dest: config.app.dest + '/public/img'
          }
        ],
      },
      fonts: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/fonts/',
            src: ['**'],
            dest: config.app.dest + '/public/fonts'
          }
        ],
      },
      pages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: ['**/**.html'],
            dest: config.app.dest + '/public'
          }
        ],
      },
      messages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['messages_*.json'],
            dest: config.app.dest + '/public/messages'
          }
        ]
      },
      credentials: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['auth_server_client.json'],
            dest: config.app.dest + '/public/credentials'
          }
        ]
      },
      fontAwesomeFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: '*',
            dest: path.join(config.app.dest, 'public/fonts')
          }
        ]
      },
      uiGridFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/angular-ui-grid/',
            src: [
              'ui-grid.eot',
              'ui-grid.svg',
              'ui-grid.ttf',
              'ui-grid.woff'
            ],
            dest: config.app.dest + '/public/fonts'
          }
        ]
      }
    },
    gulp: {
      'styleguide-generate': function() {
        return gulp.src([
                        path.join(config.styleguide.src,"**/*.scss"),
                        "!"+path.join(config.styleguide.src,"**/scss/*.scss")
                        ])
          .pipe(styleguide.generate({
            title: 'OpenLMIS Styleguide',
            appRoot: '/styleguide',
            //extraHead: '<link rel="stylesheet" type="text/css" href="/openlmis-requisition-refUI/docs/body.css"/>',
            //disableHtml5Mode: true,
            overviewPath: './overview.md'
          }))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-applystyles': function() {
        return gulp.src([
                  path.join(config.app.dest,"/public/openlmis*.css")
                  ])
          .pipe(styleguide.applyStyles())
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-fonts': function() {
        return gulp.src([
            path.join(config.app.dest, "public/fonts/*"),
          ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"fonts")));
      },
      'styleguide-png': function() {
        return gulp.src([
                    config.app.dest + "/public/images/*",
                    config.app.dest + "/public/images/*"
                   ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"images")));
      },
      'sass': function(){
   var includePaths = [
        config.app.src,
        'bower_components/font-awesome/scss',
        'bower_components/bootstrap-sass/assets/stylesheets'
    ];

    var bowerCss = wiredep().css;
    var bowerSass = wiredep().scss;

    var files = [].concat(
      [
        path.join(config.app.src, "**/*variables.scss"),
        path.join(config.app.src, "**/*.variables.scss")
      ],
      bowerSass,
      bowerCss,
      [
        path.join(config.app.src, "/**/*mixins.scss"),
        path.join(config.app.src, "/**/*.mixins.scss"),
        path.join(config.app.src, '**/*.css'),
        path.join(config.app.src, '**/*.scss'),
        "!" + path.join(config.app.src, "webapp/public/scss/*")
      ]);

    var outputStyle = "expanded";
    if(grunt.option('production')) outputStyle = "compressed";

    return gulp.src(files)
   .pipe(sourcemaps.init())
    .pipe(concat({
      path:'openlmis.scss'
    }))
    .pipe(sass({
      includePaths: includePaths,
      outputStyle: outputStyle,
    }))
    .pipe(sourcemaps.write())
    .pipe(concat('openlmis.css'))
    .pipe(replace('../','')) // remove non-relative strings
    //Replace UI-Grid font paths
    .pipe(replace('ui-grid.eot','fonts/ui-grid.eot'))
    .pipe(replace('ui-grid.ttf','fonts/ui-grid.ttf'))
    .pipe(replace('ui-grid.woff','fonts/ui-grid.woff'))
    .pipe(replace('ui-grid.svg','fonts/ui-grid.svg'))
    .pipe(bless())
    .pipe(gulp.dest(
      path.join(config.app.dest, "public")
    ));
      }
    }
  });

  grunt.registerTask('sass', ['gulp:sass']);

  function makeURL(key){
    if (!key) {
      return false;
    }
    var url = grunt.option(key) || config[key];
    if (grunt.option('addProxyService') && url && url.substr(0,4).toLowerCase() == "http") {
      return 'http://127.0.0.1:3030/' + url;
    } else {
      return url;
    }
  }

  grunt.registerTask('serve:proxy', 'Start proxy server', function(){
    var host = '127.0.0.1';
    var port = 3030;

    if (grunt.option('addProxyService')){
      grunt.log.writeln('starting proxy server at ' + host + ':' + port);
      cors_proxy.createServer().listen(port, host);
    }
  });

  grunt.registerTask('serve', ['serve:proxy', 'connect:server']);

  var buildTasks = ['clean', 'copy', 'concat', 'sass', 'replace'];
  var styleguideTasks = ['gulp:styleguide-generate', 'gulp:styleguide-png', 'gulp:styleguide-fonts', 'gulp:styleguide-applystyles'];

  if(grunt.option('production')) buildTasks.push('uglify');
  if(grunt.option('test')) buildTasks.push('karma:unit');
  if(grunt.option('styleguide')) buildTasks = buildTasks.concat(styleguideTasks);
  grunt.registerTask('build', buildTasks);

  grunt.registerTask('check', ['clean', 'jshint', 'sasslint']);

  grunt.registerTask('styleguide', ['build'].concat(styleguideTasks));
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var Promise = require('bluebird');
var logger = require('../Logger');
var dbUtil = require('./DbUtil');

var GET_RECIPIENTS = ' select id,firstname,lastname,city,verified,picture from receipient r';
var GET_RECIPIENTSBYID='select * from receipient r,family f   ';
var INSERT_RECIPIENT='INSERT INTO receipient (firstname, lastname, email, contactnumber, address_line1, address_line2, city, state, pincode, verified,moneyrequired,singleparent,marks,picture) values ' +
    '(:firstname, :lastname, :email, :contactnumber, :address_line1, :address_line2, :city, :state, :pincode, :verified,:moneyrequired,:singleparent,:marks,:picture)';
var PREFIXES = {
    receipient: "r"
};

module.exports = function(dbcp) {
    return {
        getRecipients: _.partial(getAllRecipients, dbcp),
        getRecipientById: _.partial(getRecipientByID,dbcp),
        createReceipient: _.partial(createReceipient,dbcp)
    };
};

function createReceipient(dbcp, options) {

    var orderReqId = 0;
    logger.info("receipient info -------> ", options);

    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, INSERT_RECIPIENT, options)
            .then(function(results) {
                res.json(results);
            })

            .catch(function(err) {
                reject(err);
            });
    });
}

/**
 * Gets All Recipients
 */
function getAllRecipients(dbcp, options) {
    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, getRecipientsQuery(options), options)
            .then(function(rows) {
                resolve( _.pluck(rows, PREFIXES.receipient));
            })
            .catch(function(err) {
                reject(err);
            });
    });
}

function getRecipientByID(dbcp, options) {
    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, getRecipientByIdQuery(options), options)
            .then(function(rows) {
                resolve( _.pluck(rows, PREFIXES.receipient));
            })
            .catch(function(err) {
                reject(err);
            });
    });
}

function getRecipientsQuery(options) {

    var query = GET_RECIPIENTS;
console.log(options+' is options');
    if (!_.isUndefined(options.singleparent||options.moneyrequired||options.city||options.marks)) {
        query += ' where ';
    }
    if (!_.isUndefined(options.singleparent)) {
        query += " r.singleparent = :singleparent";

    }
    if (!_.isUndefined(options.moneyrequired)) {
        query += " and r.moneyrequired <= :moneyrequired";
    }
    if (!_.isUndefined(options.city)) {
        query += " and r.city = :city";
    }
    if (!_.isUndefined(options.marks)) {
        query += " and r.marks > :marks";
    }
    return query;
}

function getRecipientByIdQuery(options){
    var query = GET_RECIPIENTSBYID;

    if (!_.isUndefined(options.id)) {
        query += "where  r.id = :id";
        query += " and r.id = f.receipientid";
    }
    return query;
}
function mapOrderRows(rows, prefixes) {
    var finalResult = _.pluck(rows, prefixes.receipient);
    console.log(JSON.stringify(finalResult));
    return finalResult;

}

<commit_msg>Students without family<commit_after>var _ = require('lodash');
var Promise = require('bluebird');
var logger = require('../Logger');
var dbUtil = require('./DbUtil');

var GET_RECIPIENTS = ' select id,firstname,lastname,city,verified,picture from receipient r';
var GET_RECIPIENTSBYID=' select * from receipient r LEFT JOIN family f ON r.id = f.receipientid ';
var INSERT_RECIPIENT='INSERT INTO receipient (firstname, lastname, email, contactnumber, address_line1, address_line2, city, state, pincode, verified,moneyrequired,singleparent,marks,picture) values ' +
    '(:firstname, :lastname, :email, :contactnumber, :address_line1, :address_line2, :city, :state, :pincode, :verified,:moneyrequired,:singleparent,:marks,:picture)';
var PREFIXES = {
    receipient: "r"
};

module.exports = function(dbcp) {
    return {
        getRecipients: _.partial(getAllRecipients, dbcp),
        getRecipientById: _.partial(getRecipientByID,dbcp),
        createReceipient: _.partial(createReceipient,dbcp)
    };
};

function createReceipient(dbcp, options) {

    var orderReqId = 0;
    logger.info("receipient info -------> ", options);

    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, INSERT_RECIPIENT, options)
            .then(function(results) {
                res.json(results);
            })

            .catch(function(err) {
                reject(err);
            });
    });
}

/**
 * Gets All Recipients
 */
function getAllRecipients(dbcp, options) {
    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, getRecipientsQuery(options), options)
            .then(function(rows) {
                resolve( _.pluck(rows, PREFIXES.receipient));
            })
            .catch(function(err) {
                reject(err);
            });
    });
}

function getRecipientByID(dbcp, options) {
    return new Promise(function(resolve, reject) {
        dbUtil.executeQuery(dbcp, getRecipientByIdQuery(options), options)
            .then(function(rows) {
                resolve( _.pluck(rows, PREFIXES.receipient));
            })
            .catch(function(err) {
                reject(err);
            });
    });
}

function getRecipientsQuery(options) {

    var query = GET_RECIPIENTS;
console.log(options+' is options');
    if (!_.isUndefined(options.singleparent||options.moneyrequired||options.city||options.marks)) {
        query += ' where ';
    }
    if (!_.isUndefined(options.singleparent)) {
        query += " r.singleparent = :singleparent";

    }
    if (!_.isUndefined(options.moneyrequired)) {
        query += " and r.moneyrequired <= :moneyrequired";
    }
    if (!_.isUndefined(options.city)) {
        query += " and r.city = :city";
    }
    if (!_.isUndefined(options.marks)) {
        query += " and r.marks > :marks";
    }
    return query;
}

function getRecipientByIdQuery(options){
    var query = GET_RECIPIENTSBYID;

    if (!_.isUndefined(options.id)) {
        query += "where  r.id = :id";
        //query += " and r.id = f.receipientid";
    }
    return query;
}
function mapOrderRows(rows, prefixes) {
    var finalResult = _.pluck(rows, prefixes.receipient);
    console.log(JSON.stringify(finalResult));
    return finalResult;

}

<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-html2js');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        port: 3000,
        base: '.'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: ['src/util.js', 'src/cubes.js', 'src/pager.js', 'src/crosstab.js', 'src/facts.js',
              'src/treemap.js', 'src/panel.js', 'src/workspace.js', 'src/cubes.js',
              'src/tmp/templates.js'],
        dest: 'build/<%= pkg.name %>.min.js'
      }
    },
    concat: {
      options: {
        stripBanners: true,
        separator: ';'
      },
      dist: {
        src: ['src/util.js', 'src/cubes.js', 'src/pager.js', 'src/crosstab.js', 'src/facts.js',
              'src/treemap.js', 'src/panel.js', 'src/workspace.js', 'src/cubes.js',
              'src/tmp/templates.js'],
        dest: 'build/<%= pkg.name %>.js'
      },
    },
    html2js: {
      dist: {
        options: {
          base: '.',
          module: 'ngCubes.templates',
          rename: function(name) {
            return name.replace('templates', 'angular-cubes-templates');
          }
        },
        src: ['templates/**/*.html'],
        dest: 'src/tmp/templates.js'
      }
    },
    less: {
      development: {
        options: {
          paths: ["less"],
          strictImports: true
        },
        files: {
          "build/angular-cubes.css": ["less/build.less"]
        }
      }
    },
    watch: {
      templates: {
        files: ['templates/**/*.html'],
        tasks: ['html2js']
      },
      js: {
        files: ['src/**/*.js'],
        tasks: ['concat', 'uglify']
      },
      style: {
        files: ['less/**/*.less'],
        tasks: ['less']
      },
    }
  });

  grunt.registerTask('default', ['less', 'html2js', 'concat', 'uglify']);
};
<commit_msg>Add grunt server task for easy development<commit_after>module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-html2js');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        port: 3000,
        base: '.'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: ['src/util.js', 'src/cubes.js', 'src/pager.js', 'src/crosstab.js', 'src/facts.js',
              'src/treemap.js', 'src/panel.js', 'src/workspace.js', 'src/cubes.js',
              'src/tmp/templates.js'],
        dest: 'build/<%= pkg.name %>.min.js'
      }
    },
    concat: {
      options: {
        stripBanners: true,
        separator: ';'
      },
      dist: {
        src: ['src/util.js', 'src/cubes.js', 'src/pager.js', 'src/crosstab.js', 'src/facts.js',
              'src/treemap.js', 'src/panel.js', 'src/workspace.js', 'src/cubes.js',
              'src/tmp/templates.js'],
        dest: 'build/<%= pkg.name %>.js'
      },
    },
    html2js: {
      dist: {
        options: {
          base: '.',
          module: 'ngCubes.templates',
          rename: function(name) {
            return name.replace('templates', 'angular-cubes-templates');
          }
        },
        src: ['templates/**/*.html'],
        dest: 'src/tmp/templates.js'
      }
    },
    less: {
      development: {
        options: {
          paths: ["less"],
          strictImports: true
        },
        files: {
          "build/angular-cubes.css": ["less/build.less"]
        }
      }
    },
    watch: {
      templates: {
        files: ['templates/**/*.html'],
        tasks: ['html2js']
      },
      js: {
        files: ['src/**/*.js'],
        tasks: ['concat', 'uglify']
      },
      style: {
        files: ['less/**/*.less'],
        tasks: ['less']
      },
    }
  });

  grunt.registerTask('default', ['less', 'html2js', 'concat', 'uglify']);
  grunt.registerTask('server', ['connect', 'watch'])
};
<|endoftext|>


<commit_before>require('../../handler-base')();

var svnDecorator = require('../../../../api/inboxes/halDecorators/svnDecorator');

var basicSvnHalResponse = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'Svn',
  "name": 'a random name',
  "url": 'http://random.url.com'
};

var basicNonSvnHalResponse = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'anything',
  "name": 'a random name',
  "url": 'http://random.url.com'
};

var expected = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'Svn',
  "name": 'a random name',
  "url": 'http://random.url.com',
  "_embedded": {
    "svn-scripts":[{
      "_links": {
        "self": {
          "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/script?platform=windows"
        }
      },
      "platform": "windows"
    },
    {
      "_links": {
        "self": {
          "href":"/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/script?platform=linux"
        }
      },
      "platform": "linux"
    }]
  }
};

describe('svnDecorator', function() {
  describe('when calling it', function() {
    it('should return the expected value', function() {
      svnDecorator.decorateHalResponse(basicSvnHalResponse).should.deep.equal(expected);
    });
  });

  describe('when asking if it should decorate a svn hal response', function() {
    it('should say that it can', function() {
      svnDecorator.shouldDecorate(basicSvnHalResponse.family).should.equal(true);
    });
  })

  describe('when asking if it should decorate a non-svn hal response', function() {
    it('should say that it can not', function() {
      svnDecorator.shouldDecorate(basicNonSvnHalResponse.family).should.equal(false);
    })
  })
});<commit_msg>S-58989 provide more detailed test expectations<commit_after>require('../../handler-base')();

var svnDecorator = require('../../../../api/inboxes/halDecorators/svnDecorator');

var basicSvnHalResponse = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'Svn',
  "name": 'a random name',
  "url": 'http://random.url.com'
};

var basicNonSvnHalResponse = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'anything',
  "name": 'a random name',
  "url": 'http://random.url.com'
};

var expected = {
  "_links": {
    "self": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    },
    "digest-parent": {
      "href": "/api/11111111-1111-4111-1111-111111111111/digests/33333333-3333-4333-3333-333333333333"
    },
    "add-commit": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/commits"
    },
    "inbox-remove": {
      "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222"
    }
  },
  'inboxId': '22222222-2222-4222-2222-222222222222',
  "family": 'Svn',
  "name": 'a random name',
  "url": 'http://random.url.com',
  "_embedded": {
    "svn-scripts":[{
      "_links": {
        "self": {
          "href": "/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/script?platform=windows"
        }
      },
      "platform": "windows"
    },
    {
      "_links": {
        "self": {
          "href":"/api/11111111-1111-4111-1111-111111111111/inboxes/22222222-2222-4222-2222-222222222222/script?platform=linux"
        }
      },
      "platform": "linux"
    }]
  }
};

describe('svnDecorator', function() {
  describe('when decorating a hal response', function() {
    it('should modify the hal response with svn specific things', function() {
      svnDecorator.decorateHalResponse(basicSvnHalResponse).should.deep.equal(expected);
    });
  });

  describe('when asking if it should decorate a svn hal response', function() {
    it('should say that it can', function() {
      svnDecorator.shouldDecorate(basicSvnHalResponse.family).should.equal(true);
    });
  })

  describe('when asking if it should decorate a non-svn hal response', function() {
    it('should say that it can not', function() {
      svnDecorator.shouldDecorate(basicNonSvnHalResponse.family).should.equal(false);
    })
  })
});<|endoftext|>


<commit_before>var promisify = require("promisify-node");
var path = require("path");
var fs = require("fs");

var whichNativeNodish = require("which-native-nodish");
var prepareForBuild = require("./prepareForBuild");

var exec = promisify(function(command, opts, callback) {
  return require("child_process").exec(command, opts, callback);
});
var nwVersion = null;
var asVersion = null;

var local = path.join.bind(path, __dirname);

return whichNativeNodish("..")
  .then(function(results) {
    nwVersion = results.nwVersion;
    asVersion = results.asVersion;
  })
  .then(function() {
    if (nwVersion) {
      console.info("[nodegit] Must build for node-webkit/nw.js");
      return prepareAndBuild();
    }
    var args = []
    if (asVersion) {
      args.push("--runtime=electron")
      console.info("version: " + asVersion)
      args.push("--target=" + asVersion)
    }
    // if (fs.existsSync(local("../.didntcomefromthenpmregistry"))) {
    //   return prepareAndBuild();
    // }
    if (process.env.BUILD_DEBUG) {
      console.info("[nodegit] Doing a debug build, no fetching allowed.");
      return prepareAndBuild();
    }
    if (process.env.BUILD_ONLY) {
      console.info("[nodegit] BUILD_ONLY is set to true, no fetching allowed.");
      return prepareAndBuild();
    }
    return installWithPreGyp(args)
  });

function installWithPreGyp(args) {
  console.info("[nodegit] Fetching binary from S3.");
  var arguments = args.join(' ')
  return exec("node-pre-gyp install " + arguments)
    .then(
      function() {
        console.info("[nodegit] Completed installation successfully.");
      },
      function(err) {
        console.info("[nodegit] Failed to install prebuilt binary, " +
          "building manually.");
        console.error(err);
        return prepareAndBuild();
      }
    );
}

function prepareAndBuild() {
  console.info("[nodegit] Regenerating and configuring code");
  return prepareForBuild()
    .then(function() {
      return build();
    });
}

function build() {
  console.info("[nodegit] Everything is ready to go, attempting compilation");
  if (nwVersion) {
    console.info("[nodegit] Building native node-webkit module.");
  }
  else {
    console.info("[nodegit] Building native node module.");
  }

  var opts = {
    cwd: ".",
    maxBuffer: Number.MAX_VALUE,
    env: process.env
  };

  var target = "";
  var debug = (process.env.BUILD_DEBUG ? " --debug" : "");
  var builder = "node-gyp";
  var distUrl = "";

  if (asVersion) {
    var home = process.platform == "win32" ?
            process.env.USERPROFILE : process.env.HOME;

    opts.env.HOME = path.join(home, ".atom-shell-gyp");

    target = "--target=" + asVersion;

    distUrl = "--dist-url=https://gh-contractor-zcbenz.s3." +
      "amazonaws.com/atom-shell/dist";
  }
  else if (nwVersion) {
    builder = "nw-gyp";
    target = "--target=" + nwVersion;
  }

  builder = path.resolve(".", "node_modules", ".bin", builder);
  builder = builder.replace(/\s/g, "\\$&");
  var cmd = [builder, "rebuild", target, debug, distUrl]
    .join(" ").trim();

  return exec(cmd, opts)
    .then(function() {
        console.info("[nodegit] Compilation complete.");
        console.info("[nodegit] Completed installation successfully.");
        process.exitCode = 0;
      },
      function(err, stderr) {
        console.error(err);
        console.error(stderr);
        process.exitCode = 13;
      }
    );
}
<commit_msg>Stop the log.<commit_after>var promisify = require("promisify-node");
var path = require("path");
var fs = require("fs");

var whichNativeNodish = require("which-native-nodish");
var prepareForBuild = require("./prepareForBuild");

var exec = promisify(function(command, opts, callback) {
  return require("child_process").exec(command, opts, callback);
});
var nwVersion = null;
var asVersion = null;

var local = path.join.bind(path, __dirname);

return whichNativeNodish("..")
  .then(function(results) {
    nwVersion = results.nwVersion;
    asVersion = results.asVersion;
  })
  .then(function() {
    if (nwVersion) {
      console.info("[nodegit] Must build for node-webkit/nw.js");
      return prepareAndBuild();
    }
    var args = []
    if (asVersion) {
      args.push("--runtime=electron")
      args.push("--target=" + asVersion)
    }
    // if (fs.existsSync(local("../.didntcomefromthenpmregistry"))) {
    //   return prepareAndBuild();
    // }
    if (process.env.BUILD_DEBUG) {
      console.info("[nodegit] Doing a debug build, no fetching allowed.");
      return prepareAndBuild();
    }
    if (process.env.BUILD_ONLY) {
      console.info("[nodegit] BUILD_ONLY is set to true, no fetching allowed.");
      return prepareAndBuild();
    }
    return installWithPreGyp(args)
  });

function installWithPreGyp(args) {
  console.info("[nodegit] Fetching binary from S3.");
  var arguments = args.join(' ')
  return exec("node-pre-gyp install " + arguments)
    .then(
      function() {
        console.info("[nodegit] Completed installation successfully.");
      },
      function(err) {
        console.info("[nodegit] Failed to install prebuilt binary, " +
          "building manually.");
        console.error(err);
        return prepareAndBuild();
      }
    );
}

function prepareAndBuild() {
  console.info("[nodegit] Regenerating and configuring code");
  return prepareForBuild()
    .then(function() {
      return build();
    });
}

function build() {
  console.info("[nodegit] Everything is ready to go, attempting compilation");
  if (nwVersion) {
    console.info("[nodegit] Building native node-webkit module.");
  }
  else {
    console.info("[nodegit] Building native node module.");
  }

  var opts = {
    cwd: ".",
    maxBuffer: Number.MAX_VALUE,
    env: process.env
  };

  var target = "";
  var debug = (process.env.BUILD_DEBUG ? " --debug" : "");
  var builder = "node-gyp";
  var distUrl = "";

  if (asVersion) {
    var home = process.platform == "win32" ?
            process.env.USERPROFILE : process.env.HOME;

    opts.env.HOME = path.join(home, ".atom-shell-gyp");

    target = "--target=" + asVersion;

    distUrl = "--dist-url=https://gh-contractor-zcbenz.s3." +
      "amazonaws.com/atom-shell/dist";
  }
  else if (nwVersion) {
    builder = "nw-gyp";
    target = "--target=" + nwVersion;
  }

  builder = path.resolve(".", "node_modules", ".bin", builder);
  builder = builder.replace(/\s/g, "\\$&");
  var cmd = [builder, "rebuild", target, debug, distUrl]
    .join(" ").trim();

  return exec(cmd, opts)
    .then(function() {
        console.info("[nodegit] Compilation complete.");
        console.info("[nodegit] Completed installation successfully.");
        process.exitCode = 0;
      },
      function(err, stderr) {
        console.error(err);
        console.error(stderr);
        process.exitCode = 13;
      }
    );
}
<|endoftext|>


<commit_before>const npmCheck = require('npm-check');

(async () => {
  const currentState = await npmCheck();
  const packages = currentState.get('packages');
  const unusedPackages = packages.filter(({ unused }) => unused);

  if (unusedPackages.length) {
    const unedPackagesAsString = unusedPackages.map(({ moduleName }) => moduleName).join(',');
    throw new Error(`There are unused dependencies : ${unedPackagesAsString}`);
  }
})();
<commit_msg>fix typo<commit_after>const npmCheck = require('npm-check');

(async () => {
  const currentState = await npmCheck();
  const packages = currentState.get('packages');
  const unusedPackages = packages.filter(({ unused }) => unused);

  if (unusedPackages.length) {
    const unusedPackagesAsString = unusedPackages.map(({ moduleName }) => moduleName).join(',');
    throw new Error(`There are unused dependencies : ${unusedPackagesAsString}`);
  }
})();
<|endoftext|>


<commit_before>$('input[type=checkbox]').click(function(){
  if($(this).is(':checked')){
    $('input[type=submit]').attr('disabled', false)
  } else {
    $('input[type=submit]').attr('disabled', true)
  }
})
$('#show_tips a').click(function(e){
  e.preventDefault()
  $('#more_tips').effect("highlight", {color: "#dfd"}, 1500);
  $(this).hide()
})
$(document).ready(function(){
  $('input[type=submit]').click(CATARSE.requireLogin)
  $('input[type=submit]').show();
  $('.submit_loader').remove()
})
<commit_msg>enable the submit button in guidelines if checked the accept<commit_after>$('input[type=checkbox]').click(function(){
  if($(this).is(':checked')){
    $('input[type=submit]').attr('disabled', false)
  } else {
    $('input[type=submit]').attr('disabled', true)
  }
})
$('#show_tips a').click(function(e){
  e.preventDefault()
  $('#more_tips').effect("highlight", {color: "#dfd"}, 1500);
  $(this).hide()
})
$(document).ready(function(){
  $('input[type=submit]').click(CATARSE.requireLogin)
  $('input[type=submit]').show();
  $('.submit_loader').remove()

  if($('input[type=checkbox]').is(':checked')){
    $('input[type=submit]').attr('disabled', false)
  }
})
<|endoftext|>


<commit_before>"use strict";

import * as JSSynth from "./jssynth";

class Serializer {
  constructor() {};

  static serializeInstrument(instrument) {
    let filterCutoff = parseInt(instrument.filterCutoff, 10);

    let serializedConfig = {
      oscillators: [
        {
          waveform: instrument.waveform1,
          octave: parseInt(instrument.waveform1Octave),
          detune: 0,
        },
        {
          waveform: instrument.waveform2,
          octave: parseInt(instrument.waveform2Octave),
          detune: parseInt(instrument.waveform2Detune),
        }
      ],
      lfo: {
        waveform:  instrument.lfoWaveform,
        frequency: parseFloat(instrument.lfoFrequency),
        amplitude: parseInt(instrument.lfoAmplitude, 10),
      },
      filter: {
        cutoff:    filterCutoff,
        resonance: parseInt(instrument.filterResonance, 10),
        mode: instrument.filterModulator,
        lfo: {
          waveform:  instrument.filterLFOWaveform,
          frequency: parseFloat(instrument.filterLFOFrequency),
          amplitude: parseFloat(instrument.filterLFOAmplitude) * filterCutoff,
        },
        envelope: {
          attack:  parseFloat(instrument.filterEnvelopeAttack),
          decay:   parseFloat(instrument.filterEnvelopeDecay),
          sustain: parseFloat(instrument.filterEnvelopeSustain),
          release: parseFloat(instrument.filterEnvelopeRelease),
        },
      },
      envelope: {
        attack:  parseFloat(instrument.envelopeAttack),
        decay:   parseFloat(instrument.envelopeDecay),
        sustain: parseFloat(instrument.envelopeSustain),
        release: parseFloat(instrument.envelopeRelease),
      },
    };

    return new JSSynth.Instrument(serializedConfig);
  };

  static serializePatterns(patterns) {
    let serializedPatterns = {};

    patterns.forEach(function(pattern) {
      let serializedRows = [];

      pattern.rows.forEach(function(row) {
        let sequence;
        let rawSequenceString;

        rawSequenceString = row.notes.map(function(note) { return note.name; }).join(' ');
        sequence = JSSynth.SequenceParser.parse(rawSequenceString);
        serializedRows.push(sequence);
      });

      serializedPatterns[pattern.id] = serializedRows;
    });

    return serializedPatterns;
  };

  static trackByID(tracks, id) {
    let i;
    for (i = 0; i < tracks.length; i++) {
      if (tracks[i].id === id) {
        return tracks[i];
      }
    }

    return undefined;
  };

  static instrumentByID(instruments, id) {
    let i;
    for (i = 0; i < instruments.length; i++) {
      if (instruments[i].id === id) {
        return instruments[i];
      }
    }

    return undefined;
  };

  static patternsByTrackID(allPatterns, trackID) {
    let i;
    let patterns = [];

    for (i = 0; i < allPatterns.length; i++) {
      if (allPatterns[i].trackID === trackID) {
        patterns.push(allPatterns[i]);
      }
    }

    return patterns;
  };

  static serialize(tracks, instruments, patterns) {
    const MEASURES = 8;
    const STEPS_PER_MEASURE = 16;
    const TOTAL_STEPS = MEASURES * STEPS_PER_MEASURE;

    let i, j;
    let serializedInstrument;
    let serializedPatterns;
    let serializedNotes = [];

    for (i = 0; i < TOTAL_STEPS; i++) {
      serializedNotes[i] = [];
    }

    let trackVolumeMultiplier = 1 / tracks.length;

    tracks.forEach(function(track) {
      if (track.muted) {
        return;
      }

      serializedInstrument = Serializer.serializeInstrument(Serializer.instrumentByID(instruments, track.instrumentID));
      serializedPatterns = Serializer.serializePatterns(Serializer.patternsByTrackID(patterns, track.id));

      for (i = 0; i < track.patterns.length; i++) {
        if (track.patterns[i].patternID !== -1) {
          let sequences = serializedPatterns[track.patterns[i].patternID];

          sequences.forEach(function(sequence) {
            for (j = 0; j < sequence.length; j++) {
              if (sequence[j] && sequence[j].name()) {
                serializedNotes[(i * STEPS_PER_MEASURE) + j].push(new JSSynth.InstrumentNote(sequence[j], serializedInstrument, track.volume * trackVolumeMultiplier));
              }
            }
          });
        }
      }
    });

    return serializedNotes;
  };
};

export { Serializer };
<commit_msg>Extracting variable to avoid repeatedly calculating the same value<commit_after>"use strict";

import * as JSSynth from "./jssynth";

class Serializer {
  constructor() {};

  static serializeInstrument(instrument) {
    let filterCutoff = parseInt(instrument.filterCutoff, 10);

    let serializedConfig = {
      oscillators: [
        {
          waveform: instrument.waveform1,
          octave: parseInt(instrument.waveform1Octave),
          detune: 0,
        },
        {
          waveform: instrument.waveform2,
          octave: parseInt(instrument.waveform2Octave),
          detune: parseInt(instrument.waveform2Detune),
        }
      ],
      lfo: {
        waveform:  instrument.lfoWaveform,
        frequency: parseFloat(instrument.lfoFrequency),
        amplitude: parseInt(instrument.lfoAmplitude, 10),
      },
      filter: {
        cutoff:    filterCutoff,
        resonance: parseInt(instrument.filterResonance, 10),
        mode: instrument.filterModulator,
        lfo: {
          waveform:  instrument.filterLFOWaveform,
          frequency: parseFloat(instrument.filterLFOFrequency),
          amplitude: parseFloat(instrument.filterLFOAmplitude) * filterCutoff,
        },
        envelope: {
          attack:  parseFloat(instrument.filterEnvelopeAttack),
          decay:   parseFloat(instrument.filterEnvelopeDecay),
          sustain: parseFloat(instrument.filterEnvelopeSustain),
          release: parseFloat(instrument.filterEnvelopeRelease),
        },
      },
      envelope: {
        attack:  parseFloat(instrument.envelopeAttack),
        decay:   parseFloat(instrument.envelopeDecay),
        sustain: parseFloat(instrument.envelopeSustain),
        release: parseFloat(instrument.envelopeRelease),
      },
    };

    return new JSSynth.Instrument(serializedConfig);
  };

  static serializePatterns(patterns) {
    let serializedPatterns = {};

    patterns.forEach(function(pattern) {
      let serializedRows = [];

      pattern.rows.forEach(function(row) {
        let sequence;
        let rawSequenceString;

        rawSequenceString = row.notes.map(function(note) { return note.name; }).join(' ');
        sequence = JSSynth.SequenceParser.parse(rawSequenceString);
        serializedRows.push(sequence);
      });

      serializedPatterns[pattern.id] = serializedRows;
    });

    return serializedPatterns;
  };

  static trackByID(tracks, id) {
    let i;
    for (i = 0; i < tracks.length; i++) {
      if (tracks[i].id === id) {
        return tracks[i];
      }
    }

    return undefined;
  };

  static instrumentByID(instruments, id) {
    let i;
    for (i = 0; i < instruments.length; i++) {
      if (instruments[i].id === id) {
        return instruments[i];
      }
    }

    return undefined;
  };

  static patternsByTrackID(allPatterns, trackID) {
    let i;
    let patterns = [];

    for (i = 0; i < allPatterns.length; i++) {
      if (allPatterns[i].trackID === trackID) {
        patterns.push(allPatterns[i]);
      }
    }

    return patterns;
  };

  static serialize(tracks, instruments, patterns) {
    const MEASURES = 8;
    const STEPS_PER_MEASURE = 16;
    const TOTAL_STEPS = MEASURES * STEPS_PER_MEASURE;

    let i, j;
    let serializedInstrument;
    let serializedPatterns;
    let serializedNotes = [];

    for (i = 0; i < TOTAL_STEPS; i++) {
      serializedNotes[i] = [];
    }

    let trackVolumeMultiplier = 1 / tracks.length;

    tracks.forEach(function(track) {
      let trackVolume = track.volume * trackVolumeMultiplier;

      if (track.muted) {
        return;
      }

      serializedInstrument = Serializer.serializeInstrument(Serializer.instrumentByID(instruments, track.instrumentID));
      serializedPatterns = Serializer.serializePatterns(Serializer.patternsByTrackID(patterns, track.id));

      for (i = 0; i < track.patterns.length; i++) {
        if (track.patterns[i].patternID !== -1) {
          let sequences = serializedPatterns[track.patterns[i].patternID];

          sequences.forEach(function(sequence) {
            for (j = 0; j < sequence.length; j++) {
              if (sequence[j] && sequence[j].name()) {
                serializedNotes[(i * STEPS_PER_MEASURE) + j].push(new JSSynth.InstrumentNote(sequence[j], serializedInstrument, trackVolume));
              }
            }
          });
        }
      }
    });

    return serializedNotes;
  };
};

export { Serializer };
<|endoftext|>


<commit_before>function GameState() { }

var types = {
  PLAYER: 1,
  BULLET: 2
};

var ready_for_render = false;

GameState.prototype.connectWebsocket = function() {
  var ws = new WebSocket('ws://localhost:1337', 'echo-protocol');
  var that = this;
  this.ws = ws;
  this.wsReady = false;
  this.players = {};

  console.log("connecting to websocket");
  ws.addEventListener('open', function(e) {
    that.wsReady = true;
    console.log("Connected");
    ws.send(JSON.stringify({
      type: 'join',
      name: that.player.name
    }));
  });
  ws.addEventListener('message', function(e) {
    message = JSON.parse(e.data);
    if(message.type == 'state') {
      oldstates = that.states;
      that.states = [that.states[1]
                    ,that.states[2]
                    ,message.state];
      that.playSounds(message.state.sounds);
    } else if (message.type == 'join') {
      that.players[message.id] = new Player(message.name);
      if(message.you) {
        that.youId = message.id;
        var team = message.team == 0 ? 'light' : 'dark';
        ready_for_render = true;
      }
    }
  });
};

GameState.prototype.init = function() {
  this.bg = loadImage('res/ggj-bg.jpg');
  this.bgDark = loadImage('res/ggj-bg-dark.jpg');
  this.bgLight = loadImage('res/ggj-bg-light.jpg');
  this.playerImgLight = loadImage('res/player-light.png');
  this.playerImgDark = loadImage('res/player-dark.png');
  this.pointsOverlay = loadImage('res/points-overlay.png');
  this.ps = new ParticleSystem();

  var soundPath = 'res/sounds/';
  for (var soundName in SOUNDS.byName) {
    if (SOUNDS.byName.hasOwnProperty(soundName)) {
      createjs.Sound.registerSound(soundPath + soundName, soundName);
    }
  }
};

GameState.prototype.pause = function() {
};

GameState.prototype.resume = function() {
  var that = this;
  this.elements = [
    [function() {
    }, {x: 7.5, y: 4, w: 1, h: 1}],
    [function() {
      mm.audioButton.toggleActivated();
    }, {x: 15, y: 0, w: 1, h: 1}]
  ];
  var playerName = document.getElementById('player-name-input').value;
  this.player = new Player(playerName);
  localStorage.playerName = playerName;
  this.connectWebsocket();
  this.scoreL = 8;
  this.scoreD = 0;
  this.cameraZoom = 0.5;
  this.cameraX = 0;
  this.cameraY = 0;
  this.states = [];
};

GameState.prototype.render = function(ctx) {

  var states = this.states;
  if(states[0] && ready_for_render) {
    if(tick < states[0].tick){
      tick = states[0].tick; //global variables <3  ...
      console.log("Local tick too long behind");
    }
    if(tick >= states[2].tick){
      tick = states[2].tick - 1; //Don't go past last tick, remember we are adding subticks too
      console.log("Local tick too far ahead");
    }

    var state = tick >= states[1].tick ? states[1] : states[0];
    var state_next = tick >= states[1].tick ? states[2] : states[1];

    var coeff = (tick + dt/15 - state.tick) / (state_next.tick - state.tick);

    var players      = state.players;
    var players_next = state_next.players;

    var you = players[this.youId];
    var you_next = players_next[this.youId];
    if(you_next && you){
      var you_x = you.x * (1 - coeff) + you_next.x * coeff;
      var you_y = you.y * (1 - coeff) + you_next.y * coeff;
      this.cameraX = you_x;
      this.cameraY = you_y;

    } else if(you){
      this.cameraX = you.x;
      this.cameraY = you.y;

    } else {
      this.cameraX = 8;
      this.cameraY = 5;
    }

    var capture_points      = state.capture_points;
    var capture_points_next = state_next.capture_points;
    var total_ownage_d = 0;
    for(var i in capture_points) {
      total_ownage_d += capture_points[i].ownage_d;
    }

    ctx.save();
    ctx.translate(8 * GU - this.cameraX * GU * this.cameraZoom,
        4.5 * GU - this.cameraY * GU * this.cameraZoom);
    ctx.scale(this.cameraZoom, this.cameraZoom);
    ctx.save();
    ctx.scale(16 * GU / 1920 * 4, 16 * GU / 1920 * 4);
    ctx.drawImage(this.bg, 0, 0);
    ctx.globalAlpha = Math.pow(Math.max(0, total_ownage_d / 5), 4);
    ctx.drawImage(this.bgDark, 0, 0);
    ctx.globalAlpha = Math.pow(Math.max(0, -total_ownage_d / 5), 4);
    ctx.drawImage(this.bgLight, 0, 0);
    ctx.restore();

    for(var i in capture_points) {
      CapturePoint.prototype.render.call(
          capture_points[i],
          ctx,
          capture_points_next[i],
          this.cpNeutralImg);
    }

    for(var i in players) {
      var player = players[i];
      var player_next = players_next[i];
      var name = this.players[i].name;
      Character.prototype.render.call(
          player,
          ctx,
          player_next,
          coeff,
          this.playerImgLight,
          this.playerImgDark,
          name);
    }

    var bullets      = state.bullets;
    var bullets_next = state_next.bullets;
    for(var i in bullets) {
      var bullet = bullets[i];
      var bullet_next = bullets_next[i];
      Bullet.prototype.render.call(bullet, ctx, bullet_next, coeff);
      if(bullet && bullet_next == undefined) {
        var color = bullet.team == 0 ? 255 : 19;
        this.ps.explode(bullet.x, bullet.y, color, color, color);
      }
    }

    this.ps.render(ctx);

    ctx.restore();

    ctx.save();
    ctx.scale(16 * GU / 1920, 16 * GU / 1920);
    ctx.drawImage(this.pointsOverlay, 0, 0);
    ctx.restore();

    ctx.fillStyle = 'white';
    ctx.fillRect(104 / 1920 * 16 * GU, 19 / 1920 * 16 * GU,
        374 / 1920 * 16 * GU * state.light_points / 100 / 300,
     12 / 1920 * 16 * GU);
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    ctx.font = (0.1 * GU) + 'px monospace';

    if(state.light_points / 300 > 0) {
      ctx.fillText('' + (state.light_points / 300 | 0),
          (104 + 10 + (state.light_points / 100 / 300) * 374) / 1920 * 16 * GU,
          18 / 1920 * 16 * GU);
    }
    ctx.fillStyle = '#191919';
    ctx.fillRect(104 / 1920 * 16 * GU, 69 / 1920 * 16 * GU,
        374 / 1920 * 16 * GU * state.dark_points / 100 / 300,
     12 / 1920 * 16 * GU);

    if(state.dark_points / 300 > 0) {
      ctx.fillStyle = 'white';
      ctx.fillText('' + (state.dark_points / 300 | 0),
          (104 + 10 + (state.dark_points / 100 / 300) * 374) / 1920 * 16 * GU,
          67 / 1920 * 16 * GU);
    }

    if(this.activeSoundDisplayTimer) {
      ctx.save();
      ctx.globalAlpha =  clamp(0, this.activeSoundDisplayTimer / 100, 1);
      ctx.font = (0.4 * GU) + 'px Arial';

      ctx.textAlign = 'left';
      ctx.fillText('\uD83D\uDD0A ' + this.activeSoundDisplayMessage,
          7 * GU - this.activeSoundDisplayTimer / 100 * GU * 0.5,
          0.17 * GU);
      ctx.restore();
    }

    ctx.save();
    ctx.globalAlpha = 0.5;
    ctx.translate(13.5 * GU, 6.5 * GU);
    ctx.scale(16 * GU / 1920 * 0.15, 16 * GU / 1920 * 0.15);
    ctx.drawImage(this.bg, 0, 0);
    ctx.strokeStyle = 'white';
    ctx.lineWidth = 0.05 * GU;
    ctx.strokeRect(0, 0, this.bg.width, this.bg.height);
    ctx.scale(0.325, 0.325);
    ctx.globalAlpha = 0.8;
    for(var i in capture_points) {
      CapturePoint.prototype.render.call(
          capture_points[i],
          ctx,
          capture_points_next[i],
          this.cpNeutralImg);
    }
    ctx.restore();

    if(KEYS[9]){ //TAB
      TabOverlay.render(ctx, players, this.players);
    }

    // Announce the winner if the winning condition is met.
    ctx.save();
    ctx.font = 0.5 * GU + 'px Arial';
    ctx.textAlign = 'center';
    ctx.baseLine = 'bottom';
    if (state.dark_points > 300) {
      if(!KEYS[9]) {
        TabOverlay.render(ctx, players, this.players);
      }
      ctx.fillStyle = '#191919';
      ctx.fillRect(4 * GU, 7 * GU, 8 * GU, 1.6 * GU);
      ctx.fillStyle = 'white';
      ctx.fillText(
        'Dark team wins! Restarting game...',
        8 * GU, 7.5 * GU);
    }
    if (state.light_points > 30000) {
      if(!KEYS[9]) {
        TabOverlay.render(ctx, players, this.players);
      }
      ctx.fillStyle = 'white';
      ctx.fillRect(3 * GU, 7 * GU, 10 * GU, 1.6 * GU);
      ctx.fillStyle = '#191919';
      ctx.fillText(
        'LIGHT TEAM WINS! Restarting game...',
        8 * GU, 7.5 * GU);
    }
    ctx.save();
    if (you) {
      Character.prototype.renderUi.call(you, ctx);
    }
  }

  mm.audioButton.render();
};

GameState.prototype.update = function() {
  var that = this;
  this.ps.update();

  if(this.activeSoundDisplayTimer) {
    this.activeSoundDisplayTimer--;
  }

  if(MOUSE.scrollY) {
    this.cameraZoom *= 1 / ((MOUSE.scrollY + 1000) / 1000);
    this.cameraZoom = clamp(0.42, this.cameraZoom, 3);
  }

  var mouseDir = Math.atan2(
    MOUSE.y - 4.5,
    MOUSE.x - 8);

  if(this.wsReady) {
    var inputs = [];
    this.ws.send(JSON.stringify({
      type: 'inputs',
      inputs: [
      KEYS[87] || KEYS[38], // W, up arrow
      KEYS[83] || KEYS[40], // S, down arrow
      KEYS[65] || KEYS[37], // A, left arrow
      KEYS[68] || KEYS[39],  // D, right arrow
      MOUSE.left,
      MOUSE.right,
      mouseDir
      ]
    }));
  }
};

GameState.prototype.playSounds = function(soundIds) {
  for (var i = 0; i < soundIds.length; i++) {
    var soundName = SOUNDS.byId[soundIds[i]];
    console.log('playing', soundName);
    createjs.Sound.play(soundName);
    var message = SOUNDS.message[soundName];
    if(message) {
      this.activeSoundDisplayTimer = 200;
      this.activeSoundDisplayMessage = message;
    }
  }
};
<commit_msg>Fix accidental win state bug<commit_after>function GameState() { }

var types = {
  PLAYER: 1,
  BULLET: 2
};

var ready_for_render = false;

GameState.prototype.connectWebsocket = function() {
  var ws = new WebSocket('ws://localhost:1337', 'echo-protocol');
  var that = this;
  this.ws = ws;
  this.wsReady = false;
  this.players = {};

  console.log("connecting to websocket");
  ws.addEventListener('open', function(e) {
    that.wsReady = true;
    console.log("Connected");
    ws.send(JSON.stringify({
      type: 'join',
      name: that.player.name
    }));
  });
  ws.addEventListener('message', function(e) {
    message = JSON.parse(e.data);
    if(message.type == 'state') {
      oldstates = that.states;
      that.states = [that.states[1]
                    ,that.states[2]
                    ,message.state];
      that.playSounds(message.state.sounds);
    } else if (message.type == 'join') {
      that.players[message.id] = new Player(message.name);
      if(message.you) {
        that.youId = message.id;
        var team = message.team == 0 ? 'light' : 'dark';
        ready_for_render = true;
      }
    }
  });
};

GameState.prototype.init = function() {
  this.bg = loadImage('res/ggj-bg.jpg');
  this.bgDark = loadImage('res/ggj-bg-dark.jpg');
  this.bgLight = loadImage('res/ggj-bg-light.jpg');
  this.playerImgLight = loadImage('res/player-light.png');
  this.playerImgDark = loadImage('res/player-dark.png');
  this.pointsOverlay = loadImage('res/points-overlay.png');
  this.ps = new ParticleSystem();

  var soundPath = 'res/sounds/';
  for (var soundName in SOUNDS.byName) {
    if (SOUNDS.byName.hasOwnProperty(soundName)) {
      createjs.Sound.registerSound(soundPath + soundName, soundName);
    }
  }
};

GameState.prototype.pause = function() {
};

GameState.prototype.resume = function() {
  var that = this;
  this.elements = [
    [function() {
    }, {x: 7.5, y: 4, w: 1, h: 1}],
    [function() {
      mm.audioButton.toggleActivated();
    }, {x: 15, y: 0, w: 1, h: 1}]
  ];
  var playerName = document.getElementById('player-name-input').value;
  this.player = new Player(playerName);
  localStorage.playerName = playerName;
  this.connectWebsocket();
  this.scoreL = 8;
  this.scoreD = 0;
  this.cameraZoom = 0.5;
  this.cameraX = 0;
  this.cameraY = 0;
  this.states = [];
};

GameState.prototype.render = function(ctx) {

  var states = this.states;
  if(states[0] && ready_for_render) {
    if(tick < states[0].tick){
      tick = states[0].tick; //global variables <3  ...
      console.log("Local tick too long behind");
    }
    if(tick >= states[2].tick){
      tick = states[2].tick - 1; //Don't go past last tick, remember we are adding subticks too
      console.log("Local tick too far ahead");
    }

    var state = tick >= states[1].tick ? states[1] : states[0];
    var state_next = tick >= states[1].tick ? states[2] : states[1];

    var coeff = (tick + dt/15 - state.tick) / (state_next.tick - state.tick);

    var players      = state.players;
    var players_next = state_next.players;

    var you = players[this.youId];
    var you_next = players_next[this.youId];
    if(you_next && you){
      var you_x = you.x * (1 - coeff) + you_next.x * coeff;
      var you_y = you.y * (1 - coeff) + you_next.y * coeff;
      this.cameraX = you_x;
      this.cameraY = you_y;

    } else if(you){
      this.cameraX = you.x;
      this.cameraY = you.y;

    } else {
      this.cameraX = 8;
      this.cameraY = 5;
    }

    var capture_points      = state.capture_points;
    var capture_points_next = state_next.capture_points;
    var total_ownage_d = 0;
    for(var i in capture_points) {
      total_ownage_d += capture_points[i].ownage_d;
    }

    ctx.save();
    ctx.translate(8 * GU - this.cameraX * GU * this.cameraZoom,
        4.5 * GU - this.cameraY * GU * this.cameraZoom);
    ctx.scale(this.cameraZoom, this.cameraZoom);
    ctx.save();
    ctx.scale(16 * GU / 1920 * 4, 16 * GU / 1920 * 4);
    ctx.drawImage(this.bg, 0, 0);
    ctx.globalAlpha = Math.pow(Math.max(0, total_ownage_d / 5), 4);
    ctx.drawImage(this.bgDark, 0, 0);
    ctx.globalAlpha = Math.pow(Math.max(0, -total_ownage_d / 5), 4);
    ctx.drawImage(this.bgLight, 0, 0);
    ctx.restore();

    for(var i in capture_points) {
      CapturePoint.prototype.render.call(
          capture_points[i],
          ctx,
          capture_points_next[i],
          this.cpNeutralImg);
    }

    for(var i in players) {
      var player = players[i];
      var player_next = players_next[i];
      var name = this.players[i].name;
      Character.prototype.render.call(
          player,
          ctx,
          player_next,
          coeff,
          this.playerImgLight,
          this.playerImgDark,
          name);
    }

    var bullets      = state.bullets;
    var bullets_next = state_next.bullets;
    for(var i in bullets) {
      var bullet = bullets[i];
      var bullet_next = bullets_next[i];
      Bullet.prototype.render.call(bullet, ctx, bullet_next, coeff);
      if(bullet && bullet_next == undefined) {
        var color = bullet.team == 0 ? 255 : 19;
        this.ps.explode(bullet.x, bullet.y, color, color, color);
      }
    }

    this.ps.render(ctx);

    ctx.restore();

    ctx.save();
    ctx.scale(16 * GU / 1920, 16 * GU / 1920);
    ctx.drawImage(this.pointsOverlay, 0, 0);
    ctx.restore();

    ctx.fillStyle = 'white';
    ctx.fillRect(104 / 1920 * 16 * GU, 19 / 1920 * 16 * GU,
        374 / 1920 * 16 * GU * state.light_points / 100 / 300,
     12 / 1920 * 16 * GU);
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    ctx.font = (0.1 * GU) + 'px monospace';

    if(state.light_points / 300 > 0) {
      ctx.fillText('' + (state.light_points / 300 | 0),
          (104 + 10 + (state.light_points / 100 / 300) * 374) / 1920 * 16 * GU,
          18 / 1920 * 16 * GU);
    }
    ctx.fillStyle = '#191919';
    ctx.fillRect(104 / 1920 * 16 * GU, 69 / 1920 * 16 * GU,
        374 / 1920 * 16 * GU * state.dark_points / 100 / 300,
     12 / 1920 * 16 * GU);

    if(state.dark_points / 300 > 0) {
      ctx.fillStyle = 'white';
      ctx.fillText('' + (state.dark_points / 300 | 0),
          (104 + 10 + (state.dark_points / 100 / 300) * 374) / 1920 * 16 * GU,
          67 / 1920 * 16 * GU);
    }

    if(this.activeSoundDisplayTimer) {
      ctx.save();
      ctx.globalAlpha =  clamp(0, this.activeSoundDisplayTimer / 100, 1);
      ctx.font = (0.4 * GU) + 'px Arial';

      ctx.textAlign = 'left';
      ctx.fillText('\uD83D\uDD0A ' + this.activeSoundDisplayMessage,
          7 * GU - this.activeSoundDisplayTimer / 100 * GU * 0.5,
          0.17 * GU);
      ctx.restore();
    }

    ctx.save();
    ctx.globalAlpha = 0.5;
    ctx.translate(13.5 * GU, 6.5 * GU);
    ctx.scale(16 * GU / 1920 * 0.15, 16 * GU / 1920 * 0.15);
    ctx.drawImage(this.bg, 0, 0);
    ctx.strokeStyle = 'white';
    ctx.lineWidth = 0.05 * GU;
    ctx.strokeRect(0, 0, this.bg.width, this.bg.height);
    ctx.scale(0.325, 0.325);
    ctx.globalAlpha = 0.8;
    for(var i in capture_points) {
      CapturePoint.prototype.render.call(
          capture_points[i],
          ctx,
          capture_points_next[i],
          this.cpNeutralImg);
    }
    ctx.restore();

    if(KEYS[9]){ //TAB
      TabOverlay.render(ctx, players, this.players);
    }

    // Announce the winner if the winning condition is met.
    ctx.save();
    ctx.font = 0.5 * GU + 'px Arial';
    ctx.textAlign = 'center';
    ctx.baseLine = 'bottom';
    if (state.dark_points > 30000) {
      if(!KEYS[9]) {
        TabOverlay.render(ctx, players, this.players);
      }
      ctx.fillStyle = '#191919';
      ctx.fillRect(4 * GU, 7 * GU, 8 * GU, 1.6 * GU);
      ctx.fillStyle = 'white';
      ctx.fillText(
        'Dark team wins! Restarting game...',
        8 * GU, 7.5 * GU);
    }
    if (state.light_points > 30000) {
      if(!KEYS[9]) {
        TabOverlay.render(ctx, players, this.players);
      }
      ctx.fillStyle = 'white';
      ctx.fillRect(3 * GU, 7 * GU, 10 * GU, 1.6 * GU);
      ctx.fillStyle = '#191919';
      ctx.fillText(
        'LIGHT TEAM WINS! Restarting game...',
        8 * GU, 7.5 * GU);
    }
    ctx.save();
    if (you) {
      Character.prototype.renderUi.call(you, ctx);
    }
  }

  mm.audioButton.render();
};

GameState.prototype.update = function() {
  var that = this;
  this.ps.update();

  if(this.activeSoundDisplayTimer) {
    this.activeSoundDisplayTimer--;
  }

  if(MOUSE.scrollY) {
    this.cameraZoom *= 1 / ((MOUSE.scrollY + 1000) / 1000);
    this.cameraZoom = clamp(0.42, this.cameraZoom, 3);
  }

  var mouseDir = Math.atan2(
    MOUSE.y - 4.5,
    MOUSE.x - 8);

  if(this.wsReady) {
    var inputs = [];
    this.ws.send(JSON.stringify({
      type: 'inputs',
      inputs: [
      KEYS[87] || KEYS[38], // W, up arrow
      KEYS[83] || KEYS[40], // S, down arrow
      KEYS[65] || KEYS[37], // A, left arrow
      KEYS[68] || KEYS[39],  // D, right arrow
      MOUSE.left,
      MOUSE.right,
      mouseDir
      ]
    }));
  }
};

GameState.prototype.playSounds = function(soundIds) {
  for (var i = 0; i < soundIds.length; i++) {
    var soundName = SOUNDS.byId[soundIds[i]];
    console.log('playing', soundName);
    createjs.Sound.play(soundName);
    var message = SOUNDS.message[soundName];
    if(message) {
      this.activeSoundDisplayTimer = 200;
      this.activeSoundDisplayMessage = message;
    }
  }
};
<|endoftext|>