<commit_before>/**
 * Created by atan on 9/14/16.
 */

"use strict";

$(document).ready(function () {
    $(window).load( function () {
        // Determine if the agencyRequestInstructions need to be shown on page load.
        var agencyEin = $("#request-agency").val();
        var requestInstructionsDiv = $("#request-agency-instructions");
        var requestInstructionsContentDiv = $("#request-agency-instructions-content");
        get_request_agency_instructions(agencyEin, requestInstructionsDiv, requestInstructionsContentDiv);
    });

    $("input[name='tz-name']").val(jstz.determine().name());

    // Prevent user from entering a non numeric value into phone and fax field
    $('#phone').keypress(function (key) {
        if (key.charCode != 0) {
            if (key.charCode < 48 || key.charCode > 57) {
                key.preventDefault();
            }
        }
    });
    $('#fax').keypress(function (key) {
        if (key.charCode != 0) {
            if (key.charCode < 48 || key.charCode > 57) {
                key.preventDefault();
            }
        }
    });

    function get_request_agency_instructions(agencyEin, requestInstructionsDiv, requestInstructionsContentDiv) {
        /*
         * ajax call to get additional information for the specified agency
         */
        $.ajax({
            url: "/agency/feature/" + agencyEin + "/" + "specific_request_instructions",
            type: "GET",
            success: function (data) {
                if (data["specific_request_instructions"]["text"] !== "") {
                    requestInstructionsContentDiv.html("
" + data["specific_request_instructions"]["text"] + "
");
                    requestInstructionsDiv.show();
                }
                else {
                    requestInstructionsDiv.hide();
                }
            },
            error: function () {
                requestInstructionsDiv.hide();
            }

        });
    }

    $("#request-agency").change(function () {
        var agencyEin = $("#request-agency").val();
        var requestInstructionsDiv = $("#request-agency-instructions");
        var requestInstructionsContentDiv = $("#request-agency-instructions-content");
        get_request_agency_instructions(agencyEin, requestInstructionsDiv, requestInstructionsContentDiv);
    });

    $("#request-agency-instructions-toggle").click(function () {
        var el = $("#request-agency-instructions-toggle");
        var requestInstructionsContentDiv = $("#request-agency-instructions-content");
        var hideHtml = "<button type=\"button\" id=\"request-agency-instructions-btn\" class=\"btn btn-block btn-info\">  Hide Agency Instructions  </button>";
        var showHtml = "<button type=\"button\" id=\"request-agency-instructions-btn\" class=\"btn btn-block btn-info\">  Show Agency Instructions  </button>";
        if (el.html() === showHtml) {
            el.html(hideHtml);
            requestInstructionsContentDiv.show();
        } else {
            el.html(showHtml);
            requestInstructionsContentDiv.hide();
        }
    });

    // javascript to add tooltip popovers when selecting the title and description
    $('#request-title').attr({
        'data-placement': "top",
        'data-trigger': "hover focus",
        'data-toggle': "popover",
        'data-content': "Public Advocate Emails from 2015",
        title: "Example Title"
    });
    $('#request-title').popover();
    // $('#request-title').click(function(){
    //     $('#request-title').popover('show');
    // });

    $('#request-description').attr({
        'data-placement': "top",
        'data-trigger': "hover focus",
        'data-toggle': "popover",
        'data-content': "Topic: Public Advocate Emails from 2015. Emails that mention bike lanes or bicycle lanes from the Public Advocate's Office between July 27, 2015 and September 10, 2015.",
        title: "Example Request"
    });
    $('#request-description').click(function () {
        $('#request-description').popover('show');
    });
    $('#request-description').popover();
    // $('#request-description').click(function(){
    //     $('#request-description').popover('show');
    // });

    // jQuery mask plugin to format fields
    $('#phone').mask("(999) 999-9999");
    $('#fax').mask("(999) 999-9999");
    $('#zipcode').mask("99999");

    // Datepicker for date request was received when creating a new request
    $(".dtpick").datepicker({
        dateFormat: "mm/dd/yy",
        maxDate: 0
    }).keydown(function (e) {
        // prevent keyboard input except for tab
        if (e.keyCode !== 9)
            e.preventDefault();
    });

    // Loop through required fields and apply a data-parsley-required attribute to them
    var required_fields = ['request-title', 'request-description', 'first-name', 'last-name', 'email',
        'phone', 'fax', 'address-line-1', 'method-received', 'request-date', 'city', 'zipcode'];
    for (var i = 0; i < required_fields.length; i++) {
        $('#' + required_fields[i]).attr('data-parsley-required', '');
    }

    // Apply parsley validation styles to the input forms for a new request.
    $('#request-title').attr('data-parsley-maxlength', 90);
    $('#request-description').attr('data-parsley-maxlength', 5000);
    $('#first-name').attr("data-parsely-maxlength", 32);
    $('#last-name').attr("data-parsely-maxlength", 64);
    $("#email").attr("data-parsley-maxlength", 254);
    $("#user-title").attr("data-parsley-maxlength", 64);
    $("#user-organization").attr("data-parsley-maxlength", 128);
    $('#phone').attr('data-parsley-length', '[14,14]');
    $('#fax').attr('data-parsley-length', '[14,14]');
    $('#zipcode').attr('data-parsley-length', '[5,5]');

    // Custom Validation Messages
    $('#fax').attr('data-parsley-length-message', 'The fax number must be 10 digits.');
    $('#phone').attr('data-parsley-length-message', 'The phone number must be 10 digits.');
    $('#zipcode').attr('data-parsley-length-message', 'The Zipcode must be 5 digits.');

    // Disable default error messages for email,phone,fax,address so custom one can be used instead.
    $('#phone').attr('data-parsley-required-message', '');
    $('#fax').attr('data-parsley-required-message', '');
    $('#address-line-1').attr('data-parsley-required-message', '');
    $('#city').attr('data-parsley-required-message', '');
    $('#email').attr('data-parsley-required-message', '');
    $('#zipcode').attr('data-parsley-required-message', '');

    // Limit the size of the file upload to 20 Mb. Second parameter is number of Mb's.
    $('#request-file').attr('data-parsley-max-file-size', "20");

    // Specify container for file input parsley error message
    $('#request-file').attr("data-parsley-errors-container", ".file-error");

    // Set name of the file to the text of filename div if file exists
    $("#request-file").change(function () {
        var file = this.files[0];
        var isChrome = window.chrome;

        if (file) {
            $("#filename").text((this.files[0].name));
        }
        // Cancel is clicked on upload window
        else {
            // If browser is chrome, reset filename text
            if (isChrome) {
                $("#filename").text("");
            }
        }
    });

    // Clear the file from input and the name from filename div
    $("#clear-file").click(function () {
        if ($(".file-error").is(":visible")) {
            $(".file-error").hide();
        }
        $("#request-file").val("");
        $("#filename").text("");
    });

    // Contact information validation
    $('#email').attr('data-parsley-type', 'email');
    // Checks that at least one form of contact was filled out in addition to the rest of the form.
    $('#request-form').parsley().on('form:validate', function () {
        // Re-apply validators to fields in the event that they were removed from previous validation requests.
        for (var i = 0; i < required_fields.length; i++) {
            $('#' + required_fields[i]).attr('data-parsley-required', '');
        }
        // If address is filled out then make sure the city, state, and zipcode are filled.
        if ($('#address-line-1').parsley().isValid()) {
            $('#city').attr('data-parsley-required', '');
            $('#state').attr('data-parsley-required', '');
            $('#zipcode').attr('data-parsley-required', '');
        }
        // Checks that at least one of the contact information fields is filled in addition to the rest of the form
        if ($('#email').parsley().isValid() ||
            $('#phone').parsley().isValid() ||
            $('#fax').parsley().isValid() ||
            ($('#address-line-1').parsley().isValid() && $('#state').parsley().isValid() && $('#zipcode').parsley().isValid() && $('#city').parsley().isValid())
        ) {
            // If at least one of the fields are validated then remove required from the rest of the contact fields that aren't being filled out
            $('#city').removeAttr('data-parsley-required');
            $('#state').removeAttr('data-parsley-required');
            $('#zipcode').removeAttr('data-parsley-required');
            $('#phone').removeAttr('data-parsley-required');
            $('#fax').removeAttr('data-parsley-required');
            $('#address-line-1').removeAttr('data-parsley-required');
            $('#email').removeAttr('data-parsley-required');
        }
        else {
            // If none of the fields are valid then produce an error message and apply required fields.
            $('.contact-form-error-message').html("*At least one of the following must be filled out: Email, Phone, Fax, and/or Address (with City, State, and Zipcode)");
            $('#fax').attr('data-parsley-required', '');
            $('#phone').attr('data-parsley-required', '');
            $('#address-line-1').attr('data-parsley-required', '');
            $('#email').attr('data-parsley-required', '');
        }

        if ($("#request-file").parsley().isValid() === false) {
            $(".file-error").show();
        }
        else {
            $(".file-error").hide();
        }

        // Scroll to input label if parsley validation fails
        if ($("#request-title").parsley().isValid() === false) {
            $(window).scrollTop($(".title-label").offset().top);
        }
        else if ($("#request-description").parsley().isValid() === false) {
            $(window).scrollTop($(".description-label").offset().top);
        }
        else if ($("#request-file").parsley().isValid() === false) {
            $(".file-error").show();
            $(window).scrollTop($("#upload-control").offset().top);
        }
        else if ($("#method-received").parsley().isValid() === false) {
            $(window).scrollTop($(".format-label").offset().top);
        }
        else if ($("#first-name").parsley().isValid() === false) {
            $(window).scrollTop($(".first-name-label").offset().top);
        }
        else if ($("#last-name").parsley().isValid() === false) {
            $(window).scrollTop($(".last-name-label").offset().top);
        }
        else if ($("#email").parsley().isValid() === false) {
            $(window).scrollTop($(".email-label").offset().top);
        }
    });

    // Clear error messages for form.request_file on submit ...
    $('#submit').click(function () {
        $('.upload-error').remove();
    });
    // ... or on input change for request_file
    $('#request-file').change(function () {
        $('.upload-error').remove();
    });

    // Disable submit button on form submission
    $('#request-form').submit(function () {
        // Prevent multiple submissions
        $(this).submit(function () {
            return false;
        });
        $('#submit').hide();
        $('#processing-submission').show()
    });

    // Character count for creating a new request
    $('#request-title').keyup(function () {
        characterCounter("#title-character-count", 90, $(this).val().length)
    });

    $('#request-description').keyup(function () {
        characterCounter("#description-character-count", 5000, $(this).val().length)
    });

    $('#first-name').keyup(function () {
        characterCounter("#first-name-character-count", 32, $(this).val().length)
    });

    $('#last-name').keyup(function () {
        characterCounter("#last-name-character-count", 64, $(this).val().length)
    });

    $("#user-title").keyup(function () {
        characterCounter("#user-title-character-count", 64, $(this).val().length)
    });

    $("#user-organization").keyup(function () {
        characterCounter("#organization-character-count", 128, $(this).val().length)
    });

});
<commit_msg>Update new-request-agency.js<commit_after>/**
 * Created by atan on 9/14/16.
 */

"use strict";

$(document).ready(function () {
    $(window).load( function () {
        // Determine if the agencyRequestInstructions need to be shown on page load.
        get_request_agency_instructions();
    });

    $("input[name='tz-name']").val(jstz.determine().name());

    // Prevent user from entering a non numeric value into phone and fax field
    $('#phone').keypress(function (key) {
        if (key.charCode != 0) {
            if (key.charCode < 48 || key.charCode > 57) {
                key.preventDefault();
            }
        }
    });
    $('#fax').keypress(function (key) {
        if (key.charCode != 0) {
            if (key.charCode < 48 || key.charCode > 57) {
                key.preventDefault();
            }
        }
    });

    function get_request_agency_instructions() {
        /*
         * ajax call to get additional information for the specified agency
         */

        var agencyEin = $("#request-agency").val();
        var requestInstructionsDiv = $("#request-agency-instructions");
        var requestInstructionsContentDiv = $("#request-agency-instructions-content");

        $.ajax({
            url: "/agency/feature/" + agencyEin + "/" + "specific_request_instructions",
            type: "GET",
            success: function (data) {
                if (data["specific_request_instructions"]["text"] !== "") {
                    requestInstructionsContentDiv.html("
" + data["specific_request_instructions"]["text"] + "
");
                    requestInstructionsDiv.show();
                }
                else {
                    requestInstructionsDiv.hide();
                }
            },
            error: function () {
                requestInstructionsDiv.hide();
            }

        });
    }

    $("#request-agency").change(function () {
        get_request_agency_instructions();
    });

    $("#request-agency-instructions-toggle").click(function () {
        var el = $("#request-agency-instructions-toggle");
        var requestInstructionsContentDiv = $("#request-agency-instructions-content");
        var hideHtml = "<button type=\"button\" id=\"request-agency-instructions-btn\" class=\"btn btn-block btn-info\">  Hide Agency Instructions  </button>";
        var showHtml = "<button type=\"button\" id=\"request-agency-instructions-btn\" class=\"btn btn-block btn-info\">  Show Agency Instructions  </button>";
        if (el.html() === showHtml) {
            el.html(hideHtml);
            requestInstructionsContentDiv.show();
        } else {
            el.html(showHtml);
            requestInstructionsContentDiv.hide();
        }
    });

    // javascript to add tooltip popovers when selecting the title and description
    $('#request-title').attr({
        'data-placement': "top",
        'data-trigger': "hover focus",
        'data-toggle': "popover",
        'data-content': "Public Advocate Emails from 2015",
        title: "Example Title"
    });
    $('#request-title').popover();
    // $('#request-title').click(function(){
    //     $('#request-title').popover('show');
    // });

    $('#request-description').attr({
        'data-placement': "top",
        'data-trigger': "hover focus",
        'data-toggle': "popover",
        'data-content': "Topic: Public Advocate Emails from 2015. Emails that mention bike lanes or bicycle lanes from the Public Advocate's Office between July 27, 2015 and September 10, 2015.",
        title: "Example Request"
    });
    $('#request-description').click(function () {
        $('#request-description').popover('show');
    });
    $('#request-description').popover();
    // $('#request-description').click(function(){
    //     $('#request-description').popover('show');
    // });

    // jQuery mask plugin to format fields
    $('#phone').mask("(999) 999-9999");
    $('#fax').mask("(999) 999-9999");
    $('#zipcode').mask("99999");

    // Datepicker for date request was received when creating a new request
    $(".dtpick").datepicker({
        dateFormat: "mm/dd/yy",
        maxDate: 0
    }).keydown(function (e) {
        // prevent keyboard input except for tab
        if (e.keyCode !== 9)
            e.preventDefault();
    });

    // Loop through required fields and apply a data-parsley-required attribute to them
    var required_fields = ['request-title', 'request-description', 'first-name', 'last-name', 'email',
        'phone', 'fax', 'address-line-1', 'method-received', 'request-date', 'city', 'zipcode'];
    for (var i = 0; i < required_fields.length; i++) {
        $('#' + required_fields[i]).attr('data-parsley-required', '');
    }

    // Apply parsley validation styles to the input forms for a new request.
    $('#request-title').attr('data-parsley-maxlength', 90);
    $('#request-description').attr('data-parsley-maxlength', 5000);
    $('#first-name').attr("data-parsely-maxlength", 32);
    $('#last-name').attr("data-parsely-maxlength", 64);
    $("#email").attr("data-parsley-maxlength", 254);
    $("#user-title").attr("data-parsley-maxlength", 64);
    $("#user-organization").attr("data-parsley-maxlength", 128);
    $('#phone').attr('data-parsley-length', '[14,14]');
    $('#fax').attr('data-parsley-length', '[14,14]');
    $('#zipcode').attr('data-parsley-length', '[5,5]');

    // Custom Validation Messages
    $('#fax').attr('data-parsley-length-message', 'The fax number must be 10 digits.');
    $('#phone').attr('data-parsley-length-message', 'The phone number must be 10 digits.');
    $('#zipcode').attr('data-parsley-length-message', 'The Zipcode must be 5 digits.');

    // Disable default error messages for email,phone,fax,address so custom one can be used instead.
    $('#phone').attr('data-parsley-required-message', '');
    $('#fax').attr('data-parsley-required-message', '');
    $('#address-line-1').attr('data-parsley-required-message', '');
    $('#city').attr('data-parsley-required-message', '');
    $('#email').attr('data-parsley-required-message', '');
    $('#zipcode').attr('data-parsley-required-message', '');

    // Limit the size of the file upload to 20 Mb. Second parameter is number of Mb's.
    $('#request-file').attr('data-parsley-max-file-size', "20");

    // Specify container for file input parsley error message
    $('#request-file').attr("data-parsley-errors-container", ".file-error");

    // Set name of the file to the text of filename div if file exists
    $("#request-file").change(function () {
        var file = this.files[0];
        var isChrome = window.chrome;

        if (file) {
            $("#filename").text((this.files[0].name));
        }
        // Cancel is clicked on upload window
        else {
            // If browser is chrome, reset filename text
            if (isChrome) {
                $("#filename").text("");
            }
        }
    });

    // Clear the file from input and the name from filename div
    $("#clear-file").click(function () {
        if ($(".file-error").is(":visible")) {
            $(".file-error").hide();
        }
        $("#request-file").val("");
        $("#filename").text("");
    });

    // Contact information validation
    $('#email').attr('data-parsley-type', 'email');
    // Checks that at least one form of contact was filled out in addition to the rest of the form.
    $('#request-form').parsley().on('form:validate', function () {
        // Re-apply validators to fields in the event that they were removed from previous validation requests.
        for (var i = 0; i < required_fields.length; i++) {
            $('#' + required_fields[i]).attr('data-parsley-required', '');
        }
        // If address is filled out then make sure the city, state, and zipcode are filled.
        if ($('#address-line-1').parsley().isValid()) {
            $('#city').attr('data-parsley-required', '');
            $('#state').attr('data-parsley-required', '');
            $('#zipcode').attr('data-parsley-required', '');
        }
        // Checks that at least one of the contact information fields is filled in addition to the rest of the form
        if ($('#email').parsley().isValid() ||
            $('#phone').parsley().isValid() ||
            $('#fax').parsley().isValid() ||
            ($('#address-line-1').parsley().isValid() && $('#state').parsley().isValid() && $('#zipcode').parsley().isValid() && $('#city').parsley().isValid())
        ) {
            // If at least one of the fields are validated then remove required from the rest of the contact fields that aren't being filled out
            $('#city').removeAttr('data-parsley-required');
            $('#state').removeAttr('data-parsley-required');
            $('#zipcode').removeAttr('data-parsley-required');
            $('#phone').removeAttr('data-parsley-required');
            $('#fax').removeAttr('data-parsley-required');
            $('#address-line-1').removeAttr('data-parsley-required');
            $('#email').removeAttr('data-parsley-required');
        }
        else {
            // If none of the fields are valid then produce an error message and apply required fields.
            $('.contact-form-error-message').html("*At least one of the following must be filled out: Email, Phone, Fax, and/or Address (with City, State, and Zipcode)");
            $('#fax').attr('data-parsley-required', '');
            $('#phone').attr('data-parsley-required', '');
            $('#address-line-1').attr('data-parsley-required', '');
            $('#email').attr('data-parsley-required', '');
        }

        if ($("#request-file").parsley().isValid() === false) {
            $(".file-error").show();
        }
        else {
            $(".file-error").hide();
        }

        // Scroll to input label if parsley validation fails
        if ($("#request-title").parsley().isValid() === false) {
            $(window).scrollTop($(".title-label").offset().top);
        }
        else if ($("#request-description").parsley().isValid() === false) {
            $(window).scrollTop($(".description-label").offset().top);
        }
        else if ($("#request-file").parsley().isValid() === false) {
            $(".file-error").show();
            $(window).scrollTop($("#upload-control").offset().top);
        }
        else if ($("#method-received").parsley().isValid() === false) {
            $(window).scrollTop($(".format-label").offset().top);
        }
        else if ($("#first-name").parsley().isValid() === false) {
            $(window).scrollTop($(".first-name-label").offset().top);
        }
        else if ($("#last-name").parsley().isValid() === false) {
            $(window).scrollTop($(".last-name-label").offset().top);
        }
        else if ($("#email").parsley().isValid() === false) {
            $(window).scrollTop($(".email-label").offset().top);
        }
    });

    // Clear error messages for form.request_file on submit ...
    $('#submit').click(function () {
        $('.upload-error').remove();
    });
    // ... or on input change for request_file
    $('#request-file').change(function () {
        $('.upload-error').remove();
    });

    // Disable submit button on form submission
    $('#request-form').submit(function () {
        // Prevent multiple submissions
        $(this).submit(function () {
            return false;
        });
        $('#submit').hide();
        $('#processing-submission').show()
    });

    // Character count for creating a new request
    $('#request-title').keyup(function () {
        characterCounter("#title-character-count", 90, $(this).val().length)
    });

    $('#request-description').keyup(function () {
        characterCounter("#description-character-count", 5000, $(this).val().length)
    });

    $('#first-name').keyup(function () {
        characterCounter("#first-name-character-count", 32, $(this).val().length)
    });

    $('#last-name').keyup(function () {
        characterCounter("#last-name-character-count", 64, $(this).val().length)
    });

    $("#user-title").keyup(function () {
        characterCounter("#user-title-character-count", 64, $(this).val().length)
    });

    $("#user-organization").keyup(function () {
        characterCounter("#organization-character-count", 128, $(this).val().length)
    });

});
<|endoftext|>


<commit_before>var canvas;
var ctx;

var screen;
var player = { x: 0, y: 0 };
var enemies = [];

var keys = {};

var counter = 0;
var score = 0;
var highscore = 0;

function main() {
	init();

	var tick = function() {
		logic();
		render();

		setTimeout(tick, 1000/60);
	}

	var spawnNewEnemy = function() {
		addEnemy();

		setTimeout(spawnNewEnemy, 1000 * 3 - enemies.length * 50);
	}

	tick();
	setTimeout(spawnNewEnemy, 1000 * 3);
}

function init() {
	canvas = document.getElementById('main');
	ctx = canvas.getContext('2d');

	$(document).keydown(keyhandler);
	$(document).keyup(keyhandler);

	screen = { w: canvas.width, h: canvas.height };
	startGame();
}

function startGame() {
	counter = 0;
	score = 0;
	player.x = screen.w / 2;
	player.y = screen.h / 2;

	enemies = [];
	for(var i = 0; i < 3; i++) {
		addEnemy();
	}
}

function addEnemy() {
	function randomPos() {
		return {
			x: Math.random()*screen.w,
			y: Math.random()*screen.h
		};
	}

	var size = Math.floor(3 + enemies.length / 2);

	var e;
	do {
		e = randomPos();
		e.size = size;
	}
	while((Math.abs(e.x - player.x) < 50) || (Math.abs(e.y - player.y) < 50));

	enemies.push(e);
}

function keyhandler(event) {
	if(event.repeat) return;

	switch(event.which) {
		case 37: input('left', event.type === 'keydown'); break;
		case 38: input('up', event.type === 'keydown'); break;
		case 39: input('right', event.type === 'keydown'); break;
		case 40: input('down', event.type === 'keydown'); break;
	}
}

function input(key, pressed) {
	if(pressed && keys[key]) return;
	keys[key] = pressed;

	// console.log(key, pressed);
}

function logic() {
	counter++;
	score = Math.floor(counter / 60);
	highscore = Math.max(highscore, score);

	if(keys.left) player.x -= 5;
	if(keys.right) player.x += 5;
	if(keys.up) player.y -= 5;
	if(keys.down) player.y += 5;

	player.x = Math.max(0, Math.min(player.x, screen.w));
	player.y = Math.max(0, Math.min(player.y, screen.h));

	enemyLogic();
	hitEnemy();
}

function enemyLogic() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];

		dir = Math.atan2(player.y - e.y, player.x - e.x);
		e.x += Math.cos(dir) * 2;
		e.y += Math.sin(dir) * 2;
	}
}

