<commit_before>// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    initializePage();
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	$("#postButtonToggle").click(postButtonToggle);
	$(".postSnippet").click(popupPost);
}
//make newpost page into a popup form
function postButtonToggle(e) {
  $(this).text(function(i, text) {
  	  if (text === "Back") {
          document.getElementById('popup_container_form').style.display = "none";
      } else {
          document.getElementById('popup_container_form').style.display = "block";
      }
      return text === "Back" ? "New Post" : "Back";
  });
}

function hideNewPostForm() {
  document.getElementById('popup_container_form').style.display = "none";
}

// pop up selected post's full post
function popupPost(e) {
	console.log("clicked");
	document.getElementById('popup_container_panel').style.display = "block";
}

function hidePostPopup() {
	document.getElementById('popup_container_panel').style.display = "none";
}

// add the following:

// bump a post script

// update when new post is added
<commit_msg>text issue<commit_after>// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
    initializePage();
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	$("#postButtonToggle").click(postButtonToggle);
	$(".postSnippet").click(popupPost);
}
//make newpost page into a popup form
function postButtonToggle(e) {
  $(this).text(function(i, text) {
  	  if (text === "Back") {
          document.getElementById('popup_container_form').style.display = "none";
      } else {
          document.getElementById('popup_container_form').style.display = "block";
      }
      return text === "Back" ? "New Post" : "Back";
  });
}

function hideNewPostForm() {
  document.getElementById('popup_container_form').style.display = "none";
}

// pop up selected post's full post
function popupPost(e) {
	console.log("clicked");
	document.getElementById('popup_container_panel').style.display = "block";
}

function hidePostPopup() {
  document.getElementById('postButtonToggle').text("New Post");
	document.getElementById('popup_container_panel').style.display = "none";
}

// add the following:

// bump a post script

// update when new post is added
<|endoftext|>


<commit_before>var ws;
function WebSocketTest(server) {
    var ws;
    if ("WebSocket" in window) {
        ws = new WebSocket("ws://" + server + "/ws/");
        ws.onopen = function() {
            ws.send('get_status');
        };
        ws.onmessage = function (evt) {
            var type = evt.data.split(' ', 1)[0];
            var received_msg = evt.data.substring(evt.data.indexOf(' ') + 1)

            var msg = jQuery.parseJSON(received_msg);

            switch(type.toUpperCase()){
                case 'STATE':
                    change_state(msg['state']);
                    break;
                case 'SYSTEM':
                    update_info(msg['system']);
                    break;
                case 'STATUS':
                    change_state(msg['state']);
                    update_info(msg['observatory']['system']);
                    refresh_images();
                    break;
                case 'ENVIRONMENT':
                    update_environment(msg['data']);
                    break;
                case 'WEATHER':
                    update_info(msg['data']);
                    update_weather(msg['data']);
                    break;
                case 'CAMERA':
                    update_cameras(msg);
                    break;
                case 'SAYBOT':
                case 'PANSHELL':
                    add_chat_item(type, msg.message, msg.timestamp);
                    break;
                default:
                    break;
            }

        };
        ws.onclose = function() {
            toggle_status('off');
        };
    } else {
        toggle_status('error');
    }

    return ws;
}

function add_chat_item(name, msg, time){

    item = '
';
    item = item + ' ';
    item = item + '  ' + time +' UTC';
    item = item + '
';
    item = item + '    ';
    item = item + name;
    item = item + '    ';
    item = item + msg;
    item = item + '
';
    item = item + '
';

    $('#bot_chat').prepend(item);
}

function toggle_connection_icon(icon){
    console.log('Should toggle status here');
    // $(icon).toggleClass('success').toggleClass('danger');
    // $(icon).toggleClass('fa-check-circle-o').toggleClass('fa-exclamation-triangle');
}

function update_environment(info){
    var computer_info = info['computer_box'];
    var camera_info = info['camera_box'];

    $('.computer_box_humidity_00').html(computer_info['humidity']);
    $('.camera_box_humidity_00').html(camera_info['humidity']);

    $('.camera_box_temp_00').html(camera_info['temp_00']);
    $('.computer_box_temp_00').html(computer_info['temp_00']);
    $('.computer_box_temp_01').html(computer_info['temp_01']);
    $('.computer_box_temp_02').html(computer_info['temp_02']);
    $('.computer_box_temp_03').html(computer_info['temp_03']);
}

function update_weather(is_safe){
    if(is_safe){
        $('.safe_condition').html('Safe').addClass('success');
        $('.title-bar').removeClass('danger');
        $('.callout').removeClass('unsafe_borders').addClass('safe_borders');
    } else {
        $('.safe_condition').html('Unsafe');
        $('.title-bar').addClass('danger');
        $('.callout').addClass('unsafe_borders').removeClass('safe_borders');
    }
}

function toggle_status(status){
    var icon = $('.current_state i');
    var text = $('.current_state span');

    icon.removeClass().addClass('fa');
    if (status == 'on'){
        icon.addClass('fa-circle').addClass('success');
        text.html('Online');
    } else if (status == 'off'){
        icon.addClass('fa-bolt').addClass('danger');
        text.html('Offline').addClass('danger');
    } else {
        icon.addClass('fa-exclamation-triangle', 'danger').addClass('danger');
        text.html('Error').addClass('danger');
    }
}

function change_state(state){
    var icon = $('.current_state i');
    var text = $('.current_state span');

    icon.removeClass().addClass('fa').addClass('success');
    text.html(state.toUpperCase());
    switch(state) {
        case 'analyzing':
            icon.addClass('fa-calculator');
            break;
        case 'tracking':
            icon.addClass('fa-binoculars');
            break;
        case 'observing':
            icon.addClass('fa-camera');
            break;
        case 'pointing':
            icon.addClass('fa-bullseye');
            break;
        case 'slewing':
            icon.addClass('fa-cog fa-spin');
            break;
        case 'scheduling':
            icon.addClass('fa-tasks');
            break;
        case 'ready':
            icon.addClass('fa-thumbs-o-up');
            break;
        case 'parking':
        case 'parked':
            icon.addClass('fa-car');
            break;
        case 'sleeping':
            icon.addClass('fa-check-circle');
            break;
        default:
            icon.addClass('fa-circle');
    }
    reload_img($('.state_img img'));
}

// Find all the elements with the class that matches a return value
// and update their html
function update_info(status){
    $.each(status, function(key, val){
        $('.' + key).each(function(idx, elem){
            $(elem).html(val);
        })
    });
}

function update_cameras(cameras){
    $.each(cameras, function(cam_name, props){
        $.each(props, function(prop, val){
            $('#' + cam_name + ' .' + prop).each(function(idx, elem){
                $(elem).html(val);
            });
            if (prop == 'exptime'){
                // Start the progress bar
                var pb = $('#' + cam_name + ' .progress-bar');
                pb.width('100%');

                var exptime = $('#' + cam_name + ' .exptime');
                exptime.html(val);

                var total_time = val;
                var count_time = val;

                var exp_count = $('#' + cam_name + ' .exp_count');
                // exp_count.timer('remove');
                exp_count.timer({
                    duration: '2s',
                    callback: function(){
                        count_time = count_time - 2;
                        var perc = (count_time/total_time) * 100;
                        console.log(perc);

                        if (perc < 0){
                            pb.width('0%');
                            exp_count.timer('remove');
                        } else {
                            pb.width(perc + '%');
                        }

                    },
                    repeat: true,
                });

                var pb_count = function(cb, count){
                    var width_perc = (count / val) * 100;
                    pb.width(width_perc + '%');
                    setTimeout(cb, 1000, cb, --count);
                };

                setTimeout(pb_count, 1000, pb_count, val);
            }
        });

    });

}

// Refresh all images with `img_refresh` container class
function refresh_images(){
    $.each($('.img_refresh img'), function(idx, img){
        reload_img(img);
    });
}

