<commit_before>var os=require('os');

module.exports = function(grunt) {
  'use strict';

  grunt.option.init({
    port: 8008
  });

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    bowercopy: {
      options: {
        clean: true
      },
      top: {
        options: {
          destPrefix: 'content'
        },
        files: {
          'lib/almond.js': 'almond/almond.js',
          'lib/coffee-script.js': 'coffee-script/extras/coffee-script.js',
          'lib/droplet.js': 'droplet/dist/droplet-full.js',
          'lib/droplet.css': 'droplet/dist/droplet.min.css',
          'lib/iced-coffee-script.js':
             'iced-coffee-script/extras/coffee-script.js',
          'lib/jquery.js' : 'jquery/dist/jquery.js',
          'lib/jquery.autocomplete.js':
              'devbridge-autocomplete/dist/jquery.autocomplete.js',
          'lib/jquery.autocomplete.min.js':
              'devbridge-autocomplete/dist/jquery.autocomplete.min.js',
          'lib/jquery-deparam.js' : 'jquery-deparam/jquery-deparam.js',
          'lib/jquery-turtle.js': 'jquery-turtle/jquery-turtle.js',
          'lib/lodash.js': 'lodash/dist/lodash.js',
          'lib/require.js': 'requirejs/require.js',
          'lib/seedrandom.js': 'seedrandom/seedrandom.js',
          'lib/socket.io.js': 'socket.io-client/socket.io.js'
        }
      },
      zeroclipboard: {
        options: {
          destPrefix: 'content/lib/zeroclipboard'
        },
        files: {
          'ZeroClipboard.js' : 'zeroclipboard/dist/ZeroClipboard.js',
          'ZeroClipboard.swf' : 'zeroclipboard/dist/ZeroClipboard.swf'
        }
      },
      tooltipster: {
        options: {
          destPrefix: 'content/lib/tooltipster'
        },
        files: {
          'js': 'tooltipster/js',
          'css': 'tooltipster/css'
        }
      },
      lib: {
        options: {
          destPrefix: 'content/lib'
        },
        files: {
          'ace' : 'ace-builds/src-min-noconflict',
          'bootstrap' : 'bootstrap'
        }
      },
      sourcemap: {
        options: {
          destPrefix: 'content/lib/sourcemap'
        },
        files: {
          'array-set.js': 'source-map/lib/source-map/array-set.js',
          'base64.js': 'source-map/lib/source-map/base64.js',
          'base64-vlq.js': 'source-map/lib/source-map/base64-vlq.js',
          'binary-search.js': 'source-map/lib/source-map/binary-search.js',
          'source-map-consumer.js':
              'source-map/lib/source-map/source-map-consumer.js',
          'util.js': 'source-map/lib/source-map/util.js'
        }
      }
    },
    requirejs: {
      compile: {
        options: {
          baseUrl: 'content',
          deps: ['src/editor-main'],
          name: 'lib/almond',
          out: 'content/editor.js',
          // optimize: 'none',
          mainConfigFile: 'content/src/editor-main.js',
          preserveLicenseComments: false
        }
      }
    },
    replace: {
      dist: {
        options: {
          patterns: [ {
            match:
              /<script data-main=".*\/([^\/"-]*)-main" src=".*require.js">/,
            replacement:
              "<script src=\"//<!--#echo var=\"site\"-->/$1.js\"></script>"
          } ]
        },
        files: [ {
          expand: true,
          flatten: true,
          src: [
            'content/src/editor.html',
            'content/src/framed.html'
          ],
          dest: 'content'
        } ]
      }
    },
    uglify: {
      all: {
        files: {
          'content/turtlebits.js': [
            'content/lib/iced-coffee-script.js',
            'content/lib/jquery.js',
            'content/lib/jquery-turtle.js',
            'content/lib/lodash.js',
            'content/lib/seedrandom.js',
            'content/lib/socket.io.js',
            'content/src/showturtle.js'
          ]
        },
        options: {
          preserveComments: false,
          report: 'min',
          beautify: {
            ascii_only: true
          }
        }
      }
    },
    less: {
      all: {
        options: { compress: true },
        files: {
          "content/welcome.css": "content/src/welcome.less",
          "content/editor.css": "content/src/editor.less"
        }
      }
    },
    concat: {
      all: {
        src: [
          'content/lib/iced-coffee-script.js',
          'content/lib/jquery.js',
          'content/lib/jquery-turtle.js',
          'content/lib/lodash.js',
          'content/lib/seedrandom.js',
          'content/lib/socket.io.js',
          'content/src/showturtle.js'
        ],
        dest: 'content/turtlebits.js'
      },
      options: {
        separator: ';'
      }
    },
    express: {
      options: {
        port: grunt.option('port'),
        output: 'listening'
      },
      dev: {
        options: {
          script: 'server/devserver.js',
          node_env: 'development'
        }
      },
      localtest: {
        options: {
          script: 'server/devserver.js',
          node_env: 'test'
        }
      },
      devtest: {
        options: {
          script: 'server/devserver.js',
          node_env: 'development',
          port: 8193
        }
      },
      test: {
        options: {
          script: 'server/devserver.js',
          node_env: 'test',
          port: 8193
        }
      }
    },
    sed: {
      iced: {
        pattern: '\n\\(function\\(root\\)',
        replacement: '\nthis.CoffeeScript||(function(root)',
        path: 'content/lib/iced-coffee-script.js',
        recursive: false
      }
    },
    watch: {
      sources: {
        files: [
          'server/*.js',
          'server/*.json',
          'content/src/filetype.js' ],
        options: { spawn: false }
      }
    },
    copy: {
      testdata: {
        files: [ {
          expand: true,
          cwd: 'test/data/',
          src: ['**'],
          dot: true,
          dest: 'local/data'
        } ]
      }
    },
    mochaTest: {
      test: {
        src: ['test/*.js'],
        options: {
          timeout: 100000,
          reporter: 'list',
          colors: false
        }
      }
    },
    'node-inspector': {
      dev: { }
    }
  });

  grunt.loadNpmTasks('grunt-bowercopy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-express-server');
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-node-inspector');
  grunt.loadNpmTasks('grunt-replace');
  grunt.loadNpmTasks('grunt-sed');

  grunt.registerTask('proxymessage', 'Show proxy instructions', function() {
    var port = grunt.option('port');
    var ifaces = os.networkInterfaces();
    grunt.log.writeln(
      'Point your browser proxy autoconfig to one of these (or download\n' +
      'a local copy of one of these proxy.pacs).  Then the dev server\n' +
      'can be used at http://pencilcode.net.dev/');
    for (var dev in ifaces) {
      ifaces[dev].forEach(function(details) {
        if (details.family == 'IPv4') {
          grunt.log.writeln(
            'http://' + details.address + ':' + port + '/proxy.pac');
        }
      });
    }
  });

  grunt.task.registerTask('builddate', 'Create builddate.txt file', function() {
    var stamp = grunt.template.today('dddd, mmmm dS, yyyy, HH:MM:ss Z');
    grunt.file.write('content/builddate.txt', stamp);
    grunt.log.writeln('Build date: ' + stamp);
  });

  grunt.task.registerTask('test', 'Run integration tests.',
  function(testname) {
    if (!!testname) {
      grunt.config('mochaTest.test.src', ['test/' + testname + '.js']);
    }
    grunt.task.run('copy:testdata');
    grunt.task.run('express:test');
    grunt.task.run('mochaTest');
  });

  grunt.task.registerTask('devtest', 'Run tests using uncompiled code.',
  function(testname) {
    if (!!testname) {
      grunt.config('mochaTest.test.src', ['test/' + testname + '.js']);
    }
    grunt.task.run('express:devtest');
    grunt.task.run('mochaTest');
  });

  // "update" does a bowercopy and a sed.
  grunt.registerTask('update', ['bowercopy', 'sed']);
  // "devserver" serves editor code directly from the src directory.
  grunt.registerTask('devserver',
      ['proxymessage', 'express:dev', 'node-inspector:dev', 'watch']);
  // "devserver" serves editor code directly from the src directory.
  grunt.registerTask('testserver',
      ['proxymessage', 'express:localtest', 'node-inspector:dev', 'watch']);
  // "debug" overwrites turtlebits.js with an unminified version.
  grunt.registerTask('debug', ['concat', 'devtest']);
  // "build", for development, builds code without running tests.
  grunt.registerTask('build', ['requirejs', 'replace', 'builddate']);
  // default target: compile editor code and uglify turtlebits.js, and test it.
  grunt.registerTask('default',
      ['requirejs', 'replace', 'uglify', 'less', 'builddate', 'test']);
};

<commit_msg>More aggressive uglification.<commit_after>var os=require('os');

