<commit_before>openerp.base_kanban = function (openerp) {
QWeb.add_template('/base_kanban/static/src/xml/base_kanban.xml');
openerp.base.views.add('kanban', 'openerp.base_kanban.KanbanView');
openerp.base_kanban.KanbanView = openerp.base.View.extend({

    init: function(parent, element_id, dataset, view_id) {
        this._super(parent, element_id);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.element_id = element_id;
        this.group_by_field = false;
        this.domains = this.dataset.domain;
        this.contexts = this.dataset.context;
        this.group_by = false;
    },

    start: function() {
        this.rpc("/base_kanban/kanbanview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.template_xml = '';

        _.each(data.fields_view.arch.children, function(child) {
            if (child.tag == "template"){
                self.template_xml = openerp.base.json_node_to_xml(child, true)
            }
        });
        if(this.template_xml){
            self.dataset.read_slice([], 0, false, function (records) {
                self.on_reload_kanban([{'records': records, 'value':false, 'header': false}]);
	        });
	    }
    },

    on_show_data: function(datas) {
        var self = this;
        this.all_records = [];
        var new_qweb = new QWeb2.Engine();
        new_qweb.add_template('<templates><t t-name="custom_template">' + this.template_xml + '</t></templates>')
		self.$element.html(QWeb.render("KanbanBiew", {"datas" :datas}));
		_.each(datas, function(data) {
	        _.each(data.records, function(record) {
	            self.$element.find("#data_" + record.id).append(new_qweb.render('custom_template', record));
	            self.all_records.push(record);
	        });
        });
        this.$element.find( ".oe_table_column " ).css("width", 99 / datas.length +"%");
		this.$element.find(".oe_column").sortable({
		    connectWith: ".oe_column",
		    stop: self.on_recieve_record,
		});
		this.$element.find(".record").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		    .find(".record-header")
		        .addClass("ui-widget-header ui-corner-all")
		        .prepend( "")
		        .end()
		    .find( ".record-content" );

		this.$element.find(".record-header .ui-icon").click(function() {
		    $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
		    $(this).parents(".record:first").find(".record-content").toggle();
		});
		this.$element.find('.record .ui-icon-closethick').click(this.on_close_action);
		this.$element.find(".oe_column").disableSelection();
    },

    on_close_action: function(e) {
        $(e.currentTarget).parents('.record:first').remove();
    },

    on_recieve_record: function(event, ui) {
        var self = this;
        var from = ui.item.index(), to = ui.item.prev().index() || 0;
        var child_record = ui.item.parent().children();
        var data, sequence=1, index = to;
        this.flag = false;
        child_record.splice(0, to);
        if(to >= 0 && child_record) {
            var record_id = child_record.attr('id').split("_");
            if(record_id.length >= 2) {
	            _.each(this.all_records, function(record){
	                if(parseInt(record_id[1]) == record.id && record.sequence) {
	                    sequence = record.sequence;
	                }
	            });
            }
        }
        _.each(child_record, function (child) {
            var child_id = parseInt($(child).attr("id").split("_")[1]);
            if(child_id) {
                self.dataset.write(child_id, {sequence: sequence});
                sequence++;
                self.flag = true;
            }
        });
        console.log(":this.group_by_field:::",this.group_by_field);
        if(ui.item.attr("id") && this.group_by_field) {
            var value = ui.item.closest("td").attr("id")
            console.log("value:::",value);
            if(value) {
                var data_val = {};
                value = value.split("_")[1];
                if(value == 'false') {
                    value = false;
                }
                data_val[this.group_by_field] = value;
                console.log("D:D:::::",data_val, parseInt(ui.item.attr("id").split("_")[1]));
                this.dataset.write(parseInt(ui.item.attr("id").split("_")[1]), data_val);
                this.flag = true;
            }
        }
        if(this.flag) {
            this.do_actual_search(this.domains, this.contexts, this.group_by);
        }
    },

    on_reload_kanban: function(datas){
        this.$element.find("#kanbanview").remove();
        this.on_show_data(datas);
    },

    do_search: function (domains, contexts, group_by) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: group_by
        }, function (results) {
            self.contexts = results.context;
            self.domains = results.domain;
            self.group_by = results.group_by;
            self.do_actual_search(results.domain, results.context, results.group_by);
        });
    },

    do_actual_search: function (domain, context, group_by) {
        var self = this;

        this.group_by_field = false;

        self.dataset.context = context;
        self.dataset.domain = domain;
        this.groups = new openerp.base.DataGroup(this, this.model, domain, context, group_by || []);
        this.groups.list([],
            function (groups) {
                if (group_by.length >= 1) {
                    self.group_by_field = group_by[0];
                    self.do_render_group(groups);
                }
            },
            function (dataset) {
                self.dataset.read_slice(false, false, false, function(records) {
                    self.on_reload_kanban([{'records': records, 'value':false, 'header' : false}]);
                });
            }
        );

    },
    do_render_group : function(datagroups){
        this.columns = [];
        var self = this;
        _.each(datagroups, function (group) {
            self.dataset.context = group.context;
            self.dataset.domain = group.domain;
            var group_name = group.value;
            var group_value = group.value;
            if(!group.value) {
                group_name = "Undefined";
                group_value = 'false';
            }
            else if(group.value instanceof Array) {
                group_name = group.value[1]
                group_value = group.value[0]
            }
	        self.dataset.read_slice(false, false, false, function(records) {
                self.columns.push({"value" : group_value, "records": records, 'header':group_name});
                if (datagroups.length == self.columns.length) {
                    self.on_reload_kanban(self.columns);
	            }
	        });
        });
    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[IMP] Improve code.<commit_after>openerp.base_kanban = function (openerp) {
QWeb.add_template('/base_kanban/static/src/xml/base_kanban.xml');
openerp.base.views.add('kanban', 'openerp.base_kanban.KanbanView');
openerp.base_kanban.KanbanView = openerp.base.View.extend({

    init: function(parent, element_id, dataset, view_id) {
        this._super(parent, element_id);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.element_id = element_id;
        this.group_by_field = false;
        this.domains = this.dataset.domain;
        this.contexts = this.dataset.context;
        this.group_by = false;
        this.destination_index = false;
    },

    start: function() {
        this.rpc("/base_kanban/kanbanview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.template_xml = '';

        _.each(data.fields_view.arch.children, function(child) {
            if (child.tag == "template"){
                self.template_xml = openerp.base.json_node_to_xml(child, true)
            }
        });
        if(this.template_xml){
            self.dataset.read_slice([], 0, false, function (records) {
                self.on_reload_kanban([{'records': records, 'value':false, 'header': false}]);
	        });
	    }
    },

    on_show_data: function(datas) {
        var self = this;
        this.all_records = [];
        var new_qweb = new QWeb2.Engine();
        new_qweb.add_template('<templates><t t-name="custom_template">' + this.template_xml + '</t></templates>')
		self.$element.html(QWeb.render("KanbanBiew", {"datas" :datas}));
		_.each(datas, function(data) {
	        _.each(data.records, function(record) {
	            self.$element.find("#data_" + record.id).append(new_qweb.render('custom_template', record));
	            self.all_records.push(record);
	        });
        });
        this.$element.find( ".oe_table_column " ).css("width", 99 / datas.length +"%");
		this.$element.find(".oe_column").sortable({
		    connectWith: ".oe_column",
		    start: function(event, ui) {
                self.destination_index = ui.item.index();
            },
		    stop: self.on_recieve_record,
		});
		this.$element.find(".record").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		    .find(".record-header")
		        .addClass("ui-widget-header ui-corner-all")
		        .prepend( "")
		        .end()
		    .find( ".record-content" );

		this.$element.find(".record-header .ui-icon").click(function() {
		    $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
		    $(this).parents(".record:first").find(".record-content").toggle();
		});
		this.$element.find('.record .ui-icon-closethick').click(this.on_close_action);
		this.$element.find(".oe_column").disableSelection();
    },

    on_close_action: function(e) {
        $(e.currentTarget).parents('.record:first').remove();
    },

    on_recieve_record: function(event, ui) {
        var self = this;
        var from = ui.item.index(), to = ui.item.prev().index() || 0;
        this.flag = false;
        if(self.destination_index != from){
	        var child_record = ui.item.parent().children();
	        var data, sequence=1, index = to;
	        child_record.splice(0, to);
	        if(to >= 0 && child_record) {
	            var record_id = child_record.attr('id').split("_");
	            if(record_id.length >= 2) {
		            _.each(this.all_records, function(record){
		                if(parseInt(record_id[1]) == record.id && record.sequence) {
		                    sequence = record.sequence;
		                }
		            });
	            }
	        }
	        _.each(child_record, function (child) {
	            var child_id = parseInt($(child).attr("id").split("_")[1]);
	            if(child_id) {
	                self.dataset.write(child_id, {sequence: sequence});
	                sequence++;
	                self.flag = true;
	            }
	        });
        }
        if(ui.item.attr("id") && this.group_by_field) {
            var value = ui.item.closest("td").attr("id")
            if(value) {
                var data_val = {};
                value = value.split("_")[1];
                if(value == 'false') {
                    value = false;
                }
                data_val[this.group_by_field] = value;
                this.dataset.write(parseInt(ui.item.attr("id").split("_")[1]), data_val);
                this.flag = true;
            }
        }
        if(this.flag) {
            this.do_actual_search(this.domains, this.contexts, this.group_by);
        }
        this.destination_index = false;
    },

    on_reload_kanban: function(datas){
        this.$element.find("#kanbanview").remove();
        this.on_show_data(datas);
    },

    do_search: function (domains, contexts, group_by) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: group_by
        }, function (results) {
            self.contexts = results.context;
            self.domains = results.domain;
            self.group_by = results.group_by;
            self.do_actual_search(results.domain, results.context, results.group_by);
        });
    },

    do_actual_search: function (domain, context, group_by) {
        var self = this;

        this.group_by_field = false;

        self.dataset.context = context;
        self.dataset.domain = domain;
        this.groups = new openerp.base.DataGroup(this, this.model, domain, context, group_by || []);
        this.groups.list([],
            function (groups) {
                if (group_by.length >= 1) {
                    self.group_by_field = group_by[0];
                    self.do_render_group(groups);
                }
            },
            function (dataset) {
                self.dataset.read_slice(false, false, false, function(records) {
                    self.on_reload_kanban([{'records': records, 'value':false, 'header' : false}]);
                });
            }
        );

    },
    do_render_group : function(datagroups){
        this.columns = [];
        var self = this;
        _.each(datagroups, function (group) {
            self.dataset.context = group.context;
            self.dataset.domain = group.domain;
            var group_name = group.value;
            var group_value = group.value;
            if(!group.value) {
                group_name = "Undefined";
                group_value = 'false';
            }
            else if(group.value instanceof Array) {
                group_name = group.value[1]
                group_value = group.value[0]
            }
	        self.dataset.read_slice(false, false, false, function(records) {
                self.columns.push({"value" : group_value, "records": records, 'header':group_name});
                if (datagroups.length == self.columns.length) {
                    self.on_reload_kanban(self.columns);
	            }
	        });
        });
    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>"use strict";
/* eslint no-eval: "off" */
const dialogs = require("./dialogs");

function getRandomItemOfArray (arr) {
	return arr[Math.floor(Math.random() * arr.length)];
}

const specials = {
	"性别": student => +student.sex ? "男" : "女",
	"你的学校属于什么位置": getRandomItemOfArray(["城市", "农村"]),
	"和谁在一起生活": getRandomItemOfArray(["父母外出", "在父母所在", "本地生活"]),
	"你家是否有灭火器": "没有",
	"你家是否制定了家庭火灾逃生路线图": "没有",
	"你家是否定期进行消防疏散演练": "没有",
	"你家如果油锅起火了": ["锅盖盖住", "干毛巾覆盖"],
	"你家是否存放了汽油": "没有",
	"你家的防盗窗上是否留有逃生出口": "没有",
	"会正确拨打119报警电话": "都会",
	"是否堆放了杂物": "没有",
	"沙发上抽烟": "没有",
	"炉灶有火时": "有",
	"抽油烟机是否会定期清洗": "会",
	"你家会定期检查线路": "会",
	"出门关闭电源": "有",
	"是否放在了安全的地方": "是",
	"是否摆放在了安全的位置": "是",
	"长期不拔的现象": "没有",
	"常年不拔电源插头的现象": "否",
	"电器着火": ["切断电源", "干粉灭火器"],
	"电视机着火": ["切断电源", "干粉灭火器"],
	"检查燃气是否有泄漏": "肥皂水",
	"是否有在消防通道停放车辆": "没有",
	"防火门": "关闭",
	"火灾报警电话": "119",
	"油锅着火": ["将锅端下", "锅盖"],
	"入住宾馆酒店时": "逃生路线图",
	"闻到煤气气味时": "打开门窗通风",
	"求救方法错误的是": "大声哭泣",
	"儿童燃放烟花爆竹时": "由大人看护",
	"被困室内无法逃生时": ["堵塞门缝", "把水泼在门上降温", "发出求救信"],
	"消防违法行为": ["封闭消防安全出口", "遮挡消防设施", "损坏公共消防设施"],
	"用电时要注意防火安全": ["不乱接乱拉电线，不超负荷用电", "及时更换老化电器设施和线路", "外出时要关闭电源开关"],
	"家庭应该采取的消防安全措施": ["配备必要的消防器材", "绘制家庭逃生疏散路线", "消除家庭火灾隐患"],
	"为做到防患于未然": "制定家庭疏散预案并进行演练",
	"正确的逃生方法是": "迅速逃生",
	"高层建筑失火时": "从疏散通道逃离",
	"你是否有闯红灯的行为": "没有",
	"当你看到红灯，但路上没有车时，你会过马路吗": "不会",
	"你过马路时是否一直都走斑马线": "是",
	"你家人开车时，有下列哪些行为": "以上行为都没有",
	"你从哪里学习交通安全知识": "学校安全教育",
	"你认为你们学校开展的交通安全教育效果怎么样": "很好",
	"你认为有必要对交通安全知识进行宣传教育吗": "有",
	"你认为在提升学生交通安全意识问题上，谁的作用最重要": "自身的意识",
	"交通事故的报警电话是": "122",
	"才能上路骑自行车": "12",
	"你是否有过翻越道路中央安全护栏的行为": "没有",
	"在车辆没有停稳之前": "不准开车门和上下人",
	"放学路上，小明准备过马路时红灯亮了，这时他应该": "不管有无车辆，都等交通灯变为绿灯时再通过",
	"在没有施划人行横道的公路上，乘车人从公共汽车下车后横过公路时，您认为下列做法正确的是": "车开走且确认安全后再通过",
	"亮亮要去马路对面的超市买东西，可是路口没有红绿灯也没有斑马线，这时你认为他怎么做才是最安全的": "在路口左看右看，反复确认安全后快速通过",
	"乘坐大巴车时，如果遇到事故被困车内，我们可以利用哪些方法逃出车外": "以上都可以"
};

window.open = url => {
	location.href = url;
};

window.alert = msg => {
	if (/已/.test(msg)) {
		callback();
	} else {
		dialogs.alert(msg);
	}
};

function callback (val) {
	if (window.callPhantom) {
		window.callPhantom(val);
	} else if (window.require) {
		const {ipcRenderer} = require("electron");
		ipcRenderer.sendToHost("close", val);
	}
}

function requestData () {
	return new Promise(resolve => {
		const {ipcRenderer} = require("electron");
		ipcRenderer.once("data", (e, data) => {
			resolve(data);
		});
		ipcRenderer.sendToHost("request-data");
	});
}

function getHomeWorkUrls () {
	let links = document.querySelectorAll("table tr a[name^=workToUrl]");
	if (links && links.length) {
		const urls = {
			specials: []
		};
		links = Array.from(links).map(a => {
			const args = eval(a.getAttribute("onclick").trim().replace(/^\s*\w+\s*\((.+)\).*$/, "[$1]"));
			if (args[5]) {
				urls.specials.push({
					title: a.parentNode.parentNode.children[1].textContent.trim(),
					url: args[5]
				});
			} else {
				urls[String(args[0])] = `/JiaTing/EscapeSkill/SeeVideo.aspx?gid=${args[3]}&li=${args[0]}`;
			}
		});
		callback(urls);
	} else {
		setTimeout(getHomeWorkUrls, 800);
	}
}

function ready (callback) {
	if (document.readyState === "complete") {
		setTimeout(callback, 200);
	} else {
		window.addEventListener("load", () => {
			setTimeout(callback, 200);
		});
	}
}

ready(() => {
	const $ = window.$;

	function whaitResult () {
		if ($("#yes:visible,#resultScore:visible").length) {
			callback();
		} else {
			setTimeout(whaitResult, 200);
		}
	}
	if (location.pathname === "/JiaTing/JtMyHomeWork.html") {
		getHomeWorkUrls();
	} else if (window.ShowTestPaper) {
		window.getAnswers = function (answers) {
			setTimeout(function () {
				$(".bto_testbox input[type=radio]").prop("checked", function (i) {
					return !!+answers.Rows[i].istrue;
				});
				$(".bto_testbox .btn_submit").click();
				whaitResult();
			}, 600);
		};

		window.eval(window.ShowTestPaper.toString().replace(/TestPaperThreelistGet2.*?\n?.*?if\s+\(.*?\b(\w+)\.Rows\.length.*?\)\s*\{/, function (s, dataVarName) {
			return s + "getAnswers(" + dataVarName + ");";
		}));
		window.ShowTestPaper();
	} else if (window.loadQuestion) {
		window.loadQuestion(0, 99, 1, false);
		// $("label:visible").filter((i, label) => (
		// 	document.getElementById(label.htmlFor).type === "radio"
		// )).click();
		requestData().then(student => {
			const grade = [
				"小学",
				"小学",
				"初中",
				"高中"
			][parseInt((student.grade - 1) / 3)];
			[
				"在规定的地点等候校车，排队上下不拥挤",
				"儿童安全座椅",
				"从不在车上饮食",
				"从不骑电动车",
				"一直都系安全带",
				"系好安全带",
				"没有电动车",
				"没有私家车",
				"步行",
				grade
			].forEach(label => {
				$(`label:contains('${label}'):visible`).click();
			});

			for (const q in specials) {
				let a = specials[q];
				if (typeof a === "function") {
					a = a(student);
				}
				const dl = $(`dt:contains('${q}'):visible`).first().parent("dl");
				if (Array.isArray(a)) {
					a.forEach(a => {
						dl.find(`label:contains('${a}'):visible`).click();
					});
				} else {
					dl.find(`label:contains('${a}'):visible`).first().click();
				}
			}

			setTimeout(() => {
				$("a:contains('提交')").click();
				whaitResult();
			}, 1000);
		});
	} else {
		const timer1 = setInterval(() => {
			$("a:contains('马上去'), a:contains('请签'), a:contains('请点')").filter(":visible").first().click();
		}, 200);
		const timer2 = setTimeout(() => {
			location.href = location.pathname.replace(/(?:_vr|\d*)(\.\w+)$/, "2$1");
		}, 3000);
		window.onbeforeunload = () => {
			clearInterval(timer1);
			clearTimeout(timer2);
		};
	}
});

if (process.env.CI_TEACHER_ACCOUNT) {
	setTimeout(callback, 90000);
}
<commit_msg>专题作业答案选项支持“高中”<commit_after>"use strict";
/* eslint no-eval: "off" */
const dialogs = require("./dialogs");

function getRandomItemOfArray (arr) {
	return arr[Math.floor(Math.random() * arr.length)];
}

const specials = {
	"性别": student => +student.sex ? "男" : "女",
	"你的学校属于什么位置": getRandomItemOfArray(["城市", "农村"]),
	"和谁在一起生活": getRandomItemOfArray(["父母外出", "在父母所在", "本地生活"]),
	"你家是否有灭火器": "没有",
	"你家是否制定了家庭火灾逃生路线图": "没有",
	"你家是否定期进行消防疏散演练": "没有",
	"你家如果油锅起火了": ["锅盖盖住", "干毛巾覆盖"],
	"你家是否存放了汽油": "没有",
	"你家的防盗窗上是否留有逃生出口": "没有",
	"会正确拨打119报警电话": "都会",
	"是否堆放了杂物": "没有",
	"沙发上抽烟": "没有",
	"炉灶有火时": "有",
	"抽油烟机是否会定期清洗": "会",
	"你家会定期检查线路": "会",
	"出门关闭电源": "有",
	"是否放在了安全的地方": "是",
	"是否摆放在了安全的位置": "是",
	"长期不拔的现象": "没有",
	"常年不拔电源插头的现象": "否",
	"电器着火": ["切断电源", "干粉灭火器"],
	"电视机着火": ["切断电源", "干粉灭火器"],
	"检查燃气是否有泄漏": "肥皂水",
	"是否有在消防通道停放车辆": "没有",
	"防火门": "关闭",
	"火灾报警电话": "119",
	"油锅着火": ["将锅端下", "锅盖"],
	"入住宾馆酒店时": "逃生路线图",
	"闻到煤气气味时": "打开门窗通风",
	"求救方法错误的是": "大声哭泣",
	"儿童燃放烟花爆竹时": "由大人看护",
	"被困室内无法逃生时": ["堵塞门缝", "把水泼在门上降温", "发出求救信"],
	"消防违法行为": ["封闭消防安全出口", "遮挡消防设施", "损坏公共消防设施"],
	"用电时要注意防火安全": ["不乱接乱拉电线，不超负荷用电", "及时更换老化电器设施和线路", "外出时要关闭电源开关"],
	"家庭应该采取的消防安全措施": ["配备必要的消防器材", "绘制家庭逃生疏散路线", "消除家庭火灾隐患"],
	"为做到防患于未然": "制定家庭疏散预案并进行演练",
	"正确的逃生方法是": "迅速逃生",
	"高层建筑失火时": "从疏散通道逃离",
	"你是否有闯红灯的行为": "没有",
	"当你看到红灯，但路上没有车时，你会过马路吗": "不会",
	"你过马路时是否一直都走斑马线": "是",
	"你家人开车时，有下列哪些行为": "以上行为都没有",
	"你从哪里学习交通安全知识": "学校安全教育",
	"你认为你们学校开展的交通安全教育效果怎么样": "很好",
	"你认为有必要对交通安全知识进行宣传教育吗": "有",
	"你认为在提升学生交通安全意识问题上，谁的作用最重要": "自身的意识",
	"交通事故的报警电话是": "122",
	"才能上路骑自行车": "12",
	"你是否有过翻越道路中央安全护栏的行为": "没有",
	"在车辆没有停稳之前": "不准开车门和上下人",
	"放学路上，小明准备过马路时红灯亮了，这时他应该": "不管有无车辆，都等交通灯变为绿灯时再通过",
	"在没有施划人行横道的公路上，乘车人从公共汽车下车后横过公路时，您认为下列做法正确的是": "车开走且确认安全后再通过",
	"亮亮要去马路对面的超市买东西，可是路口没有红绿灯也没有斑马线，这时你认为他怎么做才是最安全的": "在路口左看右看，反复确认安全后快速通过",
	"乘坐大巴车时，如果遇到事故被困车内，我们可以利用哪些方法逃出车外": "以上都可以"
};

window.open = url => {
	location.href = url;
};

window.alert = msg => {
	if (/已/.test(msg)) {
		callback();
	} else {
		dialogs.alert(msg);
	}
};

function callback (val) {
	if (window.callPhantom) {
		window.callPhantom(val);
	} else if (window.require) {
		const {ipcRenderer} = require("electron");
		ipcRenderer.sendToHost("close", val);
	}
}

function requestData () {
	return new Promise(resolve => {
		const {ipcRenderer} = require("electron");
		ipcRenderer.once("data", (e, data) => {
			resolve(data);
		});
		ipcRenderer.sendToHost("request-data");
	});
}

function getHomeWorkUrls () {
	let links = document.querySelectorAll("table tr a[name^=workToUrl]");
	if (links && links.length) {
		const urls = {
			specials: []
		};
		links = Array.from(links).map(a => {
			const args = eval(a.getAttribute("onclick").trim().replace(/^\s*\w+\s*\((.+)\).*$/, "[$1]"));
			if (args[5]) {
				urls.specials.push({
					title: a.parentNode.parentNode.children[1].textContent.trim(),
					url: args[5]
				});
			} else {
				urls[String(args[0])] = `/JiaTing/EscapeSkill/SeeVideo.aspx?gid=${args[3]}&li=${args[0]}`;
			}
		});
		callback(urls);
	} else {
		setTimeout(getHomeWorkUrls, 800);
	}
}

function ready (callback) {
	const time = process.env.CI ? 1000 : 200;
	if (document.readyState === "complete") {
		setTimeout(callback, time);
	} else {
		window.addEventListener("load", () => {
			setTimeout(callback, time);
		});
	}
}

ready(() => {
	const $ = window.$;

	function whaitResult () {
		if ($("#yes:visible,#resultScore:visible").length) {
			callback();
		} else {
			setTimeout(whaitResult, 200);
		}
	}
	if (location.pathname === "/JiaTing/JtMyHomeWork.html") {
		getHomeWorkUrls();
	} else if (window.ShowTestPaper) {
		window.getAnswers = function (answers) {
			setTimeout(function () {
				$(".bto_testbox input[type=radio]").prop("checked", function (i) {
					return !!+answers.Rows[i].istrue;
				});
				$(".bto_testbox .btn_submit").click();
				whaitResult();
			}, 600);
		};

		window.eval(window.ShowTestPaper.toString().replace(/TestPaperThreelistGet2.*?\n?.*?if\s+\(.*?\b(\w+)\.Rows\.length.*?\)\s*\{/, function (s, dataVarName) {
			return s + "getAnswers(" + dataVarName + ");";
		}));
		window.ShowTestPaper();
	} else if (window.loadQuestion) {
		window.loadQuestion(0, 99, 1, false);
		// $("label:visible").filter((i, label) => (
		// 	document.getElementById(label.htmlFor).type === "radio"
		// )).click();
		requestData().then(student => {
			[
				"在规定的地点等候校车，排队上下不拥挤",
				"儿童安全座椅",
				"从不在车上饮食",
				"从不骑电动车",
				"一直都系安全带",
				"系好安全带",
				"没有电动车",
				"没有私家车",
				student.grade <= 6 && "小学",
				student.grade >= 7 && "中学",
				student.grade >= 7 && student.grade <= 9 && "初中",
				student.grade >= 10 && student.grade <= 12 && "高中",
				"步行"
			].filter(Boolean).forEach(label => {
				$(`label:contains('${label}'):visible`).click();
			});

			for (const q in specials) {
				let a = specials[q];
				if (typeof a === "function") {
					a = a(student);
				}
				const dl = $(`dt:contains('${q}'):visible`).first().parent("dl");
				if (Array.isArray(a)) {
					a.forEach(a => {
						dl.find(`label:contains('${a}'):visible`).click();
					});
				} else {
					dl.find(`label:contains('${a}'):visible`).first().click();
				}
			}

			setTimeout(() => {
				$("a:contains('提交')").click();
				whaitResult();
			}, 1000);
		});
	} else {
		const timer1 = setInterval(() => {
			$("a:contains('马上去'), a:contains('请签'), a:contains('请点')").filter(":visible").first().click();
		}, 200);
		const timer2 = setTimeout(() => {
			location.href = location.pathname.replace(/(?:_vr|\d*)(\.\w+)$/, "2$1");
		}, process.env.CI ? 3000 : 800);
		window.onbeforeunload = () => {
			clearInterval(timer1);
			clearTimeout(timer2);
		};
	}
});

if (process.env.CI_TEACHER_ACCOUNT) {
	setTimeout(callback, 90000);
}
<|endoftext|>


<commit_before>export { default as moduleFor } from './legacy-2-x/module-for';
export { default as moduleForComponent } from './legacy-2-x/module-for-component';
export { default as moduleForModel } from './legacy-2-x/module-for-model';
export { default as QUnitAdapter, nonTestDoneCallback } from './adapter';
export { module, test, skip, only, todo } from 'qunit';
export { loadTests } from './test-loader';

import { run } from '@ember/runloop';
import { assign } from '@ember/polyfills';
import { resetOnerror } from '@ember/test-helpers';
import { loadTests } from './test-loader';
import Ember from 'ember';
import QUnit from 'qunit';
import QUnitAdapter from './adapter';
import {
  setupContext,
  teardownContext,
  setupRenderingContext,
  teardownRenderingContext,
  setupApplicationContext,
  teardownApplicationContext,
  validateErrorHandler,
} from '@ember/test-helpers';
import { installTestNotIsolatedHook } from './test-isolation-validation';

let waitForSettled = true;

export function setupTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  hooks.beforeEach(function(assert) {
    return setupContext(this, options).then(() => {
      let originalPauseTest = this.pauseTest;
      this.pauseTest = function QUnit_pauseTest() {
        assert.timeout(-1); // prevent the test from timing out

        return originalPauseTest.call(this);
      };
    });
  });

  hooks.afterEach(function() {
    return teardownContext(this, options);
  });
}

export function setupRenderingTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupRenderingContext(this);
  });

  hooks.afterEach(function() {
    return teardownRenderingContext(this, options);
  });
}

export function setupApplicationTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupApplicationContext(this);
  });

  hooks.afterEach(function() {
    return teardownApplicationContext(this, options);
  });
}

