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

    var optimist = require('optimist')
        .usage('Build the fora project.\nUsage: $0')
        .alias('h', 'help')
        .describe('client', "Build the client")
        .describe('server', "Build the server")
        .describe('host', "Run server on this host")
        .describe('port', "Run server on this port")
        .describe('no-monitor', "Do not start the server or monitor files after building")
        .describe('no-run', "Do not start the server after building")
        .describe('threads', "Number of threads to use for the build (default: 8)")
        .describe('debug', 'Start debugger for server')
        .describe('debug-brk', 'Start debugger for api with breakpoint')
        .describe('debug-build', 'Debug the build process itself')
        .describe('debug-client', 'Do not minify JS files sent to browser')
        .describe('show-errors', 'Display errors in the console')
        .describe('args-some-param', 'Pass some-param to web and api processes')
        .describe('use-es6', 'Use es6 generators in browser (skips transpiler)')
        .describe('help', 'Print this help screen');

    var argv = optimist.argv;
    if (argv.help || argv.h) {
        optimist.showHelp();
        process.exit(0);
    }

    GLOBAL.CRANKSHAFT_DEBUG_MODE = argv['debug-build'];

    var start = Date.now();

    var crankshaft = require('crankshaft');
    var tools = require('crankshaft-tools');

    var spawn = tools.process.spawn();
    var exec = tools.process.exec({ log: console.log });

    /* Create the build */
    var threads = argv.threads ? parseInt(argv.threads) : 8;
    var build = crankshaft.create({ threads: threads });

    /* The three configs */
    var serverConfig = require('./server/build-config')(tools);
    var clientConfig = require('./www-client/build-config')(tools);

    /* Set build parameters */
    build.state.monitor = true;
    build.state.run = true;
    if (argv.monitor === false) {
        build.state.monitor = false;
        build.state.run = false;
    }
    if (argv.run === false) {
        build.state.run = false;
    }

    var host = argv.host || "localhost";
    var port = argv.port || "10981";

    if (argv.client || argv.server) {
        build.state.buildClient = argv.client;
        build.state.buildServer = argv.server;
    } else {
        build.state.buildClient = true;
        build.state.buildServer = true;
    }

    if (argv.debug || argv['debug-brk']) build.state.debugServer = true;
    if (argv['debug-client']) build.state.debugClient = true;
    if (argv['use-es6']) build.state.useES6 = true;

    /* Create configuration */
    if (build.state.buildServer)
        var server = build.configure(serverConfig, 'server');
    if (build.state.buildClient)
        var client = build.configure(clientConfig, 'www-client');

    build.job(function*() {
        if (this.state.run) {
            var params = ["server/runscript.sh"];
            params.push('--harmony');
            if (argv.debug)
                params.push('--debug');
            if (argv['debug-brk'])
                params.push('--debug-brk');
            params = params.concat(['app/app.js', host, port, 'fora_app']);
            params = params.concat(process.argv.filter(function(p) { return ['--debug', '--debug-brk'].indexOf(p) === -1 ; }));

            console.log("Killing existing instances...");
            require("child_process").execSync("kill $(ps ax | grep fora_app | awk '{print $1}') 2>/dev/null");
            console.log("Restarting the server...");

            var script = spawn("sh", params);
        }
    }, "restart_server");

    /* After all configs are built */
    build.onComplete(function*() {
        this.state.complete = true;

        var elapsed = Date.now() - start;

        if (this.state.buildServer) {
            var serverTime = (server.state.end - server.state.start)/1000;
            console.log("Build(server): " + serverTime + "s");
        }

        if (this.state.buildClient) {
            var clientTime = (client.state.end - client.state.start)/1000;
            console.log("Build(client): " + clientTime + "s");
        }

        console.log("Build(total): " + (elapsed/1000) + "s");
    });

    /* Monitor? */
    if (build.state.monitor) {
        build.onComplete(function*() {
            if (build.state.run)
                this.queue("restart_server");
        });
    }

    /* Start */
    try {
        build.start(build.state.monitor);
    } catch(e) {
        console.log(e.stack);
        if (e._inner) console.log(e._inner.stack);
    }
})();
<commit_msg>Use crankshaft.run to start the build<commit_after>(function() {
    "use strict";

    var optimist = require('optimist')
        .usage('Build the fora project.\nUsage: $0')
        .alias('h', 'help')
        .describe('client', "Build the client")
        .describe('server', "Build the server")
        .describe('host', "Run server on this host")
        .describe('port', "Run server on this port")
        .describe('no-monitor', "Do not start the server or monitor files after building")
        .describe('no-run', "Do not start the server after building")
        .describe('threads', "Number of threads to use for the build (default: 8)")
        .describe('debug', 'Start debugger for server')
        .describe('debug-brk', 'Start debugger for api with breakpoint')
        .describe('debug-build', 'Debug the build process itself')
        .describe('debug-client', 'Do not minify JS files sent to browser')
        .describe('show-errors', 'Display errors in the console')
        .describe('args-some-param', 'Pass some-param to web and api processes')
        .describe('use-es6', 'Use es6 generators in browser (skips transpiler)')
        .describe('help', 'Print this help screen');

    var argv = optimist.argv;
    if (argv.help || argv.h) {
        optimist.showHelp();
        process.exit(0);
    }

    GLOBAL.CRANKSHAFT_DEBUG_MODE = argv['debug-build'];

    var start = Date.now();

    var crankshaft = require('crankshaft');
    var tools = require('crankshaft-tools');

    var spawn = tools.process.spawn();
    var exec = tools.process.exec({ log: console.log });

    /* Create the build */
    var threads = argv.threads ? parseInt(argv.threads) : 8;
    var build = crankshaft.create({ threads: threads });

    /* The three configs */
    var serverConfig = require('./server/build-config')(tools);
    var clientConfig = require('./www-client/build-config')(tools);

    /* Set build parameters */
    build.state.monitor = true;
    build.state.run = true;
    if (argv.monitor === false) {
        build.state.monitor = false;
        build.state.run = false;
    }
    if (argv.run === false) {
        build.state.run = false;
    }

    var host = argv.host || "localhost";
    var port = argv.port || "10981";

    if (argv.client || argv.server) {
        build.state.buildClient = argv.client;
        build.state.buildServer = argv.server;
    } else {
        build.state.buildClient = true;
        build.state.buildServer = true;
    }

    if (argv.debug || argv['debug-brk']) build.state.debugServer = true;
    if (argv['debug-client']) build.state.debugClient = true;
    if (argv['use-es6']) build.state.useES6 = true;

    /* Create configuration */
    if (build.state.buildServer)
        var server = build.configure(serverConfig, 'server');
    if (build.state.buildClient)
        var client = build.configure(clientConfig, 'www-client');

    build.job(function*() {
        if (this.state.run) {
            var params = ["server/runscript.sh"];
            params.push('--harmony');
            if (argv.debug)
                params.push('--debug');
            if (argv['debug-brk'])
                params.push('--debug-brk');
            params = params.concat(['app/app.js', host, port, 'fora_app']);
            params = params.concat(process.argv.filter(function(p) { return ['--debug', '--debug-brk'].indexOf(p) === -1 ; }));

            console.log("Killing existing instances...");
            require("child_process").execSync("kill $(ps ax | grep fora_app | awk '{print $1}') 2>/dev/null");
            console.log("Restarting the server...");

            var script = spawn("sh", params);
        }
    }, "restart_server");

    /* After all configs are built */
    build.onComplete(function*() {
        this.state.complete = true;

        var elapsed = Date.now() - start;

        if (this.state.buildServer) {
            var serverTime = (server.state.end - server.state.start)/1000;
            console.log("Build(server): " + serverTime + "s");
        }

        if (this.state.buildClient) {
            var clientTime = (client.state.end - client.state.start)/1000;
            console.log("Build(client): " + clientTime + "s");
        }

        console.log("Build(total): " + (elapsed/1000) + "s");
    });

    /* Monitor? */
    if (build.state.monitor) {
        build.onComplete(function*() {
            if (build.state.run)
                this.queue("restart_server");
        });
    }

    /* Start */
    try {
        crankshaft.run(build, build.state.monitor);
    } catch(e) {
        console.log(e.stack);
        if (e._inner) console.log(e._inner.stack);
    }
})();
<|endoftext|>


<commit_before>
    // Replace this line with the one on your Quickstart Guide Page
    Parse.initialize("nQkZtiTz13AY5YBulsOWNdmupWpl1JLrnykc4dYW", "jRGFMGaqXwvo1rHBxRAQARDVgJTDU0RCkd2u7XtS");

   var Blog = Parse.Object.extend("Blog");
   var Blogs = Parse.Object.extend({
       model: "Blog"});

var blogs = new Blogs();
blogs.fetch({
    success: function(blogs) {
        console.log(blogs);
    },
    error: function(blogs, error) {
        console.log(error);
    }
});

<commit_msg>Update blog.js<commit_after>$(function() {

    Parse.$ = jQuery;

    // Replace this line with the one on your Quickstart Guide Page
    Parse.initialize("nQkZtiTz13AY5YBulsOWNdmupWpl1JLrnykc4dYW", "jRGFMGaqXwvo1rHBxRAQARDVgJTDU0RCkd2u7XtS");

   var Blog = Parse.Object.extend("Blog");
   var blogs = Parse.Object.extend({
       model: kakigajet});

var blogs = new Blogs();
blogs.fetch({
    success: function(blogs) {
        console.log(blogs);
    },
    error: function(blogs, error) {
        console.log(error);
    }
});

});
<|endoftext|>