module.exports = function(grunt) {
  'use strict';

  grunt.option.init({
    port: 8008
  });

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    bowercopy: {
      options: {
        clean: true
      },
      top: {
        options: {
          destPrefix: 'content'
        },
        files: {
          'lib/almond.js': 'almond/almond.js',
          'lib/coffee-script.js': 'coffee-script/extras/coffee-script.js',
          'lib/droplet.js': 'droplet/dist/droplet-full.js',
          'lib/droplet.css': 'droplet/dist/droplet.min.css',
          'lib/iced-coffee-script.js':
             'iced-coffee-script/extras/coffee-script.js',
          'lib/jquery.js' : 'jquery/dist/jquery.js',
          'lib/jquery.autocomplete.js':
              'devbridge-autocomplete/dist/jquery.autocomplete.js',
          'lib/jquery.autocomplete.min.js':
              'devbridge-autocomplete/dist/jquery.autocomplete.min.js',
          'lib/jquery-deparam.js' : 'jquery-deparam/jquery-deparam.js',
          'lib/jquery-turtle.js': 'jquery-turtle/jquery-turtle.js',
          'lib/lodash.js': 'lodash/dist/lodash.js',
          'lib/require.js': 'requirejs/require.js',
          'lib/seedrandom.js': 'seedrandom/seedrandom.js',
          'lib/socket.io.js': 'socket.io-client/socket.io.js'
        }
      },
      zeroclipboard: {
        options: {
          destPrefix: 'content/lib/zeroclipboard'
        },
        files: {
          'ZeroClipboard.js' : 'zeroclipboard/dist/ZeroClipboard.js',
          'ZeroClipboard.swf' : 'zeroclipboard/dist/ZeroClipboard.swf'
        }
      },
      tooltipster: {
        options: {
          destPrefix: 'content/lib/tooltipster'
        },
        files: {
          'js': 'tooltipster/js',
          'css': 'tooltipster/css'
        }
      },
      lib: {
        options: {
          destPrefix: 'content/lib'
        },
        files: {
          'ace' : 'ace-builds/src-min-noconflict',
          'bootstrap' : 'bootstrap'
        }
      },
      sourcemap: {
        options: {
          destPrefix: 'content/lib/sourcemap'
        },
        files: {
          'array-set.js': 'source-map/lib/source-map/array-set.js',
          'base64.js': 'source-map/lib/source-map/base64.js',
          'base64-vlq.js': 'source-map/lib/source-map/base64-vlq.js',
          'binary-search.js': 'source-map/lib/source-map/binary-search.js',
          'source-map-consumer.js':
              'source-map/lib/source-map/source-map-consumer.js',
          'util.js': 'source-map/lib/source-map/util.js'
        }
      }
    },
    requirejs: {
      compile: {
        options: {
          baseUrl: 'content',
          deps: ['src/editor-main'],
          name: 'lib/almond',
          out: 'content/editor.js',
          // optimize: 'none',
          mainConfigFile: 'content/src/editor-main.js',
          preserveLicenseComments: false
        }
      }
    },
    replace: {
      dist: {
        options: {
          patterns: [ {
            match:
              /<script data-main=".*\/([^\/"-]*)-main" src=".*require.js">/,
            replacement:
              "<script src=\"//<!--#echo var=\"site\"-->/$1.js\"></script>"
          } ]
        },
        files: [ {
          expand: true,
          flatten: true,
          src: [
            'content/src/editor.html',
            'content/src/framed.html'
          ],
          dest: 'content'
        } ]
      }
    },
    uglify: {
      all: {
        files: {
          'content/turtlebits.js': [
            'content/lib/iced-coffee-script.js',
            'content/lib/jquery.js',
            'content/lib/jquery-turtle.js',
            'content/lib/lodash.js',
            'content/lib/seedrandom.js',
            'content/lib/socket.io.js',
            'content/src/showturtle.js'
          ]
        },
        options: {
          preserveComments: false,
          report: 'min',
          compress: {
            unsafe: true,
            "screw_ie8": true,
            "pure_getters": true
          },
          beautify: {
            semicolons: false
          }
        }
      }
    },
    less: {
      all: {
        options: { compress: true },
        files: {
          "content/welcome.css": "content/src/welcome.less",
          "content/editor.css": "content/src/editor.less"
        }
      }
    },
    concat: {
      all: {
        src: [
          'content/lib/iced-coffee-script.js',
          'content/lib/jquery.js',
          'content/lib/jquery-turtle.js',
          'content/lib/lodash.js',
          'content/lib/seedrandom.js',
          'content/lib/socket.io.js',
          'content/src/showturtle.js'
        ],
        dest: 'content/turtlebits.js'
      },
      options: {
        separator: ';'
      }
    },
    express: {
      options: {
        port: grunt.option('port'),
        output: 'listening'
      },
      dev: {
        options: {
          script: 'server/devserver.js',
          node_env: 'development'
        }
      },
      localtest: {
        options: {
          script: 'server/devserver.js',
          node_env: 'test'
        }
      },
      devtest: {
        options: {
          script: 'server/devserver.js',
          node_env: 'development',
          port: 8193
        }
      },
      test: {
        options: {
          script: 'server/devserver.js',
          node_env: 'test',
          port: 8193
        }
      }
    },
    sed: {
      iced: {
        pattern: '\n\\(function\\(root\\)',
        replacement: '\nthis.CoffeeScript||(function(root)',
        path: 'content/lib/iced-coffee-script.js',
        recursive: false
      }
    },
    watch: {
      sources: {
        files: [
          'server/*.js',
          'server/*.json',
          'content/src/filetype.js' ],
        options: { spawn: false }
      }
    },
    copy: {
      testdata: {
        files: [ {
          expand: true,
          cwd: 'test/data/',
          src: ['**'],
          dot: true,
          dest: 'local/data'
        } ]
      }
    },
    mochaTest: {
      test: {
        src: ['test/*.js'],
        options: {
          timeout: 100000,
          reporter: 'list',
          colors: false
        }
      }
    },
    'node-inspector': {
      dev: { }
    }
  });

  grunt.loadNpmTasks('grunt-bowercopy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-express-server');
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-node-inspector');
  grunt.loadNpmTasks('grunt-replace');
  grunt.loadNpmTasks('grunt-sed');

  grunt.registerTask('proxymessage', 'Show proxy instructions', function() {
    var port = grunt.option('port');
    var ifaces = os.networkInterfaces();
    grunt.log.writeln(
      'Point your browser proxy autoconfig to one of these (or download\n' +
      'a local copy of one of these proxy.pacs).  Then the dev server\n' +
      'can be used at http://pencilcode.net.dev/');
    for (var dev in ifaces) {
      ifaces[dev].forEach(function(details) {
        if (details.family == 'IPv4') {
          grunt.log.writeln(
            'http://' + details.address + ':' + port + '/proxy.pac');
        }
      });
    }
  });

  grunt.task.registerTask('builddate', 'Create builddate.txt file', function() {
    var stamp = grunt.template.today('dddd, mmmm dS, yyyy, HH:MM:ss Z');
    grunt.file.write('content/builddate.txt', stamp);
    grunt.log.writeln('Build date: ' + stamp);
  });

  grunt.task.registerTask('test', 'Run integration tests.',
  function(testname) {
    if (!!testname) {
      grunt.config('mochaTest.test.src', ['test/' + testname + '.js']);
    }
    grunt.task.run('copy:testdata');
    grunt.task.run('express:test');
    grunt.task.run('mochaTest');
  });

  grunt.task.registerTask('devtest', 'Run tests using uncompiled code.',
  function(testname) {
    if (!!testname) {
      grunt.config('mochaTest.test.src', ['test/' + testname + '.js']);
    }
    grunt.task.run('express:devtest');
    grunt.task.run('mochaTest');
  });

  // "update" does a bowercopy and a sed.
  grunt.registerTask('update', ['bowercopy', 'sed']);
  // "devserver" serves editor code directly from the src directory.
  grunt.registerTask('devserver',
      ['proxymessage', 'express:dev', 'node-inspector:dev', 'watch']);
  // "devserver" serves editor code directly from the src directory.
  grunt.registerTask('testserver',
      ['proxymessage', 'express:localtest', 'node-inspector:dev', 'watch']);
  // "debug" overwrites turtlebits.js with an unminified version.
  grunt.registerTask('debug', ['concat', 'devtest']);
  // "build", for development, builds code without running tests.
  grunt.registerTask('build', ['requirejs', 'replace', 'builddate']);
  // default target: compile editor code and uglify turtlebits.js, and test it.
  grunt.registerTask('default',
      ['requirejs', 'replace', 'uglify', 'less', 'builddate', 'test']);
};

<|endoftext|>


<commit_before>
var tempo_ms = 500;//Math.floor((Math.random() * 292) + 375)//DELAY IN MS between sounds.
var nextExpected = 0;
var totalscore = 0;
var lastSoundTime;//used in case you've really messed up.
var beatdiv = Math.floor((Math.random() * 6)+1);
var beattype = Math.floor((Math.random() * 3));
var typelut = ["lowkick", "mediumtone", "highclick"];
var currentbeat = 0;

function update() {
    t = getTimeMS();
    lastSoundTime = t;
    nextExpected = lastSoundTime + tempo_ms;
    if(isSeeding() || testDone()) {

        if(beatdiv > 1 && currentbeat % beatdiv == 0) {
            Sound.play(getBeatType()+"/major");
        } else {
            Sound.play(getBeatType()+"/minor");
        }

    }
    currentbeat++;
}
function draw() {
    canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    canvas.fillStyle = "#000"; // Set color to black
    tempo_tempo = Math.round((1000.0/tempo_ms)*60);//beats per minute like normal music.

    canvas.fillText("Tempo is: " + tempo_tempo, 50, 25);
    canvas.fillText("beat division is: " + beatdiv, 50, 50);
    canvas.fillText("beat type is: " + getBeatType(), 50, 75);
    canvas.fillText("Sound Ending in..." + (numstarter - startervar), 50, 100);
    canvas.fillText("Score: "+Math.round(totalscore), 50, 125);
}

