<commit_before>var app = angular.module("poolApp", []);
app.controller("MainController", function($scope) {
    $scope.poolbase = [ {
        title: "Google",
        tags: "googling tips",
        links: [ {
            name: "Google efficiently",
            href: "http://www.makeuseof.com/tag/google-power-user/"
        } ]
    },{
        title: "Technical Interview Q&A",
        tags: "interviews questions tr technical awesome",
        links: [ {
            name: "Awesome Interviews",
            href: "https://github.com/MaximAbramchuck/awesome-interviews"
        } ]
    }, {
        title: "Html/Html5",
        tags: "markup",
        links: [ {
            name: "Introduction to HTML",
            href: "https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Introduction#History_of_HTML"
        }, {
            name: "Learn HTML",
            href: "http://learn.shayhowe.com/html-css/getting-to-know-html/"
        }, {
            name: "HTML5 in 5 mins",
            href: "https://msdn.microsoft.com/en-us/hh549253.aspx"
        }, {
            name: "More about HTML5",
            href: "https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5"
        }, {
            name: "HTML5-Canvas tutorial",
            href: "http://www.html5canvastutorials.com/"
        }, {
            name: "HTML5 + your browser compatibility",
            href: "https://html5test.com/"
        } ]
    }, {
        title: "Free Responsive Web Templates",
        tags: "website webpage",
        links: [ {
            name: "HTML5UP",
            href: "http://html5up.net/"
        }, {
            name: "Get Template",
            href: "http://www.gettemplate.com/"
        }, {
            name: "Foundation Templates",
            href: "http://foundation.zurb.com/templates.html"
        }, {
            name: "Bootstrap Templates",
            href: "http://startbootstrap.com/template-categories/all/"
        } ]
    }, {
        title: "Css/Css3",
        tags: "flex,styling,layout",
        links: [ {
            name: "Learn CSS",
            href: "http://learn.shayhowe.com/html-css/getting-to-know-css/"
        }, {
            name: "Learn Layout",
            href: "http://learnlayout.com/"
        }, {
            name: "CSS Properties",
            href: "http://www.cssportal.com/css-properties/index.php"
        }, {
            name: "30 CSS selectors to remember",
            href: "http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048"
        }, {
            name: "Game on CSS selectors",
            href: "http://flukeout.github.io/"
        }, {
            name: "Game on CSS3 Flexbox",
            href: "http://flexboxfroggy.com/"
        }, {
            name: "Link vs Import",
            href: "https://www.stevesouders.com/blog/2009/04/09/dont-use-import/"
        } ]
    }, {
        title: "Choosing color for text",
        tags: "colors",
        links: [ {
            name: "Choose right color",
            href: "http://colorsafe.co/"
        }, {
            name: "Pick color online",
            href: "http://colourco.de/"
        } ]
    }, {
        title: "Css Generators",
        tags: "generator",
        links: [ {
            name: "Online CSS3 generator",
            href: "http://enjoycss.com/"
        }, {
            name: "CSS Matic",
            href: "http://www.cssmatic.com/"
        }, {
            name: "Generate CSS arrow",
            href: "http://cssarrowplease.com/"
        }, {
            name: "CSS Shapes",
            href: "https://css-tricks.com/examples/ShapesOfCSS/"
        }, {
            name: "CSS gradient generator",
            href: "http://www.colorzilla.com/gradient-editor/"
        } ]
    }, {
        title: "Css Frameworks",
        tags: "frameworks",
        links: [ {
            name: "Bootstrap",
            href: "http://getbootstrap.com/"
        }, {
            name: "Foundation",
            href: "http://foundation.zurb.com/"
        }, {
            name: "Metro UI",
            href: "http://metroui.org.ua/"
        }, {
            name: "Furtive-CSS micro framework",
            href: "http://furtive.co/"
        } ]
    }, {
        title: "JavaScript",
        tags: "js,ecmascript,es5",
        links: [ {
            name: "Essential JavaScript",
            href: "http://javascript.info/"
        }, {
            name: "All about JavaScript",
            href: "http://jstherightway.org/"
        }, {
            name: "JavaScript Standards",
            href: "http://bguiz.github.io/js-standards/intro/"
        }, {
            name: "Interactive way to learn JS",
            href: "http://www.codecademy.com/en/tracks/javascript"
        }, {
            name: "JavaScript Styleguide",
            href: "https://github.com/airbnb/javascript"
        }, {
            name: "Learn Object oriented JavaScript",
            href: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript"
        }, {
            name: "Javascript Design Patterns",
            href: "https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know"
        }, {
            name: "Javascript Char codes",
            href: "http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes"
        }, {
            name: "jsPerf - compare js snippets ",
            href: "https://jsperf.com/"
        } ]
    }, {
        title: "Javascript Libraries",
        tags: "js jquery",
        links: [ {
            name: "Interactive way to learn jQuery",
            href: "http://try.jquery.com/"
        } ]
    }, {
        title: "AngularJS",
        tags: "js,javascript frameworks,ajs",
        links: [ {
            name: "AngularJS Guidelines",
            href: "http://bguiz.github.io/js-standards/angularjs/single-responsibility/"
        }, {
            name: "Angular StyleGuide",
            href: "https://github.com/johnpapa/angular-styleguide/tree/master/a1"
        }, {
            name: "AngularJS in 60minutes",
            href: "http://fastandfluid.com/publicdownloads/AngularJSIn60MinutesIsh_DanWahlin_May2013.pdf"
        }, {
            name: "AngularJS examples",
            href: "http://tutorialzine.com/2013/08/learn-angularjs-5-examples/"
        } ]
    }, {
        title: "Regular Expressions",
        tags: "regex",
        links: [ {
            name: "Regexone - learn interactively",
            href: "http://regexone.com/"
        }, {
            name: "Online Regex builder",
            href: "http://regexr.com/"
        } ]
    }, {
        title: "Learn Command Line Interface",
        tags: "cli cmd",
        links: [ {
            name: "Learn CLI the hard way",
            href: "http://cli.learncodethehardway.org/book/"
        } ]
    }, {
        title: "Introduction to programming",
        tags: "beginner coding",
        links: [ {
            name: "Lets Play the game",
            href: "http://learn.code.org/hoc/1"
        } ]
    }, {
        title: "One stop for programming",
        tags: "code learn api",
        links: [ {
            name: "Learn X in Y minutes",
            href: "http://learnxinyminutes.com/"
        }, {
            name: "Api hub",
            href: "http://overapi.com/"
        } ]
    }, {
        title: "C",
        tags: "compiled",
        links: [ {
            name: "Learn C the hard way",
            href: "http://c.learncodethehardway.org/book/"
        }, {
            name: "Basic c programs",
            href: "http://www.programiz.com/c-programming/examples"
        } ]
    }, {
        title: "Python",
        tags: "interpreted",
        links: [ {
            name: "Learn python the hard way",
            href: "http://learnpythonthehardway.org/book/"
        }, {
            name: "Basic python programs",
            href: "http://www.programiz.com/python-programming/examples"
        } ]
    }, {
        title: "Ruby",
        tags: "interpreted",
        links: [ {
            name: "Learn ruby the hard way",
            href: "http://learnrubythehardway.org/book/"
        }, {
            name: "Interactive way to learn ruby",
            href: "http://tryruby.org/levels/1/challenges/0"
        } ]
    }, {
        title: "Git",
        tags: "version control system vcs",
        links: [ {
            name: "Git in 15mins",
            href: "https://try.github.io"
        } ]
    }, {
        title: "Online Tutorials",
        tags: "free online all science technology",
        links: [ {
            name: "Scotch",
            href: "https://scotch.io/"
        }, {
            name: "Codecademy",
            href: "http://codecademy.com/"
        }, {
            name: "khanacademy",
            href: "https://www.khanacademy.org/"
        }, {
            name: "Codeschool",
            href: "https://www.codeschool.com/"
        }, {
            name: "Tutorials point",
            href: "http://tutorialspoint.com/"
        } ]
    }, {
        title: "Magazines for Web-development",
        tags: "web magazines smashing alistapart",
        links: [ {
            name: "Smashing magazine",
            href: "http://www.smashingmagazine.com/"
        }, {
            name: "Alistapart",
            href: "http://alistapart.com/topics"
        } ]
    }, {
        title: "Website Building",
        tags: "websites",
        links: [ {
            name: "Website creation guidelines by Google",
            href: "https://support.google.com/webmasters/answer/6001102"
        } ]
    }, {
        title: "Miscellaneous",
        tags: "grunt",
        links: [ {
            name: "Can I Use",
            href: "http://caniuse.com/"
        },{
            name: "Getting started with Grunt",
            href: "https://scotch.io/tutorials/a-simple-guide-to-getting-started-with-grunt"
        }, {
            name: "Grunt-Smashing Magazine",
            href: "http://www.smashingmagazine.com/2013/10/get-up-running-grunt/"
        }, {
            name: "Free e-books",
            href: "https://www.syncfusion.com/resources/techportal/ebooks"
        } ]
    } ];
    $scope.searchFilter = function(obj) {
        var re = new RegExp($scope.search, "i");
        return !$scope.search || re.test(obj.title) || re.test(obj.tags);
    };
});
<commit_msg>bootstrap4 link added<commit_after>var app = angular.module("poolApp", []);
app.controller("MainController", function($scope) {
    $scope.poolbase = [ {
        title: "Google",
        tags: "googling tips",
        links: [ {
            name: "Google efficiently",
            href: "http://www.makeuseof.com/tag/google-power-user/"
        } ]
    },{
        title: "Technical Interview Q&A",
        tags: "interviews questions tr technical awesome",
        links: [ {
            name: "Awesome Interviews",
            href: "https://github.com/MaximAbramchuck/awesome-interviews"
        } ]
    }, {
        title: "Html/Html5",
        tags: "markup",
        links: [ {
            name: "Introduction to HTML",
            href: "https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Introduction#History_of_HTML"
        }, {
            name: "Learn HTML",
            href: "http://learn.shayhowe.com/html-css/getting-to-know-html/"
        }, {
            name: "HTML5 in 5 mins",
            href: "https://msdn.microsoft.com/en-us/hh549253.aspx"
        }, {
            name: "More about HTML5",
            href: "https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5"
        }, {
            name: "HTML5-Canvas tutorial",
            href: "http://www.html5canvastutorials.com/"
        }, {
            name: "HTML5 + your browser compatibility",
            href: "https://html5test.com/"
        } ]
    }, {
        title: "Free Responsive Web Templates",
        tags: "website webpage",
        links: [ {
            name: "HTML5UP",
            href: "http://html5up.net/"
        }, {
            name: "Get Template",
            href: "http://www.gettemplate.com/"
        }, {
            name: "Foundation Templates",
            href: "http://foundation.zurb.com/templates.html"
        }, {
            name: "Bootstrap Templates",
            href: "http://startbootstrap.com/template-categories/all/"
        } ]
    }, {
        title: "Css/Css3",
        tags: "flex,styling,layout",
        links: [ {
            name: "Learn CSS",
            href: "http://learn.shayhowe.com/html-css/getting-to-know-css/"
        }, {
            name: "Learn Layout",
            href: "http://learnlayout.com/"
        }, {
            name: "CSS Properties",
            href: "http://www.cssportal.com/css-properties/index.php"
        }, {
            name: "30 CSS selectors to remember",
            href: "http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048"
        }, {
            name: "Game on CSS selectors",
            href: "http://flukeout.github.io/"
        }, {
            name: "Game on CSS3 Flexbox",
            href: "http://flexboxfroggy.com/"
        }, {
            name: "Link vs Import",
            href: "https://www.stevesouders.com/blog/2009/04/09/dont-use-import/"
        } ]
    }, {
        title: "Choosing color for text",
        tags: "colors",
        links: [ {
            name: "Choose right color",
            href: "http://colorsafe.co/"
        }, {
            name: "Pick color online",
            href: "http://colourco.de/"
        } ]
    }, {
        title: "Css Generators",
        tags: "generator",
        links: [ {
            name: "Online CSS3 generator",
            href: "http://enjoycss.com/"
        }, {
            name: "CSS Matic",
            href: "http://www.cssmatic.com/"
        }, {
            name: "Generate CSS arrow",
            href: "http://cssarrowplease.com/"
        }, {
            name: "CSS Shapes",
            href: "https://css-tricks.com/examples/ShapesOfCSS/"
        }, {
            name: "CSS gradient generator",
            href: "http://www.colorzilla.com/gradient-editor/"
        } ]
    }, {
        title: "Css Frameworks",
        tags: "frameworks",
        links: [ {
            name: "Bootstrap",
            href: "http://getbootstrap.com/"
        },{
            name: "Bootstrap4",
            href: "http://v4-alpha.getbootstrap.com/"
        }, {
            name: "Foundation",
            href: "http://foundation.zurb.com/"
        }, {
            name: "Metro UI",
            href: "http://metroui.org.ua/"
        }, {
            name: "Furtive-CSS micro framework",
            href: "http://furtive.co/"
        } ]
    }, {
        title: "JavaScript",
        tags: "js,ecmascript,es5",
        links: [ {
            name: "Essential JavaScript",
            href: "http://javascript.info/"
        }, {
            name: "All about JavaScript",
            href: "http://jstherightway.org/"
        }, {
            name: "JavaScript Standards",
            href: "http://bguiz.github.io/js-standards/intro/"
        }, {
            name: "Interactive way to learn JS",
            href: "http://www.codecademy.com/en/tracks/javascript"
        }, {
            name: "JavaScript Styleguide",
            href: "https://github.com/airbnb/javascript"
        }, {
            name: "Learn Object oriented JavaScript",
            href: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript"
        }, {
            name: "Javascript Design Patterns",
            href: "https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know"
        }, {
            name: "Javascript Char codes",
            href: "http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes"
        }, {
            name: "jsPerf - compare js snippets ",
            href: "https://jsperf.com/"
        } ]
    }, {
        title: "Javascript Libraries",
        tags: "js jquery",
        links: [ {
            name: "Interactive way to learn jQuery",
            href: "http://try.jquery.com/"
        } ]
    }, {
        title: "AngularJS",
        tags: "js,javascript frameworks,ajs",
        links: [ {
            name: "AngularJS Guidelines",
            href: "http://bguiz.github.io/js-standards/angularjs/single-responsibility/"
        }, {
            name: "Angular StyleGuide",
            href: "https://github.com/johnpapa/angular-styleguide/tree/master/a1"
        }, {
            name: "AngularJS in 60minutes",
            href: "http://fastandfluid.com/publicdownloads/AngularJSIn60MinutesIsh_DanWahlin_May2013.pdf"
        }, {
            name: "AngularJS examples",
            href: "http://tutorialzine.com/2013/08/learn-angularjs-5-examples/"
        } ]
    }, {
        title: "Regular Expressions",
        tags: "regex",
        links: [ {
            name: "Regexone - learn interactively",
            href: "http://regexone.com/"
        }, {
            name: "Online Regex builder",
            href: "http://regexr.com/"
        } ]
    }, {
        title: "Learn Command Line Interface",
        tags: "cli cmd",
        links: [ {
            name: "Learn CLI the hard way",
            href: "http://cli.learncodethehardway.org/book/"
        } ]
    }, {
        title: "Introduction to programming",
        tags: "beginner coding",
        links: [ {
            name: "Lets Play the game",
            href: "http://learn.code.org/hoc/1"
        } ]
    }, {
        title: "One stop for programming",
        tags: "code learn api",
        links: [ {
            name: "Learn X in Y minutes",
            href: "http://learnxinyminutes.com/"
        }, {
            name: "Api hub",
            href: "http://overapi.com/"
        } ]
    }, {
        title: "C",
        tags: "compiled",
        links: [ {
            name: "Learn C the hard way",
            href: "http://c.learncodethehardway.org/book/"
        }, {
            name: "Basic c programs",
            href: "http://www.programiz.com/c-programming/examples"
        } ]
    }, {
        title: "Python",
        tags: "interpreted",
        links: [ {
            name: "Learn python the hard way",
            href: "http://learnpythonthehardway.org/book/"
        }, {
            name: "Basic python programs",
            href: "http://www.programiz.com/python-programming/examples"
        } ]
    }, {
        title: "Ruby",
        tags: "interpreted",
        links: [ {
            name: "Learn ruby the hard way",
            href: "http://learnrubythehardway.org/book/"
        }, {
            name: "Interactive way to learn ruby",
            href: "http://tryruby.org/levels/1/challenges/0"
        } ]
    }, {
        title: "Git",
        tags: "version control system vcs",
        links: [ {
            name: "Git in 15mins",
            href: "https://try.github.io"
        } ]
    }, {
        title: "Online Tutorials",
        tags: "free online all science technology",
        links: [ {
            name: "Scotch",
            href: "https://scotch.io/"
        }, {
            name: "Codecademy",
            href: "http://codecademy.com/"
        }, {
            name: "khanacademy",
            href: "https://www.khanacademy.org/"
        }, {
            name: "Codeschool",
            href: "https://www.codeschool.com/"
        }, {
            name: "Tutorials point",
            href: "http://tutorialspoint.com/"
        } ]
    }, {
        title: "Magazines for Web-development",
        tags: "web magazines smashing alistapart",
        links: [ {
            name: "Smashing magazine",
            href: "http://www.smashingmagazine.com/"
        }, {
            name: "Alistapart",
            href: "http://alistapart.com/topics"
        } ]
    }, {
        title: "Website Building",
        tags: "websites",
        links: [ {
            name: "Website creation guidelines by Google",
            href: "https://support.google.com/webmasters/answer/6001102"
        } ]
    }, {
        title: "Miscellaneous",
        tags: "grunt",
        links: [ {
            name: "Can I Use",
            href: "http://caniuse.com/"
        },{
            name: "Getting started with Grunt",
            href: "https://scotch.io/tutorials/a-simple-guide-to-getting-started-with-grunt"
        }, {
            name: "Grunt-Smashing Magazine",
            href: "http://www.smashingmagazine.com/2013/10/get-up-running-grunt/"
        }, {
            name: "Free e-books",
            href: "https://www.syncfusion.com/resources/techportal/ebooks"
        } ]
    } ];
    $scope.searchFilter = function(obj) {
        var re = new RegExp($scope.search, "i");
        return !$scope.search || re.test(obj.title) || re.test(obj.tags);
    };
});
<|endoftext|>