<commit_before>FRTool.initFR(FRData);

function getImgUrl(dragonID) {
    var dragonID = parseInt(dragonID);
    var miniDragonId = Math.ceil(dragonID / 100);
    return 'http://flightrising.com/rendern/350/' + miniDragonId + '/' + dragonID + '_350.png'
}

function initGeneSelect(id, type) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var genes = FRTool.getGene(FRTool.Oddss[i], type);
    var group = $("<optgroup></optgroup>").attr("label", FRTool.Oddss[i].NameZH + " " + FRTool.Oddss[i].Name);
    for (var j = 0; j < genes.length; j++) {
      group.append($("<option></option>").attr("value", genes[j].Name).text(genes[j].NameZH + " " + genes[j].Name));
    };
    $('#' + id).append(group);
  };
}

function initColorSelect(id) {
  for (var i = 0; i < FRTool.Colors.length; i++) {
    $('#' + id).append(
      $("<option></option>")
      .attr("class", FRTool.Colors[i].Name)
      .attr("value", FRTool.Colors[i].Name)
      .text(FRTool.Colors[i].NameZH + " " + FRTool.Colors[i].Name)
    );
  }
}

function initBreedSelect(id) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var breeds = FRTool.getBreed(FRTool.Oddss[i]);
    var group = $("<optgroup></optgroup>").attr("label", FRTool.Oddss[i].NameZH + " " + FRTool.Oddss[i].Name);
    for (var j = 0; j < breeds.length; j++) {
      group.append($("<option></option>").attr("value", breeds[j].Name).text(breeds[j].NameZH + " " + breeds[j].Name));
    };
    $('#' + id).append(group);
  };
}

function UpdateColorClass(colorSelect) {
  colorSelect.removeClass();
  colorSelect.addClass("form-control");
  colorSelect.addClass(colorSelect.val());
}

function drawCard(canvasId, cardData) {
    var canvas = document.getElementById(canvasId);
    canvas.setAttribute('width', '640');
    canvas.setAttribute('height', '240');
    var canvasContext = canvas.getContext("2d");
    canvasContext.clearRect(0, 0, 640, 240);

    var gene_color_left = cardData.geneColor.left;
    var gene_color_right = cardData.geneColor.right;
    var gene_color = cardData.geneColor.basic;
    var line_color = cardData.lineColor;

    // background
    canvasContext.fillStyle = cardData.background;
    canvasContext.fillRect(0, 0, 640, 240);

    // breed
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.breed == cardData.dragon2.breed) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.breed.Name, 320, 31);
            canvasContext.fillRect(280, 35, 80, 3);
        } else {
            var rate = FRTool.getBreedRate(cardData.dragon1.breed, cardData.dragon2.breed);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.breed.Name, 314, 31);
            canvasContext.fillRect(239, 35, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.breed.Name, 326, 31);
            canvasContext.fillRect(241 + 160 * rate[0], 35, 160 * rate[1], 3);
        }
    }

    // primary gene
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.primarygene == cardData.dragon2.primarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.primarygene.Name, 320, 66);
            canvasContext.fillRect(280, 70, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.primarygene, cardData.dragon2.primarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.primarygene.Name, 314, 66);
            canvasContext.fillRect(239, 70, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.primarygene.Name, 326, 66);
            canvasContext.fillRect(241 + 160 * rate[0], 70, 160 * rate[1], 3);
        }
    }

    // primary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.primarycolor, cardData.dragon2.primarycolor);
        var single = 10;
        var width;
        do{
            single -=1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 80, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 80, single, 20);
            startX += single + 1;
        }
    }

    // secondary gene
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.secondarygene == cardData.dragon2.secondarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.secondarygene.Name, 320, 128);
            canvasContext.fillRect(280, 132, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.secondarygene, cardData.dragon2.secondarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.secondarygene.Name, 314, 128);
            canvasContext.fillRect(239, 132, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.secondarygene.Name, 326, 128);
            canvasContext.fillRect(241 + 160 * rate[0], 132, 160 * rate[1], 3);
        }
    }

    // secondary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.secondarycolor, cardData.dragon2.secondarycolor);
        var single = 10;
        var width;
        do{
            single -=1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 142, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 142, single, 20);
            startX += single + 1;
        }
    }

    // tertiary gene
    {
        canvasContext.font = "14pt cursive";
        if (cardData.dragon1.tertiarygene == cardData.dragon2.tertiarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.tertiarygene.Name, 320, 190);
            canvasContext.fillRect(280, 194, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.tertiarygene, cardData.dragon2.tertiarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.tertiarygene.Name, 314, 190);
            canvasContext.fillRect(239, 194, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.tertiarygene.Name, 326, 190);
            canvasContext.fillRect(241 + 160 * rate[0], 194, 160 * rate[1], 3);
        }
    }

    // tertiary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.tertiarycolor, cardData.dragon2.tertiarycolor);
        var single = 10;
        var width;
        do{
            single -= 1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 204, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 204, single, 20);
            startX += single + 1;
        }
    }

    // image 1
    {
        var img1 = new Image();
        img1.src = getImgUrl(cardData.dragon1.id);
        img1.crossOrigin = "Anonymous";
        img1.onload = function() {
            canvasContext.drawImage(img1, 0, 0, 240, 240);
            if (cardData.dragonName.enable) {
                canvasContext.font = cardData.dragonName.font;
                canvasContext.textAlign = "start";
                canvasContext.fillStyle = cardData.dragonName.shadowcolor;
                canvasContext.fillText(cardData.dragon1.name, 21, 201);
                canvasContext.fillText(cardData.dragon1.name, 19, 199);
                canvasContext.fillStyle = cardData.dragonName.color;
                canvasContext.fillText(cardData.dragon1.name, 20, 200);
            }
        }
    }

    // image 2
    {
        var img2 = new Image();
        img2.src = getImgUrl(cardData.dragon2.id);
        img2.crossOrigin = "Anonymous";
        img2.onload = function() {
            canvasContext.drawImage(img2, 400, 0, 240, 240);
            if (cardData.dragonName.enable) {
                canvasContext.font = cardData.dragonName.font;
                canvasContext.textAlign = "end";
                canvasContext.fillStyle = cardData.dragonName.shadowcolor;
                canvasContext.fillText(cardData.dragon2.name, 621, 201);
                canvasContext.fillText(cardData.dragon2.name, 619, 199);
                canvasContext.fillStyle = cardData.dragonName.color;
                canvasContext.fillText(cardData.dragon2.name, 620, 200);
            }
        }
    }

    return canvas;
}
initBreedSelect('o_breed');
initBreedSelect('a_breed');

initGeneSelect('o_Primary_gene', 'Primary');
initGeneSelect('a_Primary_gene', 'Primary');
initGeneSelect('o_Secondary_gene', 'Secondary');
initGeneSelect('a_Secondary_gene', 'Secondary');
initGeneSelect('o_Tertiary_gene', 'Tertiary');
initGeneSelect('a_Tertiary_gene', 'Tertiary');

initColorSelect('o_primary_color');
initColorSelect('o_secondary_color');
initColorSelect('o_tertiary_color');
initColorSelect('a_primary_color');
initColorSelect('a_secondary_color');
initColorSelect('a_tertiary_color');

$("[id=draw]").click(function(){
    var card_data = {
        'dragon1': {
            'id':$('#o_id').val(),
            'name':$('#o_name').val(),
            'breed':FRTool.Breed[$('#o_breed').val()],
            'primarygene':FRTool.PrimaryGene[$('#o_Primary_gene').val()],
            'secondarygene':FRTool.SecondaryGene[$('#o_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#o_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#o_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#o_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#o_tertiary_color').val()]
        },
        'dragon2': {
            'id':$('#a_id').val(),
            'name':$('#a_name').val(),
            'breed':FRTool.Breed[$('#a_breed').val()],
            'primarygene':FRTool.PrimaryGene[$('#a_Primary_gene').val()],
            'secondarygene':FRTool.SecondaryGene[$('#a_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#a_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#a_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#a_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#a_tertiary_color').val()]
        },
        'dragonName' : {
            'enable': true,
            'font' : $('#name_font').val(),
            'color' : $('#name_color').val(),
            'shadowcolor' : $('#name_color_shadow').val()
        },
        'geneColor' : {
            'left':$('#gene_color_left').val(),
            'right':$('#gene_color_right').val(),
            'basic':$('#gene_color').val()
        },
        'geneFont' : $('#gene_font').val(),
        'lineColor' : $('#line_color').val(),
        'background' : $('#background').val()
    }
    drawCard('canvas_1', card_data);
});

$("[id$=_color]").change(function() {
  UpdateColorClass($(this));
});

$('[data-toggle="tooltip"]').tooltip();
$("[id$=_color]").change();
<commit_msg>Update card.js<commit_after>FRTool.initFR(FRData);

function getImgUrl(dragonID) {
    var dragonID = parseInt(dragonID);
    var miniDragonId = Math.ceil(dragonID / 100);
    return 'http://flightrising.com/rendern/350/' + miniDragonId + '/' + dragonID + '_350.png'
}

