<commit_before>var width = 420;
var height = 630;

var canvas = document.getElementById("arena");
var gameArena = canvas.getContext("2d");

canvas.addEventListener("click", test);

var countMatrix = new Array(9);
var colorMatrix = new Array(9);

initialiseMatrix();
drawArena();

function initialiseMatrix()
{
	for(var counter = 0; counter < 9; counter++)
	{
		countMatrix[counter] = new Array(6);
	}

	for(var counter = 0; counter < 9; counter++)
	{
		colorMatrix[counter] = new Array(6);
	}
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			colorMatrix[i][j] = 'Z';	//No color
			countMatrix[i][j] = 0;		//No value
		}
	}
}

function drawArena()
{
	var gapWidth = width/6;
	for(var counter = 1; counter < 6; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(counter*gapWidth, 0);
		gameArena.lineTo(counter*gapWidth, height);
		gameArena.closePath();
		gameArena.stroke();
	}
	var gapHeight = height/9;
	for(var counter = 1; counter < 9; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(0 , counter*gapHeight);
		gameArena.lineTo(width , counter*gapHeight);
		gameArena.closePath();
		gameArena.stroke();
	}
}

function test(event)
{
	var rect = canvas.getBoundingClientRect();
	var x = event.clientX - rect.left;
	var y = event.clientY - rect.top;
	alert("X: " + x + " Y: " + y);
}<commit_msg>Added basic functionalities<commit_after>var width = 420;
var height = 630;
var gapWidth = width/6;
var gapHeight = height/9;
var turnCount = 0;

var canvas = document.getElementById("arena");
var gameArena = canvas.getContext("2d");

canvas.addEventListener("click", test);

var countMatrix = new Array(9);
var colorMatrix = new Array(9);

initialiseMatrix();
drawArena();

function initialiseMatrix()
{
	for(var counter = 0; counter < 9; counter++)
	{
		countMatrix[counter] = new Array(6);
	}

	for(var counter = 0; counter < 9; counter++)
	{
		colorMatrix[counter] = new Array(6);
	}
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			colorMatrix[i][j] = "";		//No color
			countMatrix[i][j] = 0;		//No value
		}
	}
}

function drawArena()
{
	gameArena.clearRect(0, 0, width, height);
	gameArena.font = "35px Times New Roman";

	for(var counter = 1; counter < 6; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(counter*gapWidth, 0);
		gameArena.lineTo(counter*gapWidth, height);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var counter = 1; counter < 9; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(0 , counter*gapHeight);
		gameArena.lineTo(width , counter*gapHeight);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			if(countMatrix[i][j] == 0)
				continue;
			gameArena.fillStyle = colorMatrix[i][j];
			gameArena.fillText(countMatrix[i][j], j*gapWidth + 25, i*gapHeight + 45);
		}
	}
}

function test(event)
{
	var rect = canvas.getBoundingClientRect();
	var x = event.clientX - rect.left;
	var y = event.clientY - rect.top;

	var row = Math.floor(x/gapWidth);
	var column = Math.floor(y/gapHeight);

	if(turnCount%2 == 0 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "red"))
	{
		countMatrix[column][row]++;		//Weird graphic coordinate-system
		colorMatrix[column][row] = "red";
		turnCount++;
	}
	if(turnCount%2 == 1 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "green"))
	{
		countMatrix[column][row]++;		//Weird graphic coordinate-system
		colorMatrix[column][row] = "green";
		turnCount++;
	}
	drawArena();
}<|endoftext|>