function hitEnemy() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];

		if(Math.abs(player.x - e.x) < e.size && Math.abs(player.y - e.y) < e.size) {
			startGame();
			break;
		}
	}
}

function render() {
	ctx.fillStyle = 'black';
	ctx.fillRect(0, 0, screen.w, screen.h);

	updateScore();
	renderPlayer();
	renderEnemies();
}

function updateScore() {
	$('#score').text('' + score);
	$('#highscore').text('' + highscore);
}

function renderPlayer() {
	ctx.save();
	ctx.translate(player.x, player.y);

	ctx.fillStyle = 'red';
	ctx.fillRect(-3, -3, 6, 6);

	ctx.restore();
}

function renderEnemies() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];
		ctx.save();
		ctx.translate(e.x, e.y);

		ctx.fillStyle = 'green';
		ctx.fillRect(-e.size, -e.size, e.size*2, e.size*2);

		ctx.restore();
	}
}<commit_msg>Renamed screen var to gameScreen<commit_after>var canvas;
var ctx;

var gameScreen;
var player = { x: 0, y: 0 };
var enemies = [];

var keys = {};

var counter = 0;
var score = 0;
var highscore = 0;

function main() {
	init();

	var tick = function() {
		logic();
		render();

		setTimeout(tick, 1000/60);
	}

	var spawnNewEnemy = function() {
		addEnemy();

		setTimeout(spawnNewEnemy, 1000 * 3 - enemies.length * 50);
	}

	tick();
	setTimeout(spawnNewEnemy, 1000 * 3);
}