function initGeneSelect(id, type) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var genes = FRTool.getGene(FRTool.Oddss[i], type);
    var group = $("<optgroup></optgroup>").attr("label", FRTool.Oddss[i].NameZH + " " + FRTool.Oddss[i].Name);
    for (var j = 0; j < genes.length; j++) {
      group.append($("<option></option>").attr("value", genes[j].Name).text(genes[j].NameZH + " " + genes[j].Name));
    };
    $('#' + id).append(group);
  };
}

function initColorSelect(id) {
  for (var i = 0; i < FRTool.Colors.length; i++) {
    $('#' + id).append(
      $("<option></option>")
      .attr("class", FRTool.Colors[i].Name)
      .attr("value", FRTool.Colors[i].Name)
      .text(FRTool.Colors[i].NameZH + " " + FRTool.Colors[i].Name)
    );
  }
}

function initBreedSelect(id) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var breeds = FRTool.getBreed(FRTool.Oddss[i]);
    var group = $("<optgroup></optgroup>").attr("label", FRTool.Oddss[i].NameZH + " " + FRTool.Oddss[i].Name);
    for (var j = 0; j < breeds.length; j++) {
      group.append($("<option></option>").attr("value", breeds[j].Name).text(breeds[j].NameZH + " " + breeds[j].Name));
    };
    $('#' + id).append(group);
  };
}

function UpdateColorClass(colorSelect) {
  colorSelect.removeClass();
  colorSelect.addClass("form-control");
  colorSelect.addClass(colorSelect.val());
}

function drawCard(canvasId, cardData) {
    var canvas = document.getElementById(canvasId);
    canvas.setAttribute('width', '640');
    canvas.setAttribute('height', '240');
    var canvasContext = canvas.getContext("2d");
    canvasContext.clearRect(0, 0, 640, 240);

    var gene_color_left = cardData.geneColor.left;
    var gene_color_right = cardData.geneColor.right;
    var gene_color = cardData.geneColor.basic;
    var line_color = cardData.lineColor;

    // background
    canvasContext.fillStyle = cardData.background;
    canvasContext.fillRect(0, 0, 640, 240);

    // breed
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.breed == cardData.dragon2.breed) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.breed.Name, 320, 31);
            canvasContext.fillRect(280, 35, 80, 3);
        } else {
            var rate = FRTool.getBreedRate(cardData.dragon1.breed, cardData.dragon2.breed);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.breed.Name, 314, 31);
            canvasContext.fillRect(239, 35, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.breed.Name, 326, 31);
            canvasContext.fillRect(241 + 160 * rate[0], 35, 160 * rate[1], 3);
        }
    }

    // primary gene
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.primarygene == cardData.dragon2.primarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.primarygene.Name, 320, 66);
            canvasContext.fillRect(280, 70, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.primarygene, cardData.dragon2.primarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.primarygene.Name, 314, 66);
            canvasContext.fillRect(239, 70, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.primarygene.Name, 326, 66);
            canvasContext.fillRect(241 + 160 * rate[0], 70, 160 * rate[1], 3);
        }
    }

    // primary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.primarycolor, cardData.dragon2.primarycolor);
        var single = 10;
        var width;
        do{
            single -=1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 80, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 80, single, 20);
            startX += single + 1;
        }
    }

    // secondary gene
    {
        canvasContext.font = cardData.geneFont;
        if (cardData.dragon1.secondarygene == cardData.dragon2.secondarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.secondarygene.Name, 320, 128);
            canvasContext.fillRect(280, 132, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.secondarygene, cardData.dragon2.secondarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.secondarygene.Name, 314, 128);
            canvasContext.fillRect(239, 132, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.secondarygene.Name, 326, 128);
            canvasContext.fillRect(241 + 160 * rate[0], 132, 160 * rate[1], 3);
        }
    }

    // secondary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.secondarycolor, cardData.dragon2.secondarycolor);
        var single = 10;
        var width;
        do{
            single -=1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 142, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 142, single, 20);
            startX += single + 1;
        }
    }

    // tertiary gene
    {
        canvasContext.font = "14pt cursive";
        if (cardData.dragon1.tertiarygene == cardData.dragon2.tertiarygene) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = cardData.geneColor.basic;
            canvasContext.fillText(cardData.dragon1.tertiarygene.Name, 320, 190);
            canvasContext.fillRect(280, 194, 80, 3);
        } else {
            var rate = FRTool.getGeneRate(cardData.dragon1.tertiarygene, cardData.dragon2.tertiarygene);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = gene_color_left;
            canvasContext.fillText(cardData.dragon1.tertiarygene.Name, 314, 190);
            canvasContext.fillRect(239, 194, 160 * rate[0], 3);

            canvasContext.textAlign = "start";
            canvasContext.fillStyle = gene_color_right;
            canvasContext.fillText(cardData.dragon2.tertiarygene.Name, 326, 190);
            canvasContext.fillRect(241 + 160 * rate[0], 194, 160 * rate[1], 3);
        }
    }

    // tertiary color
    {
        var range = FRTool.getColorRange(cardData.dragon1.tertiarycolor, cardData.dragon2.tertiarycolor);
        var single = 10;
        var width;
        do{
            single -= 1 ;
            width = range.length * (single + 1);
        } while (width > 200);
        var startX = 320 - width / 2;
        for (var i = 0; i < range.length; i++) {
            canvasContext.beginPath();
            canvasContext.lineWidth = "2";
            canvasContext.strokeStyle = line_color;
            canvasContext.rect(startX, 204, single, 20);
            canvasContext.stroke();

            canvasContext.fillStyle = range[i].Color;
            canvasContext.fillRect(startX, 204, single, 20);
            startX += single + 1;
        }
    }

    // image 1
    {
        var img1 = new Image();
        img1.src = getImgUrl(cardData.dragon1.id);
        img1.onload = function() {
            canvasContext.drawImage(img1, 0, 0, 240, 240);
            if (cardData.dragonName.enable) {
                canvasContext.font = cardData.dragonName.font;
                canvasContext.textAlign = "start";
                canvasContext.fillStyle = cardData.dragonName.shadowcolor;
                canvasContext.fillText(cardData.dragon1.name, 21, 201);
                canvasContext.fillText(cardData.dragon1.name, 19, 199);
                canvasContext.fillStyle = cardData.dragonName.color;
                canvasContext.fillText(cardData.dragon1.name, 20, 200);
            }
        }
    }

    // image 2
    {
        var img2 = new Image();
        img2.src = getImgUrl(cardData.dragon2.id);
        img2.onload = function() {
            canvasContext.drawImage(img2, 400, 0, 240, 240);
            if (cardData.dragonName.enable) {
                canvasContext.font = cardData.dragonName.font;
                canvasContext.textAlign = "end";
                canvasContext.fillStyle = cardData.dragonName.shadowcolor;
                canvasContext.fillText(cardData.dragon2.name, 621, 201);
                canvasContext.fillText(cardData.dragon2.name, 619, 199);
                canvasContext.fillStyle = cardData.dragonName.color;
                canvasContext.fillText(cardData.dragon2.name, 620, 200);
            }
        }
    }

    return canvas;
}
initBreedSelect('o_breed');
initBreedSelect('a_breed');

initGeneSelect('o_Primary_gene', 'Primary');
initGeneSelect('a_Primary_gene', 'Primary');
initGeneSelect('o_Secondary_gene', 'Secondary');
initGeneSelect('a_Secondary_gene', 'Secondary');
initGeneSelect('o_Tertiary_gene', 'Tertiary');
initGeneSelect('a_Tertiary_gene', 'Tertiary');

initColorSelect('o_primary_color');
initColorSelect('o_secondary_color');
initColorSelect('o_tertiary_color');
initColorSelect('a_primary_color');
initColorSelect('a_secondary_color');
initColorSelect('a_tertiary_color');

$("[id=draw]").click(function(){
    var card_data = {
        'dragon1': {
            'id':$('#o_id').val(),
            'name':$('#o_name').val(),
            'breed':FRTool.Breed[$('#o_breed').val()],
            'primarygene':FRTool.PrimaryGene[$('#o_Primary_gene').val()],
            'secondarygene':FRTool.SecondaryGene[$('#o_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#o_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#o_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#o_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#o_tertiary_color').val()]
        },
        'dragon2': {
            'id':$('#a_id').val(),
            'name':$('#a_name').val(),
            'breed':FRTool.Breed[$('#a_breed').val()],
            'primarygene':FRTool.PrimaryGene[$('#a_Primary_gene').val()],
            'secondarygene':FRTool.SecondaryGene[$('#a_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#a_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#a_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#a_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#a_tertiary_color').val()]
        },
        'dragonName' : {
            'enable': true,
            'font' : $('#name_font').val(),
            'color' : $('#name_color').val(),
            'shadowcolor' : $('#name_color_shadow').val()
        },
        'geneColor' : {
            'left':$('#gene_color_left').val(),
            'right':$('#gene_color_right').val(),
            'basic':$('#gene_color').val()
        },
        'geneFont' : $('#gene_font').val(),
        'lineColor' : $('#line_color').val(),
        'background' : $('#background').val()
    }
    drawCard('canvas_1', card_data);
});

$("[id$=_color]").change(function() {
  UpdateColorClass($(this));
});