/**
   Uses current URL configuration to setup the test container.

   * If `?nocontainer` is set, the test container will be hidden.
   * If `?dockcontainer` or `?devmode` are set the test container will be
     absolutely positioned.
   * If `?devmode` is set, the test container will be made full screen.

   @method setupTestContainer
 */
export function setupTestContainer() {
  let testContainer = document.getElementById('ember-testing-container');
  if (!testContainer) {
    return;
  }

  let params = QUnit.urlParams;

  let containerVisibility = params.nocontainer ? 'hidden' : 'visible';
  let containerPosition = params.dockcontainer || params.devmode ? 'fixed' : 'relative';

  if (params.devmode) {
    testContainer.className = ' full-screen';
  }

  testContainer.style.visibility = containerVisibility;
  testContainer.style.position = containerPosition;

  let qunitContainer = document.getElementById('qunit');
  if (params.dockcontainer) {
    qunitContainer.style.marginBottom = window.getComputedStyle(testContainer).height;
  }
}

/**
   Instruct QUnit to start the tests.
   @method startTests
 */
export function startTests() {
  QUnit.start();
}

/**
   Sets up the `Ember.Test` adapter for usage with QUnit 2.x.

   @method setupTestAdapter
 */
export function setupTestAdapter() {
  Ember.Test.adapter = QUnitAdapter.create();
}