var currenttest = 0;
function respondKey() {
    difftest = Math.abs(getScore());
    console.log("difftest: " + difftest);
    if(isSeeding()) {
        doSeedingBehavior(difftest);
    } else {
        doTest(difftest);
    }
}
function doSeedingBehavior(difftest) {
var starterthresh = 60;//ms
    if(difftest < starterthresh) {
            startervar++;
        } else {
            startervar = 0;
        }
}
function doTest(difftest) {
    currenttest++;
    if(currenttest <= numtests && difftest <= tempo_ms) {
        ratio = parseFloat(difftest) / parseFloat(tempo_ms/2.0);
        score = 1 - ratio;
        score = score * (1000.0/numtests);
        totalscore = totalscore + score;
        console.log("test " + currenttest + " score " + difftest + ", " + score);
    }
}
function getScore() {
    t = getTimeMS();
    mid = tempo_ms/2.0;
    tempscore = t - lastSoundTime;
    if(tempscore >= mid) {
        console.log("from expected");
        return nextExpected - t;
    } else {
        console.log("from last")
        return tempscore;
    }
}
function getTimeMS() {
    var d = new Date();
    var t = d.getTime();
    return t;
}
var startervar = 0;
var numstarter = 10;
function isSeeding() {
    return startervar < numstarter;
}
var numtests = 20;
function testDone() {
    return currenttest >= numtests;
}
function getBeatType() {
    type = typelut[beattype];
    return type;
}

$(function() {
  window.keydown = {};
  setInitVal();
  $(document).bind("keydown", function(event) {
    respondKey();
  });

  $(document).bind("keyup", function(event) {
  });
});

var intervalID;
function parsevals() {
    tempo = parseInt(document.getElementById('tempo').value);
    tempo_ms = (60.0/tempo)*1000;

    beatdiv = parseInt(document.getElementById('division').value);

    beattype = document.getElementById('soundtype').value
}
function resetTestVars() {
    currentbeat = 0;
    totalscore = 0;
    startervar = 0;
    currenttest = 0;
}
function restart() {
    parsevals();

    resetTestVars();

    clearInterval(intervalID);

    intervalID = setInterval(function() {
                  update();
                }, tempo_ms);
}

function setInitVal() {
    document.getElementById('tempo').value = Math.round((1000.0/tempo_ms)*60);
    document.getElementById('division').value = beatdiv;
    document.getElementById('soundtype').value = beattype;
}<commit_msg>Added more threshold<commit_after>
var tempo_ms = 500;//Math.floor((Math.random() * 292) + 375)//DELAY IN MS between sounds.
var nextExpected = 0;
var totalscore = 0;
var lastSoundTime;//used in case you've really messed up.
var beatdiv = Math.floor((Math.random() * 6)+1);
var beattype = Math.floor((Math.random() * 3));
var typelut = ["lowkick", "mediumtone", "highclick"];
var currentbeat = 0;

function update() {
    t = getTimeMS();
    lastSoundTime = t;
    nextExpected = lastSoundTime + tempo_ms;
    if(isSeeding() || testDone()) {

        if(beatdiv > 1 && currentbeat % beatdiv == 0) {
            Sound.play(getBeatType()+"/major");
        } else {
            Sound.play(getBeatType()+"/minor");
        }

    }
    currentbeat++;
}
function draw() {
    canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    canvas.fillStyle = "#000"; // Set color to black
    tempo_tempo = Math.round((1000.0/tempo_ms)*60);//beats per minute like normal music.

    canvas.fillText("Tempo is: " + tempo_tempo, 50, 25);
    canvas.fillText("beat division is: " + beatdiv, 50, 50);
    canvas.fillText("beat type is: " + getBeatType(), 50, 75);
    canvas.fillText("Sound Ending in..." + (numstarter - startervar), 50, 100);
    canvas.fillText("Score: "+Math.round(totalscore), 50, 125);
}

var currenttest = 0;
function respondKey() {
    difftest = Math.abs(getScore());
    console.log("difftest: " + difftest);
    if(isSeeding()) {
        doSeedingBehavior(difftest);
    } else {
        doTest(difftest);
    }
}
function doSeedingBehavior(difftest) {
var starterthresh = 160;//ms
    if(difftest < starterthresh) {
            startervar++;
        } else {
            startervar = 0;
        }
}
function doTest(difftest) {
    currenttest++;
    if(currenttest <= numtests && difftest <= tempo_ms) {
        ratio = parseFloat(difftest) / parseFloat(tempo_ms/2.0);
        score = 1 - ratio;
        score = score * (1000.0/numtests);
        totalscore = totalscore + score;
        console.log("test " + currenttest + " score " + difftest + ", " + score);
    }
}
function getScore() {
    t = getTimeMS();
    mid = tempo_ms/2.0;
    tempscore = t - lastSoundTime;
    if(tempscore >= mid) {
        console.log("from expected");
        return nextExpected - t;
    } else {
        console.log("from last")
        return tempscore;
    }
}
function getTimeMS() {
    var d = new Date();
    var t = d.getTime();
    return t;
}
var startervar = 0;
var numstarter = 10;
function isSeeding() {
    return startervar < numstarter;
}
var numtests = 20;
function testDone() {
    return currenttest >= numtests;
}
function getBeatType() {
    type = typelut[beattype];
    return type;
}

$(function() {
  window.keydown = {};
  setInitVal();
  $(document).bind("keydown", function(event) {
    respondKey();
  });

  $(document).bind("keyup", function(event) {
  });
});

var intervalID;
function parsevals() {
    tempo = parseInt(document.getElementById('tempo').value);
    tempo_ms = (60.0/tempo)*1000;

    beatdiv = parseInt(document.getElementById('division').value);

    beattype = document.getElementById('soundtype').value
}
function resetTestVars() {
    currentbeat = 0;
    totalscore = 0;
    startervar = 0;
    currenttest = 0;
}
function restart() {
    parsevals();

    resetTestVars();

    clearInterval(intervalID);

    intervalID = setInterval(function() {
                  update();
                }, tempo_ms);
}

function setInitVal() {
    document.getElementById('tempo').value = Math.round((1000.0/tempo_ms)*60);
    document.getElementById('division').value = beatdiv;
    document.getElementById('soundtype').value = beattype;
}<|endoftext|>


<commit_before>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');
var adm1 = config.adm1;
var adm2 = config.adm2;

function createMessage(type, id, content, callback){
	var message = {
		recipient: {
		  id: id
		}
	};
	console.log(content);
	if(type == 'text'){
		message['message']={text: content};
	}else{
		message['message']={
			attachment:{
				type: 'template',
				payload:{
					template_type: 'button',
					text: content['text'],
					buttons: [
						content['buttons']
					]
				}
			}
		}
	}
	setImmediate(function(){
		callback(message);
	});
}

function createButtons(tab, callback){
	var buttons;
	for(var i = 0; i < tab.length; i++){
		var btn = tab[i];
		var singleBTN={
			type: btn[1],
			title: btn[3]
		}
		if(btn[1]=='web_url'){
			singleBTN['url']=btn[2];
		} else if(btn[1]=='postback'){
			singleBTN['payload']=btn[2];
		}
		buttons.push(singleBTN);
	}
	setImmediate(function(){
		callback(buttons);
	});
}

function sendSubstitutions(senderID, message){
	var admMessage1 = {
		recipient: {
		  id: adm1
		},
		message: {
		  attachment:{
			  type: 'template',
			  payload:{
					template_type: 'button',
					text: 'nowa wiadomość:\n' + message,
					buttons:[
						{
							type: 'web_url',
							url: 'https://www.facebook.com/Zastępstwa-dla-szkół-573446562859405/messages',
							title: 'Odpowiedz'
						}
					]
			  }
		  }
		}
	};
	var admMessage2 = {
		recipient: {
		  id: adm2
		},
		message: {
		  attachment:{
			  type: 'template',
			  payload:{
					template_type: 'button',
					text: 'nowa wiadomość:\n' + message,
					buttons:[
						{
							type: 'web_url',
							url: 'https://www.facebook.com/Zastępstwa-dla-szkół-573446562859405/messages',
							title: 'Odpowiedz'
						}
					]
			  }
		  }
		}
	};
	var body = {
		'mode': 'classList',
		'param': 'today'
	};
	message = message.toLowerCase();
	var opt = message[0];
	var help = 'Dostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';
	var messageData = {
		recipient: {
		  id: senderID
		},
		message: {
		  text: help
		}
	};
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
		reqClass += message[4];
	}
	switch(opt){
		case '0':
			break;
		case '1':
			body['param']='tomorrow'; //masz else, więc jak dam dobrze to przejdzie, chociaż ty piszesz źle
			break;
		case '2':
			body['mode']='NO';
			var messageData = {
				recipient: {
				  id: senderID
				},
				message: {
				  text: 'Skontaktujemy się aby odpowiedzieć na pytanie.'
				}
			};
			callSendAPI(messageData);
			callSendAPI(admMessage1);
			callSendAPI(admMessage2);
			break;
		case '3':
			body['mode']='NO';
			createMessage('text', senderID, 'Jakiś tekst - test', function(message){
				callSendAPI(message);
			});
			createButtons([{'web_url', 'https://google.com', 'TEST LINK'},{'postback', 'payload', 'POSTBACK - TEST'}], function(btns){
				console.log(btns);
			});
			break;
		default:
			body['mode']='NO';
			callSendAPI(messageData);
			break;
	};
	if(body['mode'] != 'NO'){
		manageUsers.postCall('0000', body, function(classes){
			var is = 0;
			for(var i = 0; i < classes.length; i++){
				if(classes[i] == reqClass){
					is++;
				}
			}
			if(is > 0){
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  attachment:{
						  type: 'template',
						  payload:{
								template_type: 'button',
								text: 'zastępstwa',
								buttons:[
									{
										type: 'web_url',
										url: 'https://domek.emadar.eu',
										title: 'Sprawdź na stronie'
									},
									{
										type: 'postback',
										title: 'Send on chat',
										payload: message
									}
								]
						  }
					  }
					}
				};
			} else {
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'brak zastępstw'
					}
				};
			}
			callSendAPI(messageData);
		});
	}
}