// Reload individual image
function reload_img(img){
    base = $(img).attr('src').split('?')[0];
    // console.log("Reloading image: " + $(img).attr('src'));

    // Hack for others
    if(base.startsWith('http')){
        new_src = $(img).attr('src');
    } else {
        new_src = base + '?' + Math.random()
    }

    $(img).attr('src', new_src);
}
<commit_msg>Don't style safety flag<commit_after>var ws;
function WebSocketTest(server) {
    var ws;
    if ("WebSocket" in window) {
        ws = new WebSocket("ws://" + server + "/ws/");
        ws.onopen = function() {
            ws.send('get_status');
        };
        ws.onmessage = function (evt) {
            var type = evt.data.split(' ', 1)[0];
            var received_msg = evt.data.substring(evt.data.indexOf(' ') + 1)

            var msg = jQuery.parseJSON(received_msg);

            switch(type.toUpperCase()){
                case 'STATE':
                    change_state(msg['state']);
                    break;
                case 'SYSTEM':
                    update_info(msg['system']);
                    break;
                case 'STATUS':
                    change_state(msg['state']);
                    update_info(msg['observatory']['system']);
                    refresh_images();
                    break;
                case 'ENVIRONMENT':
                    update_environment(msg['data']);
                    break;
                case 'WEATHER':
                    update_info(msg['data']);
                    update_weather(msg['data']);
                    break;
                case 'CAMERA':
                    update_cameras(msg);
                    break;
                case 'SAYBOT':
                case 'PANSHELL':
                    add_chat_item(type, msg.message, msg.timestamp);
                    break;
                default:
                    break;
            }

        };
        ws.onclose = function() {
            toggle_status('off');
        };
    } else {
        toggle_status('error');
    }

    return ws;
}

function add_chat_item(name, msg, time){

    item = '
';
    item = item + ' ';
    item = item + '  ' + time +' UTC';
    item = item + '
';
    item = item + '    ';
    item = item + name;
    item = item + '    ';
    item = item + msg;
    item = item + '
';
    item = item + '
';

    $('#bot_chat').prepend(item);
}

function toggle_connection_icon(icon){
    console.log('Should toggle status here');
    // $(icon).toggleClass('success').toggleClass('danger');
    // $(icon).toggleClass('fa-check-circle-o').toggleClass('fa-exclamation-triangle');
}

function update_environment(info){
    var computer_info = info['computer_box'];
    var camera_info = info['camera_box'];

    $('.computer_box_humidity_00').html(computer_info['humidity']);
    $('.camera_box_humidity_00').html(camera_info['humidity']);

    $('.camera_box_temp_00').html(camera_info['temp_00']);
    $('.computer_box_temp_00').html(computer_info['temp_00']);
    $('.computer_box_temp_01').html(computer_info['temp_01']);
    $('.computer_box_temp_02').html(computer_info['temp_02']);
    $('.computer_box_temp_03').html(computer_info['temp_03']);
}

function update_weather(is_safe){
    if(is_safe){
        $('.safe_condition').html('Safe');
        $('.title-bar').removeClass('danger');
        $('.callout').removeClass('unsafe_borders').addClass('safe_borders');
    } else {
        $('.safe_condition').html('Unsafe');
        $('.title-bar').addClass('danger');
        $('.callout').addClass('unsafe_borders').removeClass('safe_borders');
    }
}

function toggle_status(status){
    var icon = $('.current_state i');
    var text = $('.current_state span');

    icon.removeClass().addClass('fa');
    if (status == 'on'){
        icon.addClass('fa-circle').addClass('success');
        text.html('Online');
    } else if (status == 'off'){
        icon.addClass('fa-bolt').addClass('danger');
        text.html('Offline').addClass('danger');
    } else {
        icon.addClass('fa-exclamation-triangle', 'danger').addClass('danger');
        text.html('Error').addClass('danger');
    }
}

function change_state(state){
    var icon = $('.current_state i');
    var text = $('.current_state span');

    icon.removeClass().addClass('fa').addClass('success');
    text.html(state.toUpperCase());
    switch(state) {
        case 'analyzing':
            icon.addClass('fa-calculator');
            break;
        case 'tracking':
            icon.addClass('fa-binoculars');
            break;
        case 'observing':
            icon.addClass('fa-camera');
            break;
        case 'pointing':
            icon.addClass('fa-bullseye');
            break;
        case 'slewing':
            icon.addClass('fa-cog fa-spin');
            break;
        case 'scheduling':
            icon.addClass('fa-tasks');
            break;
        case 'ready':
            icon.addClass('fa-thumbs-o-up');
            break;
        case 'parking':
        case 'parked':
            icon.addClass('fa-car');
            break;
        case 'sleeping':
            icon.addClass('fa-check-circle');
            break;
        default:
            icon.addClass('fa-circle');
    }
    reload_img($('.state_img img'));
}

// Find all the elements with the class that matches a return value
// and update their html
function update_info(status){
    $.each(status, function(key, val){
        $('.' + key).each(function(idx, elem){
            $(elem).html(val);
        })
    });
}

function update_cameras(cameras){
    $.each(cameras, function(cam_name, props){
        $.each(props, function(prop, val){
            $('#' + cam_name + ' .' + prop).each(function(idx, elem){
                $(elem).html(val);
            });
            if (prop == 'exptime'){
                // Start the progress bar
                var pb = $('#' + cam_name + ' .progress-bar');
                pb.width('100%');

                var exptime = $('#' + cam_name + ' .exptime');
                exptime.html(val);

                var total_time = val;
                var count_time = val;

                var exp_count = $('#' + cam_name + ' .exp_count');
                // exp_count.timer('remove');
                exp_count.timer({
                    duration: '2s',
                    callback: function(){
                        count_time = count_time - 2;
                        var perc = (count_time/total_time) * 100;
                        console.log(perc);

                        if (perc < 0){
                            pb.width('0%');
                            exp_count.timer('remove');
                        } else {
                            pb.width(perc + '%');
                        }

                    },
                    repeat: true,
                });

                var pb_count = function(cb, count){
                    var width_perc = (count / val) * 100;
                    pb.width(width_perc + '%');
                    setTimeout(cb, 1000, cb, --count);
                };

                setTimeout(pb_count, 1000, pb_count, val);
            }
        });

    });

}

// Refresh all images with `img_refresh` container class
function refresh_images(){
    $.each($('.img_refresh img'), function(idx, img){
        reload_img(img);
    });
}

// Reload individual image
function reload_img(img){
    base = $(img).attr('src').split('?')[0];
    // console.log("Reloading image: " + $(img).attr('src'));

    // Hack for others
    if(base.startsWith('http')){
        new_src = $(img).attr('src');
    } else {
        new_src = base + '?' + Math.random()
    }

    $(img).attr('src', new_src);
}
<|endoftext|>


<commit_before>/**
 * Created with PyCharm.
 * User: mruskov
 * Date: 22/06/13
 * Time: 13:25
 * To change this template use File | Settings | File Templates.
 */
/*wait until document is loaded*/
function init(){
    //submit_change();
    $('.target').change(submit_change);
    $('.target').change(submit_change_mul); //graphs are loaded if anything is changed

    //$('#play').click(send) // the play message is not sent from here, but from render decoration (views/index-private.html)

	var d = new Date();
	var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear()+", "+ d.getHours()+":"+d.getMinutes();

	//document.getElementById('curr_date').innerHTML = strDate;

	if(!policyExists()){
        // If code executed, then we have a new user
        // Greet them accordingly
		alert('This is your first visit. You can see the policy as it has been left by your predecessor.')
	}

    // contains elements in the following order:
    start_policy = getInitPolicy();

    console.log("found plen " + start_policy["plen"]);
    $("#len" + start_policy["plen"]).prop('checked', true);

	/*preset pswd sets value*/
    console.log("found sets " + start_policy["psets"]);
    $("#sets" + start_policy["psets"]).prop('checked', true);

	/*preset pswd dictionary value*/
    console.log("found " + (start_policy["pdict"]?"use":"no") + " dict");
    $("#dic").prop('checked', start_policy["pdict"] == 1);

    console.log("found phist difficulty " + start_policy["phist"]);
    $("#hist" + start_policy["phist"]).prop('checked', true);

    console.log("found renew " + start_policy["prenew"]);
    $("#renew" + start_policy["prenew"]).prop('checked', true);

	/*preset pswd attempts number check (yes/no)*/
    /* 0 - unlimited, 1 - limit of 10 attempts, 2 - limit of 3 attempts */
    console.log("found attempts " + start_policy["prenew"]);
    $("#renew" + start_policy["pattempts"]).prop('checked', true);

	/*preset pswd recovery option*/
    console.log("found pautorecover " + start_policy["pautorecover"]);
    $("#autorecover").prop('checked', start_policy["pautorecover"] == 1);

    console.log("Policy initialized...");
}

function verboseScore(score) {
    if(score < 0.2)
    {
        return "very low";
    }
    if(score < 0.4)
    {
        return "low";
    }
    if(score < 0.6)
    {
        return "average";
    }
    if(score < 0.8)
    {
        return "high";
    }
    if(score <= 1)
    {
        return "very high";
    }
}