function init() {
	canvas = document.getElementById('main');
	ctx = canvas.getContext('2d');

	$(document).keydown(keyhandler);
	$(document).keyup(keyhandler);

	gameScreen = { w: canvas.width, h: canvas.height };
	startGame();
}

function startGame() {
	counter = 0;
	score = 0;
	player.x = gameScreen.w / 2;
	player.y = gameScreen.h / 2;

	enemies = [];
	for(var i = 0; i < 3; i++) {
		addEnemy();
	}
}

function addEnemy() {
	function randomPos() {
		return {
			x: Math.random()*gameScreen.w,
			y: Math.random()*gameScreen.h
		};
	}

	var size = Math.floor(3 + enemies.length / 2);

	var e;
	do {
		e = randomPos();
		e.size = size;
	}
	while((Math.abs(e.x - player.x) < 50) || (Math.abs(e.y - player.y) < 50));

	enemies.push(e);
}

function keyhandler(event) {
	if(event.repeat) return;

	switch(event.which) {
		case 37: input('left', event.type === 'keydown'); break;
		case 38: input('up', event.type === 'keydown'); break;
		case 39: input('right', event.type === 'keydown'); break;
		case 40: input('down', event.type === 'keydown'); break;
	}
}

function input(key, pressed) {
	if(pressed && keys[key]) return;
	keys[key] = pressed;

	// console.log(key, pressed);
}

function logic() {
	counter++;
	score = Math.floor(counter / 60);
	highscore = Math.max(highscore, score);

	if(keys.left) player.x -= 5;
	if(keys.right) player.x += 5;
	if(keys.up) player.y -= 5;
	if(keys.down) player.y += 5;

	player.x = Math.max(0, Math.min(player.x, gameScreen.w));
	player.y = Math.max(0, Math.min(player.y, gameScreen.h));

	enemyLogic();
	hitEnemy();
}

function enemyLogic() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];

		dir = Math.atan2(player.y - e.y, player.x - e.x);
		e.x += Math.cos(dir) * 2;
		e.y += Math.sin(dir) * 2;
	}
}

function hitEnemy() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];

		if(Math.abs(player.x - e.x) < e.size && Math.abs(player.y - e.y) < e.size) {
			startGame();
			break;
		}
	}
}

function render() {
	ctx.fillStyle = 'black';
	ctx.fillRect(0, 0, gameScreen.w, gameScreen.h);

	updateScore();
	renderPlayer();
	renderEnemies();
}

function updateScore() {
	$('#score').text('' + score);
	$('#highscore').text('' + highscore);
}

function renderPlayer() {
	ctx.save();
	ctx.translate(player.x, player.y);

	ctx.fillStyle = 'red';
	ctx.fillRect(-3, -3, 6, 6);

	ctx.restore();
}

function renderEnemies() {
	for(var i = 0; i < enemies.length; i++) {
		e = enemies[i];
		ctx.save();
		ctx.translate(e.x, e.y);

		ctx.fillStyle = 'green';
		ctx.fillRect(-e.size, -e.size, e.size*2, e.size*2);

		ctx.restore();
	}
}<|endoftext|>


<commit_before>const http = require('http'),
      req = require('request'),
      Promise = require('bluebird'),
      default_resp = require('./default_resp.json')
      imgur = require('./sources/imgur.js')
      async = require('async')

var port = 3000
if (process.argv.length > 2) {
  port = process.argv[2]
}

var sources = initSources()

const requestHandler = function (request, response) {
  console.log(request.method, " on ", request.url)
  if(request.method == "POST") {
    var body = "";
    request.on('data', function (chunk) {
      body += chunk;
    });
    request.on('end', function () {
      var contents = getContents(body)
      var fullUrl = decodeURIComponent(contents.response_url)
      picResponse(decodeURIComponent(contents.text)).then(function(pic){
        req.post(fullUrl, {body:pic, json:true},function(err,httpResponse,body){
          if(err || httpResponse.statusCode >= 300){
            console.log("Errors replying:")
            console.log(err)
            console.log(httpResponse.statusCode)
            console.log(body)
          }
        })
      })
    })
  }
  response.setHeader('content-type', 'application/json');
  response.end(JSON.stringify(default_resp))
}

const server = http.createServer(requestHandler)

server.listen(port, function (err) {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log('server is listening on', port)
})

function getContents(body) {
  var parts = body.split('&')
  var contents = {}
  parts.forEach(function(item) {
    var pair = item.split("=")
    contents[pair[0]] = pair[1]
  }, this);
  return contents
}

function picResponse(terms_concat) {
  var terms = terms_concat.split('+')
  var totalPics = 1
  if (terms.length > 0 && !isNaN(Number(terms[0]))){
    totalPics = terms.shift()
    console.log("Grabbing ", totalPics, "for terms ", terms)
  }
  return getOptions(terms).then(function(options){
    var pic = selectRandom(options)
    var response = {
      "response_type": "in_channel",
      "text":pic
    }
    return response
  })
}

function getOptions(terms){
  return new Promise(function(resolve, reject){
    async.concat(sources, function(source, callback){
      source.search(terms).then(function(results){
        callback(null, results)
      })
    }, function(err, results){
      if(err) {
        console.log("Error getting images from sources:", err)
        return reject(err)
      }
      resolve(results)
    })
  })
}

function initSources(){
  return [new imgur.Imgur()]
}

function selectRandom(options){
  var total = options.length
  var optionIndex = Math.floor(Math.random() * total)
  return options[optionIndex]
}
<commit_msg>Adding ip logging to investigate some fishy requests<commit_after>const http = require('http'),
      req = require('request'),
      Promise = require('bluebird'),
      default_resp = require('./default_resp.json')
      imgur = require('./sources/imgur.js')
      async = require('async')

var port = 3000
if (process.argv.length > 2) {
  port = process.argv[2]
}

var sources = initSources()

const requestHandler = function (request, response) {
  console.log(request.method, " on ", request.url, " from ", request.connection.remoteAddress)
  if(request.method == "POST") {
    var body = "";
    request.on('data', function (chunk) {
      body += chunk;
    });
    request.on('end', function () {
      var contents = getContents(body)
      var fullUrl = decodeURIComponent(contents.response_url)
      picResponse(decodeURIComponent(contents.text)).then(function(pic){
        req.post(fullUrl, {body:pic, json:true},function(err,httpResponse,body){
          if(err || httpResponse.statusCode >= 300){
            console.log("Errors replying:")
            console.log(err)
            console.log(httpResponse.statusCode)
            console.log(body)
          }
        })
      })
    })
  }
  response.setHeader('content-type', 'application/json');
  response.end(JSON.stringify(default_resp))
}

const server = http.createServer(requestHandler)

server.listen(port, function (err) {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log('server is listening on', port)
})

function getContents(body) {
  var parts = body.split('&')
  var contents = {}
  parts.forEach(function(item) {
    var pair = item.split("=")
    contents[pair[0]] = pair[1]
  }, this);
  return contents
}

function picResponse(terms_concat) {
  var terms = terms_concat.split('+')
  var totalPics = 1
  if (terms.length > 0 && !isNaN(Number(terms[0]))){
    totalPics = terms.shift()
    console.log("Grabbing ", totalPics, "for terms ", terms)
  }
  return getOptions(terms).then(function(options){
    var pic = selectRandom(options)
    var response = {
      "response_type": "in_channel",
      "text":pic
    }
    return response
  })
}

function getOptions(terms){
  return new Promise(function(resolve, reject){
    async.concat(sources, function(source, callback){
      source.search(terms).then(function(results){
        callback(null, results)
      })
    }, function(err, results){
      if(err) {
        console.log("Error getting images from sources:", err)
        return reject(err)
      }
      resolve(results)
    })
  })
}

function initSources(){
  return [new imgur.Imgur()]
}

function selectRandom(options){
  var total = options.length
  var optionIndex = Math.floor(Math.random() * total)
  return options[optionIndex]
}
<|endoftext|>


<commit_before>import React from 'react';
import {StateNavigator} from 'navigation';
import {MobileHistoryManager} from 'navigation-react-mobile';
import Grid from './Grid';
import Detail from './Detail';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

export default () => {
  const stateNavigator = new StateNavigator([
    {key: 'grid', title: 'Colors', route: ''},
    {key: 'detail', title: 'Color', trackCrumbTrail: true},
  ], new MobileHistoryManager(url => {
    var {state, data} = stateNavigator.parseLink(url);
    return stateNavigator.fluent()
      .navigate('grid')
      .navigate(state.key, data).url;
  }));

  const {grid, detail} = stateNavigator.states;
  grid.renderScene = () => <Grid colors={colors} />;
  detail.renderScene = ({color}) => <Detail colors={colors} color={color} />;

  detail.truncateCrumbTrail = (state, data, crumbs) => (
    crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs
  );

  return stateNavigator;
}
<commit_msg>Missed them from last check in<commit_after>import React from 'react';
import {StateNavigator} from 'navigation';
import Grid from './Grid';
import Detail from './Detail';

const colors = [
  'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive',
  'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black'
];