<commit_before>define('app/controllers/rules', ['app/models/rule', 'ember'],
    //
    //  Rules Controller
    //
    //  @returns Class
    //
    function(Rule) {

        'use strict';

        return Ember.ArrayController.extend({

            content: [],
            command: null,
            commandRule: null,
            creationPending: false,

            metricList: [
                'load',
                'cpu',
                'ram',
                'disk-write',
                'network-tx'
            ],

            operatorList: [{
                'title': 'gt',
                'symbol': '>'
            }, {
                'title': 'lt',
                'symbol': '<'
            }],

            actionList: [
                'alert',
                'reboot',
                'destroy',
                'command'
            ],

            setContent: function(rules) {
                if (!rules) return;
                var that = this;
                Ember.run(function() {
                    for (var ruleId in rules) {
                        var rule = rules[ruleId];
                        rule.id = ruleId;
                        rule.actionToTake = rules[ruleId].action;
                        rule.operator = that.getOperatorByTitle(rules[ruleId].operator);
                        rule.metric = Mist.metricsController.getMetric(rules[ruleId].metric);
                        rule.machine = Mist.backendsController.getMachine(rule.machine, rule.backend) || rule.machine;
                        that.content.pushObject(Rule.create(rule));
                    }
                });
            },

            getRuleById: function(ruleId) {
                return this.content.findBy('id', ruleId);
            },

            getOperatorByTitle: function(ruleTitle) {
                return this.operatorList.findBy('title', ruleTitle);
            },

            creationPendingObserver: function() {
                if (this.creationPending)
                    $('#add-rule-button').addClass('ui-state-disabled');
                else
                    $('#add-rule-button').removeClass('ui-state-disabled');
            }.observes('creationPending'),

            newRule: function(machine, metric, operator, value, actionToTake) {
                this.set('creationPending', true);
                var that = this;
                Mist.ajax.POST('/rules', {
                    'backendId': machine.backend.id,
                    'machineId': machine.id,
                    'metric': metric.id,
                    'operator': operator.title,
                    'value': value,
                    'action': actionToTake
                }).success(function(data) {
                    info('Successfully created rule ', data.id);
                    that.set('creationPending', false);
                    var rule = Rule.create({
                        'id': data.id,
                        'value': value,
                        'metric': metric,
                        'machine': machine,
                        'operator': operator,
                        'maxValue': data.max_value,
                        'actionToTake': actionToTake,
                    });
                    that.pushObject(rule);
                    that.redrawRules();
                }).error(function(message) {
                    Mist.notificationController.notify('Error while creating rule: ' + message);
                    that.set('creationPending', false);
                });
            },

            deleteRule: function (rule) {
                var that = this;
                rule.set('pendingAction', true);
                Mist.ajax.DELETE('/rules/' + rule.id, {
                }).success(function(){
                    Mist.rulesController.removeObject(rule);
                    Mist.rulesController.redrawRules();
                }).error(function(message) {
                    Mist.notificationController.notify('Error while deleting rule: ' + message);
                    rule.set('pendingAction', false);
                });
            },

            updateRule: function(id, metric, operator, value, actionToTake, command) {

                var rule = this.getRuleById(id);

                if (!rule) {
                    return false;
                }

                // Make sure parameters are not null
                if (!value) { value = rule.value; }
                if (!metric) { metric = rule.metric.id; }
                if (!command) { command = rule.command; }
                if (!operator) { operator = rule.operator; }
                if (!actionToTake) { actionToTake = rule.actionToTake; }

                // Check if anything changed
                if (value == rule.value &&
                    metric == rule.metric.id &&
                    command == rule.command &&
                    actionToTake == rule.actionToTake &&
                    operator.title == rule.operator.title ) {
                        return false;
                }

                var that = this;
                rule.set('pendingAction', true);
                Mist.ajax.POST('/rules', {
                    'id': id,
                    'value': value,
                    'metric': metric,
                    'command': command,
                    'operator': operator.title,
                    'action': actionToTake,
                }).success(function(data) {
                    info('Successfully updated rule ', id);
                    rule.set('pendingAction', false);
                    rule.set('value', value);
                    rule.set('metric', Mist.metricsController.getMetric(metric));
                    rule.set('command', command);
                    rule.set('operator', operator);
                    rule.set('actionToTake', actionToTake);

                    var maxvalue = parseInt(rule.maxValue);
                    var curvalue = parseInt(rule.value);
                    if (curvalue > maxvalue) {
                        rule.set('value', maxvalue);
                    }
                }).error(function(message) {
                    Mist.notificationController.notify('Error while updating rule: ' + message);
                    rule.set('pendingAction', false);
                });
            },

            setSliderEventHandlers: function() {
                function showSlider(event) {
                    var rule_id = $(event.currentTarget).parent().attr('id');
                    var rule = Mist.rulesController.getRuleById(rule_id);
                    if (rule.metric.hasRange) {
                        $(event.currentTarget).addClass('open');
                        $(event.currentTarget).find('.ui-slider-track').fadeIn(100);
                    }
                }
                function hideSlider(event) {
                    $(event.currentTarget).find('.ui-slider-track').fadeOut(100);
                    $(event.currentTarget).find('.ui-slider').removeClass('open');
                }
                $('.rules-container .ui-slider').on('tap', showSlider);
                $('.rules-container .ui-slider').on('click', showSlider);
                $('.rules-container .ui-slider').on('mouseover', showSlider);
                $('#single-machine').on('tap', hideSlider);
                $('.rules-container .rule-box').on('mouseleave', hideSlider);
            },

            removeSliderEventHandlers: function() {
                $('.rules-container .ui-slider').off('tap');
                $('.rules-container .ui-slider').off('click');
                $('.rules-container .ui-slider').off('mouseover');
                $('#single-machine').off('tap');
                $('.rules-container .rule-box').off('mouseleave');
            },

            redrawRules: function() {
                var that = this;
                Ember.run.next(function() {
                    that.removeSliderEventHandlers();
                    $('.rule-box').trigger('create');
                    that.setSliderEventHandlers();
                });
            },
        });
    }
);
<commit_msg>Fix rules after disable->enable monitoring<commit_after>define('app/controllers/rules', ['app/models/rule', 'ember'],
    //
    //  Rules Controller
    //
    //  @returns Class
    //
    function(Rule) {

        'use strict';

        return Ember.ArrayController.extend({

            content: [],
            command: null,
            commandRule: null,
            creationPending: false,

            metricList: [
                'load',
                'cpu',
                'ram',
                'disk-write',
                'network-tx'
            ],

            operatorList: [{
                'title': 'gt',
                'symbol': '>'
            }, {
                'title': 'lt',
                'symbol': '<'
            }],

            actionList: [
                'alert',
                'reboot',
                'destroy',
                'command'
            ],

            setContent: function(rules) {
                if (!rules) return;
                var that = this;
                Ember.run(function() {
                    var newRules = [];
                    for (var ruleId in rules) {
                        var rule = rules[ruleId];
                        rule.id = ruleId;
                        rule.actionToTake = rules[ruleId].action;
                        rule.operator = that.getOperatorByTitle(rules[ruleId].operator);
                        rule.metric = Mist.metricsController.getMetric(rules[ruleId].metric);
                        rule.machine = Mist.backendsController.getMachine(rule.machine, rule.backend) || rule.machine;
                        newRules.push(Rule.create(rule));
                    }
                    that.set('content', newRules);
                });
            },

            getRuleById: function(ruleId) {
                return this.content.findBy('id', ruleId);
            },

            getOperatorByTitle: function(ruleTitle) {
                return this.operatorList.findBy('title', ruleTitle);
            },

            creationPendingObserver: function() {
                if (this.creationPending)
                    $('#add-rule-button').addClass('ui-state-disabled');
                else
                    $('#add-rule-button').removeClass('ui-state-disabled');
            }.observes('creationPending'),

            newRule: function(machine, metric, operator, value, actionToTake) {
                this.set('creationPending', true);
                var that = this;
                Mist.ajax.POST('/rules', {
                    'backendId': machine.backend.id,
                    'machineId': machine.id,
                    'metric': metric.id,
                    'operator': operator.title,
                    'value': value,
                    'action': actionToTake
                }).success(function(data) {
                    info('Successfully created rule ', data.id);
                    that.set('creationPending', false);
                    var rule = Rule.create({
                        'id': data.id,
                        'value': value,
                        'metric': metric,
                        'machine': machine,
                        'operator': operator,
                        'maxValue': data.max_value,
                        'actionToTake': actionToTake,
                    });
                    that.pushObject(rule);
                    that.redrawRules();
                }).error(function(message) {
                    Mist.notificationController.notify('Error while creating rule: ' + message);
                    that.set('creationPending', false);
                });
            },

            deleteRule: function (rule) {
                var that = this;
                rule.set('pendingAction', true);
                Mist.ajax.DELETE('/rules/' + rule.id, {
                }).success(function(){
                    Mist.rulesController.removeObject(rule);
                    Mist.rulesController.redrawRules();
                }).error(function(message) {
                    Mist.notificationController.notify('Error while deleting rule: ' + message);
                    rule.set('pendingAction', false);
                });
            },

            updateRule: function(id, metric, operator, value, actionToTake, command) {

                var rule = this.getRuleById(id);

                if (!rule) {
                    return false;
                }

                // Make sure parameters are not null
                if (!value) { value = rule.value; }
                if (!metric) { metric = rule.metric.id; }
                if (!command) { command = rule.command; }
                if (!operator) { operator = rule.operator; }
                if (!actionToTake) { actionToTake = rule.actionToTake; }

                // Check if anything changed
                if (value == rule.value &&
                    metric == rule.metric.id &&
                    command == rule.command &&
                    actionToTake == rule.actionToTake &&
                    operator.title == rule.operator.title ) {
                        return false;
                }

                var that = this;
                rule.set('pendingAction', true);
                Mist.ajax.POST('/rules', {
                    'id': id,
                    'value': value,
                    'metric': metric,
                    'command': command,
                    'operator': operator.title,
                    'action': actionToTake,
                }).success(function(data) {
                    info('Successfully updated rule ', id);
                    rule.set('pendingAction', false);
                    rule.set('value', value);
                    rule.set('metric', Mist.metricsController.getMetric(metric));
                    rule.set('command', command);
                    rule.set('operator', operator);
                    rule.set('actionToTake', actionToTake);

                    var maxvalue = parseInt(rule.maxValue);
                    var curvalue = parseInt(rule.value);
                    if (curvalue > maxvalue) {
                        rule.set('value', maxvalue);
                    }
                }).error(function(message) {
                    Mist.notificationController.notify('Error while updating rule: ' + message);
                    rule.set('pendingAction', false);
                });
            },

            setSliderEventHandlers: function() {
                function showSlider(event) {
                    var rule_id = $(event.currentTarget).parent().attr('id');
                    var rule = Mist.rulesController.getRuleById(rule_id);
                    if (rule.metric.hasRange) {
                        $(event.currentTarget).addClass('open');
                        $(event.currentTarget).find('.ui-slider-track').fadeIn(100);
                    }
                }
                function hideSlider(event) {
                    $(event.currentTarget).find('.ui-slider-track').fadeOut(100);
                    $(event.currentTarget).find('.ui-slider').removeClass('open');
                }
                $('.rules-container .ui-slider').on('tap', showSlider);
                $('.rules-container .ui-slider').on('click', showSlider);
                $('.rules-container .ui-slider').on('mouseover', showSlider);
                $('#single-machine').on('tap', hideSlider);
                $('.rules-container .rule-box').on('mouseleave', hideSlider);
            },

            removeSliderEventHandlers: function() {
                $('.rules-container .ui-slider').off('tap');
                $('.rules-container .ui-slider').off('click');
                $('.rules-container .ui-slider').off('mouseover');
                $('#single-machine').off('tap');
                $('.rules-container .rule-box').off('mouseleave');
            },

            redrawRules: function() {
                var that = this;
                Ember.run.next(function() {
                    that.removeSliderEventHandlers();
                    $('.rule-box').trigger('create');
                    that.setSliderEventHandlers();
                });
            },
        });
    }
);
<|endoftext|>


<commit_before>// mouseevent

function start() {
	document.onclick = mouseClicked;
	if(ns){document.captureEvents(Event.CLICK);	}
}

//------------------------------------------
// global variables and global functions
// m.schleich 03.01.2000
//------------------------------------------
var shown = false;
var letztelyr='null';
var x=0;
var y=0;

// parameter for the kontextmenu
var kontextparam;

// which operation is clicked
var DO_LOCK=1;
var DO_LOCKUSER=2;
var DO_UNLOCK=3;

var DO_COPY=4;
var DO_COPYFOLDER=42;
var DO_MOVE=5;
var DO_RENAME=6;
var DO_DELETE=7;

var DO_CHOWN=8;
var DO_CHGRP=9;
var DO_CHMOD=10;
var DO_CHTYPE=11;
var DO_META=12;
var DO_METAVIEW=13;

var DO_EDIT=14;
var DO_HTMLEDIT=15;
var DO_VIEW=16;
var DO_EXPORT=17;

var DO_TEMPLATEEDIT=18;
var DO_DATAEDIT=19;

var DO_EDITDOC=20;
var DO_ATE=21;
var DO_MAILEDIT=22;
var DO_NEWSEDIT=23;

var DO_COPYF=30;
var DO_MOVEF=31;
var DO_RENAMEF=32;
var DO_DELETEF=33;

var DO_HISTORY=40;
var DO_HISTVIEW=41;
//=======================================
var DO_PUNLOCK=1;
var DO_PONLINELOCK=2;
var DO_PONLINE=3;
var DO_PDELETE=4

var DO_PTASK=10;
var DO_TASK=99;

var DO_PREACT=20;

// mousekoordinates on click
function mouseClicked(e)
{
		if (ie) {x=event.x; y=event.y;}
		if (ns) {x=e.x; y=e.y;}
		hidemenu(letztelyr);
}