function sendList(senderID, message){
	var body = {
		'mode': 'getChanges',
		'param': 'today'
	};
	if(message[0]=='1'){
		body['param']='tomorrow';
	}
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
		reqClass += message[4];
	}
	manageUsers.postCall('0000', body, function(obj){
		var subs = obj['substitution'];
		var msg = "";
		for(var i = 0; i < subs.length; i++){
			var oneSub = subs[i];
			if(oneSub.classes == reqClass){
				var changes = oneSub['changes'];
				if(oneSub.cancelled[0]){
					msg+='anulowanie';
				} else {
					msg+='Typ: ' + oneSub.substitution_types;
				}
				msg+='\nLekcja: ' + oneSub.periods;
				msg+='\nNauczyciel: ' + oneSub.teachers;
				if(changes){
					if(changes.teachers){
						msg+=' => ' + changes.teachers;
					}
				}
				msg+='\nPrzedmiot: ' + oneSub.subjects;
				if(changes){
					if(changes.subjects){
						msg+= ' => ' + changes.subjects;
					}
				}
				msg+='\nSala: ' + oneSub.classrooms;
				if(changes){
					if(changes.classrooms){
						msg+=' => ' + changes.classrooms;
					}
				}
				if(oneSub.groupnames){
					if(oneSub.groupnames != ""){
						msg+='\nGrupa: ' + oneSub.groupnames;
					}
				}
				if(oneSub.note){
					if(oneSub.note != ""){
						msg+='\nKomentarz: '  + oneSub.note;
					}
				}
				var messageData = {
					recipient: {
						id: senderID
					},
					message: {
						text: msg
					}
				};
				callSendAPI(messageData);
				msg='';
			}
		}
	});
}

function receivedPostback(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfPostback = event.timestamp;

	// The 'payload' param is a developer-defined field which is set in a postback
	// button for Structured Messages.
	var payload = event.postback.payload;

	console.log("Received postback for user %d and page %d with payload '%s' " +
	"at %d", senderID, recipientID, payload, timeOfPostback);

	sendList(senderID, payload);
}

function receivedMessage(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfMessage = event.timestamp;
	var message = event.message;

	console.log("Received message for user %d and page %d at %d with message:",
	senderID, recipientID, timeOfMessage);
	console.log(JSON.stringify(message));

	var messageId = message.mid;

	var messageText = message.text;
	var messageAttachments = message.attachments;
	var help = 'NIE PRZYJMUJEMY ZAŁĄCZNIKÓW\nDostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';

	if (messageText) {
		sendSubstitutions(senderID, messageText);
	} else {
		var messageData = {
			recipient: {
			  id: senderID
			},
			message: {
			  text: help
			}
		};
		callSendAPI(messageData);
	}
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<commit_msg>attempt to fix ,<commit_after>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');
var adm1 = config.adm1;
var adm2 = config.adm2;

function createMessage(type, id, content, callback){
	var message = {
		recipient: {
		  id: id
		}
	};
	console.log(content);
	if(type == 'text'){
		message['message']={text: content};
	}else{
		message['message']={
			attachment:{
				type: 'template',
				payload:{
					template_type: 'button',
					text: content['text'],
					buttons: [
						content['buttons']
					]
				}
			}
		}
	}
	setImmediate(function(){
		callback(message);
	});
}

function createButtons(tab, callback){
	var buttons;
	for(var i = 0; i < tab.length; i++){
		var btn = tab[i];
		var singleBTN={
			type: btn[1],
			title: btn[3]
		}
		if(btn[1]=='web_url'){
			singleBTN['url']=btn[2];
		} else if(btn[1]=='postback'){
			singleBTN['payload']=btn[2];
		}
		buttons.push(singleBTN);
	}
	setImmediate(function(){
		callback(buttons);
	});
}

function sendSubstitutions(senderID, message){
	var admMessage1 = {
		recipient: {
		  id: adm1
		},
		message: {
		  attachment:{
			  type: 'template',
			  payload:{
					template_type: 'button',
					text: 'nowa wiadomość:\n' + message,
					buttons:[
						{
							type: 'web_url',
							url: 'https://www.facebook.com/Zastępstwa-dla-szkół-573446562859405/messages',
							title: 'Odpowiedz'
						}
					]
			  }
		  }
		}
	};
	var admMessage2 = {
		recipient: {
		  id: adm2
		},
		message: {
		  attachment:{
			  type: 'template',
			  payload:{
					template_type: 'button',
					text: 'nowa wiadomość:\n' + message,
					buttons:[
						{
							type: 'web_url',
							url: 'https://www.facebook.com/Zastępstwa-dla-szkół-573446562859405/messages',
							title: 'Odpowiedz'
						}
					]
			  }
		  }
		}
	};
	var body = {
		'mode': 'classList',
		'param': 'today'
	};
	message = message.toLowerCase();
	var opt = message[0];
	var help = 'Dostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';
	var messageData = {
		recipient: {
		  id: senderID
		},
		message: {
		  text: help
		}
	};
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
		reqClass += message[4];
	}
	switch(opt){
		case '0':
			break;
		case '1':
			body['param']='tomorrow'; //masz else, więc jak dam dobrze to przejdzie, chociaż ty piszesz źle
			break;
		case '2':
			body['mode']='NO';
			var messageData = {
				recipient: {
				  id: senderID
				},
				message: {
				  text: 'Skontaktujemy się aby odpowiedzieć na pytanie.'
				}
			};
			callSendAPI(messageData);
			callSendAPI(admMessage1);
			callSendAPI(admMessage2);
			break;
		case '3':
			body['mode']='NO';
			createMessage('text', senderID, 'Jakiś tekst - test', function(message){
				callSendAPI(message);
			});
			createButtons([['web_url', 'https://google.com', 'TEST LINK'],['postback', 'payload', 'POSTBACK - TEST']], function(btns){
				console.log(btns);
			});
			break;
		default:
			body['mode']='NO';
			callSendAPI(messageData);
			break;
	};
	if(body['mode'] != 'NO'){
		manageUsers.postCall('0000', body, function(classes){
			var is = 0;
			for(var i = 0; i < classes.length; i++){
				if(classes[i] == reqClass){
					is++;
				}
			}
			if(is > 0){
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  attachment:{
						  type: 'template',
						  payload:{
								template_type: 'button',
								text: 'zastępstwa',
								buttons:[
									{
										type: 'web_url',
										url: 'https://domek.emadar.eu',
										title: 'Sprawdź na stronie'
									},
									{
										type: 'postback',
										title: 'Send on chat',
										payload: message
									}
								]
						  }
					  }
					}
				};
			} else {
				var messageData = {
					recipient: {
					  id: senderID
					},
					message: {
					  text: 'brak zastępstw'
					}
				};
			}
			callSendAPI(messageData);
		});
	}
}

function sendList(senderID, message){
	var body = {
		'mode': 'getChanges',
		'param': 'today'
	};
	if(message[0]=='1'){
		body['param']='tomorrow';
	}
	var reqClass = message[2] + message[3];
	if(reqClass[1]=='g'){
		reqClass += message[4];
	}
	manageUsers.postCall('0000', body, function(obj){
		var subs = obj['substitution'];
		var msg = "";
		for(var i = 0; i < subs.length; i++){
			var oneSub = subs[i];
			if(oneSub.classes == reqClass){
				var changes = oneSub['changes'];
				if(oneSub.cancelled[0]){
					msg+='anulowanie';
				} else {
					msg+='Typ: ' + oneSub.substitution_types;
				}
				msg+='\nLekcja: ' + oneSub.periods;
				msg+='\nNauczyciel: ' + oneSub.teachers;
				if(changes){
					if(changes.teachers){
						msg+=' => ' + changes.teachers;
					}
				}
				msg+='\nPrzedmiot: ' + oneSub.subjects;
				if(changes){
					if(changes.subjects){
						msg+= ' => ' + changes.subjects;
					}
				}
				msg+='\nSala: ' + oneSub.classrooms;
				if(changes){
					if(changes.classrooms){
						msg+=' => ' + changes.classrooms;
					}
				}
				if(oneSub.groupnames){
					if(oneSub.groupnames != ""){
						msg+='\nGrupa: ' + oneSub.groupnames;
					}
				}
				if(oneSub.note){
					if(oneSub.note != ""){
						msg+='\nKomentarz: '  + oneSub.note;
					}
				}
				var messageData = {
					recipient: {
						id: senderID
					},
					message: {
						text: msg
					}
				};
				callSendAPI(messageData);
				msg='';
			}
		}
	});
}

function receivedPostback(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfPostback = event.timestamp;

	// The 'payload' param is a developer-defined field which is set in a postback
	// button for Structured Messages.
	var payload = event.postback.payload;

	console.log("Received postback for user %d and page %d with payload '%s' " +
	"at %d", senderID, recipientID, payload, timeOfPostback);

	sendList(senderID, payload);
}