export default () => {
  const stateNavigator = new StateNavigator([
    {key: 'grid', title: 'Colors', route: ''},
    {key: 'detail', title: 'Color', trackCrumbTrail: true},
  ]);

  const {grid, detail} = stateNavigator.states;
  grid.renderScene = () => <Grid colors={colors} />;
  detail.renderScene = ({color}) => <Detail colors={colors} color={color} />;

  detail.truncateCrumbTrail = (state, data, crumbs) => (
    crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs
  );

  return stateNavigator;
}
<|endoftext|>


<commit_before>var util = require('util');
var stream = require('stream');
var PassThrough = stream.PassThrough || require('readable-stream').PassThrough;

var ansi_styles = require('./lib/ansi_styles'),
    ansi_styles_flat = {},
    color_regex = /\x1b\[[0-9;]*m/g,
    attr;

util.inherits(ANSIState, PassThrough);

// build ansi_styles_flat table object with each element of the form:
// code: [attribute, description]

for (var attr_name in ansi_styles) {
    attr = ansi_styles[attr_name];
    for (var code in attr) {
        ansi_styles_flat[code] = [attr_name, attr[code]];
    }
}

// ANSI state constructor

function ANSIState(legacy) {

    var feed = '',
        last_match = '',
        stream_match = [],
        _this = this;

    PassThrough.call(this);

    this.attrs = {};
    this.reset();
    this.is_reset = false;
    this.setEncoding('utf8');

    this.on('data', function(chunk) {
        feed += chunk;
        if (feed.indexOf('\033') === -1) {
            feed = '';
        } else {
            stream_match = feed.match(color_regex);
            if (stream_match.length > 0) {
                last_match = stream_match[stream_match.length - 1];
                feed = feed.slice(feed.lastIndexOf(last_match) + last_match.length);
                _this.updateWithArray(stream_match);
            }
        }
    });

    if (legacy !== undefined) {
        this.update(legacy);
    }
}

// ansi state prototype getter/setter properties

Object.defineProperty(ANSIState.prototype, 'code', {
    get: function() {
        return this.buildCode();
    }
});

Object.defineProperty(ANSIState.prototype, 'attributes', {
    get: function() {
        return this.attrs;
    }
});

addAliasesToPrototype(ANSIState.prototype, ansi_styles);

// ANSI state main API prototype methods

ANSIState.prototype.update = function(data) {

    if (Array.isArray(data)) {
        this.updateWithArray(data);
    } else if (typeof data === 'string') {
        this.updateWithString(data);
    } else if (data instanceof ANSIState) {
        this.updateWithState(data);
    }

    return this;
};

ANSIState.prototype.restore = function(date) {

    this.push(this.code);
    return this;
};

ANSIState.prototype.reset = function() {

    var attributes = this.attrs;

    for (var attr_name in ansi_styles) {
        attributes[attr_name] = null;
    }

    this.is_reset = true;
    this.xterm_foreground = undefined;
    this.xterm_background = undefined;

    return this;
};

// integral helper methods

ANSIState.prototype.updateWithRawArray = function(codes) {

    var code;
    this.is_reset = false;

    for (var i = 0; i < codes.length; i++) {
        code = codes[i];
        if (code === '38' || code === '48') {
            this.updateWithSpecialCode(code, codes, i);
        } else {
            this.updateWithCode(code);
        }
    }
    return this;
};

ANSIState.prototype.updateWithCode = function(code) {

    if (code === '0') {
        this.reset();
    } else {
        if (ansi_styles_flat[code]) {
            this.attrs[ansi_styles_flat[code][0]] = code;
        }
    }
    return this;
};

ANSIState.prototype.updateWithSpecialCode = function(code, codes, i) {

    switch (code) {
        case '38':
            this.xterm_foreground = xtermColor(codes, i);
            break;
        case '48':
            this.xterm_background = xtermColor(codes, i);
            break;
    }

    this.updateWithCode(code);
    return this;
};

ANSIState.prototype.updateWithState = function(ansi_state) {

    var state_attributes = ansi_state.attrs;

    if (ansi_state.is_reset === true) {
        this.is_reset = true;
        return this;
    } else {
        this.is_reset = false;
        for (var attr_name in state_attributes) {
            this.attrs[attr_name] = state_attributes[attr_name];
        }
    }

    if (ansi_state.xterm_foreground) this.xterm_foreground = ansi_state.xterm_foreground;
    if (ansi_state.xterm_background) this.xterm_background = ansi_state.xterm_background;

    return this;
};

ANSIState.prototype.updateWithArray = function(codes) {

    var code,
        codeList = [];

    if (codes !== null) {
        for (var i = 0; i < codes.length; i++) {
            code = codes[i];
            if (typeof code === 'string' && code[code.length - 1] === 'm') {
                codeList = codeList.concat(code.replace(/[\x1b\[|m]/g, '').split(';'));
            } else if (typeof code === 'number') {
                codeList.push('' + code);
            }
        }
    }

    this.updateWithRawArray(codeList);
    return this;
};

ANSIState.prototype.updateWithString = function(line) {

    var codes = line.match(color_regex),
        codeList = [],
        code;

    if (codes !== null) {
        for (var i = 0; i < codes.length; i++) {
            code = codes[i];
            codeList = codeList.concat(code.replace(/[\x1b\[|m]/g, '').split(';'));
        }
    }

    this.updateWithRawArray(codeList);

    return this;
};

ANSIState.prototype.buildCode = function() {

    var attributes = this.attrs,
        line = '\033[',
        val,
        i = 0;

    if (this.is_reset === true) {

        line += '0';

    } else {

        for (var attr_name in ansi_styles) {

            val = attributes[attr_name];

            if (val !== null) {

                if (val === '38') val += ';' + this.xterm_foreground.join(';');
                if (val === '48') val += ';' + this.xterm_background.join(';');

                line += (i === 0 ? '' : ';') + val;
                i++;
            }
        }
    }

    return line + 'm';
};

function xtermColor(codes, i) {

    var type = codes[i + 1];

    if (type === '2') {
        return codes.splice(i + 1, 4);
    } else {
        return codes.splice(i + 1, 2);
    }
}

function addAliasesToPrototype(proto, styles) {
    var propertiesObj = {};
    for (var attr in styles) {
        propertiesObj[attr] = createAliasObject(attr);
    }

    Object.defineProperties(proto, propertiesObj);
}

function createAliasObject(alias_name) {
    return {
        enumerable: true,
        get: function() {
            return ansi_styles[alias_name][this.attrs[alias_name]].toLowerCase();
        }
    };
}

module.exports = exports = ANSIState;
<commit_msg>Fixing bug when returning attribute with null value.<commit_after>var util = require('util');
var stream = require('stream');
var PassThrough = stream.PassThrough || require('readable-stream').PassThrough;

var ansi_styles = require('./lib/ansi_styles'),
    ansi_styles_flat = {},
    color_regex = /\x1b\[[0-9;]*m/g,
    attr;

util.inherits(ANSIState, PassThrough);

// build ansi_styles_flat table object with each element of the form:
// code: [attribute, description]

for (var attr_name in ansi_styles) {
    attr = ansi_styles[attr_name];
    for (var code in attr) {
        ansi_styles_flat[code] = [attr_name, attr[code]];
    }
}

// ANSI state constructor

function ANSIState(legacy) {

    var feed = '',
        last_match = '',
        stream_match = [],
        _this = this;

    PassThrough.call(this);

    this.attrs = {};
    this.reset();
    this.is_reset = false;
    this.setEncoding('utf8');

    this.on('data', function(chunk) {
        feed += chunk;
        if (feed.indexOf('\033') === -1) {
            feed = '';
        } else {
            stream_match = feed.match(color_regex);
            if (stream_match.length > 0) {
                last_match = stream_match[stream_match.length - 1];
                feed = feed.slice(feed.lastIndexOf(last_match) + last_match.length);
                _this.updateWithArray(stream_match);
            }
        }
    });

    if (legacy !== undefined) {
        this.update(legacy);
    }
}

// ansi state prototype getter/setter properties

Object.defineProperty(ANSIState.prototype, 'code', {
    get: function() {
        return this.buildCode();
    }
});

Object.defineProperty(ANSIState.prototype, 'attributes', {
    get: function() {
        return this.attrs;
    }
});

addAliasesToPrototype(ANSIState.prototype, ansi_styles);

// ANSI state main API prototype methods

ANSIState.prototype.update = function(data) {

    if (Array.isArray(data)) {
        this.updateWithArray(data);
    } else if (typeof data === 'string') {
        this.updateWithString(data);
    } else if (data instanceof ANSIState) {
        this.updateWithState(data);
    }

    return this;
};

ANSIState.prototype.restore = function(date) {

    this.push(this.code);
    return this;
};

ANSIState.prototype.reset = function() {

    var attributes = this.attrs;

    for (var attr_name in ansi_styles) {
        attributes[attr_name] = null;
    }

    this.is_reset = true;
    this.xterm_foreground = undefined;
    this.xterm_background = undefined;

    return this;
};

// integral helper methods

ANSIState.prototype.updateWithRawArray = function(codes) {

    var code;
    this.is_reset = false;

    for (var i = 0; i < codes.length; i++) {
        code = codes[i];
        if (code === '38' || code === '48') {
            this.updateWithSpecialCode(code, codes, i);
        } else {
            this.updateWithCode(code);
        }
    }
    return this;
};

ANSIState.prototype.updateWithCode = function(code) {

    if (code === '0') {
        this.reset();
    } else {
        if (ansi_styles_flat[code]) {
            this.attrs[ansi_styles_flat[code][0]] = code;
        }
    }
    return this;
};

ANSIState.prototype.updateWithSpecialCode = function(code, codes, i) {

    switch (code) {
        case '38':
            this.xterm_foreground = xtermColor(codes, i);
            break;
        case '48':
            this.xterm_background = xtermColor(codes, i);
            break;
    }

    this.updateWithCode(code);
    return this;
};

ANSIState.prototype.updateWithState = function(ansi_state) {

    var state_attributes = ansi_state.attrs;

    if (ansi_state.is_reset === true) {
        this.is_reset = true;
        return this;
    } else {
        this.is_reset = false;
        for (var attr_name in state_attributes) {
            this.attrs[attr_name] = state_attributes[attr_name];
        }
    }

    if (ansi_state.xterm_foreground) this.xterm_foreground = ansi_state.xterm_foreground;
    if (ansi_state.xterm_background) this.xterm_background = ansi_state.xterm_background;

    return this;
};

ANSIState.prototype.updateWithArray = function(codes) {

    var code,
        codeList = [];

    if (codes !== null) {
        for (var i = 0; i < codes.length; i++) {
            code = codes[i];
            if (typeof code === 'string' && code[code.length - 1] === 'm') {
                codeList = codeList.concat(code.replace(/[\x1b\[|m]/g, '').split(';'));
            } else if (typeof code === 'number') {
                codeList.push('' + code);
            }
        }
    }

    this.updateWithRawArray(codeList);
    return this;
};

ANSIState.prototype.updateWithString = function(line) {

    var codes = line.match(color_regex),
        codeList = [],
        code;

    if (codes !== null) {
        for (var i = 0; i < codes.length; i++) {
            code = codes[i];
            codeList = codeList.concat(code.replace(/[\x1b\[|m]/g, '').split(';'));
        }
    }

    this.updateWithRawArray(codeList);

    return this;
};

ANSIState.prototype.buildCode = function() {

    var attributes = this.attrs,
        line = '\033[',
        val,
        i = 0;

    if (this.is_reset === true) {

        line += '0';

    } else {

        for (var attr_name in ansi_styles) {

            val = attributes[attr_name];

            if (val !== null) {

                if (val === '38') val += ';' + this.xterm_foreground.join(';');
                if (val === '48') val += ';' + this.xterm_background.join(';');

                line += (i === 0 ? '' : ';') + val;
                i++;
            }
        }
    }

    return line + 'm';
};

function xtermColor(codes, i) {

    var type = codes[i + 1];

    if (type === '2') {
        return codes.splice(i + 1, 4);
    } else {
        return codes.splice(i + 1, 2);
    }
}

function addAliasesToPrototype(proto, styles) {
    var propertiesObj = {};
    for (var attr in styles) {
        propertiesObj[attr] = createAliasObject(attr);
    }

    Object.defineProperties(proto, propertiesObj);
}

function createAliasObject(alias_name) {
    return {
        enumerable: true,
        get: function() {
            if (this.attrs[alias_name] !== null) {
                return ansi_styles[alias_name][this.attrs[alias_name]].toLowerCase();
            }
            return null;
        }
    };
}

module.exports = exports = ANSIState;
<|endoftext|>


<commit_before>let listing, register, go, submit, learn, ocr, automate, restart, stop, exportListing;
let isAutomated = false;
let block = false;
let wordLoop = null;
let minerLoop = null;
let message, frequency;

listing = {
	"http://s0urce.io/client/img/words/easy/hwejg3.png": "stat",
	"http://s0urce.io/client/img/words/easy/h5343.png": "load",
	"http://s0urce.io/client/img/words/easy/u6jz345h.png": "signal",
	"http://s0urce.io/client/img/words/easy/gerg43643.png": "info",
	"http://s0urce.io/client/img/words/easy/5h3j5.png": "size",
	"http://s0urce.io/client/img/words/easy/gfu4643876.png": "count",
	"http://s0urce.io/client/img/words/easy/23j4d.png": "part",
	"http://s0urce.io/client/img/words/easy/ztuz2gh.png": "system",
	"http://s0urce.io/client/img/words/easy/4j22.png": "user",
	"http://s0urce.io/client/img/words/easy/i2i542.png": "reset",
	"http://s0urce.io/client/img/words/easy/rh324525.png": "list",
	"http://s0urce.io/client/img/words/easy/t342.png": "ghost",
	"http://s0urce.io/client/img/words/easy/fhj332.png": "write",
	"http://s0urce.io/client/img/words/easy/f4tr3.png": "event",
	"http://s0urce.io/client/img/words/easy/4232.png": "ping",
	"http://s0urce.io/client/img/words/easy/fge332.png": "file",
	"http://s0urce.io/client/img/words/easy/gfzu3.png": "set",
	"http://s0urce.io/client/img/words/easy/32jrh32r.png": "join",
	"http://s0urce.io/client/img/words/easy/56436u.png": "num",
	"http://s0urce.io/client/img/words/easy/jfs3231.png": "add",
	"http://s0urce.io/client/img/words/easy/bz334.png": "xml",
	"http://s0urce.io/client/img/words/easy/g45u3.png": "pass",
	"http://s0urce.io/client/img/words/easy/34h34.png": "bit",
	"http://s0urce.io/client/img/words/easy/f436fghz.png": "val",
	"http://s0urce.io/client/img/words/easy/r3r3f.png": "anon",
	"http://s0urce.io/client/img/words/easy/fej5.png": "com",
	"http://s0urce.io/client/img/words/easy/f3425.png": "temp",
	"http://s0urce.io/client/img/words/easy/gg44.png": "loop",
	"http://s0urce.io/client/img/words/easy/42j4.png": "add",
	"http://s0urce.io/client/img/words/easy/4353i.png": "call",
	"http://s0urce.io/client/img/words/easy/35d.png": "poly",
	"http://s0urce.io/client/img/words/easy/f487k.png": "client",
	"http://s0urce.io/client/img/words/easy/gg421.png": "http",
	"http://s0urce.io/client/img/words/easy/h5jz5.png": "handle",
	"http://s0urce.io/client/img/words/easy/hj5646.png": "socket",
	"http://s0urce.io/client/img/words/easy/zhg43z34.png": "data",
	"http://s0urce.io/client/img/words/easy/rnr3ur23gh325.png": "status",
	"http://s0urce.io/client/img/words/easy/f43543.png": "init",
	"http://s0urce.io/client/img/words/easy/3523ghr.png": "log",
	"http://s0urce.io/client/img/words/easy/f32.png": "buffer",
	"http://s0urce.io/client/img/words/easy/fh3rg32.png": "global",
	"http://s0urce.io/client/img/words/easy/44j.png": "upload",
	"http://s0urce.io/client/img/words/easy/fg32t.png": "get",
	"http://s0urce.io/client/img/words/easy/tu34ht.png": "key",
	"http://s0urce.io/client/img/words/easy/fjwegf2.png": "cookies",
	"http://s0urce.io/client/img/words/easy/5h.png": "url",
	"http://s0urce.io/client/img/words/easy/j3245g3.png": "root",
	"http://s0urce.io/client/img/words/easy/f4365.png": "right",
	"http://s0urce.io/client/img/words/easy/i5ut5.png": "net",
	"http://s0urce.io/client/img/words/easy/jgj4.png": "intel",
	"http://s0urce.io/client/img/words/easy/kj44.png": "remove",
	"http://s0urce.io/client/img/words/easy/gher43.png": "port",
	"http://s0urce.io/client/img/words/easy/j5675.png": "domain",
	"http://s0urce.io/client/img/words/easy/fzh32.png": "point",
	"http://s0urce.io/client/img/words/easy/grj23.png": "host",
	"http://s0urce.io/client/img/words/easy/klj52.png": "delete",
	"http://s0urce.io/client/img/words/easy/34jhg23.png": "bytes",
	"http://s0urce.io/client/img/words/easy/f34.png": "emit",
	"http://s0urce.io/client/img/words/easy/gi9846.png": "type",
	"http://s0urce.io/client/img/words/medium/3k6734.png": "encryptfile",
	"http://s0urce.io/client/img/words/medium/3jh5.png": "encrypt",
	"http://s0urce.io/client/img/words/medium/jbg5335.png": "setping",
	"http://s0urce.io/client/img/words/medium/894h.png": "encode",
	"http://s0urce.io/client/img/words/medium/j5h632.png": "download",
	"http://s0urce.io/client/img/words/easy/djk3.png": "dir",
	"http://s0urce.io/client/img/words/medium/935h.png": "setport",
	"http://s0urce.io/client/img/words/medium/5h213553.png": "serverproxy",
	"http://s0urce.io/client/img/words/medium/82365h.png": "getlog",
	"http://s0urce.io/client/img/words/hard/3k5.png": "uploaduserstats",
	"http://s0urce.io/client/img/words/medium/hg4.png": "package",
	"http://s0urce.io/client/img/words/medium/fh3.png": "gridheight",
	"http://s0urce.io/client/img/words/medium/5335jf.png": "gridwidth",
	"http://s0urce.io/client/img/words/medium/k34h63.png": "filedir",
	"http://s0urce.io/client/img/words/hard/2n52b.png": "loadregisterlist",
	"http://s0urce.io/client/img/words/hard/n3b55.png": "create3axisvector",
	"http://s0urce.io/client/img/words/hard/3v5235.png": "respondertimeout",
	"http://s0urce.io/client/img/words/hard/m3n636.png": "hostnewserver",
	"http://s0urce.io/client/img/words/hard/v235.png": "removeoldcookie",
	"http://s0urce.io/client/img/words/medium/385gh2.png": "setstats",
	"http://s0urce.io/client/img/words/medium/56j3hn.png": "getpass",
	"http://s0urce.io/client/img/words/medium/63623.png": "sizeof",
	"http://s0urce.io/client/img/words/medium/k3465jh.png": "setcookie",
	"http://s0urce.io/client/img/words/hard/l4j56.png": "decryptdatabatch",
	"http://s0urce.io/client/img/words/hard/3bv5235.png": "statusofprocess",
	"http://s0urce.io/client/img/words/hard/k32h6j.png": "rootcookieset",
	"http://s0urce.io/client/img/words/hard/bv35.png": "changeusername",
	"http://s0urce.io/client/img/words/medium/nfn3.png": "urlcheck",
	"http://s0urce.io/client/img/words/medium/74n4.png": "accountname",
	"http://s0urce.io/client/img/words/medium/l3976.png": "length",
	"http://s0urce.io/client/img/words/hard/v535.png": "getfirewallchannel",
	"http://s0urce.io/client/img/words/hard/3h25g125.png": "callmodule",
	"http://s0urce.io/client/img/words/hard/j5h35.png": "disconnectserver",
	"http://s0urce.io/client/img/words/medium/l3667.png": "filetype",
	"http://s0urce.io/client/img/words/medium/424h8.png": "hexagon",
	"http://s0urce.io/client/img/words/hard/j56b3.png": "exportconfigpackage",
	"http://s0urce.io/client/img/words/hard/3426h.png": "sizeofhexagon",
	"http://s0urce.io/client/img/words/hard/n3bv5.png": "loadloggedpassword",
	"http://s0urce.io/client/img/words/hard/n3v5b56.png": "encodenewfolder",
	"http://s0urce.io/client/img/words/hard/v42.png": "channelsetpackage",
	"http://s0urce.io/client/img/words/hard/h35g.png": "dodecahedron",
	"http://s0urce.io/client/img/words/hard/j235g23.png": "tempdatapass",
	"http://s0urce.io/client/img/words/hard/j52.png": "createnewsocket",
	"http://s0urce.io/client/img/words/hard/n234v65.png": "fileexpresslog",
	"http://s0urce.io/client/img/words/hard/njm23b632.png": "emitconfiglist",
	"http://s0urce.io/client/img/words/hard/n2356b.png": "sendintelpass",
	"http://s0urce.io/client/img/words/hard/b533252.png": "unpacktmpfile",
	"http://s0urce.io/client/img/words/hard/u254oo.png": "httpbuffersize",
	"http://s0urce.io/client/img/words/hard/jn35.png": "disconnectchannel",
	"http://s0urce.io/client/img/words/hard/n32v52.png": "getxmlprotocol",
	"http://s0urce.io/client/img/words/hard/n326.png": "wordcounter",
	"http://s0urce.io/client/img/words/hard/b626.png": "encryptunpackedbatch",
	"http://s0urce.io/client/img/words/hard/j3453.png": "deleteallids",
	"http://s0urce.io/client/img/words/hard/k23j6.png": "eventlistdir",
	"http://s0urce.io/client/img/words/hard/m3n63.png": "checkhttptype",
	"http://s0urce.io/client/img/words/medium/hj436.png": "listconfig",
	"http://s0urce.io/client/img/words/medium/sn2.png": "getping",
	"http://s0urce.io/client/img/words/medium/3k5jh3.png": "connect",
	"http://s0urce.io/client/img/words/medium/jn35b.png": "command",
	"http://s0urce.io/client/img/words/medium/5j2356h.png": "getfile",
	"http://s0urce.io/client/img/words/medium/ycmn25.png": "threat",
	"http://s0urce.io/client/img/words/medium/f3234.png": "getinfo",
	"http://s0urce.io/client/img/words/medium/h5g325.png": "getkey",
	"http://s0urce.io/client/img/words/medium/j35h5.png": "number",
	"http://s0urce.io/client/img/words/medium/v235.png": "generate",
	"http://s0urce.io/client/img/words/medium/3h5g5.png": "datatype",
	"http://s0urce.io/client/img/words/hard/n23b56.png": "includedirectory",
	"http://s0urce.io/client/img/words/hard/v51.png": "createnewpackage",
	"http://s0urce.io/client/img/words/hard/n23v55.png": "createfilethread",
	"http://s0urce.io/client/img/words/hard/m2b62.png": "getpartoffile",
	"http://s0urce.io/client/img/words/hard/mb2.png": "ghostfilesystem",
	"http://s0urce.io/client/img/words/hard/lkkj2.png": "destroybatch",
	"http://s0urce.io/client/img/words/hard/yxb24.png": "loadaltevent",
	"http://s0urce.io/client/img/words/hard/b5256.png": "changepassword",
	"http://s0urce.io/client/img/words/hard/j35g2.png": "mergesocket",
	"http://s0urce.io/client/img/words/hard/b235.png": "getmysqldomain",
	"http://s0urce.io/client/img/words/hard/mb235.png": "batchallfiles",
	"http://s0urce.io/client/img/words/hard/nv2353.png": "blockthreat",
	"http://s0urce.io/client/img/words/hard/h2v5.png": "setnewproxy",
	"http://s0urce.io/client/img/words/hard/j363.png": "getdatapassword",
	"http://s0urce.io/client/img/words/hard/fhweg.png": "patcheventlog",
	"http://s0urce.io/client/img/words/hard/k43h2.png": "systemgridtype",
	"http://s0urce.io/client/img/words/hard/bv35b23.png": "create2axisvector",
	"http://s0urce.io/client/img/words/hard/b32563.png": "removenewcookie",
	"http://s0urce.io/client/img/words/hard/vbv42.png": "bufferpingset",
	"http://s0urce.io/client/img/words/hard/f5452.png": "joinnetworkclient",
	"http://s0urce.io/client/img/words/hard/h552.png": "generatecodepack",
	"http://s0urce.io/client/img/words/hard/dnv24.png": "systemportkey",
	"http://s0urce.io/client/img/words/medium/5hj23.png": "password",
	"http://s0urce.io/client/img/words/medium/j2h512.png": "mysql",
	"http://s0urce.io/client/img/words/medium/j3k6h.png": "writefile",
	"http://s0urce.io/client/img/words/medium/78m.png": "account",
	"http://s0urce.io/client/img/words/medium/f3j3.png": "loadbytes",
	"http://s0urce.io/client/img/words/medium/8725h.png": "newserver",
	"http://s0urce.io/client/img/words/easy/gf43t.png": "send",
	"http://s0urce.io/client/img/words/easy/f4ef3.png":"left",
	"http://s0urce.io/client/img/words/medium/736h.png":"proxy",
	"http://s0urce.io/client/img/words/medium/j3252.png": "config",
	"http://s0urce.io/client/img/words/medium/35hj.png": "server",
	"http://s0urce.io/client/img/words/medium/3j2gh5.png": "response",
	"http://s0urce.io/client/img/words/medium/j35h.png": "syscall",
	"http://s0urce.io/client/img/words/medium/5h323.png": "module"
};

message = "papa bless, one love /r/javascript";
frequency = 1000;

automate = () => {
	if ($("#player-list").is(":visible") === false) {
		console.error("! Target list must be open");
		$("#desktop-list").children("img").click();
	}
	if ($("#window-shop").is(":visible") === false) {
		console.error("! Black market must be open");
		$("#desktop-shop").children("img").click();
	}
	isAutomated = true;
	const targetName = $("#player-list").children("tr").eq(0)[0].innerText;
	console.log(`* Now attacking ${targetName}`);
	$("#player-list").children("tr").eq(0)[0].click();
	$("#window-other-button").click();
	$("#window-other-port2").click();
	wordLoop = setInterval(() => {
		if (block === true) {
			return;
		}
		if ($("#targetmessage-input").is(":visible") === true) {
			// we're done!
			$("#targetmessage-input").val(message);
			$("#targetmessage-button-send").click();
			restart();
			return;
		}
		go();
	}, frequency);
	minerLoop =  = setInterval(() => {
		// first, get the status of our miners

	}, frequency);
}

restart = () => {
	stop();
	automate();
}

stop = () => {
	if (wordLoop === null && minerLoop === null) {
		console.log("! No loops to stop");
		return;
	}
	isAutomated = false;
	block = false;
	clearInterval(wordLoop);
	clearInterval(minerLoop);
	wordLoop = null;
	console.log("* Stopped loop");
}

exportListing = () => {
	console.log(JSON.stringify(listing, null, 2));
}

register = () => {
	$("#desktop-computer").children("img").on("click", (e) => {
		go();
	});
	$("#desktop-miner").children("img").on("click", (e) => {
		const word = $("#tool-type-word").val();
		learn(word);
	});
	return "* Event listeners registered!";
}

go = () => {
	console.log("* Running 'go'");
	const wordLink = $(".tool-type-img").prop("src");
	if (listing.hasOwnProperty(wordLink) === true) {
		const word = listing[wordLink];
		console.log(`* Found word: [${word}]`);
		submit(word);
		return;
	}
	console.log("* Not seen, trying OCR...");
	ocr(wordLink);
}

submit = (word) => {
	$("#tool-type-word").val(word);
	$("#tool-type-word").submit();
}

learn = (word) => {
	const wordLink = $(".tool-type-img").prop("src");
	listing[wordLink] = word;
	submit(word);
}

ocr = (url) => {
	block = true;
	$.post("http://api.ocr.space/parse/image", {
		apikey: "e3b7e80ac588957",
		language: "eng",
		url: url
	}).done((data) => {
		const word = String(data["ParsedResults"][0]["ParsedText"]).trim().toLowerCase();
		if (word.length > 3) {
			console.log(`* Got data: [${word}]`);
			$("#tool-type-word").val(word);
			if (isAutomated === true) {
				learn(word);
				block = false;
			}
		} else {
			console.log("! OCR failed");
			restart();
		}
	});
}
<commit_msg>restructured app, made listing via db<commit_after>let app;
let listing = null;
let isAutomated = false;
let block = false;
let wordLoop = null;
let minerLoop = null;
let minerStatus = [
	{
		name: "shop-basic-miner",
		value: 0
	},
	{
		name: "shop-advanced-miner",
		value: 0
	},
	{
		name: "shop-mining-drill",
		value: 0
	},
	{
		name: "shop-data-center",
		value: 0
	},
	{
		name: "shop-bot-net",
		value: 0
	},
	{
		name: "shop-quantum-server",
		value: 0
	}
];

const ocrApiKey = "e3b7e80ac588957";
const db = "https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json";
const message = "papa bless, one love /r/javascript";
const frequency = 1250;
const minerLevel = 20;

app = {
	downloadListing: () => {
		$.get("https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json").done((data) => {
			listing = JSON.parse(data);
		});
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	automate: () => {
		// first check the windows are open, and open them if they aren't
		if ($("#player-list").is(":visible") === false) {
			console.error("! Target list must be open");
			$("#desktop-list").children("img").click();
		}
		if ($("#window-shop").is(":visible") === false) {
			console.error("! Black market must be open");
			$("#desktop-shop").children("img").click();
		}
		isAutomated = true;
		// start by getting the first target in the list
		const targetName = $("#player-list").children("tr").eq(0)[0].innerText;
		console.log(`* Now attacking ${targetName}`);
		// click it, and then hack, and then port b
		$("#player-list").children("tr").eq(0)[0].click();
		$("#window-other-button").click();
		// do a check for money
		const portStyle = $("#window-other-port2").attr("style");
		if (portStyle.indexOf("opacity: 1") === -1) {
			// this port costs too much, let's wait a bit
			console.log("* Hack too expensive, waiting");
			setTimeout(app.automate, frequency);
		}
		$("#window-other-port2").click();
		// start the loop that does the guessing
		wordLoop = setInterval(app.loops.word, frequency);
		// start the loop for btc monitoring
		minerLoop = setInterval(app.loops.miner, frequency);
	},

	loops: {
		word: () => {
			if (block === true) {
				return;
			}
			if ($("#targetmessage-input").is(":visible") === true) {
				// we're done!
				$("#targetmessage-input").val(message);
				$("#targetmessage-button-send").click();
				app.restart();
				return;
			}
			app.go();
		},
		miner: () => {
			// first, get the status of our miners
			for (const miner of minerStatus) {
				// set value
				miner.value = parseInt($(`#${miner.name}-amount`).text());
				// this is available to buy
				if ($(`#${miner.name}`).attr("style") === "opacity: 1;") {
					if (miner.value < minerLevel) {
						// we should buy this
						$(`#${miner.name}`).click();
					}
				}
			}
		}
	},

	restart: () => {
		app.stop();
		app.automate();
	},

	stop: () => {
		if (wordLoop === null && minerLoop === null) {
			console.log("! No loops to stop");
			return;
		}
		isAutomated = false;
		block = false;
		clearInterval(wordLoop);
		clearInterval(minerLoop);
		wordLoop = null;
		console.log("* Stopped loop");
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	go: () => {
		console.log("* Running 'go'");
		const wordLink = $(".tool-type-img").prop("src");
		if (listing.hasOwnProperty(wordLink) === true) {
			const word = listing[wordLink];
			console.log(`* Found word: [${word}]`);
			app.submit(word);
			return;
		}
		console.log("* Not seen, trying OCR...");
		app.ocr(wordLink);
	},

	submit: (word) => {
		$("#tool-type-word").val(word);
		$("#tool-type-word").submit();
	},

	learn: (word) => {
		const wordLink = $(".tool-type-img").prop("src");
		listing[wordLink] = word;
		app.submit(word);
	},

	ocr: (url) => {
		block = true;
		$.post("http://api.ocr.space/parse/image", {
			apikey: ocrApiKey,
			language: "eng",
			url: url
		}).done((data) => {
			const word = String(data["ParsedResults"][0]["ParsedText"]).trim().toLowerCase();
			if (word.length > 3) {
				console.log(`* Got data: [${word}]`);
				$("#tool-type-word").val(word);
				if (isAutomated === true) {
					app.learn(word);
					block = false;
				}
			} else {
				console.log("! OCR failed");
				app.restart();
			}
		});
	}
};
<|endoftext|>


<commit_before>var fs = require("fs");
var normalizeOptions = require("./lib/options").normalize;
var types = require("./lib/types");
var parse = require("./lib/parser").parse;
var Printer = require("./lib/printer").Printer;

function print(node, options) {
    return new Printer(options).print(node);
}

function prettyPrint(node, options) {
    return new Printer(options).printGenerically(node);
}

function run(transformer, options) {
    return runFile(process.argv[2], transformer, options);
}

function runFile(path, transformer, options) {
    fs.readFile(path, "utf-8", function(err, code) {
        if (err) {
            console.error(err);
            return;
        }

        runString(code, transformer, options);
    });
}

function runString(code, transformer, options) {
    options = normalizeOptions(options);
    transformer(parse(code, options), function(node) {
        var output = print(node, options);
        if (options.writeback) {
            options.writeback(output);
        } else {
            process.stdout.write(output);
        }
    });
}

Object.defineProperties(exports, {
    /**
     * Scriptable interface to recast.
     */
    run: {
        enumerable: true,
        value: run
    },

    runFile: {
        enumerable: true,
        value: runFile
    },

    runString: {
        enumerable: true,
        value: runString
    },

    /**
     * Useful utilities for implementing transformer functions.
     */
    Syntax: {
        enumerable: true,
        value: types.Syntax,
    },

    Visitor: {
        enumerable: true,
        value: require("./lib/visitor").Visitor
    },

    builder: { // Legacy singular form.
        enumerable: false,
        value: types.builders
    },

    builders: { // Plural preferred.
        enumerable: true,
        value: types.builders
    },

    namedTypes: {
        enumerable: true,
        value: types.namedTypes
    },

    /**
     * Direct access to the parsing and printing interfaces.
     */
    parse: {
        enumerable: true,
        value: parse
    },

    print: {
        enumerable: true,
        value: print
    },

    prettyPrint: {
        enumerable: true,
        value: prettyPrint
    }
});
<commit_msg>Don't clobber options.writeback by calling normalizeOptions too soon.<commit_after>var fs = require("fs");
var normalizeOptions = require("./lib/options").normalize;
var types = require("./lib/types");
var parse = require("./lib/parser").parse;
var Printer = require("./lib/printer").Printer;

function print(node, options) {
    return new Printer(options).print(node);
}

function prettyPrint(node, options) {
    return new Printer(options).printGenerically(node);
}

function run(transformer, options) {
    return runFile(process.argv[2], transformer, options);
}

function runFile(path, transformer, options) {
    fs.readFile(path, "utf-8", function(err, code) {
        if (err) {
            console.error(err);
            return;
        }

        runString(code, transformer, options);
    });
}

function defaultWriteback(output) {
    process.stdout.write(output);
}

function runString(code, transformer, options) {
    var writeback = options.writeback || defaultWriteback;
    transformer(parse(code, options), function(node) {
        writeback(print(node, options));
    });
}

Object.defineProperties(exports, {
    /**
     * Scriptable interface to recast.
     */
    run: {
        enumerable: true,
        value: run
    },

    runFile: {
        enumerable: true,
        value: runFile
    },

    runString: {
        enumerable: true,
        value: runString
    },

    /**
     * Useful utilities for implementing transformer functions.
     */
    Syntax: {
        enumerable: true,
        value: types.Syntax,
    },

    Visitor: {
        enumerable: true,
        value: require("./lib/visitor").Visitor
    },

    builder: { // Legacy singular form.
        enumerable: false,
        value: types.builders
    },

    builders: { // Plural preferred.
        enumerable: true,
        value: types.builders
    },

    namedTypes: {
        enumerable: true,
        value: types.namedTypes
    },

    /**
     * Direct access to the parsing and printing interfaces.
     */
    parse: {
        enumerable: true,
        value: parse
    },

    print: {
        enumerable: true,
        value: print
    },

    prettyPrint: {
        enumerable: true,
        value: prettyPrint
    }
});
<|endoftext|>


<commit_before>// Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
    grunt.config('watch', {
        icons: {
            files: 'fontello.json',
            tasks: ['fontello:build'],
            options: {
                atBegin: true,
                livereload: false
            }
        },
        js: {
            files: ['scripts/main.js'],
            tasks: ['concat'],
            options: {
                atBegin: true,
                livereload: true
            }
        },
        assemble: {
            files: ['*.hbs', 'src/inc/*.hbs', 'src/tpl/*.hbs'],
            tasks: ['assemble:dev'],
            options: {
                atBegin: true,
                livereload: false
            }
        },
        html: {
            files: ['*.html'],
            tasks: [],
            options: {
                atBegin: false,
                livereload: true
            }
        },
        scss: {
            files: 'scss/**/*.scss',
            tasks: ['sass:dev', 'autoprefixer:dev'],
            options: {
                atBegin: true,
                livereload: false
            }
        },
        css: {
            files: 'styles/*.css',
            tasks: [],
            options: {
                atBegin: false,
                livereload: true
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
};
<commit_msg>Also watch on Handlebars files<commit_after>// Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
    grunt.config('watch', {
        icons: {
            files: 'fontello.json',
            tasks: ['fontello:build'],
            options: {
                atBegin: true,
                livereload: false
            }
        },
        js: {
            files: ['scripts/main.js'],
            tasks: ['concat'],
            options: {
                atBegin: true,
                livereload: true
            }
        },
        assemble: {
            files: ['*.hbs', 'src/inc/*.hbs', 'src/tpl/*.hbs'],
            tasks: ['assemble:dev'],
            options: {
                atBegin: true,
                livereload: true
            }
        },
        html: {
            files: ['*.html'],
            tasks: [],
            options: {
                atBegin: false,
                livereload: true
            }
        },
        scss: {
            files: 'scss/**/*.scss',
            tasks: ['sass:dev', 'autoprefixer:dev'],
            options: {
                atBegin: true,
                livereload: false
            }
        },
        css: {
            files: 'styles/*.css',
            tasks: [],
            options: {
                atBegin: false,
                livereload: true
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
};
<|endoftext|>


<commit_before>module.exports = atom

function atom(write, read) {
  return function reactor(changes, options) {
    var entity = write(changes, options)
    if (read) {
      return read(entity, options)
    }
  }
}
<commit_msg>add docs to atom<commit_after>module.exports = atom

/*
    Atom produces a `reactor` function out of given `write` function
    responsible for applying state changes to a single entity of the atom
    and a `read` function that is responsible for reading state changes caused
    by interaction with that entity.

    In case of UI component is likely to be a widget. Given `write` function
    will reflect changes to the view of that widget while `read` function will
    map user interaction events to that widget into state changes.
*/
function atom(write, read) {
  return function reactor(changes, options) {
    var entity = write(changes, options)
    if (read) {
      return read(entity, options)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const request = require('request');
const Web3 = require('web3');

const config = require('../config');
const dealHelpers = require('../deals/helpers');
const lib = require('./lib');
const userHelpers = require('../users/helpers');

const web3 = new Web3();

web3.setProvider(new web3.providers.HttpProvider(config.getGethUrl()));

const ABI = fs.readFileSync(__dirname + "/ABI.txt", "utf8").trim();
const address = fs.readFileSync(__dirname + "/contractAddress.txt", "utf8").trim();

const blockchainContract = web3.eth.contract(JSON.parse(ABI)).at(address.trim());

const createDealEvent = blockchainContract.createDealEvent((error, result) => {
  if (!error) {
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");

    const ethereumId = result.args.deal_id.toString();
    const borrowerId = result.args.borrower.replace('0x', ''); // remove `0x` from the start of the string
    const lenderId = result.args.lender.replace('0x', ''); // remove `0x` from the start of the string
    const txId = result.transactionHash;

    const status = 'created';

    const attributes = {
      ethereumId,
      lenderId,
      borrowerId,
      status,
      txId,
    };
    console.log("\n\n", attributes, "\n\n");
    // create deal in DB
    request.post(config.getURL() + '/api/deals').form(attributes);
    // send notification
      // get borrower's firebase id from db to post to
    const where = {
      ethAccount: attributes.borrowerId
    };
    let to = null;

    userHelpers.findUser(where, (err, user) => {
      if (err) {
        console.error(err);
      } else {
        to = user.firebaseToken;
        lib.notify(to, {data: result});
      };
    });

  } else {
    console.error(error);
  }
});

const acceptDealEvent = blockchainContract.acceptDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");

    const ethereumId = result.args.deal_id.toString();
    const txId = result.transactionHash;

    const data = JSON.parse(result.args.data);
    const borrowerId = data.to.replace('0x', '');
    const lenderId = data.from.replace('0x', '');

    const status = 'accepted';

    const attributes = {
      status,
      txId
    };

    // find and update deal in DB
    request(config.getURL() + '/api/deals/?ethereumId=' + ethereumId, (err, response, body) => {
      if (err) {
        console.error(err);
      } else {
        const id = body[0]._id;
        request.post(config.getURL() + '/api/deals/' + id).form(attributes);
      }
    });

    // notify user
    const where = {
      ethAccount: lenderId
    };
    let to = null;

    userHelpers.findUser(where, (err, user) => {
      if (err) {
        console.error(err);
      } else {
        to = user.firebaseToken;
        lib.notify(to, {data: result});
      };
    });
  } else {
    console.error(error);
  }

});

const settleDealEvent = blockchainContract.settleDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");
  }
});

const acceptSettleDealEvent = blockchainContract.acceptSettleDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");
  }
});

module.exports = {};
<commit_msg>Refactored acceptDealEvent<commit_after>'use strict';

const fs = require('fs');
const request = require('request');
const Web3 = require('web3');

const config = require('../config');
const dealHelpers = require('../deals/helpers');
const lib = require('./lib');
const userHelpers = require('../users/helpers');

const web3 = new Web3();

web3.setProvider(new web3.providers.HttpProvider(config.getGethUrl()));

const ABI = fs.readFileSync(__dirname + "/ABI.txt", "utf8").trim();
const address = fs.readFileSync(__dirname + "/contractAddress.txt", "utf8").trim();

const blockchainContract = web3.eth.contract(JSON.parse(ABI)).at(address.trim());

const createDealEvent = blockchainContract.createDealEvent((error, result) => {
  if (!error) {
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");

    const ethereumId = result.args.deal_id.toString();
    const borrowerId = result.args.borrower.replace('0x', ''); // remove `0x` from the start of the string
    const lenderId = result.args.lender.replace('0x', ''); // remove `0x` from the start of the string
    const txId = result.transactionHash;

    const status = 'created';

    const attributes = {
      ethereumId,
      lenderId,
      borrowerId,
      status,
      txId,
    };
    console.log("\n\n", attributes, "\n\n");
    // create deal in DB
    request.post(config.getURL() + '/api/deals').form(attributes);
    // send notification
      // get borrower's firebase id from db to post to
    const where = {
      ethAccount: attributes.borrowerId
    };
    let to = null;

    userHelpers.findUser(where, (err, user) => {
      if (err) {
        console.error(err);
      } else {
        to = user.firebaseToken;
        lib.notify(to, {data: result});
      };
    });

  } else {
    console.error(error);
  }
});

const acceptDealEvent = blockchainContract.acceptDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");

    const ethereumId = result.args.deal_id.toString();
    const txId = result.transactionHash;

    const data = JSON.parse(result.args.data);
    const borrowerId = data.to.replace('0x', '');
    const lenderId = data.from.replace('0x', '');

    const status = 'accepted';

    const attributes = {
      status,
      txId
    };

    // find and update deal in DB
    request(config.getURL() + '/api/deals/?ethereumId=' + ethereumId, (err, response, body) => {
      if (err) {
        console.error(err);
      } else {
        const id = body[0]._id;
        request.post(config.getURL() + '/api/deals/' + id).form(attributes);

        // notify user
        const where = {
          ethAccount: lenderId
        };
        let to = null;

        userHelpers.findUser(where, (err, user) => {
          if (err) {
            console.error(err);
          } else {
            to = user.firebaseToken;
            lib.notify(to, {data: result});
          };
        });
      }
    });
  } else {
    console.error(error);
  }

});

const settleDealEvent = blockchainContract.settleDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");
  }
});

const acceptSettleDealEvent = blockchainContract.acceptSettleDealEvent((error, result) => {
  if (!error) {
    console.log(result + "\n");
    console.log(JSON.stringify(result) + "\n");
    console.log(JSON.stringify(result.args) + "\n");
  }
});

module.exports = {};
<|endoftext|>


<commit_before>/* eslint strict: 0 */
'use strict';

const electron = require('electron');

const {app, BrowserWindow, crashReporter, Menu, shell} = electron;

let menu;
let template;
let mainWindow = null;

var pkg = require('./package.json');

const {companyName, productName} = pkg;

crashReporter.start(
	{
		productName,
		companyName,
		submitURL: 'https://your-domain.com/url-to-submit',
		autoSubmit: true
	}
);

process.env.NODE_ENV = process.env.NODE_ENV || 'production';

var {NODE_ENV} = process.env;

var DEV_ENV = NODE_ENV === 'development';

require('electron-debug')(
	{
		enabled: true,
		showDevTools: DEV_ENV
	}
);

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') app.quit();
});