//----------------------------------------
// function to display the filecontextmenu
// parameters:
// welche: layer name
// parameter: parameter for menu
// id: each link for layer must have a unic id number
// m.schleich 03.12.1999
//----------------------------------------
function showkontext(welche, parameter, id)
{
	// set the kontextparameter
	kontextparam = parameter.replace(/\//g, "%2F");

	if(welche!='')
	{

	if (!shown || id!=altid)
	{

		if(y >= (screen.availHeight/2))
		{

			if(ie)lyrheight=checklyrheight(welche);

			if(ns)lyrheight=document.layers[welche].clip.height;

			lyrheight='-'+lyrheight;
			eval(ypos_01+welche+ypos_02+'y'+yoffset+lyrheight);
		}
		else
		{
			lyrheight='-0';
		}
		eval(xpos_01+welche+xpos_02+'x'+xoffset);
		eval(ypos_01+welche+ypos_02+'y'+yoffset+lyrheight);

		hidemenu(letztelyr);
		eval(layerzeigen_01+welche+layerzeigen_02);

		shown = true;
	}
	else
	{
		hidemenu(letztelyr);
		shown = false;
	}
	letztelyr=welche;
	altid=id;
	}
}

// hides the file context (layer)
function hidemenu(welche)
{
	if(welche!='null')
	{
		eval(layerverstecken_01+welche+layerverstecken_02);
		//shown=false;
	}
	else
	{
		return;
	}
}

function checklyrheight(welche)
{
	switch(welche)
	     {
	       case 'plain':
	       	{
	         return 220;
	         break;
	       	}
			case 'plainlock':
	     	{
	         return 220;
	         break;
	       	}
			case 'plainlockuser':
			{
			 return 220;
			 break;
	       	}
			case 'pic':
	     	{
	         return 220;
	         break;
	       	}
	       case 'online_p':
	       	{
	         return 81;
	         break;
	        }
			default:
			{
			 return 220;
			 break;
	        }
        }

}

// which action on layer is clicked
function doAction(action) {
	hidemenu(letztelyr);
	var encLasturl = simpleEscape(location.href);

	switch(action)	{
		case 1: {
			location.href='lock.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 2:	{
			location.href='lockchange.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 3: {
			location.href='unlock.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 4: {
			location.href='copy.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 5: {
			location.href='move.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 6: {
			location.href='rename.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 7: {
			location.href='delete.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 8: {
			location.href='chown.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 9: {
			location.href='chgrp.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 10: {
			location.href='chmod.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 11: {
			location.href='chtype.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 12: {
		    location.href='property.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		}
		case 13:
		{
			location.href='explorer_files_metashow.html';
			break;
		} case 14: {
			top.location.href='edit_text.html?file='+ kontextparam;
			break;
		} case 15: {
			top.location.href='edit_html.html?file='+ kontextparam;
			break;
		}
		case 16:
		{
			top.location.href='edit_view.html';
			break;
		}
	    case 18:
		{
		    // Template Editor
		    top.location.href='edit_page.html?file='+ kontextparam;
			break;
		}

	    case 23:
		{
		    // News Editor
		    top.body.location.href='news_edit.html?action=edit&lasturl=' + top.body.location.href + '&file='+ kontextparam + '&initial=true';
			break;
		}

		case 30:
		{
			location.href='explorer_files_copyf.html';
			break;
		}
		case 31:
		{
			location.href='explorer_files_movef.html';
			break;
		}
		case 32:
		{
			location.href='explorer_files_renamef.html';
			break;
		}
		case 33:
		{
			location.href='explorer_files_deletef.html';
			break;
		} case 40:{
		    location.href='history.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		}
		case 41:
		{
			location.href='explorer_files_historyshow.html';
			break;
		} case 42: {
			location.href='copy.html?file='+ kontextparam;
			break;
		}
	}
}

function doPAction(action) // which action on layer Project is clicked
{
	hidemenu(letztelyr);

	switch(action)
	{
		case 1:
		{
			location.href='administration_content_lockchange.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 2:
		{
			confirm('Sind Sie sicher, dass das Projekt verffentlicht werden soll? \nEs sind noch Dateien in Bearbeitung.');
			break;
		}
		case 3:
		{
			location.href='administration_content_publish_project.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 4:
		{
			location.href='administration_content_delete_project.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 10:
		{
			location.href='tasks_content_new_forproject.html';
			break;
		}
		case 20:
		{
			location.href='administration_content_projecthistory_react.html';
			break;
		}
		case 99:
		{
			location.href='tasks_content_new_forfile.html';
			break;
		}
	}
}
<commit_msg>wrong lasturl parameter corrected<commit_after>// mouseevent

function start() {
	document.onclick = mouseClicked;
	if(ns){document.captureEvents(Event.CLICK);	}
}

//------------------------------------------
// global variables and global functions
// m.schleich 03.01.2000
//------------------------------------------
var shown = false;
var letztelyr='null';
var x=0;
var y=0;

// parameter for the kontextmenu
var kontextparam;

// which operation is clicked
var DO_LOCK=1;
var DO_LOCKUSER=2;
var DO_UNLOCK=3;

var DO_COPY=4;
var DO_COPYFOLDER=42;
var DO_MOVE=5;
var DO_RENAME=6;
var DO_DELETE=7;

var DO_CHOWN=8;
var DO_CHGRP=9;
var DO_CHMOD=10;
var DO_CHTYPE=11;
var DO_META=12;
var DO_METAVIEW=13;

var DO_EDIT=14;
var DO_HTMLEDIT=15;
var DO_VIEW=16;
var DO_EXPORT=17;

var DO_TEMPLATEEDIT=18;
var DO_DATAEDIT=19;

var DO_EDITDOC=20;
var DO_ATE=21;
var DO_MAILEDIT=22;
var DO_NEWSEDIT=23;

var DO_COPYF=30;
var DO_MOVEF=31;
var DO_RENAMEF=32;
var DO_DELETEF=33;

var DO_HISTORY=40;
var DO_HISTVIEW=41;
//=======================================
var DO_PUNLOCK=1;
var DO_PONLINELOCK=2;
var DO_PONLINE=3;
var DO_PDELETE=4

var DO_PTASK=10;
var DO_TASK=99;

var DO_PREACT=20;

// mousekoordinates on click
function mouseClicked(e)
{
		if (ie) {x=event.x; y=event.y;}
		if (ns) {x=e.x; y=e.y;}
		hidemenu(letztelyr);
}

//----------------------------------------
// function to display the filecontextmenu
// parameters:
// welche: layer name
// parameter: parameter for menu
// id: each link for layer must have a unic id number
// m.schleich 03.12.1999
//----------------------------------------
function showkontext(welche, parameter, id)
{
	// set the kontextparameter
	kontextparam = parameter.replace(/\//g, "%2F");

	if(welche!='')
	{

	if (!shown || id!=altid)
	{

		if(y >= (screen.availHeight/2))
		{

			if(ie)lyrheight=checklyrheight(welche);

			if(ns)lyrheight=document.layers[welche].clip.height;

			lyrheight='-'+lyrheight;
			eval(ypos_01+welche+ypos_02+'y'+yoffset+lyrheight);
		}
		else
		{
			lyrheight='-0';
		}
		eval(xpos_01+welche+xpos_02+'x'+xoffset);
		eval(ypos_01+welche+ypos_02+'y'+yoffset+lyrheight);

		hidemenu(letztelyr);
		eval(layerzeigen_01+welche+layerzeigen_02);

		shown = true;
	}
	else
	{
		hidemenu(letztelyr);
		shown = false;
	}
	letztelyr=welche;
	altid=id;
	}
}

// hides the file context (layer)
function hidemenu(welche)
{
	if(welche!='null')
	{
		eval(layerverstecken_01+welche+layerverstecken_02);
		//shown=false;
	}
	else
	{
		return;
	}
}

function checklyrheight(welche)
{
	switch(welche)
	     {
	       case 'plain':
	       	{
	         return 220;
	         break;
	       	}
			case 'plainlock':
	     	{
	         return 220;
	         break;
	       	}
			case 'plainlockuser':
			{
			 return 220;
			 break;
	       	}
			case 'pic':
	     	{
	         return 220;
	         break;
	       	}
	       case 'online_p':
	       	{
	         return 81;
	         break;
	        }
			default:
			{
			 return 220;
			 break;
	        }
        }

}

// which action on layer is clicked
function doAction(action) {
	hidemenu(letztelyr);
	var encLasturl = simpleEscape(location.href);

	switch(action)	{
		case 1: {
			location.href='lock.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 2:	{
			location.href='lockchange.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 3: {
			location.href='unlock.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 4: {
			location.href='copy.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 5: {
			location.href='move.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 6: {
			location.href='rename.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 7: {
			location.href='delete.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 8: {
			location.href='chown.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 9: {
			location.href='chgrp.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 10: {
			location.href='chmod.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 11: {
			location.href='chtype.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		} case 12: {
		    location.href='property.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		}
		case 13:
		{
			location.href='explorer_files_metashow.html';
			break;
		} case 14: {
			top.location.href='edit_text.html?file='+ kontextparam;
			break;
		} case 15: {
			top.location.href='edit_html.html?file='+ kontextparam;
			break;
		}
		case 16:
		{
			top.location.href='edit_view.html';
			break;
		}
	    case 18:
		{
		    // Template Editor
		    top.location.href='edit_page.html?file='+ kontextparam;
			break;
		}

	    case 23:
		{
		    // News Editor
		    top.body.location.href='news_edit.html?action=edit&lasturl=' + simpleEscape(top.body.location.href) + '&file='+ kontextparam + '&initial=true';
			break;
		}

		case 30:
		{
			location.href='explorer_files_copyf.html';
			break;
		}
		case 31:
		{
			location.href='explorer_files_movef.html';
			break;
		}
		case 32:
		{
			location.href='explorer_files_renamef.html';
			break;
		}
		case 33:
		{
			location.href='explorer_files_deletef.html';
			break;
		} case 40:{
		    location.href='history.html?lasturl=' + encLasturl + '&file='+ kontextparam + '&initial=true';
			break;
		}
		case 41:
		{
			location.href='explorer_files_historyshow.html';
			break;
		} case 42: {
			location.href='copy.html?file='+ kontextparam;
			break;
		}
	}
}

function doPAction(action) // which action on layer Project is clicked
{
	hidemenu(letztelyr);

	switch(action)
	{
		case 1:
		{
			location.href='administration_content_lockchange.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 2:
		{
			confirm('Sind Sie sicher, dass das Projekt verffentlicht werden soll? \nEs sind noch Dateien in Bearbeitung.');
			break;
		}
		case 3:
		{
			location.href='administration_content_publish_project.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 4:
		{
			location.href='administration_content_delete_project.html?projectid=' + kontextparam+ '&initial=true';
			break;
		}
		case 10:
		{
			location.href='tasks_content_new_forproject.html';
			break;
		}
		case 20:
		{
			location.href='administration_content_projecthistory_react.html';
			break;
		}
		case 99:
		{
			location.href='tasks_content_new_forfile.html';
			break;
		}
	}
}
<|endoftext|>


<commit_before>(() => {
    'use strict';

    const analytics = require('@waves/event-sender');
    const ds = require('data-service');
    const { libs } = require('@waves/waves-transactions');
    const { base58Decode } = libs.crypto;

    /**
     * @param {typeof Base} Base
     * @param {ng.IScope} $scope
     * @param {*} $state
     * @param {MultiAccount} multiAccount
     * @param {User} user
     * @return {SignUpCtrl}
     */
    const controller = function (Base, $scope, $state, multiAccount, user) {

        class MigrateCtrl extends Base {

            migrateForm = null;
            migratePassword = '';
            activeStep = 0;
            userListLocked = [];
            userListUnlocked = [];
            userToMigrate = null;
            showPasswordError = false;

            constructor() {
                super($scope);

                Promise.all([
                    user.getFilteredUserList(),
                    user.getMultiAccountUsers()
                ]).then(([userList, multiAccountUsers]) => {
                    this.activeStep = userList && userList.length ? 0 : 1;
                    this.userListLocked = userList;
                    this.userListUnlocked = multiAccountUsers;

                    this.migrateUsersWithoutPassword(userList.filter(lockedUser => (
                        lockedUser.userType !== 'seed' &&
                        lockedUser.userType !== 'privateKey'
                    )));

                    const { id } = $state.params;

                    if (id) {
                        const lockedUserByHash = this.userListLocked.find(lockedUser => (
                            multiAccount.hash(lockedUser.address) === id
                        ));

                        if (lockedUserByHash) {
                            this.startMigrate(lockedUserByHash);
                        }
                    }
                });
            }

            nextStep() {
                this.activeStep += 1;
            }

            prevStep() {
                const { id } = $state.params;

                if (id) {
                    user.getMultiAccountUsers().then((mUsers = []) => {
                        const userToLogin = mUsers.find(mUser => (
                            multiAccount.hash(mUser.address) === id
                        ));

                        if (userToLogin) {
                            user.login(userToLogin);
                        }

                        $state.go(user.getActiveState('wallet'));
                    });
                } else {
                    this.activeStep -= 1;
                }
            }

            startMigrate(userToMigrate) {
                this.userToMigrate = userToMigrate;
                this.nextStep();
            }

            migrateUser(userData) {
                return multiAccount.addUser(userData)
                    .then(data => Promise.all([
                        user.saveMultiAccount(data),
                        user.migrateUser(this.userToMigrate, data.userHash)
                    ]))
                    .then(() => user.getMultiAccountUsers())
                    .then(multiAccountUsers => {
                        this.userListLocked = this.userListLocked.filter(lockedUser => (
                            lockedUser.address !== this.userToMigrate.address
                        ));

                        this.userListUnlocked = multiAccountUsers;
                        this.userToMigrate = null;
                    });
            }

            async migrateUsersWithoutPassword(usersWithoutPassword) {
                for (const legacyUser of usersWithoutPassword) {
                    const { userType, id, publicKey, address } = legacyUser;
                    const networkByte = base58Decode(address)[1];

                    this.userToMigrate = legacyUser;

                    // eslint-disable-next-line no-await-in-loop
                    await this.migrateUser({
                        userType,
                        networkByte,
                        id,
                        publicKey
                    });
                }
            }

            onSubmit() {
                try {
                    this._hidePasswordError();

                    const { userType, id, publicKey, address } = this.userToMigrate;
                    const networkByte = base58Decode(address)[1];
                    const seed = userType === 'seed' ?
                        ds.Seed.decryptSeedPhrase(
                            this.userToMigrate.encryptedSeed,
                            this.migratePassword
                        ) :
                        undefined;
                    const privateKey = userType === 'privateKey' ?
                        ds.Seed.decryptSeedPhrase(
                            this.userToMigrate.encryptedPrivateKey,
                            this.migratePassword
                        ) :
                        undefined;

                    this.migrateUser({
                        userType,
                        networkByte,
                        seed,
                        id,
                        privateKey,
                        publicKey
                    }).then(() => {
                        this.migratePassword = '';
                        this.prevStep();
                        analytics.send({ name: 'Successfully Unlocked' });
                    });
                } catch (e) {
                    this._showPasswordError();
                    analytics.send({ name: 'Failed Unlock' });
                }
            }

            finish() {
                const [firstUser] = this.userListUnlocked;

                user.login(firstUser).then(() => {
                    $state.go(user.getActiveState('wallet'));
                });
            }

            _showPasswordError() {
                this.migratePassword = '';
                this.showPasswordError = true;
            }

            _hidePasswordError() {
                this.showPasswordError = false;
            }

        }

        return new MigrateCtrl();
    };

    controller.$inject = ['Base', '$scope', '$state', 'multiAccount', 'user'];

    angular.module('app.migrate').controller('MigrateCtrl', controller);
})();
<commit_msg>DEXW-2177: check password<commit_after>(() => {
    'use strict';

    const analytics = require('@waves/event-sender');
    const ds = require('data-service');
    const { libs } = require('@waves/waves-transactions');
    const { base58Decode } = libs.crypto;

    /**
     * @param {typeof Base} Base
     * @param {ng.IScope} $scope
     * @param {*} $state
     * @param {MultiAccount} multiAccount
     * @param {User} user
     * @return {SignUpCtrl}
     */
    const controller = function (Base, $scope, $state, multiAccount, user) {

        class MigrateCtrl extends Base {

            migrateForm = null;
            migratePassword = '';
            activeStep = 0;
            userListLocked = [];
            userListUnlocked = [];
            userToMigrate = null;
            showPasswordError = false;

            constructor() {
                super($scope);

                Promise.all([
                    user.getFilteredUserList(),
                    user.getMultiAccountUsers()
                ]).then(([userList, multiAccountUsers]) => {
                    this.activeStep = userList && userList.length ? 0 : 1;
                    this.userListLocked = userList;
                    this.userListUnlocked = multiAccountUsers;

                    this.migrateUsersWithoutPassword(userList.filter(lockedUser => (
                        lockedUser.userType !== 'seed' &&
                        lockedUser.userType !== 'privateKey'
                    )));

                    const { id } = $state.params;

                    if (id) {
                        const lockedUserByHash = this.userListLocked.find(lockedUser => (
                            multiAccount.hash(lockedUser.address) === id
                        ));

                        if (lockedUserByHash) {
                            this.startMigrate(lockedUserByHash);
                        }
                    }
                });
            }

            nextStep() {
                this.activeStep += 1;
            }

            prevStep() {
                const { id } = $state.params;

                if (id) {
                    user.getMultiAccountUsers().then((mUsers = []) => {
                        const userToLogin = mUsers.find(mUser => (
                            multiAccount.hash(mUser.address) === id
                        ));

                        if (userToLogin) {
                            user.login(userToLogin);
                        }

                        $state.go(user.getActiveState('wallet'));
                    });
                } else {
                    this.activeStep -= 1;
                }
            }

            startMigrate(userToMigrate) {
                this.userToMigrate = userToMigrate;
                this.nextStep();
            }

            migrateUser(userData) {
                return multiAccount.addUser(userData)
                    .then(data => Promise.all([
                        user.saveMultiAccount(data),
                        user.migrateUser(this.userToMigrate, data.userHash)
                    ]))
                    .then(() => user.getMultiAccountUsers())
                    .then(multiAccountUsers => {
                        this.userListLocked = this.userListLocked.filter(lockedUser => (
                            lockedUser.address !== this.userToMigrate.address
                        ));

                        this.userListUnlocked = multiAccountUsers;
                        this.userToMigrate = null;
                    });
            }

            async migrateUsersWithoutPassword(usersWithoutPassword) {
                for (const legacyUser of usersWithoutPassword) {
                    const { userType, id, publicKey, address } = legacyUser;
                    const networkByte = base58Decode(address)[1];

                    this.userToMigrate = legacyUser;

                    // eslint-disable-next-line no-await-in-loop
                    await this.migrateUser({
                        userType,
                        networkByte,
                        id,
                        publicKey
                    });
                }
            }

            checkSeed(seed, publicKey) {
                return publicKey === libs.crypto.publicKey(seed);
            }

            checkPK(privateKey, publicKey) {
                return libs.crypto.publicKey({ privateKey }) === publicKey;
            }

            onSubmit() {
                try {
                    this._hidePasswordError();

                    const { id, publicKey, address } = this.userToMigrate;
                    const userType = userType || 'seed';
                    const networkByte = base58Decode(address)[1];
                    const seed = userType === 'seed' ?
                        ds.Seed.decryptSeedPhrase(
                            this.userToMigrate.encryptedSeed,
                            this.migratePassword
                        ) :
                        undefined;
                    const privateKey = userType === 'privateKey' ?
                        ds.Seed.decryptSeedPhrase(
                            this.userToMigrate.encryptedPrivateKey,
                            this.migratePassword
                        ) :
                        undefined;

                    if (seed && !this.checkSeed(seed, publicKey)) {
                        throw new Error('Incorrect seed');
                    }

                    if (privateKey && !this.checkPK(privateKey, publicKey)) {
                        throw new Error('Incorrect private key');
                    }

                    this.migrateUser({
                        userType,
                        networkByte,
                        seed,
                        id,
                        privateKey,
                        publicKey
                    }).then(() => {
                        this.migratePassword = '';
                        this.prevStep();
                        analytics.send({ name: 'Successfully Unlocked' });
                    });
                } catch (e) {
                    this._showPasswordError();
                    analytics.send({ name: 'Failed Unlock' });
                }
            }

            finish() {
                const [firstUser] = this.userListUnlocked;

                user.login(firstUser).then(() => {
                    $state.go(user.getActiveState('wallet'));
                });
            }

            _showPasswordError() {
                this.migratePassword = '';
                this.showPasswordError = true;
            }

            _hidePasswordError() {
                this.showPasswordError = false;
            }

        }

        return new MigrateCtrl();
    };

    controller.$inject = ['Base', '$scope', '$state', 'multiAccount', 'user'];

    angular.module('app.migrate').controller('MigrateCtrl', controller);
})();
<|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.flat.DropDownList');

goog.require('org.apache.flex.core.ListBase');
goog.require('org.apache.flex.html.beads.models.ArraySelectionModel');

/**
 * @constructor
 * @extends {org.apache.flex.core.ListBase}
 */
org.apache.flex.flat.DropDownList = function() {
  org.apache.flex.flat.DropDownList.base(this, 'constructor');
  this.model = new org.apache.flex.html.beads.models.ArraySelectionModel();
};
goog.inherits(org.apache.flex.flat.DropDownList,
    org.apache.flex.core.ListBase);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.flat.DropDownList.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'DropDownList',
                qName: 'org.apache.flex.flat.DropDownList'}] };

/**
 * @override
 */
org.apache.flex.flat.DropDownList.prototype.createElement =
    function() {
  var button, input;

  this.element = document.createElement('div');

  this.button = button = document.createElement('button');
  button.className = 'dropdown-toggle-open-btn';
  goog.events.listen(button, 'click', goog.bind(this.buttonClicked, this));
  this.element.appendChild(button);

  var caret = document.createElement('span');
  caret.className = 'dropdown-caret';

  this.positioner = this.element;
  this.positioner.style.position = 'relative';

  // add a click handler so that a click outside of the combo box can
  // dismiss the pop-up should it be visible.
  goog.events.listen(document, 'click',
      goog.bind(this.dismissPopup, this));

  button.flexjs_wrapper = this;
  this.element.flexjs_wrapper = this;
  caret.flexjs_wrapper = this;

  return this.element;
};

/**
 * @export
 * @param {Object} event The event.
 */
org.apache.flex.flat.DropDownList.prototype.selectChanged =
    function(event) {
  var select;

  select = event.target;

  this.selectedIndex = parseInt(select.id, 10);

  this.menu.parentNode.removeChild(this.menu);
  this.menu = null;

  this.dispatchEvent('change');
};

/**
 * @export
 * @param {Object=} opt_event The event.
 */
org.apache.flex.flat.DropDownList.prototype.dismissPopup =
    function(opt_event) {
  // remove the popup if it already exists
  if (this.menu) {
    this.menu.parentNode.removeChild(this.menu);
    this.menu = null;
  }
};

/**
 * @export
 * @param {Object} event The event.
 */
org.apache.flex.flat.DropDownList.prototype.buttonClicked =
    function(event) {
  /**
   * @type {Array.<string>}
   */
  var dp;
  var i, button, left, n, opt, opts, pn, popup, select, si, top, width;

  event.stopPropagation();

  if (this.popup) {
    this.dismissPopup();

    return;
  }

  button = this.element.childNodes.item(0);

  pn = this.element;
  top = pn.offsetTop + button.offsetHeight;
  left = pn.offsetLeft;
  width = pn.offsetWidth;

  /*
  popup = document.createElement('div');
  popup.className = 'dropdown-menu';
  popup.id = 'test';
  popup.style.position = 'absolute';
  popup.style.top = top.toString() + 'px';
  popup.style.left = left.toString() + 'px';
  popup.style.width = width.toString() + 'px';
  popup.style.margin = '0px auto';
  popup.style.padding = '0px';
  popup.style.zIndex = '10000';
  */

  this.menu = select = document.createElement('ul');
  select.style.width = width.toString() + 'px';
  goog.events.listen(select, 'click', goog.bind(this.selectChanged, this));
  select.className = 'dropdown-menu';

  var lf = this.labelField;
  dp = /** @type {Array.<string>} */ (this.dataProvider);
  n = dp.length;
  for (i = 0; i < n; i++) {
    opt = document.createElement('li');
    opt.style.backgroundColor = 'transparent';
    var ir = document.createElement('a');
    if (lf)
      ir.innerHTML = dp[i][lf];
    else
      ir.innerHTML = dp[i];
    ir.id = i.toString();
    if (i == this.selectedIndex)
      ir.className = 'dropdown-menu-item-renderer-selected';
    else
      ir.className = 'dropdown-menu-item-renderer';
    opt.appendChild(ir);
    select.appendChild(opt);
  }

  this.element.appendChild(select);
};

Object.defineProperties(org.apache.flex.flat.DropDownList.prototype, {
    dataProvider: {
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.dataProvider;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            var dp, i, n, opt;

            this.model.dataProvider = value;
        }
    },
    /** @export */
    labelField: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.labelField;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.labelField = value;
        }
    },
    /** @export */
    selectedIndex: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.selectedIndex;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.selectedIndex = value;
            var lf = this.labelField;
            if (lf)
              this.button.innerHTML = this.selectedItem[lf] + '';
            else
              this.button.innerHTML = this.selectedItem + '';
        }
    },
    /** @export */
    selectedItem: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.selectedItem;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.selectedItem = value;
            var lf = this.labelField;
            if (lf)
              this.button.innerHTML = this.selectedItem[lf] + '';
            else
              this.button.innerHTML = this.selectedItem + '';
         }
    }
});
<commit_msg>get DDL to respond to outer class styles<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.flat.DropDownList');