$('[data-toggle="tooltip"]').tooltip();
$("[id$=_color]").change();
<|endoftext|>


<commit_before>/**
 * Created by huiji001 on 2015/9/10.
 */
function copyWiki(){
    this.init();
}

function getFormattedDate() {
    var date = new Date();
    var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return str;
}

copyWiki.prototype ={
    init: function(){
        this._addListener();
        this._addModal();
    },
    _addListener: function(){
        $('#ca-fork a').on('click', $.proxy(this._getFollow, this));
        $('body').on('click','.copy-modal .copy', $.proxy(this._wikiSelect, this));
    },
    _getFollow: function(){
        var user_name = mw.config.get('wgUserName');
        $('.copy-modal').modal();
        if(user_name == null){
            e.preventDefault();
            $('.wiki-copy .dropdown-menu').empty().append('请登录');
            $('.user-login').modal();
        }else {
            $.post(
                mw.util.wikiScript(), {
                    action: 'ajax',
                    rs: 'wfUserSiteFollowsDetailsResponse',
                    rsargs: [user_name, user_name]
                },
                function (data) {
                    var res = $.parseJSON(data);
                    var content = '';
                    if (res.success == true) {
                        if (res.result.length == 0) {
                            content = '您要把这个页面搬运到哪里呢？不妨先关注那个维基吧';
                            $('.copy-modal .modal-body').empty().append(content);
                        }
                        $.each(res.result,
                            function (i, item) {
                                content += '
' + item.val + '
'
                            }
                        );
                        $('.copy-modal .modal-body').empty().append(content);
                    }
                }
            );
        }
    },
    _addModal: function(){
        var modal = '
'+
            '
'+
            '
'+
                '
'+
                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>'+
                    '
把这个页面搬运到哪？
'+
                    '
根据页面历史长短和嵌套的模板数量，搬运会需要相应的等候时间。
'+
                '
'+
                '
'+
                ''+
                '
'+
            '
'+
        '
'+
        '
';
        $("body").append(modal);
    },
    _wikiSelect: function(e){
        e.stopPropagation();
        var targetPrefix = $(e.target).data('src');
        var ajaxurl = 'http://'+$(e.target).data('src')+mw.config.get('wgHuijiSuffix')+'/api.php';
        var redirectUrl = 'http://'+$(e.target).data('src')+mw.config.get('wgHuijiSuffix')+'/wiki/'+mw.config.get('wgPageName');
        $(e.target).append('');
        this.targetPrefix = targetPrefix;
        this.ajaxurl = ajaxurl;
        this.redirectUrl = redirectUrl;
        this._getToken();
    },
    _getToken: function(){
        $.ajax({
            url: this.ajaxurl,
            data: {
                action: 'query',
                meta: 'tokens',
                format: 'json',
                origin:'http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix')
            },
            xhrFields: {
                withCredentials: true
            },
            dataType: 'json',
            type: 'POST',
            context: this,
            success: function( data ){
                var token = data.query.tokens.csrftoken;
                this._queryPage(token);
            },
            error: function( error ){
                console.log( error );
            }
        })
    },
    _queryData: function(){
        var _this = copyWiki.prototype;
        console.log(_this);
//        $.ajax({
//            url:'api.php?action=query&titles=API&export&exportnowrap',
//            title: mw.config.get( "wgPageName" )
//        })
        $.ajax({
            url: mw.util.wikiScript( 'api' ),
            data: {
                format: 'xml',
                action: 'query',
                titles: '首页',
                prop: 'revisions',
                rvprop: 'content'
            },
            type: 'POST',
            success: function( data ) {
                console.log(data);
                this._importData(data);
            },
            error: function( xhr ) {
                alert( 'Error: Request failed.' );
            }
        });
    },
    _copyContent: function(){

    },
    _queryPage: function(token){
        $.ajax({
            url:this.ajaxurl,
            data:{
                action: 'query',
                titles: mw.config.get('wgPageName'),
                format: 'json',
                origin:'http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix')
            },
            xhrFields: {
                withCredentials: true
            },
            type: 'post',
            success: $.proxy(function(data){

                for (var key in data.query.pages){
                    if (key < 0){
                        this._importWiki(token);
                    }else{

                        var warn = '
' +
                            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>' +
                            '
页面已存在!
' +
                            '
点击覆盖，将覆盖您维基已有的同名页面内容。否则请关闭。
' +
                            '
<button type="button" class="btn btn-danger" data-loading-text="搬运中" autocomplete="off">覆盖</button>
' +
                            '
';
                        $('body').append(warn).on('click', '.copy-warn .btn', $.proxy(this._importWiki, this, token));
                        $('body').append(warn).on('click', '.copy-warn .close',function(){
                            $('.copy-modal').modal('hide');
                            $('.copy-warn').remove();
                        });

                    }
                }
            },this),
            error: function(error){
                console.log(error)
            }
        })
    },
    _importWiki: function(token){
        var $btn = $('.copy-warn .btn').button('loading');
        $.ajax({
            url: this.ajaxurl+'?origin=http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix'),
            data: {
                action: 'import',
                interwikisource: mw.config.get('wgHuijiPrefix'),
                interwikipage: mw.config.get('wgPageName'),
                token: token,
                format:'json',
                // fullhistory: true,
                templates: true,
                createonly: true
            },
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            success: $.proxy(function(data){

                var result = data.import||[];
                var error = data.error||'';
                $('.copy .fa-spinner').remove();
                if(result.length>0) {
                    $btn.button('reset');
                    $('.copy-warn .close').trigger('click');
                    var options = {
                        tag: 'import',
                        type: 'info'
                    }
                    $('.copy-modal').modal('hide');
                    this._addSource(token);
                    jQuery.post(
                        mw.util.wikiScript(), {
                        action: 'ajax',
                        rs: 'wfAddForkCount',
                        rsargs: [mw.config.get('wgArticleId')],
                    },function(){
                        mw.notification.notify('搬运成功', options);
                    });
                }else if(error.code == 'cantimport'){
                    var options = {
                        tag: 'import',
                        type: 'error'
                    }
                    mw.notification.notify('您在目标维基没有管理员权限', options);
                }else if(error.code == 'unknown_interwikisource'){
                    var options = {
                        tag: 'import',
                        type: 'error'
                    }
                    mw.notification.notify('您选择的维基不能为当前维基', options);
                }else{
                    console.log(data);
                }
            },this),
            error: function( error ){
                console.log( error );
            }
        });

    },
    _addSource: function(token){
        $.ajax({
            url: this.ajaxurl+'?origin=http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix'),
            data:{
                action: "edit",
                title: mw.config.get('wgPageName'),
                summary: "注明出处",
                format:"json",
                appendtext: "<noinclude>{{raw:templatemanager:ForkCredit|time="+getFormattedDate()+"|source_page=[["+mw.config.get('wgHuijiPrefix')+":"+mw.config.get('wgPageName')+"]]"+"|carrier=[[User:"+mw.config.get('wgUserName')+"]]}}</noinclude>",
                token: token
            },
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            success: $.proxy(function(data){
                var that = this;
                jQuery.post(
                    mw.util.wikiScript(), {
                    action: 'ajax',
                    rs: 'wfAddForkInfo',
                    rsargs: [mw.config.get('wgArticleId'), wgNamespaceNumber, mw.config.get('wgPageName'), mw.config.get('wgHuijiPrefix'), this.targetPrefix]
                },function(){
                    window.location = that.redirectUrl;
                });
            },this)

        });

    }

};
$(function() {
    jQuery.post(
    mw.util.wikiScript(), {
        action: 'ajax',
        rs: 'wfGetForkInfoByPageId',
        rsargs: [mw.config.get('wgArticleId')]
    },
    function( data ) {
        var res = JSON.parse(data);
        console.log(res);
        console.log(typeof res);
        var content = '来自'+res.fork_from+'.huiji.wiki';
        $('#contentSub').append(content);
    });

    return new copyWiki();
});<commit_msg>copy.js add judge<commit_after>/**
 * Created by huiji001 on 2015/9/10.
 */
function copyWiki(){
    this.init();
}

function getFormattedDate() {
    var date = new Date();
    var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return str;
}