app.on('ready', function() {
	var electronScreen = electron.screen;

	var size = electronScreen.getPrimaryDisplay().workAreaSize;

	global.USER_PREFS_PATH = app.getPath('userData');

	electron.ipcMain.on(
		'userPrefsPath',
		(event, arg) => {
			event.returnValue = global.USER_PREFS_PATH;
		}
	);

	var windowConfig = {
		height: size.height,
		resizable: true,
		width: 768
	};

	if (DEV_ENV) {
		// Account for the devtools being open
		windowConfig.width = Math.min(1400, size.width);
	}

	mainWindow = new BrowserWindow(windowConfig);

	mainWindow.loadURL(`file://${__dirname}/app/app.html`);

	var webContents = mainWindow.webContents;

	mainWindow.on(
		'closed',
		() => {
			mainWindow = null;
		}
	);

	if (process.platform === 'darwin') {
		template = [{
			label: productName,
			submenu: [
			{
				label: `About ${productName}`,
				selector: 'orderFrontStandardAboutPanel:'
			},
			{type: 'separator'},
			{
				label: 'Services',
				submenu: []
			},
			{type: 'separator'},
			{
				label: `Hide ${productName}`,
				accelerator: 'Command+H',
				selector: 'hide:'
			},
			{
				label: 'Hide Others',
				accelerator: 'Command+Shift+H',
				selector: 'hideOtherApplications:'
			},
			{
				label: 'Show All',
				selector: 'unhideAllApplications:'
			},
			{type: 'separator'},
			{
				label: 'Quit',
				accelerator: 'Command+Q',
				click() {
					app.quit();
				}
			}]
		},
		{
			label: 'Edit',
			submenu: [
			{
				label: 'Undo',
				accelerator: 'Command+Z',
				selector: 'undo:'
			},
			{
				label: 'Redo',
				accelerator: 'Shift+Command+Z',
				selector: 'redo:'
			},
			{type: 'separator'},
			{
				label: 'Cut',
				accelerator: 'Command+X',
				selector: 'cut:'
			},
			{
				label: 'Copy',
				accelerator: 'Command+C',
				selector: 'copy:'
			},
			{
				label: 'Paste',
				accelerator: 'Command+V',
				selector: 'paste:'
			},
			{
				label: 'Select All',
				accelerator: 'Command+A',
				selector: 'selectAll:'
			}]
		},
		{
			label: 'View',
			submenu: [
			{
				label: 'Reload',
				accelerator: 'Command+R',
				click() {
					mainWindow.restart();
				}
			},
			{
				label: 'Toggle Full Screen',
				accelerator: 'Ctrl+Command+F',
				click() {
					mainWindow.setFullScreen(!mainWindow.isFullScreen());
				}
			},
			{
				label: 'Toggle Developer Tools',
				accelerator: 'Alt+Command+I',
				click() {
					if (webContents.isDevToolsOpened()) {
						webContents.closeDevTools();
					}
					else {
						webContents.openDevTools({
							detach: true
						});
					}
				}
			}]
		},
		{
			label: 'Window',
			submenu: [
			{
				label: 'Minimize',
				accelerator: 'Command+M',
				selector: 'performMiniaturize:'
			},
			{
				label: 'Close',
				accelerator: 'Command+W',
				selector: 'performClose:'
			},
			{type: 'separator'},
			{
				label: 'Bring All to Front',
				selector: 'arrangeInFront:'
			}]
		},
		{
			label: 'Help',
			submenu: [
			{
				label: 'Learn More',
				click() {
					shell.openExternal('http://electron.atom.io');
				}
			},
			{
				label: 'Documentation',
				click() {
					shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
				}
			},
			{
				label: 'Community Discussions',
				click() {
					shell.openExternal('https://discuss.atom.io/c/electron');
				}
			},
			{
				label: 'Search Issues',
				click() {
					shell.openExternal('https://github.com/atom/electron/issues');
				}
			}]
		}];

		menu = Menu.buildFromTemplate(template);
		Menu.setApplicationMenu(menu);
	} else {
		template = [{
			label: '&File',
			submenu: [
			{
				label: '&Open',
				accelerator: 'Ctrl+O'
			},
			{
				label: '&Close',
				accelerator: 'Ctrl+W',
				click() {
					mainWindow.close();
				}
			}]
		},
		{
			label: '&View',
			submenu: [
			{
				label: '&Reload',
				accelerator: 'Ctrl+R',
				click() {
					mainWindow.restart();
				}
			},
			{
				label: 'Toggle &Full Screen',
				accelerator: 'F11',
				click() {
					mainWindow.setFullScreen(!mainWindow.isFullScreen());
				}
			},
			{
				label: 'Toggle &Developer Tools',
				accelerator: 'Alt+Ctrl+I',
				click() {
					webContents.toggleDevTools();
				}
			}]
		},
		{
			label: 'Help',
			submenu: [
			{
				label: 'Learn More',
				click() {
					shell.openExternal('http://electron.atom.io');
				}
			},
			{
				label: 'Documentation',
				click() {
					shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
				}
			},
			{
				label: 'Community Discussions',
				click() {
					shell.openExternal('https://discuss.atom.io/c/electron');
				}
			},
			{
				label: 'Search Issues',
				click() {
					shell.openExternal('https://github.com/atom/electron/issues');
				}
			}]
		}];
		menu = Menu.buildFromTemplate(template);
		mainWindow.setMenu(menu);
	}
});<commit_msg>Remove crash reporter<commit_after>/* eslint strict: 0 */
'use strict';