goog.require('org.apache.flex.core.ListBase');
goog.require('org.apache.flex.html.beads.models.ArraySelectionModel');
goog.require('org.apache.flex.utils.Language');

/**
 * @constructor
 * @extends {org.apache.flex.core.ListBase}
 */
org.apache.flex.flat.DropDownList = function() {
  org.apache.flex.flat.DropDownList.base(this, 'constructor');
  this.model = new org.apache.flex.html.beads.models.ArraySelectionModel();
};
goog.inherits(org.apache.flex.flat.DropDownList,
    org.apache.flex.core.ListBase);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.flat.DropDownList.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'DropDownList',
                qName: 'org.apache.flex.flat.DropDownList'}] };

/**
 * @override
 */
org.apache.flex.flat.DropDownList.prototype.createElement =
    function() {
  var button, input;

  this.element = document.createElement('div');

  this.button = button = document.createElement('button');
  button.className = 'dropdown-toggle-open-btn';
  if (this.className)
    button.className += ' ' + this.className;
  goog.events.listen(button, 'click', goog.bind(this.buttonClicked, this));
  this.element.appendChild(button);

  var caret = document.createElement('span');
  caret.className = 'dropdown-caret';

  this.positioner = this.element;
  this.positioner.style.position = 'relative';

  // add a click handler so that a click outside of the combo box can
  // dismiss the pop-up should it be visible.
  goog.events.listen(document, 'click',
      goog.bind(this.dismissPopup, this));

  button.flexjs_wrapper = this;
  this.element.flexjs_wrapper = this;
  caret.flexjs_wrapper = this;

  return this.element;
};