<commit_before>
window.attach_placeling_place = function(json) {
    jQuery('#placeling_place_json').val( encodeURI( json ) );
    renderPlaceAdmin( );
};

window.get_placeling_json = function(json) {
    return jQuery('#placeling_place_json').val();
};

jQuery(document).ready(function(){
    jQuery("#placeling_js_warning").remove();

    renderPlaceAdmin( );

    jQuery("a#placeling_remove_place").live('click', function(){
        jQuery("#placeling_place_json").val("");
        jQuery("#placeling_placemarker_initial_memo").val("")
        jQuery("textarea[name=placeling_placemark_memo]").val("");
        renderPlaceAdmin( );
        return false;
    });

});

function renderPlaceAdmin( ){

	if ( jQuery("#placeling_place_json").val() != ""){
	    raw_json = unescape( jQuery("#placeling_place_json").val() );

	    place =  JSON.parse( raw_json );

	    var raw_place = jQuery('#placeling_place_json').val();
	    var json_place = unescape( raw_place );
	    var place = JSON.parse( json_place );

	    if ( !place.street_address ){
		    place.street_address = "";
	    }

	    if ( !place.city_data ){
            place.city_data = "";
	    }

        jQuery("#placeling_place_name").html( place.name );
        jQuery("#placeling_place_address").html( place.street_address );
        jQuery("#placeling_place_city").html( place.city_data );
        jQuery("#placeling_place_map").attr("src", place.map_url);

	    jQuery("#placeling_add_place_metabox .placeling_place_name").html( place.name );
	    jQuery("#placeling_add_place_metabox #placeling_tagged").show();
	    jQuery("#placeling_add_place_metabox #placeling_untagged").hide();

        if ( jQuery("#placeling_placemarker_initial_memo").val() != ""){
            jQuery("textarea[name=placeling_placemark_memo]").val( jQuery("#placeling_placemarker_initial_memo").val() );
	    } else if ( undefined != place.referring_perspectives && place.referring_perspectives.length > 0){
            jQuery("textarea[name=placeling_placemark_memo]").val( place.referring_perspectives[0].memo );
	    }

	    jQuery("#placeling_empty_place").hide();
	    jQuery("#placeling_tagged_place").show();

	} else {
	    jQuery("#placeling_add_place_metabox .placeling_place_name").html( "" );
	    jQuery("#placeling_add_place_metabox #placeling_tagged").hide();
	    jQuery("#placeling_add_place_metabox #placeling_untagged").show();
	    jQuery("#placeling_empty_place").show();
	    jQuery("#placeling_tagged_place").hide();
	}
}