const electron = require('electron');

const {app, BrowserWindow, Menu, shell} = electron;

let menu;
let template;
let mainWindow = null;

var pkg = require('./package.json');

const {productName} = pkg;

process.env.NODE_ENV = process.env.NODE_ENV || 'production';

var {NODE_ENV} = process.env;

var DEV_ENV = NODE_ENV === 'development';

require('electron-debug')(
	{
		enabled: true,
		showDevTools: DEV_ENV
	}
);

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') app.quit();
});

app.on('ready', function() {
	var electronScreen = electron.screen;

	var size = electronScreen.getPrimaryDisplay().workAreaSize;

	global.USER_PREFS_PATH = app.getPath('userData');

	electron.ipcMain.on(
		'userPrefsPath',
		(event, arg) => {
			event.returnValue = global.USER_PREFS_PATH;
		}
	);

	var windowConfig = {
		height: size.height,
		resizable: true,
		width: 768
	};

	if (DEV_ENV) {
		// Account for the devtools being open
		windowConfig.width = Math.min(1400, size.width);
	}

	mainWindow = new BrowserWindow(windowConfig);

	mainWindow.loadURL(`file://${__dirname}/app/app.html`);

	var webContents = mainWindow.webContents;

	mainWindow.on(
		'closed',
		() => {
			mainWindow = null;
		}
	);

	if (process.platform === 'darwin') {
		template = [{
			label: productName,
			submenu: [
			{
				label: `About ${productName}`,
				selector: 'orderFrontStandardAboutPanel:'
			},
			{type: 'separator'},
			{
				label: 'Services',
				submenu: []
			},
			{type: 'separator'},
			{
				label: `Hide ${productName}`,
				accelerator: 'Command+H',
				selector: 'hide:'
			},
			{
				label: 'Hide Others',
				accelerator: 'Command+Shift+H',
				selector: 'hideOtherApplications:'
			},
			{
				label: 'Show All',
				selector: 'unhideAllApplications:'
			},
			{type: 'separator'},
			{
				label: 'Quit',
				accelerator: 'Command+Q',
				click() {
					app.quit();
				}
			}
			].concat(
				DEV_ENV ?
				[
					{type: 'separator'},
					{
						label: 'Crash Main Process',
						click() {
							process.crash();
						}
					}
				]
				:
				[]

			)
		},
		{
			label: 'Edit',
			submenu: [
			{
				label: 'Undo',
				accelerator: 'Command+Z',
				selector: 'undo:'
			},
			{
				label: 'Redo',
				accelerator: 'Shift+Command+Z',
				selector: 'redo:'
			},
			{type: 'separator'},
			{
				label: 'Cut',
				accelerator: 'Command+X',
				selector: 'cut:'
			},
			{
				label: 'Copy',
				accelerator: 'Command+C',
				selector: 'copy:'
			},
			{
				label: 'Paste',
				accelerator: 'Command+V',
				selector: 'paste:'
			},
			{
				label: 'Select All',
				accelerator: 'Command+A',
				selector: 'selectAll:'
			}]
		},
		{
			label: 'View',
			submenu: [
			{
				label: 'Reload',
				accelerator: 'Command+R',
				click() {
					mainWindow.restart();
				}
			},
			{
				label: 'Toggle Full Screen',
				accelerator: 'Ctrl+Command+F',
				click() {
					mainWindow.setFullScreen(!mainWindow.isFullScreen());
				}
			},
			{
				label: 'Toggle Developer Tools',
				accelerator: 'Alt+Command+I',
				click() {
					if (webContents.isDevToolsOpened()) {
						webContents.closeDevTools();
					}
					else {
						webContents.openDevTools({
							detach: true
						});
					}
				}
			}]
		},
		{
			label: 'Window',
			submenu: [
			{
				label: 'Minimize',
				accelerator: 'Command+M',
				selector: 'performMiniaturize:'
			},
			{
				label: 'Close',
				accelerator: 'Command+W',
				selector: 'performClose:'
			},
			{type: 'separator'},
			{
				label: 'Bring All to Front',
				selector: 'arrangeInFront:'
			}]
		},
		{
			label: 'Help',
			submenu: [
			{
				label: 'Learn More',
				click() {
					shell.openExternal('http://electron.atom.io');
				}
			},
			{
				label: 'Documentation',
				click() {
					shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
				}
			},
			{
				label: 'Community Discussions',
				click() {
					shell.openExternal('https://discuss.atom.io/c/electron');
				}
			},
			{
				label: 'Search Issues',
				click() {
					shell.openExternal('https://github.com/atom/electron/issues');
				}
			}]
		}];

		menu = Menu.buildFromTemplate(template);
		Menu.setApplicationMenu(menu);
	} else {
		template = [{
			label: '&File',
			submenu: [
			{
				label: '&Open',
				accelerator: 'Ctrl+O'
			},
			{
				label: '&Close',
				accelerator: 'Ctrl+W',
				click() {
					mainWindow.close();
				}
			}]
		},
		{
			label: '&View',
			submenu: [
			{
				label: '&Reload',
				accelerator: 'Ctrl+R',
				click() {
					mainWindow.restart();
				}
			},
			{
				label: 'Toggle &Full Screen',
				accelerator: 'F11',
				click() {
					mainWindow.setFullScreen(!mainWindow.isFullScreen());
				}
			},
			{
				label: 'Toggle &Developer Tools',
				accelerator: 'Alt+Ctrl+I',
				click() {
					webContents.toggleDevTools();
				}
			}]
		},
		{
			label: 'Help',
			submenu: [
			{
				label: 'Learn More',
				click() {
					shell.openExternal('http://electron.atom.io');
				}
			},
			{
				label: 'Documentation',
				click() {
					shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
				}
			},
			{
				label: 'Community Discussions',
				click() {
					shell.openExternal('https://discuss.atom.io/c/electron');
				}
			},
			{
				label: 'Search Issues',
				click() {
					shell.openExternal('https://github.com/atom/electron/issues');
				}
			}]
		}];
		menu = Menu.buildFromTemplate(template);
		mainWindow.setMenu(menu);
	}
});<|endoftext|>