/**
  Ensures that `Ember.testing` is set to `true` before each test begins
  (including `before` / `beforeEach`), and reset to `false` after each test is
  completed. This is done via `QUnit.testStart` and `QUnit.testDone`.

 */
export function setupEmberTesting() {
  QUnit.testStart(() => {
    Ember.testing = true;
  });

  QUnit.testDone(() => {
    Ember.testing = false;
  });
}

/**
  Ensures that `Ember.onerror` (if present) is properly configured to re-throw
  errors that occur while `Ember.testing` is `true`.
*/
export function setupEmberOnerrorValidation() {
  QUnit.module('ember-qunit: Ember.onerror validation', function() {
    QUnit.test('Ember.onerror is functioning properly', function(assert) {
      assert.expect(1);
      let result = validateErrorHandler();
      assert.ok(
        result.isValid,
        `Ember.onerror handler with invalid testing behavior detected. An Ember.onerror handler _must_ rethrow exceptions when \`Ember.testing\` is \`true\` or the test suite is unreliable. See https://git.io/vbine for more details.`
      );
    });
  });
}

export function setupResetOnerror() {
  QUnit.on('testDone', resetOnerror);
}

export function setupTestIsolationValidation() {
  waitForSettled = false;
  run.backburner.DEBUG = true;
  QUnit.on('testStart', installTestNotIsolatedHook);
}

/**
   @method start
   @param {Object} [options] Options to be used for enabling/disabling behaviors
   @param {Boolean} [options.loadTests] If `false` tests will not be loaded automatically.
   @param {Boolean} [options.setupTestContainer] If `false` the test container will not
   be setup based on `devmode`, `dockcontainer`, or `nocontainer` URL params.
   @param {Boolean} [options.startTests] If `false` tests will not be automatically started
   (you must run `QUnit.start()` to kick them off).
   @param {Boolean} [options.setupTestAdapter] If `false` the default Ember.Test adapter will
   not be updated.
   @param {Boolean} [options.setupEmberTesting] `false` opts out of the
   default behavior of setting `Ember.testing` to `true` before all tests and
   back to `false` after each test will.
   @param {Boolean} [options.setupEmberOnerrorValidation] If `false` validation
   of `Ember.onerror` will be disabled.
   @param {Boolean} [options.setupTestIsolationValidation] If `false` test isolation validation
   will be disabled.
 */
export function start(options = {}) {
  if (options.loadTests !== false) {
    loadTests();
  }

  if (options.setupTestContainer !== false) {
    setupTestContainer();
  }

  if (options.setupTestAdapter !== false) {
    setupTestAdapter();
  }

  if (options.setupEmberTesting !== false) {
    setupEmberTesting();
  }

  if (options.setupEmberOnerrorValidation !== false) {
    setupEmberOnerrorValidation();
  }

  if (
    typeof options.setupTestIsolationValidation !== 'undefined' &&
    options.setupTestIsolationValidation !== false
  ) {
    setupTestIsolationValidation();
  }

  if (options.startTests !== false) {
    startTests();
  }

  setupResetOnerror();
}
<commit_msg>Changing to use correct testDone hook<commit_after>export { default as moduleFor } from './legacy-2-x/module-for';
export { default as moduleForComponent } from './legacy-2-x/module-for-component';
export { default as moduleForModel } from './legacy-2-x/module-for-model';
export { default as QUnitAdapter, nonTestDoneCallback } from './adapter';
export { module, test, skip, only, todo } from 'qunit';
export { loadTests } from './test-loader';

import { run } from '@ember/runloop';
import { assign } from '@ember/polyfills';
import { resetOnerror } from '@ember/test-helpers';
import { loadTests } from './test-loader';
import Ember from 'ember';
import QUnit from 'qunit';
import QUnitAdapter from './adapter';
import {
  setupContext,
  teardownContext,
  setupRenderingContext,
  teardownRenderingContext,
  setupApplicationContext,
  teardownApplicationContext,
  validateErrorHandler,
} from '@ember/test-helpers';
import { installTestNotIsolatedHook } from './test-isolation-validation';

let waitForSettled = true;

export function setupTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  hooks.beforeEach(function(assert) {
    return setupContext(this, options).then(() => {
      let originalPauseTest = this.pauseTest;
      this.pauseTest = function QUnit_pauseTest() {
        assert.timeout(-1); // prevent the test from timing out

        return originalPauseTest.call(this);
      };
    });
  });

  hooks.afterEach(function() {
    return teardownContext(this, options);
  });
}

export function setupRenderingTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupRenderingContext(this);
  });

  hooks.afterEach(function() {
    return teardownRenderingContext(this, options);
  });
}

export function setupApplicationTest(hooks, _options) {
  let options = _options === undefined ? { waitForSettled } : assign({ waitForSettled }, _options);

  setupTest(hooks, options);

  hooks.beforeEach(function() {
    return setupApplicationContext(this);
  });

  hooks.afterEach(function() {
    return teardownApplicationContext(this, options);
  });
}

/**
   Uses current URL configuration to setup the test container.

   * If `?nocontainer` is set, the test container will be hidden.
   * If `?dockcontainer` or `?devmode` are set the test container will be
     absolutely positioned.
   * If `?devmode` is set, the test container will be made full screen.

   @method setupTestContainer
 */
export function setupTestContainer() {
  let testContainer = document.getElementById('ember-testing-container');
  if (!testContainer) {
    return;
  }

  let params = QUnit.urlParams;

  let containerVisibility = params.nocontainer ? 'hidden' : 'visible';
  let containerPosition = params.dockcontainer || params.devmode ? 'fixed' : 'relative';

  if (params.devmode) {
    testContainer.className = ' full-screen';
  }

  testContainer.style.visibility = containerVisibility;
  testContainer.style.position = containerPosition;

  let qunitContainer = document.getElementById('qunit');
  if (params.dockcontainer) {
    qunitContainer.style.marginBottom = window.getComputedStyle(testContainer).height;
  }
}

/**
   Instruct QUnit to start the tests.
   @method startTests
 */
export function startTests() {
  QUnit.start();
}

/**
   Sets up the `Ember.Test` adapter for usage with QUnit 2.x.

   @method setupTestAdapter
 */
export function setupTestAdapter() {
  Ember.Test.adapter = QUnitAdapter.create();
}

/**
  Ensures that `Ember.testing` is set to `true` before each test begins
  (including `before` / `beforeEach`), and reset to `false` after each test is
  completed. This is done via `QUnit.testStart` and `QUnit.testDone`.

 */
export function setupEmberTesting() {
  QUnit.testStart(() => {
    Ember.testing = true;
  });

  QUnit.testDone(() => {
    Ember.testing = false;
  });
}

/**
  Ensures that `Ember.onerror` (if present) is properly configured to re-throw
  errors that occur while `Ember.testing` is `true`.
*/
export function setupEmberOnerrorValidation() {
  QUnit.module('ember-qunit: Ember.onerror validation', function() {
    QUnit.test('Ember.onerror is functioning properly', function(assert) {
      assert.expect(1);
      let result = validateErrorHandler();
      assert.ok(
        result.isValid,
        `Ember.onerror handler with invalid testing behavior detected. An Ember.onerror handler _must_ rethrow exceptions when \`Ember.testing\` is \`true\` or the test suite is unreliable. See https://git.io/vbine for more details.`
      );
    });
  });
}