/* handle AJAX (realtime) submission */
/*
send = function() { // need different event handling, to capture any change

    var obj = {};
    var obj1 = {};
	var strDate = document.forms["input"]["date"].value;
    obj.userid=document.forms["input"]["userid"].value;
    obj1.plen=$$('input[name="plen"]:checked').val();
    obj1.psets=$$('input[name="psets"]:checked').val();
    obj1.pdict=$$('input[name="pdict"]:checked').val();
    obj1.phist=$$('input[name="phist"]:checked').val();
    obj1.prenew=$$('input[name="prenew"]:checked').val();
    obj1.pattempts=$$('input[name="pattempts"]:checked').val();
    obj1.pautorecover=$$('input[name="pautorecover"]:checked').val();
    obj.data=JSON.stringify(obj1);
    obj.date=strDate;
    console.log(obj);
    var request = jQuery.ajax({
        url: "/forward",
        type: "POST",
        async : false,
        data : JSON.stringify(obj),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(score) {
            $$(score).each(function(i) {
                document.forms["input"]["date"].value=score[i].value;
            })
        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;
}
//sends data when users press play button
*/
function submit_change() { // need different event handling, to capture any change
    var d = new Date();
    var msg = {};
    var new_policy = {};
    var day = d.getDate()-1; // Why is this -1? --Martin
	var strDate =document.forms["input"]["date"].value;
    msg.date=strDate;
    msg.userid=document.forms["input"]["userid"].value;
    new_policy.plen=$('input[name="plen"]:checked').val();
    new_policy.psets=$('input[name="psets"]:checked').val();
    new_policy.pdict=$('input[name="pdict"]:checked').val();
    new_policy.phist=$('input[name="phist"]:checked').val();
    new_policy.prenew=$('input[name="prenew"]:checked').val();
    new_policy.pattempts=$('input[name="pattempts"]:checked').val();
    new_policy.pautorecover=$('input[name="pautorecover"]:checked').val();
    msg.data=JSON.stringify(new_policy);
    console.log(msg);
    var request = $.ajax({
        url: "/pwpolicy",
        type: "POST",
        async : false,
        data : JSON.stringify(msg),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(score) {
            console.log("test: " + JSON.stringify(score));
            $(score).each(function(i) {
                $("#" + score[i].name).text(verboseScore(score[i].value));
            })

        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;
}

function submit_change_mul(){
    var msgs = [];
    var new_policy = {};
    var msg = {};
    var risk = [];
    var cost = [];
    var ids = [];

    msg.id = $(this).closest($(".qn")).attr('id'); //get the id of a question with changed option

    new_policy.plen=$('input[name="plen"]:checked').val();
    new_policy.psets=$('input[name="psets"]:checked').val();
    if($('input[name="pdict"]:checked').val()==null)
    {
        new_policy.pdict = 0;
    }
    else
    {
        new_policy.pdict = 1;
    }
    if($('input[name="pautorecover"]:checked').val()==null)
    {
        new_policy.pautorecover = 0;
    }
    else
    {
        new_policy.pautorecover = 1;
    }
    //new_policy.pdict=$('input[name="pdict"]:checked').val();
    new_policy.phist=$('input[name="phist"]:checked').val();
    new_policy.prenew=$('input[name="prenew"]:checked').val();
    new_policy.pattempts=$('input[name="pattempts"]:checked').val();
    //new_policy.pautorecover=$('input[name="pautorecover"]:checked').val();
    msg.data=JSON.stringify(new_policy);
    console.log(msgs);
    msgs.push(msg);

    $(".qn").each(function(i) { //iteration accross questions
        var id_tmp =  $(this).attr('id');
        console.log(id_tmp);
        msgs = msgs.concat(get_range(new_policy, id_tmp));
    });
//    msgs = msgs.concat(get_range(new_policy, msg.id));
    // console.log(msgs.concat(get_range(new_policy, "plen")));
    var request = $.ajax({
        url: "/score/multiple",
        type: "POST",
        async : false,
        data : JSON.stringify(msgs),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(policy_costs_risks) {
            /*
            console.log("success: " + JSON.stringify(policy_costs_risks));
            $(policy_costs_risks).each(function(i) { //iteration accross policies
                //iteration accross policy values
                cost[i] = policy_costs_risks[i].cost;
                risk[i] = policy_costs_risks[i].risk;
                ids[i] = policy_costs_risks[i].id;

            })
            */

            //display_graph(ids, risk,cost);
            display_graph(policy_costs_risks);
        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;

}

function create_variation(policy, id, value) {
    var new_policy = {};
    for (var key in policy) {
        new_policy[key] = policy[key];
    }
    new_policy[id] = value;
//    new_policy['id'] = id + value;
    return new_policy;
}

function get_range (policy, id){
    var msgs = [];

        var input_vals = [];
        $(document).find("#"+id).find('input').each(function(i) {
            var new_policy = create_variation(policy, id, this.value);
            var msg = {};
           // if (this.value != policy[id]) {
                msg['id'] = id + this.value;
                msg.data=JSON.stringify(new_policy);
                msgs.push(msg);
            //}
        });
return msgs;
}
function display_graph(policy_costs_risks){ //id examples: plen, psets, pdict, etc.
    var graph_ids = ["graph_plen","graph_psets"];
    $(policy_costs_risks).each(function (i){
        $(this).each(function (j){
            +console.log(this.id);
        });

    });

    /*
    var graphid = "graph_"+ids[0];//find corresponding graph placeholder id

    var dps1 = [];
    var dps2 = [];

    $(document).find("#"+ids[0]).find('input').each(function(i) { //find options for corresponding question
        //if(this.checked== true){
            tmpRisk = {label:this.value, y:risk[i]};
            tmpCost = {label:this.value, y:cost[i]};
        //}else{
        //    tmpRisk = {label:this.value};
        //    tmpCost = {label:this.value};
        //}
        dps1.push(tmpRisk);
        dps2.push(tmpCost);

    })

    //display graph
    var chart = new CanvasJS.Chart(graphid,{
 title :{
 text: "Risc/cost"
 },
 axisX: {
 title: ids[0]
 },
 axisY: {
 title: "result"
 },
 // begin data for 2 line graphs. Note dps1 and dps2 are
 //defined above as a json object. See http://www.w3schools.com/json/
 data: [
 { type: "line", name: "R", showInLegend: true, dataPoints : dps1},
 { type: "line", name: "PC", showInLegend: true, dataPoints : dps2}
 ]
 // end of data for 2 line graphs

 }); // End of new chart variable

 chart.render();

*/

}
<commit_msg>Updated pwpolicy(js) graphs for questions<commit_after>/**
 * Created with PyCharm.
 * User: mruskov
 * Date: 22/06/13
 * Time: 13:25
 * To change this template use File | Settings | File Templates.
 */
/*wait until document is loaded*/
function init(){
    //submit_change();
    $('.target').change(submit_change);
    $('.target').change(submit_change_mul); //graphs are loaded if anything is changed

    //$('#play').click(send) // the play message is not sent from here, but from render decoration (views/index-private.html)

	var d = new Date();
	var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear()+", "+ d.getHours()+":"+d.getMinutes();

	//document.getElementById('curr_date').innerHTML = strDate;

	if(!policyExists()){
        // If code executed, then we have a new user
        // Greet them accordingly
		alert('This is your first visit. You can see the policy as it has been left by your predecessor.')
	}

    // contains elements in the following order:
    start_policy = getInitPolicy();

    console.log("found plen " + start_policy["plen"]);
    $("#len" + start_policy["plen"]).prop('checked', true);

	/*preset pswd sets value*/
    console.log("found sets " + start_policy["psets"]);
    $("#sets" + start_policy["psets"]).prop('checked', true);

	/*preset pswd dictionary value*/
    console.log("found " + (start_policy["pdict"]?"use":"no") + " dict");
    $("#dic").prop('checked', start_policy["pdict"] == 1);

    console.log("found phist difficulty " + start_policy["phist"]);
    $("#hist" + start_policy["phist"]).prop('checked', true);

    console.log("found renew " + start_policy["prenew"]);
    $("#renew" + start_policy["prenew"]).prop('checked', true);

	/*preset pswd attempts number check (yes/no)*/
    /* 0 - unlimited, 1 - limit of 10 attempts, 2 - limit of 3 attempts */
    console.log("found attempts " + start_policy["prenew"]);
    $("#renew" + start_policy["pattempts"]).prop('checked', true);

	/*preset pswd recovery option*/
    console.log("found pautorecover " + start_policy["pautorecover"]);
    $("#autorecover").prop('checked', start_policy["pautorecover"] == 1);

    console.log("Policy initialized...");
}

function verboseScore(score) {
    if(score < 0.2)
    {
        return "very low";
    }
    if(score < 0.4)
    {
        return "low";
    }
    if(score < 0.6)
    {
        return "average";
    }
    if(score < 0.8)
    {
        return "high";
    }
    if(score <= 1)
    {
        return "very high";
    }
}

/* handle AJAX (realtime) submission */
/*
send = function() { // need different event handling, to capture any change

    var obj = {};
    var obj1 = {};
	var strDate = document.forms["input"]["date"].value;
    obj.userid=document.forms["input"]["userid"].value;
    obj1.plen=$$('input[name="plen"]:checked').val();
    obj1.psets=$$('input[name="psets"]:checked').val();
    obj1.pdict=$$('input[name="pdict"]:checked').val();
    obj1.phist=$$('input[name="phist"]:checked').val();
    obj1.prenew=$$('input[name="prenew"]:checked').val();
    obj1.pattempts=$$('input[name="pattempts"]:checked').val();
    obj1.pautorecover=$$('input[name="pautorecover"]:checked').val();
    obj.data=JSON.stringify(obj1);
    obj.date=strDate;
    console.log(obj);
    var request = jQuery.ajax({
        url: "/forward",
        type: "POST",
        async : false,
        data : JSON.stringify(obj),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(score) {
            $$(score).each(function(i) {
                document.forms["input"]["date"].value=score[i].value;
            })
        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;
}
//sends data when users press play button
*/
function submit_change() { // need different event handling, to capture any change
    var d = new Date();
    var msg = {};
    var new_policy = {};
    var day = d.getDate()-1; // Why is this -1? --Martin
	var strDate =document.forms["input"]["date"].value;
    msg.date=strDate;
    msg.userid=document.forms["input"]["userid"].value;
    new_policy.plen=$('input[name="plen"]:checked').val();
    new_policy.psets=$('input[name="psets"]:checked').val();
    new_policy.pdict=$('input[name="pdict"]:checked').val();
    new_policy.phist=$('input[name="phist"]:checked').val();
    new_policy.prenew=$('input[name="prenew"]:checked').val();
    new_policy.pattempts=$('input[name="pattempts"]:checked').val();
    new_policy.pautorecover=$('input[name="pautorecover"]:checked').val();
    msg.data=JSON.stringify(new_policy);
    console.log(msg);
    var request = $.ajax({
        url: "/pwpolicy",
        type: "POST",
        async : false,
        data : JSON.stringify(msg),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(score) {
            console.log("test: " + JSON.stringify(score));
            $(score).each(function(i) {
                $("#" + score[i].name).text(verboseScore(score[i].value));
            })

        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;
}

function submit_change_mul(){
    var msgs = [];
    var new_policy = {};
    var msg = {};
    var risk = [];
    var cost = [];
    var ids = [];

    msg.id = $(this).closest($(".qn")).attr('id'); //get the id of a question with changed option

    new_policy.plen=$('input[name="plen"]:checked').val();
    new_policy.psets=$('input[name="psets"]:checked').val();
    if($('input[name="pdict"]:checked').val()==null)
    {
        new_policy.pdict = 0;
    }
    else
    {
        new_policy.pdict = 1;
    }
    if($('input[name="pautorecover"]:checked').val()==null)
    {
        new_policy.pautorecover = 0;
    }
    else
    {
        new_policy.pautorecover = 1;
    }
    //new_policy.pdict=$('input[name="pdict"]:checked').val();
    new_policy.phist=$('input[name="phist"]:checked').val();
    new_policy.prenew=$('input[name="prenew"]:checked').val();
    new_policy.pattempts=$('input[name="pattempts"]:checked').val();
    //new_policy.pautorecover=$('input[name="pautorecover"]:checked').val();
    msg.data=JSON.stringify(new_policy);

    msgs.push(msg);

    $(".qn").each(function(i) { //iteration accross questions
        var id_tmp =  $(this).attr('id');

        msgs = msgs.concat(get_range(new_policy, id_tmp));
    });
//    msgs = msgs.concat(get_range(new_policy, msg.id));
    // console.log(msgs.concat(get_range(new_policy, "plen")));
    var request = $.ajax({
        url: "/score/multiple",
        type: "POST",
        async : false,
        data : JSON.stringify(msgs),
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function(policy_costs_risks) {
            initialize_graphs(policy_costs_risks);
        },
        error: function(response) {
            console.log("fail: " + response.responseText);
        }
        });
    return false;

}

function create_variation(policy, id, value) {
    var new_policy = {};
    for (var key in policy) {
        new_policy[key] = policy[key];
    }
    new_policy[id] = value;

    return new_policy;
}

function get_range (policy, id){
    var msgs = [];
        $(document).find("#"+id).find('input').each(function(i) {
            var new_policy = create_variation(policy, id, this.value);
            var msg = {};

                msg['id'] = id + this.value;
                msg.data=JSON.stringify(new_policy);
                msgs.push(msg);

        });
return msgs;
}
function initialize_graphs(policy_costs_risks){ //id examples: plen, psets, pdict, etc.
    console.log(policy_costs_risks);
    var graph_id = {};
    dps_risk = {};
    dps_cost = {};

    $(".qn").each( function(i){
         dps_risk[$(this).closest($(".qn")).attr('id')] = [];//initializing dps
         dps_cost[$(this).closest($(".qn")).attr('id')] = [];//initializing dps
         graph_id[$(this).closest($(".qn")).attr('id')] = "graph_"+[$(this).closest($(".qn")).attr('id')]; //assigning graph ids like graph_id.plen = "graph_plen"
    });

    $(policy_costs_risks).each(function (i){
        if(this.id.replace(/[a-z]+/, '') != ''){//skip ids without value numbers to avoid duplicate data (e.g. plen)
                var new_string = this.id.replace(/[0-9]+/, ''); // removing numbers from plen0 etc.
                tmpRisk = {label:this.id, y:this.risk};
                tmpCost = {label:this.id, y:this.cost};
                dps_risk[new_string].push(tmpRisk);
                dps_cost[new_string].push(tmpCost);
        }
    });
    console.log("Initializing graphs details(ids, risks, costs)...");
    console.log(graph_id);
    console.log(dps_risk);
    console.log(dps_cost);

    display_graphs(graph_id,dps_risk,dps_cost);
}

function display_graphs(graph_id,dps_risk,dps_cost){

     $(".qn").each( function(i){

var chart = new CanvasJS.Chart(graph_id[$(this).closest($(".qn")).attr('id')],{ //processing graph for each question
 title :{
 text: "Risc/cost"
 },
 axisX: {
 title: $(this).closest($(".qn")).attr('id')
 },
 axisY: {
 title: "result"
 },
 // begin data for 2 line graphs. Note dps1 and dps2 are
 //defined above as a json object. See http://www.w3schools.com/json/
 data: [
 { type: "line", name: "R", showInLegend: true, dataPoints : dps_risk[$(this).closest($(".qn")).attr('id')]},
 { type: "line", name: "PC", showInLegend: true, dataPoints : dps_cost[$(this).closest($(".qn")).attr('id')]}
 ]
 // end of data for 2 line graphs

 }); // End of new chart variable

 chart.render();

     });

}

    /*
    var graphid = "graph_"+ids[0];//find corresponding graph placeholder id

    var dps1 = [];
    var dps2 = [];

    $(document).find("#"+ids[0]).find('input').each(function(i) { //find options for corresponding question
        //if(this.checked== true){
            tmpRisk = {label:this.value, y:risk[i]};
            tmpCost = {label:this.value, y:cost[i]};
        //}else{
        //    tmpRisk = {label:this.value};
        //    tmpCost = {label:this.value};
        //}
        dps1.push(tmpRisk);
        dps2.push(tmpCost);

    })

    //display graph
    var chart = new CanvasJS.Chart(graphid,{
 title :{
 text: "Risc/cost"
 },
 axisX: {
 title: ids[0]
 },
 axisY: {
 title: "result"
 },
 // begin data for 2 line graphs. Note dps1 and dps2 are
 //defined above as a json object. See http://www.w3schools.com/json/
 data: [
 { type: "line", name: "R", showInLegend: true, dataPoints : dps1},
 { type: "line", name: "PC", showInLegend: true, dataPoints : dps2}
 ]
 // end of data for 2 line graphs

 }); // End of new chart variable

 chart.render();

*/
<|endoftext|>


<commit_before>var post_top_url = "/api/v1/friendposts/";
var post_bottom_url = "/api/v1/friendposts/";
var comment_offsets = new Object();
var isBottominit = 0;

// post create
$("#form_post").submit(function(event) {
    alert("@");
    var feedback_api = "/api/v1/post/";
    var data = JSON.stringify({
        "post": $("input[name=post]").val()
    });
    console.log(data);
    $.ajax({
        url: feedback_api,
        type: "POST",
        contentType: "application/json",
        data: data,
        dataType: "json",
        statusCode: {
            201: function(data) {
                /*post로 생성 후 생성한 json response*/
                console.log("post submit response");
                console.log(data);
            }
        }
    });
    return false;
});

// comment create
$(document).on("submit", "#form_comment",function(event) {
        var feedback_api = "/api/v1/comment/";
        var data = JSON.stringify({
            "comment": $("input[name=comment]").val(),
            "post_key": $("input[name=post_key]").val()
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            statusCode: {
                201: function(data) {
                    console.log("post submit response");
                    console.log(data);
                    pollComment($("input[name=post_key]").val());
                }
            }
        });
        return false;
});

// polling post
function PostTopPolling() {
    $.ajax({
        url: post_top_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("TOP POLL POST  url:" + post_top_url);
            console.log(data)
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).prependTo("#timeline");
                $.waypoints('refresh');
                post_top_url = data.meta.previous;
                console.log("1 previous url:  "+post_top_url);
                if(!data.meta.previous)
                    post_top_url = "api/v1/friendposts/?id__gt=" + data.objects[0].id;
                console.log("2 previous url:  "+post_top_url);
                if(isBottominit==0) {
                    post_bottom_url = data.meta.next;
                    console.log("next url:  "+post_bottom_url);
                    isBottominit = 1;
                }
//                focusComment();
            }
        }
        });
}

// when screen on top, call PostTopPolling
$(document).ready(function() {
  PostTopPolling();
  setTimeout(function(){$("#p_timeline").waypoint(function(){postBottom();}, { offset: 'bottom-in-view' });}, 1000);
  $("#p_timeline").waypoint(function(){
  (function poll() {
    setTimeout(function(){PostTopPolling();$.ajax({complete:poll()});}, 5000);
  })()}, { offset: '0' })
});

function postBottom() {
    if(!post_bottom_url)
        return;
    $.ajax({
        url: post_bottom_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("BOTTOM POLL POST   url:" + post_bottom_url);
            console.log(data);
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).appendTo("#timeline");
                post_bottom_url = data.meta.next;
                console.log("next url:  "+post_bottom_url);
            }
        }
        });
}

// when on post, call pollComment
function focusComment(){
    $(".p_commentList").waypoint(function(){
        var tagid = $(this).attr("id");
        if (!tagid)
            return false;
        var postid = tagid.replace("commentList", "");
        pollComment(postid);
        (function poll() {
            console.log(postid);
            setTimeout(function(){$.ajax({complete:poll()});pollComment(postid);}, 60000);
        })();
    }, { offset: "bottom-in-view"});
}

$(document).on("waypoint", { offset: "bottom-in-view"}, ".p_commentList", function(){
    var tagid = $(this).attr("id");
        if (!tagid)
            return false;
        var postid = tagid.replace("commentList", "");
        pollComment(postid);
        (function poll() {
            console.log(postid);
            setTimeout(function(){$.ajax({complete:poll()});pollComment(postid);}, 60000);
        })();
})

// polling comment
function pollComment(post_id) {
    if(!post_id)
        return;

    get_uri = "/api/v1/comment/?post=" + post_id; // api inner parameter ?limit=20&offset=0"

    if(comment_offsets[post_id]){
        get_uri = "/api/v1/comment/?limit=30&offset=" + comment_offsets[post_id];
    }
    $.ajax({
        url: get_uri,
        type: "GET",
        dataType: "json",
        success: function(data) {
            if(data.objects.length != 0)
            {
                $("#comment_template").tmpl(data.objects).appendTo("#commentList"+post_id);
                comment_offsets[post_id] = data.meta.offset + data.objects.length;
                console.log("댓글 폴링한 마지막 오프셋 :"+comment_offsets[post_id]);
            }
        }
        });
}

// comment toggle
$(document).on("click", ".p_responses", function(){
                    $(this).parent().children("section").toggle();
                    $(this).toggleClass("opened");
                    return false;
                });<commit_msg>top poll paging test<commit_after>var post_top_url = "/api/v1/friendposts/";
var post_bottom_url = "/api/v1/friendposts/";
var comment_offsets = new Object();
var isBottominit = 0;

// post create
$("#form_post").submit(function(event) {
    alert("@");
    var feedback_api = "/api/v1/post/";
    var data = JSON.stringify({
        "post": $("input[name=post]").val()
    });
    console.log(data);
    $.ajax({
        url: feedback_api,
        type: "POST",
        contentType: "application/json",
        data: data,
        dataType: "json",
        statusCode: {
            201: function(data) {
                /*post로 생성 후 생성한 json response*/
                console.log("post submit response");
                console.log(data);
            }
        }
    });
    return false;
});

// comment create
$(document).on("submit", "#form_comment",function(event) {
        var feedback_api = "/api/v1/comment/";
        var data = JSON.stringify({
            "comment": $("input[name=comment]").val(),
            "post_key": $("input[name=post_key]").val()
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            statusCode: {
                201: function(data) {
                    console.log("post submit response");
                    console.log(data);
                    pollComment($("input[name=post_key]").val());
                }
            }
        });
        return false;
});

// polling post
function PostTopPolling() {
    $.ajax({
        url: post_top_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("TOP POLL POST  url:" + post_top_url);
            console.log(data)
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).prependTo("#timeline");
                $.waypoints('refresh');
                post_top_url = data.meta.previous;
                console.log("1 previous url:  "+post_top_url);
                if(!data.meta.previous)
                    post_top_url = "api/v1/friendposts/?offset=0&limit=1&id__gt=" + data.objects[0].id;
                console.log("2 previous url:  "+post_top_url);
                if(isBottominit==0) {
                    post_bottom_url = data.meta.next;
                    console.log("next url:  "+post_bottom_url);
                    isBottominit = 1;
                }
//                focusComment();
            }
        }
        });
}