<commit_msg>get rid of dead memo references in javascript<commit_after>
window.attach_placeling_place = function(json) {
    jQuery('#placeling_place_json').val( encodeURI( json ) );
    renderPlaceAdmin( );
};

window.get_placeling_json = function(json) {
    return jQuery('#placeling_place_json').val();
};

jQuery(document).ready(function(){
    jQuery("#placeling_js_warning").remove();

    renderPlaceAdmin( );

    jQuery("a#placeling_remove_place").live('click', function(){
        jQuery("#placeling_place_json").val("");
        renderPlaceAdmin( );
        return false;
    });

});

function renderPlaceAdmin( ){

	if ( jQuery("#placeling_place_json").val() != ""){
	    raw_json = unescape( jQuery("#placeling_place_json").val() );

	    place =  JSON.parse( raw_json );

	    var raw_place = jQuery('#placeling_place_json').val();
	    var json_place = unescape( raw_place );
	    var place = JSON.parse( json_place );

	    if ( !place.street_address ){
		    place.street_address = "";
	    }

	    if ( !place.city_data ){
            place.city_data = "";
	    }

        jQuery("#placeling_place_name").html( place.name );
        jQuery("#placeling_place_address").html( place.street_address );
        jQuery("#placeling_place_city").html( place.city_data );
        jQuery("#placeling_place_map").attr("src", place.map_url);

	    jQuery("#placeling_add_place_metabox .placeling_place_name").html( place.name );
	    jQuery("#placeling_add_place_metabox #placeling_tagged").show();
	    jQuery("#placeling_add_place_metabox #placeling_untagged").hide();

	    jQuery("#placeling_empty_place").hide();
	    jQuery("#placeling_tagged_place").show();

	} else {
	    jQuery("#placeling_add_place_metabox .placeling_place_name").html( "" );
	    jQuery("#placeling_add_place_metabox #placeling_tagged").hide();
	    jQuery("#placeling_add_place_metabox #placeling_untagged").show();
	    jQuery("#placeling_empty_place").show();
	    jQuery("#placeling_tagged_place").hide();
	}
}

<|endoftext|>


<commit_before>function _debug(msg){
    DEBUG && console.log(msg);
}

function callBotAPI(newmsg,callback,sendto,jumpback) {
    //jsonp proxy
    var url = 'https://cuhk.me/wx/jsonp.php';
    $.ajax({
        'url': url,
        'data': {msg: encodeURIComponent(newmsg), s: session_id} ,
        'dataType': 'jsonp',
        'success': function(response) {
            if (typeof(response.text)=='undefined') {
                ans = '太累了，我想休息一下，zzz～';
            } else {
                ans = response.text;
            }
            callback(ans,sendto,jumpback);
        },
        'error': function() {
            _debug("ajax error occured");
        }
    });
}

function sendmsg_callback(ans,sendto,jumpback){
    _debug("bot resp with: " + ans);
    $(sendto).find('.desc').removeClass('read'); //clear read mark
    sendto && $(sendto).click();
    $('#textInput')[0].value=ans;
    $('.chatSend')[0].click();
    $(jumpback).click();
}

function installbot(chats){
    //add bot notes
    for (i=0;i<chats.length;i++) {
        var bot = document.createElement('div');
        bot.className='bot';
        chats[i].appendChild(bot);
    }

    //listen on bot click event
    $(chats).children('.bot').click(function(e){
        e.stopPropagation();
        $(this).toggleClass('active');
        typeof(observer) !== 'undefined' && observer.disconnect();
    });

    //add drag drop event to bot div
    jQuery.event.props.push('dataTransfer');
    $(chats).on({
        dragenter: function(e) {
            $(this).addClass('over');
        },
        dragover: function(e) {
            e.preventDefault();
        },
        dragleave: function(e) {
            $(this).removeClass('over');
        },
        drop: function() {
            $(this).find('.bot').toggleClass('active');
        },
    });

    _debug("installed "+chats.length.toString()+" bots");
}

function buildbothome() {
    //add bot home
    $('#profile').append([
    '
',
        '',
        '',
            '
快把我拖到聊天列表上
',
            '
点击我可以 暂停/恢复
',
        '',
        '',
    '
'].join(''));

    //show tooltip for 10s
    $('img.botico').load(function(){
        $('#bot-wrapper span').show();
        setTimeout(function(){
            $('#bot-wrapper span').hide();
        },10*1000);
    });

    //clear tooltip on mousedown
    $('.bot-home').mousedown(function(){
        $('#bot-wrapper span').hide();
    });

    //listen on bot-home click event
    $('.bot-home').click(function(){
        $('.bot-home').toggleClass('paused');
    });

    //listen drag event
    jQuery.event.props.push('dataTransfer');
    $('.bot-home').on({
        dragstart: function() {
            $(this).css('opacity', '0.5');
            $('.chatListColumn *').css('pointer-events','none');
        },
        dragend: function() {
            $(this).css('opacity', '1');
            $('.chatListColumn *').css('pointer-events','');
            $('.chatListColumn').removeClass('over');
        },
    });
    _debug("bot home constructed");
}

function botinit(){
    $(document).ready(function(){
        //init bot-home
        buildbothome();
        //init bot divs
        var bots = $(['.chatListColumn',
            ':not([un="newsapp"])',
            ':not([un="filehelper"])',
            ':not([un="fmessage"])',
            ':not(".loadMoreConv")'].join(''))
        installbot(bots);
        _debug(bots.length.toString()+" bots initiated");
        //set chat list update listener
        setupdater();
        //identify user by cookie
        C = function(k){return encodeURIComponent(document.cookie.match(k+'=([^;]*)')[1])};
        session_id = C('xsid');
        nm = encodeURIComponent($('.myProfile .nickName').text());
    });
}

function botstart(interval){
    interval = typeof interval !== 'undefined' ? interval : 30;
    setInterval(chatbot,interval*1000);
    _debug("started with interval: "+interval.toString()+"s");
}

function botupdate(){
    uninstalled = $(['.chatListColumn',
            ':not([un="newsapp"])',
            ':not([un="filehelper"])',
            ':not([un="fmessage"])',
            ':not(".loadMoreConv")',
            ':not(:has(".bot"))'].join(''));
    uninstalled.length && installbot(uninstalled);
}

function setupdater() {
    updater = new MutationObserver(function(mutations) {
        botupdate();
    });
    updater.observe($('#conversationContainer')[0], { childList: true});
    _debug('updater set');
}

function chatbot() {
    //if paused
    if ( $('.bot-home').hasClass('paused') ) return;
    //if no bot-took-overed
    if ( $('.bot.active').length == 0 )  return;

    //record current chat
    var activechat = $('.activeColumn');

    //reply in current chat window
    if ( $('.activeColumn:has(".bot.active")').length ) {
        var lastchat = $('#chat_chatmsglist').children().last();
            if ($(lastchat).not('.read').hasClass('chatItem you')) {  //has read or self msg
                var name = $(activechat).find('.left.name').text();
                var newmsg = $(lastchat).find('pre').text();
                _debug("msg from: " + name);
                if (newmsg) {
                    _debug("msg content: " + newmsg);
                    $(lastchat).addClass('read'); //add read mark
                    callBotAPI(newmsg,sendmsg_callback,activechat);
                } else {
                    _debug("no msg found");
                }
            }
    }

    //reply for red dotted item
    $('.unreadDot:visible, .unreadDotS:visible').each(function()
    {
        var receiver = $(this).parent();
        is_active = $(receiver).find(".bot").hasClass("active");
        if (!is_active) return;
        if ($(receiver).find('.desc').hasClass('read')) return;  //has read, wait for response
        var name = $(receiver).find(".left.name").text();
        _debug("msg from: " + name);
        var newmsg = $(receiver).find('.desc').text();
        if (newmsg) {
            _debug("msg content: " + newmsg);
            $(receiver).find('.desc').addClass('read'); // add read mark
            callBotAPI(newmsg,sendmsg_callback,$(receiver),$(activechat));
        } else {
            _debug("no msg found");
        }
    });
}

DEBUG = true;
VERSION = "2.2.2";
botinit();
botstart(runtimeGlobal.interval);
botupdate();
<commit_msg>bug fixed<commit_after>function _debug(msg){
    DEBUG && console.log(msg);
}

function callBotAPI(newmsg,callback,sendto,jumpback) {
    //jsonp proxy
    var url = 'https://cuhk.me/wx/jsonp.php';
    $.ajax({
        'url': url,
        'data': {msg: encodeURIComponent(newmsg), s: session_id} ,
        'dataType': 'jsonp',
        'success': function(response) {
            if (typeof(response.text)=='undefined') {
                ans = '太累了，我想休息一下，zzz～';
            } else {
                ans = response.text;
            }
            callback(ans,sendto,jumpback);
        },
        'error': function() {
            _debug("ajax error occured");
        }
    });
}

function sendmsg_callback(ans,sendto,jumpback){
    _debug("bot resp with: " + ans);
    sendto && $(sendto).click();
    $('#textInput')[0].value=ans;
    $('.chatSend')[0].click();
    $(jumpback).click();
    $(sendto).find('.desc').removeClass('read'); //clear read mark
}

function installbot(chats){
    //add bot notes
    for (i=0;i<chats.length;i++) {
        var bot = document.createElement('div');
        bot.className='bot';
        chats[i].appendChild(bot);
    }

    //listen on bot click event
    $(chats).children('.bot').click(function(e){
        e.stopPropagation();
        $(this).toggleClass('active');
        typeof(observer) !== 'undefined' && observer.disconnect();
    });

    //add drag drop event to bot div
    jQuery.event.props.push('dataTransfer');
    $(chats).on({
        dragenter: function(e) {
            $(this).addClass('over');
        },
        dragover: function(e) {
            e.preventDefault();
        },
        dragleave: function(e) {
            $(this).removeClass('over');
        },
        drop: function() {
            $(this).find('.bot').toggleClass('active');
        },
    });

    _debug("installed "+chats.length.toString()+" bots");
}

function buildbothome() {
    //add bot home
    $('#profile').append([
    '
',
        '',
        '',
            '
快把我拖到聊天列表上
',
            '
点击我可以 暂停/恢复
',
        '',
        '',
    '
'].join(''));

    //show tooltip for 10s
    $('img.botico').load(function(){
        $('#bot-wrapper span').show();
        setTimeout(function(){
            $('#bot-wrapper span').hide();
        },10*1000);
    });

    //clear tooltip on mousedown
    $('.bot-home').mousedown(function(){
        $('#bot-wrapper span').hide();
    });

    //listen on bot-home click event
    $('.bot-home').click(function(){
        $('.bot-home').toggleClass('paused');
    });

    //listen drag event
    jQuery.event.props.push('dataTransfer');
    $('.bot-home').on({
        dragstart: function() {
            $(this).css('opacity', '0.5');
            $('.chatListColumn *').css('pointer-events','none');
        },
        dragend: function() {
            $(this).css('opacity', '1');
            $('.chatListColumn *').css('pointer-events','');
            $('.chatListColumn').removeClass('over');
        },
    });
    _debug("bot home constructed");
}

function botinit(){
    $(document).ready(function(){
        //init bot-home
        buildbothome();
        //init bot divs
        var bots = $(['.chatListColumn',
            ':not([un="newsapp"])',
            ':not([un="filehelper"])',
            ':not([un="fmessage"])',
            ':not(".loadMoreConv")'].join(''))
        installbot(bots);
        _debug(bots.length.toString()+" bots initiated");
        //set chat list update listener
        setupdater();
        //identify user by cookie
        C = function(k){return encodeURIComponent(document.cookie.match(k+'=([^;]*)')[1])};
        session_id = C('xsid');
        nm = encodeURIComponent($('.myProfile .nickName').text());
    });
}

function botstart(interval){
    interval = typeof interval !== 'undefined' ? interval : 30;
    setInterval(chatbot,interval*1000);
    _debug("started with interval: "+interval.toString()+"s");
}

function botupdate(){
    uninstalled = $(['.chatListColumn',
            ':not([un="newsapp"])',
            ':not([un="filehelper"])',
            ':not([un="fmessage"])',
            ':not(".loadMoreConv")',
            ':not(:has(".bot"))'].join(''));
    uninstalled.length && installbot(uninstalled);
}

function setupdater() {
    updater = new MutationObserver(function(mutations) {
        botupdate();
    });
    updater.observe($('#conversationContainer')[0], { childList: true});
    _debug('updater set');
}

function chatbot() {
    //if paused
    if ( $('.bot-home').hasClass('paused') ) return;
    //if no bot-took-overed
    if ( $('.bot.active').length == 0 )  return;

    //record current chat
    var activechat = $('.activeColumn');

    //reply in current chat window
    if ( $('.activeColumn:has(".bot.active")').length ) {
        var lastchat = $('#chat_chatmsglist').children().last();
            if ($(lastchat).not('.read').hasClass('chatItem you')) {  //has read or self msg
                var name = $(activechat).find('.left.name').text();
                var newmsg = $(lastchat).find('pre').text();
                _debug("msg from: " + name);
                if (newmsg) {
                    _debug("msg content: " + newmsg);
                    $(lastchat).addClass('read'); //add read mark
                    callBotAPI(newmsg,sendmsg_callback,activechat);
                } else {
                    _debug("no msg found");
                }
            }
    }

    //reply for red dotted item
    $('.unreadDot:visible, .unreadDotS:visible').each(function()
    {
        var receiver = $(this).parent();
        is_active = $(receiver).find(".bot").hasClass("active");
        if (!is_active) return;
        if ($(receiver).find('.desc').hasClass('read')) return;  //has read, wait for response
        var name = $(receiver).find(".left.name").text();
        _debug("msg from: " + name);
        var newmsg = $(receiver).find('.desc').text();
        if (newmsg) {
            _debug("msg content: " + newmsg);
            $(receiver).find('.desc').addClass('read'); // add read mark
            callBotAPI(newmsg,sendmsg_callback,$(receiver),$(activechat));
        } else {
            _debug("no msg found");
        }
    });
}

DEBUG = true;
VERSION = "2.2.2";
botinit();
botstart(runtimeGlobal.interval);
botupdate();
<|endoftext|>


<commit_before>var dotVoteCardButtonCallback = function (t) {
    var currentMember = {};
    return t.member('all')
    .then(function(member) {
        currentMember = member;
        return t.get('card', 'shared', UMTrello.constants.data.votes, {});
    })
    .then(function(currentVotes) {
        if(currentVotes[currentMember.id] === undefined) {
            currentVotes[currentMember.id] = 0;
        }
        console.log("Old Value: " + currentVotes[currentMember.id]);
        currentVotes[currentMember.id]++;
        console.log("New Value: " + currentVotes[currentMember.id]);
        console.dir(currentVotes);
        return t.set('card', 'shared', UMTrello.constants.data.votes, currentVotes);
    });
};

var sortCardsInListPopup = function (t) {
    return t.popup({
        title: 'Select List for Sorting',
        url: './sort-list.html',
        height: 200
    })
};

var clearListVotesPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear Votes',
        url: './clear-list.html',
        height: 200
    })
};

var boardButtonCallback = function (t) {
    return t.popup({
        title: 'Dot Voting Actions',
        items: [
            {
                text: 'Clear Votes on a List',
                callback: clearListVotesPopup
            }
        ]
    });
};

var idsCallback = function (t) {
    return t.popup({
        title: 'IDS Discovery',
        url: './ids.html',
        height: 200
    })
};

var getCardBadges = function (t) {
    return t.get('card','shared', UMTrello.constants.data.votes, 0)
    .then(function(dotVotes) {
        var votes = 0;
        for(var key in dotVotes) {
            votes += dotVotes[key];
        }
        if(votes > 0) {
            return [{
                text: votes,
                icon: GREY_DOT_ICON
            }];
        }
        return [];
    })
    .catch(function(err) {
        console.log("Card Badge Error");
        console.dir(err);
    });
};

var getMemberFirstName = function(id, members) {
    var member = members.find(function(element) {
        return element.id === id;
    });
    if(member) {
        return UMTrello.getMembersFirstName(member);
    }
    console.log("Could not find member and/or name for member");
    return "";
};

var getCardDetailBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var cards = [];
        for(var key in dotVotes) {
            if(dotVotes[key] > 0) {
                var description = dotVotes[key] + " votes";
                var memberName = getMemberFirstName(key, members);
                cards.push({
                    title: memberName,
                    text: description,
                    icon: GREY_DOT_ICON
                });
            }
        }
        return cards;
    })
    .catch(function(err) {
       console.log("Error When Creating Details Cards.");
       console.dir(err);
    });
};

var getIDSBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.ids, {})
    .then(function(ids) {
        var cards = [];
        if(ids.reporter !== undefined && ids.reporter !== 0) {
            cards.push({
                title: 'IDS',
                text: 'Reporter: ' + UMTrello.getMembersNameFromID(members, ids.reporter),
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.assignee !== undefined && ids.assignee !== 0) {
            cards.push({
                title: 'IDS',
                text: 'Reporter: ' + UMTrello.getMembersNameFromID(members, ids.assignee),
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.what !== undefined && ids.what.trim() !== '') {
            cards.push({
                title: 'IDS',
                text: 'Issue: ' + ids.what,
                icon: null,
                callback: idsCallback
            });
        }
        console.log("IDS Cards");
        console.dir(cards);
        return cards;
    })
    .catch(function(err) {
        console.log("Error creating IDS cards");
        console.dir(err);
    })
};

var DOT_ICON = './images/dot.png';
var GREY_DOT_ICON = './images/grey-dot.png';

var _members;
var getMembers = function(t) {
    return new Promise(function(resolve, reject) {
        if(_members !== undefined) {
            resolve(_members);
        }
        return t.board('members')
        .then(function(board) {
            _members = board.members;
            resolve(_members);
        })
        .catch(function(err) {
            reject(err);
        });
    });

};

TrelloPowerUp.initialize({
    'board-buttons': function (t, options) {
        return [{
            icon: DOT_ICON,
            text: 'Dot Voting Actions',
            callback: boardButtonCallback
        }];
    },
    'card-buttons': function (t, options) {
        return [{
            icon: GREY_DOT_ICON,
            text: 'Dot Vote',
            callback: dotVoteCardButtonCallback
        }, {
            icon: GREY_DOT_ICON,
            text:  'IDS',
            callback: idsCallback
        }];
    },
    'card-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardBadges(t), getIDSBadges(t, members)])
            .spread(function(dotVotingBadges, idsBadges) {
                var output = idsBadges.concat(dotVotingBadges);
                console.log("Output");
                console.dir(output);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Card Badges");
            console.dir(err);
        });
    },
    'card-detail-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardDetailBadges(t, members), getIDSBadges(t, members)])
            .spread(function (dotVotingBadges, idsBadges) {
                var output = idsBadges.concat(dotVotingBadges);
                console.log("Output");
                console.dir(output);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Detail Card Badges");
            console.dir(err);
        });
    }
});

<commit_msg>Adding logging for voting error<commit_after>var dotVoteCardButtonCallback = function (t) {
    var currentMember = {};
    return t.member('all')
    .then(function(member) {
        currentMember = member;
        return t.get('card', 'shared', UMTrello.constants.data.votes, {});
    })
    .then(function(currentVotes) {
        if(currentVotes[currentMember.id] === undefined) {
            currentVotes[currentMember.id] = 0;
        }
        console.log("Old Value: " + currentVotes[currentMember.id]);
        currentVotes[currentMember.id]++;
        console.log("New Value: " + currentVotes[currentMember.id]);
        console.dir(currentVotes);
        return t.set('card', 'shared', UMTrello.constants.data.votes, currentVotes);
    })
    .catch(function(err) {
        console.log("Voting Error");
        console.dir(err);
    });
};

var sortCardsInListPopup = function (t) {
    return t.popup({
        title: 'Select List for Sorting',
        url: './sort-list.html',
        height: 200
    })
};

var clearListVotesPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear Votes',
        url: './clear-list.html',
        height: 200
    })
};

var boardButtonCallback = function (t) {
    return t.popup({
        title: 'Dot Voting Actions',
        items: [
            {
                text: 'Clear Votes on a List',
                callback: clearListVotesPopup
            }
        ]
    });
};

var idsCallback = function (t) {
    return t.popup({
        title: 'IDS Discovery',
        url: './ids.html',
        height: 200
    })
};

var getCardBadges = function (t) {
    return t.get('card','shared', UMTrello.constants.data.votes, 0)
    .then(function(dotVotes) {
        var votes = 0;
        for(var key in dotVotes) {
            votes += dotVotes[key];
        }
        if(votes > 0) {
            return [{
                text: votes,
                icon: GREY_DOT_ICON
            }];
        }
        return [];
    })
    .catch(function(err) {
        console.log("Card Badge Error");
        console.dir(err);
    });
};