copyWiki.prototype ={
    init: function(){
        this._addListener();
        this._addModal();
    },
    _addListener: function(){
        $('#ca-fork a').on('click', $.proxy(this._getFollow, this));
        $('body').on('click','.copy-modal .copy', $.proxy(this._wikiSelect, this));
    },
    _getFollow: function(){
        var user_name = mw.config.get('wgUserName');
        $('.copy-modal').modal();
        if(user_name == null){
            e.preventDefault();
            $('.wiki-copy .dropdown-menu').empty().append('请登录');
            $('.user-login').modal();
        }else {
            $.post(
                mw.util.wikiScript(), {
                    action: 'ajax',
                    rs: 'wfUserSiteFollowsDetailsResponse',
                    rsargs: [user_name, user_name]
                },
                function (data) {
                    var res = $.parseJSON(data);
                    var content = '';
                    if (res.success == true) {
                        if (res.result.length == 0) {
                            content = '您要把这个页面搬运到哪里呢？不妨先关注那个维基吧';
                            $('.copy-modal .modal-body').empty().append(content);
                        }
                        $.each(res.result,
                            function (i, item) {
                                content += '
' + item.val + '
'
                            }
                        );
                        $('.copy-modal .modal-body').empty().append(content);
                    }
                }
            );
        }
    },
    _addModal: function(){
        var modal = '
'+
            '
'+
            '
'+
                '
'+
                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>'+
                    '
把这个页面搬运到哪？
'+
                    '
根据页面历史长短和嵌套的模板数量，搬运会需要相应的等候时间。
'+
                '
'+
                '
'+
                ''+
                '
'+
            '
'+
        '
'+
        '
';
        $("body").append(modal);
    },
    _wikiSelect: function(e){
        e.stopPropagation();
        var targetPrefix = $(e.target).data('src');
        var ajaxurl = 'http://'+$(e.target).data('src')+mw.config.get('wgHuijiSuffix')+'/api.php';
        var redirectUrl = 'http://'+$(e.target).data('src')+mw.config.get('wgHuijiSuffix')+'/wiki/'+mw.config.get('wgPageName');
        $(e.target).append('');
        this.targetPrefix = targetPrefix;
        this.ajaxurl = ajaxurl;
        this.redirectUrl = redirectUrl;
        this._getToken();
    },
    _getToken: function(){
        $.ajax({
            url: this.ajaxurl,
            data: {
                action: 'query',
                meta: 'tokens',
                format: 'json',
                origin:'http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix')
            },
            xhrFields: {
                withCredentials: true
            },
            dataType: 'json',
            type: 'POST',
            context: this,
            success: function( data ){
                var token = data.query.tokens.csrftoken;
                this._queryPage(token);
            },
            error: function( error ){
                console.log( error );
            }
        })
    },
    _queryData: function(){
        var _this = copyWiki.prototype;
        console.log(_this);
//        $.ajax({
//            url:'api.php?action=query&titles=API&export&exportnowrap',
//            title: mw.config.get( "wgPageName" )
//        })
        $.ajax({
            url: mw.util.wikiScript( 'api' ),
            data: {
                format: 'xml',
                action: 'query',
                titles: '首页',
                prop: 'revisions',
                rvprop: 'content'
            },
            type: 'POST',
            success: function( data ) {
                console.log(data);
                this._importData(data);
            },
            error: function( xhr ) {
                alert( 'Error: Request failed.' );
            }
        });
    },
    _copyContent: function(){

    },
    _queryPage: function(token){
        $.ajax({
            url:this.ajaxurl,
            data:{
                action: 'query',
                titles: mw.config.get('wgPageName'),
                format: 'json',
                origin:'http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix')
            },
            xhrFields: {
                withCredentials: true
            },
            type: 'post',
            success: $.proxy(function(data){

                for (var key in data.query.pages){
                    if (key < 0){
                        this._importWiki(token);
                    }else{

                        var warn = '
' +
                            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>' +
                            '
页面已存在!
' +
                            '
点击覆盖，将覆盖您维基已有的同名页面内容。否则请关闭。
' +
                            '
<button type="button" class="btn btn-danger" data-loading-text="搬运中" autocomplete="off">覆盖</button>
' +
                            '
';
                        $('body').append(warn).on('click', '.copy-warn .btn', $.proxy(this._importWiki, this, token));
                        $('body').append(warn).on('click', '.copy-warn .close',function(){
                            $('.copy-modal').modal('hide');
                            $('.copy-warn').remove();
                        });

                    }
                }
            },this),
            error: function(error){
                console.log(error)
            }
        })
    },
    _importWiki: function(token){
        var $btn = $('.copy-warn .btn').button('loading');
        $.ajax({
            url: this.ajaxurl+'?origin=http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix'),
            data: {
                action: 'import',
                interwikisource: mw.config.get('wgHuijiPrefix'),
                interwikipage: mw.config.get('wgPageName'),
                token: token,
                format:'json',
                // fullhistory: true,
                templates: true,
                createonly: true
            },
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            success: $.proxy(function(data){

                var result = data.import||[];
                var error = data.error||'';
                $('.copy .fa-spinner').remove();
                if(result.length>0) {
                    $btn.button('reset');
                    $('.copy-warn .close').trigger('click');
                    var options = {
                        tag: 'import',
                        type: 'info'
                    }
                    $('.copy-modal').modal('hide');
                    this._addSource(token);
                    jQuery.post(
                        mw.util.wikiScript(), {
                        action: 'ajax',
                        rs: 'wfAddForkCount',
                        rsargs: [mw.config.get('wgArticleId')],
                    },function(){
                        mw.notification.notify('搬运成功', options);
                    });
                }else if(error.code == 'cantimport'){
                    var options = {
                        tag: 'import',
                        type: 'error'
                    }
                    mw.notification.notify('您在目标维基没有管理员权限', options);
                }else if(error.code == 'unknown_interwikisource'){
                    var options = {
                        tag: 'import',
                        type: 'error'
                    }
                    mw.notification.notify('您选择的维基不能为当前维基', options);
                }else{
                    console.log(data);
                }
            },this),
            error: function( error ){
                console.log( error );
            }
        });

    },
    _addSource: function(token){
        $.ajax({
            url: this.ajaxurl+'?origin=http://'+mw.config.get('wgHuijiPrefix')+mw.config.get('wgHuijiSuffix'),
            data:{
                action: "edit",
                title: mw.config.get('wgPageName'),
                summary: "注明出处",
                format:"json",
                appendtext: "<noinclude>{{raw:templatemanager:ForkCredit|time="+getFormattedDate()+"|source_page=[["+mw.config.get('wgHuijiPrefix')+":"+mw.config.get('wgPageName')+"]]"+"|carrier=[[User:"+mw.config.get('wgUserName')+"]]}}</noinclude>",
                token: token
            },
            type: 'post',
            xhrFields: {
                withCredentials: true
            },
            success: $.proxy(function(data){
                var that = this;
                jQuery.post(
                    mw.util.wikiScript(), {
                    action: 'ajax',
                    rs: 'wfAddForkInfo',
                    rsargs: [mw.config.get('wgArticleId'), wgNamespaceNumber, mw.config.get('wgPageName'), mw.config.get('wgHuijiPrefix'), this.targetPrefix]
                },function(){
                    window.location = that.redirectUrl;
                });
            },this)

        });

    }

};
$(function() {
    if(wgNamespaceNumber==10||wgNamespaceNumber==828) {
        jQuery.post(
            mw.util.wikiScript(), {
                action: 'ajax',
                rs: 'wfGetForkInfoByPageId',
                rsargs: [mw.config.get('wgArticleId')]
            },
            function (data) {
                var res = JSON.parse(data);
                if (data != '[]') {
                    var content = '来自' + res.fork_from + '.huiji.wiki';
                    $('#contentSub small').append(content);
                }
            });
    }

    return new copyWiki();
});<|endoftext|>


<commit_before>"use strict";

// Data manipulation logic
var data = (function() {
  var _commits = {};

  var module = {};

  module.getOrgEvent = function(org, cb) {
    var url = API_BASE_URL + API_ORG + org + API_EVENTS;
    d3.json(url)
    .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
    .get(function(err, data) {
      if (err) {
        console.log(err);
      } else {
        console.log(data.filter(filterPushEvents));
        // _updateCommitsFromPushes(user, data.filter(filterPushEvents));
        // _fetchCommitDetails(user, cb);
      }
    });
  };

  module.getPubEvent = function(user, cb) {
    console.log(user);
    var url = API_BASE_URL + API_USER + user.username + API_PUBLIC_EVENTS;
    d3.json(url)
    .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
    .get(function(err, data) {
      if (err) {
        console.log(err);
      } else {
        _updateCommitsFromPushes(user, data.filter(filterPushEvents));
        _fetchCommitDetails(user, cb);
      }
    });
  };

  var _updateCommitsFromPushes = function(user, data) {
    if (!_commits[user.username]) {
      _commits[user.username] = [];
    }

    data.forEach(function(event) {
      if (event["payload"]["commits"]) {
        event["payload"]["commits"].forEach(function(commit) {
          if (user.email === (commit["author"]["email"])) {
            _commits[user.username].push(commit);
          } else {
            // console.log("commit from others");
            // console.log(commit["author"]["email"]);
          }
        });
      }
      // _commits[user] = _commits[user].concat(event["payload"]["commits"]);
    });
  }

  var _fetchCommitDetails = function(user, cb) {
    if (!_commits[user.username]) {
      console.log("user does not exist");
      return;
    }
    var commitsRemaining = 0;
    _commits[user.username].forEach(function(d) {
      commitsRemaining++;
      d3.json(d.url)
      .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
      .get(function(err, res) {
        if (err) {
          console.log(err);
        } else {
          //console.log(res);
          d.date = parseDate(res["commit"]["author"]["date"]);
          commitsRemaining--;
          // if (commitsRemaining === 0) {
          // _commits[user].sort(sortTime);
          cb(user, _commits[user.username]);
          // }
        }
      });
      //console.log(d);
    });
  }

  module.getDomain = function(accessor) {
    var domains = [];
    for (var userkey in _commits) {
      if (_commits.hasOwnProperty(userkey)) {
        var userCommits = _commits[userkey];
        domains = domains.concat(d3.extent(userCommits, accessor));
      }
    }
    return d3.extent(domains);
  }

  return module;

})();
<commit_msg>added date filter for old commits<commit_after>"use strict";