/**
 * @export
 * @param {Object} event The event.
 */
org.apache.flex.flat.DropDownList.prototype.selectChanged =
    function(event) {
  var select;

  select = event.target;

  this.selectedIndex = parseInt(select.id, 10);

  this.menu.parentNode.removeChild(this.menu);
  this.menu = null;

  this.dispatchEvent('change');
};

/**
 * @export
 * @param {Object=} opt_event The event.
 */
org.apache.flex.flat.DropDownList.prototype.dismissPopup =
    function(opt_event) {
  // remove the popup if it already exists
  if (this.menu) {
    this.menu.parentNode.removeChild(this.menu);
    this.menu = null;
  }
};

/**
 * @export
 * @param {Object} event The event.
 */
org.apache.flex.flat.DropDownList.prototype.buttonClicked =
    function(event) {
  /**
   * @type {Array.<string>}
   */
  var dp;
  var i, button, left, n, opt, opts, pn, popup, select, si, top, width;

  event.stopPropagation();

  if (this.popup) {
    this.dismissPopup();

    return;
  }

  button = this.element.childNodes.item(0);

  pn = this.element;
  top = pn.offsetTop + button.offsetHeight;
  left = pn.offsetLeft;
  width = pn.offsetWidth;

  /*
  popup = document.createElement('div');
  popup.className = 'dropdown-menu';
  popup.id = 'test';
  popup.style.position = 'absolute';
  popup.style.top = top.toString() + 'px';
  popup.style.left = left.toString() + 'px';
  popup.style.width = width.toString() + 'px';
  popup.style.margin = '0px auto';
  popup.style.padding = '0px';
  popup.style.zIndex = '10000';
  */

  this.menu = select = document.createElement('ul');
  var el = /** @type {Element} */ (this.element);
  var cv = window.getComputedStyle(el);
  select.style.width = cv.width;
  goog.events.listen(select, 'click', goog.bind(this.selectChanged, this));
  select.className = 'dropdown-menu';

  var lf = this.labelField;
  dp = /** @type {Array.<string>} */ (this.dataProvider);
  n = dp.length;
  for (i = 0; i < n; i++) {
    opt = document.createElement('li');
    opt.style.backgroundColor = 'transparent';
    var ir = document.createElement('a');
    if (lf)
      ir.innerHTML = dp[i][lf];
    else
      ir.innerHTML = dp[i];
    ir.id = i.toString();
    if (i == this.selectedIndex)
      ir.className = 'dropdown-menu-item-renderer-selected';
    else
      ir.className = 'dropdown-menu-item-renderer';
    opt.appendChild(ir);
    select.appendChild(opt);
  }

  this.element.appendChild(select);
};