function receivedMessage(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfMessage = event.timestamp;
	var message = event.message;

	console.log("Received message for user %d and page %d at %d with message:",
	senderID, recipientID, timeOfMessage);
	console.log(JSON.stringify(message));

	var messageId = message.mid;

	var messageText = message.text;
	var messageAttachments = message.attachments;
	var help = 'NIE PRZYJMUJEMY ZAŁĄCZNIKÓW\nDostępne polecenia to:\n"0 <klasa>" - zastępstwa dla klasy na dzisiaj\n"1 <klasa>" - zastępstwa dla klasy na jutro\n"2 <pytanie>" - pomoc';

	if (messageText) {
		sendSubstitutions(senderID, messageText);
	} else {
		var messageData = {
			recipient: {
			  id: senderID
			},
			message: {
			  text: help
			}
		};
		callSendAPI(messageData);
	}
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<|endoftext|>


<commit_before>define('/style/js/biz/list.js', function(require, exports, module) {
	var body = $('#captureListBody');
	var	MAX_COUNT = 512;
	var ids = [];
	var data = {};
	var index = 0;
	var pending;

	function getList(options) {
		if (pending) {
			return;
		}
		pending = true;

		return $.ajax({
			url: '/cgi-bin/list/get',
			dataType: 'json',
			timeout: 5000,
			type: 'post',
			data: options,
			success: handleData,
			complete: function() {
				setTimeout(load, 1600);
			}
		});
	}

	function load() {
		var id;
		var pendingIds = [];
		for (var i = 0, len = ids.length; i < len; i++) {
			id = ids[i];
			var curData = data[id];
			if (curData && !curData.endTime) {
				pendingIds.push(id);
			}
		}
		var startTime = ids.length <= MAX_COUNT ? id : -1;

		function _load() {
			pending = false;
			getList({
				ids: pendingIds.join(),
				startTime: startTime
			});
		}

		if (startTime == -1 && !pendingIds.length) {
			setTimeout(_load, 5000);
		} else {
			_load();
		}
	}

	function handleData(json) {
		for (var i in json.data) {
			var curData = json.data[i];
			if (curData) {
				data[i] = curData;
			}
		}
		ids = ids.concat(json.newIds);
		createList();
	}

	function createList() {
		var list = body.find('tr');
		if (list.length >= MAX_COUNT) {
			return;
		}

		list.filter('.pending').each(function() {
			var self = $(this);
			var curData = data[self.attr('id')];
			curData && updateElement(self, curData);
		});

		var last = list.filter(':last');
		var lastId = last.attr('id');
		lastId = lastId && (lastId = $.inArray(lastId, ids)) != -1 ? lastId : 0;
		var html = [];
		for (len = ids.length; lastId < len; lastId++) {
			html.push(getHtml(data[ids[lastId]]));
		}
		body.append(html.join(''));
	}

	function getHtml(data) {
		if (!data) {
			return '';
		}
		var res = data.res;
		var req = data.req;
		return '
\
			        ' + ++index + '	\
			        ' + (res.statusCode || '-') + '	\
			        ' + getProtocol(data.url) + '	\
			        ' + req.method + '	\
			        ' + getHostname(data.url) + '	\
			        ' + (res.host || '-') + '	\
			        ' + data.url + '	\
			        ' + (res.headers && res.headers['content-type'] || '-') + '	\
			        ' + (data.endTime ? data.endTime - data.startTime : '-') + '	\

';
	}

	function updateElement(elem, data) {
		var res = data.res;
		var error = data.reqError || data.resError;
		elem.find('.result').text(error ? 'error' : (res.statusCode || '-'));
		elem.find('.host-ip').text(res.host || '-');
		elem.find('.type').text((res.headers && res.headers['content-type'] || '-'));
		elem.find('.time').text(data.endTime ? data.endTime - data.startTime : '-');
		elem.addClass(getClassname(data));
		if (data.endTime) {
			elem.removeClass('pending');
		}
	}

	function getHostname(url) {
		var index = url.indexOf(':\/\/') + 3;
		return url.substring(index, url.indexOf('\/', index));
	}

	function getProtocol(url) {
		return url.substring(0, url.indexOf(':\/\/')).toUpperCase();
	}

	function getClassname(data) {
		if (data.reqError || data.resError) {
			return 'danger';
		}
		var headers = data.res.headers;
		switch(getContentType(headers)) {
			case 'JS':
				return 'warning';
			case 'CSS':
				return 'info';
			case 'HTML':
				return 'success';
			case 'IMG':
				return 'active';
		}

		return '';
	}

	function getContentType(contentType) {
		if (contentType && typeof contentType != 'string') {
			contentType = contentType['content-type'] || contentType.contentType;
		}

		if (typeof contentType == 'string') {
			contentType = contentType.toLowerCase();
			if (contentType.indexOf('javascript') != -1) {
		        return 'JS';
		    }

			if (contentType.indexOf('css') != -1) {
		        return 'CSS';
		    }

			if (contentType.indexOf('html') != -1) {
		        return 'HTML';
		    }

			if (contentType.indexOf('json') != -1) {
		        return 'JSON';
		    }

			if (contentType.indexOf('text/') != -1) {
		        return 'TEXT';
		    }

			if (contentType.indexOf('image') != -1) {
		        return 'IMG';
		    }
		}

		return null;
	}

	function removeElements(elems) {
		var index = $.inArray(elems.id, ids);
		if (index != -1) {
			ids.splice(index, 1);
		}
		elems.remove();
	}

	module.exports = function init() {
		getList();
	};
});<commit_msg>add error status<commit_after>define('/style/js/biz/list.js', function(require, exports, module) {
	var body = $('#captureListBody');
	var	MAX_COUNT = 512;
	var ids = [];
	var data = {};
	var index = 0;
	var pending;

	function getList(options) {
		if (pending) {
			return;
		}
		pending = true;

		return $.ajax({
			url: '/cgi-bin/list/get',
			dataType: 'json',
			timeout: 5000,
			type: 'post',
			data: options,
			success: handleData,
			complete: function() {
				setTimeout(load, 1600);
			}
		});
	}

	function load() {
		var id;
		var pendingIds = [];
		for (var i = 0, len = ids.length; i < len; i++) {
			id = ids[i];
			var curData = data[id];
			if (curData && !curData.endTime) {
				pendingIds.push(id);
			}
		}
		var startTime = ids.length <= MAX_COUNT ? id : -1;

		function _load() {
			pending = false;
			getList({
				ids: pendingIds.join(),
				startTime: startTime
			});
		}

		if (startTime == -1 && !pendingIds.length) {
			setTimeout(_load, 5000);
		} else {
			_load();
		}
	}

	function handleData(json) {
		for (var i in json.data) {
			var curData = json.data[i];
			if (curData) {
				data[i] = curData;
			}
		}
		ids = ids.concat(json.newIds);
		createList();
	}

	function createList() {
		var list = body.find('tr');
		if (list.length >= MAX_COUNT) {
			return;
		}

		list.filter('.pending').each(function() {
			var self = $(this);
			var curData = data[self.attr('id')];
			curData && updateElement(self, curData);
		});

		var last = list.filter(':last');
		var lastId = last.attr('id');
		lastId = lastId && (lastId = $.inArray(lastId, ids)) != -1 ? lastId : 0;
		var html = [];
		for (len = ids.length; lastId < len; lastId++) {
			html.push(getHtml(data[ids[lastId]]));
		}
		body.append(html.join(''));
	}

	function getHtml(data) {
		if (!data) {
			return '';
		}
		var res = data.res;
		var req = data.req;
		return '
\
			        ' + ++index + '	\
			        ' + (res.statusCode || '-') + '	\
			        ' + getProtocol(data.url) + '	\
			        ' + req.method + '	\
			        ' + getHostname(data.url) + '	\
			        ' + (res.host || '-') + '	\
			        ' + data.url + '	\
			        ' + (res.headers && res.headers['content-type'] || '-') + '	\
			        ' + (data.endTime ? data.endTime - data.startTime : '-') + '	\

';
	}

	function updateElement(elem, data) {
		var res = data.res;
		var defaultValue = data.reqError || data.resError ? 'error' : '-';
		elem.find('.result').text(res.statusCode || defaultValue);
		elem.find('.host-ip').text(res.host || defaultValue);
		elem.find('.type').text((res.headers && res.headers['content-type'] || defaultValue));
		elem.find('.time').text(data.endTime ? data.endTime - data.startTime : defaultValue);
		elem.addClass(getClassname(data));
		if (data.endTime) {
			elem.removeClass('pending');
		}
	}

	function getHostname(url) {
		var index = url.indexOf(':\/\/') + 3;
		return url.substring(index, url.indexOf('\/', index));
	}

	function getProtocol(url) {
		return url.substring(0, url.indexOf(':\/\/')).toUpperCase();
	}

	function getClassname(data) {
		if (data.reqError || data.resError) {
			return 'danger';
		}
		var headers = data.res.headers;
		switch(getContentType(headers)) {
			case 'JS':
				return 'warning';
			case 'CSS':
				return 'info';
			case 'HTML':
				return 'success';
			case 'IMG':
				return 'active';
		}

		return '';
	}

	function getContentType(contentType) {
		if (contentType && typeof contentType != 'string') {
			contentType = contentType['content-type'] || contentType.contentType;
		}

		if (typeof contentType == 'string') {
			contentType = contentType.toLowerCase();
			if (contentType.indexOf('javascript') != -1) {
		        return 'JS';
		    }

			if (contentType.indexOf('css') != -1) {
		        return 'CSS';
		    }

			if (contentType.indexOf('html') != -1) {
		        return 'HTML';
		    }

			if (contentType.indexOf('json') != -1) {
		        return 'JSON';
		    }

			if (contentType.indexOf('text/') != -1) {
		        return 'TEXT';
		    }

			if (contentType.indexOf('image') != -1) {
		        return 'IMG';
		    }
		}

		return null;
	}

	function removeElements(elems) {
		var index = $.inArray(elems.id, ids);
		if (index != -1) {
			ids.splice(index, 1);
		}
		elems.remove();
	}

	module.exports = function init() {
		getList();
	};
});<|endoftext|>


<commit_before>/*:
 * @plugindesc Wav File Encrypter
 * @author biud436
 *
 * @param key
 * @desc
 * @default myKey
 *
 */

var Imported = Imported || {};
Imported.RS_WavFileEncrypter = true;

function Encrypter() {
    throw new Error('This is a static class');
}

(function() {

  var parameters = PluginManager.parameters('RS_WavFileEncrypter');

  var fs = require('fs');

  Encrypter.SIGNATURE = "5250474d56000000";
  Encrypter.VER = "000301";
  Encrypter.REMAIN = "0000000000";
  Encrypter._headerlength = 16;
  Encrypter.key = parameters['key'] || 'myKey';
  Encrypter._path = 'js/libs/CryptoJS/';
  Encrypter._wavPath = 'audio/wav/';
  Encrypter._encryptionKey = ["d4", "1d", "8c", "d9", "8f", "00", "b2", "04", "e9", "80", "09", "98", "ec", "f8", "42", "7e"];

  Encrypter.loadScript = function(name) {
    var url = Encrypter.getCurrentPath() + this._path + name;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.async = false;
    script._url = url;
    document.body.appendChild(script);
  };

  Encrypter.getWaveFiles = function() {
    if(!!process === false) return;
    var index = 0;
    if(process.versions.node && process.versions.v8) {
        var path = require('path'),
        fs = require('fs'),
        root = path.join(".", path.dirname(window.location.pathname), 'audio', 'wav');
        var files = fs.readdirSync(root);
        return files.filter(function(i) {
            var reg = /^[^\.]+$/
            return !reg.test(i);
        });
    }
  };

  Encrypter.isNodeWebkit = function () {
    return Utils.isNwjs();
  };

  Encrypter.readWavStream = function (path) {
    if(!this.isNodeWebkit()) return;

    var requestFile = new XMLHttpRequest();
    requestFile.open("GET", Encrypter.getCurrentPath() + path);
    requestFile.responseType = "arraybuffer";
    requestFile.send();

    requestFile.onload = function () {
        if(this.status < 400) {
          var buffer = Encrypter.encryptArrayBuffer(requestFile.response);
          Encrypter.writeEncryptWaveStream(Encrypter.getCurrentPath() + path, Encrypter.toBuffer(buffer));
        }
    };
  };

  Encrypter.writeEncryptWaveStream = function (path, bin) {
    if(!this.isNodeWebkit()) return;
    var mpath = path.slice( 0, path.lastIndexOf(".") );
    var ext = path.slice( path.lastIndexOf(".") );
    var writeStream = fs.createWriteStream( mpath + ".rpgmvw",  {flags: 'w+'});
    writeStream.write( bin );
    writeStream.end();
    writeStream.on('finish', function() {
    	console.log('finish');
    });
  };

  Encrypter.getCurrentPath = function () {
    if(Utils.isNwjs()) {
      var path = require('path');
      return path.join(".", path.dirname(window.location.pathname), '/');
    } else {
      return window.location.pathname.slice(0, window.location.pathname.lastIndexOf("/")) + "/";
    }
  };

  Encrypter.createHeader = function (size) {
    var bin = new ArrayBuffer(size);
    var dataView = new DataView(bin);
    var i, ref = this.SIGNATURE + this.VER + this.REMAIN;
    for (i = 0; i < size; i++) {
        dataView.setUint8(i, parseInt("0x" + ref.substr(i * 2, 2), size) );
    }
    return bin;
  };

  Encrypter.generateKey = function (encryptKey) {
    var compressedKey = CryptoJS.MD5(encryptKey).toString();
    this._encryptionKey = compressedKey.split(/(.{2})/).filter(Boolean);
  };

  Encrypter.toBuffer = function (bin) {
    var buf = new Buffer(bin.byteLength);
    var headerView = new Uint8Array(bin);
    for (i = 0; i < bin.byteLength; i++) {
      buf[i] = headerView[i];
    }
    return buf;
  };

  Encrypter.encryptArrayBuffer = function(arrayBuffer) {

    if (!arrayBuffer) return null;

    var i = 0;

    // header
    var ref = this.SIGNATURE + this.VER + this.REMAIN;
    var refBytes = new Uint8Array(16);
    for (i = 0; i < this._headerlength; i++) {
        refBytes[i] = parseInt("0x" + ref.substr(i * 2, 2), 16);
    }

    var resultBuffer = new ArrayBuffer(refBytes.byteLength + arrayBuffer.byteLength);

    var view = new DataView(resultBuffer);

    Encrypter.generateKey( Encrypter.key );

    // Address  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | DUMP
    // 00000000 | ------------------------------------------------------------- | RPGMV........................
    // 00000010 | ------------------------------------------------------------- | .wav file header (encrypted)
    // 00000020 | ------------------------------------------------------------- | Do not encrypt

    if (arrayBuffer) {

      // source data
      var resultArray = new Uint8Array(resultBuffer);
      var byteArray = new Uint8Array(arrayBuffer);

      // 0x00 ~ 0x0F
      for (i = 0; i < this._headerlength; i++) {
          resultArray[i] = refBytes[i];
          view.setUint8(i, resultArray[i]);
      }

      // 0x10 ~ 0x1F
      for (i = 0x10; i < 0x20; i++) {
          resultArray[i] = byteArray[i - 0x10] ^ parseInt(this._encryptionKey[i - 0x10], 16);
          view.setUint8(i, resultArray[i]);
      }

      for (i = 0x20; i < resultArray.length; i++) {
          resultArray[i] = byteArray[i -  0x10];
          view.setUint8(i, resultArray[i]);
      }

    }

    return resultBuffer;
  };

  Encrypter.startBuild = function () {
    var files = Encrypter.getWaveFiles();
    files.forEach(function (i) {
      Encrypter.readWavStream(Encrypter._wavPath + i);
    });
  };

  // https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core-min.js
  Encrypter.loadScript('core-min.js');

  // https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js
  Encrypter.loadScript('md5.js');

  Decrypter.extToEncryptExt = function(url) {
      var ext = url.split('.').pop();
      var encryptedExt = ext;

      if(ext === "ogg") encryptedExt = ".rpgmvo";
      else if(ext === "m4a") encryptedExt = ".rpgmvm";
      else if(ext === "png") encryptedExt = ".rpgmvp";
      else if(ext === "wav") encryptedExt = ".rpgmvw";
      else encryptedExt = ext;

      return url.slice(0, url.lastIndexOf(ext) - 1) + encryptedExt;
  };

})();
<commit_msg>First Release<commit_after>/*:
 * @plugindesc (v1.0.0) Wav File Encrypter
 * @author biud436
 *
 * @param key
 * @desc Encryption Key
 * @default myKey
 *
 * @help
 * 1. Make new directory to js/libs folder
 * 2. Installing the library called CryptoJS and place them in js/libs/CryptoJS folder
 * https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core-min.js
 * https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js
 * 3. Sets up this plugin and your secret key in Plugin Manager.
 * 4. Start Game and then run code as follows.
 * Encrypter.startBuild();
 * 5. Copy them to your release project after completed build.
 * -----------------------------------------------------------------------------
 * Change Log
 * -----------------------------------------------------------------------------
 * 2016.11.30 (v1.0.0) - First Release.
 */

var Imported = Imported || {};
Imported.RS_WavFileEncrypter = true;

function Encrypter() {
    throw new Error('This is a static class');
}

(function() {

  var parameters = PluginManager.parameters('RS_WavFileEncrypter');

  var fs = require('fs');

  Encrypter.SIGNATURE = "5250474d56000000";
  Encrypter.VER = "000301";
  Encrypter.REMAIN = "0000000000";
  Encrypter._headerlength = 16;
  Encrypter.key = parameters['key'] || 'myKey';
  Encrypter._path = 'js/libs/CryptoJS/';
  Encrypter._wavPath = 'audio/wav/';
  Encrypter._encryptionKey = ["d4", "1d", "8c", "d9", "8f", "00", "b2", "04", "e9", "80", "09", "98", "ec", "f8", "42", "7e"];

  Encrypter.loadScript = function(name) {
    var url = Encrypter.getCurrentPath() + this._path + name;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.async = false;
    script._url = url;
    document.body.appendChild(script);
  };

  Encrypter.getWaveFiles = function() {
    if(!!process === false) return;
    var index = 0;
    if(process.versions.node && process.versions.v8) {
        var path = require('path'),
        fs = require('fs'),
        root = path.join(".", path.dirname(window.location.pathname), 'audio', 'wav');
        var files = fs.readdirSync(root);
        return files.filter(function(i) {
            var reg = /^[^\.]+$/
            return !reg.test(i);
        });
    }
  };

  Encrypter.isNodeWebkit = function () {
    return Utils.isNwjs();
  };

  Encrypter.readWavStream = function (path) {
    if(!this.isNodeWebkit()) return;

    var requestFile = new XMLHttpRequest();
    requestFile.open("GET", Encrypter.getCurrentPath() + path);
    requestFile.responseType = "arraybuffer";
    requestFile.send();

    requestFile.onload = function () {
        if(this.status < 400) {
          var buffer = Encrypter.encryptArrayBuffer(requestFile.response);
          Encrypter.writeEncryptWaveStream(Encrypter.getCurrentPath() + path, Encrypter.toBuffer(buffer));
        }
    };
  };

  Encrypter.writeEncryptWaveStream = function (path, bin) {
    if(!this.isNodeWebkit()) return;
    var mpath = path.slice( 0, path.lastIndexOf(".") );
    var ext = path.slice( path.lastIndexOf(".") );
    var writeStream = fs.createWriteStream( mpath + ".rpgmvw",  {flags: 'w+'});
    writeStream.write( bin );
    writeStream.end();
    writeStream.on('finish', function() {
    	console.log('finish');
    });
  };

  Encrypter.getCurrentPath = function () {
    if(Utils.isNwjs()) {
      var path = require('path');
      return path.join(".", path.dirname(window.location.pathname), '/');
    } else {
      return window.location.pathname.slice(0, window.location.pathname.lastIndexOf("/")) + "/";
    }
  };

  Encrypter.createHeader = function (size) {
    var bin = new ArrayBuffer(size);
    var dataView = new DataView(bin);
    var i, ref = this.SIGNATURE + this.VER + this.REMAIN;
    for (i = 0; i < size; i++) {
        dataView.setUint8(i, parseInt("0x" + ref.substr(i * 2, 2), size) );
    }
    return bin;
  };

  Encrypter.generateKey = function (encryptKey) {
    var compressedKey = CryptoJS.MD5(encryptKey).toString();
    this._encryptionKey = compressedKey.split(/(.{2})/).filter(Boolean);
  };

  Encrypter.toBuffer = function (bin) {
    var buf = new Buffer(bin.byteLength);
    var headerView = new Uint8Array(bin);
    for (i = 0; i < bin.byteLength; i++) {
      buf[i] = headerView[i];
    }
    return buf;
  };

  Encrypter.encryptArrayBuffer = function(arrayBuffer) {

    if (!arrayBuffer) return null;

    var i = 0;

    // header
    var ref = this.SIGNATURE + this.VER + this.REMAIN;
    var refBytes = new Uint8Array(16);
    for (i = 0; i < this._headerlength; i++) {
        refBytes[i] = parseInt("0x" + ref.substr(i * 2, 2), 16);
    }

    var resultBuffer = new ArrayBuffer(refBytes.byteLength + arrayBuffer.byteLength);

    var view = new DataView(resultBuffer);

    Encrypter.generateKey( Encrypter.key );

    // Address  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | DUMP
    // 00000000 | ------------------------------------------------------------- | RPGMV........................
    // 00000010 | ------------------------------------------------------------- | .wav file header (encrypted)
    // 00000020 | ------------------------------------------------------------- | Do not encrypt

    if (arrayBuffer) {

      // source data
      var resultArray = new Uint8Array(resultBuffer);
      var byteArray = new Uint8Array(arrayBuffer);

      // 0x00 ~ 0x0F
      for (i = 0; i < this._headerlength; i++) {
          resultArray[i] = refBytes[i];
          view.setUint8(i, resultArray[i]);
      }

      // 0x10 ~ 0x1F
      for (i = 0x10; i < 0x20; i++) {
          resultArray[i] = byteArray[i - 0x10] ^ parseInt(this._encryptionKey[i - 0x10], 16);
          view.setUint8(i, resultArray[i]);
      }

      for (i = 0x20; i < resultArray.length; i++) {
          resultArray[i] = byteArray[i -  0x10];
          view.setUint8(i, resultArray[i]);
      }

    }

    return resultBuffer;
  };

  Encrypter.startBuild = function () {
    var files = Encrypter.getWaveFiles();
    files.forEach(function (i) {
      Encrypter.readWavStream(Encrypter._wavPath + i);
    });
  };

  // https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core-min.js
  Encrypter.loadScript('core-min.js');

  // https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js
  Encrypter.loadScript('md5.js');

  Decrypter.extToEncryptExt = function(url) {
      var ext = url.split('.').pop();
      var encryptedExt = ext;

      if(ext === "ogg") encryptedExt = ".rpgmvo";
      else if(ext === "m4a") encryptedExt = ".rpgmvm";
      else if(ext === "png") encryptedExt = ".rpgmvp";
      else if(ext === "wav") encryptedExt = ".rpgmvw";
      else encryptedExt = ext;

      return url.slice(0, url.lastIndexOf(ext) - 1) + encryptedExt;
  };

})();
<|endoftext|>


<commit_before>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                console.log("Flag");
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<commit_msg>You made a decision for the group<commit_after>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var policy = $(this).attr("return-policy");
                var style = $(this).attr("style");
                console.log(policy);
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<|endoftext|>


<commit_before>/** @flow */

export const DEFAULT_HEIGHT = 30
export const DEFAULT_WIDTH = 100

// Enables more intelligent mapping of a given column and row index to an item ID.
// This prevents a cell cache from being invalidated when its parent collection is modified.
type KeyMapper = (
  rowIndex: number,
  columnIndex: number
) => any;

type CellMeasurerCacheParams = {
  defaultHeight ?: number,
  defaultWidth ?: number,
  fixedHeight ?: boolean,
  fixedWidth ?: boolean,
  minHeight?: number,
  minWidth?: number,
  keyMapper ?: KeyMapper
};

type Cache = {
  [key: any]: number
};

type IndexParam = {
  index: number
};

/**
 * Caches measurements for a given cell.
 */
export default class CellMeasurerCache {
  _cellHeightCache: Cache;
  _cellWidthCache: Cache;
  _columnWidthCache: Cache;
  _defaultHeight: ?number;
  _defaultWidth: ?number;
  _minHeight: ?number;
  _minWidth: ?number;
  _keyMapper: KeyMapper;
  _rowHeightCache: Cache;

  constructor (params : CellMeasurerCacheParams = {}) {
    const {
      defaultHeight,
      defaultWidth,
      fixedHeight,
      fixedWidth,
      keyMapper,
      minHeight,
      minWidth
    } = params

    this._hasFixedHeight = fixedHeight === true
    this._hasFixedWidth = fixedWidth === true
    this._minHeight = minHeight || 0
    this._minWidth = minWidth || 0
    this._keyMapper = keyMapper || defaultKeyMapper

    this._defaultHeight = Math.max(
      this._minHeight,
      typeof defaultHeight === 'number'
        ? defaultHeight
        : DEFAULT_HEIGHT
    )
    this._defaultWidth = Math.max(
      this._minWidth,
      typeof defaultWidth === 'number'
        ? defaultWidth
        : DEFAULT_WIDTH
    )

    if (process.env.NODE_ENV !== 'production') {
      if (
        this._hasFixedHeight === false &&
        this._hasFixedWidth === false
      ) {
        console.warn(
          'CellMeasurerCache should only measure a cell\'s width or height. ' +
          'You have configured CellMeasurerCache to measure both. ' +
          'This will result in poor performance.'
        )
      }

      if (
        this._hasFixedHeight === false &&
        this._defaultHeight === 0
      ) {
        console.warn(
          'Fixed height CellMeasurerCache should specify a :defaultHeight greater than 0. ' +
          'Failing to do so will lead to unnecessary layout and poor performance.'
        )
      }

      if (
        this._hasFixedWidth === false &&
        this._defaultWidth === 0
      ) {
        console.warn(
          'Fixed width CellMeasurerCache should specify a :defaultWidth greater than 0. ' +
          'Failing to do so will lead to unnecessary layout and poor performance.'
        )
      }
    }

    this._columnCount = 0
    this._rowCount = 0

    this._cellHeightCache = {}
    this._cellWidthCache = {}
    this._columnWidthCache = {}
    this._rowHeightCache = {}
  }

  clear (
    rowIndex: number,
    columnIndex: number
  ) : void {
    const key = this._keyMapper(rowIndex, columnIndex)

    delete this._cellHeightCache[key]
    delete this._cellWidthCache[key]

    this._updateCachedColumnAndRowSizes(rowIndex, columnIndex)
  }

  clearAll () : void {
    this._cellHeightCache = {}
    this._cellWidthCache = {}
    this._columnWidthCache = {}
    this._rowHeightCache = {}
  }

  columnWidth = ({ index } : IndexParam) => {
    const key = this._keyMapper(0, index)

    return this._columnWidthCache.hasOwnProperty(key)
      ? this._columnWidthCache[key]
      : this._defaultWidth
  }

  get defaultHeight () : number {
    return this._defaultHeight
  }

  get defaultWidth () : number {
    return this._defaultWidth
  }

  hasFixedHeight () : boolean {
    return this._hasFixedHeight
  }

  hasFixedWidth () : boolean {
    return this._hasFixedWidth
  }

  getHeight (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : ?number {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellHeightCache.hasOwnProperty(key)
      ? Math.max(this._minHeight, this._cellHeightCache[key])
      : this._defaultHeight
  }

  getWidth (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : ?number {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellWidthCache.hasOwnProperty(key)
      ? Math.max(this._minWidth, this._cellWidthCache[key])
      : this._defaultWidth
  }

  has (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : boolean {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellHeightCache.hasOwnProperty(key)
  }

  rowHeight = ({ index } : IndexParam) => {
    const key = this._keyMapper(index, 0)

    return this._rowHeightCache.hasOwnProperty(key)
      ? this._rowHeightCache[key]
      : this._defaultHeight
  }

  set (
    rowIndex: number,
    columnIndex: number,
    width: number,
    height: number
  ) : void {
    const key = this._keyMapper(rowIndex, columnIndex)

    if (columnIndex >= this._columnCount) {
      this._columnCount = columnIndex + 1
    }
    if (rowIndex >= this._rowCount) {
      this._rowCount = rowIndex + 1
    }

    // Size is cached per cell so we don't have to re-measure if cells are re-ordered.
    this._cellHeightCache[key] = height
    this._cellWidthCache[key] = width

    this._updateCachedColumnAndRowSizes(rowIndex, columnIndex)
  }

  _updateCachedColumnAndRowSizes (
    rowIndex: number,
    columnIndex: number
  ) : void {
    // :columnWidth and :rowHeight are derived based on all cells in a column/row.
    // Pre-cache these derived values for faster lookup later.
    // Reads are expected to occur more frequently than writes in this case.
    let columnWidth = 0
    for (let i = 0; i < this._rowCount; i++) {
      columnWidth = Math.max(columnWidth, this.getWidth(i, columnIndex))
    }
    let rowHeight = 0
    for (let i = 0; i < this._columnCount; i++) {
      rowHeight = Math.max(rowHeight, this.getHeight(rowIndex, i))
    }

    const columnKey = this._keyMapper(0, columnIndex)
    const rowKey = this._keyMapper(rowIndex, 0)

    this._columnWidthCache[columnKey] = columnWidth
    this._rowHeightCache[rowKey] = rowHeight
  }
}

function defaultKeyMapper (
  rowIndex: number,
  columnIndex: number
): any {
  return `${rowIndex}-${columnIndex}`
}
<commit_msg>Optimizing column/row cache update mechanism. Has huge performance improvement when CellMeasurer is used<commit_after>/** @flow */

export const DEFAULT_HEIGHT = 30
export const DEFAULT_WIDTH = 100

// Enables more intelligent mapping of a given column and row index to an item ID.
// This prevents a cell cache from being invalidated when its parent collection is modified.
type KeyMapper = (
  rowIndex: number,
  columnIndex: number
) => any;

type CellMeasurerCacheParams = {
  defaultHeight ?: number,
  defaultWidth ?: number,
  fixedHeight ?: boolean,
  fixedWidth ?: boolean,
  minHeight?: number,
  minWidth?: number,
  keyMapper ?: KeyMapper
};

type Cache = {
  [key: any]: number
};

type IndexParam = {
  index: number
};

/**
 * Caches measurements for a given cell.
 */
export default class CellMeasurerCache {
  _cellHeightCache: Cache;
  _cellWidthCache: Cache;
  _columnWidthCache: Cache;
  _defaultHeight: ?number;
  _defaultWidth: ?number;
  _minHeight: ?number;
  _minWidth: ?number;
  _keyMapper: KeyMapper;
  _rowHeightCache: Cache;

  constructor (params : CellMeasurerCacheParams = {}) {
    const {
      defaultHeight,
      defaultWidth,
      fixedHeight,
      fixedWidth,
      keyMapper,
      minHeight,
      minWidth
    } = params

    this._hasFixedHeight = fixedHeight === true
    this._hasFixedWidth = fixedWidth === true
    this._minHeight = minHeight || 0
    this._minWidth = minWidth || 0
    this._keyMapper = keyMapper || defaultKeyMapper

    this._defaultHeight = Math.max(
      this._minHeight,
      typeof defaultHeight === 'number'
        ? defaultHeight
        : DEFAULT_HEIGHT
    )
    this._defaultWidth = Math.max(
      this._minWidth,
      typeof defaultWidth === 'number'
        ? defaultWidth
        : DEFAULT_WIDTH
    )

    if (process.env.NODE_ENV !== 'production') {
      if (
        this._hasFixedHeight === false &&
        this._hasFixedWidth === false
      ) {
        console.warn(
          'CellMeasurerCache should only measure a cell\'s width or height. ' +
          'You have configured CellMeasurerCache to measure both. ' +
          'This will result in poor performance.'
        )
      }

      if (
        this._hasFixedHeight === false &&
        this._defaultHeight === 0
      ) {
        console.warn(
          'Fixed height CellMeasurerCache should specify a :defaultHeight greater than 0. ' +
          'Failing to do so will lead to unnecessary layout and poor performance.'
        )
      }

      if (
        this._hasFixedWidth === false &&
        this._defaultWidth === 0
      ) {
        console.warn(
          'Fixed width CellMeasurerCache should specify a :defaultWidth greater than 0. ' +
          'Failing to do so will lead to unnecessary layout and poor performance.'
        )
      }
    }

    this._columnCount = 0
    this._rowCount = 0

    this._cellHeightCache = {}
    this._cellWidthCache = {}
    this._columnWidthCache = {}
    this._rowHeightCache = {}
  }

  clear (
    rowIndex: number,
    columnIndex: number
  ) : void {
    const key = this._keyMapper(rowIndex, columnIndex)

    delete this._cellHeightCache[key]
    delete this._cellWidthCache[key]

    this._updateCachedColumnAndRowSizes(rowIndex, columnIndex)
  }

  clearAll () : void {
    this._cellHeightCache = {}
    this._cellWidthCache = {}
    this._columnWidthCache = {}
    this._rowHeightCache = {}
  }

  columnWidth = ({ index } : IndexParam) => {
    const key = this._keyMapper(0, index)

    return this._columnWidthCache.hasOwnProperty(key)
      ? this._columnWidthCache[key]
      : this._defaultWidth
  }

  get defaultHeight () : number {
    return this._defaultHeight
  }

  get defaultWidth () : number {
    return this._defaultWidth
  }

  hasFixedHeight () : boolean {
    return this._hasFixedHeight
  }

  hasFixedWidth () : boolean {
    return this._hasFixedWidth
  }

  getHeight (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : ?number {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellHeightCache.hasOwnProperty(key)
      ? Math.max(this._minHeight, this._cellHeightCache[key])
      : this._defaultHeight
  }

  getWidth (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : ?number {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellWidthCache.hasOwnProperty(key)
      ? Math.max(this._minWidth, this._cellWidthCache[key])
      : this._defaultWidth
  }

  has (
    rowIndex: number,
    columnIndex: ?number = 0
  ) : boolean {
    const key = this._keyMapper(rowIndex, columnIndex)

    return this._cellHeightCache.hasOwnProperty(key)
  }

  rowHeight = ({ index } : IndexParam) => {
    const key = this._keyMapper(index, 0)

    return this._rowHeightCache.hasOwnProperty(key)
      ? this._rowHeightCache[key]
      : this._defaultHeight
  }

  set (
    rowIndex: number,
    columnIndex: number,
    width: number,
    height: number
  ) : void {
    const key = this._keyMapper(rowIndex, columnIndex)

    if (columnIndex >= this._columnCount) {
      this._columnCount = columnIndex + 1
    }
    if (rowIndex >= this._rowCount) {
      this._rowCount = rowIndex + 1
    }

    // Size is cached per cell so we don't have to re-measure if cells are re-ordered.
    this._cellHeightCache[key] = height
    this._cellWidthCache[key] = width

    this._updateCachedColumnAndRowSizes(rowIndex, columnIndex)
  }

  _updateCachedColumnAndRowSizes (
    rowIndex: number,
    columnIndex: number
  ) : void {
    // :columnWidth and :rowHeight are derived based on all cells in a column/row.
    // Pre-cache these derived values for faster lookup later.
    // Reads are expected to occur more frequently than writes in this case.
    const columnKey = this._keyMapper(0, columnIndex)
    const rowKey = this._keyMapper(rowIndex, 0)
    let columnWidth = 0
    if (this._hasFixedWidth) {
      // if has fixed width columns, no need to calculate width for each row
      columnWidth = this._columnWidthCache[columnKey] || columnWidth;
      columnWidth = Math.max(columnWidth, this.getWidth(rowIndex, columnIndex))
    }
    else {
      for (let i = 0; i < this._rowCount; i++) {
        columnWidth = Math.max(columnWidth, this.getWidth(i, columnIndex))
      }
    }
    let rowHeight = 0
    if (this._hasFixedHeight) {
      // if has fixed height rows, no need to calculate height for each column
      rowHeight = this._rowHeightCache[rowKey] || rowHeight;
      rowHeight = Math.max(rowHeight, this.getHeight(rowIndex, columnIndex))
    }
    else {
      for (let i = 0; i < this._columnCount; i++) {
        rowHeight = Math.max(rowHeight, this.getHeight(rowIndex, i))
      }
    }

    this._columnWidthCache[columnKey] = columnWidth
    this._rowHeightCache[rowKey] = rowHeight
  }
}

function defaultKeyMapper (
  rowIndex: number,
  columnIndex: number
): any {
  return `${rowIndex}-${columnIndex}`
}
<|endoftext|>