export function setupResetOnerror() {
  QUnit.testDone(resetOnerror);
}

export function setupTestIsolationValidation() {
  waitForSettled = false;
  run.backburner.DEBUG = true;
  QUnit.on('testStart', installTestNotIsolatedHook);
}

/**
   @method start
   @param {Object} [options] Options to be used for enabling/disabling behaviors
   @param {Boolean} [options.loadTests] If `false` tests will not be loaded automatically.
   @param {Boolean} [options.setupTestContainer] If `false` the test container will not
   be setup based on `devmode`, `dockcontainer`, or `nocontainer` URL params.
   @param {Boolean} [options.startTests] If `false` tests will not be automatically started
   (you must run `QUnit.start()` to kick them off).
   @param {Boolean} [options.setupTestAdapter] If `false` the default Ember.Test adapter will
   not be updated.
   @param {Boolean} [options.setupEmberTesting] `false` opts out of the
   default behavior of setting `Ember.testing` to `true` before all tests and
   back to `false` after each test will.
   @param {Boolean} [options.setupEmberOnerrorValidation] If `false` validation
   of `Ember.onerror` will be disabled.
   @param {Boolean} [options.setupTestIsolationValidation] If `false` test isolation validation
   will be disabled.
 */
export function start(options = {}) {
  if (options.loadTests !== false) {
    loadTests();
  }

  if (options.setupTestContainer !== false) {
    setupTestContainer();
  }

  if (options.setupTestAdapter !== false) {
    setupTestAdapter();
  }

  if (options.setupEmberTesting !== false) {
    setupEmberTesting();
  }

  if (options.setupEmberOnerrorValidation !== false) {
    setupEmberOnerrorValidation();
  }

  if (
    typeof options.setupTestIsolationValidation !== 'undefined' &&
    options.setupTestIsolationValidation !== false
  ) {
    setupTestIsolationValidation();
  }

  if (options.startTests !== false) {
    startTests();
  }

  setupResetOnerror();
}
<|endoftext|>


<commit_before>/**
 * Text Editor for the Cloud9 IDE
 *
 * @copyright 2010, Ajax.org B.V.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */
define(function(require, exports, module) {
    main.consumes = ["editors", "settings"];
    main.provides = ["ace.repl"];
    return main;

    function main(options, imports, register) {
        var editors  = imports.editors;
        var settings = imports.settings;

        var Repl = require("./repl").Repl;

        var counter  = 0;

        /***** Initialization *****/

        var extensions = [];

        function ReplEditor(){
            var Baseclass = editors.findEditor("ace")
            var plugin = new Baseclass(true, []);
            // var emit   = plugin.getEmitter();

            var currentSession;
            var ace;

            plugin.on("draw", function(e){
                ace = plugin.ace;

                if (currentSession)
                    currentSession.repl.attach(ace);
            })

            /***** Method *****/

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            plugin.on("document.load", function(e){
                var session = e.doc.getSession();

                if (session.repl) return;

                session.repl = new Repl(session.session, {
                    mode      : e.state.mode,
                    evaluator : e.state.evaluator,
                    message   : e.state.message
                });
            });
            plugin.on("document.activate", function(e){
                currentSession = e.doc.getSession();
                if (ace)
                    currentSession.repl.attach(ace);
            });
            plugin.on("document.unload", function(e){
                var session = e.doc.getSession();
                session.repl.detach();
                delete session.repl;
            });
            plugin.on("state.get", function(e){
            });
            plugin.on("state.set", function(e){
            });
            plugin.on("clear", function(){
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Read Only Image Editor
             **/
            plugin.freezePublicAPI({

            });

            plugin.load("ace.repl" + counter++);

            return plugin;
        }

        register(null, {
            "ace.repl": editors.register("ace.repl", "Ace REPL",
                                         ReplEditor, extensions)
        });
    }
});<commit_msg>Revert "Revert "Merge pull request +128 from c9/docs""<commit_after>/**
 * Text Editor for the Cloud9 IDE
 *
 * @copyright 2010, Ajax.org B.V.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */
define(function(require, exports, module) {
    main.consumes = ["editors", "settings"];
    main.provides = ["ace.repl"];
    return main;

    function main(options, imports, register) {
        var editors  = imports.editors;
        var settings = imports.settings;

        var Repl = require("./repl").Repl;

        var counter  = 0;

        /***** Initialization *****/

        var extensions = [];

        function ReplEditor(){
            var Baseclass = editors.findEditor("ace")
            var plugin = new Baseclass(true, []);
            // var emit   = plugin.getEmitter();

            var currentSession;
            var ace;

            plugin.on("draw", function(e){
                ace = plugin.ace;

                if (currentSession)
                    currentSession.repl.attach(ace);
            })

            /***** Method *****/

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            plugin.on("documentLoad", function(e){
                var session = e.doc.getSession();

                if (session.repl) return;

                session.repl = new Repl(session.session, {
                    mode      : e.state.mode,
                    evaluator : e.state.evaluator,
                    message   : e.state.message
                });
            });
            plugin.on("documentActivate", function(e){
                currentSession = e.doc.getSession();
                if (ace)
                    currentSession.repl.attach(ace);
            });
            plugin.on("documentUnload", function(e){
                var session = e.doc.getSession();
                session.repl.detach();
                delete session.repl;
            });
            plugin.on("getState", function(e){
            });
            plugin.on("setState", function(e){
            });
            plugin.on("clear", function(){
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Read Only Image Editor
             **/
            plugin.freezePublicAPI({

            });

            plugin.load("ace.repl" + counter++);

            return plugin;
        }

        register(null, {
            "ace.repl": editors.register("ace.repl", "Ace REPL",
                                         ReplEditor, extensions)
        });
    }
});<|endoftext|>


<commit_before>function something()
	{
		var x = window.localStorage.getItem('bbb');

		x = x * 1 + 1;

		window.localStorage.setItem('bbb', x);

		alert(x);
	}

	function add_to_cart(id)
	{

		var key = 'product_' + id;

		var x = window.localStorage.getItem(key);
		x = x * 1 + 1
		window.localStorage.setItem(key, x);

		// вывов количества item ов в корзине
		alert('Item in your cart: ' + cart_get_number_of_items());
	}

	function cart_get_number_of_items()
	{
		var cnt = 0;

		for(var i = 0; i < window.localStorage.length; i++)
		{
			var key = window.localStorage.key(i);// получаем ключ
			var value = window.localStorage.getItem(key);// получаем значение, аналог в ruby: hh[key] = x

			if(key.indexOf('product_') == 0)
			{
				cnt = cnt + value * 1;
			}
		}

		return cnt;
	}<commit_msg>Add cart_get_orders<commit_after>function something()
	{
		var x = window.localStorage.getItem('bbb');

		x = x * 1 + 1;

		window.localStorage.setItem('bbb', x);

		alert(x);
	}

	function add_to_cart(id)
	{

		var key = 'product_' + id;

		var x = window.localStorage.getItem(key);
		x = x * 1 + 1
		window.localStorage.setItem(key, x);

		// вывов количества item ов в корзине
		alert('Item in your cart: ' + cart_get_number_of_items());
	}

	function cart_get_number_of_items()
	{
		var cnt = 0;

		for(var i = 0; i < window.localStorage.length; i++)
		{
			var key = window.localStorage.key(i);// получаем ключ
			var value = window.localStorage.getItem(key);// получаем значение, аналог в ruby: hh[key] = x

			if(key.indexOf('product_') == 0)
			{
				cnt = cnt + value * 1;
			}
		}

		return cnt;
	}

	function cart_get_orders()
	{
		var orders = '';

		for(var i = 0; i < window.localStorage.length; i++)
		{
			var key = window.localStorage.key(i);// получаем ключ
			var value = window.localStorage.getItem(key);// получаем значение, аналог в ruby: hh[key] = x

			if(key.indexOf('product_') == 0)
			{
				orders = orders + key + '=' + value + ',';
			}
		}

		return orders;
	}<|endoftext|>


<commit_before>const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
<commit_msg>Remove webpack.mix.js since we're not using webpack [API-141]<commit_after><|endoftext|>


<commit_before>var CameraDisplayObject3D = require('threejs-camera-display-object3d');
var setPlaneToOrthographicRectangle = require('threejs-helper-set-plane-to-orthographic-rectangle');
var gridCellPositionerX = require('./cellPositioners/horizontalScroll');
var gridCellPositionerY = require('./cellPositioners/verticalScroll');
var GridLayoutSolver = require('grid-layout-solver');
var cellDecoratorCctv = require('./cellDecorators/cctv');
var Signal = require('signals').Signal;
var nameID = 0;

function noop() {}

function generateName(baseName) {
	nameID++;
	return baseName + nameID;
}

function GridView(params) {
	var _this = this;
	var _rectangle = params.rectangle || {
		width: window.innerWidth-200,
		height: window.innerHeight-200,
		x: 100,
		y: 100
	};

	var _changed = true;

	var _useDevicePixelRatio = params.useDevicePixelRatio || true;
	var _scrollX = params.scrollX || 0;
	var _scrollY = params.scrollY || 0;
	var _lastScrollX = _scrollX;
	var _lastScrollY = _scrollY;
	var _totalCells = params.totalCells || 0;
	var _debugLevel = params.debugLevel || 0;
	var _scrollAxis = params.scrollAxis || 'y';
	var _scrollAxisCapitalized = _scrollAxis.toUpperCase();
	var _margin = params.margin || 0;
	var _autoClear = params.autoClear || false;
	var _camera = new THREE.OrthographicCamera(0, 1, 0, 1, -100, 100);
	var _scene = new THREE.Scene();
	var _renderer = params.renderer;
	var _cells = [];
	var CellClass = params.CellClass ? params.CellClass : CameraDisplayObject3D;

	var onCellResetSignal = new Signal();

	var _scrollTolerance = 0.1;

	var _marginX = 0;
	var _marginY = 0;
	var _scrollXScale = 0;
	var _scrollYScale = 0;

	switch(_scrollAxis) {
		case 'x':
			_gridCellPositioner = gridCellPositionerX;
			break;
		default:
			_gridCellPositioner = gridCellPositionerY;
	}

	var _actualCellPoolSize = 0;
	var _cellPoolSize = 0;

	var _gridLayout = new GridLayoutSolver(params.gridSolverParams);
	var _gridSolution;
	//extra grid properties
	_gridLayout.scrollX = 0;
	_gridLayout.scrollY = 0;

	_setRectangle(_rectangle);

	function _onEnterFrame() {
		_updateCameraBounds();
	}

	function _updateCameraBounds() {
		_camera.left = _rectangle.x + _gridLayout.scrollX * _scrollXScale;
		_camera.right = _rectangle.x + _rectangle.width + _gridLayout.scrollX * _scrollYScale;
		_camera.top = _rectangle.y + _rectangle.height - _gridLayout.scrollY;
		_camera.bottom = _rectangle.y - _gridLayout.scrollY;
		_camera.updateProjectionMatrix();
		if(Math.abs(_lastScrollX - _gridLayout.scrollX) > _scrollTolerance || Math.abs(_lastScrollY !== _gridLayout.scrollY) > _scrollTolerance) {
			_changed = true;
		}
		_lastScrollX = _gridLayout.scrollX;
		_lastScrollY = _gridLayout.scrollY;
	};

	function _getCellUnderPosition(x, y) {
		var intersection = _gridCellPositioner.getCellIntersectionUnderPosition(_gridLayout, _rectangle, _gridSolution, x, y);
		if(intersection && intersection.index != -1 && intersection.index < _totalCells) {
			intersection.cell = _cells[intersection.index % _cellPoolSize];
			return intersection;
		}
	}

	function _updateCells() {
		var visibleCellIndices = _gridCellPositioner.getVisibleIndices(_gridLayout, _rectangle, _gridSolution);
		return visibleCellIndices.map(function(index){
			if(index >= 0 && index < _totalCells) {
				var cell = _cells[index % _cellPoolSize];
				if(cell.index !== index) _changeCellData(cell, index);
				if(cell.update) cell.update();
			}
		});
	}

	function _getVisibleCells() {
		var visibleCellIndices = _gridCellPositioner.getVisibleIndices(_gridLayout, _rectangle, _gridSolution);
		return visibleCellIndices.map(function(index){
			if(index >= 0 && index < _totalCells) {
				return _cells[index % _cellPoolSize];
			}
		}).filter(function(cell) {
			return !!cell;
		});
	}

	function _render() {
		_updateCells();
		_renderer.render(_scene, _camera);
	}

	function _createCell() {
		var cell = {
			x: 0,
			y: 0,
			width: _gridSolution.cellWidth,
			height: _gridSolution.cellHeight,
			resolutionWidth: ~~_gridSolution.cellWidth,
			resolutionHeight: ~~_gridSolution.cellHeight,
			renderer: _renderer,
			fresh: true
		};

		if(_useDevicePixelRatio) {
			cell.resolutionWidth *= _renderer.devicePixelRatio,
			cell.resolutionHeight *= _renderer.devicePixelRatio
		}
		if(!cell.name) cell.name = generateName('cell');
		cell.object3D = new CellClass(cell);
		if(!cell.object3D.changed) cell.object3D.changed = noop;
		var oldUpdate = cell.object3D.update.bind(cell.object3D);
		function newUpdate() {
			this._changed = true;
			oldUpdate();
		}
		cell.object3D.update = newUpdate.bind(cell);
		function changed() {
			var a = this.object3D.changed();
			var b = this._changed;
			this._changed = false;
			return a || b;
		}
		cell.changed = changed;
		if(_debugLevel >= 1) console.log('create', cell.name);
		_cells.push(cell);
		_scene.add(cell.object3D);
	}

	function _destroyCell() {
		var cell = _cells.pop();
		if(_debugLevel >= 1) console.log('destroy', cell.name)
		_scene.remove(cell.object3D);
		cell.object3D.destroy();
	}

	function _layoutCells() {
		_cells.forEach(function(cell) {
			cell.needsUpdate = true;
			_layoutCell(cell, cell.index);
		});
	}

	function _layoutCell(cell, index) {
		var cellRectangle = _gridCellPositioner.getCellRectangleOfIndex(_gridSolution, index);
		cellRectangle.x += _rectangle.x;
		cellRectangle.y = _rectangle.height - cellRectangle.y - cellRectangle.height + _rectangle.y;
		if(_debugLevel >= 1) console.log('layout', cell.name, index);
		setPlaneToOrthographicRectangle(cell.object3D, cellRectangle);
		cell.x = cellRectangle.x;
		cell.y = cellRectangle.y;
		cell.width = cellRectangle.width;
		cell.height = cellRectangle.height;
		cell.object3D.setSize(cellRectangle.width, cellRectangle.height);
		cell.object3D.setResolution(cellRectangle.width * _renderer.devicePixelRatio, cellRectangle.height * _renderer.devicePixelRatio);
		cell.object3D.visible = index < _totalCells;
		if(cell.reset) cell.reset();
	}

	function _changeCellData(cell, index) {
		var data = _data[index];
		cell.index = index;

		//set/change cell behaviour
		if(data.cellDecorator !== cell.initdCellDecorator) {
			data.cellDecorator(cell);
			cell.initdCellDecorator = data.cellDecorator;
		}

		cell.setData(data);

		if(_debugLevel >= 1) console.log('change', cell.name, index);

		_layoutCell(cell, index);
		cell.needsUpdate = true;
		onCellResetSignal.dispatch(cell);
		delete cell.fresh;
	}

	function _setRectangle(rectangle) {
		_rectangle = rectangle;
		_solveGrid();
		//extra precalculations for speed
		_updateCameraBounds();
	}

	function _updateCellPool() {
		_cellPoolSize = _gridCellPositioner.getPoolSize(_gridSolution);
		_cellPoolSize = Math.min(_cellPoolSize, _totalCells);
		if(_actualCellPoolSize !== _cellPoolSize) {
			while(_actualCellPoolSize < _cellPoolSize) {
				_createCell();
				_actualCellPoolSize++;
			}
			while(_actualCellPoolSize > _cellPoolSize) {
				_destroyCell();
				_actualCellPoolSize--;
			}
		}
	}

	function _setData(data){
		_data = data;
		_totalCells = data.length;
		_updateCellPool();
		_cells.forEach(function(cell) {
			cell.index = -1;
			cell.needsUpdate = true;
		});
	}

	function _determineGridMargins() {
		_marginX = 0;
		_marginY = 0;
		if(_totalCells > _gridSolution.cellCount) {
			if(_scrollAxis === 'x') {
				_marginX = 0.25;
			} else {
				_marginY = 0.25;
			}
		}

		var paddedWidth = _rectangle.width + _gridSolution.cellWidth * _marginX;
		var ratioWidth = _rectangle.width / paddedWidth;
		_gridSolution.cellWidth *= ratioWidth;
		_gridSolution.innerWidth = _rectangle.width * ratioWidth;
		_gridSolution.marginWidth = _rectangle.width - _gridSolution.innerWidth;

		var paddedHeight = _rectangle.height + _gridSolution.cellHeight * _marginY;
		var ratioHeight = _rectangle.height / paddedHeight;
		_gridSolution.cellHeight *= ratioHeight;
		_gridSolution.innerHeight = _rectangle.height * ratioHeight;
		_gridSolution.marginHeight = _rectangle.height - _gridSolution.innerHeight;

	}

	function _determineScrolling() {
		_scrollXScale = _scrollYScale = _totalCells > _gridSolution.cellCount ? 1 : 0;
	}

	function _solveGrid() {
		var index = _gridSolution ? _gridCellPositioner.getIndexOfScroll(_gridSolution, _gridLayout['scroll' + _scrollAxisCapitalized]) : undefined;
		_gridSolution = _gridLayout.solve(_rectangle);
		_determineGridMargins();
		_determineScrolling();
		if(index !== undefined) _gridCellPositioner.setScrollFromIndex(_gridLayout, _gridSolution, index);
		_rectangle.right = _rectangle.x + _rectangle.width;
		_rectangle.bottom = _rectangle.y + _rectangle.height;
		_updateCellPool();
		_layoutCells();
		_this.gridSolution = _gridSolution;
	}

	function _setPreferredCellCount(val) {
		_gridLayout.setPreferredCellCount(val);
		_solveGrid();
	}

	function getCellRectangleOfIndex(index) {
		var rect = _gridCellPositioner.getCellRectangleOfIndex(_gridSolution, index);
		rect.x += _rectangle.x;
		rect.y = _rectangle.height - rect.y - rect.height + _rectangle.y;
		return rect;
	}

	function _getScene() {
		return _scene;
	}

	function _getCamera() {
		return _camera;
	}

	function changed() {
		var anythingChanged = false;
		for (var i = _cells.length - 1; i >= 0; i--) {
			anythingChanged = _cells[i].object3D.changed() || anythingChanged;
		};
		if(_changed) {
			anythingChanged = true;
			_changed = false;
		}
		return anythingChanged;
	}

	this.setData = _setData;
	this.gridLayout = _gridLayout;
	this.setRectangle = _setRectangle;
	this.onEnterFrame = _onEnterFrame;
	this.getCellUnderPosition = _getCellUnderPosition;
	this.getVisibleCells = _getVisibleCells;
	this.render = _render;
	this.setPreferredCellCount = _setPreferredCellCount;
	this.cells = _cells;
	this.onCellResetSignal = onCellResetSignal;
	this.updateCells = _updateCells;
	this.getScene = _getScene;
	this.getCamera = _getCamera;
	this.getCellRectangleOfIndex = getCellRectangleOfIndex;
	this.changed = changed;
}

module.exports = GridView;<commit_msg>allow arguments passthru for cell update<commit_after>var CameraDisplayObject3D = require('threejs-camera-display-object3d');
var setPlaneToOrthographicRectangle = require('threejs-helper-set-plane-to-orthographic-rectangle');
var gridCellPositionerX = require('./cellPositioners/horizontalScroll');
var gridCellPositionerY = require('./cellPositioners/verticalScroll');
var GridLayoutSolver = require('grid-layout-solver');
var cellDecoratorCctv = require('./cellDecorators/cctv');
var Signal = require('signals').Signal;
var nameID = 0;

function noop() {}

function generateName(baseName) {
	nameID++;
	return baseName + nameID;
}

function GridView(params) {
	var _this = this;
	var _rectangle = params.rectangle || {
		width: window.innerWidth-200,
		height: window.innerHeight-200,
		x: 100,
		y: 100
	};

	var _changed = true;

	var _useDevicePixelRatio = params.useDevicePixelRatio || true;
	var _scrollX = params.scrollX || 0;
	var _scrollY = params.scrollY || 0;
	var _lastScrollX = _scrollX;
	var _lastScrollY = _scrollY;
	var _totalCells = params.totalCells || 0;
	var _debugLevel = params.debugLevel || 0;
	var _scrollAxis = params.scrollAxis || 'y';
	var _scrollAxisCapitalized = _scrollAxis.toUpperCase();
	var _margin = params.margin || 0;
	var _autoClear = params.autoClear || false;
	var _camera = new THREE.OrthographicCamera(0, 1, 0, 1, -100, 100);
	var _scene = new THREE.Scene();
	var _renderer = params.renderer;
	var _cells = [];
	var CellClass = params.CellClass ? params.CellClass : CameraDisplayObject3D;

	var onCellResetSignal = new Signal();

	var _scrollTolerance = 0.1;

	var _marginX = 0;
	var _marginY = 0;
	var _scrollXScale = 0;
	var _scrollYScale = 0;

	switch(_scrollAxis) {
		case 'x':
			_gridCellPositioner = gridCellPositionerX;
			break;
		default:
			_gridCellPositioner = gridCellPositionerY;
	}

	var _actualCellPoolSize = 0;
	var _cellPoolSize = 0;

	var _gridLayout = new GridLayoutSolver(params.gridSolverParams);
	var _gridSolution;
	//extra grid properties
	_gridLayout.scrollX = 0;
	_gridLayout.scrollY = 0;

	_setRectangle(_rectangle);

	function _onEnterFrame() {
		_updateCameraBounds();
	}

	function _updateCameraBounds() {
		_camera.left = _rectangle.x + _gridLayout.scrollX * _scrollXScale;
		_camera.right = _rectangle.x + _rectangle.width + _gridLayout.scrollX * _scrollYScale;
		_camera.top = _rectangle.y + _rectangle.height - _gridLayout.scrollY;
		_camera.bottom = _rectangle.y - _gridLayout.scrollY;
		_camera.updateProjectionMatrix();
		if(Math.abs(_lastScrollX - _gridLayout.scrollX) > _scrollTolerance || Math.abs(_lastScrollY !== _gridLayout.scrollY) > _scrollTolerance) {
			_changed = true;
		}
		_lastScrollX = _gridLayout.scrollX;
		_lastScrollY = _gridLayout.scrollY;
	};

	function _getCellUnderPosition(x, y) {
		var intersection = _gridCellPositioner.getCellIntersectionUnderPosition(_gridLayout, _rectangle, _gridSolution, x, y);
		if(intersection && intersection.index != -1 && intersection.index < _totalCells) {
			intersection.cell = _cells[intersection.index % _cellPoolSize];
			return intersection;
		}
	}

	function _updateCells() {
		var visibleCellIndices = _gridCellPositioner.getVisibleIndices(_gridLayout, _rectangle, _gridSolution);
		return visibleCellIndices.map(function(index){
			if(index >= 0 && index < _totalCells) {
				var cell = _cells[index % _cellPoolSize];
				if(cell.index !== index) _changeCellData(cell, index);
				if(cell.update) cell.update();
			}
		});
	}

	function _getVisibleCells() {
		var visibleCellIndices = _gridCellPositioner.getVisibleIndices(_gridLayout, _rectangle, _gridSolution);
		return visibleCellIndices.map(function(index){
			if(index >= 0 && index < _totalCells) {
				return _cells[index % _cellPoolSize];
			}
		}).filter(function(cell) {
			return !!cell;
		});
	}

	function _render() {
		_updateCells();
		_renderer.render(_scene, _camera);
	}

	function _createCell() {
		var cell = {
			x: 0,
			y: 0,
			width: _gridSolution.cellWidth,
			height: _gridSolution.cellHeight,
			resolutionWidth: ~~_gridSolution.cellWidth,
			resolutionHeight: ~~_gridSolution.cellHeight,
			renderer: _renderer,
			fresh: true
		};

		if(_useDevicePixelRatio) {
			cell.resolutionWidth *= _renderer.devicePixelRatio,
			cell.resolutionHeight *= _renderer.devicePixelRatio
		}
		if(!cell.name) cell.name = generateName('cell');
		cell.object3D = new CellClass(cell);
		if(!cell.object3D.changed) cell.object3D.changed = noop;
		var oldUpdate = cell.object3D.update.bind(cell.object3D);
		function newUpdate() {
			this._changed = true;
			oldUpdate.apply(this, arguments);
		}
		cell.object3D.update = newUpdate.bind(cell);
		function changed() {
			var a = this.object3D.changed();
			var b = this._changed;
			this._changed = false;
			return a || b;
		}
		cell.changed = changed;
		if(_debugLevel >= 1) console.log('create', cell.name);
		_cells.push(cell);
		_scene.add(cell.object3D);
	}

	function _destroyCell() {
		var cell = _cells.pop();
		if(_debugLevel >= 1) console.log('destroy', cell.name)
		_scene.remove(cell.object3D);
		cell.object3D.destroy();
	}

	function _layoutCells() {
		_cells.forEach(function(cell) {
			cell.needsUpdate = true;
			_layoutCell(cell, cell.index);
		});
	}

	function _layoutCell(cell, index) {
		var cellRectangle = _gridCellPositioner.getCellRectangleOfIndex(_gridSolution, index);
		cellRectangle.x += _rectangle.x;
		cellRectangle.y = _rectangle.height - cellRectangle.y - cellRectangle.height + _rectangle.y;
		if(_debugLevel >= 1) console.log('layout', cell.name, index);
		setPlaneToOrthographicRectangle(cell.object3D, cellRectangle);
		cell.x = cellRectangle.x;
		cell.y = cellRectangle.y;
		cell.width = cellRectangle.width;
		cell.height = cellRectangle.height;
		cell.object3D.setSize(cellRectangle.width, cellRectangle.height);
		cell.object3D.setResolution(cellRectangle.width * _renderer.devicePixelRatio, cellRectangle.height * _renderer.devicePixelRatio);
		cell.object3D.visible = index < _totalCells;
		if(cell.reset) cell.reset();
	}

	function _changeCellData(cell, index) {
		var data = _data[index];
		cell.index = index;

		//set/change cell behaviour
		if(data.cellDecorator !== cell.initdCellDecorator) {
			data.cellDecorator(cell);
			cell.initdCellDecorator = data.cellDecorator;
		}

		cell.setData(data);

		if(_debugLevel >= 1) console.log('change', cell.name, index);

		_layoutCell(cell, index);
		cell.needsUpdate = true;
		onCellResetSignal.dispatch(cell);
		delete cell.fresh;
	}

	function _setRectangle(rectangle) {
		_rectangle = rectangle;
		_solveGrid();
		//extra precalculations for speed
		_updateCameraBounds();
	}

	function _updateCellPool() {
		_cellPoolSize = _gridCellPositioner.getPoolSize(_gridSolution);
		_cellPoolSize = Math.min(_cellPoolSize, _totalCells);
		if(_actualCellPoolSize !== _cellPoolSize) {
			while(_actualCellPoolSize < _cellPoolSize) {
				_createCell();
				_actualCellPoolSize++;
			}
			while(_actualCellPoolSize > _cellPoolSize) {
				_destroyCell();
				_actualCellPoolSize--;
			}
		}
	}

	function _setData(data){
		_data = data;
		_totalCells = data.length;
		_updateCellPool();
		_cells.forEach(function(cell) {
			cell.index = -1;
			cell.needsUpdate = true;
		});
	}

	function _determineGridMargins() {
		_marginX = 0;
		_marginY = 0;
		if(_totalCells > _gridSolution.cellCount) {
			if(_scrollAxis === 'x') {
				_marginX = 0.25;
			} else {
				_marginY = 0.25;
			}
		}

		var paddedWidth = _rectangle.width + _gridSolution.cellWidth * _marginX;
		var ratioWidth = _rectangle.width / paddedWidth;
		_gridSolution.cellWidth *= ratioWidth;
		_gridSolution.innerWidth = _rectangle.width * ratioWidth;
		_gridSolution.marginWidth = _rectangle.width - _gridSolution.innerWidth;

		var paddedHeight = _rectangle.height + _gridSolution.cellHeight * _marginY;
		var ratioHeight = _rectangle.height / paddedHeight;
		_gridSolution.cellHeight *= ratioHeight;
		_gridSolution.innerHeight = _rectangle.height * ratioHeight;
		_gridSolution.marginHeight = _rectangle.height - _gridSolution.innerHeight;

	}

	function _determineScrolling() {
		_scrollXScale = _scrollYScale = _totalCells > _gridSolution.cellCount ? 1 : 0;
	}

	function _solveGrid() {
		var index = _gridSolution ? _gridCellPositioner.getIndexOfScroll(_gridSolution, _gridLayout['scroll' + _scrollAxisCapitalized]) : undefined;
		_gridSolution = _gridLayout.solve(_rectangle);
		_determineGridMargins();
		_determineScrolling();
		if(index !== undefined) _gridCellPositioner.setScrollFromIndex(_gridLayout, _gridSolution, index);
		_rectangle.right = _rectangle.x + _rectangle.width;
		_rectangle.bottom = _rectangle.y + _rectangle.height;
		_updateCellPool();
		_layoutCells();
		_this.gridSolution = _gridSolution;
	}

	function _setPreferredCellCount(val) {
		_gridLayout.setPreferredCellCount(val);
		_solveGrid();
	}

	function getCellRectangleOfIndex(index) {
		var rect = _gridCellPositioner.getCellRectangleOfIndex(_gridSolution, index);
		rect.x += _rectangle.x;
		rect.y = _rectangle.height - rect.y - rect.height + _rectangle.y;
		return rect;
	}

	function _getScene() {
		return _scene;
	}

	function _getCamera() {
		return _camera;
	}

	function changed() {
		var anythingChanged = false;
		for (var i = _cells.length - 1; i >= 0; i--) {
			anythingChanged = _cells[i].object3D.changed() || anythingChanged;
		};
		if(_changed) {
			anythingChanged = true;
			_changed = false;
		}
		return anythingChanged;
	}

	this.setData = _setData;
	this.gridLayout = _gridLayout;
	this.setRectangle = _setRectangle;
	this.onEnterFrame = _onEnterFrame;
	this.getCellUnderPosition = _getCellUnderPosition;
	this.getVisibleCells = _getVisibleCells;
	this.render = _render;
	this.setPreferredCellCount = _setPreferredCellCount;
	this.cells = _cells;
	this.onCellResetSignal = onCellResetSignal;
	this.updateCells = _updateCells;
	this.getScene = _getScene;
	this.getCamera = _getCamera;
	this.getCellRectangleOfIndex = getCellRectangleOfIndex;
	this.changed = changed;
}

module.exports = GridView;<|endoftext|>


<commit_before>(function () {
	var url = window.location,
		body = document.body,
		slides = document.querySelectorAll('div.slide'),
		progress = document.querySelector('div.progress div'),
		slideList = [],
		l = slides.length, i;

	for (i = 0; i < l; i++) {
		slideList.push({
			id: slides[i].id,
			hasInnerNavigation: null !== slides[i].querySelector('.inner')
		});
	}

	function getTransform() {
		var denominator = Math.max(
			body.clientWidth / window.innerWidth,
			body.clientHeight / window.innerHeight
		);

		return 'scale(' + (1 / denominator) + ')';
	}

	function applyTransform(transform) {
		body.style.WebkitTransform = transform;
		body.style.MozTransform = transform;
		body.style.msTransform = transform;
		body.style.OTransform = transform;
		body.style.transform = transform;
	}

	function enterSlideMode() {
		body.className = 'full';
		applyTransform(getTransform());
	}

	function enterListMode() {
		body.className = 'list';
		applyTransform('none');
	}

	function getCurrentSlideNumber() {
		var i, l = slideList.length,
			currentSlideId = url.hash.substr(1);

		for (i = 0; i < l; ++i) {
			if (currentSlideId === slideList[i].id) {
				return i;
			}
		}

		return -1;
	}

	function scrollToCurrentSlide() {
		var currentSlide = document.getElementById(
			slideList[getCurrentSlideNumber()].id
		);

		if (null != currentSlide) {
			window.scrollTo(0, currentSlide.offsetTop);
		}
	}

	function isListMode() {
		return 'full' !== url.search.substr(1);
	}

	function normalizeSlideNumber(slideNumber) {
		if (0 > slideNumber) {
			return slideList.length - 1;
		} else if (slideList.length <= slideNumber) {
			return 0;
		} else {
			return slideNumber;
		}
	}

	function updateProgress(slideNumber) {
		if (null === progress) { return; }
		progress.style.width = (100 / (slideList.length - 1) * normalizeSlideNumber(slideNumber)).toFixed(2) + '%';
	}

	function getSlideHash(slideNumber) {
		return '#' + slideList[normalizeSlideNumber(slideNumber)].id;
	}

	function goToSlide(slideNumber) {
		url.hash = getSlideHash(slideNumber);

		if (!isListMode()) {
			updateProgress(slideNumber);
		}
	}

	function getContainingSlideId(el) {
		var node = el;
		while ('BODY' !== node.nodeName && 'HTML' !== node.nodeName) {
			if (-1 !== node.className.indexOf('slide')) {
				return node.id;
			} else {
				node = node.parentNode;
			}
		}

		return '';
	}

	function dispatchSingleSlideMode(e) {
		var slideId = getContainingSlideId(e.target);

		if ('' !== slideId && isListMode()) {
			e.preventDefault();

			// NOTE: we should update hash to get things work properly
			url.hash = '#' + slideId;
			history.replaceState(null, null, url.pathname + '?full#' + slideId);
			enterSlideMode();

			updateProgress(getCurrentSlideNumber());
		}
	}

	// Increases inner navigation by adding 'active' class to next inactive inner navigation item
	function increaseInnerNavigation(slideNumber) {
		// Shortcut for slides without inner navigation
		if (true !== slideList[slideNumber].hasInnerNavigation) { return -1; }

		var activeNodes = document.querySelectorAll(getSlideHash(slideNumber) + ' .active'),
			// NOTE: we assume there is no other elements in inner navigation
			node = activeNodes[activeNodes.length - 1].nextElementSibling;

		if (null !== node) {
			node.classList.add('active');
			return activeNodes.length + 1;
		} else {
			return -1;
		}
	}

	// Event handlers

	window.addEventListener('DOMContentLoaded', function () {
		if (!isListMode()) {
			// "?full" is present without slide hash, so we should display first slide
			if (-1 === getCurrentSlideNumber()) {
				history.replaceState(null, null, url.pathname + '?full' + getSlideHash(0));
			}

			enterSlideMode();
			updateProgress(getCurrentSlideNumber());
		}
	}, false);

	window.addEventListener('popstate', function (e) {
		if (isListMode()) {
			enterListMode();
			scrollToCurrentSlide();
		} else {
			enterSlideMode();
		}
	}, false);

	window.addEventListener('resize', function (e) {
		if (!isListMode()) {
			applyTransform(getTransform());
		}
	}, false);

	document.addEventListener('keydown', function (e) {
		// Shortcut for alt, shift and meta keys
		if (e.altKey || e.ctrlKey || e.metaKey) { return; }

		var currentSlideNumber = getCurrentSlideNumber();

		switch (e.which) {
			case 116: // F5
			case 13: // Enter
				if (isListMode()) {
					e.preventDefault();

					history.pushState(null, null, url.pathname + '?full' + getSlideHash(currentSlideNumber));
					enterSlideMode();

					updateProgress(currentSlideNumber);
				}
			break;

			case 27: // Esc
				if (!isListMode()) {
					e.preventDefault();

					history.pushState(null, null, url.pathname + getSlideHash(currentSlideNumber));
					enterListMode();
					scrollToCurrentSlide();
				}
			break;

			case 33: // PgUp
			case 38: // Up
			case 37: // Left
			case 72: // h
			case 75: // k
				e.preventDefault();

				currentSlideNumber--;
				goToSlide(currentSlideNumber);
			break;

			case 34: // PgDown
			case 40: // Down
			case 39: // Right
			case 76: // l
			case 74: // j
				e.preventDefault();

				// Only go to next slide if current slide have no inner
				// navigation or inner navigation is fully shown
				if (
					!slideList[currentSlideNumber].hasInnerNavigation ||
					-1 === increaseInnerNavigation(currentSlideNumber)
				) {
					currentSlideNumber++;
					goToSlide(currentSlideNumber);
				}
			break;

			case 36: // Home
				e.preventDefault();

				currentSlideNumber = 0;
				goToSlide(currentSlideNumber);
			break;

			case 35: // End
				e.preventDefault();

				currentSlideNumber = slideList.length - 1;
				goToSlide(currentSlideNumber);
			break;

			case 9: // Tab = +1; Shift + Tab = -1
			case 32: // Space = +1; Shift + Space = -1
				e.preventDefault();

				currentSlideNumber += e.shiftKey ? -1 : 1;
				goToSlide(currentSlideNumber);
			break;

			default:
				// Behave as usual
		}
	}, false);

	document.addEventListener('click', dispatchSingleSlideMode, false);
	document.addEventListener('touchend', dispatchSingleSlideMode, false);

	document.addEventListener('touchstart', function (e) {
		if (!isListMode()) {
			var currentSlideNumber = getCurrentSlideNumber(),
				x = e.touches[0].pageX;
			if (x > window.innerWidth / 2) {
				currentSlideNumber++;
			} else {
				currentSlideNumber--;
			}

			goToSlide(currentSlideNumber);
		}
	}, false);

	document.addEventListener('touchmove', function (e) {
		if (!isListMode()) {
			e.preventDefault();
		}
	}, false);

}());<commit_msg>className.indexOf replaced with classList.contains<commit_after>(function () {
	var url = window.location,
		body = document.body,
		slides = document.querySelectorAll('div.slide'),
		progress = document.querySelector('div.progress div'),
		slideList = [],
		l = slides.length, i;

	for (i = 0; i < l; i++) {
		slideList.push({
			id: slides[i].id,
			hasInnerNavigation: null !== slides[i].querySelector('.inner')
		});
	}

	function getTransform() {
		var denominator = Math.max(
			body.clientWidth / window.innerWidth,
			body.clientHeight / window.innerHeight
		);

		return 'scale(' + (1 / denominator) + ')';
	}

	function applyTransform(transform) {
		body.style.WebkitTransform = transform;
		body.style.MozTransform = transform;
		body.style.msTransform = transform;
		body.style.OTransform = transform;
		body.style.transform = transform;
	}

	function enterSlideMode() {
		body.className = 'full';
		applyTransform(getTransform());
	}

	function enterListMode() {
		body.className = 'list';
		applyTransform('none');
	}

	function getCurrentSlideNumber() {
		var i, l = slideList.length,
			currentSlideId = url.hash.substr(1);

		for (i = 0; i < l; ++i) {
			if (currentSlideId === slideList[i].id) {
				return i;
			}
		}

		return -1;
	}

	function scrollToCurrentSlide() {
		var currentSlide = document.getElementById(
			slideList[getCurrentSlideNumber()].id
		);

		if (null != currentSlide) {
			window.scrollTo(0, currentSlide.offsetTop);
		}
	}

	function isListMode() {
		return 'full' !== url.search.substr(1);
	}

	function normalizeSlideNumber(slideNumber) {
		if (0 > slideNumber) {
			return slideList.length - 1;
		} else if (slideList.length <= slideNumber) {
			return 0;
		} else {
			return slideNumber;
		}
	}

	function updateProgress(slideNumber) {
		if (null === progress) { return; }
		progress.style.width = (100 / (slideList.length - 1) * normalizeSlideNumber(slideNumber)).toFixed(2) + '%';
	}

	function getSlideHash(slideNumber) {
		return '#' + slideList[normalizeSlideNumber(slideNumber)].id;
	}

	function goToSlide(slideNumber) {
		url.hash = getSlideHash(slideNumber);

		if (!isListMode()) {
			updateProgress(slideNumber);
		}
	}

	function getContainingSlideId(el) {
		var node = el;
		while ('BODY' !== node.nodeName && 'HTML' !== node.nodeName) {
			if (node.classList.contains('slide')) {
				return node.id;
			} else {
				node = node.parentNode;
			}
		}

		return '';
	}

	function dispatchSingleSlideMode(e) {
		var slideId = getContainingSlideId(e.target);

		if ('' !== slideId && isListMode()) {
			e.preventDefault();

			// NOTE: we should update hash to get things work properly
			url.hash = '#' + slideId;
			history.replaceState(null, null, url.pathname + '?full#' + slideId);
			enterSlideMode();

			updateProgress(getCurrentSlideNumber());
		}
	}

	// Increases inner navigation by adding 'active' class to next inactive inner navigation item
	function increaseInnerNavigation(slideNumber) {
		// Shortcut for slides without inner navigation
		if (true !== slideList[slideNumber].hasInnerNavigation) { return -1; }

		var activeNodes = document.querySelectorAll(getSlideHash(slideNumber) + ' .active'),
			// NOTE: we assume there is no other elements in inner navigation
			node = activeNodes[activeNodes.length - 1].nextElementSibling;

		if (null !== node) {
			node.classList.add('active');
			return activeNodes.length + 1;
		} else {
			return -1;
		}
	}

	// Event handlers

	window.addEventListener('DOMContentLoaded', function () {
		if (!isListMode()) {
			// "?full" is present without slide hash, so we should display first slide
			if (-1 === getCurrentSlideNumber()) {
				history.replaceState(null, null, url.pathname + '?full' + getSlideHash(0));
			}

			enterSlideMode();
			updateProgress(getCurrentSlideNumber());
		}
	}, false);

	window.addEventListener('popstate', function (e) {
		if (isListMode()) {
			enterListMode();
			scrollToCurrentSlide();
		} else {
			enterSlideMode();
		}
	}, false);

	window.addEventListener('resize', function (e) {
		if (!isListMode()) {
			applyTransform(getTransform());
		}
	}, false);

	document.addEventListener('keydown', function (e) {
		// Shortcut for alt, shift and meta keys
		if (e.altKey || e.ctrlKey || e.metaKey) { return; }

		var currentSlideNumber = getCurrentSlideNumber();

		switch (e.which) {
			case 116: // F5
			case 13: // Enter
				if (isListMode()) {
					e.preventDefault();

					history.pushState(null, null, url.pathname + '?full' + getSlideHash(currentSlideNumber));
					enterSlideMode();

					updateProgress(currentSlideNumber);
				}
			break;

			case 27: // Esc
				if (!isListMode()) {
					e.preventDefault();

					history.pushState(null, null, url.pathname + getSlideHash(currentSlideNumber));
					enterListMode();
					scrollToCurrentSlide();
				}
			break;

			case 33: // PgUp
			case 38: // Up
			case 37: // Left
			case 72: // h
			case 75: // k
				e.preventDefault();

				currentSlideNumber--;
				goToSlide(currentSlideNumber);
			break;

			case 34: // PgDown
			case 40: // Down
			case 39: // Right
			case 76: // l
			case 74: // j
				e.preventDefault();

				// Only go to next slide if current slide have no inner
				// navigation or inner navigation is fully shown
				if (
					!slideList[currentSlideNumber].hasInnerNavigation ||
					-1 === increaseInnerNavigation(currentSlideNumber)
				) {
					currentSlideNumber++;
					goToSlide(currentSlideNumber);
				}
			break;

			case 36: // Home
				e.preventDefault();

				currentSlideNumber = 0;
				goToSlide(currentSlideNumber);
			break;

			case 35: // End
				e.preventDefault();

				currentSlideNumber = slideList.length - 1;
				goToSlide(currentSlideNumber);
			break;

			case 9: // Tab = +1; Shift + Tab = -1
			case 32: // Space = +1; Shift + Space = -1
				e.preventDefault();

				currentSlideNumber += e.shiftKey ? -1 : 1;
				goToSlide(currentSlideNumber);
			break;

			default:
				// Behave as usual
		}
	}, false);

	document.addEventListener('click', dispatchSingleSlideMode, false);
	document.addEventListener('touchend', dispatchSingleSlideMode, false);

	document.addEventListener('touchstart', function (e) {
		if (!isListMode()) {
			var currentSlideNumber = getCurrentSlideNumber(),
				x = e.touches[0].pageX;
			if (x > window.innerWidth / 2) {
				currentSlideNumber++;
			} else {
				currentSlideNumber--;
			}

			goToSlide(currentSlideNumber);
		}
	}, false);

	document.addEventListener('touchmove', function (e) {
		if (!isListMode()) {
			e.preventDefault();
		}
	}, false);

}());<|endoftext|>


<commit_before>/**
 * 项目里的Controller基类
 * 这里做一些通用的处理逻辑，其他Controller继承该类
 * @param  {[type]}
 * @return {[type]}         [description]
 */
module.exports = Controller(function(){
  'use strict';

  return {
    init: function(http){
      var self = this;
      self.super("init", http);
      if (self.http.action != "login") {
        return this.session("userInfo").then(function(value){
          if(value){
            self.userInfo = value;
          }else{
            var auth_info = self.cookie(AUTH_ID);
            if(auth_info){
              auth_info = decrypt(auth_info);
              auth_info = auth_info.split('\t');
              self.userInfo = {
                username : auth_info[0],
                id : auth_info[1] - 0,
                avator : auth_info[2] -1
              }
            }else{
              self.userInfo = null;
            }
          }

          //self.assign('userInfo', value);
        })
      };
    }
  }
})<commit_msg>fix bug by wangpengfei<commit_after>/**
 * 项目里的Controller基类
 * 这里做一些通用的处理逻辑，其他Controller继承该类
 * @param  {[type]}
 * @return {[type]}         [description]
 */
module.exports = Controller(function(){
  'use strict';

  return {
    init: function(http){
      var self = this;
      self.super("init", http);
      if (self.http.action != "login") {
        return this.session("userInfo").then(function(value){
          if(value){
            self.userInfo = value;
          }else{
            var auth_info = self.cookie(AUTH_ID);
            if(auth_info){
              auth_info = decrypt(auth_info);
              auth_info = auth_info.split('\t');
              self.userInfo = {
                username : auth_info[0],
                id : auth_info[1] - 0,
                avator : auth_info[2] - 0
              }
            }else{
              self.userInfo = null;
            }
          }

          //self.assign('userInfo', value);
        })
      };
    }
  }
})<|endoftext|>


<commit_before>const delegate = function(criteria, listener) {
  return function(e) {
    const el = e.target
    do {
      if (!criteria(el))
        continue
      e.delegateTarget = el
      listener.apply(this, arguments)
      return
    } while((el = el.parentNode))
  }
}

export default delegate
<commit_msg>let instead of const<commit_after>const delegate = function(criteria, listener) {
  return function(e) {
    let el = e.target
    do {
      if (!criteria(el))
        continue
      e.delegateTarget = el
      listener.apply(this, arguments)
      return
    } while((el = el.parentNode))
  }
}

export default delegate
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Mixin.create({
  classNameBindings:[
    'raised:md-raised'
  ],
  raised:false,
  animatedShadow:true,
  bottomShadowCSS:Ember.computed('z',function(){
    var raised = this.get('raised'),
      disabled = this.get('disabled');
    if(!raised || disabled){
      return;
    }
    var z = this.get('z');
    return z?'paper-shadow-bottom-z-'+z:'';
  })
});
<commit_msg>remove unused shadow mixin<commit_after><|endoftext|>


<commit_before>var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var $ = utils.getLocaleString;
var VNetCRUD = require('./vnetCRUD');

function DnsServerCRUD(cli, networkResourceProviderClient) {
  this.cli = cli;
  this.networkResourceProviderClient = networkResourceProviderClient;
  this.vNetCRUD = new VNetCRUD(this.cli, this.networkResourceProviderClient);
}

__.extend(DnsServerCRUD.prototype, {
  list: function (resourceGroupName, vNetName, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vNetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s'), vNetName, resourceGroupName));
    }

    var output = this.cli.output;
    var hasDns = this._hasDnsServers(vnet.virtualNetwork);
    this.cli.interaction.formatOutput(vnet.virtualNetwork, function (outputData) {
      if (hasDns) {
        output.table(outputData.properties.dhcpOptions.dnsServers, function (row, item) {
          row.cell($('IP Address'), item);
        });
      } else {
        output.info($('No dns servers found'));
      }
    });
  },

  register: function (resourceGroupName, vnetName, dnsIp, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vnetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s'), vnetName, resourceGroupName));
    }

    var vnetProfile = vnet.virtualNetwork;
    this._createDnsIfNotExist(vnetProfile);
    vnetProfile.properties.dhcpOptions.dnsServers.push(dnsIp);

    this.vNetCRUD.update(resourceGroupName, vnetName, vnetProfile, _);
  },

  unregister: function (resourceGroupName, vnetName, dnsIp, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vnetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s'), vnetName, resourceGroupName));
    }

    var vnetProfile = vnet.virtualNetwork;
    this._createDnsIfNotExist(vnetProfile);
    var dnsServers = vnetProfile.properties.dhcpOptions.dnsServers;
    dnsServers = __.without(dnsServers, dnsIp);
    vnetProfile.properties.dhcpOptions.dnsServers = dnsServers;

    this.vNetCRUD.update(resourceGroupName, vnetName, vnetProfile, _);
  },

  _hasDnsServers: function (vnet) {
    var prop = vnet.properties;
    return (prop.dhcpOptions && prop.dhcpOptions.dnsServers && prop.dhcpOptions.dnsServers.length !== 0);
  },

  _createDnsIfNotExist: function (vnet) {
    if (!vnet.properties.dhcpOptions) vnet.properties.dhcpOptions = {};
    if (!vnet.properties.dhcpOptions.dnsServers) vnet.properties.dhcpOptions.dnsServers = [];
  }
});

module.exports = DnsServerCRUD;<commit_msg>register & unregister extra check added string format fixed<commit_after>var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var $ = utils.getLocaleString;
var VNetCRUD = require('./vnetCRUD');

function DnsServerCRUD(cli, networkResourceProviderClient) {
  this.cli = cli;
  this.networkResourceProviderClient = networkResourceProviderClient;
  this.vNetCRUD = new VNetCRUD(this.cli, this.networkResourceProviderClient);
}

__.extend(DnsServerCRUD.prototype, {
  list: function (resourceGroupName, vNetName, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vNetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s"'), vNetName, resourceGroupName));
    }

    var output = this.cli.output;
    var hasDns = this._hasDnsServers(vnet.virtualNetwork);
    this.cli.interaction.formatOutput(vnet.virtualNetwork, function (outputData) {
      if (hasDns) {
        output.table(outputData.properties.dhcpOptions.dnsServers, function (row, item) {
          row.cell($('IP Address'), item);
        });
      } else {
        output.info($('No dns servers found'));
      }
    });
  },

  register: function (resourceGroupName, vnetName, dnsIp, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vnetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s"'), vnetName, resourceGroupName));
    }

    var vnetProfile = vnet.virtualNetwork;
    this._createDnsIfNotExist(vnetProfile);
    var dnsServers = vnetProfile.properties.dhcpOptions.dnsServers;

    if(!__.contains(dnsServers, dnsIp)) {
      vnetProfile.properties.dhcpOptions.dnsServers.push(dnsIp);
      this.vNetCRUD.update(resourceGroupName, vnetName, vnetProfile, _);
    } else {
      this.cli.output.error(util.format($('A DNS Server with IP "%s" already registered'), dnsIp));
    }
  },

  unregister: function (resourceGroupName, vnetName, dnsIp, _) {
    var vnet = this.vNetCRUD.get(resourceGroupName, vnetName, _);
    if (!vnet) {
      throw new Error(util.format($('A virtual network with name "%s" not found in the resource group "%s"'), vnetName, resourceGroupName));
    }

    var vnetProfile = vnet.virtualNetwork;
    this._createDnsIfNotExist(vnetProfile);
    var dnsServers = vnetProfile.properties.dhcpOptions.dnsServers;

    if(__.contains(dnsServers, dnsIp)) {
      dnsServers = __.without(dnsServers, dnsIp);
      vnetProfile.properties.dhcpOptions.dnsServers = dnsServers;
      this.vNetCRUD.update(resourceGroupName, vnetName, vnetProfile, _);
    } else {
      this.cli.output.error(util.format($('A DNS Server with IP "%s" not found'), dnsIp));
    }
  },

  _hasDnsServers: function (vnet) {
    var prop = vnet.properties;
    return (prop.dhcpOptions && prop.dhcpOptions.dnsServers && prop.dhcpOptions.dnsServers.length !== 0);
  },

  _createDnsIfNotExist: function (vnet) {
    if (!vnet.properties.dhcpOptions) vnet.properties.dhcpOptions = {};
    if (!vnet.properties.dhcpOptions.dnsServers) vnet.properties.dhcpOptions.dnsServers = [];
  }
});