Object.defineProperties(org.apache.flex.flat.DropDownList.prototype, {
    /** @export */
    className: {
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return org.apache.flex.utils.Language.superGetter(org.apache.flex.flat.DropDownList, this, 'className');
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            org.apache.flex.utils.Language.superSetter(org.apache.flex.flat.DropDownList, this, 'className', value);
            if (this.button) {
              this.button.className = this.typeNames ?
                      value + ' ' + 'dropdown-toggle-open-btn' + ' ' + this.typeNames :
                      value + ' ' + 'dropdown-toggle-open-btn';
            }
        }
    },
    dataProvider: {
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.dataProvider;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            var dp, i, n, opt;

            this.model.dataProvider = value;
        }
    },
    /** @export */
    labelField: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.labelField;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.labelField = value;
        }
    },
    /** @export */
    selectedIndex: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.selectedIndex;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.selectedIndex = value;
            var lf = this.labelField;
            if (lf)
              this.button.innerHTML = this.selectedItem[lf] + '';
            else
              this.button.innerHTML = this.selectedItem + '';
        }
    },
    /** @export */
    selectedItem: {
        // TODO: (aharui) copied from ListBase because you
        // can't just override the setter in a defineProps
        // structure.
        /** @this {org.apache.flex.flat.DropDownList} */
        get: function() {
            return this.model.selectedItem;
        },
        /** @this {org.apache.flex.flat.DropDownList} */
        set: function(value) {
            this.model.selectedItem = value;
            var lf = this.labelField;
            if (lf)
              this.button.innerHTML = this.selectedItem[lf] + '';
            else
              this.button.innerHTML = this.selectedItem + '';
         }
    }
});
<|endoftext|>


<commit_before>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

window.onerror = alert;

function resultInit() {
	document.getElementById("result").innerHTML = "";
}

function resultAppend(element) {
	return document.getElementById("result").appendChild(element);
}

function resultAppendText(text) {
	element = document.createElement("div");
	element.textContent = text;
	return resultAppend(element);
}

resultAppendText("Initializing");

function fetchJson(input, init) {
	return fetch(input, init).then(function(response) {
		return response.json();
	}, alert);
}

const token = fetchJson("https://api.twitter.com/oauth2/token", {
	method: "POST",
	headers: {
		"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
		"Authorization": CREDENTIAL
	}, body: "grant_type=client_credentials" });

token.catch(alert);

const open = window.indexedDB.open("tweets", 1);

open.onerror = function(event) {
	alert(event.target.error);
}

function getIteratorOfString(string) {
	function next() {
		if (this.count >= this.value.length) {
			return { done: true };
		} else {
			const value = this.value[this.count];
			this.count++;

			return { done: false, value: value };
		}
	}

	return { next: next, count: 0, value: string };
}

function getTypeOfQuery(string) {
	if (string.length <= 0)
		return null;
	else if (string == "OR")
		return "OPCODE";
	else
		return "STRING";
}

function parse(iterator, block) {
	const queries = [];
	var word;

	function continueWord(from) {
		iterator = getIteratorOfString(from + iterator.value);
	}

	function initializeWord() {
		word = "";
	}

	function finalizeWord() {
		const type = getTypeOfQuery(word);
		if (type)
			queries.push({ type: type, value: word });
	}

	initializeWord();
	while (true) {
		var result = iterator.next();
		if (result.done || result.value == ")")
			break;

		switch (result.value) {
		case " ":
			finalizeWord();
			initializeWord();
			break;

		case "\"":
			var quoted = "";
			while (true) {
				result = iterator.next();
				if (result.done || result.value == "\"")
					break;
				else
					quoted += result.value;
			}

			if (result.done) {
				word += "\"";
				continueWord(quoted);
			} else if (word.length > 0) {
				const query = { type: "STRING", value: word + quoted };
				queries.push(query);
				initializeWord();
			}

			break;

		case "(":
			if (word.length > 0) {
				word += result.value;
			} else {
				const query = { type: "BLOCK" };
				query.value = parse(iterator, true);
				if (query.value)
					queries.push(query);
			}

			break;

		case ")":
			if (block) {
				finalizeWord();
				return queries;
			} else {
				word += result.value;
				break;
			}

		case "-":
			if (word.length > 0)
				word += result.value;
			else
				queries.push({ type: "OPCODE", value: "NOT" });

			break;

		case "<":
		case "=":
		case ">":
			word += result.value;
			if (word.length > 1)
				break;

			op = result.value;
			result = iterator.next();
			if (result.done)
				break;

			if (result.value == '=') {
				op += value;
				result = iterator.next();
			}

			dateString = "";
			while (true) {
				if (result.done || result.value == " ")
					break;
				else
					dateString += result.value;

				result = iterator.next();
			}

			const date = new Date(dateString);
			if (!date) {
				continueWord(op[2] ?
					op[2] + dateString : dateString);

				break;
			}

			queries.push({ type: "RANGE", value: { op: op, date: date } });

			initializeWord();
			break;

		default:
			word += result.value;
			break;
		}
	}

	finalizeWord();
	return queries;
}

function matchRange(range, value) {
	const left = value.timestamp;
	const right = range.date;

	switch (range.op) {
	case "<":
		return left < right;

	case "<=":
		return left <= right;

	case "=":
	case "==":
		return left == right;

	case ">":
		return left > right;

	case ">=":
		return left >= right;

	default:
		return false;
	}
}

function matchString(string, value) {
	return value.text.toUpperCase().indexOf(string.toUpperCase()) >= 0;
}