var getMemberFirstName = function(id, members) {
    var member = members.find(function(element) {
        return element.id === id;
    });
    if(member) {
        return UMTrello.getMembersFirstName(member);
    }
    console.log("Could not find member and/or name for member");
    return "";
};

var getCardDetailBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var cards = [];
        for(var key in dotVotes) {
            if(dotVotes[key] > 0) {
                var description = dotVotes[key] + " votes";
                var memberName = getMemberFirstName(key, members);
                cards.push({
                    title: memberName,
                    text: description,
                    icon: GREY_DOT_ICON
                });
            }
        }
        return cards;
    })
    .catch(function(err) {
       console.log("Error When Creating Details Cards.");
       console.dir(err);
    });
};

var getIDSBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.ids, {})
    .then(function(ids) {
        var cards = [];
        if(ids.reporter !== undefined && ids.reporter !== 0) {
            cards.push({
                title: 'IDS',
                text: 'Reporter: ' + UMTrello.getMembersNameFromID(members, ids.reporter),
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.assignee !== undefined && ids.assignee !== 0) {
            cards.push({
                title: 'IDS',
                text: 'Reporter: ' + UMTrello.getMembersNameFromID(members, ids.assignee),
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.what !== undefined && ids.what.trim() !== '') {
            cards.push({
                title: 'IDS',
                text: 'Issue: ' + ids.what,
                icon: null,
                callback: idsCallback
            });
        }
        console.log("IDS Cards");
        console.dir(cards);
        return cards;
    })
    .catch(function(err) {
        console.log("Error creating IDS cards");
        console.dir(err);
    })
};

var DOT_ICON = './images/dot.png';
var GREY_DOT_ICON = './images/grey-dot.png';

var _members;
var getMembers = function(t) {
    return new Promise(function(resolve, reject) {
        if(_members !== undefined) {
            resolve(_members);
        }
        return t.board('members')
        .then(function(board) {
            _members = board.members;
            resolve(_members);
        })
        .catch(function(err) {
            reject(err);
        });
    });

};

TrelloPowerUp.initialize({
    'board-buttons': function (t, options) {
        return [{
            icon: DOT_ICON,
            text: 'Dot Voting Actions',
            callback: boardButtonCallback
        }];
    },
    'card-buttons': function (t, options) {
        return [{
            icon: GREY_DOT_ICON,
            text: 'Dot Vote',
            callback: dotVoteCardButtonCallback
        }, {
            icon: GREY_DOT_ICON,
            text:  'IDS',
            callback: idsCallback
        }];
    },
    'card-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardBadges(t), getIDSBadges(t, members)])
            .spread(function(dotVotingBadges, idsBadges) {
                var output = idsBadges.concat(dotVotingBadges);
                console.log("Output");
                console.dir(output);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Card Badges");
            console.dir(err);
        });
    },
    'card-detail-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardDetailBadges(t, members), getIDSBadges(t, members)])
            .spread(function (dotVotingBadges, idsBadges) {
                var output = idsBadges.concat(dotVotingBadges);
                console.log("Output");
                console.dir(output);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Detail Card Badges");
            console.dir(err);
        });
    }
});

<|endoftext|>


<commit_before>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    for(var vertex in vertices){
        buffer.fillStyle = vertices[vertex]['color'];
        buffer.fillRect(
          vertices[vertex]['x'],
          vertices[vertex]['y'],
          vertices[vertex]['width'],
          vertices[vertex]['height']
        );
    }

    // Draw vertices_amount and lineWidth.
    buffer.fillStyle = '#fff';
    buffer.fillText(
      rotation_rate_display,
      0,
      25
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['rotation'] += rotation_rate * (25 - vertices[vertex]['layer']);
        if(vertices[vertex]['rotation'] >= tau){
            vertices[vertex]['rotation'] -= tau;
        }else if(vertices[vertex]['rotation'] < 0){
            vertices[vertex]['rotation'] += tau;
        }

        vertices[vertex]['x'] = x + vertices[vertex]['layer'] * 10 * Math.cos(vertices[vertex]['rotation']) - 5;
        vertices[vertex]['y'] = y + vertices[vertex]['layer'] * 10 * Math.sin(vertices[vertex]['rotation']) - 5;
    }
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';
}

var buffer = document.getElementById('buffer').getContext('2d', {
  'alpha': false,
});
var canvas = document.getElementById('canvas').getContext('2d', {
  'alpha': false,
});
var height = 0;
var rotation_rate = .005;
var rotation_rate_display = '5';
var tau = Math.PI * 2;
var vertices = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: increase rotation_rate.
    if(key === 187){
        rotation_rate += .001;

    // -: decrease rotation_rate.
    }else if(key === 189){
        rotation_rate -= .001;

    // ESC: rotation_rate = 0;
    }else if(key === 27){
        rotation_rate = 0;
    }

    rotation_rate_display = (rotation_rate * 1000).toFixed(0);
};

window.onload = function(e){
    resize();

    var loop_counter = 23;
    do{
        var inner_counter = loop_counter;
        do{
            vertices.push({
              'color': random_hex(),
              'height': 10,
              'layer': loop_counter + 1,
              'rotation': inner_counter,
              'width': 10,
              'x': 0,
              'y': 0,
            });
        }while(inner_counter--);
    }while(loop_counter--);

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onresize = resize;
<commit_msg>fixed incorrect comment<commit_after>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    for(var vertex in vertices){
        buffer.fillStyle = vertices[vertex]['color'];
        buffer.fillRect(
          vertices[vertex]['x'],
          vertices[vertex]['y'],
          vertices[vertex]['width'],
          vertices[vertex]['height']
        );
    }

    // Draw rotation_rate_display.
    buffer.fillStyle = '#fff';
    buffer.fillText(
      rotation_rate_display,
      0,
      25
    );

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['rotation'] += rotation_rate * (25 - vertices[vertex]['layer']);
        if(vertices[vertex]['rotation'] >= tau){
            vertices[vertex]['rotation'] -= tau;
        }else if(vertices[vertex]['rotation'] < 0){
            vertices[vertex]['rotation'] += tau;
        }

        vertices[vertex]['x'] = x + vertices[vertex]['layer'] * 10 * Math.cos(vertices[vertex]['rotation']) - 5;
        vertices[vertex]['y'] = y + vertices[vertex]['layer'] * 10 * Math.sin(vertices[vertex]['rotation']) - 5;
    }
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';
}

var buffer = document.getElementById('buffer').getContext('2d', {
  'alpha': false,
});
var canvas = document.getElementById('canvas').getContext('2d', {
  'alpha': false,
});
var height = 0;
var rotation_rate = .005;
var rotation_rate_display = '5';
var tau = Math.PI * 2;
var vertices = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: increase rotation_rate.
    if(key === 187){
        rotation_rate += .001;

    // -: decrease rotation_rate.
    }else if(key === 189){
        rotation_rate -= .001;

    // ESC: rotation_rate = 0;
    }else if(key === 27){
        rotation_rate = 0;
    }

    rotation_rate_display = (rotation_rate * 1000).toFixed(0);
};

window.onload = function(e){
    resize();

    var loop_counter = 23;
    do{
        var inner_counter = loop_counter;
        do{
            vertices.push({
              'color': random_hex(),
              'height': 10,
              'layer': loop_counter + 1,
              'rotation': inner_counter,
              'width': 10,
              'x': 0,
              'y': 0,
            });
        }while(inner_counter--);
    }while(loop_counter--);

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onresize = resize;
<|endoftext|>


<commit_before>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

//'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 1
    this.curr_col   = 1
    this.curr_token = ''
    this.curr_val   = '';

}