module.exports = DnsServerCRUD;<|endoftext|>


<commit_before>"use strict";
window.open = url => {
	location.href = url;
};

window.alert = () => {};

function callback(val) {
	if (window.callPhantom) {
		window.callPhantom(val);
	} else if (window.require) {
		const {ipcRenderer} = require("electron");
		ipcRenderer.sendToHost("close", val);
	}
}

function requestData() {
	return new Promise(resolve => {
		const {ipcRenderer} = require("electron");
		ipcRenderer.once("data", (e, data) => {
			resolve(data);
		});
		ipcRenderer.sendToHost("request-data");
	});
}

function getHomeWorkUrls() {
	let links = document.querySelectorAll("table tr a[name^=workToUrl]");
	if (links && links.length) {
		const urls = {
			specials: [],
		};
		links = Array.from(links).map(a => {
			const args = eval(a.getAttribute("onclick").trim().replace(/^\s*\w+\s*\((.+)\).*$/, "[$1]"));
			if (args[5]) {
				urls.specials.push({
					title: a.parentNode.parentNode.children[1].textContent.trim(),
					url: args[5],
				});
			} else {
				urls[String(args[0])] = `/JiaTing/EscapeSkill/SeeVideo.aspx?gid=${ args[3] }&li=${ args[0] }`;
			}
		});
		callback(urls);
	} else {
		setTimeout(getHomeWorkUrls, 800);
	}
}