function matchQuery(queries, value) {
	var r;
	var opcode = null;
	queries.some(function(query) {
		var cur;

		switch (query.type) {
		case "RANGE":
			cur = matchRange(query.value, value);
			break;

		case "STRING":
			cur = matchString(query.value, value);
			break;

		case "OPCODE":
			if (opcode) {
				r = false;
				return true;
			}

			opcode = query.value;
			break;

		case "BLOCK":
			cur = matchQuery(query.value, value);
			break;

		default:
			throw "Internal error: unexpected type";
		}

		if (cur == undefined)
			return;

		if (r == undefined) {
			switch (opcode) {
			case null:
				r = cur;
				break;

			case "OR":
				r = matchString(opcode, value) && cur;
				break;

			case "NOT":
				r = false;
				return true;

			default:
				throw "Internal error: unexpected opcode";
			}
		} else {
			switch (opcode) {
			case null:
				r = r && cur;
				break;

			case "OR":
				r = r || cur;
				break;

			case "NOT":
				r = r && !cur;
				break;

			default:
				throw "Internal error: unexpected opcode";
			}
		}
	});

	return r;
}

var last;

function getTweetOriginUserId(tweet) {
	return tweet.retweeted_status_user_id ?
		tweet.retweeted_status_user_id : tweet.user_id;
}

function chainShowTweets(users, tweets) {
	if (last &&
		document.body.scrollTop + document.documentElement.clientHeight
			< last.offsetTop + last.clientHeight)
	{
		return;
	}

	const tweet = tweets.pop();
	if (!tweet)
		return;

	const tweetOriginUserId = getTweetOriginUserId(tweet);

	if (tweet.html_expire < new Date())
		tweet.html = undefined;

	var oembed;
	if (!tweet.html) {
		oembed = fetchJson("https://api.twitter.com/1/statuses/oembed.json?omit_script=true&id="
			+ encodeURI(tweet.tweet_id), { method: "GET" });
	}

	const image = document.createElement("img");
	image.className = "image";
	image.setAttribute("src", users[tweetOriginUserId]);

	const text = document.createElement("span");
	text.className = "text";

	const imageClear = document.createElement("p");
	imageClear.className = "image-clear";

	const top = document.createElement("p");
	top.appendChild(image);
	top.appendChild(text);
	top.appendChild(imageClear);
	last = resultAppend(top);

	if (tweet.html) {
		text.innerHTML = tweet.html;
		window.onscroll();
	} else {
		oembed.then(function(oembedResponse) {
			if (oembedResponse.html) {
				text.innerHTML = oembedResponse.html;

				tweet.html_expire = new Date(Date.now() + oembedResponse.cache_age);
				tweet.html = oembedResponse.html;

				const transaction = open.result.transaction("tweets", "readwrite");
				transaction.onerror = open.onerror;
				transaction.objectStore("tweets").put(tweet)
					.onerror = open.onerror;
			} else {
				text.textContent = oembedResponse.error;
			}

			window.onscroll();
		}, alert);
	}
}

function chainInitializeResult(users, tweets) {
	resultInit();
	window.onscroll = function() {
		result.style.height = last.offsetTop + last.clientHeight + tweets.length * 40 + "px";
		chainShowTweets(users, tweets);
	}

	chainShowTweets(users, tweets);
}

function chainGetUserObjectsContainer(users, tweets, token) {
	const userObjects = [];

	function chainGetUserObjects(left) {
		const max = 100;

		if (left.length <= 0) {
			chainInitializeResult(userObjects, tweets);
			return;
		}

		const request = fetchJson("https://api.twitter.com/1.1/users/lookup.json?user_id="
					+ left.slice(-max).join(","), {
				method: "POST",
				headers: { "Authorization": "Bearer " + token }
			});

		if (left.length > max)
			left.length -= max;
		else
			left.length = 0;

		request.then(function(response) {
			for (user of response)
				userObjects[user.id] = user.profile_image_url_https;

			chainGetUserObjects(left);
		});
	}

	chainGetUserObjects(users);
}

open.onsuccess = function() {
	resultAppendText("Parsing queries");
	const queries = parse(getIteratorOfString(decodeURI(window.location.search.substring(1))), false);

	const progress = resultAppendText("Searching");
	const users = [];
	const tweets = [];

	token.then(function(response) {
		open.result.transaction("tweets", "readonly")
			.objectStore("tweets")
			.openCursor()
			.onsuccess = function(event)
		{
			const cursor = event.target.result;
			if (cursor) {
				const value = cursor.value;
				if (matchQuery(queries, value)) {
					tweets.push(value);

					const user = getTweetOriginUserId(value);
					if (users.indexOf(user) < 0)
						users.push(user);

					progress.textContent = "Searching (found "
						+ tweets.length
						+ " tweets)";
				}

				cursor.continue();
			} else {
				chainGetUserObjectsContainer(users, tweets,
					response.access_token);
			}
		}
	});
}

open.onupgradeneeded = function() {
	resultAppendText("Initialized");
	const progress = resultAppendText("Creating database");
	store = open.result.createObjectStore("tweets", { keyPath : "tweet_id" });
	const col = [ { title: "user_id", unique: false },
		{ title: "in_reply_to_status_id", unique: false },
		{ title: "in_reply_to_user_id", unique: false },
		{ title: "timestamp", unique: false },
		{ title: "source", unique: false },
		{ title: "text", unique: false },
		{ title: "retweeted_status_id", unique: false },
		{ title: "retweeted_status_user_id", unique: false },
		{ title: "retweeted_status_timestamp", unique: false },
		{ title: "expanded_urls", unique: false },
		{ title: "html_expire", unique: false },
		{ title: "html", unique: false }];
	for (var i = 0; i < col.length; i++) {
		store.createIndex(col[i].title, col[i].title, { unique: col[i].unique });
		progress.textContent = "Creating database ("
			+ Math.round(i / col.length) + "%, "
			+ i + "/" + col.length + ")";
	};

	function move() {
		window.location = "import.html";
	}

	token.then(move, move);
}
<commit_msg>search: Allow to search only retweets<commit_after>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

window.onerror = alert;

function resultInit() {
	document.getElementById("result").innerHTML = "";
}

function resultAppend(element) {
	return document.getElementById("result").appendChild(element);
}

function resultAppendText(text) {
	element = document.createElement("div");
	element.textContent = text;
	return resultAppend(element);
}

resultAppendText("Initializing");

function fetchJson(input, init) {
	return fetch(input, init).then(function(response) {
		return response.json();
	}, alert);
}

const token = fetchJson("https://api.twitter.com/oauth2/token", {
	method: "POST",
	headers: {
		"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
		"Authorization": CREDENTIAL
	}, body: "grant_type=client_credentials" });

token.catch(alert);

const open = window.indexedDB.open("tweets", 1);

open.onerror = function(event) {
	alert(event.target.error);
}

function getIteratorOfString(string) {
	function next() {
		if (this.count >= this.value.length) {
			return { done: true };
		} else {
			const value = this.value[this.count];
			this.count++;

			return { done: false, value: value };
		}
	}

	return { next: next, count: 0, value: string };
}

function getTypeOfQuery(string) {
	if (string.length <= 0)
		return null;
	else if (string == "OR")
		return "OPCODE";
	else if (string == "RT")
		return "SPECIAL";
	else
		return "STRING";
}

function parse(iterator, block) {
	const queries = [];
	var word;

	function continueWord(from) {
		iterator = getIteratorOfString(from + iterator.value);
	}

	function initializeWord() {
		word = "";
	}

	function finalizeWord() {
		const type = getTypeOfQuery(word);
		if (type)
			queries.push({ type: type, value: word });
	}

	initializeWord();
	while (true) {
		var result = iterator.next();
		if (result.done || result.value == ")")
			break;

		switch (result.value) {
		case " ":
			finalizeWord();
			initializeWord();
			break;

		case "\"":
			var quoted = "";
			while (true) {
				result = iterator.next();
				if (result.done || result.value == "\"")
					break;
				else
					quoted += result.value;
			}

			if (result.done) {
				word += "\"";
				continueWord(quoted);
			} else if (word.length > 0) {
				const query = { type: "STRING", value: word + quoted };
				queries.push(query);
				initializeWord();
			}

			break;

		case "(":
			if (word.length > 0) {
				word += result.value;
			} else {
				const query = { type: "BLOCK" };
				query.value = parse(iterator, true);
				if (query.value)
					queries.push(query);
			}

			break;

		case ")":
			if (block) {
				finalizeWord();
				return queries;
			} else {
				word += result.value;
				break;
			}

		case "-":
			if (word.length > 0)
				word += result.value;
			else
				queries.push({ type: "OPCODE", value: "NOT" });

			break;

		case "<":
		case "=":
		case ">":
			word += result.value;
			if (word.length > 1)
				break;

			op = result.value;
			result = iterator.next();
			if (result.done)
				break;

			if (result.value == '=') {
				op += value;
				result = iterator.next();
			}

			dateString = "";
			while (true) {
				if (result.done || result.value == " ")
					break;
				else
					dateString += result.value;

				result = iterator.next();
			}

			const date = new Date(dateString);
			if (!date) {
				continueWord(op[2] ?
					op[2] + dateString : dateString);

				break;
			}

			queries.push({ type: "RANGE", value: { op: op, date: date } });

			initializeWord();
			break;

		default:
			word += result.value;
			break;
		}
	}

	finalizeWord();
	return queries;
}