// Adds token to list
Scanner.prototype.addToken = function(){
    // console.log(this);
    if(this.curr_token){
        var token = {
            'token': this.curr_token,
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);
    }

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Default printer method
Scanner.prototype.printer = function(){
    return;
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(char){
    return char.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(char){
    return char.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(char){
    return char.toUpperCase();
}

// Handles whitespace character
Scanner.prototype.setSpace = function(ascii_value){
    this.addToken();
    this.reset();
    return;
}

// Handles comments
Scanner.prototype.setComment = function(char){
    // TODO
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(char){
    // TODO
    return;
}

// Handles newline characters
Scanner.prototype.setLine = function(ascii_value){
    this.addToken();
    this.reset();
    if(ascii_value == '10' || ascii_value == '13'){
        self.curr_row += 1;
        self.curr_col = 0;
    }
    return;
}

function setToken(token_type, character){

}
// Adds the last token into the list, sets new token
Scanner.prototype.setToken = function(token_type, character){
    this.addToken();
    this.reset();
    this.curr_token = token_type;
    this.curr_val += character;
    return;
}

// Handles characters
Scanner.prototype.setCharacter = function(character){
    if(this.curr_token != 'TK_IDENTIFIER'){
        this.setToken('TK_IDENTIFIER', character);
    }
    else{
        this.curr_val += character;
        if(this.curr_val in keywords){
            this.curr_token = keywords[this.curr_val];
        }
        else if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    return;
}

// Main scanner function
function scan(){
    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;
    // Initalize scanner
    var scanner = new Scanner();
    // Begin scanning input text
    for(var i = 0; i < program.length; i++){
        var character = scanner.toUpper(program[i]);
        var ascii = scanner.toAscii(character);
        // Handle case for newline character
        if(ascii == '10'){
            scanner.setLine(ascii);
        }
        // Handle case for space
        else if(ascii == '32'){
            scanner.setSpace(ascii);
        }
        // Handle case for valid letters
        else if( (ascii >= 97 && ascii <= 122) || (ascii >= 65 && ascii <= 90) ){
            scanner.setCharacter(character);
        }
        scanner.curr_col += 1;

    }
    console.log(scanner.tokens);

}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<commit_msg>scanner.js: Adding default implementation of setOperator method<commit_after>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

//'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 1
    this.curr_col   = 1
    this.curr_token = ''
    this.curr_val   = '';

}

// Adds token to list
Scanner.prototype.addToken = function(){
    // console.log(this);
    if(this.curr_token){
        var token = {
            'token': this.curr_token,
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);
    }

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Default printer method
Scanner.prototype.printer = function(){
    return;
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(char){
    return char.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(char){
    return char.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(char){
    return char.toUpperCase();
}

// Handles comments
Scanner.prototype.setComment = function(char){
    // TODO
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(char){
    // TODO
    return;
}

// Handles newline characters
Scanner.prototype.setLine = function(ascii_value){
    this.addToken();
    this.reset();
    if(ascii_value == '10' || ascii_value == '13'){
        self.curr_row += 1;
        self.curr_col = 0;
    }
    return;
}

// Handles whitespace character
Scanner.prototype.setSpace = function(ascii_value){
    this.addToken();
    this.reset();
    return;
}

// Adds the last token into the list, sets new token
Scanner.prototype.setToken = function(token_type, character){
    this.addToken();
    this.reset();
    this.curr_token = token_type;
    this.curr_val += character;
    return;
}

// Handles characters
Scanner.prototype.setCharacter = function(character){
    if(this.curr_token != 'TK_IDENTIFIER'){
        this.setToken('TK_IDENTIFIER', character);
    }
    else{
        this.curr_val += character;
        if(this.curr_val in keywords){
            this.curr_token = keywords[this.curr_val];
        }
        else if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    return;
}

// Handles operators
Scanner.prototype.setOperator = function(character){
    // TODO
    return;
}

// Main scanner function
function scan(){

    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;

    // Initalize scanner
    var scanner = new Scanner();

    // Begin scanning input text
    for(var i = 0; i < program.length; i++){
        var character = scanner.toUpper(program[i]);
        var ascii = scanner.toAscii(character);

        // Handle case for newline character
        if(ascii == '10'){
            scanner.setLine(ascii);
        }

        // Handle case for space
        else if(ascii == '32'){
            scanner.setSpace(ascii);
        }

        // Handle case for valid letters
        else if( (ascii >= 97 && ascii <= 122) || (ascii >= 65 && ascii <= 90) ){
            scanner.setCharacter(character);
        }

        // Handle case for operators
        else if(character in operators){
            scanner.setOperator(character);
        }

        scanner.curr_col += 1;

    }
    console.log(scanner.tokens);

}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<|endoftext|>


<commit_before>// Pomodoro Clock v.1.0
// Created by: Elminster White - elminsterthewhite@gmail.com

"use strict";

// Code wrapped in a closure to avoid global variables
(function () {
  let countdown;
  let timeIsRunnig = false;
  let actionTypeSwitch = "Work";

  const timerDisplay = document.querySelector(".display__time-left");
  const infoDisplay = document.querySelector(".display__info");
  const endTime = document.querySelector(".display__end-time");
  const buttons = document.querySelectorAll("[data-time]");
  const breakSettings = document.querySelectorAll(".settings__breakButton");
  const workSettings = document.querySelectorAll(".settings__workButton");
  const breakValue = document.querySelector("#valueBreak");
  const workValue = document.querySelector("#valueWork");
  const buttonMain = document.querySelector("#buttonMain");

  let workValueSettings = 25; // Default work session value in min
  let breakValueSettings = 5; // Default break session value in min

  workValue.textContent = workValueSettings + ' min';
  breakValue.textContent = breakValueSettings + ' min';

  timerDisplay.textContent = `${ workValueSettings}:00`;
  infoDisplay.textContent = "Are you ready?";
  endTime.textContent = "Press START";

  function timer(seconds) {
    // Clear any existing timers
    clearInterval(countdown);
    // Current time in ms
    const now = Date.now();
    const future = now + seconds * 1000;
    displayTimeLeft(seconds);
    displayEndTime(future);

    function timeCalc() {
      const secondsLeft = Math.round((future - Date.now()) / 1000);
      // Check if we should stop it
      if (secondsLeft < 0) {
        clearInterval(countdown);
        return;
      }
      // Display it
      displayTimeLeft(secondsLeft);
    }
    countdown = setInterval(timeCalc, 1000);
  }

  function startTimer() {
    const seconds = workValueSettings * 60;
    actionTypeSwitch = "Work";
    infoDisplay.textContent = "Working hard!";
    timer(seconds);
  }

  function startBreak() {
    const seconds = breakValueSettings * 60;
    actionTypeSwitch = "Break";
    infoDisplay.textContent = "Short break!";
    timer(seconds);
  }

  function resetTimer() {
    const seconds = workValueSettings * 60;
    // Clear any existing timers
    clearInterval(countdown);
    // Refresh display
    displayTimeLeft(seconds);
    infoDisplay.textContent = "Are you ready?";
    endTime.textContent = "Press START";
  }

  function startAndReset() {
    let name = "START";
    if (timeIsRunnig === false) {
      timeIsRunnig = true;
      name = "RESET";
      this.innerHTML = name;
      startTimer();
    } else {
      timeIsRunnig = false;
      name = "START";
      this.innerHTML = name;
      resetTimer();
    }
  }

  function playSoundStartBreak() {
    // Returns the first Element within the document
    // that matches the specified group of selectors.
    const audio = document.querySelector(`audio[data-sound="workDone"]`);
    if(!audio) return; // Stop the function from running
    audio.currentTime = 0; // Rewind to the start
    audio.play();
  }

  function playSoundBackToWork() {
    // Returns the first Element within the document
    // that matches the specified group of selectors.
    const audio = document.querySelector(`audio[data-sound="backToWork"]`);
    if(!audio) return; // Stop the function from running
    audio.currentTime = 0; // Rewind to the start
    audio.play();
  }

  function displayTimeLeft(sec) {
    const hours = parseFloat(Math.floor(sec / 3600));
    const minutes = parseFloat(Math.floor(sec / 60));
    const remainderMinutes = parseFloat(minutes % 60);
    const remainderSeconds = parseFloat(sec % 60);
    console.log(hours, remainderMinutes, remainderSeconds);

    // Play sound when timer gets to 0
    if (parseFloat(sec) === 0) {
      if (actionTypeSwitch === "Work") {
        playSoundStartBreak()
        startBreak();
      } else {
        playSoundBackToWork();
        startTimer();
      }
    }

    // Hide hours when hours is 0
    let hoursFirstStatement = hours < 10 ? "0" : "";
    let hoursSecondStatement = hours;
    let colon = ":";

    if (hours === 0) {
      hoursFirstStatement = "";
      hoursSecondStatement = "";
      colon = "";
    }

    // This `${}` allows adding javascript variables in strings
    const display = `${hoursFirstStatement}${hoursSecondStatement}${colon}${
      remainderMinutes < 10 ? "0" : ""}${remainderMinutes}:${
      remainderSeconds < 10 ? "0" : ""}${remainderSeconds}`;
    timerDisplay.textContent = display;
    document.title = display + " " + "(" + actionTypeSwitch + ")";
  }

  function displayEndTime(timestamp) {
    const end = new Date(timestamp);
    const hours = end.getHours();
    const minutes = end.getMinutes();
    endTime.textContent = `This session ends at ${hours < 10 ? "0" : ""}${hours}:${
      minutes < 10 ? "0" : ""}${minutes}`;
  }

  function changeBreakSettings() {
    const breakChangeValue = parseInt(this.dataset.settings);
    if ((breakValueSettings <= 1 && breakChangeValue === -1) ||
        (breakValueSettings >= 30 && breakChangeValue === 1))  {
      return; // Do nothing when this conditions are fulfilled
    } else {
      breakValueSettings = breakValueSettings + breakChangeValue;
      breakValue.textContent = breakValueSettings + ' min';
    }
  }

  function changeWorkSettings() {
    const workChangeValue = parseInt(this.dataset.settings);
    if ((workValueSettings <= 5 && workChangeValue === -1) ||
        (workValueSettings >= 120 && workChangeValue === 1))  {
      return; // Do nothing when this conditions are fulfilled
    } else {
      workValueSettings = workValueSettings + workChangeValue;
      workValue.textContent = workValueSettings + ' min';
    }
  }

  breakSettings.forEach(button => button.addEventListener("click", changeBreakSettings));
  workSettings.forEach(button => button.addEventListener("click", changeWorkSettings));
  buttonMain.addEventListener("click", startAndReset);
}());<commit_msg>Add clearInterval(timeCalc) to avoid infinite loop<commit_after>// Pomodoro Clock v.1.0
// Created by: Elminster White - elminsterthewhite@gmail.com

"use strict";

// Code wrapped in a closure to avoid global variables
(function () {
  let countdown;
  let timeIsRunnig = false;
  let actionTypeSwitch = "Work";

  const timerDisplay = document.querySelector(".display__time-left");
  const infoDisplay = document.querySelector(".display__info");
  const endTime = document.querySelector(".display__end-time");
  const buttons = document.querySelectorAll("[data-time]");
  const breakSettings = document.querySelectorAll(".settings__breakButton");
  const workSettings = document.querySelectorAll(".settings__workButton");
  const breakValue = document.querySelector("#valueBreak");
  const workValue = document.querySelector("#valueWork");
  const buttonMain = document.querySelector("#buttonMain");

  let workValueSettings = 25; // Default work session value in min
  let breakValueSettings = 5; // Default break session value in min

  workValue.textContent = workValueSettings + ' min';
  breakValue.textContent = breakValueSettings + ' min';

  timerDisplay.textContent = `${ workValueSettings}:00`;
  infoDisplay.textContent = "Are you ready?";
  endTime.textContent = "Press START";

  function timer(seconds) {
    // Clear any existing timers
    clearInterval(countdown);
    // Current time in ms
    const now = Date.now();
    const future = now + seconds * 1000;
    displayTimeLeft(seconds);
    displayEndTime(future);

    function timeCalc() {
      const secondsLeft = Math.round((future - Date.now()) / 1000);
      // Check if we should stop it
      if (secondsLeft < 0) {
        clearInterval(timeCalc);
        clearInterval(countdown);
        return;
      }
      // Display it
      displayTimeLeft(secondsLeft);
    }
    countdown = setInterval(timeCalc, 1000);
  }

  function startTimer() {
    const seconds = workValueSettings * 60;
    actionTypeSwitch = "Work";
    infoDisplay.textContent = "Working hard!";
    timer(seconds);
  }

  function startBreak() {
    const seconds = breakValueSettings * 60;
    actionTypeSwitch = "Break";
    infoDisplay.textContent = "Short break!";
    timer(seconds);
  }

  function resetTimer() {
    const seconds = workValueSettings * 60;
    // Clear any existing timers
    clearInterval(countdown);
    // Refresh display
    displayTimeLeft(seconds);
    infoDisplay.textContent = "Are you ready?";
    endTime.textContent = "Press START";
  }

  function startAndReset() {
    let name = "START";
    if (timeIsRunnig === false) {
      timeIsRunnig = true;
      name = "RESET";
      this.innerHTML = name;
      startTimer();
    } else {
      timeIsRunnig = false;
      name = "START";
      this.innerHTML = name;
      resetTimer();
    }
  }

  function playSoundStartBreak() {
    // Returns the first Element within the document
    // that matches the specified group of selectors.
    const audio = document.querySelector(`audio[data-sound="workDone"]`);
    if(!audio) return; // Stop the function from running
    audio.currentTime = 0; // Rewind to the start
    audio.play();
  }

  function playSoundBackToWork() {
    // Returns the first Element within the document
    // that matches the specified group of selectors.
    const audio = document.querySelector(`audio[data-sound="backToWork"]`);
    if(!audio) return; // Stop the function from running
    audio.currentTime = 0; // Rewind to the start
    audio.play();
  }

  function displayTimeLeft(sec) {
    const hours = parseFloat(Math.floor(sec / 3600));
    const minutes = parseFloat(Math.floor(sec / 60));
    const remainderMinutes = parseFloat(minutes % 60);
    const remainderSeconds = parseFloat(sec % 60);
    console.log(hours, remainderMinutes, remainderSeconds);

    // Play sound when timer gets to 0
    if (parseFloat(sec) === 0) {
      if (actionTypeSwitch === "Work") {
        playSoundStartBreak()
        startBreak();
      } else {
        playSoundBackToWork();
        startTimer();
      }
    }

    // Hide hours when hours is 0
    let hoursFirstStatement = hours < 10 ? "0" : "";
    let hoursSecondStatement = hours;
    let colon = ":";

    if (hours === 0) {
      hoursFirstStatement = "";
      hoursSecondStatement = "";
      colon = "";
    }

    // This `${}` allows adding javascript variables in strings
    const display = `${hoursFirstStatement}${hoursSecondStatement}${colon}${
      remainderMinutes < 10 ? "0" : ""}${remainderMinutes}:${
      remainderSeconds < 10 ? "0" : ""}${remainderSeconds}`;
    timerDisplay.textContent = display;
    document.title = display + " " + "(" + actionTypeSwitch + ")";
  }

  function displayEndTime(timestamp) {
    const end = new Date(timestamp);
    const hours = end.getHours();
    const minutes = end.getMinutes();
    endTime.textContent = `This session ends at ${hours < 10 ? "0" : ""}${hours}:${
      minutes < 10 ? "0" : ""}${minutes}`;
  }

  function changeBreakSettings() {
    const breakChangeValue = parseInt(this.dataset.settings);
    if ((breakValueSettings <= 1 && breakChangeValue === -1) ||
        (breakValueSettings >= 30 && breakChangeValue === 1))  {
      return; // Do nothing when this conditions are fulfilled
    } else {
      breakValueSettings = breakValueSettings + breakChangeValue;
      breakValue.textContent = breakValueSettings + ' min';
    }
  }

  function changeWorkSettings() {
    const workChangeValue = parseInt(this.dataset.settings);
    if ((workValueSettings <= 5 && workChangeValue === -1) ||
        (workValueSettings >= 120 && workChangeValue === 1))  {
      return; // Do nothing when this conditions are fulfilled
    } else {
      workValueSettings = workValueSettings + workChangeValue;
      workValue.textContent = workValueSettings + ' min';
    }
  }

  breakSettings.forEach(button => button.addEventListener("click", changeBreakSettings));
  workSettings.forEach(button => button.addEventListener("click", changeWorkSettings));
  buttonMain.addEventListener("click", startAndReset);
}());
<|endoftext|>


<commit_before>		//Classe para emular o objeto de geolocalizacao
		function Position(latitude, longitude, altitude, accurary, altitudeAccuracy, heading, speed) {
			this.coords = function(latitude, longitude, altitude, accurary, altitudeAccuracy, heading, speed) {
				this.latitude = latitude;
				this.longitude = longitude;
				this.altitude = altitude;
				this.accuracy = accuracy;
				this.altitudeAccuracy = altitudeAccuracy;
				this.heading = heading;
				this.speed = speed;
			}
		}

		var Position2 = {
			coords : {
				latitude : "",
				longitude : "",
				altitude : "",
				accuracy : "",
				altitudeAccuracy : "",
				heading : "",
				speed : ""
			}
		}

		//Funcoes especificas do Phonegap

		var celular_modelo = "";
		var celular_plataforma = "";
		var celular_uuid = "";
		var celular_versao = "";
		var isPhoneGapReady = false;
		var isConnected = false;
		var isHighSpeed = false;
		var status_bateria = "aguarde...";
		var watchID;
		var retorno_rastreio = "(nao houve o envio de dados)";

		// Wait for device API libraries to load
		// device APIs are available
		//

		document.addEventListener("deviceready", onDeviceReady, false);

		function onDeviceReady() {

			isPhoneGapReady = true;
			// detect for network access
			networkDetection();
			// attach events for online and offline detection
			document.addEventListener("online", onOnline, false);
			document.addEventListener("offline", onOffline, false);
			document.addEventListener("batterystatus", onBatteryStatus, false);

			var conteudo = "";
			conteudo = conteudo + 'Modelo: '    + device.model    + '
';
			conteudo = conteudo + 'Plataforma: ' + device.platform + '
';
			conteudo = conteudo + 'UUID: '     + device.uuid     + '
';
			conteudo = conteudo + 'Verso: '  + device.version  + '
';
			conteudo = conteudo + 'Bateria: '  + status_bateria  + '
';

			celular_modelo = device.model;
			celular_plataforma = device.platform;
			celular_uuid = device.uuid;
			celular_versao = device.version;

			$("#deviceproperties").append(conteudo);
		}

		 // alert dialog dismissed
		function alertDismissed() {
			// do something
		}

		function formatAMPM() {
			var date = new Date();
			var hours = date.getHours();
			var days = date.getDay();
			var minutes = date.getMinutes();
			var ampm = hours >= 12 ? 'pm' : 'am';
			hours = hours % 12;
			hours = hours ? hours : 12; // the hour '0' should be '12'
			minutes = minutes < 10 ? '0'+minutes : minutes;
			var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
			return strTime;
		}

		function networkDetection() {
			if (isPhoneGapReady) {
				// as long as the connection type is not none,
				// the device should have Internet access

				isConnected = true;
				isHighSpeed = true;
				//O codigo abaixo somente funciona no dispositivo
				//if (navigator.network.connection.type != Connection.NONE) {
				//	isConnected = true;
				//}
				// determine whether this connection is high-speed
				//switch (navigator.network.connection.type) {
				//	case Connection.UNKNOWN:
				//	case Connection.CELL_2G:
				//	isHighSpeed = false;
				//	break;
				//	default:
				//	isHighSpeed = true;
				//	break;
				//}
			}
		}

		function onOnline() {
			isConnected = true;
		}
		function onOffline() {
			isConnected = false;
		}

		function onBatteryStatus(battery_info) {
			status_bateria = battery_info.level + '%';
		}

		$(document).on('pageshow', '#posicao', function(){
			if (isPhoneGapReady){
				if (isConnected) {
					// load the google api
					var fileref=document.createElement('script');
					fileref.setAttribute("type","text/javascript");
					fileref.setAttribute("src",	"http://maps.googleapis.com/maps/api/js?sensor=true&callback=" + "getGeolocation");
					document.getElementsByTagName("head")[0].appendChild(fileref);
				} else {
					navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Rastreio Mobile', 'OK');
					$.mobile.changePage("#pageone");
				}
			} else {
				navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Rastreio Mobile', 'OK');
				$.mobile.changePage("#pageone");
			}
		});

		//Funcoes para exibir o mapa
		function getGeolocation() {
			$.mobile.loading('show', {
				theme: "a",
				text: "Aguarde...",
				textonly: true,
				textVisible: true
			});
			// get the user's gps coordinates and display map
			var options = {
			maximumAge: 3000,
			timeout: 5000,
			enableHighAccuracy: true
			};
			navigator.geolocation.getCurrentPosition(loadMap, geoError, options);
		}

		function loadMap(position) {
			var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			var myOptions = {
			zoom: 16,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			var mapObj = document.getElementById("map_canvas");
			var map = new google.maps.Map(mapObj, myOptions);
			var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title:"You"
			});
			$.mobile.loading('hide');
		}

		function geoError(error) {
			alert('codigo: ' + error.code + '\n' + 'mensagem: ' + error.message + '\n');
		}

		function ajaxCallBackRASTREIO(retString){
			retorno_rastreio = retString;
		}

		//Funcoes para o rastremanto automatico
		function onSuccessRastreio(position){

			var var_latitude = position.coords.latitude;
			var var_longitude = position.coords.longitude;
			var var_altitude = position.coords.altitude;
			var var_accuracy = position.coords.accuracy;
			var var_altitude_accuracy = position.coords.altitudeAccuracy;
			var var_heading = position.coords.heading;
			var var_speed = position.coords.speed;

			//Zerando campos que podem vir nulos
			if(!var_altitude) {
				var_altitude = 0;
			}
			if(!var_altitude_accuracy) {
				var_altitude_accuracy = 0;
			}
			if(!var_heading) {
				var_heading = 0;
			}
			if(!var_speed) {
				var_speed = 0;
			}

			$.ajax({
			type: "POST",
			url: "http://www.interiornaweb.com.br/rastreio_mobile_teste.php",
			dataType:"text",
			data: {latitude: var_latitude, longitude: var_longitude, altitude: var_altitude, accuracy: var_accuracy, altitude_accuracy: var_altitude_accuracy, heading: var_heading, speed: var_speed, gravar: "SIM" },
			async: true,
			error: function(request, status, error) {

				//alert(request.responseText);
				ajaxCallBackRASTREIO("(Houve um problema de comunicacao com os nossos sistemas)");
			}
			}).done(function(data) {
				//Nao faz nada

				if (data == 1){
					ajaxCallBackRASTREIO("(Dados gravados com sucesso - ultima atualizacao:" + formatAMPM() + ")");
					var element = document.getElementById("posicao_atual");
					element.innerHTML = "Latitude: " + position.coords.latitude + "
" +
					"Longitude: " + position.coords.longitude + "
"+ "Altitude: " + var_altitude + "
" + "Accuracy:" + var_accuracy + "
" + "Altitude Accuracy:" + var_altitude_accuracy + "
" + "Heading: " + var_heading + "
" + "Speed: " + var_speed + "
Dados gravados com sucesso - ultima atualizacao:" + formatAMPM() + ")
";
				} else {
					ajaxCallBackRASTREIO("(Houve um problema ao gravar os dados)");
				}
			});
			var element = document.getElementById("posicao_atual");
			element.innerHTML = "Latitude: " + position.coords.latitude + "
" +
			"Longitude: " + position.coords.longitude + "
"+ "Altitude: " + var_altitude + "
" + "Accuracy:" + var_accuracy + "
" + "Altitude Accuracy:" + var_altitude_accuracy + "
" + "Heading: " + var_heading + "
" + "Speed: " + var_speed + "
" + retorno_rastreio + "
";
		}

		function DesativarRastreio(){
			//Habilitar em producao
			navigator.geolocation.clearWatch(watchID);
			clearTimeout(watchID);
			$.mobile.changePage("#pageone");
		}

		$(document).on('pageshow', '#rastreio', function(){
			if (isPhoneGapReady){
				if (isConnected) {
					//rastreando
					navigator.notification.alert('iniciando o rastreio...', alertDismissed, 'Rastreio Mobile', 'OK');
					objeto_position = new Position("43,425397", "-80,442334", 100, 10, 10, 0, 0);
					console.log(objeto_position);
					//Ambiente de testes
					//watchID = setInterval(onSuccessRastreio(objeto_position), 3000);
					//Habilitar em producao
					watchID = navigator.geolocation.watchPosition(onSuccessRastreio, geoError,{timeout: 10000, enableHighAccuracy: false, frequency: 10000 }); //10 segundos

				} else {
					navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Rastreio Mobile', 'OK');
					$.mobile.changePage("#pageone");
				}
			} else {
				navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Rastreio Mobile', 'OK');
				$.mobile.changePage("#pageone");
			}
		});

		<commit_msg>2015-05-01<commit_after>		//Classe para emular o objeto de geolocalizacao
		function Position(latitude, longitude, altitude, accurary, altitudeAccuracy, heading, speed) {
			this.coords = function(latitude, longitude, altitude, accurary, altitudeAccuracy, heading, speed) {
				this.latitude = latitude;
				this.longitude = longitude;
				this.altitude = altitude;
				this.accuracy = accuracy;
				this.altitudeAccuracy = altitudeAccuracy;
				this.heading = heading;
				this.speed = speed;
			}
		}

		var Position2 = {
			coords : {
				latitude : "",
				longitude : "",
				altitude : "",
				accuracy : "",
				altitudeAccuracy : "",
				heading : "",
				speed : ""
			}
		}

		//Funcoes especificas do Phonegap

		var celular_modelo = "";
		var celular_plataforma = "";
		var celular_uuid = "";
		var celular_versao = "";
		var isPhoneGapReady = false;
		var isConnected = false;
		var isHighSpeed = false;
		var status_bateria = "aguarde...";
		var watchID;
		var retorno_rastreio = "(nao houve o envio de dados)";

		// Wait for device API libraries to load
		// device APIs are available
		//

		document.addEventListener("deviceready", onDeviceReady, false);

		function onDeviceReady() {

			isPhoneGapReady = true;
			// detect for network access
			networkDetection();
			// attach events for online and offline detection
			document.addEventListener("online", onOnline, false);
			document.addEventListener("offline", onOffline, false);
			document.addEventListener("batterystatus", onBatteryStatus, false);

			var conteudo = "";
			conteudo = conteudo + 'Modelo: '    + device.model    + '
';
			conteudo = conteudo + 'Plataforma: ' + device.platform + '
';
			conteudo = conteudo + 'UUID: '     + device.uuid     + '
';
			conteudo = conteudo + 'Verso: '  + device.version  + '
';
			conteudo = conteudo + 'Bateria: '  + status_bateria  + '
';

			celular_modelo = device.model;
			celular_plataforma = device.platform;
			celular_uuid = device.uuid;
			celular_versao = device.version;

			$("#deviceproperties").append(conteudo);
		}

		 // alert dialog dismissed
		function alertDismissed() {
			// do something
		}

		function formatAMPM() {
			var date = new Date();
			var hours = date.getHours();
			var days = date.getDay();
			var minutes = date.getMinutes();
			var ampm = hours >= 12 ? 'pm' : 'am';
			hours = hours % 12;
			hours = hours ? hours : 12; // the hour '0' should be '12'
			minutes = minutes < 10 ? '0'+minutes : minutes;
			var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
			return strTime;
		}

		function networkDetection() {
			if (isPhoneGapReady) {
				// as long as the connection type is not none,
				// the device should have Internet access

				isConnected = true;
				isHighSpeed = true;
				//O codigo abaixo somente funciona no dispositivo
				//if (navigator.network.connection.type != Connection.NONE) {
				//	isConnected = true;
				//}
				// determine whether this connection is high-speed
				//switch (navigator.network.connection.type) {
				//	case Connection.UNKNOWN:
				//	case Connection.CELL_2G:
				//	isHighSpeed = false;
				//	break;
				//	default:
				//	isHighSpeed = true;
				//	break;
				//}
			}
		}

		function onOnline() {
			isConnected = true;
		}
		function onOffline() {
			isConnected = false;
		}

		function onBatteryStatus(battery_info) {
			status_bateria = battery_info.level + '%';
		}

		$(document).on('pageshow', '#posicao', function(){
			if (isPhoneGapReady){
				if (isConnected) {
					// load the google api
					var fileref=document.createElement('script');
					fileref.setAttribute("type","text/javascript");
					fileref.setAttribute("src",	"http://maps.googleapis.com/maps/api/js?sensor=true&callback=" + "getGeolocation");
					document.getElementsByTagName("head")[0].appendChild(fileref);
				} else {
					navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Rastreio Mobile', 'OK');
					$.mobile.changePage("#pageone");
				}
			} else {
				navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Rastreio Mobile', 'OK');
				$.mobile.changePage("#pageone");
			}
		});

		//Funcoes para exibir o mapa
		function getGeolocation() {
			$.mobile.loading('show', {
				theme: "a",
				text: "Aguarde...",
				textonly: true,
				textVisible: true
			});
			// get the user's gps coordinates and display map
			var options = {
			maximumAge: 3000,
			timeout: 5000,
			enableHighAccuracy: true
			};
			navigator.geolocation.getCurrentPosition(loadMap, geoError, options);
		}

		function loadMap(position) {
			var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			var myOptions = {
			zoom: 16,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			var mapObj = document.getElementById("map_canvas");
			var map = new google.maps.Map(mapObj, myOptions);
			var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title:"You"
			});
			$.mobile.loading('hide');
		}

		function geoError(error) {
			alert('codigo: ' + error.code + '\n' + 'mensagem: ' + error.message + '\n');
		}

		function ajaxCallBackRASTREIO(retString){
			retorno_rastreio = retString;
		}

		//Funcoes para o rastremanto automatico
		function onSuccessRastreio(position){

			var var_latitude = position.coords.latitude;
			var var_longitude = position.coords.longitude;
			var var_altitude = position.coords.altitude;
			var var_accuracy = position.coords.accuracy;
			var var_altitude_accuracy = position.coords.altitudeAccuracy;
			var var_heading = position.coords.heading;
			var var_speed = position.coords.speed;

			//Zerando campos que podem vir nulos
			if(!var_altitude) {
				var_altitude = 0;
			}
			if(!var_altitude_accuracy) {
				var_altitude_accuracy = 0;
			}
			if(!var_heading) {
				var_heading = 0;
			}
			if(!var_speed) {
				var_speed = 0;
			}

			$.ajax({
			type: "POST",
			url: "http://www.interiornaweb.com.br/rastreio_mobile_teste.php",
			dataType:"text",
			data: {latitude: var_latitude, longitude: var_longitude, altitude: var_altitude, accuracy: var_accuracy, altitude_accuracy: var_altitude_accuracy, heading: var_heading, speed: var_speed, gravar: "SIM" },
			async: true,
			error: function(request, status, error) {

				//alert(request.responseText);
				ajaxCallBackRASTREIO("(Houve um problema de comunicacao com os nossos sistemas)");
			}
			}).done(function(data) {
				//Nao faz nada

				if (data == 1){
					ajaxCallBackRASTREIO("(Dados gravados com sucesso - ultima atualizacao:" + formatAMPM() + ")");
					var element = document.getElementById("posicao_atual");
					element.innerHTML = "Latitude: " + position.coords.latitude + "
" +
					"Longitude: " + position.coords.longitude + "
"+ "Altitude: " + var_altitude + "
" + "Accuracy:" + var_accuracy + "
" + "Altitude Accuracy:" + var_altitude_accuracy + "
" + "Heading: " + var_heading + "
" + "Speed: " + var_speed + "
Dados gravados com sucesso - ultima atualizacao:" + formatAMPM() + ")
";
				} else {
					ajaxCallBackRASTREIO("(Houve um problema ao gravar os dados)");
				}
			});
			var element = document.getElementById("posicao_atual");
			element.innerHTML = "Latitude: " + position.coords.latitude + "
" +
			"Longitude: " + position.coords.longitude + "
"+ "Altitude: " + var_altitude + "
" + "Accuracy:" + var_accuracy + "
" + "Altitude Accuracy:" + var_altitude_accuracy + "
" + "Heading: " + var_heading + "
" + "Speed: " + var_speed + "
" + retorno_rastreio + "
";
		}

		function DesativarRastreio(){
			//Habilitar em producao
			navigator.geolocation.clearWatch(watchID);
			clearTimeout(watchID);
			$.mobile.changePage("#pageone");
		}

		$(document).on('pageshow', '#rastreio', function(){
			if (isPhoneGapReady){
				if (isConnected) {
					//rastreando
					navigator.notification.alert('iniciando o rastreio...', alertDismissed, 'Rastreio Mobile', 'OK');
					objeto_position = new Position("43,425397", "-80,442334", 100, 10, 10, 0, 0);
					console.log(objeto_position);
					//Ambiente de testes
					//watchID = setInterval(onSuccessRastreio(objeto_position), 3000);
					//Habilitar em producao
					//watchID = navigator.geolocation.watchPosition(onSuccessRastreio, geoError,{timeout: 10000, enableHighAccuracy: false, frequency: 10000 }); //10 segundos

					watchID = setInterval(function(){
						navigator.geolocation.getCurrentPosition(onSuccessRastreio, geoError, ,{timeout: 10000, enableHighAccuracy: false});},10000); //10 segundos

				} else {
					navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Rastreio Mobile', 'OK');
					$.mobile.changePage("#pageone");
				}
			} else {
				navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Rastreio Mobile', 'OK');
				$.mobile.changePage("#pageone");
			}
		});

		<|endoftext|>