window.addEventListener("load", () => {
	setTimeout(() => {
		const $ = window.$;

		function whaitResult() {
			if ($("#yes:visible").length) {
				callback();
			} else {
				setTimeout(whaitResult, 600);
			}
		}
		if (location.pathname === "/JiaTing/JtMyHomeWork.html") {
			getHomeWorkUrls();
		} else if (window.ShowTestPaper) {
			window.getAnswers = function(answers) {
				setTimeout(function() {
					$(".bto_testbox input[type=radio]").prop("checked", function(i) {
						return !!+answers.Rows[i].istrue;
					});
					$(".bto_testbox .btn_submit").click();
					whaitResult();
				}, 600);
			};

			window.eval(window.ShowTestPaper.toString().replace(/TestPaperThreelistGet2.*?\n?.*?if\s+\(.*?\b(\w+)\.Rows\.length.*?\)\s*\{/, function(s, dataVarName) {
				return s + "getAnswers(" + dataVarName + ");";
			}));
			window.ShowTestPaper();
		} else if (window.loadQuestion) {
			window.loadQuestion(0, 99, 1, false);
			$("label:visible").click();
			requestData().then(student => {
				const sex = "男女"[student.sex - 1];
				const grade = [
					"小学",
					"小学",
					"初中",
					"高中",
				][parseInt((student.grade - 1) / 3)];
				[
					"在本地生活",
					"12339",
					"2015年7月1日",
					"城市",
					sex,
					grade,
				].forEach(label => {
					$(`label:contains('${label}'):visible`).click();
				});

				setTimeout(() => {
					$("a:contains('提交')").click();
					setTimeout(callback, 1000);
				}, 1000);
			});
		} else {
			$("a:contains('马上去'), a:contains('请签'), a:contains('请点')").filter(":visible").click();
			setTimeout(() => {
				location.href = $("a:contains('二'):visible").prop("href");
			}, 1000);
		}
	}, 1000);
});

if (process.env.CI_TEACHER_ACCOUNT) {
	setTimeout(callback, 90000);
}
<commit_msg>Close #41<commit_after>"use strict";

function getRandomItemOfArray(arr) {
	return arr[Math.floor(Math.random() * arr.length)];
}

const specials = {
	"性别": student => "男女"[student.sex - 1],
	"你的学校属于什么位置": getRandomItemOfArray(["城市", "农村"]),
	"和谁在一起生活": getRandomItemOfArray(["父母外出", "在父母所在", "本地生活"]),
	"你家是否有灭火器": "没有",
	"你家是否制定了家庭火灾逃生路线图": "没有",
	"你家是否定期进行消防疏散演练": "没有",
	"你家如果油锅起火了": ["锅盖盖住", "干毛巾覆盖"],
	"你家是否存放了汽油": "没有",
	"你家的防盗窗上是否留有逃生出口": "没有",
	"会正确拨打119报警电话": "都会",
	"是否堆放了杂物": "没有",
	"沙发上抽烟": "没有",
	"炉灶有火时": "有",
	"抽油烟机是否会定期清洗": "会",
	"你家会定期检查线路": "会",
	"出门关闭电源": "有",
	"是否放在了安全的地方": "是",
	"是否摆放在了安全的位置": "是",
	"长期不拔的现象": "没有",
	"常年不拔电源插头的现象": "否",
	"电器着火": ["切断电源", "干粉灭火器"],
	"电视机着火": ["切断电源", "干粉灭火器"],
	"检查燃气是否有泄漏": "肥皂水",
	"是否有在消防通道停放车辆": "没有",
	"防火门": "关闭",
	"火灾报警电话": "119",
	"油锅着火": ["将锅端下", "锅盖"],
	"入住宾馆酒店时": "逃生路线图",
	"闻到煤气气味时": "打开门窗通风",
	"求救方法错误的是": "大声哭泣",
	"儿童燃放烟花爆竹时": "由大人看护",
	"被困室内无法逃生时": ["堵塞门缝", "把水泼在门上降温", "发出求救信"],
	"消防违法行为": ["封闭消防安全出口", "遮挡消防设施", "损坏公共消防设施"],
	"用电时要注意防火安全": ["不乱接乱拉电线，不超负荷用电", "及时更换老化电器设施和线路", "外出时要关闭电源开关"],
	"家庭应该采取的消防安全措施": ["配备必要的消防器材", "绘制家庭逃生疏散路线", "消除家庭火灾隐患"],
	"为做到防患于未然": "制定家庭疏散预案并进行演练",
	"正确的逃生方法是": "迅速逃生",
	"高层建筑失火时": "从疏散通道逃离",
};

window.open = url => {
	location.href = url;
};

window.alert = () => {};

function callback(val) {
	if (window.callPhantom) {
		window.callPhantom(val);
	} else if (window.require) {
		const {ipcRenderer} = require("electron");
		ipcRenderer.sendToHost("close", val);
	}
}

function requestData() {
	return new Promise(resolve => {
		const {ipcRenderer} = require("electron");
		ipcRenderer.once("data", (e, data) => {
			resolve(data);
		});
		ipcRenderer.sendToHost("request-data");
	});
}

function getHomeWorkUrls() {
	let links = document.querySelectorAll("table tr a[name^=workToUrl]");
	if (links && links.length) {
		const urls = {
			specials: [],
		};
		links = Array.from(links).map(a => {
			const args = eval(a.getAttribute("onclick").trim().replace(/^\s*\w+\s*\((.+)\).*$/, "[$1]"));
			if (args[5]) {
				urls.specials.push({
					title: a.parentNode.parentNode.children[1].textContent.trim(),
					url: args[5],
				});
			} else {
				urls[String(args[0])] = `/JiaTing/EscapeSkill/SeeVideo.aspx?gid=${ args[3] }&li=${ args[0] }`;
			}
		});
		callback(urls);
	} else {
		setTimeout(getHomeWorkUrls, 800);
	}
}

function ready(callback) {
	if (document.readyState === "complete") {
		callback();
	} else {
		window.addEventListener("load", callback);
	}
}

ready(() => {
	setTimeout(() => {
		const $ = window.$;

		function whaitResult() {
			if ($("#yes:visible").length) {
				callback();
			} else {
				setTimeout(whaitResult, 600);
			}
		}
		if (location.pathname === "/JiaTing/JtMyHomeWork.html") {
			getHomeWorkUrls();
		} else if (window.ShowTestPaper) {
			window.getAnswers = function(answers) {
				setTimeout(function() {
					$(".bto_testbox input[type=radio]").prop("checked", function(i) {
						return !!+answers.Rows[i].istrue;
					});
					$(".bto_testbox .btn_submit").click();
					whaitResult();
				}, 600);
			};

			window.eval(window.ShowTestPaper.toString().replace(/TestPaperThreelistGet2.*?\n?.*?if\s+\(.*?\b(\w+)\.Rows\.length.*?\)\s*\{/, function(s, dataVarName) {
				return s + "getAnswers(" + dataVarName + ");";
			}));
			window.ShowTestPaper();
		} else if (window.loadQuestion) {
			window.loadQuestion(0, 99, 1, false);
			$("label:visible").filter((i, label) => (
				document.getElementById(label.htmlFor).type === "radio"
			)).click();
			requestData().then(student => {
				const sex = "男女"[student.sex - 1];
				const grade = [
					"小学",
					"小学",
					"初中",
					"高中",
				][parseInt((student.grade - 1) / 3)];
				[
					sex,
					grade,
				].forEach(label => {
					$(`label:contains('${label}'):visible`).click();
				});

				for (const q in specials) {
					let a = specials[q];
					if (typeof a === "function") {
						a = a(student);
					}
					const dl = $(`dt:contains('${q}'):visible`).first().parent("dl");
					if (Array.isArray(a)) {
						a.forEach(a => {
							dl.find(`label:contains('${a}'):visible`).click();
						});
					} else {
						dl.find(`label:contains('${a}'):visible`).first().click();
					}
				}

				setTimeout(() => {
					$("a:contains('提交')").click();
					setTimeout(callback, 1000);
				}, 1000);
			});
		} else {
			$("a:contains('马上去'), a:contains('请签'), a:contains('请点')").filter(":visible").first().click();
			setTimeout(() => {
				location.href = $("a:contains('二'):visible").prop("href") || location.pathname.replace(/\d*(\.\w+)$/, "2$1");
			}, 1000);
		}
	}, 1000);
});

if (process.env.CI_TEACHER_ACCOUNT) {
	setTimeout(callback, 90000);
}
<|endoftext|>