// Data manipulation logic
var data = (function() {
  var _commits = {};

  var module = {};

  module.getOrgEvent = function(org, cb) {
    var url = API_BASE_URL + API_ORG + org + API_EVENTS;
    d3.json(url)
    .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
    .get(function(err, data) {
      if (err) {
        console.log(err);
      } else {
        console.log(data.filter(filterPushEvents));
        // _updateCommitsFromPushes(user, data.filter(filterPushEvents));
        // _fetchCommitDetails(user, cb);
      }
    });
  };

  module.getPubEvent = function(user, cb) {
    console.log(user);
    var url = API_BASE_URL + API_USER + user.username + API_PUBLIC_EVENTS;
    d3.json(url)
    .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
    .get(function(err, data) {
      if (err) {
        console.log(err);
      } else {
        _updateCommitsFromPushes(user, data.filter(filterPushEvents));
        _fetchCommitDetails(user, cb);
      }
    });
  };

  var _updateCommitsFromPushes = function(user, data) {
    if (!_commits[user.username]) {
      _commits[user.username] = [];
    }

    data.forEach(function(event) {
      if (event["payload"]["commits"]) {
        event["payload"]["commits"].forEach(function(commit) {
          if (isCommitValid(user, commit)) {
            _commits[user.username].push(commit);
          } else {
            // console.log("commit from others");
            // console.log(commit["author"]["email"]);
          }
        });
      }
      // _commits[user] = _commits[user].concat(event["payload"]["commits"]);
    });
  }

  var isCommitValid = function(user, commit) {
    if(user.email === (commit["author"]["email"])){
      return true;
    } else {
      return false;
    }
  }

  var _fetchCommitDetails = function(user, cb) {
    if (!_commits[user.username]) {
      console.log("user does not exist");
      return;
    }
    var commitsRemaining = 0;
    _commits[user.username].forEach(function(d) {
      commitsRemaining++;
      d3.json(d.url)
      .header("Authorization", "Basic cGFyYWRpdGU6YTFhY2MzM2FlZDU2ZGE5OTg4YzY1NGJkMjQxNzdiZTY1NjFkZTllZQ==")
      .get(function(err, res) {
        if (err) {
          console.log(err);
        } else {
          //console.log(res);
          commitsRemaining--;
          var commitDate = parseDate(res["commit"]["author"]["date"]);
          if(isCommitTooEarly(commitDate)){
            console.log("too ealry");
            return;
          }
          d.date = commitDate;
          // if (commitsRemaining === 0) {
          // _commits[user].sort(sortTime);
          cb(user, _commits[user.username]);
          // }
        }
      });
      //console.log(d);
    });
  }

  var _ValidDateEarliest = new Date(2016, 0, 11); // Semester start at Jan 11

  var isCommitTooEarly = function(date) {
    return date < _ValidDateEarliest;
  }

  module.getDomain = function(accessor) {
    var domains = [];
    for (var userkey in _commits) {
      if (_commits.hasOwnProperty(userkey)) {
        var userCommits = _commits[userkey];
        domains = domains.concat(d3.extent(userCommits, accessor));
      }
    }
    return d3.extent(domains);
  }

  return module;

})();
<|endoftext|>


<commit_before>'use strict';