function matchRange(range, value) {
	const left = value.timestamp;
	const right = range.date;

	switch (range.op) {
	case "<":
		return left < right;

	case "<=":
		return left <= right;

	case "=":
	case "==":
		return left == right;

	case ">":
		return left > right;

	case ">=":
		return left >= right;

	default:
		return false;
	}
}

function matchSpecial(query, value) {
	switch (query) {
	case "RT":
		return value.retweeted_status_id ? true : false;

	default:
		throw "Internal error: unexpected query";
	}
}

function matchString(string, value) {
	return value.text.toUpperCase().indexOf(string.toUpperCase()) >= 0;
}

function matchQuery(queries, value) {
	var r;
	var opcode = null;
	queries.some(function(query) {
		var cur;

		switch (query.type) {
		case "RANGE":
			cur = matchRange(query.value, value);
			break;

		case "SPECIAL":
			cur = matchSpecial(query.value, value);
			break;

		case "STRING":
			cur = matchString(query.value, value);
			break;

		case "OPCODE":
			if (opcode) {
				r = false;
				return true;
			}

			opcode = query.value;
			break;

		case "BLOCK":
			cur = matchQuery(query.value, value);
			break;

		default:
			throw "Internal error: unexpected type";
		}

		if (cur == undefined)
			return;

		if (r == undefined) {
			switch (opcode) {
			case null:
				r = cur;
				break;

			case "OR":
				r = matchString(opcode, value) && cur;
				break;

			case "NOT":
				r = false;
				return true;

			default:
				throw "Internal error: unexpected opcode";
			}
		} else {
			switch (opcode) {
			case null:
				r = r && cur;
				break;

			case "OR":
				r = r || cur;
				break;

			case "NOT":
				r = r && !cur;
				break;

			default:
				throw "Internal error: unexpected opcode";
			}
		}
	});

	return r;
}

var last;

function getTweetOriginUserId(tweet) {
	return tweet.retweeted_status_user_id ?
		tweet.retweeted_status_user_id : tweet.user_id;
}

function chainShowTweets(users, tweets) {
	if (last &&
		document.body.scrollTop + document.documentElement.clientHeight
			< last.offsetTop + last.clientHeight)
	{
		return;
	}

	const tweet = tweets.pop();
	if (!tweet)
		return;

	const tweetOriginUserId = getTweetOriginUserId(tweet);

	if (tweet.html_expire < new Date())
		tweet.html = undefined;

	var oembed;
	if (!tweet.html) {
		oembed = fetchJson("https://api.twitter.com/1/statuses/oembed.json?omit_script=true&id="
			+ encodeURI(tweet.tweet_id), { method: "GET" });
	}

	const image = document.createElement("img");
	image.className = "image";
	image.setAttribute("src", users[tweetOriginUserId]);

	const text = document.createElement("span");
	text.className = "text";

	const imageClear = document.createElement("p");
	imageClear.className = "image-clear";

	const top = document.createElement("p");
	top.appendChild(image);
	top.appendChild(text);
	top.appendChild(imageClear);
	last = resultAppend(top);

	if (tweet.html) {
		text.innerHTML = tweet.html;
		window.onscroll();
	} else {
		oembed.then(function(oembedResponse) {
			if (oembedResponse.html) {
				text.innerHTML = oembedResponse.html;

				tweet.html_expire = new Date(Date.now() + oembedResponse.cache_age);
				tweet.html = oembedResponse.html;

				const transaction = open.result.transaction("tweets", "readwrite");
				transaction.onerror = open.onerror;
				transaction.objectStore("tweets").put(tweet)
					.onerror = open.onerror;
			} else {
				text.textContent = oembedResponse.error;
			}

			window.onscroll();
		}, alert);
	}
}

function chainInitializeResult(users, tweets) {
	resultInit();
	window.onscroll = function() {
		result.style.height = last.offsetTop + last.clientHeight + tweets.length * 40 + "px";
		chainShowTweets(users, tweets);
	}

	chainShowTweets(users, tweets);
}

function chainGetUserObjectsContainer(users, tweets, token) {
	const userObjects = [];

	function chainGetUserObjects(left) {
		const max = 100;

		if (left.length <= 0) {
			chainInitializeResult(userObjects, tweets);
			return;
		}

		const request = fetchJson("https://api.twitter.com/1.1/users/lookup.json?user_id="
					+ left.slice(-max).join(","), {
				method: "POST",
				headers: { "Authorization": "Bearer " + token }
			});

		if (left.length > max)
			left.length -= max;
		else
			left.length = 0;

		request.then(function(response) {
			for (user of response)
				userObjects[user.id] = user.profile_image_url_https;

			chainGetUserObjects(left);
		});
	}

	chainGetUserObjects(users);
}

open.onsuccess = function() {
	resultAppendText("Parsing queries");
	const queries = parse(getIteratorOfString(decodeURI(window.location.search.substring(1))), false);

	const progress = resultAppendText("Searching");
	const users = [];
	const tweets = [];

	token.then(function(response) {
		open.result.transaction("tweets", "readonly")
			.objectStore("tweets")
			.openCursor()
			.onsuccess = function(event)
		{
			const cursor = event.target.result;
			if (cursor) {
				const value = cursor.value;
				if (matchQuery(queries, value)) {
					tweets.push(value);

					const user = getTweetOriginUserId(value);
					if (users.indexOf(user) < 0)
						users.push(user);

					progress.textContent = "Searching (found "
						+ tweets.length
						+ " tweets)";
				}

				cursor.continue();
			} else {
				chainGetUserObjectsContainer(users, tweets,
					response.access_token);
			}
		}
	});
}

open.onupgradeneeded = function() {
	resultAppendText("Initialized");
	const progress = resultAppendText("Creating database");
	store = open.result.createObjectStore("tweets", { keyPath : "tweet_id" });
	const col = [ { title: "user_id", unique: false },
		{ title: "in_reply_to_status_id", unique: false },
		{ title: "in_reply_to_user_id", unique: false },
		{ title: "timestamp", unique: false },
		{ title: "source", unique: false },
		{ title: "text", unique: false },
		{ title: "retweeted_status_id", unique: false },
		{ title: "retweeted_status_user_id", unique: false },
		{ title: "retweeted_status_timestamp", unique: false },
		{ title: "expanded_urls", unique: false },
		{ title: "html_expire", unique: false },
		{ title: "html", unique: false }];
	for (var i = 0; i < col.length; i++) {
		store.createIndex(col[i].title, col[i].title, { unique: col[i].unique });
		progress.textContent = "Creating database ("
			+ Math.round(i / col.length) + "%, "
			+ i + "/" + col.length + ")";
	};

	function move() {
		window.location = "import.html";
	}

	token.then(move, move);
}
<|endoftext|>


<commit_before>'use strict';

describe('AccountService', function() {

  // INJECTS
  var $httpBackend;
  var AccountService, BackendClientService, HttpClientService;

  // MOCKS
  var accountResponse = getJSONFixture('accountResponse.json');

  // SETUP / TEARDOWN
  beforeEach(function() {
    module('em.appTest');

    inject(function (_$httpBackend_, _AccountService_, _BackendClientService_, _HttpClientService_) {
      $httpBackend = _$httpBackend_;
      AccountService = _AccountService_;
      BackendClientService = _BackendClientService_;
      HttpClientService = _HttpClientService_;
    });
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  // TESTS
  it('should get account', function () {
    var email;
    $httpBackend.expectGET('/api/account').respond(200, accountResponse);
    AccountService.getAccount().then(function(authenticateResponse) {
      email = authenticateResponse.email;
    });
    $httpBackend.flush();

    expect(email).toBeDefined();
  });

});
<commit_msg>AccountService test using spies.<commit_after>'use strict';

describe('AccountService', function() {

  // INJECTS
  var $httpBackend;
  var AccountService, UserSessionService;

  // MOCKS
  var accountResponse = getJSONFixture('accountResponse.json');

  // SETUP / TEARDOWN
  beforeEach(function() {
    module('em.appTest');

    inject(function (_$httpBackend_, _AccountService_, _UserSessionService_) {
      $httpBackend = _$httpBackend_;
      AccountService = _AccountService_;
      UserSessionService = _UserSessionService_;
    });
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  // TESTS
  it('should get account', function () {
    spyOn(UserSessionService, 'setEmail');
    $httpBackend.expectGET('/api/account').respond(200, accountResponse);
    AccountService.getAccount().then(function(authenticateResponse) {
      expect(UserSessionService.setEmail).toHaveBeenCalledWith(authenticateResponse.email);
    });
    $httpBackend.flush();
  });
});
<|endoftext|>