// when screen on top, call PostTopPolling
$(document).ready(function() {
  PostTopPolling();
  setTimeout(function(){$("#p_timeline").waypoint(function(){postBottom();}, { offset: 'bottom-in-view' });}, 1000);
  $("#p_timeline").waypoint(function(){
  (function poll() {
    setTimeout(function(){PostTopPolling();$.ajax({complete:poll()});}, 5000);
  })()}, { offset: '0' })
});

function postBottom() {
    if(!post_bottom_url)
        return;
    $.ajax({
        url: post_bottom_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("BOTTOM POLL POST   url:" + post_bottom_url);
            console.log(data);
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).appendTo("#timeline");
                post_bottom_url = data.meta.next;
                console.log("next url:  "+post_bottom_url);
            }
        }
        });
}

// when on post, call pollComment
function focusComment(){
    $(".p_commentList").waypoint(function(){
        var tagid = $(this).attr("id");
        if (!tagid)
            return false;
        var postid = tagid.replace("commentList", "");
        pollComment(postid);
        (function poll() {
            console.log(postid);
            setTimeout(function(){$.ajax({complete:poll()});pollComment(postid);}, 60000);
        })();
    }, { offset: "bottom-in-view"});
}

$(document).on("waypoint", { offset: "bottom-in-view"}, ".p_commentList", function(){
    var tagid = $(this).attr("id");
        if (!tagid)
            return false;
        var postid = tagid.replace("commentList", "");
        pollComment(postid);
        (function poll() {
            console.log(postid);
            setTimeout(function(){$.ajax({complete:poll()});pollComment(postid);}, 60000);
        })();
})