function check(){
    // Check if every button has correct solution on it.
    var win = true;
    var loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    var loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(){
    core_storage_save();

    var first = 0;
    var second = 0;
    var which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    var loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = core_random_integer({
          'max': 9,
          'todo': 'ceil',
        });
        do{
            second = core_random_integer({
              'max': 9,
              'todo': 'ceil',
            });
        }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different columns to switch.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different rows.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        times = 8;
        do{
            var temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        var element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.style.position = 'relative';
        element.value = ' ';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = core_storage_data['locked'] - 1;
    if(loop_counter >= 0){
        do{
            first = core_random_integer({
              'max': 81,
            });
            var first_element = document.getElementById(first);
            var element_80 = document.getElementById(80 - first);

            first_element.disabled = true;
            element_80.disabled = true;

            first_element.style.background = '#777';
            element_80.style.background = '#777';

            first_element.style.color = '#000';
            element_80.style.color = '#000';

            first_element.value = puzzle[first];
            element_80.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : ' ';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function update_number_select(id){
    // Make sure the number select box doesn't go past the left/right edges.
    var xpos = document.getElementById(id).offsetLeft - 100 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    var number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top  =
      (document.getElementById(id).offsetTop  - 50 - window.pageYOffset)
      + 'px';
}

var puzzle = [];
var selected_button = -1;
var times = 0;
<commit_msg>improved formatting<commit_after>'use strict';

function check(){
    // Check if every button has correct solution on it.
    var win = true;
    var loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    var loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(){
    core_storage_save();

    var first = 0;
    var second = 0;
    var which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    var loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = core_random_integer({
          'max': 9,
          'todo': 'ceil',
        });
        do{
            second = core_random_integer({
              'max': 9,
              'todo': 'ceil',
            });
        }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different columns to switch.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different rows.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        times = 8;
        do{
            var temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        var element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.style.position = 'relative';
        element.value = ' ';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = core_storage_data['locked'] - 1;
    if(loop_counter >= 0){
        do{
            first = core_random_integer({
              'max': 81,
            });
            var element = document.getElementById(first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[first];

            element = document.getElementById(80 - first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : ' ';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function update_number_select(id){
    // Make sure the number select box doesn't go past the left/right edges.
    var xpos = document.getElementById(id).offsetLeft - 100 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    var number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top  =
      (document.getElementById(id).offsetTop  - 50 - window.pageYOffset)
      + 'px';
}

var puzzle = [];
var selected_button = -1;
var times = 0;
<|endoftext|>


<commit_before>'use strict';

const WINDOW_WIDTH = 400;
const WINDOW_HEIGHT = 460;
const METER = 100;

var sprites;
var world;

var meterToPixel = (mx) => mx*METER;
var pixelToMeter = (px) => px/METER;

function createParticleGroup() {
    var psd = new b2ParticleSystemDef();
    psd.radius = 0.025;
    psd.dampingStrength = 0.2;
    var particleSystem = world.CreateParticleSystem(psd);
    var box = new b2PolygonShape();
    box.SetAsBoxXYCenterAngle(
        1.25, 1.25,
        new b2Vec2(pixelToMeter(WINDOW_WIDTH) / 2, 2.0),
        0
    );
    var particleGroupDef = new b2ParticleGroupDef();
    particleGroupDef.shape = box;
    var particleGroup = particleSystem.CreateParticleGroup(particleGroupDef);
}

function InitializeRainMaker() {
	createParticleGroup();
}

(function init(divName) {
	// define gravity in LiquidFun and initialize world
    let gravity = new b2Vec2(0, 10);
    world = new b2World(gravity);

	// create minimal phaser.js game:
	sprites = [];
    let game = new Phaser.Game(WINDOW_WIDTH, WINDOW_HEIGHT, Phaser.AUTO, divName, {
		preload: () => {
			game.load.image('dot', 'img/particles.png');
			InitializeRainMaker();
		},
		create: () => {
			let SetupParticles = function() {
				let particles = world.particleSystems[0].GetPositionBuffer();
				for (let i = 0; i < particles.length/2; i++)
				{
					let x = meterToPixel(particles[i * 2]);
					let y = meterToPixel(particles[(i * 2) + 1]);
					sprites[i] = game.add.sprite(x,y, 'dot');
					sprites[i].anchor.set(0.5, 0.5);

					let color = Math.floor(Math.random()*256)*0x10000
							+ Math.floor(Math.random()*256)*0x100
							+ Math.floor(Math.random()*256);  // RGB random colors
					sprites[i].tint = color;
				}
			}

			SetupParticles();
		},
		update: () => {
		}
	});
}("rain"));
<commit_msg>Added movement<commit_after>'use strict';

const WINDOW_WIDTH = 400;
const WINDOW_HEIGHT = 460;
const METER = 100;

var sprites;
var world;

var meterToPixel = (mx) => mx*METER;
var pixelToMeter = (px) => px/METER;

function createParticleGroup() {
    var psd = new b2ParticleSystemDef();
    psd.radius = 0.025;
    psd.dampingStrength = 0.2;
    var particleSystem = world.CreateParticleSystem(psd);
    var box = new b2PolygonShape();
    box.SetAsBoxXYCenterAngle(
        1.25, 1.25,
        new b2Vec2(pixelToMeter(WINDOW_WIDTH) / 2, 2.0),
        0
    );
    var particleGroupDef = new b2ParticleGroupDef();
    particleGroupDef.shape = box;
    var particleGroup = particleSystem.CreateParticleGroup(particleGroupDef);
}

function InitializeRainMaker() {
	createParticleGroup();
}

function tick() {
	const TIME_STEP = 1.0 / 30.0;
	const VELOCITY_ITERATIONS = 8;
	const POSITION_ITERATIONS = 3;

    world.Step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);

	let particles = world.particleSystems[0].GetPositionBuffer();
    for (var i = 0; i < particles.length / 2; i++)
    {
        let x = meterToPixel(particles[i * 2]);
        let y = WINDOW_HEIGHT - meterToPixel(particles[(i * 2) + 1]);
		sprites[i].x = x;
		sprites[i].y = WINDOW_HEIGHT - y;
    }
}

(function init(divName) {
	// define gravity in LiquidFun and initialize world
    let gravity = new b2Vec2(0, 10);
    world = new b2World(gravity);

	// create minimal phaser.js game:
	sprites = [];
    let game = new Phaser.Game(WINDOW_WIDTH, WINDOW_HEIGHT, Phaser.AUTO, divName, {
		preload: () => {
			game.load.image('dot', 'img/particles.png');
			InitializeRainMaker();
		},
		create: () => {
			let SetupParticles = function() {
				let particles = world.particleSystems[0].GetPositionBuffer();
				for (let i = 0; i < particles.length/2; i++)
				{
					let x = meterToPixel(particles[i * 2]);
					let y = meterToPixel(particles[(i * 2) + 1]);
					sprites[i] = game.add.sprite(x,y, 'dot');
					sprites[i].anchor.set(0.5, 0.5);

					let color = Math.floor(Math.random()*256)*0x10000
							+ Math.floor(Math.random()*256)*0x100
							+ Math.floor(Math.random()*256);  // RGB random colors
					sprites[i].tint = color;
				}
			}

			SetupParticles();
		},
		update: () => {
			tick();
		}
	});
}("rain"));
<|endoftext|>


<commit_before>/* globals ajax app dom listenCanvas canvas getState setState setMoatUI*/

(function(global) {
  "use strict";

  // CONFIGURATION
  const USE_MOAT = true;
  const MOAT_URL = "https://sd-moat.glitch.me/";

  var defaultCanvas = `<svg id="canvas" width="2560px" height="1116px" data-tool="pen" data-stroke-width="2" data-do-onionskin="true" data-fps="10" data-palette="0" data-color="#000000" data-bgcolor="#FFFFFF" data-color1="#000000" data-color2="#FFFFFF" data-color3="#666666" data-color4="#69D2E7" data-color5="#A7DBD8" data-color6="#E0E4CC" data-color7="#F38630" data-color8="#FA6900" data-tab_file="false" data-tab_draw="true" data-tab_animate="true"><g class="frame selected"></g></svg>`;

  function saveLocal() {
    localStorage._currentWork = saveFormat();
  }

  function updateSavedState() {
    let state = getState();
    for (let key in state) {
      canvas.dataset[key] = state[key];
    }
  }

  function restoreSavedState() {
    let state = {};
    for (let key in canvas.dataset) {
      state[key] = canvas.dataset[key];
    }
    setState(state);
  }

  function saveFormat() {
    if (canvas) {
      updateSavedState();
      return canvas.outerHTML;
    } else {
      return "";
    }
  }

  window.canvas = null;

  function restoreFormat(savetext) {
    canvas = document.querySelector("#canvas");
    if (!canvas) {
      canvas = dom.svg("svg");
      document.body.prepend(canvas);
    }
    if (!savetext) {
      savetext = defaultCanvas;
    }
    canvas.outerHTML = savetext;
    canvas = document.querySelector("#canvas");
    app.updateFrameCount();
    canvas.setAttribute("width", document.body.clientWidth + "px");
    canvas.setAttribute("height", document.body.clientHeight + "px");
    listenCanvas();
    restoreSavedState();
  }

  function restore() {
    var path = location.href.split("?");
    var query = location.search;
    if (query) {
      var queryparts = query.slice(1).split("=");
      if (queryparts[0] === "gist") {
        loadScriptsFromGistId(queryparts[1]);
        return;
      }
    }
    restoreLocal();
  }

  function restoreLocal() {
    restoreFormat(localStorage._currentWork || defaultCanvas);
  }

  function clear() {
    restoreFormat(defaultCanvas);
  }

  function saveFile(evt) {
    if (evt) {
      evt.preventDefault();
    }
    var title = prompt("Save file as: ");
    if (!title) {
      return;
    }
    saveAs(saveFormat(), `${title}.svg`);
  }

  const filetypes = {
    svg: "image/svg+xml",
    png: "image/png",
    gif: "image/gif"
  };

  function saveToCallback(data, filename, cb) {
    // Callback is shaped cb(blob, filename);
    console.log('saveToCallback(%s)', filename);
    let ext = filename.split(".").pop();
    let filetype = filetypes[ext];
    if (data.toBlob) {
      // ex: canvas.toBlob()
      data.toBlob(blob => cb(blob, filename), filetype);
    } else {
      cb(new Blob([data], { type: filetype }), filename);
    }
  }

  function sendToMoat(progid) {
    console.log('sendToMoat(%s)', progid);
    saveToCallback(saveFormat(), "shimmy.svg", (blob, filename) =>
      sendToMoatCB(blob, filename, progid)
    );
  }

  // function sendToMoatPreflight(blob, filename, progid){
  //   console.log('sendToMoatPreflight(%s)', filename);
  //   let request = new XMLHttpRequest();
  //   request.open('OPTIONS', MOAT_URL + 'file/create');
  //   request.send();
  //   request.onLoad = () => sendToMoatCB(blob, filename, progid);
  //   request.onError = () => handleError('preflight');
  //   request.onTimeout = () => handleTimeout('preflight');
  // }

  function sendToMoatCB(blob, filename, progid) {
    console.log('sendToMoatCB(%s)', filename);
    let formData = new FormData();
    formData.append("program", progid);
    formData.append("file", blob, filename);
    let request = new XMLHttpRequest();
    request.open("POST", MOAT_URL + 'file/create');
    request.setRequestHeader('X-Requested-With', 'XMLHTTPRequest');
    request.send(formData);
    request.onLoad = () => showFilePage;
    request.onError = () => handleError('send file');
    request.onTimeout = () => handleTimeout('send file');
  }

  function handleError(step) {
    alert("Error uploading to Moat during " + step + " step, please try again.");
  }

  function handleTimeout(step) {
    alert("Timeout uploading to Moat during " + step + ", please try again.");
  }

  function showFilePage() {
    console.log('showFilePage');
    let dialog = dom.html("dialog");
    document.body.append(dialog);
    console.log(this.responseXML);
    dialog.append(this.responseXML.querySelector("main"));
    dialog.showModal();
  }

  function saveAs(data, filename) {
    saveToCallback(data, filename, saveBlob);
  }

  function saveBlob(blob, filename) {
    var reader = new FileReader();
    reader.onloadend = function() {
      var a = dom.html("a", {
        href: reader.result,
        download: filename,
        target: "_blank"
      });
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
    reader.readAsDataURL(blob);
  }

  function readFile(file) {
    var fileName = file.name;
    if (fileName.indexOf(".svg", fileName.length - 5) === -1) {
      return alert("Not an SVG file");
    }
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(evt) {
      restoreFormat(evt.target.result);
    };
  }

  function loadFile() {
    var input = dom.html("input", { type: "file", accept: "image/svg+xml" });
    if (!input) {
      return;
    }
    input.addEventListener("change", function(evt) {
      readFile(input.files[0]);
    });
    input.click();
  }

  // Save script to gist;
  function saveCurrentScriptsToGist(event) {
    event.preventDefault();
    // console.log("Saving to Gist");
    ajax.post(
      "https://api.github.com/gists",
      function(data) {
        //var raw_url = JSON.parse(data).files["script.json"].raw_url;
        gistID = JSON.parse(data)
          .url.split("/")
          .pop();
        var path = location.href.split("?")[0];
        path += "?gist=" + gistID;
        window.location = path;
      },
      JSON.stringify({
        description: "saved drawingboard file",
        public: true,
        files: {
          "animation.svg": {
            content: saveFormat()
          }
        }
      }),
      function(statusCode, x) {
        alert(
          "Can't save to Gist:\n" + statusCode + " (" + x.statusText + ") "
        );
      }
    );
  }

  var gistID = null;

  function loadScriptsFromGistId(id) {
    //we may get an event passed to this function so make sure we have a valid id or ask for one
    gistID = isNaN(parseInt(id))
      ? prompt(
          "What Gist would you like to load? Please enter the ID of the Gist: "
        )
      : id;
    if (!gistID) return;
    ajax.get(
      "https://api.github.com/gists/" + gistID,
      function(gist) {
        restoreFormat(JSON.parse(gist).files["animation.svg"].content);
      },
      function(statusCode, x) {
        alert(
          "Can't load from Gist:\n" + statusCode + " (" + x.statusText + ") "
        );
      }
    );
  }

  function newFile() {
    clear();
    onChange();
  }

  function onChange() {
    if (gistID) {
      gistID = null;
      var path = location.href.split("?")[0];
      history.replaceState(null, null, path);
    }
  }

  function queryMoat(cb) {
    fetch(MOAT_URL + "programs/?integration=shimmy").then(response =>
      response.json().then(cb)
    );
  }
  if (USE_MOAT) {
    window.addEventListener("load", e => queryMoat(setMoatUI), true);
  }

  window.file = {
    onChange: onChange,
    new: newFile,
    clear: clear,
    loadFile,
    saveFile,
    saveBlob,
    saveLocal,
    saveAs,
    sendToMoat
  };

  window.addEventListener("unload", saveLocal, false);
  window.addEventListener("load", restore, false);
})(window);
<commit_msg>🏦💝 Checkpoint ./js/file.js:739936/79<commit_after>/* globals ajax app dom listenCanvas canvas getState setState setMoatUI*/

(function(global) {
  "use strict";

  // CONFIGURATION
  const USE_MOAT = true;
  const MOAT_URL = "https://sd-moat.glitch.me/";

  var defaultCanvas = `<svg id="canvas" width="2560px" height="1116px" data-tool="pen" data-stroke-width="2" data-do-onionskin="true" data-fps="10" data-palette="0" data-color="#000000" data-bgcolor="#FFFFFF" data-color1="#000000" data-color2="#FFFFFF" data-color3="#666666" data-color4="#69D2E7" data-color5="#A7DBD8" data-color6="#E0E4CC" data-color7="#F38630" data-color8="#FA6900" data-tab_file="false" data-tab_draw="true" data-tab_animate="true"><g class="frame selected"></g></svg>`;

  function saveLocal() {
    localStorage._currentWork = saveFormat();
  }

  function updateSavedState() {
    let state = getState();
    for (let key in state) {
      canvas.dataset[key] = state[key];
    }
  }

  function restoreSavedState() {
    let state = {};
    for (let key in canvas.dataset) {
      state[key] = canvas.dataset[key];
    }
    setState(state);
  }

  function saveFormat() {
    if (canvas) {
      updateSavedState();
      return canvas.outerHTML;
    } else {
      return "";
    }
  }

  window.canvas = null;

  function restoreFormat(savetext) {
    canvas = document.querySelector("#canvas");
    if (!canvas) {
      canvas = dom.svg("svg");
      document.body.prepend(canvas);
    }
    if (!savetext) {
      savetext = defaultCanvas;
    }
    canvas.outerHTML = savetext;
    canvas = document.querySelector("#canvas");
    app.updateFrameCount();
    canvas.setAttribute("width", document.body.clientWidth + "px");
    canvas.setAttribute("height", document.body.clientHeight + "px");
    listenCanvas();
    restoreSavedState();
  }

  function restore() {
    var path = location.href.split("?");
    var query = location.search;
    if (query) {
      var queryparts = query.slice(1).split("=");
      if (queryparts[0] === "gist") {
        loadScriptsFromGistId(queryparts[1]);
        return;
      }
    }
    restoreLocal();
  }

  function restoreLocal() {
    restoreFormat(localStorage._currentWork || defaultCanvas);
  }

  function clear() {
    restoreFormat(defaultCanvas);
  }

  function saveFile(evt) {
    if (evt) {
      evt.preventDefault();
    }
    var title = prompt("Save file as: ");
    if (!title) {
      return;
    }
    saveAs(saveFormat(), `${title}.svg`);
  }

  const filetypes = {
    svg: "image/svg+xml",
    png: "image/png",
    gif: "image/gif"
  };

  function saveToCallback(data, filename, cb) {
    // Callback is shaped cb(blob, filename);
    console.log('saveToCallback(%s)', filename);
    let ext = filename.split(".").pop();
    let filetype = filetypes[ext];
    if (data.toBlob) {
      // ex: canvas.toBlob()
      data.toBlob(blob => cb(blob, filename), filetype);
    } else {
      cb(new Blob([data], { type: filetype }), filename);
    }
  }

  function sendToMoat(progid) {
    console.log('sendToMoat(%s)', progid);
    saveToCallback(saveFormat(), "shimmy.svg", (blob, filename) =>
      sendToMoatCB(blob, filename, progid)
    );
  }

  // function sendToMoatPreflight(blob, filename, progid){
  //   console.log('sendToMoatPreflight(%s)', filename);
  //   let request = new XMLHttpRequest();
  //   request.open('OPTIONS', MOAT_URL + 'file/create');
  //   request.send();
  //   request.onLoad = () => sendToMoatCB(blob, filename, progid);
  //   request.onError = () => handleError('preflight');
  //   request.onTimeout = () => handleTimeout('preflight');
  // }

  function sendToMoatCB(blob, filename, progid) {
    console.log('sendToMoatCB(%s)', filename);
    let formData = new FormData();
    formData.append("program", progid);
    formData.append("file", blob, filename);
    let request = new XMLHttpRequest();
    request.open("POST", MOAT_URL + 'file/create');
    request.setRequestHeader('X-Requested-With', 'XMLHTTPRequest');
    request.send(formData);
    request.onLoad = () => showFilePage(request.xml);
    request.onError = () => handleError('send file');
    request.onTimeout = () => handleTimeout('send file');
  }

  function handleError(step) {
    alert("Error uploading to Moat during " + step + " step, please try again.");
  }

  function handleTimeout(step) {
    alert("Timeout uploading to Moat during " + step + ", please try again.");
  }

  function showFilePage(html) {
    console.log('showFilePage');
    let dialog = dom.html("dialog");
    document.body.append(dialog);
    console.log(html);
    dialog.append(html);
    dialog.showModal();
  }

  function saveAs(data, filename) {
    saveToCallback(data, filename, saveBlob);
  }

  function saveBlob(blob, filename) {
    var reader = new FileReader();
    reader.onloadend = function() {
      var a = dom.html("a", {
        href: reader.result,
        download: filename,
        target: "_blank"
      });
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
    reader.readAsDataURL(blob);
  }

  function readFile(file) {
    var fileName = file.name;
    if (fileName.indexOf(".svg", fileName.length - 5) === -1) {
      return alert("Not an SVG file");
    }
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(evt) {
      restoreFormat(evt.target.result);
    };
  }

  function loadFile() {
    var input = dom.html("input", { type: "file", accept: "image/svg+xml" });
    if (!input) {
      return;
    }
    input.addEventListener("change", function(evt) {
      readFile(input.files[0]);
    });
    input.click();
  }

  // Save script to gist;
  function saveCurrentScriptsToGist(event) {
    event.preventDefault();
    // console.log("Saving to Gist");
    ajax.post(
      "https://api.github.com/gists",
      function(data) {
        //var raw_url = JSON.parse(data).files["script.json"].raw_url;
        gistID = JSON.parse(data)
          .url.split("/")
          .pop();
        var path = location.href.split("?")[0];
        path += "?gist=" + gistID;
        window.location = path;
      },
      JSON.stringify({
        description: "saved drawingboard file",
        public: true,
        files: {
          "animation.svg": {
            content: saveFormat()
          }
        }
      }),
      function(statusCode, x) {
        alert(
          "Can't save to Gist:\n" + statusCode + " (" + x.statusText + ") "
        );
      }
    );
  }

  var gistID = null;

  function loadScriptsFromGistId(id) {
    //we may get an event passed to this function so make sure we have a valid id or ask for one
    gistID = isNaN(parseInt(id))
      ? prompt(
          "What Gist would you like to load? Please enter the ID of the Gist: "
        )
      : id;
    if (!gistID) return;
    ajax.get(
      "https://api.github.com/gists/" + gistID,
      function(gist) {
        restoreFormat(JSON.parse(gist).files["animation.svg"].content);
      },
      function(statusCode, x) {
        alert(
          "Can't load from Gist:\n" + statusCode + " (" + x.statusText + ") "
        );
      }
    );
  }

  function newFile() {
    clear();
    onChange();
  }

  function onChange() {
    if (gistID) {
      gistID = null;
      var path = location.href.split("?")[0];
      history.replaceState(null, null, path);
    }
  }

  function queryMoat(cb) {
    fetch(MOAT_URL + "programs/?integration=shimmy").then(response =>
      response.json().then(cb)
    );
  }
  if (USE_MOAT) {
    window.addEventListener("load", e => queryMoat(setMoatUI), true);
  }

  window.file = {
    onChange: onChange,
    new: newFile,
    clear: clear,
    loadFile,
    saveFile,
    saveBlob,
    saveLocal,
    saveAs,
    sendToMoat
  };

  window.addEventListener("unload", saveLocal, false);
  window.addEventListener("load", restore, false);
})(window);
<|endoftext|>


<commit_before>(function () {

	$('html').addClass('js');

	contactForm = {

		formContainer: $('#contact'),

		init: function (conf) {

			$('<a/>', {
				text: "Push Me",
				'class': "btn btn-danger",
				'id': "myButton",
				'href': "http://google.com"
			})
			.insertAfter('article')
			.on('click', this.show);
		},

		show: function (event) {
			// console.log('showing ...');
			event.preventDefault();

			var $self = contactForm;

			// $self.close();

			$self.close.call($self.formContainer);

			$self.formContainer.show();

			// $self.call.close();

		},

		close: function (event) {

			$('<span/>', {
				text: "X",
				'class': "close"
			})
				.prependTo(this);

			// console.log(this);
		}

	}

})();
<commit_msg>close button added<commit_after>(function () {

	$('html').addClass('js');

	contactForm = {

		formContainer: $('#contact'),

		init: function (conf) {

			$('<a/>', {
				text: "Push Me",
				'class': "btn btn-danger",
				'id': "myButton",
				'href': "http://google.com"
			})
			.insertAfter('article')
			.on('click', this.show);
		},

		show: function (event) {
			// console.log('showing ...');
			event.preventDefault();

			var $self = contactForm;

			$self.close.call($self.formContainer);

			$self.formContainer.show();

		},

		close: function (event) {

			$('<span/>', {
				text: "X",
				'class': "close"
			})
				.prependTo(this);

		}

	}

})();
<|endoftext|>