text:
$("[name='edit_switch']").bootstrapSwitch();
$("[name='edit_switch']").on("switchChange.bootstrapSwitch", function(event, state) {
    if (state) {
        $(".edit-lock").prop("disabled", false);
        if (["Mage",""].indexOf($("#class").val()) != -1) {
            $("#add_spell").removeClass("disabled");
        } else {
            $("#add_spell").addClass("disabled");
            $("#mana_max").prop("disabled",true);
            $("#mana_current").prop("disabled",true);
        }
    } else {
        $(".edit-lock").prop("disabled", true);
        $("#add_spell").addClass("disabled");
    }
})

function switch_size(event) {
    window_width=parseInt($('#body_container').css('width'));
    if (parseInt($('html').css('width'))<=991) {
        $("[name='edit_switch']").bootstrapSwitch('size', 'normal');
    } else {
        $("[name='edit_switch']").bootstrapSwitch('size', 'mini');
    }
}

switch_size();

window.onresize = switch_size

// Fill in the more tedious parts using js

// The skills table
function make_skill_row1(skill_name) {
    var lower_name = skill_name.toLowerCase();
    var tr = $("

");
    var td = $("	").appendTo(tr);
    var row = $("

").addClass("row").appendTo(td);
    var div1 = $("

").addClass("accordion-toggle col-xs-8").css("cursor","pointer").attr("data-toggle", "collapse").attr("data-target","#"+lower_name+"_row").appendTo(row);
    var span1 = $("").addClass("skill-arrow glyphicon glyphicon-chevron-right").appendTo(div1);
    var h4 = $("

").html(skill_name).appendTo(div1);

    var div2 = $("

").addClass("col-xs-4").appendTo(row);
    var input_group = $("

").addClass("input-group input-group-sm").appendTo(div2);
    var span2 = $("").addClass("input-group-addon").appendTo(input_group);
    var check_box = $("<input>").attr("type", "checkbox").attr("id",lower_name+"_prime").prop("disabled", true).appendTo(span2);
    var input = $("<input>").addClass("form-control edit-lock is-int").attr("id",lower_name+"_value").attr("type","text").appendTo(input_group);

    return tr
}

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

function make_skill_row2_inner(skill_name_lower,start_num) {
    var div1 = $("

").addClass("row top-buffer-small");
    var div2 = $("

").addClass("col-xs-12").appendTo(div1);
    var input_group = $("

").addClass("input-group input-group-sm").appendTo(div2);
    for (var i=start_num; i<start_num+4; i++) {
        var input = $("<input>").attr("type", "text").addClass("form-control edit-lock").attr("id", skill_name_lower+"_"+pad(i)).appendTo(input_group);
        if (i<start_num+3) {
            var span = $("").addClass("input-group-btn").css("width","3px").appendTo(input_group);
        }
    }
    return div1;
}

function make_skill_row2(skill_name,num_rows) {
    var lower_name = skill_name.toLowerCase();
    var tr = $("

");
    var td = $("	").addClass("hiddenRow").appendTo(tr);
    var div1 = $("

").addClass("accordian-body collapse").attr("id",lower_name+"_row").appendTo(td);
    for (var i=0; i<num_rows; i++) {
        var row = make_skill_row2_inner(lower_name,i*4+1);
        row.appendTo(div1)
    }
    return tr
}

$.each(["Communication","Constitution","Cunning","Dexterity","Magic","Perception","Strength","Willpower"], function (idx, value) {
    var r1 = make_skill_row1(value);
    var r2 = make_skill_row2(value, 4);
    r1.appendTo("#accordion_table");
    r2.appendTo("#accordion_table");
});

// Set of 3 input boxes to be used in many places
function set_of_3(name_lower,start_num){
    var div1 = $("

").addClass("row top-buffer-small");
    var div2 = $("

").addClass("col-xs-12").appendTo(div1);
    var input_group = $("

").addClass("input-group input-group-sm").appendTo(div2);
    for (var i=start_num; i<start_num+3; i++) {
        var input = $("<input>").attr("type", "text").addClass("form-control").attr("id", name_lower+"_"+pad(i)).appendTo(input_group);
        if (i<start_num+2) {
            var span = $("").addClass("input-group-btn").css("width","3px").appendTo(input_group);
        }
    }
    return div1;
}

function set_of_3_edit_lock(name_lower,start_num){
    var div1 = $("

").addClass("row top-buffer-small");
    var div2 = $("

").addClass("col-xs-12").appendTo(div1);
    var input_group = $("

").addClass("input-group input-group-sm").appendTo(div2);
    for (var i=start_num; i<start_num+3; i++) {
        var input = $("<input>").attr("type", "text").addClass("form-control edit-lock").attr("id", name_lower+"_"+pad(i)).appendTo(input_group);
        if (i<start_num+2) {
            var span = $("").addClass("input-group-btn").css("width","3px").appendTo(input_group);
        }
    }
    return div1;
}

// Weapons
function weapon_row(idx) {
    var row = $("

").addClass("row top-buffer-small");
    var weapon = $("

").addClass("col-xs-4 no-margin-right").appendTo(row);
    var input_group1 = $("

").addClass("input-group input-group-sm").appendTo(weapon);
    var input1 = $("<input>").attr("type","text").attr("id","weapon_"+pad(idx)).addClass("form-control").appendTo(input_group1);

    var att_dam = $("

").addClass("col-xs-5 no-margin").appendTo(row);
    var input_group2 = $("

").addClass("input-group input-group-sm").appendTo(att_dam);
    var input2 = $("<input>").attr("type","text").attr("id","attack_"+pad(idx)).addClass("form-control").appendTo(input_group2);
    var span1 = $("").addClass("input-group-btn").css("width","0px").appendTo(input_group2);
    var input3 = $("<input>").attr("type","text").attr("id","damage_"+pad(idx)).addClass("form-control").appendTo(input_group2);

    var range = $("

").addClass("col-xs-3 no-margin-left").appendTo(row);
    var input_group3 = $("

").addClass("input-group input-group-sm").appendTo(range);
    var input4 = $("<input>").attr("type","text").attr("id","range_s_"+pad(idx)).addClass("form-control is-int").appendTo(input_group3);
    var span2 = $("").addClass("input-group-btn").css("width","0px").appendTo(input_group3);
    var input5 = $("<input>").attr("type","text").attr("id","range_l_"+pad(idx)).addClass("form-control is-int").appendTo(input_group3);

    return row;
}

for (var i=0; i<6; i++) {
    var r = weapon_row(i+1);
    r.appendTo("#weapons");
}

// Talents
function talent_check(talent_name) {
    var lower_name = talent_name.toLowerCase();
    lower_name = lower_name.replace(".","");
    lower_name = lower_name.replace(" ","_");
    var input_group = $("

").addClass("input-group font-sm input-group-sm");
    var span1 = $("").addClass("input-group-addon").html(talent_name).appendTo(input_group);
    var span2 = $("").addClass("input-group-addon check").appendTo(input_group);
    var check = $("<input>").attr("type","checkbox").attr("id",lower_name).addClass("edit-lock").appendTo(span2);
    return input_group;
}

function talent_row(list) {
    var row = $("

").addClass("row top-buffer-small")
    $.each(list, function(idx, value) {
        var div = $("

").addClass("col-xs-3");
        if (idx==0) {
            div.addClass("no-margin-right")
        } else if (idx==3) {
            div.addClass("no-margin-left")
        } else {
            div.addClass("no-margin")
        }
        div.appendTo(row);
        tc=talent_check(value)
        tc.appendTo(div);
    });
    row.appendTo("#talents_and_powers")
}

talent_row(["Axes", "Bludg.", "Bows", "Brawl"]);
talent_row(["H blades", "L blades", "Spears", "Staves"]);

// Class Powers
for (var i=0; i<5; i++) {
    var r = set_of_3_edit_lock("class_power", i*3+1);
    r.appendTo("#talents_and_powers")
}

// Languages box
for (var i=0; i<4; i++) {
    var r = set_of_3_edit_lock("language", i*3+1);
    r.appendTo("#languages")
}

// Equipment box
for (var i=0; i<6; i++) {
    var r = set_of_3("equipment", i*3+1);
    r.appendTo("#equipment");
}

// adjust the primary abilities when the class is changed
$("#class").on("change", function() {
    switch(this.value) {
    case "Mage":
        $("#communication_prime").prop("checked", false);
        $("#constitution_prime").prop("checked", false);
        $("#cunning_prime").prop("checked", true);
        $("#dexterity_prime").prop("checked", false);
        $("#magic_prime").prop("checked", true);
        $("#perception_prime").prop("checked", false);
        $("#strength_prime").prop("checked", false);
        $("#willpower_prime").prop("checked", true);
        $("#mana_max").prop("disabled",false);
        $("#mana_current").prop("disabled",false);
        $("#mana_button").removeClass("disabled");
        $("#add_spell").removeClass("disabled");
        break;
    case "Rogue":
        $("#communication_prime").prop("checked", true);
        $("#constitution_prime").prop("checked", false);
        $("#cunning_prime").prop("checked", false);
        $("#dexterity_prime").prop("checked", true);
        $("#magic_prime").prop("checked", false);
        $("#perception_prime").prop("checked", true);
        $("#strength_prime").prop("checked", false);
        $("#willpower_prime").prop("checked", false);
        $("#mana_max").prop("disabled",true);
        $("#mana_current").prop("disabled",true);
        $("#mana_max").val("");
        $("#mana_current").val("");
        $("#mana_button").addClass("disabled");
        $("#add_spell").addClass("disabled");
        break;
    case "Warrior":
        $("#communication_prime").prop("checked", false);
        $("#constitution_prime").prop("checked", true);
        $("#cunning_prime").prop("checked", false);
        $("#dexterity_prime").prop("checked", true);
        $("#magic_prime").prop("checked", false);
        $("#perception_prime").prop("checked", false);
        $("#strength_prime").prop("checked", true);
        $("#willpower_prime").prop("checked", false);
        $("#mana_max").prop("disabled",true);
        $("#mana_current").prop("disabled",true);
        $("#mana_max").val("");
        $("#mana_current").val("");
        $("#mana_button").addClass("disabled");
        $("#add_spell").addClass("disabled");
        break;
    default:
        $("#communication_prime").prop("checked", false);
        $("#constitution_prime").prop("checked", false);
        $("#cunning_prime").prop("checked", false);
        $("#dexterity_prime").prop("checked", false);
        $("#magic_prime").prop("checked", false);
        $("#perception_prime").prop("checked", false);
        $("#strength_prime").prop("checked", false);
        $("#willpower_prime").prop("checked", false);
        $("#mana_max").prop("disabled",false);
        $("#mana_current").prop("disabled",false);
        $("#mana_button").removeClass("disabled");
        $("#add_spell").removeClass("disabled");
        break;
    }
})

// validate that an input has a non-negitive intiger entered
$(".is-int").on("change", function() {
    this.value = parseInt(this.value) || "0";
})

// create popovers for adding/removing health, mana, and money
$("#health_button").popover({
    html: true,
    placement: "bottom",
    container: "body",
    content: function() {
        return $("#popover_health_mana_body").html();
    },
    title: "Add/Remove Health"
}).on("shown.bs.popover", function() {
    var button = $(this)
    var pop = button.data('bs.popover').tip()
    var health_max = parseInt($("#health_max").val());
    var hc=$("#health_current")
    var a_r_v=pop.find("#add_remove_value")
    pop.find("#add").on("click", function() {
        var health_current = parseInt(hc.val());
        var add = parseInt(a_r_v.val()) || 0;
        var health_new = health_current + add
        if (health_new > health_max) {
            health_new = health_max;
        }
        hc.val(health_new);
        a_r_v.val("");
        button.popover('toggle');
    });
    pop.find("#remove").on("click", function() {
        var health_current = parseInt(hc.val());
        var remove = parseInt(a_r_v.val()) || 0;
        var health_new = health_current - remove
        if (health_new < 0) {
            health_new = 0;
        }
        hc.val(health_new);
        a_r_v.val("");
        button.popover('toggle');
    });
});

$("#mana_button").popover({
    html: true,
    placement: "bottom",
    container: "body",
    content: function() {
        return $("#popover_health_mana_body").html();
    },
    title: "Add/Remove Mana"
}).on("shown.bs.popover", function() {
    var button = $(this);
    var pop = button.data('bs.popover').tip();
    var mana_max = parseInt($("#mana_max").val());
    var mc=$("#mana_current")
    var a_r_v=pop.find("#add_remove_value")
    pop.find("#add").on("click", function() {
        var mana_current = parseInt(mc.val());
        var add = parseInt(a_r_v.val()) || 0;
        var mana_new = mana_current + add
        if (mana_new > mana_max) {
            mana_new = mana_max;
        }
        mc.val(mana_new);
        can_cast();
        a_r_v.val("");
        button.popover('toggle');
    });
    pop.find("#remove").on("click", function() {
        var mana_current = parseInt(mc.val());
        var remove = parseInt(a_r_v.val()) || 0;
        var mana_new = mana_current - remove
        if (mana_new < 0) {
            mana_new = 0;
        }
        mc.val(mana_new);
        can_cast();
        a_r_v.val("");
        button.popover('toggle');
    });
});

$("#money_button").popover({
    html: true,
    placement: "bottom",
    container: "body",
    content: function() {
        return $("#popover_money_body").html();
    },
    title: "Add/Remove Money"
}).on("shown.bs.popover", function() {
    var button = $(this);
    var pop = button.data('bs.popover').tip();
    var cg = $('#gold');
    var cs = $('#silver');
    var cc = $('#copper');
    var all = 10000*(parseInt(cg.val()) || 0) + 100*(parseInt(cs.val()) || 0) + (parseInt(cc.val()) || 0);
    var a_r_g = pop.find("#new_gold");
    var a_r_s = pop.find("#new_silver");
    var a_r_c = pop.find("#new_copper");
    pop.find('#add').on("click", function() {
        var a_r_all = 10000*(parseInt(a_r_g.val()) || 0) + 100*(parseInt(a_r_s.val()) || 0) + (parseInt(a_r_c.val()) || 0);
        var new_all = all + a_r_all;
        var tmp = new_all%10000
        ng = (new_all-tmp)/10000;
        nc = tmp%100;
        ns = (tmp-nc)/100;
        cg.val(ng);
        cc.val(nc);
        cs.val(ns);
        a_r_g.val("");
        a_r_s.val("");
        a_r_c.val("");
        button.popover('toggle');
    });
    pop.find('#remove').on("click", function() {
        var a_r_all = 10000*(parseInt(a_r_g.val()) || 0) + 100*(parseInt(a_r_s.val()) || 0) + (parseInt(a_r_c.val()) || 0);
        var new_all = all - a_r_all;
        var tmp = new_all%10000
        ng = (new_all-tmp)/10000;
        nc = tmp%100;
        ns = (tmp-nc)/100;
        cg.val(ng);
        cc.val(nc);
        cs.val(ns);
        a_r_g.val("");
        a_r_s.val("");
        a_r_c.val("");
        button.popover('toggle');
    });
});

$('body').on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});

// initialize the tree-grids
$.getJSON("./js/spells_table.json", function(data) {
    var p1=0;
    var p2=0;
    var p3=0;
    var i=1;
    $.each(data, function(key1,value1){
        var tr1 = $("

").addClass("treegrid-"+i).appendTo($("#spell_tree")).html(""+key1+"	  	");
        p1=i;
        i+=1;
        $.each(value1, function(key2,value2){
            var tr2 = $("

").addClass("treegrid-"+i).addClass("treegrid-parent-"+p1).appendTo($("#spell_tree")).html(""+key2+"	  	");
            p2=i;
            i+=1;
            if (Object.keys(value2).length>0) {
                $.each(value2, function(key3,value3){
                    var spell_name=key3.split(' ').join('_').toLowerCase();
                    var tr3 = $("

").addClass("treegrid-"+i).addClass("treegrid-parent-"+p2).appendTo($("#spell_tree")).html(''+key3+'	  <input type="checkbox" class="spell_check" id="spell_'+spell_name+'"> 	');
                    p3=i;
                    i+=1;
                    $.each(['requirement','tn', 'mp', 'cast time', 'range', 'test', 'full damage', 'half damage', 'AoE'], function(index, value4){
                        var tr4 = $("

").addClass("treegrid-"+i).addClass("treegrid-parent-"+p3).appendTo($("#spell_tree")).html(''+value4+'	 '+value3[value4]+'	');
                        i+=1
                    });
                });
            };
        });
    });
    $('#spell_tree').treegrid({
        'initialState': 'collapsed'
    });
});

$("#update_spells").on("click", function() {
    spell_list=[]
    $(".spell_check").each(function() {
        if (this.checked) {
            spell_list.push(this.id)
        }
    });
    update_spells(spell_list);
});

function update_spells(spell_list) {
    $("#known_spell_body").html("");
    $.getJSON("./js/spells.json", function(data) {
        var i=1;
        var p=0;
        $.each(spell_list, function(index1, value1) {
            var this_spell = data[value1]
            var t1 = $("

").addClass("treegrid-"+i).appendTo($("#known_spell_body")).html(''+this_spell["name"]+'	 	 '+this_spell["mp"]+'	'+this_spell["tn"]+'	 <button class="btn btn-default btn-xs spell-cast" type="button" data-toggle="popover" style="width:100%">Cast</button>	');
            p=i;
            i+=1;
            $.each(['school', 'type', 'cast time', 'range', 'test', 'full damage', 'half damage', 'AoE'], function(index2, value2) {
                var t2 = $("

").addClass("treegrid-"+i).addClass("treegrid-parent-"+p).appendTo($("#known_spell_body")).html(''+value2+'	 '+this_spell[value2]+'	');
                i+=1;
            });
        });
        $('#known_spell_tree').treegrid({
            'initialState': 'collapsed'
        });
        var spell_buttons = $(".spell-cast");
        if (spell_buttons.length > 0) {
            can_cast();
            spell_buttons.each(function(index3, value3){
                var current_button = $(value3);
                var mp = current_button.parent().prev().prev().html();
                if (mp.indexOf('-')>-1) {
                    current_button.popover({
                        html: true,
                        placement: "left",
                        container: "body",
                        content: function() {
                            return $("#popover_cast_body").html();
                        },
                        title: "Cast ammount "+mp+" MP"
                    }).on("shown.bs.popover", function() {
                        var pop = current_button.data('bs.popover').tip();
                        var mc=$("#mana_current");
                        var cast_value = pop.find("#cast_value");
                        var cast_button = pop.find("#spell_cast_po");
                        var mp_cost = mp.split("-");
                        mp_cost[1] = Math.min(mp_cost[1], mc.val());
                        cast_value.on("keyup", function(){
                            var mp = cast_value.val();
                            if (((parseInt(mp)|0) >= parseInt(mp_cost[0])) && ((parseInt(mp)|0) <= parseInt(mp_cost[1]))) {
                                cast_button.removeClass("disabled");
                            } else {
                                cast_button.addClass("disabled");
                            }
                        });
                        cast_button.on("click", function() {
                            var mp = cast_value.val();
                            var mana_new = parseInt(mc.val())-parseInt(mp);
                            mc.val(mana_new);
                            can_cast();
                            cast_value.val("")
                            current_button.popover('toggle');
                        });
                        pop.find("#spell_cancel_po").on("click", function() {
                            cast_value.val("")
                            current_button.popover('toggle');
                        });
                    });
                } else {
                    current_button.on("click", function() {
                        var mc=$("#mana_current")
                        var mana_new = parseInt(mc.val())-parseInt(mp);
                        mc.val(mana_new);
                        can_cast();
                    });
                }
            });
        }
    });
}

$("#mana_current").on("change", function() {
    var mc = parseInt($(this).val())|0
    var mm = parseInt($("#mana_max").val())|0
    if (mc > mm) {
        $(this).val(mm);
    }
    can_cast();
});

$("#health_current").on("change", function() {
    var hc = parseInt($(this).val())|0
    var hm = parseInt($("#health_max").val())|0
    if (hc > hm) {
        $(this).val(hm);
    }
});

function can_cast() {
    var mc = parseInt($("#mana_current").val())|0;
    var spell_buttons = $(".spell-cast");
    if (spell_buttons.length > 0) {
        spell_buttons.each(function(index, value) {
            var current_button = $(value)
            var mp = current_button.parent().prev().prev().html();
            if (mp.indexOf('-')>-1) {
                mp = mp.split("-")[0];
            }
            mp = parseInt(mp);
            if (mc < mp) {
                current_button.addClass("disabled");
            } else {
                current_button.removeClass("disabled");
            }
        });
    }
}

// Upload save file (json)
$("#load").on("click", function() {
    $("#file_upload").click();
})

$("#file_upload").on("change", function() {
    var file = this.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            var dataText = evt.target.result;
            input_json = dataText;
            upload_me(dataText);
        };
        reader.readAsText(file);
    };
});

function upload_me(input_json) {
    input_json = JSON.parse(input_json);
    $.each(input_json["text"], function(idx, v) {
        $("#body_container").find("#"+idx).val(v);
    });
    $.each(input_json["checkbox"], function(idx, v) {
        $("#body_container").find("#"+idx).prop("checked", v);
    });
    $.each(input_json["select"], function(idx, v) {
        $("#body_container").find("#"+idx).selectpicker("val", v);
    });
    var spell_list = []
    $.each(input_json["spell_check"], function(idx, v) {
        $("#spell_modal").find("#"+idx).prop("checked", v);
        if (v) {
            spell_list.push(idx);
        }
    });
    update_spells(spell_list);
    if ($("#class").val()=="Mage") {
        $("#add_spell").removeClass("disabled");
        $("#mana_max").prop("disabled",false);
        $("#mana_current").prop("disabled",false);
    } else {
        $("#add_spell").addClass("disabled");
        $("#mana_max").prop("disabled",true);
        $("#mana_current").prop("disabled",true);
    }
    $("#notes").val(input_json["notes"]);
}

// Save state to file (json)
$("#save").on("click", function() {
    var all_input = $("#body_container").find('input[type=text]');
    var all_checkbox = $("#body_container").find('input[type=checkbox]');
    var all_select = $("#body_container").find('select');
    var all_spell = $("#spell_modal").find("input[type=checkbox]");
    var output_json = {"text": {}, "checkbox": {}, "select": {}, "spell_check": {}, "notes": ""}
    all_input.each(function(idx, v) {
        output_json["text"][v.id] = v.value;
    });
    all_checkbox.each(function(idx, v) {
        if (v.id!="edit_switch") {
            output_json["checkbox"][v.id] = v.checked;
        }
    });
    all_select.each(function(idx,v) {
        output_json["select"][v.id] = $(v).selectpicker("val");
    });
    all_spell.each(function(idx,v) {
        output_json["spell_check"][v.id] = v.checked;
    });
    output_json["notes"]=$("#notes").val();
    save_me(output_json);
});

var illegalRe = /[\/\?<>\\:\*\|":']/g;
var controlRe = /[\x00-\x1f\x80-\x9f]/g;
var reservedRe = /^\.+$/;
var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;

function sanitize(input, replacement) {
    return input
        .replace(illegalRe, replacement)
        .replace(controlRe, replacement)
        .replace(reservedRe, replacement)
        .replace(windowsReservedRe, replacement)
        .replace(" ","_");
}

function save_me(output_json) {
    var json = JSON.stringify(output_json, null, '    ');
    var blob = new Blob([json], {type: "application/json"});
    var url = URL.createObjectURL(blob);
    var save_link = $("#file_save");
    var save_name = "save.json"
    if (output_json['text']['name']) {
        save_name = sanitize(output_json['text']['name'],"")+".json"
    }
    save_link.prop("download",save_name);
    save_link.prop("href", url);
    save_link[0].click();
}

// Clear button
$("#clear").on("click",clear_all);

function clear_all() {
    var all_input = $("#body_container").find('input[type=text]');
    var all_checkbox = $("#body_container").find('input[type=checkbox]');
    var all_select = $("#body_container").find('select');
    var all_spell = $("#spell_modal").find("input[type=checkbox]");
    all_input.each(function(idx, v) {
        v.value=""
    });
    all_checkbox.each(function(idx, v) {
        if (v.id!="edit_switch") {
            v.checked = false;
        }
    });
    all_select.each(function(idx,v) {
        $(v).selectpicker("val", "");
    });
    all_spell.each(function(idx,v) {
        v.checked = false;
    });
    $("#mana_max").prop("disabled",false);
    $("#mana_current").prop("disabled",false);
    $("#add_spell").removeClass("disabled");
    $("#notes").val("");
    update_spells([]);
}

clear_all();

// add arrows to skill expander
function toggleChevron(e) {
    $(e.target).parent().parent().prev().find('.skill-arrow').toggleClass('glyphicon-chevron-right glyphicon-chevron-down')
}

$("#accordion_table").on('hidden.bs.collapse', toggleChevron);
$("#accordion_table").on('show.bs.collapse', toggleChevron);

window.addEventListener("beforeunload", function (e) {
    var confirmationMessage = "Don't forget to save.";

    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});


text:
import pickle
import unittest

from mock import MagicMock as Mock

import pyrax.utils as utils
import pyrax.exceptions as exc

from pyrax import fakes

fake_url = "http://example.com"

class ExceptionsTest(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(ExceptionsTest, self).__init__(*args, **kwargs)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_from_response_no_body(self):
        fake_resp = fakes.FakeResponse()
        fake_resp.status_code = 666
        ret = exc.from_response(fake_resp, None)
        self.assertTrue(isinstance(ret, exc.ClientException))
        self.assertEqual(ret.code, fake_resp.status_code)

    def test_from_response_with_body(self):
        fake_resp = fakes.FakeResponse()
        fake_resp.status_code = 666
        fake_body = {"error": {
                "message": "fake_message",
                "details": "fake_details"}}
        ret = exc.from_response(fake_resp, fake_body)
        self.assertTrue(isinstance(ret, exc.ClientException))
        self.assertEqual(ret.code, fake_resp.status_code)
        self.assertEqual(ret.message, "fake_message")
        self.assertEqual(ret.details, "fake_details")
        self.assertTrue("HTTP 666" in str(ret))

    def test_pickle(self):
        error = exc.NotFound(42, 'message', 'details', 0xDEADBEEF)

        pickled_error = pickle.dumps(error, -1)
        unpickled_error = pickle.loads(pickled_error)

        self.assertIsInstance(unpickled_error, exc.NotFound)
        self.assertEqual(unpickled_error.code, 42)
        self.assertEqual(unpickled_error.message, 'message')
        self.assertEqual(unpickled_error.details, 'details')
        self.assertEqual(unpickled_error.request_id, 0xDEADBEEF)

if __name__ == "__main__":
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
FROM openshift/origin-base

ADD egress-router.sh /bin/egress-router.sh

ENTRYPOINT /bin/egress-router.sh


text:
package com.example.fw;

import java.io.File;
import java.io.FileReader;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.support.pagefactory.ByChained;

public class UIMap {

  public By MESSAGE_SUBJECT;

  static UIMap uimap2;
  static UIMap uimap3;

  static {
    uimap2 = new UIMap();
    uimap3 = new UIMap();

    uimap3.MESSAGE_SUBJECT =
        new ByChained(
            By.cssSelector("div#layout_3pane"),
            By.cssSelector("div.wm_message_pane_border"),
            By.cssSelector("div.wm_message_headers"),
            By.tagName("div"),
            By.tagName("span"));
  }

  public static UIMap get(String layout) {
    if (layout.equals("3pane")) {
      return uimap3;
    } else {
      return uimap2;
    }
  }

  protected static By uimap(Properties map, String key) {
    String locator = map.getProperty(key);
    if (locator.startsWith("xpath:")) {
      return By.xpath(locator.substring("xpath:".length()));
    } else if (locator.startsWith("css:")) {
      return By.cssSelector(locator.substring("css:".length()));
    } else {
      throw new Error("Unrecognized locator " + locator);
    }
  }

}


text:
import AjvSchema from './ajv-schema'

/*
 * createSchemaMiddleware - create a middleware to validate a payload against
 * an ajv schema. See https://github.com/epoberezkin/ajv for details.
 *
 * @public
 * @param {Object} schema - ajv schema to validate against
 * @param {Object} options - ajv options to apply to schema
 * @param {Object} keywords - dict of <keyword name>: <keyword definition>
 */
export default function createSchemaMiddleware(schema, options = {}, keywords = {}) {

  const ajvSchema = new AjvSchema(schema, options, keywords)

  return async function (req, res, next) {

    const pkg = req.body
    const headers = req.headers
    const params = req.params

    pkg.headers = headers
    pkg.params = params

    const errors = await ajvSchema.validateData(pkg)

    delete pkg.headers
    delete pkg.params

    next(errors)

  }

}


text: angular.module('cloud', []);


text:
namespace v8 {
namespace internal {

namespace {

WasmInstanceObject GetWasmInstanceOnStackTop(Isolate* isolate) {
  StackFrameIterator it(isolate, isolate->thread_local_top());
  // On top: C entry stub.
  DCHECK_EQ(StackFrame::EXIT, it.frame()->type());
  it.Advance();
  // Next: the wasm compiled frame.
  DCHECK(it.frame()->is_wasm_compiled());
  WasmCompiledFrame* frame = WasmCompiledFrame::cast(it.frame());
  return frame->wasm_instance();
}

Context GetNativeContextFromWasmInstanceOnStackTop(Isolate* isolate) {
  return GetWasmInstanceOnStackTop(isolate)->native_context();
}

class ClearThreadInWasmScope {
 public:
  ClearThreadInWasmScope() {
    DCHECK_EQ(trap_handler::IsTrapHandlerEnabled(),
              trap_handler::IsThreadInWasm());
    trap_handler::ClearThreadInWasm();
  }
  ~ClearThreadInWasmScope() {
    DCHECK(!trap_handler::IsThreadInWasm());
    trap_handler::SetThreadInWasm();
  }
};

Object ThrowWasmError(Isolate* isolate, MessageTemplate message) {
  HandleScope scope(isolate);
  Handle<Object> error_obj = isolate->factory()->NewWasmRuntimeError(message);
  return isolate->Throw(*error_obj);
}
}  // namespace

RUNTIME_FUNCTION(Runtime_WasmIsValidAnyFuncValue) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, function, 0);

  if (function->IsNull(isolate)) {
    return Smi::FromInt(true);
  }
  if (WasmExportedFunction::IsWasmExportedFunction(*function)) {
    return Smi::FromInt(true);
  }
  return Smi::FromInt(false);
}

RUNTIME_FUNCTION(Runtime_WasmMemoryGrow) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  // {delta_pages} is checked to be a positive smi in the WasmMemoryGrow builtin
  // which calls this runtime function.
  CONVERT_UINT32_ARG_CHECKED(delta_pages, 1);

  // This runtime function is always being called from wasm code.
  ClearThreadInWasmScope flag_scope;

  int ret = WasmMemoryObject::Grow(
      isolate, handle(instance->memory_object(), isolate), delta_pages);
  // The WasmMemoryGrow builtin which calls this runtime function expects us to
  // always return a Smi.
  return Smi::FromInt(ret);
}

RUNTIME_FUNCTION(Runtime_ThrowWasmError) {
  ClearThreadInWasmScope clear_wasm_flag;
  DCHECK_EQ(1, args.length());
  CONVERT_SMI_ARG_CHECKED(message_id, 0);
  return ThrowWasmError(isolate, MessageTemplateFromInt(message_id));
}

RUNTIME_FUNCTION(Runtime_ThrowWasmStackOverflow) {
  SealHandleScope shs(isolate);
  DCHECK_LE(0, args.length());
  return isolate->StackOverflow();
}

RUNTIME_FUNCTION(Runtime_WasmThrowTypeError) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kWasmTrapTypeError));
}

RUNTIME_FUNCTION(Runtime_WasmThrowCreate) {
  // TODO(kschimpf): Can this be replaced with equivalent TurboFan code/calls.
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  DCHECK(isolate->context().is_null());
  isolate->set_context(GetNativeContextFromWasmInstanceOnStackTop(isolate));
  CONVERT_ARG_CHECKED(WasmExceptionTag, tag_raw, 0);
  CONVERT_SMI_ARG_CHECKED(size, 1);
  // TODO(mstarzinger): Manually box because parameters are not visited yet.
  Handle<Object> tag(tag_raw, isolate);
  Handle<Object> exception = isolate->factory()->NewWasmRuntimeError(
      MessageTemplate::kWasmExceptionError);
  CHECK(!Object::SetProperty(isolate, exception,
                             isolate->factory()->wasm_exception_tag_symbol(),
                             tag, StoreOrigin::kMaybeKeyed,
                             Just(ShouldThrow::kThrowOnError))
             .is_null());
  Handle<FixedArray> values = isolate->factory()->NewFixedArray(size);
  CHECK(!Object::SetProperty(isolate, exception,
                             isolate->factory()->wasm_exception_values_symbol(),
                             values, StoreOrigin::kMaybeKeyed,
                             Just(ShouldThrow::kThrowOnError))
             .is_null());
  return *exception;
}

RUNTIME_FUNCTION(Runtime_WasmExceptionGetTag) {
  // TODO(kschimpf): Can this be replaced with equivalent TurboFan code/calls.
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  DCHECK(isolate->context().is_null());
  isolate->set_context(GetNativeContextFromWasmInstanceOnStackTop(isolate));
  CONVERT_ARG_CHECKED(Object, except_obj_raw, 0);
  // TODO(mstarzinger): Manually box because parameters are not visited yet.
  Handle<Object> except_obj(except_obj_raw, isolate);
  return *WasmExceptionPackage::GetExceptionTag(isolate, except_obj);
}

RUNTIME_FUNCTION(Runtime_WasmExceptionGetValues) {
  // TODO(kschimpf): Can this be replaced with equivalent TurboFan code/calls.
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  DCHECK(isolate->context().is_null());
  isolate->set_context(GetNativeContextFromWasmInstanceOnStackTop(isolate));
  CONVERT_ARG_CHECKED(Object, except_obj_raw, 0);
  // TODO(mstarzinger): Manually box because parameters are not visited yet.
  Handle<Object> except_obj(except_obj_raw, isolate);
  return *WasmExceptionPackage::GetExceptionValues(isolate, except_obj);
}

RUNTIME_FUNCTION(Runtime_WasmRunInterpreter) {
  DCHECK_EQ(2, args.length());
  HandleScope scope(isolate);
  CONVERT_NUMBER_CHECKED(int32_t, func_index, Int32, args[0]);
  CONVERT_ARG_HANDLE_CHECKED(Object, arg_buffer_obj, 1);

  // The arg buffer is the raw pointer to the caller's stack. It looks like a
  // Smi (lowest bit not set, as checked by IsSmi), but is no valid Smi. We just
  // cast it back to the raw pointer.
  CHECK(!arg_buffer_obj->IsHeapObject());
  CHECK(arg_buffer_obj->IsSmi());
  Address arg_buffer = arg_buffer_obj->ptr();

  ClearThreadInWasmScope wasm_flag;

  // Find the frame pointer and instance of the interpreter frame on the stack.
  Handle<WasmInstanceObject> instance;
  Address frame_pointer = 0;
  {
    StackFrameIterator it(isolate, isolate->thread_local_top());
    // On top: C entry stub.
    DCHECK_EQ(StackFrame::EXIT, it.frame()->type());
    it.Advance();
    // Next: the wasm interpreter entry.
    DCHECK_EQ(StackFrame::WASM_INTERPRETER_ENTRY, it.frame()->type());
    instance = handle(
        WasmInterpreterEntryFrame::cast(it.frame())->wasm_instance(), isolate);
    frame_pointer = it.frame()->fp();
  }

  // Set the current isolate's context.
  DCHECK(isolate->context().is_null());
  isolate->set_context(instance->native_context());

  // Run the function in the interpreter. Note that neither the {WasmDebugInfo}
  // nor the {InterpreterHandle} have to exist, because interpretation might
  // have been triggered by another Isolate sharing the same WasmEngine.
  Handle<WasmDebugInfo> debug_info =
      WasmInstanceObject::GetOrCreateDebugInfo(instance);
  bool success = WasmDebugInfo::RunInterpreter(
      isolate, debug_info, frame_pointer, func_index, arg_buffer);

  if (!success) {
    DCHECK(isolate->has_pending_exception());
    return ReadOnlyRoots(isolate).exception();
  }
  return ReadOnlyRoots(isolate).undefined_value();
}

RUNTIME_FUNCTION(Runtime_WasmStackGuard) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(0, args.length());
  DCHECK(!trap_handler::IsTrapHandlerEnabled() ||
         trap_handler::IsThreadInWasm());

  ClearThreadInWasmScope wasm_flag;

  // Check if this is a real stack overflow.
  StackLimitCheck check(isolate);
  if (check.JsHasOverflowed()) return isolate->StackOverflow();

  return isolate->stack_guard()->HandleInterrupts();
}

RUNTIME_FUNCTION(Runtime_WasmCompileLazy) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_SMI_ARG_CHECKED(func_index, 1);

  ClearThreadInWasmScope wasm_flag;

#ifdef DEBUG
  StackFrameIterator it(isolate, isolate->thread_local_top());
  // On top: C entry stub.
  DCHECK_EQ(StackFrame::EXIT, it.frame()->type());
  it.Advance();
  // Next: the wasm lazy compile frame.
  DCHECK_EQ(StackFrame::WASM_COMPILE_LAZY, it.frame()->type());
  DCHECK_EQ(*instance, WasmCompileLazyFrame::cast(it.frame())->wasm_instance());
#endif

  auto* native_module = instance->module_object()->native_module();
  wasm::CompileLazy(isolate, native_module, func_index);

  Address entrypoint = native_module->GetCallTargetForFunction(func_index);
  return Object(entrypoint);
}

// Should be called from within a handle scope
Handle<JSArrayBuffer> getSharedArrayBuffer(Handle<WasmInstanceObject> instance,
                                           Isolate* isolate, uint32_t address) {
  DCHECK(instance->has_memory_object());
  Handle<JSArrayBuffer> array_buffer(instance->memory_object()->array_buffer(),
                                     isolate);

  // Validation should have failed if the memory was not shared.
  DCHECK(array_buffer->is_shared());

  // Should have trapped if address was OOB
  DCHECK_LT(address, array_buffer->byte_length());
  return array_buffer;
}

RUNTIME_FUNCTION(Runtime_WasmAtomicNotify) {
  HandleScope scope(isolate);
  DCHECK_EQ(3, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_NUMBER_CHECKED(uint32_t, address, Uint32, args[1]);
  CONVERT_NUMBER_CHECKED(uint32_t, count, Uint32, args[2]);
  Handle<JSArrayBuffer> array_buffer =
      getSharedArrayBuffer(instance, isolate, address);
  return FutexEmulation::Wake(array_buffer, address, count);
}

double WaitTimeoutInMs(double timeout_ns) {
  return timeout_ns < 0
             ? V8_INFINITY
             : timeout_ns / (base::Time::kNanosecondsPerMicrosecond *
                             base::Time::kMicrosecondsPerMillisecond);
}

RUNTIME_FUNCTION(Runtime_WasmI32AtomicWait) {
  HandleScope scope(isolate);
  DCHECK_EQ(4, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_NUMBER_CHECKED(uint32_t, address, Uint32, args[1]);
  CONVERT_NUMBER_CHECKED(int32_t, expected_value, Int32, args[2]);
  CONVERT_DOUBLE_ARG_CHECKED(timeout_ns, 3);
  double timeout_ms = WaitTimeoutInMs(timeout_ns);
  Handle<JSArrayBuffer> array_buffer =
      getSharedArrayBuffer(instance, isolate, address);
  return FutexEmulation::Wait32(isolate, array_buffer, address, expected_value,
                                timeout_ms);
}

RUNTIME_FUNCTION(Runtime_WasmI64AtomicWait) {
  HandleScope scope(isolate);
  DCHECK_EQ(5, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_NUMBER_CHECKED(uint32_t, address, Uint32, args[1]);
  CONVERT_NUMBER_CHECKED(uint32_t, expected_value_high, Uint32, args[2]);
  CONVERT_NUMBER_CHECKED(uint32_t, expected_value_low, Uint32, args[3]);
  CONVERT_DOUBLE_ARG_CHECKED(timeout_ns, 4);
  int64_t expected_value = (static_cast<uint64_t>(expected_value_high) << 32) |
                           static_cast<uint64_t>(expected_value_low);
  double timeout_ms = WaitTimeoutInMs(timeout_ns);
  Handle<JSArrayBuffer> array_buffer =
      getSharedArrayBuffer(instance, isolate, address);
  return FutexEmulation::Wait64(isolate, array_buffer, address, expected_value,
                                timeout_ms);
}

namespace {
Object ThrowTableOutOfBounds(Isolate* isolate,
                             Handle<WasmInstanceObject> instance) {
  // Handle out-of-bounds access here in the runtime call, rather
  // than having the lower-level layers deal with JS exceptions.
  if (isolate->context().is_null()) {
    isolate->set_context(instance->native_context());
  }
  Handle<Object> error_obj = isolate->factory()->NewWasmRuntimeError(
      MessageTemplate::kWasmTrapTableOutOfBounds);
  return isolate->Throw(*error_obj);
}
}  // namespace

RUNTIME_FUNCTION(Runtime_WasmFunctionTableGet) {
  // This runtime function is always being called from wasm code.
  ClearThreadInWasmScope flag_scope;

  HandleScope scope(isolate);
  DCHECK_EQ(3, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_UINT32_ARG_CHECKED(table_index, 1);
  CONVERT_UINT32_ARG_CHECKED(entry_index, 2);
  DCHECK_LT(table_index, instance->tables()->length());
  auto table = handle(
      WasmTableObject::cast(instance->tables()->get(table_index)), isolate);

  if (!WasmTableObject::IsInBounds(isolate, table, entry_index)) {
    return ThrowWasmError(isolate, MessageTemplate::kWasmTrapTableOutOfBounds);
  }

  return *WasmTableObject::Get(isolate, table, entry_index);
}

RUNTIME_FUNCTION(Runtime_WasmFunctionTableSet) {
  // This runtime function is always being called from wasm code.
  ClearThreadInWasmScope flag_scope;

  HandleScope scope(isolate);
  DCHECK_EQ(4, args.length());
  CONVERT_ARG_HANDLE_CHECKED(WasmInstanceObject, instance, 0);
  CONVERT_UINT32_ARG_CHECKED(table_index, 1);
  CONVERT_UINT32_ARG_CHECKED(entry_index, 2);
  CONVERT_ARG_CHECKED(Object, element_raw, 3);
  // TODO(mstarzinger): Manually box because parameters are not visited yet.
  Handle<Object> element(element_raw, isolate);
  DCHECK_LT(table_index, instance->tables()->length());
  auto table = handle(
      WasmTableObject::cast(instance->tables()->get(table_index)), isolate);

  if (!WasmTableObject::IsInBounds(isolate, table, entry_index)) {
    return ThrowWasmError(isolate, MessageTemplate::kWasmTrapTableOutOfBounds);
  }
  WasmTableObject::Set(isolate, table, entry_index, element);
  return ReadOnlyRoots(isolate).undefined_value();
}

RUNTIME_FUNCTION(Runtime_WasmIndirectCallCheckSignatureAndGetTargetInstance) {
  HandleScope scope(isolate);
  DCHECK_EQ(3, args.length());
  auto instance =
      Handle<WasmInstanceObject>(GetWasmInstanceOnStackTop(isolate), isolate);
  CONVERT_UINT32_ARG_CHECKED(table_index, 0);
  CONVERT_UINT32_ARG_CHECKED(entry_index, 1);
  CONVERT_UINT32_ARG_CHECKED(sig_index, 2);
  DCHECK(isolate->context().is_null());
  isolate->set_context(instance->native_context());

  DCHECK_LT(table_index, instance->tables()->length());
  auto table_obj = handle(
      WasmTableObject::cast(instance->tables()->get(table_index)), isolate);

  // This check is already done in generated code.
  DCHECK(WasmTableObject::IsInBounds(isolate, table_obj, entry_index));

  bool is_valid;
  bool is_null;
  MaybeHandle<WasmInstanceObject> maybe_target_instance;
  int function_index;
  WasmTableObject::GetFunctionTableEntry(
      isolate, table_obj, entry_index, &is_valid, &is_null,
      &maybe_target_instance, &function_index);

  CHECK(is_valid);
  if (is_null) {
    // We throw a signature mismatch trap to be in sync with the generated
    // code. There we do a signature check instead of a null-check. Trap
    // reasons are not defined in the spec. Otherwise, a null-check is
    // performed before a signature, according to the spec.
    return ThrowWasmError(isolate, MessageTemplate::kWasmTrapFuncSigMismatch);
  }

  // Now we do the signature check.
  Handle<WasmInstanceObject> target_instance =
      maybe_target_instance.ToHandleChecked();

  const wasm::WasmModule* target_module =
      target_instance->module_object()->native_module()->module();

  wasm::FunctionSig* target_sig = target_module->functions[function_index].sig;

  auto target_sig_id = instance->module()->signature_map.Find(*target_sig);
  uint32_t expected_sig_id = instance->module()->signature_ids[sig_index];

  if (expected_sig_id != static_cast<uint32_t>(target_sig_id)) {
    return ThrowWasmError(isolate, MessageTemplate::kWasmTrapFuncSigMismatch);
  }

  if (function_index <
      static_cast<int>(target_instance->module()->num_imported_functions)) {
    // The function in the target instance was imported. Use its imports table,
    // which contains a tuple needed by the import wrapper.
    ImportedFunctionEntry entry(target_instance, function_index);
    return entry.object_ref();
  }
  return *target_instance;
}

RUNTIME_FUNCTION(Runtime_WasmIndirectCallGetTargetAddress) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  auto instance =
      Handle<WasmInstanceObject>(GetWasmInstanceOnStackTop(isolate), isolate);
  CONVERT_UINT32_ARG_CHECKED(table_index, 0);
  CONVERT_UINT32_ARG_CHECKED(entry_index, 1);

  DCHECK_LT(table_index, instance->tables()->length());
  auto table_obj = handle(
      WasmTableObject::cast(instance->tables()->get(table_index)), isolate);

  DCHECK(WasmTableObject::IsInBounds(isolate, table_obj, entry_index));

  bool is_valid;
  bool is_null;
  MaybeHandle<WasmInstanceObject> maybe_target_instance;
  int function_index;
  WasmTableObject::GetFunctionTableEntry(
      isolate, table_obj, entry_index, &is_valid, &is_null,
      &maybe_target_instance, &function_index);

  CHECK(is_valid);
  // The null-check should already have been done in
  // Runtime_WasmIndirectCallCheckSignatureAndGetTargetInstance. That runtime
  // function should always be called first.
  CHECK(!is_null);

  Handle<WasmInstanceObject> target_instance =
      maybe_target_instance.ToHandleChecked();

  Address call_target = 0;
  if (function_index <
      static_cast<int>(target_instance->module()->num_imported_functions)) {
    // The function in the target instance was imported. Use its imports table,
    // which contains a tuple needed by the import wrapper.
    ImportedFunctionEntry entry(target_instance, function_index);
    call_target = entry.target();
  } else {
    // The function in the target instance was not imported.
    call_target = target_instance->GetCallTarget(function_index);
  }

  // The return value is an address and not a SMI. However, the address is
  // always aligned, and a SMI uses the same space as {Address}.
  CHECK(HAS_SMI_TAG(call_target));
  return Smi(call_target);
}

RUNTIME_FUNCTION(Runtime_WasmTableInit) {
  HandleScope scope(isolate);
  DCHECK_EQ(5, args.length());
  auto instance =
      Handle<WasmInstanceObject>(GetWasmInstanceOnStackTop(isolate), isolate);
  CONVERT_UINT32_ARG_CHECKED(table_index, 0);
  CONVERT_UINT32_ARG_CHECKED(elem_segment_index, 1);
  CONVERT_UINT32_ARG_CHECKED(dst, 2);
  CONVERT_UINT32_ARG_CHECKED(src, 3);
  CONVERT_UINT32_ARG_CHECKED(count, 4);

  DCHECK(isolate->context().is_null());
  isolate->set_context(instance->native_context());

  bool oob = !WasmInstanceObject::InitTableEntries(
      isolate, instance, table_index, elem_segment_index, dst, src, count);
  if (oob) return ThrowTableOutOfBounds(isolate, instance);
  return ReadOnlyRoots(isolate).undefined_value();
}

RUNTIME_FUNCTION(Runtime_WasmTableCopy) {
  HandleScope scope(isolate);
  DCHECK_EQ(5, args.length());
  auto instance =
      Handle<WasmInstanceObject>(GetWasmInstanceOnStackTop(isolate), isolate);
  CONVERT_UINT32_ARG_CHECKED(table_src_index, 0);
  CONVERT_UINT32_ARG_CHECKED(table_dst_index, 1);
  CONVERT_UINT32_ARG_CHECKED(dst, 2);
  CONVERT_UINT32_ARG_CHECKED(src, 3);
  CONVERT_UINT32_ARG_CHECKED(count, 4);

  bool oob = !WasmInstanceObject::CopyTableEntries(
      isolate, instance, table_src_index, table_dst_index, dst, src, count);
  if (oob) return ThrowTableOutOfBounds(isolate, instance);
  return ReadOnlyRoots(isolate).undefined_value();
}
}  // namespace internal
}  // namespace v8


text:
package gov.nist.javax.sip.header.ims;

public interface PAssociatedURIHeader
  extends javax.sip.header.Header, javax.sip.header.Parameters, javax.sip.header.HeaderAddress
{
  // Fields

  public static final java.lang.String NAME = "P-Associated-URI";

  // Methods

  public void setAssociatedURI(@com.francetelecom.rd.stubs.annotation.FieldSet("associatedURI") javax.sip.address.URI arg1) throws java.lang.NullPointerException;
  @com.francetelecom.rd.stubs.annotation.FieldGet("associatedURI")
  public javax.sip.address.URI getAssociatedURI();
}


text:
package com.mcreations.renderer.velocity;

import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.runtime.resource.loader.FileResourceLoader;

/**
 *
 * @author Reza Rahimi <rahimi@m-creations.com>
 *
 */
public class VelocityRenderer {
	private static final Logger LOG = LogManager.getLogger(VelocityRenderer.class);

	public static final String[][] OPTIONS = {
	      { "s", "src", "src-path", "Source path for velocity template files" },
	      { "f", "files", "files-wildcard", "Velocity template file names pattern, by example: *.vm" },
	      { "d", "dest", "destination-path", "Destination path for rendered velocity template files" }
	};

	private static final String APPLICATION_NAME = "VelocityRenderer";

	public static void main(String[] args) {
		VelocityRenderer velocityRenderer = new VelocityRenderer();
		String sourcePath = null;
		String destPath = null;
		String filePattern = null;
		/*
		 * create the command line parser
		 */
		CommandLineParser parser = new DefaultParser();
		HelpFormatter formatter = new HelpFormatter();
		// create the Options
		Options options = new Options();
		for(String[] option : OPTIONS) {
			options.addOption(Option.builder(option[0]).argName(option[1]).type(String.class).longOpt(option[2]).hasArg(true).desc(option[3]).build());
		}
		/*
		 * Parse the command line options
		 */

		try {
			CommandLine line = parser.parse(options, args);
			/*
			 * Validate command lines options
			 */
			for(String[] option : OPTIONS) {
				if(!line.hasOption(option[2])) {
					formatter.printHelp(APPLICATION_NAME, options);
					System.exit(-1);
				}
			}

			sourcePath = line.getOptionValue("s");
			destPath = line.getOptionValue("d");
			filePattern = line.getOptionValue("f");
		} catch(ParseException e) {
			formatter.printHelp(APPLICATION_NAME, options);
		}

		/*
		 * Logging application arguments
		 */
		LOG.info("sourcePath=" + sourcePath);
		LOG.info("destPath=" + destPath);
		LOG.info("filePattern=" + filePattern);
		try {
			velocityRenderer.render(sourcePath, destPath, filePattern, null);
		} catch(Exception e) {
			LOG.error("Rendering velocity templats failed: ", e);
			System.exit(-2);
		}
	}

	public void render(String sourcePath, String destPath, String filePattern, Map<String, Object> additionalContextParameters) throws Exception {
		List<String> foundFiles = new ArrayList<String>();
		final String filePatternLocal = filePattern;
		Stream<Path> foundStream = Files.find(Paths.get(sourcePath),
		      Integer.MAX_VALUE, (path, basicFileAttributes) -> path.toFile().getName().matches(filePatternLocal));
		foundFiles = foundStream
		      .sorted()
		      .map(f -> f.getFileName().toString())
		      .collect(Collectors.toList());
		/*
		 * Velocity Engine init
		 */
		VelocityEngine ve = new VelocityEngine();
		ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file,classpath");
		ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		ve.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
		ve.setProperty("file.resource.loader.class", FileResourceLoader.class.getName());
		ve.setProperty("input.encoding", "UTF-8");
		ve.setProperty("file.resource.loader.path", Paths.get(sourcePath).toString());
		ve.setProperty("runtime.log.logsystem.log4j.logger", VelocityRenderer.class.getName());
		ve.init();

		/*
		 * Prepare velocity context
		 */
		VelocityContext context = new VelocityContext();
		if(additionalContextParameters != null && !additionalContextParameters.isEmpty()) {
			for(String paramKey : additionalContextParameters.keySet()) {
				context.put(paramKey, additionalContextParameters.get(paramKey));
			}
		}
		context.put("envVars", System.getenv());
		/*
		 * Parsing templattes and writing in destination
		 */
		for(String foundFile : foundFiles) {

			Template t = ve.getTemplate(foundFile);
			File destFile = Paths.get(destPath, FilenameUtils.getBaseName(foundFile)).toFile();
			FileWriter writer = new FileWriter(destFile, false);
			// StringWriter writer = new StringWriter();
			t.merge(context, writer);
			writer.flush();
			writer.close();
			LOG.info("Rendered velocity template file saved here: " + destFile.getAbsolutePath());
			LOG.info("\n" + FileUtils.readFileToString(destFile, StandardCharsets.UTF_8));
		}
	}

}


text:
package com.mercadopago.android.px.internal.datasource;

import android.content.Context;
import android.support.annotation.NonNull;
import com.mercadopago.android.px.configuration.PaymentConfiguration;
import com.mercadopago.android.px.core.PaymentMethodPlugin;
import com.mercadopago.android.px.internal.repository.PaymentSettingRepository;
import com.mercadopago.android.px.internal.repository.PluginInitTask;
import com.mercadopago.android.px.internal.repository.PluginRepository;
import com.mercadopago.android.px.model.PaymentMethod;
import com.mercadopago.android.px.model.PaymentMethodInfo;
import java.util.ArrayList;
import java.util.Collection;

public class PluginService implements PluginRepository {

    @NonNull private final Context context;
    @NonNull private final PaymentSettingRepository paymentSettings;

    /**
     * represents if the plugin has been initialized.
     */
    private boolean hasBeenInitialized;

    public PluginService(@NonNull final Context context,
        @NonNull final PaymentSettingRepository paymentSettings) {
        this.context = context;
        this.paymentSettings = paymentSettings;
        hasBeenInitialized = false;
    }

    @Override
    @NonNull
    public PaymentMethodPlugin getPlugin(@NonNull final String pluginId) throws IllegalStateException {

        for (final PaymentMethodPlugin plugin : all()) {
            if (plugin.getId().equalsIgnoreCase(pluginId)) {
                return plugin;
            }
        }

        throw new IllegalStateException("there is no plugin with id " + pluginId);
    }

    @NonNull
    private Iterable<PaymentMethodPlugin> all() {
        final PaymentConfiguration paymentConfiguration = paymentSettings.getPaymentConfiguration();
        return paymentConfiguration == null ? new ArrayList<PaymentMethodPlugin>() :
            paymentConfiguration.getPaymentMethodPluginList();
    }

    @Override
    @NonNull
    public PaymentMethod getPluginAsPaymentMethod(@NonNull final String pluginId, @NonNull final String paymentType) {
        final PaymentMethodPlugin plugin = getPlugin(pluginId);
        final PaymentMethodInfo paymentInfo = getPaymentMethodInfo(plugin);
        return new PaymentMethod(paymentInfo.getId(), paymentInfo.getName(), paymentType);
    }

    @Override
    @NonNull
    public PaymentMethodInfo getPaymentMethodInfo(final PaymentMethodPlugin plugin) {
        return plugin.getPaymentMethodInfo(context);
    }

    @NonNull
    @Override
    public PaymentMethodInfo getPaymentMethodInfo(@NonNull final String pluginId) {
        return getPaymentMethodInfo(getPlugin(pluginId));
    }

    @Override
    public Collection<PaymentMethodPlugin> getEnabledPlugins() {
        final Collection<PaymentMethodPlugin> plugins = new ArrayList<>();
        for (final PaymentMethodPlugin plugin : all()) {
            if (plugin.isEnabled()) {
                plugins.add(plugin);
            }
        }
        return plugins;
    }

    @Override
    public int getPaymentMethodPluginCount() {
        return getEnabledPlugins().size();
    }

    @Override
    @NonNull
    public PaymentMethodPlugin getFirstEnabledPlugin() {
        for (final PaymentMethodPlugin plugin : getEnabledPlugins()) {
            return plugin;
        }
        throw new IllegalStateException("there is no plugin");
    }

    @Override
    public PluginInitTask getInitTask(final boolean sync) {
        if (hasBeenInitialized) {
            return new PluginInitTask() {
                @Override
                public void init(@NonNull final DataInitializationCallbacks callback) {
                    callback.onDataInitialized();
                }

                @Override
                public void cancel() {
                    // Do nothing
                }
            };
        } else {
            if (sync) {
                return new PluginInitSync(all(),
                    new PaymentMethodPlugin.CheckoutData(paymentSettings.getCheckoutPreference(),
                        null,
                        paymentSettings.getPrivateKey()));
            } else {
                return new PluginInitializationAsync(all(),
                    new PaymentMethodPlugin.CheckoutData(paymentSettings.getCheckoutPreference(),
                        null,
                        paymentSettings.getPrivateKey()));
            }

        }
    }

    @Override
    public void initialized() {
        hasBeenInitialized = true;
    }

    @Override
    public boolean hasEnabledPaymentMethodPlugin() {
        return !getEnabledPlugins().isEmpty();
    }
}


text:
package armpostgresql_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/postgresql/armpostgresql"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionGet.json
func ExamplePrivateEndpointConnectionsClient_Get() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armpostgresql.NewPrivateEndpointConnectionsClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Get(ctx,
		"Default",
		"test-svr",
		"private-endpoint-connection-name",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionUpdate.json
func ExamplePrivateEndpointConnectionsClient_BeginCreateOrUpdate() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armpostgresql.NewPrivateEndpointConnectionsClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginCreateOrUpdate(ctx,
		"Default",
		"test-svr",
		"private-endpoint-connection-name",
		armpostgresql.PrivateEndpointConnection{
			Properties: &armpostgresql.PrivateEndpointConnectionProperties{
				PrivateLinkServiceConnectionState: &armpostgresql.PrivateLinkServiceConnectionStateProperty{
					Description: to.Ptr("Approved by johndoe@contoso.com"),
					Status:      to.Ptr("Approved"),
				},
			},
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	res, err := poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionDelete.json
func ExamplePrivateEndpointConnectionsClient_BeginDelete() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armpostgresql.NewPrivateEndpointConnectionsClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginDelete(ctx,
		"Default",
		"test-svr",
		"private-endpoint-connection-name",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	_, err = poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionUpdateTags.json
func ExamplePrivateEndpointConnectionsClient_BeginUpdateTags() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armpostgresql.NewPrivateEndpointConnectionsClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginUpdateTags(ctx,
		"Default",
		"test-svr",
		"private-endpoint-connection-name",
		armpostgresql.TagsObject{
			Tags: map[string]*string{
				"key1": to.Ptr("val1"),
				"key2": to.Ptr("val2"),
				"key3": to.Ptr("val3"),
			},
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	res, err := poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionList.json
func ExamplePrivateEndpointConnectionsClient_NewListByServerPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armpostgresql.NewPrivateEndpointConnectionsClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListByServerPager("Default",
		"test-svr",
		nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}


text:
package cluster

import (
	"sync"
	"time"

	"github.com/AsynkronIT/protoactor-go/actor"
	"github.com/AsynkronIT/protoactor-go/cluster/chash"
	"github.com/AsynkronIT/protoactor-go/log"
	"github.com/AsynkronIT/protoactor-go/remote"
	cmap "github.com/orcaman/concurrent-map"
)

type GrainMeta struct {
	ID      *ClusterIdentity
	PID     *actor.PID
	EventID uint64
}

type spawnTask func() *ActivationResponse

type partitionIdentityActor struct {
	cluster               *Cluster
	partitionKind         *PartitionKind
	lookup                cmap.ConcurrentMap
	chash                 chash.ConsistentHash
	spawns                map[string]spawnTask
	lastEventId           uint64
	lastEventTimestamp    time.Time
	handoverTimeout       time.Duration
	topologyChangeTimeout time.Duration
	self                  *actor.PID
	spawnings             map[string]*spawningProcess // spawning actor/grain futures
	logPartition          log.Field
}

func newPartitionIdentityActor(c *Cluster, pk *PartitionKind, rdv chash.ConsistentHash) *partitionIdentityActor {
	return &partitionIdentityActor{
		cluster:               c,
		partitionKind:         pk,
		handoverTimeout:       10 * time.Second,
		topologyChangeTimeout: 3 * time.Second,
		lookup:                cmap.New(),
		spawnings:             map[string]*spawningProcess{},
		chash:                 rdv,
		logPartition:          log.String("partition", pk.actorNames.Identity),
	}
}

func (p *partitionIdentityActor) PID() *actor.PID {
	return p.self
}

func (p *partitionIdentityActor) Receive(ctx actor.Context) {
	switch msg := ctx.Message().(type) {
	case *actor.Started:
		p.onStart(ctx)
	case *actor.Stopped:
		p.onStopped(ctx)
	case *actor.ReceiveTimeout:
		p.onTimeout(msg, ctx)
	case *actor.Stopping:
		// nothing
	case *remote.Ping:
		ctx.Respond(&remote.Pong{})

	case *ActivationRequest:
		p.handleActivationRequest(msg, ctx)
	case *ActivationTerminated:
		p.handleActivationTerminated(msg, ctx)
	case *ClusterTopology:
		p.handleClusterTopology(msg, ctx)
	default:
		plog.Error("Invalid message", p.logPartition, log.TypeOf("type", msg), log.PID("sender", ctx.Sender()))
	}
}

func (p *partitionIdentityActor) onStart(ctx actor.Context) {
	plog.Info("Started PartitionIdentity", p.logPartition)
	p.lastEventTimestamp = time.Now()
	p.self = ctx.Self()
}

func (p *partitionIdentityActor) onStopped(ctx actor.Context) {
	plog.Info("Stopped PartitionIdentity", p.logPartition)
}

func (p *partitionIdentityActor) onTimeout(msg *actor.ReceiveTimeout, ctx actor.Context) {
	ctx.SetReceiveTimeout(3 * time.Second)
	plog.Info(" ...", p.logPartition)
}

func (p *partitionIdentityActor) handleActivationRequest(msg *ActivationRequest, ctx actor.Context) {
	grainId := msg.ClusterIdentity
	key := grainId.AsKey()
	_log := plog.With(p.logPartition, log.String("grain", key))
	if p.chash == nil {
		_log.Debug("handleActivationRequest", log.String("status", "nil DHT"))
		ctx.Respond(&ActivationResponse{Pid: nil})
		return
	}
	// other member
	ownerAddr := p.chash.Get(grainId.Identity)
	if ownerAddr != p.self.Address {
		ownerPID := p.partitionKind.PidOfIdentityActor(ownerAddr)
		ctx.Forward(ownerPID)
		_log.Debug("handleActivationRequest", log.PID("forwardTo", ownerPID))
		return
	}

	// self
	if _pid, ok := p.lookup.Get(key); ok {
		_log.Debug("handleActivationRequest", log.String("status", "cache hited"))
		meta := _pid.(GrainMeta)
		ctx.Respond(&ActivationResponse{Pid: meta.PID})
		return
	}
	_log.Debug("handleActivationRequest", log.String("status", "cache missing, spawning"))
	p.spawn(msg, ctx)
}

func (p *partitionIdentityActor) handleActivationTerminated(msg *ActivationTerminated, ctx actor.Context) {
	// clean cache
	key := msg.ClusterIdentity.AsKey()
	p.lookup.Remove(key)

	ownerAddr := p.chash.Get(msg.ClusterIdentity.Identity)
	if ownerAddr != p.self.Address {
		ownerPid := p.partitionKind.PidOfIdentityActor(ownerAddr)
		ctx.Forward(ownerPid)
		plog.Debug("Terminated", p.logPartition, log.String("owner", ownerAddr), log.String("grain", key))
		return
	}
	plog.Debug("Terminated", p.logPartition, log.String("owner", "self"), log.String("grain", key))
}

func (p *partitionIdentityActor) handleClusterTopology(msg *ClusterTopology, ctx actor.Context) {
	if p.lastEventId >= msg.EventId {
		plog.Warn("Skipped ClusterTopology", log.String("kind", p.partitionKind.Kind), log.Uint64("eventId", msg.EventId), log.Int("members", len(msg.Members)))
		return
	}
	now := time.Now()
	p.lastEventId = msg.EventId
	p.chash = NewRendezvousV2(msg.Members)
	p.lookup = cmap.New()
	var req = IdentityHandoverRequest{
		EventId: msg.EventId,
		Members: msg.Members,
		Address: p.self.Address,
	}
	var wg sync.WaitGroup
	for _, member := range msg.Members {
		wg.Add(1)
		placementPid := p.partitionKind.PidOfPlacementActor(member.Address())
		go func() {
			defer wg.Done()
			_resp, err := ctx.RequestFuture(placementPid, &req, p.handoverTimeout).Result()
			if err != nil {
				plog.Error("Invalid IdentityHandoverResponse", p.logPartition, log.PID("placement", placementPid), log.Error(err))
				return
			}
			switch resp := _resp.(type) {
			case *IdentityHandoverResponse:
				p.takeOwnership(resp)
			default:
				plog.Error("Invalid IdentityHandoverResponse", p.logPartition, log.TypeOf("type", msg), log.PID("from", placementPid))
			}
		}()
	}
	wg.Wait()
	plog.Info("Updated ClusterTopology",
		log.String("kind", p.partitionKind.Kind),
		log.Uint64("eventId", msg.EventId),
		log.Int("members", len(msg.Members)),
		log.Duration("cost", time.Since(now)))
	return
}

func (p *partitionIdentityActor) takeOwnership(resp *IdentityHandoverResponse) {
	for _, tmp := range resp.Actors {
		key := tmp.ClusterIdentity.AsKey()
		if old, isExist := p.lookup.Get(key); isExist {
			_old := old.(GrainMeta)
			if _old.PID.Address == tmp.Pid.Address {
				continue
			}
		}
		p.lookup.Set(key, GrainMeta{
			ID:      tmp.ClusterIdentity,
			PID:     tmp.Pid,
			EventID: tmp.EventId,
		})
	}
}

func (p *partitionIdentityActor) spawn(msg *ActivationRequest, context actor.Context) {
	if p.cluster.MemberList.Length() <= 0 {
		context.Respond(&ActivationResponse{Pid: nil})
		plog.Error("spawn failed: Empty memberlist")
		return
	}
	key := msg.ClusterIdentity.AsKey()
	plog.Debug("spawn", log.String("grain", key))

	if ownerAddr := p.chash.Get(msg.ClusterIdentity.Identity); ownerAddr != p.self.Address {
		pid := p.partitionKind.PidOfIdentityActor(ownerAddr)
		context.Forward(pid)
		return
	}

	spawnCallback := func(r interface{}, err error) {
		delete(p.spawnings, key)
		// Check if exist in current partition dictionary
		// This is necessary to avoid race condition during partition map transferring.
		if _meta, ok := p.lookup.Get(key); ok {
			if meta, ok := _meta.(GrainMeta); ok {
				context.Respond(&ActivationResponse{Pid: meta.PID})
			} else {
				plog.Error("Invalid GrainMeta", log.TypeOf("type", meta))
				context.Respond(&ActivationResponse{Pid: nil})
				p.lookup.Remove(key)
			}
			return
		}
		p.spawningCallback(msg, context, key, r, err)
		return
	}

	// Check if is spawning, if so just await spawning finish.
	if spawning := p.spawnings[key]; spawning != nil {
		context.AwaitFuture(spawning.Future, spawnCallback)
		return
	}

	// Create SpawningProcess and cache it in spawnings dictionary.
	spawning := &spawningProcess{actor.NewFuture(context.ActorSystem(), -1), ""}
	p.spawnings[key] = spawning

	// Await SpawningProcess
	context.AwaitFuture(spawning.Future, spawnCallback)
	// Perform Spawning
	go p.spawning(spawning.PID(), msg, context, 3)
}

func (p *partitionIdentityActor) spawning(spawningPID *actor.PID, msg *ActivationRequest, context actor.Context, retryCount int) {
	// for i := 0; i < retryCount; i++ {
	// ownerAddr := p.cluster.MemberList.getPartitionMemberV2(msg.ClusterIdentity)
	ownerAddr := p.chash.Get(msg.ClusterIdentity.Identity)
	if ownerAddr == "" {
		context.Send(spawningPID, &ActivationResponse{Pid: nil})
		plog.Debug("Empty address of owner", log.PID("spawningPID", spawningPID), log.String("address", ownerAddr))
		return
	}
	timeout := p.cluster.Config.TimeoutTime
	pid := p.partitionKind.PidOfPlacementActor(ownerAddr)
	plog.Debug("spawning", log.PID("pid", pid), log.PID("spawningPID", spawningPID))
	context.RequestFuture(pid, msg, timeout).PipeTo(spawningPID)
	// }
}

func (p *partitionIdentityActor) spawningCallback(req *ActivationRequest, ctx actor.Context, key string, resp interface{}, err error) {
	plog.Debug("spawning callback", log.String("key", key), log.Object("resp", resp), log.Error(err))
	if resp == nil {
		ctx.Respond(&ActivationResponse{Pid: nil})
		return
	}
	var respPID *actor.PID
	switch _resp := resp.(type) {
	case *ActivationResponse:
		ctx.Respond(_resp)
		respPID = _resp.Pid
	default:
		ctx.Respond(&ActivationResponse{Pid: nil})
	}
	if respPID != nil {
		p.lookup.Set(key, GrainMeta{PID: respPID, ID: req.ClusterIdentity})
	}
	return
}


text:
package org.fcrepo.auth.roles.basic.integration;

import static org.fcrepo.auth.roles.basic.BasicRolesAuthorizationDelegate.EVERYONE_NAME;
import static org.slf4j.LoggerFactory.getLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.fcrepo.auth.roles.common.integration.AbstractRolesIT;
import org.fcrepo.auth.roles.common.integration.RolesFadTestObjectBean;
import org.slf4j.Logger;

/**
 * @author Scott Prater
 */
public abstract class AbstractBasicRolesIT extends AbstractRolesIT {

    private static Logger logger = getLogger(AbstractBasicRolesIT.class);

    protected final static String testParent1 = getRandomPid();
    protected final static String testParent2 = getRandomPid();
    protected final static String testParent3 = getRandomPid();
    protected final static String testParent4 = getRandomPid();
    protected final static String testChild1NoACL = getRandomPid();
    protected final static String testChild2WithACL = getRandomPid();
    protected final static String testChild3A = getRandomPid();
    protected final static String testChild3B = getRandomPid();
    protected final static String testChild4WithACL = getRandomPid();
    protected final static String testChild5WithACL = getRandomPid();
    protected final static String tsp1Data = getRandomPid();
    protected final static String tsp2Data = getRandomPid();
    protected final static String tsc1Data = getRandomPid();
    protected final static String tsc2Data = getRandomPid();

    protected final static List<RolesFadTestObjectBean> test_objs =
            defineTestObjects();

    private static List<RolesFadTestObjectBean> defineTestObjects() {

        logger.debug("testParent1: {}", testParent1);
        logger.debug("testParent2: {}", testParent2);
        logger.debug("testParent3: {}", testParent3);
        logger.debug("testParent4: {}", testParent4);
        logger.debug("testChild1NoACL: {}", testChild1NoACL);
        logger.debug("testChild2WithACL: {}", testChild2WithACL);
        logger.debug("testChild3A: {}", testChild3A);
        logger.debug("testChild3B: {}", testChild3B);
        logger.debug("testChild4WithACL: {}", testChild4WithACL);
        logger.debug("testChild5WithACL: {}", testChild5WithACL);
        logger.debug("tsp1Data: {}", tsp1Data);
        logger.debug("tsp2Data: {}", tsp2Data);
        logger.debug("tsc1Data: {}", tsc1Data);
        logger.debug("tsc2Data: {}", tsc2Data);

        final List<RolesFadTestObjectBean> test_objs = new ArrayList<>();
        /* public object with public datastream */
        final RolesFadTestObjectBean objA = new RolesFadTestObjectBean();
        objA.setPath(testParent1);
        objA.addACL(EVERYONE_NAME, "reader");
        objA.addACL("examplereader", "reader");
        objA.addACL("examplewriter", "writer");
        objA.addACL("exampleadmin", "admin");
        objA.addDatastream(tsp1Data, "Test Parent 1, datastream 1,  Hello!");
        test_objs.add(objA);

        /* public object with one public datastream, one restricted datastream */
        final RolesFadTestObjectBean objB = new RolesFadTestObjectBean();
        objB.setPath(testParent2);
        objB.addACL(EVERYONE_NAME, "reader");
        objB.addACL("examplereader", "reader");
        objB.addACL("examplewriter", "writer");
        objB.addACL("exampleadmin", "admin");
        objB.addDatastream(tsp1Data, "Test Parent 2, datastream 1,  Hello!");
        objB.addDatastream(tsp2Data,
                "Test Parent 2, datastream 2,  secret stuff");
        objB.addDatastreamACL(tsp2Data, "examplereader", "reader");
        objB.addDatastreamACL(tsp2Data, "examplewriter", "writer");
        objB.addDatastreamACL(tsp2Data, "exampleadmin", "admin");
        test_objs.add(objB);

        /* public child object with datastream, no ACLs */
        final RolesFadTestObjectBean objC = new RolesFadTestObjectBean();
        objC.setPath(testParent1 + "/" + testChild1NoACL);
        objC.addDatastream(tsc1Data, "Test Child 1, datastream 1,  Hello!");
        test_objs.add(objC);

        /* restricted child object with restricted datastreams */
        final RolesFadTestObjectBean objD = new RolesFadTestObjectBean();
        objD.setPath(testParent1 + "/" + testChild2WithACL);
        objD.addACL("examplereader", "reader");
        objD.addACL("examplewriter", "writer");
        objD.addACL("exampleadmin", "admin");
        objD.addDatastream(tsc1Data,
                "Test Child 2, datastream 1,  really secret stuff");
        objD.addDatastream(tsc2Data,
                "Test Child 2, datastream 2,  really really secret stuff");
        objD.addDatastreamACL(tsc2Data, "examplewriter", "writer");
        objD.addDatastreamACL(tsc2Data, "exampleadmin", "admin");
        test_objs.add(objD);

        /*
         * even more restricted child object, with even more restricted
         * datastreams
         */
        final RolesFadTestObjectBean objE = new RolesFadTestObjectBean();
        objE.setPath(testParent1 + "/" + testChild4WithACL);
        objE.addACL("examplewriter", "writer");
        objE.addACL("exampleadmin", "admin");
        objE.addDatastream(tsc1Data,
                "Test Child 3, datastream 1,  really secret stuff");
        objE.addDatastream(tsc2Data,
                "Test Child 3, datastream 2,  really really secret stuff");
        objE.addDatastreamACL(tsc2Data, "exampleadmin", "admin");
        test_objs.add(objE);

        /* private child object with 1 private datastream, 1 public datastream */
        final RolesFadTestObjectBean objF = new RolesFadTestObjectBean();
        objF.setPath(testParent2 + "/" + testChild5WithACL);
        objF.addACL("exampleadmin", "admin");
        objF.addDatastream(tsc1Data,
                "Test Child 5, datastream 1, burn before reading");
        objF.addDatastream(tsc2Data, "Test Child 5, datastream 2, Hello!");
        objF.addDatastreamACL(tsc2Data, EVERYONE_NAME, "reader");
        test_objs.add(objF);

        /* Public object, restricted datastream */
        final RolesFadTestObjectBean objG = new RolesFadTestObjectBean();
        objG.setPath(testParent3);
        objG.addACL(EVERYONE_NAME, "reader");
        objG.addACL("examplereader", "reader");
        objG.addACL("examplewriter", "writer");
        objG.addACL("exampleadmin", "admin");
        objG.addDatastream(tsp1Data, "Test Parent 3, datastream 1, hello!");
        objG.addDatastream(tsp2Data,
                "Test Parent 3, datastream 2, private stuff");
        objG.addDatastreamACL(tsp2Data, "exampleadmin", "admin");
        test_objs.add(objG);

        final RolesFadTestObjectBean objH = new RolesFadTestObjectBean();
        objH.setPath(testParent3 + "/" + testChild3A);
        objH.addACL("exampleadmin", "admin");
        test_objs.add(objH);

        final RolesFadTestObjectBean objI = new RolesFadTestObjectBean();
        objI.setPath(testParent3 + "/" + testChild3B);
        test_objs.add(objI);

        final RolesFadTestObjectBean objJ = new RolesFadTestObjectBean();
        objJ.setPath(testParent4);
        objJ.addACL("exampleWriterReader", "reader");
        objJ.addACL("exampleWriterReader", "writer");
        test_objs.add(objJ);

        /* restricted child object with restricted parent */
        final RolesFadTestObjectBean objK = new RolesFadTestObjectBean();
        objK.setPath(testParent4 + "/" + testChild4WithACL);
        objK.addACL("examplewriter", "writer");
        objK.addACL("exampleadmin", "admin");
        test_objs.add(objK);

        return test_objs;

    }

    public static String getRandomPid() {
        return UUID.randomUUID().toString();
    }
}


text:
using NUnit.Framework;
using _11_Hard_Calendar;

namespace UnitTests
{
    [TestFixture]
    public class CalendarTests
    {
        private CalendarGenerator _calculator;

        [SetUp]
        public void Setup()
        {
            _calculator = new CalendarGenerator();
        }

        [Test]
        public void LessThanTwoArgsShouldFail()
        {
            var args = new[] { "First" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void TwoArgsShouldSucceed()
        {
            var args = new[] { "-m11", "-y2017" };

            Assert.IsTrue(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void MoreThanTwoArgsShouldFail()
        {
            var args = new[] { "First", "Second", "Third" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void UnsupportedSwitchShouldFail()
        {
            var args = new[] { "-z11", "-y2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void IncorrectFormatMonthParamShouldFail()
        {
            var args = new[] { "1", "-y2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void MissingMonthParamShouldFail()
        {
            var args = new[] { "-m", "-y2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void NonNumericMonthParamShouldFail()
        {
            var args = new[] { "-mFred", "-y2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void InvalidMonthParamShouldFail()
        {
            var args = new[] { "-m14", "-y2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void IncorrectFormatYearParamShouldFail()
        {
            var args = new[] { "-m11", "2017" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void MissingYearParamShouldFail()
        {
            var args = new[] { "-m11", "-y" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void NonNumericYearParamShouldFail()
        {
            var args = new[] { "-m12", "-yBob" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }

        [Test]
        public void InvalidYearParamShouldFail()
        {
            var args = new[] { "-m12", "-y2100" };

            Assert.IsFalse(_calculator.IsValidCommandLine(args));
        }
    }
}


text:
package org.openntf.domino.nsfdata;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;

public interface NSFNote {

	/**
	 * The note class based on the API documentation (NOTE_CLASS_xxx). This includes deprecated and virtual types.
	 */
	public static enum NoteClass {
		DOCUMENT(0x0001), DATA(DOCUMENT), INFO(0x0002), FORM(0x0004), VIEW(0x0008), ICON(0x0010), DESIGN(0x0020), ACL(0x0040),
		HELP_INDEX(0x0080), HELP(0x0100), FILTER(0x0200), FIELD(0x0400), REPLFORMULA(0x0800), PRIVATE(0x1000), DEFAULT(0x8000),
		NOTIFYDELETION(DEFAULT), ALL(0x7fff), ALLNONDATA(0x7ffe), NONE(0x000), SINGLE_INSTANCE(DESIGN.getValue() | ACL.getValue()
				| INFO.getValue() | ICON.getValue() | HELP_INDEX.getValue() | 0), HELPUSINGDOCUMENT(HELP_INDEX), HELPABOUTDOCUMENT(HELP),
		SHAREDFIELD(FORM);

		private final int value_;
		private final boolean alias_;

		private NoteClass(final int value) {
			value_ = value;
			alias_ = false;
		}

		private NoteClass(final NoteClass aliased) {
			value_ = aliased.getValue();
			alias_ = true;
		}

		public int getValue() {
			return value_;
		}

		public boolean isAlias() {
			return alias_;
		}

		public boolean isDesign() {
			return this != DOCUMENT && this != DATA;
		}
	}

	NoteClass getNoteClass();

	int getNoteId();

	String getUniversalId();

	boolean isDefault();

	int getSequence();

	Collection<NSFItem> getItems(String itemName);

	Collection<NSFItem> getItems();

	NSFRichTextData getRichText(String itemName);

	NSFMimeData getMimeData(String itemName);

	boolean hasItem(String itemName);

	void extractFileResource(String itemName, OutputStream os) throws IOException;
}


text:
package com.hortonworks.simulator.impl.messages;

public class StartSimulation {

}