// polling comment
function pollComment(post_id) {
    if(!post_id)
        return;

    get_uri = "/api/v1/comment/?post=" + post_id; // api inner parameter ?limit=20&offset=0"

    if(comment_offsets[post_id]){
        get_uri = "/api/v1/comment/?limit=30&offset=" + comment_offsets[post_id];
    }
    $.ajax({
        url: get_uri,
        type: "GET",
        dataType: "json",
        success: function(data) {
            if(data.objects.length != 0)
            {
                $("#comment_template").tmpl(data.objects).appendTo("#commentList"+post_id);
                comment_offsets[post_id] = data.meta.offset + data.objects.length;
                console.log("댓글 폴링한 마지막 오프셋 :"+comment_offsets[post_id]);
            }
        }
        });
}

// comment toggle
$(document).on("click", ".p_responses", function(){
                    $(this).parent().children("section").toggle();
                    $(this).toggleClass("opened");
                    return false;
                });<|endoftext|>


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

    /*
     * Simple linear regression to find the m in:
     * y = x * m + b
     * if m > 0 the series of values is increasing
     * if m < 0 the series is decreasing
     */
    var find_slope = function(values_y) {
        var sum_x = 0;
        var sum_y = 0;
        var sum_xy = 0;
        var sum_xx = 0;
        var count = values_y.length;

        /*
         * Calculate the sum for each of the parts necessary.
         */
        for (var x = 0; x < values_y.length; x++) {
            var y = values_y[x];
            sum_x += x;
            sum_y += y;
            sum_xx += x*x;
            sum_xy += x*y;
        }

        var m = (count*sum_xy - sum_x*sum_y) / (count*sum_xx - sum_x*sum_x);

        return m;
    }

    var Tutorial = function(){

        var steps = [],
            dashboard = undefined,
            open_btn = undefined,
            close_btn = undefined,
            main_cnt = undefined,
            title_cnt = undefined,
            header_cnt = undefined,
            tutorial_cnt = undefined,
            repad = function(){
                // main_cnt.css('padding-top', header_cnt.outerHeight()+4);
            },
            slide_in = function(e){
                tutorial_cnt.slideDown(500, function(){
                    open_btn.closest('li').hide();
                    repad();
                });
                e.preventDefault();
            },
            slide_out = function(e){
                tutorial_cnt.slideUp(500, function(){
                    open_btn.closest('li').show();
                    repad();
                });
                e.preventDefault();

            },
            setup_step = function(step){
                var step_number = step.data('tut-step');

                step.attr('id', 'tut-step-'+step_number).
                     data('target', '#tut-step-'+step_number).
                     data('toggle', 'tab').
                     append('

');

                _.each(step.find('.tut-help'), function(help){
                    $(help).
                        html('
'+$(help).html()+'
');
                        // html('
: '+$(help).html()+'
');
                        // html('
'+$(help).html()+'
');
                });

                // setup the answer via the callback (if present)
                if (_.isFunction(answers_setup['step_'+step_number])) {
                   answers_setup['step_'+step_number](step);
                }
            },
            add_step_button = function(where, label, goto_step_number, callback){
                var button = $('').
                                text(label).
                                addClass('btn btn-default btn-sm').
                                data('target', '#tut-step-'+goto_step_number).
                                data('toggle', 'tab').
                                on('click', function(e){
                                    if (_.isFunction(callback)){
                                        callback();
                                    }
                                    show_step(goto_step_number);
                                    e.preventDefault();
                                })
                where.append(button).append(' ');
            },
            show_step = function(step_number){
                var step = $('#tut-step-'+step_number);
                step.tab('show');
                title_cnt.html(step.data('tut-title'));
                repad();
            },
            answers_setup = function(){},
            answers = {},
            show_answer = function(step, success, message, callback){
                $(step).
                    find('.tut-result').
                    html('
'+message+'

');

                // goto next step (add button to do so)
                var next = step.data('tut-step-next');
                add_step_button($(step).find('.tut-result .tut-control'), "Next", next, callback);

                update_end_results();

                repad();
            },
            // setup the step verifiers (functions called to check the step answer);
            betweenness_bin_respond = false,
            betweenness_bin = function(step, node){
                if (!betweenness_bin_respond) {
                    return;
                }
                // what percentile of the betweenness does the current node
                var betweenness = _.values(Dashboard.current_metrics()['full:betweenness']);
                var node_betweenness = Dashboard.current_metrics()['full:betweenness'][node.id];
                var counts = _.countBy(betweenness, function(n){ return (n >= node_betweenness ? 'greater' : 'smaller') });
                var percent = Math.round((counts.greater/betweenness.length)*100); // how many % are bigger than this?

                var success = false;
                var percent_message = undefined;
                if(percent>50) {
                    percent_message ='50% least central';
                } else if (percent>25 && percent<=50) {
                    percent_message ='50% most central';
                } else if (percent>10 && percent<=25) {
                    percent_message ='25% most central';
                    success = true;
                } else if (percent>5 && percent<=10) {
                    percent_message ='10% most central';
                    success = true;
                } else if (percent>1 && percent<=5) {
                    percent_message ='5% most central';
                    success = true;
                } else if (percent<=1) {
                    percent_message ='1% most central';
                    success = true;
                }

                answers['betweenness_bin'] = success;

                $('#node-marker').hide();
                $('#node-marker').popover('destroy');

                var message = "You have selected "+node.name+". It is one of the "+percent_message+" nodes of this network. Try again?";

                show_answer(step, success, message, function(){ betweenness_bin_respond = false; });

            },
            relationship_percentage = function(step, option){
                // what % of the links are from the moderators? the metric is edges_count
                // 1. disable
                $(step).find('input[name=tut-step-2-answers]').iCheck('disable');
                // 2. find the right answer
                var total_edges = dashboard.current_metrics()['full:edges_count'];
                var user_edges = dashboard.current_metrics()['user:edges_count'];
                var answer = (total_edges-user_edges)/total_edges;
                var success = false;
                switch (option.val()) {
                    case 'lt-20':
                        success = answer<0.2;
                        break;
                    case '20-40':
                        success = (answer>=0.2 && answer<0.4);
                        break;
                    case '40-60':
                        success = (answer>=0.4 && answer<0.6);
                        break;
                    case '60-80':
                        success = (answer>=0.6 && answer<0.8);
                        break;
                    case 'gt-80':
                        success = answer>=0.8;
                        break;
                }

                answers['relationship_percentage'] = success;

                // 3. show answer
                var message = (success ? "Well done! " : "")+"Moderators in this network account for "+d3.round(answer*100)+"% of all relationships.";
                show_answer(step, success, message);
            },
            posts_percentage = function(step, option){
                // what % of the posts are from the moderators? the metric is posts_count
                // 1. disable
                $(step).find('input[name=tut-step-3-answers]').iCheck('disable');
                // 2. find the right answer
                var total_posts = dashboard.current_metrics()['full:posts_count'];
                var user_posts = dashboard.current_metrics()['user:posts_count'];
                var answer = user_posts/total_posts;
                var success = false;
                switch (option.val()) {
                    case 'lt-20':
                        success = answer<0.2;
                        break;
                    case '20-40':
                        success = (answer>=0.2 && answer<0.4);
                        break;
                    case '40-60':
                        success = (answer>=0.4 && answer<0.6);
                        break;
                    case '60-80':
                        success = (answer>=0.6 && answer<0.8);
                        break;
                    case 'gt-80':
                        success = answer>=0.8;
                        break;
                }

                answers['posts_percentage'] = success;

                // 3. show answer
                var message = (success ? "Well done! " : "")+"Your non-moderator community members have contributed "+d3.round(answer*100)+"% of all posts."
                show_answer(step, success, message);
            },
            comments_share = function(step, option){
                // Do the comment share of community content rise? the metric is user:ts_comments_share
                // 1. disable
                $(step).find('input[name=tut-step-4-answers]').iCheck('disable');
                // 2. find the right answer
                var metrics_cf = crossfilter(dashboard.data()['metrics']);
                var metrics_bydate = metrics_cf.dimension(function(m) { return m.date; });
                var last_metrics = _.map(metrics_bydate.top(5), function(m){ return m['user:ts_comments_share'];});
                var slope = find_slope(last_metrics.reverse());
                var success = false;
                var message = '';
                var messages = [
                    "Well done! The share of comments written by non-moderators has increased. This means that the conversation has become more self-sustaining lately. Good work!",
                    "Well done! The share of comments written by non-moderators has decreased. This means that the conversation has become less self-sustaining lately. Is it a random fluctuation or a trend? Do you have a plan to fix it?",
                    "The share of comments written by non-moderators has indeed increased. However, if anything this means that the conversation might have become more self-sustaining lately, not less. Good work!",
                    "The share of comments written by non-moderators has indeed decreased. However, if anything this means that the conversation might have become less self-sustaining lately, not more. Is it a random fluctuation or a trend? Do you have a plan to fix it?"
                    ];
                switch (option.val()) {
                    case 'incr-more':
                        if (slope>0) {
                            message = messages[0];
                            success = true;
                        } else {
                            message = messages[2];
                            success = false;
                        }
                        break;
                    case 'decr-more':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[3];
                            success = false;
                        }
                        break;
                    case 'incr-less':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[3];
                            success = false;
                        }
                        break;
                    case 'decr-less':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[1];
                            success = true;
                        }
                        break;
                }

                answers['comments_share'] = success;

                // 3. show answer
                show_answer(step, success, message);
            },
            modularity_increase = function(step, option){
                // Do the moderators increase or decrease modularity? the metric is louvain_modularity
                // 1. disable
                $(step).find('input[name=tut-step-5-answers]').iCheck('disable');
                // 2. find the right answer
                var total_modularity = dashboard.current_metrics()['full:louvain_modularity'];
                var user_modularity = dashboard.current_metrics()['user:louvain_modularity'];
                var modularity_increased_by_moderators = (total_modularity>user_modularity)
                var success = false;
                var message = '';

                if (modularity_increased_by_moderators) {
                    message = "Your moderators do indeed increase modularity. This may indeed signal that they are talking mostly to each other, or to a small group of people in the community";
                } else {
                    message = "Your moderators do indeed decrease modularity. This may happen because moderators try to engage many or most new users, and so they end up acting as hubs, pulling the whole network together.";
                }

                switch (option.val()) {
                    case 'incr-team':
                        if (modularity_increased_by_moderators) {
                            message = "Well done! "+message;
                            success = true;
                        }
                        break;
                    case 'incr-other':
                        break;
                    case 'decr-team':
                        break;
                    case 'decr-other':
                        if (!modularity_increased_by_moderators) {
                            message = "Well done! "+message;
                            success = true;
                        }
                        break;
                }
                answers['modularity_increase'] = success;

                // 3. show answer
                show_answer(step, success, message);
            },
            update_end_results = function(){
                var correct_answers = _.filter(answers, function(r){ return r; }).length;
                $('.tut-end-result').html(correct_answers);
            },
            restart = function(){
                answers = {};
                betweenness_bin_respond = false;
                $('input[name=tut-step-2-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-3-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-4-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-5-answers]').iCheck('enable').iCheck('uncheck');
                $('.tut-result').html('');
                $('.tut-end-result').html('-');
            };

        // add the step answer setup code
        answers_setup.step_1 = function(step){
            step.on('shown.bs.tab', function (e) {
                dashboard.close_node_popover();
                betweenness_bin_respond = true;
            })

            // setup the dashboard node callback
            dashboard.network_graph().bind('clickNode', function(e){
                betweenness_bin(step, e.data.node);
            });
        }

        answers_setup.step_2 = function(step){
            $(step).find('input[name=tut-step-2-answers]').on('ifChecked', function(event){
                relationship_percentage(step, $(this));
            });
        }

        answers_setup.step_3 = function(step){
            $(step).find('input[name=tut-step-3-answers]').on('ifChecked', function(event){
                posts_percentage(step, $(this));
            });
        }

        answers_setup.step_4 = function(step){
            $(step).find('input[name=tut-step-4-answers]').on('ifChecked', function(event){
                comments_share(step, $(this));
            });
        }

        answers_setup.step_5 = function(step){
            $(step).find('input[name=tut-step-5-answers]').on('ifChecked', function(event){
                modularity_increase(step, $(this));
            });
        }

        function t(){
        };

        t.dashboard = function(db){
            if (!arguments.length) return dashboard;

            dashboard = db;

            return t;
        }

        t.setup = function(){
            open_btn = $('#tutorial-open');
            close_btn = $('#tutorial-close');
            main_cnt = $('#main-block');
            header_cnt = $('.content-header');
            tutorial_cnt = $('#tutorial');

            open_btn.on('click', slide_in);
            close_btn.on('click', slide_out);

            // load all the steps from the page
            steps = _.map($('.tut-step'), function(s){ return $(s) });
            _.each(steps, setup_step);

            // add back/next buttons
            var first_step = _.first(steps);
            add_step_button(first_step.find('.tut-control div'), "Start", first_step.data('tut-step')+1);
            first_step.data('tut-step-next', first_step.data('tut-step')+1);

            var middle_steps = _.initial(_.rest(steps));
            _.each(middle_steps, function(s){
                var step_number = s.data('tut-step');
                s.data('tut-step-prev', step_number-1);
                s.data('tut-step-next', step_number+1);
            });

            var last_step = _.last(steps);
            add_step_button(last_step.find('.tut-control div'), "Restart", first_step.data('tut-step')+1, restart);

            // setup title
            title_cnt = $('')
            $('#tutorial .box-title').append(' - ').append(title_cnt);
            title_cnt.html(first_step.data('tut-title'));
            return t;
        }

        return t;
    };
    window.Tutorial = Tutorial();

});

