<commit_before>'use strict';

var express = require( 'express' ),
    app = express.createServer(),
    async = require( 'async'),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    rimraf = require( 'rimraf' ),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    regexp = require( './lib/regexp' ),
	requirejs = require( 'requirejs' ),
    requirejs_traceFiles = require( './lib/r.js' );

var httpPort = process.env.PORT || 8080,
    repoBaseDir = path.normalize( process.env.REPO_BASE_DIR ),
    workBaseDir = path.normalize ( process.env.WORK_BASE_DIR );

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
    app.use( express.logger( 'tiny' ) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

function fetch( repo, callback ) {
    exec( "git fetch",
        {
            encoding: 'utf8',
            timeout: 0,
            cwd: repo,
            env: null
        },
        callback
    );
}

function checkout( repoName, repoDir, tag, force, callback ){
    if ( typeof force === "function" ) {
        callback = force;
        force = false;
    }
    if (!repoName) throw new Error( "No repo name specified" );
    if (!repoDir) throw new Error( "No repo dir specified" );
    if (!callback) throw new Error( "No callback passed to checkout()" );
    if (!tag) {
        tag = "master";
    }

    // Workspace
    var wsDir  = workBaseDir + "/" + repoName + "." + tag;

    path.exists( wsDir, function( exists ) {
        if ( exists || force ) {
            fs.mkdir( wsDir, function () {
                exec( "git --work-tree=" + wsDir + " checkout -f " + tag,
                    {
                        encoding: 'utf8',
                        timeout: 0,
                        cwd: repoDir,
                        env: null
                    },
                    callback
                );
            });
        } else {
            callback( "Worspace for " + repoName + "/" + tag + " has not been created" );
        }
    });
}

function getFirstExistingDir( candidates, callback ) {
    var dir = candidates.shift();
    path.exists( dir , function( exists ) {
        if ( exists ) {
            callback( null, dir );
        } else {
            if ( candidates.length ) {
                getFirstExistingDir( candidates, callback );
            } else {
                callback( "none found" );
            }
        }
    });
}

function getRepoDir( repo, callback ) {
    var repoDir = repoBaseDir + "/" + repo;
    getFirstExistingDir( [ repoDir, repoDir + ".git" ], callback );
}

function getWorkspaceDir( repo, tag, callback ) {
    var workspaceDir = workBaseDir + "/" + repo + "." + tag;
    callback( null, workspaceDir );
}

app.get( '/:repo/fetch', function ( req, res ) {
    var repo = repoBaseDir + "/" + req.params.repo;

    fetch( repo,
        function ( error, stdout, stderr ) {
            //console.log('stdout: ' + stdout);
            //console.log('stderr: ' + stderr);
            if ( error !== null ) {
                res.send( error, 500 );
            } else {
                res.send( stdout );
            }
        }
    );
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload,
        repo, repoDir, tag,
        fetchIfExists = function( candidates, callback ) {
            var dir = candidates.shift();
            path.exists( dir , function( exists ) {
                if ( exists ) {
                    fetch( dir,
                        function ( error, stdout, stderr ) {
                            if ( error !== null ) {
                                res.send( error, 500 );
                            } else {
                                callback( dir );
                            }
                        }
                    );
                } else {
                    if ( candidates.length ) {
                        fetchIfExists( candidates );
                    } else {
                        res.send( "Workspace for '" + repo + "' hasn't been checked out", 404 );
                    }
                }
            });
        };

    if ( payload ) {
        try {
            payload = JSON.parse( payload );
            repo = payload.repository.name;
            tag = payload.ref.split( "/" ).pop();

            if ( payload.repository && payload.repository.name ) {
                async.waterfall([
                    function( callback ){
                        getRepoDir( repo, callback );
                    },
                    function( dir, callback ) {
                        repoDir = dir;
                        fetch( dir, callback );
                    },
                    function( stdout, stderr, callback ) {
                        checkout( repo, repoDir, tag, callback );
                    },
                    function( stdout, stderr, callback ) {
                        var workspace = workBaseDir + "/" + repo + "." + tag,
                            compiled = workspace + "/compiled";
                        async.series([
                            function( cb ) {
                                rimraf( compiled, cb );
                            },
                            function( cb ) {
                                fs.mkdir( compiled, cb );
                            }

                        ], function( err, results ) {
                            if ( err )  {
                                callback( err );
                            } else {
                                callback( null, stdout );
                            }
                        });
                    }
                ],
                function ( err, result ) {
                    if ( err ) {
                        res.send( err, 500 );
                    } else {
                        res.send( "OK" );
                    }
                });
            } else {
                res.send( "Payload is missing data", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:repo/:tag/checkout', function ( req, res ) {
    var repoName = req.params.repo,
        tag      = req.params.tag;

    async.waterfall([
        function( callback ) {
            getRepoDir( repoName, callback )
        },
        function( repoDir, callback ) {
            checkout( repoName, repoDir, tag, callback );
        },
        function( stdout, stderr, callback ) {
            res.send( stdout );
            callback( null );
        }

    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        pragmas = JSON.parse( req.param( "pragmas", "{}" ) ),
        pragmasOnSave = JSON.parse( req.param( "pragmasOnSave", "{}" ) ),
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        shasum = crypto.createHash( 'sha1' ),
        wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        dstDir, dstFile;

	//Set up the config passed to the optimizer
	var config = {
		baseUrl: wsDir + "/" + baseUrl,
		include: include,
        pragmas: pragmas,
        pragmasOnSave: pragmasOnSave
	};

    shasum.update( JSON.stringify( config ) );

    dstDir = wsDir + "/compiled/" + shasum.digest( 'hex' );
    dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    config.out = dstFile;
    config.optimize = optimize;

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            try {
				requirejs.optimize( config, function ( buildResponse ) {
					//buildResponse is just a text output of the modules
					//included. Load the built file for the contents.
					fs.readFile( config.out, 'utf8', function( err, contents ) {
                        if ( err ) throw err;
						res.send( contents );
					});
				});
			} catch ( e ) {
				res.send( e.toString(), 500 );
			}
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir   = workBaseDir + "/" + req.params.repo + "." + req.params.tag,
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        names = req.param( "names", req.params.repo ).split( "," ).sort(),
        baseUrl = path.normalize( wsDir + "/" + req.param( "baseUrl", "." ) ),
        shasum = crypto.createHash( 'sha1' ),
        filename = wsDir + "/deps-";

    // Generate a sha on the sorted names
    shasum.update( names.join( "," ) );
    filename += shasum.digest( 'hex' ) + ".json";

    path.exists( filename, function( exists ) {
        if ( exists ){
            res.sendfile( filename );
        } else {
            requirejs_traceFiles.tools.traceFiles( {
                    baseUrl: baseUrl,
                    modules: names.map( function( name ) { return { name: name } } )
                },
                function( deps ) {
                    // Walk through the dep map and remove baseUrl and js extention
                    var module,
                        baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl + "/") ),
                        jsExtRE = new RegExp( regexp.escapeString( ".js" ) + "$" );
                    for ( module in deps ) {
                        deps[ module ].files.pop();
                        deps[ module ].deps = deps[ module ].files.map(
                            function( file ) {
                                return file.replace( baseUrlRE, "" ).replace( jsExtRE, "" );
                            }
                        );
                        delete deps[ module ].files;
                    }
                    fs.writeFile( filename, JSON.stringify( deps ),
                        function (err) {
                            if (err) throw err;
                        }
                    );
                    res.json( deps );
                }
            );
        }
    });
});

console.log( "listening on port:", httpPort );
app.listen( httpPort );<commit_msg>Added /dependencies with no name returning dep map for all js objects in baseUrl Made some function synchronous<commit_after>'use strict';

var express = require( 'express' ),
    app = express.createServer(),
    async = require( 'async'),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    rimraf = require( 'rimraf' ),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    regexp = require( './lib/regexp' ),
	requirejs = require( 'requirejs' ),
    requirejs_traceFiles = require( './lib/r.js' );

var httpPort = process.env.PORT || 8080,
    repoBaseDir = path.normalize( process.env.REPO_BASE_DIR ),
    workBaseDir = path.normalize ( process.env.WORK_BASE_DIR );

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
    app.use( express.logger( 'tiny' ) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

function fetch( repo, callback ) {
    exec( "git fetch",
        {
            encoding: 'utf8',
            timeout: 0,
            cwd: repo,
            env: null
        },
        callback
    );
}

function checkout( repoName, repoDir, tag, force, callback ){
    if ( typeof force === "function" ) {
        callback = force;
        force = false;
    }
    if (!repoName) throw new Error( "No repo name specified" );
    if (!repoDir) throw new Error( "No repo dir specified" );
    if (!callback) throw new Error( "No callback passed to checkout()" );
    if (!tag) {
        tag = "master";
    }

    // Workspace
    var wsDir  = workBaseDir + "/" + repoName + "." + tag;

    path.exists( wsDir, function( exists ) {
        if ( exists || force ) {
            fs.mkdir( wsDir, function () {
                exec( "git --work-tree=" + wsDir + " checkout -f " + tag,
                    {
                        encoding: 'utf8',
                        timeout: 0,
                        cwd: repoDir,
                        env: null
                    },
                    callback
                );
            });
        } else {
            callback( "Worspace for " + repoName + "/" + tag + " has not been created" );
        }
    });
}

function getFirstExistingDir( candidates, callback ) {
    var dir = candidates.shift();
    path.exists( dir , function( exists ) {
        if ( exists ) {
            callback( null, dir );
        } else {
            if ( candidates.length ) {
                getFirstExistingDir( candidates, callback );
            } else {
                callback( "none found" );
            }
        }
    });
}

function getRepoDir( repo, callback ) {
    var repoDir = repoBaseDir + "/" + repo;
    getFirstExistingDir( [ repoDir, repoDir + ".git" ], callback );
}

function getWorkspaceDirSync( repo, tag ) {
    return workBaseDir + "/" + repo + "." + tag;
}

function getCompiledDirSync( repo, tag ) {
    return getWorkspaceDirSync( repo, tag ) + "/__compiled";
}

app.get( '/:repo/fetch', function ( req, res ) {
    var repo = repoBaseDir + "/" + req.params.repo;

    fetch( repo,
        function ( error, stdout, stderr ) {
            //console.log('stdout: ' + stdout);
            //console.log('stderr: ' + stderr);
            if ( error !== null ) {
                res.send( error, 500 );
            } else {
                res.send( stdout );
            }
        }
    );
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload,
        repoName, repoDir, tag,
        fetchIfExists = function( candidates, callback ) {
            var dir = candidates.shift();
            path.exists( dir , function( exists ) {
                if ( exists ) {
                    fetch( dir,
                        function ( error, stdout, stderr ) {
                            if ( error !== null ) {
                                res.send( error, 500 );
                            } else {
                                callback( dir );
                            }
                        }
                    );
                } else {
                    if ( candidates.length ) {
                        fetchIfExists( candidates );
                    } else {
                        res.send( "Workspace for '" + repoName + "' hasn't been checked out", 404 );
                    }
                }
            });
        };

    if ( payload ) {
        try {
            payload = JSON.parse( payload );
            repoName = payload.repository.name;
            tag = payload.ref.split( "/" ).pop();

            if ( payload.repository && payload.repository.name ) {
                async.waterfall([
                    function( callback ){
                        getRepoDir( repoName, callback );
                    },
                    function( dir, callback ) {
                        repoDir = dir;
                        fetch( dir, callback );
                    },
                    function( stdout, stderr, callback ) {
                        checkout( repoName, repoDir, tag, callback );
                    },
                    function( stdout, stderr, callback ) {
                        var compiled = getCompiledDirSync( repoName, tag );
                        async.series([
                            function( cb ) {
                                rimraf( compiled, cb );
                            },
                            function( cb ) {
                                fs.mkdir( compiled, cb );
                            }

                        ], function( err, results ) {
                            if ( err )  {
                                callback( err );
                            } else {
                                callback( null, stdout );
                            }
                        });
                    }
                ],
                function ( err, result ) {
                    if ( err ) {
                        res.send( err, 500 );
                    } else {
                        res.send( "OK" );
                    }
                });
            } else {
                res.send( "Payload is missing data", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:repo/:tag/checkout', function ( req, res ) {
    var repoName = req.params.repo,
        tag      = req.params.tag;

    async.waterfall([
        function( callback ) {
            getRepoDir( repoName, callback )
        },
        function( repoDir, callback ) {
            checkout( repoName, repoDir, tag, callback );
        },
        function( stdout, stderr, callback ) {
            res.send( stdout );
            callback( null );
        }

    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        pragmas = JSON.parse( req.param( "pragmas", "{}" ) ),
        pragmasOnSave = JSON.parse( req.param( "pragmasOnSave", "{}" ) ),
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        shasum = crypto.createHash( 'sha1' ),
        wsDir   = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        dstDir, dstFile;

	//Set up the config passed to the optimizer
	var config = {
		baseUrl: wsDir + "/" + baseUrl,
		include: include,
        pragmas: pragmas,
        pragmasOnSave: pragmasOnSave
	};

    shasum.update( JSON.stringify( config ) );

    dstDir = getCompiledDirSync( req.params.repo, req.params.tag ) + shasum.digest( 'hex' );
    dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    config.out = dstFile;
    config.optimize = optimize;

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            try {
				requirejs.optimize( config, function ( buildResponse ) {
					//buildResponse is just a text output of the modules
					//included. Load the built file for the contents.
					fs.readFile( config.out, 'utf8', function( err, contents ) {
                        if ( err ) throw err;
						res.send( contents );
					});
				});
			} catch ( e ) {
				res.send( e.toString(), 500 );
			}
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        names = req.param( "names", "" ).split( "," ).filter( function(name) {return !!name} ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        baseUrl = path.normalize( wsDir + "/" + req.param( "baseUrl", "." ) ),
        shasum = crypto.createHash( 'sha1' ),
        filename = getCompiledDirSync( req.params.repo, req.params.tag ) + "/deps-";

    async.series([
        function( callback ) {
            // If no name is provided, scan the baseUrl for js files and return the dep map for all JS objects in baseUrl
            if ( names.length ) {
                callback( null );
            } else {
                fs.readdir(baseUrl, function( err, files ) {
                    if ( err ) {
                        callback( err );
                    } else {
                        files = files.filter( function( file ) { return path.extname( file ) === ".js" } );
                        names = files.map( function( file ) { return path.basename( file, ".js" ) } );

                        callback( null );
                    }
                });
            }
        },
        function( callback ) {
            // Generate a sha on the sorted names
            shasum.update( names.join( "," ) );
            filename += shasum.digest( 'hex' ) + ".json";

            path.exists( filename,
                function( exists ) {
                    if ( exists ){
                        res.sendfile( filename );
                    } else {
                        requirejs_traceFiles.tools.traceFiles( {
                                baseUrl: baseUrl,
                                modules: names.map( function( name ) { return { name: name } } )
                            },
                            function( deps ) {
                                // Walk through the dep map and remove baseUrl and js extention
                                var module,
                                    baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl + "/") ),
                                    jsExtRE = new RegExp( regexp.escapeString( ".js" ) + "$" );
                                for ( module in deps ) {
                                    deps[ module ].files.pop();
                                    deps[ module ].deps = deps[ module ].files.map(
                                        function( file ) {
                                            return file.replace( baseUrlRE, "" ).replace( jsExtRE, "" );
                                        }
                                    );
                                    delete deps[ module ].files;
                                }
                                fs.writeFile( filename, JSON.stringify( deps ),
                                    function (err) {
                                        if (err) throw err;
                                    }
                                );
                                res.json( deps );
                            }
                        );
                    }
                }
            )
        }
    ]);
});

console.log( "listening on port:", httpPort );
app.listen( httpPort );<|endoftext|>


<commit_before>var test = false,originspp = 0;
numberWithCommas = function(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
removeCommas = function(myVar){
    myVar = myVar.replace(/[ ,]/g, "");
    return myVar;
}
filltotal = function(){
    var total = parseInt(removeCommas($("#spp_").val()))+parseInt(removeCommas($("#psb").val()))+parseInt(removeCommas($("#book").val()))+parseInt(removeCommas($("#bimbel").val()));
    $("#total").val(numberWithCommas(total));
}
fillreturnmoney = function(){
    $("#returnmoney").val(numberWithCommas(parseInt(removeCommas($("#cashpay").val()))-parseInt(removeCommas($("#total").val()))));
}
togglespp = function(){
    if($("#sppcheckbox").prop("checked")){
        $("#sppmonthdiv").show();
        $("#spp_").val($("#orispp").val());
    }else{
        $("#sppmonthdiv").hide();
        $("#spp_").val(0);
    }
    filltotal();
    fillreturnmoney();
}
togglebimbel = function(){
    if($("#bimbelcheckbox").prop("checked")){
        $("#bimbelmonthdiv").show();
        $("#bimbel").val($("#oribimbel").val());
    }else{
        $("#bimbelmonthdiv").hide();
        $("#bimbel").val(0);
    }
    filltotal();
    fillreturnmoney();
}
$.fn.adjustval = function(options){
    $(this).change(function(){
        var settings = $.extend({
            firstmonth:$("#sppfrstmonth"),
            firstyear:$("#sppfrstyear"),
            nextmonth:$("#sppnextmonth"),
            nextyear:$("#sppnextyear"),
            hiddenval : $("#spp_"),
            shownval: $("#bimbel"),
            orival:$("#orival")
        },options);
        console.log("time changed");
        monthcount = 0;
        if(settings.nextyear.val()===settings.firstyear.val()){
            if(settings.nextmonth.val()===settings.firstmonth.val()){
                monthcount = 1;
            }else
            if(settings.nextmonth.val()>settings.firstmonth.val()){
                monthcount = settings.nextmonth.val() - settings.firstmonth.val() + 1;

            }else{
                settings.nextmonth.val(settings.firstmonth.val());
            }
        }else
        if(settings.nextyear.val()>settings.firstyear.val()){
            frsmonths = 12 - settings.firstmonth.val();
            months = 12*(settings.nextyear.val()-settings.firstyear.val() - 1);
            nextmonths = settings.nextmonth.val();
            monthcount = parseInt(frsmonths)+parseInt(months)+parseInt(nextmonths) + 1;
        }else{
            settings.nextyear.val(settings.firstyear.val());
        }
        _total = parseInt(settings.orival.val())*monthcount;
        settings.shownval.val(numberWithCommas(_total));
        settings.hiddenval.val(_total);
        filltotal();
        fillreturnmoney();
        if(test===true){
            alert(monthcount);
        };
    });
};
$.ajax({
    url:'/students/getjson',
    dataType:'json'
})
.done(function(res){
    $("#sname").focus(function(){
        $(this).select();
    });
    $('#sname').autocomplete({
        lookup: res.out,
        onSelect: function(suggestion) {
            console.log('suggestion-data',suggestion.data);
            console.log('suggestion',suggestion);
            console.log('cek status');
            $("#nis").val(suggestion.nis);
            $("#studentname").val(suggestion.name);
            $("#grade").val(suggestion.grade);
                $.ajax({
                    url:'/students/getproperties/'+suggestion.nis,
                    type:'get',
                    dataType:'Json'
                })
                .done(function(res){
                    originspp = res.spp;
                    $("#spp_").val(numberWithCommas(res.spp));
                    $("#spp").val(res.spp);
                    $("#orispp").val(res.spp);
                    $("#bimbel_").val(numberWithCommas(res.bimbel));
                    $("#bimbel").val(res.bimbel);
                    $("#oribimbel").val(res.bimbel);
                    $("#psb_").val(numberWithCommas(res.dupsbremain));
                    $("#psb").val(numberWithCommas(res.dupsbremain));
                    filltotal();
                    fillreturnmoney();
                });
        },
        onHint: function (hint) {
            console.log('hint',hint);
        },
        onInvalidateSelection: function() {
        }
    });
})
.fail(function(err){
    console.log("Error fetch json",err);
});
$("#cashpay").keyup(function(){
    fillreturnmoney()
});
$("#cashpay").focus(function(){
    $(this).select();
})
$("#cashpay").blur(function(){
    $(this).val(numberWithCommas($(this).val()));
})
$(".affect-total").focus(function(){
    $(this).val(removeCommas($(this).val().toString()));
    $(this).select();
})
$(".formatted").blur(function(){
    $(this).val(numberWithCommas($(this).val().toString()));
})
togglespp();
$("#sppcheckbox").change(function(){
    togglespp();
})
togglebimbel();
$("#bimbelcheckbox").change(function(){
    togglebimbel();
});
$(".affect-total").keyup(function(){
    filltotal();
    fillreturnmoney();
});
$(".affect-total").change(function(){
    filltotal();
    fillreturnmoney();
});
$(".bimbelperiod").adjustval({
    firstmonth:$("#bimbelfrstmonth"),
    firstyear:$("#bimbelfrstyear"),
    nextmonth:$("#bimbelnextmonth"),
    nextyear:$("#bimbelnextyear"),
    hiddenval : $("#bimbel"),
    shownval: $("#bimbel_"),
    orival: $("#oribimbel")
});
$(".sppperiod").adjustval({
    firstmonth:$("#sppfrstmonth"),
    firstyear:$("#sppfrstyear"),
    nextmonth:$("#sppnextmonth"),
    nextyear:$("#sppnextyear"),
    hiddenval : $("#spp"),
    shownval: $("#spp_"),
    orival: $("#orispp")
});
<commit_msg>add tooltip for help<commit_after>var test = false,originspp = 0;
numberWithCommas = function(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
removeCommas = function(myVar){
    myVar = myVar.replace(/[ ,]/g, "");
    return myVar;
}
filltotal = function(){
    var total = parseInt(removeCommas($("#spp_").val()))+parseInt(removeCommas($("#psb").val()))+parseInt(removeCommas($("#book").val()))+parseInt(removeCommas($("#bimbel").val()));
    $("#total").val(numberWithCommas(total));
}
fillreturnmoney = function(){
    $("#returnmoney").val(numberWithCommas(parseInt(removeCommas($("#cashpay").val()))-parseInt(removeCommas($("#total").val()))));
}
togglespp = function(){
    if($("#sppcheckbox").prop("checked")){
        $("#sppmonthdiv").show();
        $("#spp_").val($("#orispp").val());
    }else{
        $("#sppmonthdiv").hide();
        $("#spp_").val(0);
    }
    filltotal();
    fillreturnmoney();
}
togglebimbel = function(){
    if($("#bimbelcheckbox").prop("checked")){
        $("#bimbelmonthdiv").show();
        $("#bimbel").val($("#oribimbel").val());
    }else{
        $("#bimbelmonthdiv").hide();
        $("#bimbel").val(0);
    }
    filltotal();
    fillreturnmoney();
}
$.fn.adjustval = function(options){
    $(this).change(function(){
        var settings = $.extend({
            firstmonth:$("#sppfrstmonth"),
            firstyear:$("#sppfrstyear"),
            nextmonth:$("#sppnextmonth"),
            nextyear:$("#sppnextyear"),
            hiddenval : $("#spp_"),
            shownval: $("#bimbel"),
            orival:$("#orival")
        },options);
        console.log("time changed");
        monthcount = 0;
        if(settings.nextyear.val()===settings.firstyear.val()){
            if(settings.nextmonth.val()===settings.firstmonth.val()){
                monthcount = 1;
            }else
            if(settings.nextmonth.val()>settings.firstmonth.val()){
                monthcount = settings.nextmonth.val() - settings.firstmonth.val() + 1;

            }else{
                settings.nextmonth.val(settings.firstmonth.val());
            }
        }else
        if(settings.nextyear.val()>settings.firstyear.val()){
            frsmonths = 12 - settings.firstmonth.val();
            months = 12*(settings.nextyear.val()-settings.firstyear.val() - 1);
            nextmonths = settings.nextmonth.val();
            monthcount = parseInt(frsmonths)+parseInt(months)+parseInt(nextmonths) + 1;
        }else{
            settings.nextyear.val(settings.firstyear.val());
        }
        _total = parseInt(settings.orival.val())*monthcount;
        settings.shownval.val(numberWithCommas(_total));
        settings.hiddenval.val(_total);
        filltotal();
        fillreturnmoney();
        if(test===true){
            alert(monthcount);
        };
    });
};
$.ajax({
    url:'/students/getjson',
    dataType:'json'
})
.done(function(res){
    $("#sname").focus(function(){
        $(this).select();
    });
    $('#sname').autocomplete({
        lookup: res.out,
        onSelect: function(suggestion) {
            console.log('suggestion-data',suggestion.data);
            console.log('suggestion',suggestion);
            console.log('cek status');
            $("#nis").val(suggestion.nis);
            $("#studentname").val(suggestion.name);
            $("#grade").val(suggestion.grade);
                $.ajax({
                    url:'/students/getproperties/'+suggestion.nis,
                    type:'get',
                    dataType:'Json'
                })
                .done(function(res){
                    originspp = res.spp;
                    $("#spp_").val(numberWithCommas(res.spp));
                    $("#spp").val(res.spp);
                    $("#orispp").val(res.spp);
                    $("#bimbel_").val(numberWithCommas(res.bimbel));
                    $("#bimbel").val(res.bimbel);
                    $("#oribimbel").val(res.bimbel);
                    $("#psb_").val(numberWithCommas(res.dupsbremain));
                    $("#psb").val(numberWithCommas(res.dupsbremain));
                    filltotal();
                    fillreturnmoney();
                });
        },
        onHint: function (hint) {
            console.log('hint',hint);
        },
        onInvalidateSelection: function() {
        }
    });
})
.fail(function(err){
    console.log("Error fetch json",err);
});
$("#cashpay").keyup(function(){
    fillreturnmoney()
});
$("#cashpay").focus(function(){
    $(this).select();
})
$("#cashpay").blur(function(){
    $(this).val(numberWithCommas($(this).val()));
})
$(".affect-total").focus(function(){
    $(this).val(removeCommas($(this).val().toString()));
    $(this).select();
})
$(".formatted").blur(function(){
    $(this).val(numberWithCommas($(this).val().toString()));
})
togglespp();
$("#sppcheckbox").change(function(){
    togglespp();
})
togglebimbel();
$("#bimbelcheckbox").change(function(){
    togglebimbel();
});
$(".affect-total").keyup(function(){
    filltotal();
    fillreturnmoney();
});
$(".affect-total").change(function(){
    filltotal();
    fillreturnmoney();
});
$(".bimbelperiod").adjustval({
    firstmonth:$("#bimbelfrstmonth"),
    firstyear:$("#bimbelfrstyear"),
    nextmonth:$("#bimbelnextmonth"),
    nextyear:$("#bimbelnextyear"),
    hiddenval : $("#bimbel"),
    shownval: $("#bimbel_"),
    orival: $("#oribimbel")
});
$(".sppperiod").adjustval({
    firstmonth:$("#sppfrstmonth"),
    firstyear:$("#sppfrstyear"),
    nextmonth:$("#sppnextmonth"),
    nextyear:$("#sppnextyear"),
    hiddenval : $("#spp"),
    shownval: $("#spp_"),
    orival: $("#orispp")
});
$('[data-toggle="tooltip"]').tooltip();<|endoftext|>


<commit_before>import RoughSpriteGenerator from 'object/RoughSpriteGenerator';
import Sun from 'object/Sun';
import House from 'object/House';
import Building from 'object/Building';

class GameState extends Phaser.State {

  create() {
    this.game.time.advancedTiming = true;
    this.game.stage.backgroundColor = "#a9f1f6";

    this.game.world.setBounds(0, 0, 1500, 600);

    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    this.game.physics.arcade.gravity.y = 300;
    // rough sprite generator
    const rsg = new RoughSpriteGenerator(this.game);

    this.house = new House(this.game, rsg, 50, this.game.height - 32 - 100, 150, 100);
    this.game.add.existing(this.house);

    this.house2 = new House(this.game, rsg, this.game.width - 20, this.game.height - 32 - 150, 150, 150);
    this.game.add.existing(this.house2);

    this.building = new Building(
      this.game,
      rsg,
      250,
      this.game.height - 32 - 400,
      200,
      400,
      {wallConfig: { fill: "rgba(226, 78, 46, 1.0)"}}
    );
    this.game.add.existing(this.building);

    this.building2 = new Building(
      this.game,
      rsg,
      500,
      this.game.height - 32 - 300,
      250,
      300,
      {wallConfig: { fill: "rgba(204, 179, 151, 1.0)"}}
    );
    this.game.add.existing(this.building2);

    this.building3 = new Building(
      this.game,
      rsg,
      this.game.world.bounds.width - 400,
      this.game.height - 32 - 500,
      200,
      500);
    this.game.add.existing(this.building3);

    this.sun = new Sun(this.game, rsg, 0, 0, 75);
    this.sun.fixedToCamera = true;
    this.game.add.existing(this.sun);

    this.cloud = rsg.getPolygonSprite(500, 30, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white', strokeWidth: 3, fillWeight: 5});
    this.cloud.scale.setTo(0.45,0.45);
    // add my own attribute
    this.cloud.vel = -0.05;
    this.game.add.existing(this.cloud);

    this.cloud2 = rsg.getPolygonSprite(0, 50, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white',  strokeWidth: 3, fillWeight: 5});
    this.cloud2.scale.setTo(0.5,0.5);
    this.cloud2.vel = 0.08;
    this.game.add.existing(this.cloud2);

    this.cloud3 = rsg.getPolygonSprite(700, 10, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white',  strokeWidth: 3, fillWeight: 5});
    this.cloud3.scale.setTo(0.35,0.35);
    this.cloud3.vel = 0.1;
    this.game.add.existing(this.cloud3);

    this.group = this.game.add.group();
    for(let i=0; i < 50; i++) {
      const rnd = Math.random();
      const x = this.getRandomInt((i * 50), (i + 1) * 50);
      const y = this.getRandomInt(350, 450);
      const config = {
        fill: this.getRandomColor(),
        fillWeight: this.getRandomInt(1, 5)
      }
      let sprite = null;
      if(rnd > 0.5) {
        const radius = this.getRandomInt(10, 25)
        sprite = rsg.getCircleSprite(x, y, radius, config);
        this.game.physics.enable(sprite, Phaser.Physics.ARCADE);
        const realRadius = radius + (config.fillWeight|| 0);
        sprite.body.setCircle(realRadius);
      } else {
        const width = this.getRandomInt(20, 50);
        const height = this.getRandomInt(20, 50);
        sprite = rsg.getRectangleSprite(x, y, width, height, config);
        this.game.physics.enable(sprite, Phaser.Physics.ARCADE);
      }
      sprite.body.bounce.setTo (0.80, 0.80);
      sprite.body.collideWorldBounds = true;
      sprite.body.velocity.x = this.getRandomInt(-75, 75);
      this.group.add(sprite);
    }

    this.character = rsg.getAnimatedRectangle(100, 20, 50, 50, {fillStyle: "solid", fill: "#D84315"}, 4);
    this.game.physics.enable(this.character, Phaser.Physics.ARCADE);
    this.character.body.collideWorldBounds = true;
    this.game.add.existing(this.character);
    this.game.camera.follow(this.character);

    this.ground = rsg.getRectangleSprite(0, this.game.height - 32 , this.game.world.bounds.width, 30, {fill: "#00A6A6", strokeWidth: 2});
    this.game.physics.enable(this.ground, Phaser.Physics.ARCADE);
    this.ground.body.allowGravity = false;
    this.ground.body.immovable = true;
    this.game.add.existing(this.ground);

    this.cursors = this.game.input.keyboard.createCursorKeys();
    this.jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
  }

  preload() {
  }

  cloudManagement() {
    [this.cloud, this.cloud2, this.cloud3].forEach(cloud => {
      if(cloud.x + cloud.width > this.game.world.bounds.width) {
        cloud.x = 0;
      } else if(cloud.x + cloud.width < 0) {
        cloud.x = this.game.world.bounds.width - cloud.width;
      } else {
        cloud.x += cloud.vel;
      }
    });
  }

  update() {
    this.game.physics.arcade.collide(this.character, this.ground);
    this.game.physics.arcade.collide(this.group, this.ground);

    this.character.body.velocity.x = 0;
    if (this.cursors.left.isDown)
    {
        this.character.body.velocity.x = -150;
    }
    else if (this.cursors.right.isDown)
    {
        this.character.body.velocity.x = 150;
    }

    if (this.jumpButton.isDown && !this.character.body.touching.none)
    {
        this.character.body.velocity.y = -300;
    }

    this.cloudManagement();
  }

  render() {
    this.game.debug.text(this.game.time.fps, 2, 14, "#00ff00");
    //this.game.debug.spriteBounds(this.house)
  }

  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }
}

export default GameState;
<commit_msg>update scene<commit_after>import RoughSpriteGenerator from 'object/RoughSpriteGenerator';
import Sun from 'object/Sun';
import House from 'object/House';
import Building from 'object/Building';

class GameState extends Phaser.State {

  create() {
    this.game.time.advancedTiming = true;
    this.game.stage.backgroundColor = "#a9f1f6";

    this.game.world.setBounds(0, 0, 1500, 600);

    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    this.game.physics.arcade.gravity.y = 300;
    // rough sprite generator
    const rsg = new RoughSpriteGenerator(this.game);

    this.house = new House(this.game, rsg, 50, this.game.height - 32 - 100, 150, 100);
    this.game.add.existing(this.house);

    this.house2 = new House(this.game, rsg, this.game.width - 20, this.game.height - 32 - 150, 150, 150);
    this.game.add.existing(this.house2);

    this.building = new Building(
      this.game,
      rsg,
      250,
      this.game.height - 32 - 400,
      200,
      400,
      {wallConfig: { fill: "rgba(226, 78, 46, 1.0)"}},
      true
    );
    this.game.add.existing(this.building);

    this.building2 = new Building(
      this.game,
      rsg,
      500,
      this.game.height - 32 - 300,
      250,
      300,
      {wallConfig: { fill: "rgba(204, 179, 151, 1.0)"}}
    );
    this.game.add.existing(this.building2);

    this.building3 = new Building(
      this.game,
      rsg,
      this.game.world.bounds.width - 400,
      this.game.height - 32 - 500,
      200,
      500);
    this.game.add.existing(this.building3);

    this.sun = new Sun(this.game, rsg, 0, 0, 75);
    this.sun.fixedToCamera = true;
    this.game.add.existing(this.sun);

    this.cloud = rsg.getPolygonSprite(500, 30, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white', strokeWidth: 3, fillWeight: 5});
    this.cloud.scale.setTo(0.45,0.45);
    // add my own attribute
    this.cloud.vel = -0.05;
    this.game.add.existing(this.cloud);

    this.cloud2 = rsg.getPolygonSprite(0, 50, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white',  strokeWidth: 3, fillWeight: 5});
    this.cloud2.scale.setTo(0.5,0.5);
    this.cloud2.vel = 0.08;
    this.game.add.existing(this.cloud2);

    this.cloud3 = rsg.getPolygonSprite(700, 10, 'M406.1 227.63c-8.23-103.65-144.71-137.8-200.49-49.05 -36.18-20.46-82.33 3.61-85.22 45.9C80.73 229.34 50 263.12 50 304.1c0 44.32 35.93 80.25 80.25 80.25h251.51c44.32 0 80.25-35.93 80.25-80.25C462 268.28 438.52 237.94 406.1 227.63z', 512, 512,{fill: 'white',  strokeWidth: 3, fillWeight: 5});
    this.cloud3.scale.setTo(0.35,0.35);
    this.cloud3.vel = 0.1;
    this.game.add.existing(this.cloud3);

    this.group = this.game.add.group();
    for(let i=0; i < 25; i++) {
      const rnd = Math.random();
      const x = this.getRandomInt((i * 50), (i + 1) * 50);
      const y = this.getRandomInt(350, 450);
      const config = {
        fill: this.getRandomColor(),
        fillWeight: this.getRandomInt(1, 5)
      }
      let sprite = null;
      if(rnd > 0.5) {
        const radius = this.getRandomInt(10, 25)
        sprite = rsg.getCircleSprite(x, y, radius, config);
        this.game.physics.enable(sprite, Phaser.Physics.ARCADE);
        const realRadius = radius + (config.fillWeight|| 0);
        sprite.body.setCircle(realRadius);
      } else {
        const width = this.getRandomInt(20, 50);
        const height = this.getRandomInt(20, 50);
        sprite = rsg.getRectangleSprite(x, y, width, height, config);
        this.game.physics.enable(sprite, Phaser.Physics.ARCADE);
      }
      sprite.body.bounce.setTo (0.80, 0.80);
      sprite.body.collideWorldBounds = true;
      sprite.body.velocity.x = this.getRandomInt(-75, 75);
      this.group.add(sprite);
    }

    this.character = rsg.getAnimatedRectangle(100, 450, 50, 75, {
        fill: "#00B0FF",
        roughness: 1.5,
        strokeWidth: 10,
        hachureAngle: 90,
        hachureGap: 5,
        fillWeight: 5,
        strokeWidth: 5
      }, 4);
    this.game.physics.enable(this.character, Phaser.Physics.ARCADE);
    this.character.body.collideWorldBounds = true;
    this.game.add.existing(this.character);
    this.game.camera.follow(this.character);

    this.ground = rsg.getRectangleSprite(0, this.game.height - 32 , this.game.world.bounds.width, 30, {fill: "#00A6A6", strokeWidth: 2});
    this.game.physics.enable(this.ground, Phaser.Physics.ARCADE);
    this.ground.body.allowGravity = false;
    this.ground.body.immovable = true;
    this.game.add.existing(this.ground);

    this.cursors = this.game.input.keyboard.createCursorKeys();
    this.jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
  }

  preload() {
  }

  cloudManagement() {
    [this.cloud, this.cloud2, this.cloud3].forEach(cloud => {
      if(cloud.x + cloud.width > this.game.world.bounds.width) {
        cloud.x = 0;
      } else if(cloud.x + cloud.width < 0) {
        cloud.x = this.game.world.bounds.width - cloud.width;
      } else {
        cloud.x += cloud.vel;
      }
    });
  }

  update() {
    this.game.physics.arcade.collide(this.character, this.ground);
    this.game.physics.arcade.collide(this.group, this.ground);

    this.character.body.velocity.x = 0;
    if (this.cursors.left.isDown)
    {
        this.character.body.velocity.x = -150;
    }
    else if (this.cursors.right.isDown)
    {
        this.character.body.velocity.x = 150;
    }

    if (this.jumpButton.isDown && !this.character.body.touching.none)
    {
        this.character.body.velocity.y = -300;
    }

    this.cloudManagement();
  }

  render() {
    this.game.debug.text(this.game.time.fps, 2, 14, "#00ff00");
    //this.game.debug.spriteBounds(this.house)
  }

  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }
}

export default GameState;
<|endoftext|>


<commit_before>// @flow
import React from 'react';

type Props = {
  executionCount: any,
  running: boolean,
};

export default class Inputs extends React.PureComponent {
  props: Props;

  render(): ?React.Element<any> {
    const { executionCount, running } = this.props;
    const count = !executionCount ? ' ' : executionCount;
    const input = running ? '*' : count;
    return (

        [{input}]

    );
  }
}
<commit_msg>refactor(Inputs): Rewrite component into stateless function<commit_after>// @flow
import React from 'react';

type Props = {
  executionCount: any,
  running: boolean,
};

export default function Inputs(props: Props): ?React.Element<any> {
  const { executionCount, running } = props;
  const count = !executionCount ? ' ' : executionCount;
  const input = running ? '*' : count;

  return (

      [{input}]

  );
}
<|endoftext|>


<commit_before>import { isString, isPlainObject } from 'lodash';

export default class RocExportPlugin {
    constructor(resolveRequest) {
        this.resolveRequest = resolveRequest;
    }

    apply(compiler) {
        const getAlias = createGetAlias(compiler.options.resolve.alias); // eslint-disable-line
        const resolveRequest = this.resolveRequest;

        // We assume that loaders will be managed in Webpack-land, meaning that we will not manage
        // them using exports in Roc
        compiler.resolvers.normal.plugin('module', function (result, next) {
            let request = result.request;

            // Use resolve.alias to use the alias if one exists and match
            const beforeAlias = request;
            request = getAlias(request);
            const afterAlias = request;

            // Try to resolve the dependency against the roc dependency context
            request = resolveRequest(request, result.path);

            return this.doResolve('normal', { ...result, request }, (err) => {
                if (err) {
                    // We got an error and will try again with fallback enabled
                    request = resolveRequest(request, result.path, true);
                }

                // If we have not changed the request we want to revert the alias change
                request = request === afterAlias ? beforeAlias : request;

                // Update the resolving with the new value if the request was modified
                if (request !== result.request) {
                    return this.doResolve(['file'], { ...result, request }, next);
                }

                // Do nothing and just pass through
                return next();
            });
        });
    }
}

// Based on code from enhanced-resolve
function createGetAlias(aliases) {
    if (isPlainObject(aliases) && !Array.isArray(aliases)) {
        aliases = Object.keys(aliases).map((key) => { // eslint-disable-line
            let onlyModule = false;
            let obj = aliases[key];
            if (/\$$/.test(key)) {
                onlyModule = true;
                key = key.substr(0, key.length - 1); // eslint-disable-line
            }
            if (isString(obj)) {
                obj = {
                    alias: obj,
                };
            }
            return {
                name: key,
                onlyModule,
                ...obj,
            };
        });
    }

    return (request) => {
        for (const alias of aliases) {
            if ((!alias.onlyModule && request.indexOf(`${alias.name}/`) === 0) || request === alias.name) {
                if (request.indexOf(`${alias.alias}/`) !== 0 && request !== alias.alias) {
                    return alias.alias + request.substr(alias.name.length);
                }
            }
        }
        return request;
    };
}
<commit_msg>Changed resolver used for checking response from Roc resolver<commit_after>import { isString, isPlainObject } from 'lodash';

export default class RocExportPlugin {
    constructor(resolveRequest) {
        this.resolveRequest = resolveRequest;
    }

    apply(compiler) {
        const getAlias = createGetAlias(compiler.options.resolve.alias); // eslint-disable-line
        const resolveRequest = this.resolveRequest;
        const resolving = {};

        // We assume that loaders will be managed in Webpack-land, meaning that we will not manage
        // them using exports in Roc
        compiler.resolvers.normal.plugin('module', function (result, next) {
            if (resolving[cacheKey(result)]) {
                return next();
            }

            let request = result.request;

            // Use resolve.alias to use the alias if one exists and match
            const beforeAlias = request;
            request = getAlias(request);
            const afterAlias = request;

            // Try to resolve the dependency against the roc dependency context
            request = resolveRequest(request, result.path);

            resolving[cacheKey(result)] = true;
            return this.resolve(result.path, request, (err) => {
                resolving[cacheKey(result)] = false;

                if (err) {
                    // We got an error and will try again with fallback enabled
                    request = resolveRequest(request, result.path, true);
                }

                // If we have not changed the request we want to revert the alias change
                request = request === afterAlias ? beforeAlias : request;

                // Update the resolving with the new value if the request was modified
                if (request !== result.request) {
                    return this.doResolve(['file'], { ...result, request }, next);
                }

                // Do nothing and just pass through
                return next();
            });
        });
    }
}

function cacheKey(result) {
    return `${result.path}@@@@@${result.request}`;
}

// Based on code from enhanced-resolve
function createGetAlias(aliases) {
    if (isPlainObject(aliases) && !Array.isArray(aliases)) {
        aliases = Object.keys(aliases).map((key) => { // eslint-disable-line
            let onlyModule = false;
            let obj = aliases[key];
            if (/\$$/.test(key)) {
                onlyModule = true;
                key = key.substr(0, key.length - 1); // eslint-disable-line
            }
            if (isString(obj)) {
                obj = {
                    alias: obj,
                };
            }
            return {
                name: key,
                onlyModule,
                ...obj,
            };
        });
    }

    return (request) => {
        for (const alias of aliases) {
            if ((!alias.onlyModule && request.indexOf(`${alias.name}/`) === 0) || request === alias.name) {
                if (request.indexOf(`${alias.alias}/`) !== 0 && request !== alias.alias) {
                    return alias.alias + request.substr(alias.name.length);
                }
            }
        }
        return request;
    };
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  // loading dependencies
  var Plugin = require('plugin');
  var Db = require('db');
  var Timer = require('timer');

  var Constants = require('Constants')();
  var GameTime = require('GameTime');

  // variables

  // the current GameTime (is updated on restart)
  var time = GameTime.startingOn(Db.shared.get('time', 'start'));

  /**
   * + Jonas Raoni Soares Silva
   * @ http://jsfromhell.com/array/shuffle [v1.0]
   */
  function shuffle(o){ //v1.0
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
  }

  /**
   * Creates a mapping of the userids to a role.
   * @param roles an object containing what roles should be added.
   *            each key should represent a role and the value how many of those
   *            roles. (if not enough roles, than we add normal citizens).
   * @param users the id of the users to assign roles to.
   */
  function generateRoles(roles, users) {

    // an array containing all the roles we want to add
    var roleArray = [];
    // index used for looping
    var i;

    // adding all the roles
    for (var role in roles) {
      if (roles.hasOwnProperty(role)) {
        // add the role
        for (i = 0; i < roles[role]; i++) {
          roleArray.push(role);
        }
      }
    }

    // add the missing roles
    for (i = roleArray.length; i < users.length; i++) {
      // add a citizen
      roleArray.push(Constants.roles.CITIZEN);
    }

    // shuffle the array
    shuffle(roleArray);

    // the result object (mapping from user -> role)
    var result = {};
    for (i = 0; i < users.length; i++) {
      result[users[i]] = roleArray[i];
    }

    return result;
  }

  /**
   * Gets all the users with the given role.
   */
  function usersWithRole(role) {
    var users = Plugin.userIds();
    return users.filter(function (user) {
      return Db.personal(user).get('role') === role;
    });
  }

  /**
   * Kills the given user.
   * The user is no longer alive and his role will be exposed.
   */
  function kill(user) {
    Db.shared.set('users', user, {
      isAlive: false,
      role: Db.personal(user).get('role')
    });
  }

  /**
   * Gets the player who has the most votes in the voting with the given id.
   * If multiple players have the same number of votes, then one will be picked
   * randomly.
   * Returns null when no one has voted.
   */
  function mostVotes(votingId) {
    var voting = Db.shared.get('votings', votingId);

    // count the votes for each player
    var votes = {};

    // counting the votes
    for (var user in voting) {
      if (voting.hasOwnProperty(user)) {
        var voteFor = '' + voting[user];

        if (votes[voteFor]) { // votes[voteFor] is defined (and atleast 1)
          votes[voteFor]++;
        } else { // not yet defined
          votes[voteFor] = 1;
        }
      }
    }

    // get the max number of votes
    var values = Object.keys(votes).map(function (user) {
      return votes[user];
    });
    var max = Math.max.apply(null, values);

    if (max) { // there has been voted
      // get the users that have the max number of votes
      var maxUsers = Object.keys(voting).filter(function (user) {
        return votes[user] === max;
      });

      // take on randomly from the maxUsers
      var r = Math.floor(Math.random() * maxUsers.length);
      return maxUsers[r];
    } else { // no one has voted
      return null;
    }
  }

  /**
   * Creates a new voting with the given votingId.
   * For this voting there is an entry prepared for users
   */
  function createVoting(votingId, users) {
    users.forEach(function (user) {
      Db.shared.ref('votings').set(votingId, user, 0);
    });
  }

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {
    if (number === 0) { // no voting on day 0
      // TODO: send some message about first day and welcome and stuff
    } else {
      // kill the player voted for by the werewolves
      var target = mostVotes('night' + (number - 1));
      if (target) kill(target);

      // start a new vote
      var votingId = 'day' + number;
      createVoting(votingId, Plugin.userIds());
    }

  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {
    if (number > 0) { // if there was a day before, then finish the lynching
      // kill the player voted for (if there has been voted)
      var target = mostVotes('day' + number);
      if (target) kill(target);
    }

    // start a new vote
    var votingId = 'night' + number;
    var werewolves = usersWithRole(Constants.roles.WEREWOLF);
    createVoting(votingId, werewolves);
  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   */
  function onTimeChanged() {
    // getting the time
    var now = new Date();

    // starting new timer
    var nextChange = time.getNextChange(now);
    var delay = nextChange.getTime() - now.getTime();
    Timer.set(delay, 'onTimeChanged');

    // calling startDay/startNight
    var number = time.getNumber(now);
    if (time.isDay(now)) {
      startDay(number);
    } else {
      startNight(number);
    }
  }

  /**
   * Starts a new game with the given configuration.
   * THis will destroy the current game (if there is any).
   */
  function restart(config) {
    // destroy old game
    Timer.cancel('onTimeChanged');

    // start new game
    var users = Plugin.userIds();

    // saving each player in the players list
    users.forEach(function (user) {
      Db.shared.ref('users').set('' + user, {
        isAlive: true
      });
    });

    // the roles to select
    var selectRoles = {};
    selectRoles[Constants.roles.WEREWOLF] = config.nWerewolf;

    // the roles for the users
    var userRoles = generateRoles(selectRoles, users);

    // save the roles
    users.forEach(function (user) {
      var role = userRoles['' + user];
      Db.personal(user).set('role', role);
    });

    // setting up the time
    var now = Date.now();
    Db.shared.ref('time').set({
      start: now
    });

    // starting the timer and init the game time
    time = GameTime.startingOn(now);
    onTimeChanged();
  }

  /**
   * Handles the installation of the application in a Happening group.
   */
  exports.onInstall = function (config) {
    restart(config);
  };

  /**
   * Updates the settings for this game
   */
  exports.onConfig = function (config) {
    if (config.restart) { // restart the game
      restart(config);
    }
  };

  exports.onTimeChanged = onTimeChanged;

  /* The rpc calls */

  /**
   * Votes at the voting for the given user.
   * @param votingId the id of the voting you want to vote on
   * @param vote the user to vote for
   */
  exports.client_vote = function (votingId, vote) {
    // the user that is trying to vote
    var currentUser = Plugin.userId();

    // verify whether the user is allowed to vote for this
    var voting = Db.shared.ref('votings').get(votingId);
    if (voting.hasOwnProperty(currentUser)) {
      // the current user is allowed to vote

      // and voting!
      Db.shared.ref('votings').set(votingId, currentUser, vote);
    }
  };

}());
<commit_msg>Update voting creation to only allow alive users<commit_after>(function () {
  'use strict';

  // loading dependencies
  var Plugin = require('plugin');
  var Db = require('db');
  var Timer = require('timer');

  var Constants = require('Constants')();
  var GameTime = require('GameTime');

  // variables

  // the current GameTime (is updated on restart)
  var time = GameTime.startingOn(Db.shared.get('time', 'start'));

  /**
   * + Jonas Raoni Soares Silva
   * @ http://jsfromhell.com/array/shuffle [v1.0]
   */
  function shuffle(o){ //v1.0
      for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
      return o;
  }

  /**
   * Creates a mapping of the userids to a role.
   * @param roles an object containing what roles should be added.
   *            each key should represent a role and the value how many of those
   *            roles. (if not enough roles, than we add normal citizens).
   * @param users the id of the users to assign roles to.
   */
  function generateRoles(roles, users) {

    // an array containing all the roles we want to add
    var roleArray = [];
    // index used for looping
    var i;

    // adding all the roles
    for (var role in roles) {
      if (roles.hasOwnProperty(role)) {
        // add the role
        for (i = 0; i < roles[role]; i++) {
          roleArray.push(role);
        }
      }
    }

    // add the missing roles
    for (i = roleArray.length; i < users.length; i++) {
      // add a citizen
      roleArray.push(Constants.roles.CITIZEN);
    }

    // shuffle the array
    shuffle(roleArray);

    // the result object (mapping from user -> role)
    var result = {};
    for (i = 0; i < users.length; i++) {
      result[users[i]] = roleArray[i];
    }

    return result;
  }

  /**
   * Determines whether the given user is alive.
   * This is used in filters to find the correct users
   */
  function isAlive(user) {
    return Db.shared.get('users', user, 'isAlive');
  }

  /**
   * Gets all the users with the given role.
   */
  function usersWithRole(role) {
    var users = Plugin.userIds();
    return users.filter(function (user) {
      return Db.personal(user).get('role') === role;
    });
  }

  /**
   * Kills the given user.
   * The user is no longer alive and his role will be exposed.
   */
  function kill(user) {
    Db.shared.set('users', user, {
      isAlive: false,
      role: Db.personal(user).get('role')
    });
  }

  /**
   * Gets the player who has the most votes in the voting with the given id.
   * If multiple players have the same number of votes, then one will be picked
   * randomly.
   * Returns null when no one has voted.
   */
  function mostVotes(votingId) {
    var voting = Db.shared.get('votings', votingId);

    // count the votes for each player
    var votes = {};

    // counting the votes
    for (var user in voting) {
      if (voting.hasOwnProperty(user)) {
        var voteFor = '' + voting[user];

        if (votes[voteFor]) { // votes[voteFor] is defined (and atleast 1)
          votes[voteFor]++;
        } else { // not yet defined
          votes[voteFor] = 1;
        }
      }
    }

    // get the max number of votes
    var values = Object.keys(votes).map(function (user) {
      return votes[user];
    });
    var max = Math.max.apply(null, values);

    if (max) { // there has been voted
      // get the users that have the max number of votes
      var maxUsers = Object.keys(voting).filter(function (user) {
        return votes[user] === max;
      });

      // take on randomly from the maxUsers
      var r = Math.floor(Math.random() * maxUsers.length);
      return maxUsers[r];
    } else { // no one has voted
      return null;
    }
  }

  /**
   * Creates a new voting with the given votingId.
   * For this voting there is an entry prepared for users
   */
  function createVoting(votingId, users) {
    users.forEach(function (user) {
      Db.shared.ref('votings').set(votingId, user, 0);
    });
  }

  /**
   * Closes the previous night and starts the new day.
   * @param number the current number of the day that just started
   */
  function startDay(number) {
    if (number === 0) { // no voting on day 0
      // TODO: send some message about first day and welcome and stuff
    } else {
      // kill the player voted for by the werewolves
      var target = mostVotes('night' + (number - 1));
      if (target) kill(target);

      // start a new vote
      var votingId = 'day' + number;
      var users = Plugin.userIds().filter(isAlive);
      createVoting(votingId, users);
    }

  }

  /**
   * Closes the day and starts the night.
   * @param number the current number of the day
   */
  function startNight(number) {
    if (number > 0) { // if there was a day before, then finish the lynching
      // kill the player voted for (if there has been voted)
      var target = mostVotes('day' + number);
      if (target) kill(target);
    }

    // start a new vote
    var votingId = 'night' + number;
    var werewolves = usersWithRole(Constants.roles.WEREWOLF);
    createVoting(votingId, werewolves.filter(isAlive));
  }

  /**
   * Will be called when the day changes from night to day.
   * (or when a new game has been started)
   */
  function onTimeChanged() {
    // getting the time
    var now = new Date();

    // starting new timer
    var nextChange = time.getNextChange(now);
    var delay = nextChange.getTime() - now.getTime();
    Timer.set(delay, 'onTimeChanged');

    // calling startDay/startNight
    var number = time.getNumber(now);
    if (time.isDay(now)) {
      startDay(number);
    } else {
      startNight(number);
    }
  }

  /**
   * Starts a new game with the given configuration.
   * THis will destroy the current game (if there is any).
   */
  function restart(config) {
    // destroy old game
    Timer.cancel('onTimeChanged');

    // start new game
    var users = Plugin.userIds();

    // saving each player in the players list
    users.forEach(function (user) {
      Db.shared.ref('users').set('' + user, {
        isAlive: true
      });
    });

    // the roles to select
    var selectRoles = {};
    selectRoles[Constants.roles.WEREWOLF] = config.nWerewolf;

    // the roles for the users
    var userRoles = generateRoles(selectRoles, users);

    // save the roles
    users.forEach(function (user) {
      var role = userRoles['' + user];
      Db.personal(user).set('role', role);
    });

    // setting up the time
    var now = Date.now();
    Db.shared.ref('time').set({
      start: now
    });

    // starting the timer and init the game time
    time = GameTime.startingOn(now);
    onTimeChanged();
  }

  /**
   * Handles the installation of the application in a Happening group.
   */
  exports.onInstall = function (config) {
    restart(config);
  };

  /**
   * Updates the settings for this game
   */
  exports.onConfig = function (config) {
    if (config.restart) { // restart the game
      restart(config);
    }
  };

  exports.onTimeChanged = onTimeChanged;

  /* The rpc calls */

  /**
   * Votes at the voting for the given user.
   * @param votingId the id of the voting you want to vote on
   * @param vote the user to vote for
   */
  exports.client_vote = function (votingId, vote) {
    // the user that is trying to vote
    var currentUser = Plugin.userId();

    // verify whether the user is allowed to vote for this
    var voting = Db.shared.ref('votings').get(votingId);
    if (voting.hasOwnProperty(currentUser)) {
      // the current user is allowed to vote

      // and voting!
      Db.shared.ref('votings').set(votingId, currentUser, vote);
    }
  };

}());
<|endoftext|>


<commit_before>const UrlPathValidator = require('../services/validators/url-path-validator')
const SessionHandler = require('../services/validators/session-handler')
const log = require('../services/log')

module.exports = function (router) {
  router.get('/application-submitted', function (req, res) {
    UrlPathValidator(req.params)
    var decryptedRef = req.session.decryptedRef
    var advanceOrPast = req.session.advanceOrPast
    log.info('ClaimID '+ req.session.claimId + ' Submitted')
    req.session = SessionHandler.clearSession(req.session, req.url)

    return res.render('application-submitted', {
      reference: decryptedRef,
      advanceOrPast: advanceOrPast
    })
  })
}
<commit_msg>Fixed Coding standards tests<commit_after>const UrlPathValidator = require('../services/validators/url-path-validator')
const SessionHandler = require('../services/validators/session-handler')
const log = require('../services/log')

module.exports = function (router) {
  router.get('/application-submitted', function (req, res) {
    UrlPathValidator(req.params)
    var decryptedRef = req.session.decryptedRef
    var advanceOrPast = req.session.advanceOrPast
    log.info('ClaimID ' + req.session.claimId + ' Submitted')
    req.session = SessionHandler.clearSession(req.session, req.url)

    return res.render('application-submitted', {
      reference: decryptedRef,
      advanceOrPast: advanceOrPast
    })
  })
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2010  Seneca College
  MIT LICENSE

  Version:  0.1
  Author:   Andor Salga
            asalga.wordpress.com
  Date:     November 16, 2010

  Notes:
  This parser parses .ASC filetypes. These files are ASCII
  files which have their data stored in one of the following ways:

  X, Y, Z
  X, Y, Z, R, G, B
  X, Y, Z, I, J, K
  X, Y, Z, R, G, B, I, J, K
*/

var ASCParser = (function() {

  /**
    Constructor
  */
  function ASCParser() {

    const UNKNOWN = -1;

    const XHR_DONE = 4;
    const STARTED = 1;

    //
    var events = {
      "onstart": function(){},
      "onparse": function(){},
      "onfinish": function(){}
    };

    var pathToFile = null;
    var fileSize = 0;

    //
    var numParsedPoints = 0;
    var numTotalPoints = 0;
    var progress = 0;

    //
    var numValuesPerLine = -1;
    var normalsPresent = false;
    var colorsPresent = false;
    var layoutCode = UNKNOWN;

    //
    var parsedVerts = [];
    var parsedCols = [];
    var parsedNorms = [];

    // keep track if onprogress event handler was called to
    // handle Chrome/WebKit vs. Minefield differences.
    //
    // Minefield will call onprogress zero or many times
    // Chrome/WebKit will call onprogress one or many times
    var onProgressCalled = false;
    var AJAX = null;

    // WebGL compatibility wrapper
    try{
      Float32Array;
    }catch(ex){
      Float32Array = WebGLFloatArray;
    }

    /**
      @private

      ASC files can either contain
      X, Y, Z
      X, Y, Z, R,  G,  B
      X, Y, Z, NX, NY, NZ
      X, Y, Z, R,  G,  B, NX, NY, NZ

      @returns {Number}
      0 first case
      1 second case
      2 third case
      3 fourth case
    */
    var getDataLayout = function(values){
      var normalsPresent = false;
      var colorsPresent = false;

      var VERTS = 0;
      var VERTS_COLS = 1;
      var VERTS_NORMS = 2;
      var VERTS_COLS_NORMS = 3;

      // first check if there are 9 values, which would mean we have
      // xyz rgb and normals

      // We can do this by counting the number of whitespace on the first line
      var i = 0;
      var numSpaces = 0;
      do{
        i++;
        if(values[i] == " "){
          numSpaces++;
        }
      }while(values[i] != '\n');

      // Vertices, Colors, Normals:
      // 1.916 -2.421 -4.0   64 32 16   -0.3727 -0.2476 -0.8942
      if(numSpaces === 8){
        return VERTS_COLS_NORMS;
      }

      // Just vertices:
      // 1.916 -2.421 -4.0339
      if(numSpaces == 2){
        return VERTS;
      }

      var str = "";

      //
      // !! fix me
      for(i = 0; i < 500; i++){
        str += values[i];
      }

      var str_split = str.split(/\s+/);
      var data = [];

      for(var i = 3; i < str_split.length;){
        data.push(str_split[i++]);
        data.push(str_split[i++]);
        data.push(str_split[i++]);
        i += 3;
      }

      for(var i = 0; i < data.length; i++){
        if(data[i] < 0 || data[i] > 255){
          normalsPresent = true;
          return VERTS_NORMS;
        }
      }

      // Vertices and Normals:
      // 1.916 -2.421 -4.0   -0.3727 -0.2476 -0.8942
      return VERTS_COLS;
    };

    /*
      Returns the version of this parser

      @returns {String} parser version
    */
    this.getVersion = function(){
      return "0.1";
    };

    /**
      "onstart"
      "onparse"
      "onfinish"

      @param {String} eventName
      @param {Function} func
    */
    this.addEventListener = function(eventName, func){
      events[eventName] = func;
    };

    /*
    */
    this.getNumParsedPoints = function(){
      return numParsedPoints;
    };

    /*
    */
    this.getNumTotalPoints = function(){
      return numTotalPoints;
    }

    this.getProgress = function(){
      return progress;
    }

    /*
    */
    this.getFileSize = function(){
      return fileSize;
    };

    /**
      pathToFile
    */
    this.load = function(path){
      pathToFile = path;

      AJAX = new XMLHttpRequest();

      // put a reference to the parser in the AJAX object
      // so we can give the library a reference to the
      // parser within the AJAX event handler scope.
      // !! eventually need to fix this
      AJAX.parser = this;

      /**
        occurs exactly once when the resource begins
        to be downloaded
      */
      AJAX.onloadstart = function(evt){
        events["onstart"](AJAX.parser);
      };

      /*
        occurs exactly once, when the file is done
        being downloaded
      */
      AJAX.onload = function(evt){

        var ascData = AJAX.responseText;
        var chunk = null;

        // if the onprogress event didn't get called--we simply got
        // the file in one go, we can parse from start to finish.
        if(onProgressCalled === false){
          chunk = ascData;
        }
        // otherwise the onprogress event was called at least once,
        // that means we need to get the data from a specific point to the end.
        else if(ascData.length - AJAX.lastNewLineIndex > 1){
          chunk = ascData.substring(AJAX.lastNewLineIndex, ascData.length);
        }

        // if the last chunk doesn't have any digits (just spaces)
        // don't parse it.
        if(chunk && chunk.match(/[0-9]/)){
          AJAX.parseChunk(chunk);
        }

        numTotalPoints = numParsedPoints;

        progress = 1;

        events["onfinish"](AJAX.parser);
      }

      /**
        !! fix me
      */
      AJAX.parseChunk = function(chunkData){
        var chunk = chunkData;

        // !! fix this
        if(layoutCode === UNKNOWN){
          layoutCode = getDataLayout(chunk);
          numValuesPerLine = -1;

          switch(layoutCode){
            case 0: numValuesPerLine = 3;
                    break;
            case 1: numValuesPerLine = 6;
                    colorsPresent = true;
                    break;
            case 2: numValuesPerLine = 6;
                    normalsPresent = true;
                    break;
            case 3: numValuesPerLine = 9;
                    normalsPresent = true;
                    colorsPresent = true;
                    break;
          }
          gotLayout = true;
        }

        // trim trailing spaces
        chunk = chunk.replace(/\s+$/,"");

        // trim leading spaces
        chunk = chunk.replace(/^\s+/,"");

        // split on white space
        chunk = chunk.split(/\s+/);

        var numVerts = chunk.length/numValuesPerLine;
        numParsedPoints += numVerts;

        var verts = new Float32Array(numVerts*3);
        var cols = null;
        var norms = null;

        if(colorsPresent){
          cols = new Float32Array(numVerts*3);
        }

        if(normalsPresent){
          norms = new Float32Array(numVerts*3);
        }

        // depending if there are colors,
        // we'll need to read different indices.
        // if there aren't:
        // x  y  z  r  g  b  nx ny nz
        // 0  1  2  3  4  5  6  7  8 <- normals start at index 6
        //
        // if there are:
        // x  y  z  nx ny nz
        // 0  1  2  3  4  5 <- normals start at index 3
        var valueOffset = 0;
        if(colorsPresent){
          valueOffset = 3;
        }

        // xyz  rgb  normals
        for(var i = 0, j = 0, len = chunk.length; i < len; i += numValuesPerLine, j += 3){
          verts[j]   = parseFloat(chunk[i]);
          verts[j+1] = parseFloat(chunk[i+1]);
          verts[j+2] = parseFloat(chunk[i+2]);

          // XBPS spec for parsers requires colors to be normalized
          if(cols){
            cols[j]   = parseInt(chunk[i+3])/255;
            cols[j+1] = parseInt(chunk[i+4])/255;
            cols[j+2] = parseInt(chunk[i+5])/255;
          }

          if(norms){
            norms[j]   = parseFloat(chunk[i + 3 + valueOffset]);
            norms[j+1] = parseFloat(chunk[i + 4 + valueOffset]);
            norms[j+2] = parseFloat(chunk[i + 5 + valueOffset]);
          }
        }

        // !! pushing on null?
        parsedVerts.push(verts);
        parsedCols.push(cols);
        parsedNorms.push(norms);

        // !! needs test
        // !! needs comment
        var test = {};
        if(verts){test["VERTEX"] = verts;}
        if(cols){test["COLOR"] = cols;}
        if(norms){test["NORMAL"] = norms;}

        events["onparse"](test, AJAX.parser);
      };

      /**
        On Minefield, this will occur zero or many times
        On Chrome/WebKit this will occur one or many times
      */
      AJAX.onprogress = function(evt){

       if(evt.lengthComputable){
          fileSize = evt.total;
          progress = evt.loaded/evt.total;
        }

        onProgressCalled = true;

        // if we have something to actually parse
        if(AJAX.responseText){
          var ascData = AJAX.responseText;

          // we likely stopped getting data somewhere in the middle of
          // a line in the ASC file

          // 5.813 2.352 6.500 0 0 0 2.646 3.577 2.516\n
          // 1.079 1.296 9.360 0 0 0 4.307 1.181 5.208\n
          // 3.163 2.225 6.139 0 0 0 0.6<-- stopped here

          // So find the last known newline. Everything from the last
          // request to this last newline can be placed in a buffer.
          var lastNewLineIndex = ascData.lastIndexOf("\n");
          AJAX.lastNewLineIndex = lastNewLineIndex;

          // if the status just changed and we finished downloading the
          // file, grab everyting until the end. If there is only a bunch
          // of whitespace, make a note of that and don't bother parsing.
          if(AJAX.readyState === XHR_DONE){
            var chunk = ascData.substring(AJAX.startOfNextChunk, ascData.length);
            // If the last chunk doesn't have any digits (just spaces)
            // don't parse it.
            if(chunk.match(/[0-9]/)){
              AJAX.parseChunk(chunk);
            }
          }
          // if we still have more data to go
          else{
            // Start of the next chunk starts after the newline.
            var chunk = ascData.substring(AJAX.startOfNextChunk, lastNewLineIndex + 1);
            AJAX.startOfNextChunk = lastNewLineIndex + 1;
            AJAX.parseChunk(chunk);
          }
        }
      };//onprogress

      // open an asynchronous request to the path
      AJAX.open("GET", path, true);
      AJAX.send(null);
    };// load
  }//ctor
  return ASCParser;
}());
<commit_msg>added empty comments to getProgress<commit_after>/*
  Copyright (c) 2010  Seneca College
  MIT LICENSE

  Version:  0.1
  Author:   Andor Salga
            asalga.wordpress.com
  Date:     November 16, 2010

  Notes:
  This parser parses .ASC filetypes. These files are ASCII
  files which have their data stored in one of the following ways:

  X, Y, Z
  X, Y, Z, R, G, B
  X, Y, Z, I, J, K
  X, Y, Z, R, G, B, I, J, K
*/

var ASCParser = (function() {

  /**
    Constructor
  */
  function ASCParser() {

    const UNKNOWN = -1;

    const XHR_DONE = 4;
    const STARTED = 1;

    //
    var events = {
      "onstart": function(){},
      "onparse": function(){},
      "onfinish": function(){}
    };

    var pathToFile = null;
    var fileSize = 0;

    //
    var numParsedPoints = 0;
    var numTotalPoints = 0;
    var progress = 0;

    //
    var numValuesPerLine = -1;
    var normalsPresent = false;
    var colorsPresent = false;
    var layoutCode = UNKNOWN;

    //
    var parsedVerts = [];
    var parsedCols = [];
    var parsedNorms = [];

    // keep track if onprogress event handler was called to
    // handle Chrome/WebKit vs. Minefield differences.
    //
    // Minefield will call onprogress zero or many times
    // Chrome/WebKit will call onprogress one or many times
    var onProgressCalled = false;
    var AJAX = null;

    // WebGL compatibility wrapper
    try{
      Float32Array;
    }catch(ex){
      Float32Array = WebGLFloatArray;
    }

    /**
      @private

      ASC files can either contain
      X, Y, Z
      X, Y, Z, R,  G,  B
      X, Y, Z, NX, NY, NZ
      X, Y, Z, R,  G,  B, NX, NY, NZ

      @returns {Number}
      0 first case
      1 second case
      2 third case
      3 fourth case
    */
    var getDataLayout = function(values){
      var normalsPresent = false;
      var colorsPresent = false;

      var VERTS = 0;
      var VERTS_COLS = 1;
      var VERTS_NORMS = 2;
      var VERTS_COLS_NORMS = 3;

      // first check if there are 9 values, which would mean we have
      // xyz rgb and normals

      // We can do this by counting the number of whitespace on the first line
      var i = 0;
      var numSpaces = 0;
      do{
        i++;
        if(values[i] == " "){
          numSpaces++;
        }
      }while(values[i] != '\n');

      // Vertices, Colors, Normals:
      // 1.916 -2.421 -4.0   64 32 16   -0.3727 -0.2476 -0.8942
      if(numSpaces === 8){
        return VERTS_COLS_NORMS;
      }

      // Just vertices:
      // 1.916 -2.421 -4.0339
      if(numSpaces == 2){
        return VERTS;
      }

      var str = "";

      //
      // !! fix me
      for(i = 0; i < 500; i++){
        str += values[i];
      }

      var str_split = str.split(/\s+/);
      var data = [];

      for(var i = 3; i < str_split.length;){
        data.push(str_split[i++]);
        data.push(str_split[i++]);
        data.push(str_split[i++]);
        i += 3;
      }

      for(var i = 0; i < data.length; i++){
        if(data[i] < 0 || data[i] > 255){
          normalsPresent = true;
          return VERTS_NORMS;
        }
      }

      // Vertices and Normals:
      // 1.916 -2.421 -4.0   -0.3727 -0.2476 -0.8942
      return VERTS_COLS;
    };

    /*
      Returns the version of this parser

      @returns {String} parser version
    */
    this.getVersion = function(){
      return "0.1";
    };

    /**
      "onstart"
      "onparse"
      "onfinish"

      @param {String} eventName
      @param {Function} func
    */
    this.addEventListener = function(eventName, func){
      events[eventName] = func;
    };

    /*
    */
    this.getNumParsedPoints = function(){
      return numParsedPoints;
    };

    /*
    */
    this.getNumTotalPoints = function(){
      return numTotalPoints;
    }

    /*
    */
    this.getProgress = function(){
      return progress;
    }

    /*
    */
    this.getFileSize = function(){
      return fileSize;
    };

    /**
      pathToFile
    */
    this.load = function(path){
      pathToFile = path;

      AJAX = new XMLHttpRequest();

      // put a reference to the parser in the AJAX object
      // so we can give the library a reference to the
      // parser within the AJAX event handler scope.
      // !! eventually need to fix this
      AJAX.parser = this;

      /**
        occurs exactly once when the resource begins
        to be downloaded
      */
      AJAX.onloadstart = function(evt){
        events["onstart"](AJAX.parser);
      };

      /*
        occurs exactly once, when the file is done
        being downloaded
      */
      AJAX.onload = function(evt){

        var ascData = AJAX.responseText;
        var chunk = null;

        // if the onprogress event didn't get called--we simply got
        // the file in one go, we can parse from start to finish.
        if(onProgressCalled === false){
          chunk = ascData;
        }
        // otherwise the onprogress event was called at least once,
        // that means we need to get the data from a specific point to the end.
        else if(ascData.length - AJAX.lastNewLineIndex > 1){
          chunk = ascData.substring(AJAX.lastNewLineIndex, ascData.length);
        }

        // if the last chunk doesn't have any digits (just spaces)
        // don't parse it.
        if(chunk && chunk.match(/[0-9]/)){
          AJAX.parseChunk(chunk);
        }

        numTotalPoints = numParsedPoints;

        progress = 1;

        events["onfinish"](AJAX.parser);
      }

      /**
        !! fix me
      */
      AJAX.parseChunk = function(chunkData){
        var chunk = chunkData;

        // !! fix this
        if(layoutCode === UNKNOWN){
          layoutCode = getDataLayout(chunk);
          numValuesPerLine = -1;

          switch(layoutCode){
            case 0: numValuesPerLine = 3;
                    break;
            case 1: numValuesPerLine = 6;
                    colorsPresent = true;
                    break;
            case 2: numValuesPerLine = 6;
                    normalsPresent = true;
                    break;
            case 3: numValuesPerLine = 9;
                    normalsPresent = true;
                    colorsPresent = true;
                    break;
          }
          gotLayout = true;
        }

        // trim trailing spaces
        chunk = chunk.replace(/\s+$/,"");

        // trim leading spaces
        chunk = chunk.replace(/^\s+/,"");

        // split on white space
        chunk = chunk.split(/\s+/);

        var numVerts = chunk.length/numValuesPerLine;
        numParsedPoints += numVerts;

        var verts = new Float32Array(numVerts*3);
        var cols = null;
        var norms = null;

        if(colorsPresent){
          cols = new Float32Array(numVerts*3);
        }

        if(normalsPresent){
          norms = new Float32Array(numVerts*3);
        }

        // depending if there are colors,
        // we'll need to read different indices.
        // if there aren't:
        // x  y  z  r  g  b  nx ny nz
        // 0  1  2  3  4  5  6  7  8 <- normals start at index 6
        //
        // if there are:
        // x  y  z  nx ny nz
        // 0  1  2  3  4  5 <- normals start at index 3
        var valueOffset = 0;
        if(colorsPresent){
          valueOffset = 3;
        }

        // xyz  rgb  normals
        for(var i = 0, j = 0, len = chunk.length; i < len; i += numValuesPerLine, j += 3){
          verts[j]   = parseFloat(chunk[i]);
          verts[j+1] = parseFloat(chunk[i+1]);
          verts[j+2] = parseFloat(chunk[i+2]);

          // XBPS spec for parsers requires colors to be normalized
          if(cols){
            cols[j]   = parseInt(chunk[i+3])/255;
            cols[j+1] = parseInt(chunk[i+4])/255;
            cols[j+2] = parseInt(chunk[i+5])/255;
          }

          if(norms){
            norms[j]   = parseFloat(chunk[i + 3 + valueOffset]);
            norms[j+1] = parseFloat(chunk[i + 4 + valueOffset]);
            norms[j+2] = parseFloat(chunk[i + 5 + valueOffset]);
          }
        }

        // !! pushing on null?
        parsedVerts.push(verts);
        parsedCols.push(cols);
        parsedNorms.push(norms);

        // !! needs test
        // !! needs comment
        var test = {};
        if(verts){test["VERTEX"] = verts;}
        if(cols){test["COLOR"] = cols;}
        if(norms){test["NORMAL"] = norms;}

        events["onparse"](test, AJAX.parser);
      };

      /**
        On Minefield, this will occur zero or many times
        On Chrome/WebKit this will occur one or many times
      */
      AJAX.onprogress = function(evt){

       if(evt.lengthComputable){
          fileSize = evt.total;
          progress = evt.loaded/evt.total;
        }

        onProgressCalled = true;

        // if we have something to actually parse
        if(AJAX.responseText){
          var ascData = AJAX.responseText;

          // we likely stopped getting data somewhere in the middle of
          // a line in the ASC file

          // 5.813 2.352 6.500 0 0 0 2.646 3.577 2.516\n
          // 1.079 1.296 9.360 0 0 0 4.307 1.181 5.208\n
          // 3.163 2.225 6.139 0 0 0 0.6<-- stopped here

          // So find the last known newline. Everything from the last
          // request to this last newline can be placed in a buffer.
          var lastNewLineIndex = ascData.lastIndexOf("\n");
          AJAX.lastNewLineIndex = lastNewLineIndex;

          // if the status just changed and we finished downloading the
          // file, grab everyting until the end. If there is only a bunch
          // of whitespace, make a note of that and don't bother parsing.
          if(AJAX.readyState === XHR_DONE){
            var chunk = ascData.substring(AJAX.startOfNextChunk, ascData.length);
            // If the last chunk doesn't have any digits (just spaces)
            // don't parse it.
            if(chunk.match(/[0-9]/)){
              AJAX.parseChunk(chunk);
            }
          }
          // if we still have more data to go
          else{
            // Start of the next chunk starts after the newline.
            var chunk = ascData.substring(AJAX.startOfNextChunk, lastNewLineIndex + 1);
            AJAX.startOfNextChunk = lastNewLineIndex + 1;
            AJAX.parseChunk(chunk);
          }
        }
      };//onprogress

      // open an asynchronous request to the path
      AJAX.open("GET", path, true);
      AJAX.send(null);
    };// load
  }//ctor
  return ASCParser;
}());
<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    app = express(),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    github = require('./github'),
    Org = require('./models/orgs'),
    Repo = require('./models/repo'),
    Contrib = require('./models/contrib');

mongoose.connect('mongodb://localhost/dat-ass');

app.use(bodyParser.json());

app.use(bodyParser.json({ type: 'application/vnd.api+json'}));

app.use(bodyParser.urlencoded({extended: true}));

app.use(methodOverride('X-HTTP-Method-Override'));
var CORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if ('OPTIONS' === req.method) {
  res.send(200);
}
else {
  next();
}
};
app.use(CORS);

app.get('/', function (req, res) {
    res.send('Check out Dat Ass!!!');
});

app.get('/joi', function (req, res) {
    // Org.find({"name": "hapijs"}, function (err, orgs) {
    //   var contributors = orgs[0].repos[0].contributors;
    //   contributors.forEach(function (user) {
    //     // do stuff with the user
    //     console.log(contributors[0])
    //   });
    // });
    github.importRepository('expressjs', 'session').spread((repository, repositoryStats) => {
        var organization = new Org({
          name: 'expressjs',
          repos: []
        });
        var repository = new Repo({
          name: 'session',
          contributors: []
        });
        repositoryStats.forEach(function (stat) {
            var contributor = new Contrib({
              name: stat.author.login,
              totalCommits: stat.total,
              contributions: stat.weeks
            });
            return repository.contributors.push(contributor);
        });
        Org.find({"name": organization.name}, function(err, org) {
          if (err) return handleError(err);
          if (org) {
            return;
          }
        })
        organization.repos.push(repository);
        organization.save(function (err) {
          if (err) return handleError(err);

          res.status(200).send(organization);
        });
    });
});

app.get('/octocard/:username', function (req, res) {
    var contributor = [];
    Org.find(function (err, orgs) {
      if (err) return handleError(err);
      orgs.forEach(function (organization) {
        organization.repos.forEach(function (repo) {
          repo.contributors.forEach(function (user) {
            var username = user.name.toLowerCase();
            var paramsUser = req.params.username.toLowerCase()
            if (username === paramsUser) {
              return contributor.push({
                org: organization.name,
                repo: repo.name,
                contributions: user.contributions,
                totalCommits: user.totalCommits
              })
            }
          });
        });
      });

      return res.status(200).json(contributor);
    });
})

// seeding db
// github.importRepository('hapijs', 'joi').spread((repository, repositoryStats) => {
//     var organization = new Org({
//       name: 'hapijs',
//       repos: []
//     });
//     var repository = new Repo({
//       name: 'joi',
//       contributors: []
//     });
//     repositoryStats.forEach(function (stat) {
//         var contributor = new Contrib({
//           name: stat.author.login,
//           totalCommits: stat.total,
//           contributions: stat.weeks
//         });
//         return repository.contributors.push(contributor);
//     });
//     organization.repos.push(repository);
//     organization.save(function (err) {
//       if (err) return handleError(err);
//
//       res.status(200).send(organization);
//     });
// });

app.listen('8081');
exports.module = app;
<commit_msg>simple get<commit_after>'use strict';

var express = require('express'),
    app = express(),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    github = require('./github'),
    Org = require('./models/orgs'),
    Repo = require('./models/repo'),
    Contrib = require('./models/contrib');

mongoose.connect('mongodb://localhost/dat-ass');

app.use(bodyParser.json());

app.use(bodyParser.json({ type: 'application/vnd.api+json'}));

app.use(bodyParser.urlencoded({extended: true}));

app.use(methodOverride('X-HTTP-Method-Override'));
var CORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if ('OPTIONS' === req.method) {
  res.send(200);
}
else {
  next();
}
};
app.use(CORS);

app.get('/', function (req, res) {
    res.send('Check out Dat Ass!!!');
});

app.get('/joi', function (req, res) {
    Org.find({"name": "hapijs"}, function (err, orgs) {
      var contributors = orgs[0].repos[0].contributors;
      contributors.forEach(function (user) {
        // do stuff with the user
        console.log(contributors[0])
      });
    });
});

app.get('/octocard/:username', function (req, res) {
    var contributor = [];
    Org.find(function (err, orgs) {
      if (err) return handleError(err);
      orgs.forEach(function (organization) {
        organization.repos.forEach(function (repo) {
          repo.contributors.forEach(function (user) {
            var username = user.name.toLowerCase();
            var paramsUser = req.params.username.toLowerCase()
            if (username === paramsUser) {
              return contributor.push({
                org: organization.name,
                repo: repo.name,
                contributions: user.contributions,
                totalCommits: user.totalCommits
              })
            }
          });
        });
      });

      return res.status(200).json(contributor);
    });
})

// seeding db
// github.importRepository('hapijs', 'joi').spread((repository, repositoryStats) => {
//     var organization = new Org({
//       name: 'hapijs',
//       repos: []
//     });
//     var repository = new Repo({
//       name: 'joi',
//       contributors: []
//     });
//     repositoryStats.forEach(function (stat) {
//         var contributor = new Contrib({
//           name: stat.author.login,
//           totalCommits: stat.total,
//           contributions: stat.weeks
//         });
//         return repository.contributors.push(contributor);
//     });
//     organization.repos.push(repository);
//     organization.save(function (err) {
//       if (err) return handleError(err);
//
//       res.status(200).send(organization);
//     });
// });

app.listen('8081');
exports.module = app;
<|endoftext|>