<commit_msg>changes the metric considered in the third tutorial step, Fixes #25<commit_after>jQuery(function($) {
    "use strict";

    /*
     * Simple linear regression to find the m in:
     * y = x * m + b
     * if m > 0 the series of values is increasing
     * if m < 0 the series is decreasing
     */
    var find_slope = function(values_y) {
        var sum_x = 0;
        var sum_y = 0;
        var sum_xy = 0;
        var sum_xx = 0;
        var count = values_y.length;

        /*
         * Calculate the sum for each of the parts necessary.
         */
        for (var x = 0; x < values_y.length; x++) {
            var y = values_y[x];
            sum_x += x;
            sum_y += y;
            sum_xx += x*x;
            sum_xy += x*y;
        }

        var m = (count*sum_xy - sum_x*sum_y) / (count*sum_xx - sum_x*sum_x);

        return m;
    }

    var Tutorial = function(){

        var steps = [],
            dashboard = undefined,
            open_btn = undefined,
            close_btn = undefined,
            main_cnt = undefined,
            title_cnt = undefined,
            header_cnt = undefined,
            tutorial_cnt = undefined,
            repad = function(){
                // main_cnt.css('padding-top', header_cnt.outerHeight()+4);
            },
            slide_in = function(e){
                tutorial_cnt.slideDown(500, function(){
                    open_btn.closest('li').hide();
                    repad();
                });
                e.preventDefault();
            },
            slide_out = function(e){
                tutorial_cnt.slideUp(500, function(){
                    open_btn.closest('li').show();
                    repad();
                });
                e.preventDefault();

            },
            setup_step = function(step){
                var step_number = step.data('tut-step');

                step.attr('id', 'tut-step-'+step_number).
                     data('target', '#tut-step-'+step_number).
                     data('toggle', 'tab').
                     append('

');

                _.each(step.find('.tut-help'), function(help){
                    $(help).
                        html('
'+$(help).html()+'
');
                        // html('
: '+$(help).html()+'
');
                        // html('
'+$(help).html()+'
');
                });

                // setup the answer via the callback (if present)
                if (_.isFunction(answers_setup['step_'+step_number])) {
                   answers_setup['step_'+step_number](step);
                }
            },
            add_step_button = function(where, label, goto_step_number, callback){
                var button = $('').
                                text(label).
                                addClass('btn btn-default btn-sm').
                                data('target', '#tut-step-'+goto_step_number).
                                data('toggle', 'tab').
                                on('click', function(e){
                                    if (_.isFunction(callback)){
                                        callback();
                                    }
                                    show_step(goto_step_number);
                                    e.preventDefault();
                                })
                where.append(button).append(' ');
            },
            show_step = function(step_number){
                var step = $('#tut-step-'+step_number);
                step.tab('show');
                title_cnt.html(step.data('tut-title'));
                repad();
            },
            answers_setup = function(){},
            answers = {},
            show_answer = function(step, success, message, callback){
                $(step).
                    find('.tut-result').
                    html('
'+message+'

');

                // goto next step (add button to do so)
                var next = step.data('tut-step-next');
                add_step_button($(step).find('.tut-result .tut-control'), "Next", next, callback);

                update_end_results();

                repad();
            },
            // setup the step verifiers (functions called to check the step answer);
            betweenness_bin_respond = false,
            betweenness_bin = function(step, node){
                if (!betweenness_bin_respond) {
                    return;
                }
                // what percentile of the betweenness does the current node
                var betweenness = _.values(Dashboard.current_metrics()['full:betweenness']);
                var node_betweenness = Dashboard.current_metrics()['full:betweenness'][node.id];
                var counts = _.countBy(betweenness, function(n){ return (n >= node_betweenness ? 'greater' : 'smaller') });
                var percent = Math.round((counts.greater/betweenness.length)*100); // how many % are bigger than this?

                var success = false;
                var percent_message = undefined;
                if(percent>50) {
                    percent_message ='50% least central';
                } else if (percent>25 && percent<=50) {
                    percent_message ='50% most central';
                } else if (percent>10 && percent<=25) {
                    percent_message ='25% most central';
                    success = true;
                } else if (percent>5 && percent<=10) {
                    percent_message ='10% most central';
                    success = true;
                } else if (percent>1 && percent<=5) {
                    percent_message ='5% most central';
                    success = true;
                } else if (percent<=1) {
                    percent_message ='1% most central';
                    success = true;
                }

                answers['betweenness_bin'] = success;

                $('#node-marker').hide();
                $('#node-marker').popover('destroy');

                var message = "You have selected "+node.name+". It is one of the "+percent_message+" nodes of this network. Try again?";

                show_answer(step, success, message, function(){ betweenness_bin_respond = false; });

            },
            relationship_percentage = function(step, option){
                // what % of the links are from the moderators? the metric is edges_count
                // 1. disable
                $(step).find('input[name=tut-step-2-answers]').iCheck('disable');
                // 2. find the right answer
                var total_edges = dashboard.current_metrics()['full:edges_count'];
                var user_edges = dashboard.current_metrics()['user:edges_count'];
                var answer = (total_edges-user_edges)/total_edges;
                var success = false;
                switch (option.val()) {
                    case 'lt-20':
                        success = answer<0.2;
                        break;
                    case '20-40':
                        success = (answer>=0.2 && answer<0.4);
                        break;
                    case '40-60':
                        success = (answer>=0.4 && answer<0.6);
                        break;
                    case '60-80':
                        success = (answer>=0.6 && answer<0.8);
                        break;
                    case 'gt-80':
                        success = answer>=0.8;
                        break;
                }

                answers['relationship_percentage'] = success;

                // 3. show answer
                var message = (success ? "Well done! " : "")+"Moderators in this network account for "+d3.round(answer*100)+"% of all relationships.";
                show_answer(step, success, message);
            },
            posts_percentage = function(step, option){
                // what % of the posts are from the moderators? the metric is user:ts_posts_share
                // 1. disable
                $(step).find('input[name=tut-step-3-answers]').iCheck('disable');
                // 2. find the right answer
                var answer = dashboard.current_metrics()['user:ts_posts_share'];
                var success = false;
                switch (option.val()) {
                    case 'lt-20':
                        success = answer<0.2;
                        break;
                    case '20-40':
                        success = (answer>=0.2 && answer<0.4);
                        break;
                    case '40-60':
                        success = (answer>=0.4 && answer<0.6);
                        break;
                    case '60-80':
                        success = (answer>=0.6 && answer<0.8);
                        break;
                    case 'gt-80':
                        success = answer>=0.8;
                        break;
                }

                answers['posts_percentage'] = success;

                // 3. show answer
                var message = (success ? "Well done! " : "")+"Your non-moderator community members have contributed "+d3.round(answer*100)+"% of all posts."
                show_answer(step, success, message);
            },
            comments_share = function(step, option){
                // Do the comment share of community content rise? the metric is user:ts_comments_share
                // 1. disable
                $(step).find('input[name=tut-step-4-answers]').iCheck('disable');
                // 2. find the right answer
                var metrics_cf = crossfilter(dashboard.data()['metrics']);
                var metrics_bydate = metrics_cf.dimension(function(m) { return m.date; });
                var last_metrics = _.map(metrics_bydate.top(5), function(m){ return m['user:ts_comments_share'];});
                var slope = find_slope(last_metrics.reverse());
                var success = false;
                var message = '';
                var messages = [
                    "Well done! The share of comments written by non-moderators has increased. This means that the conversation has become more self-sustaining lately. Good work!",
                    "Well done! The share of comments written by non-moderators has decreased. This means that the conversation has become less self-sustaining lately. Is it a random fluctuation or a trend? Do you have a plan to fix it?",
                    "The share of comments written by non-moderators has indeed increased. However, if anything this means that the conversation might have become more self-sustaining lately, not less. Good work!",
                    "The share of comments written by non-moderators has indeed decreased. However, if anything this means that the conversation might have become less self-sustaining lately, not more. Is it a random fluctuation or a trend? Do you have a plan to fix it?"
                    ];
                switch (option.val()) {
                    case 'incr-more':
                        if (slope>0) {
                            message = messages[0];
                            success = true;
                        } else {
                            message = messages[2];
                            success = false;
                        }
                        break;
                    case 'decr-more':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[3];
                            success = false;
                        }
                        break;
                    case 'incr-less':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[3];
                            success = false;
                        }
                        break;
                    case 'decr-less':
                        if (slope>0) {
                            message = messages[2];
                            success = false;
                        } else {
                            message = messages[1];
                            success = true;
                        }
                        break;
                }

                answers['comments_share'] = success;

                // 3. show answer
                show_answer(step, success, message);
            },
            modularity_increase = function(step, option){
                // Do the moderators increase or decrease modularity? the metric is louvain_modularity
                // 1. disable
                $(step).find('input[name=tut-step-5-answers]').iCheck('disable');
                // 2. find the right answer
                var total_modularity = dashboard.current_metrics()['full:louvain_modularity'];
                var user_modularity = dashboard.current_metrics()['user:louvain_modularity'];
                var modularity_increased_by_moderators = (total_modularity>user_modularity)
                var success = false;
                var message = '';

                if (modularity_increased_by_moderators) {
                    message = "Your moderators do indeed increase modularity. This may indeed signal that they are talking mostly to each other, or to a small group of people in the community";
                } else {
                    message = "Your moderators do indeed decrease modularity. This may happen because moderators try to engage many or most new users, and so they end up acting as hubs, pulling the whole network together.";
                }

                switch (option.val()) {
                    case 'incr-team':
                        if (modularity_increased_by_moderators) {
                            message = "Well done! "+message;
                            success = true;
                        }
                        break;
                    case 'incr-other':
                        break;
                    case 'decr-team':
                        break;
                    case 'decr-other':
                        if (!modularity_increased_by_moderators) {
                            message = "Well done! "+message;
                            success = true;
                        }
                        break;
                }
                answers['modularity_increase'] = success;

                // 3. show answer
                show_answer(step, success, message);
            },
            update_end_results = function(){
                var correct_answers = _.filter(answers, function(r){ return r; }).length;
                $('.tut-end-result').html(correct_answers);
            },
            restart = function(){
                answers = {};
                betweenness_bin_respond = false;
                $('input[name=tut-step-2-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-3-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-4-answers]').iCheck('enable').iCheck('uncheck');
                $('input[name=tut-step-5-answers]').iCheck('enable').iCheck('uncheck');
                $('.tut-result').html('');
                $('.tut-end-result').html('-');
            };

        // add the step answer setup code
        answers_setup.step_1 = function(step){
            step.on('shown.bs.tab', function (e) {
                dashboard.close_node_popover();
                betweenness_bin_respond = true;
            })

            // setup the dashboard node callback
            dashboard.network_graph().bind('clickNode', function(e){
                betweenness_bin(step, e.data.node);
            });
        }

        answers_setup.step_2 = function(step){
            $(step).find('input[name=tut-step-2-answers]').on('ifChecked', function(event){
                relationship_percentage(step, $(this));
            });
        }

        answers_setup.step_3 = function(step){
            $(step).find('input[name=tut-step-3-answers]').on('ifChecked', function(event){
                posts_percentage(step, $(this));
            });
        }

        answers_setup.step_4 = function(step){
            $(step).find('input[name=tut-step-4-answers]').on('ifChecked', function(event){
                comments_share(step, $(this));
            });
        }

        answers_setup.step_5 = function(step){
            $(step).find('input[name=tut-step-5-answers]').on('ifChecked', function(event){
                modularity_increase(step, $(this));
            });
        }

        function t(){
        };

        t.dashboard = function(db){
            if (!arguments.length) return dashboard;

            dashboard = db;

            return t;
        }

        t.setup = function(){
            open_btn = $('#tutorial-open');
            close_btn = $('#tutorial-close');
            main_cnt = $('#main-block');
            header_cnt = $('.content-header');
            tutorial_cnt = $('#tutorial');

            open_btn.on('click', slide_in);
            close_btn.on('click', slide_out);

            // load all the steps from the page
            steps = _.map($('.tut-step'), function(s){ return $(s) });
            _.each(steps, setup_step);

            // add back/next buttons
            var first_step = _.first(steps);
            add_step_button(first_step.find('.tut-control div'), "Start", first_step.data('tut-step')+1);
            first_step.data('tut-step-next', first_step.data('tut-step')+1);

            var middle_steps = _.initial(_.rest(steps));
            _.each(middle_steps, function(s){
                var step_number = s.data('tut-step');
                s.data('tut-step-prev', step_number-1);
                s.data('tut-step-next', step_number+1);
            });

            var last_step = _.last(steps);
            add_step_button(last_step.find('.tut-control div'), "Restart", first_step.data('tut-step')+1, restart);

            // setup title
            title_cnt = $('')
            $('#tutorial .box-title').append(' - ').append(title_cnt);
            title_cnt.html(first_step.data('tut-title'));
            return t;
        }

        return t;
    };
    window.Tutorial = Tutorial();

});

<|endoftext|>