<commit_before>var editor = undefined;
var window = new Object();
var navigator = new Object();
navigator.userAgent = "chrome";
window.navigator = navigator;
window.location = new Object();

window.location.protocol = "";
window.location.host = "";
window.location.href = "";

window.NATIVE_EDITOR_ENJINE = true;
window.NATIVE_EDITOR_ENJINE_SYNC_RECALC = true;

var document = new Object();
window.document = document;

function Image()
{
    this.src = "";
    this.onload = function()
    {
    }
    this.onerror = function()
    {
    }
}

function _image_data()
{
    this.data = null;
    this.length = 0;
}

function native_context2d(parent)
{
    this.canvas = parent;

    this.globalAlpha = 0;
    this.globalCompositeOperation = "";
    this.fillStyle = "";
    this.strokeStyle = "";

    this.lineWidth = 0;
    this.lineCap = 0;
    this.lineJoin = 0;
    this.miterLimit = 0;
    this.shadowOffsetX = 0;
    this.shadowOffsetY = 0;
    this.shadowBlur = 0;
    this.shadowColor = 0;
    this.font = "";
    this.textAlign = 0;
    this.textBaseline = 0;
}
native_context2d.prototype =
{
    save : function() {},
    restore : function() {},

    scale : function(x,y) {},
    rotate : function(angle) {},
    translate : function(x,y) {},
    transform : function(m11,m12,m21,m22,dx,dy) {},
    setTransform : function(m11,m12,m21,m22,dx,dy) {},

    createLinearGradient : function(x0,y0,x1,y1) { return null; },
    createRadialGradient : function(x0,y0,r0,x1,y1,r1) { return null; },
    createPattern : function(image,repetition) { return null; },

    clearRect : function(x,y,w,h) {},
    fillRect : function(x,y,w,h) {},
    strokeRect : function(x,y,w,h) {},

    beginPath : function() {},
    closePath : function() {},
    moveTo : function(x,y) {},
    lineTo : function(x,y) {},
    quadraticCurveTo : function(cpx,cpy,x,y) {},
    bezierCurveTo : function(cp1x,cp1y,cp2x,cp2y,x,y) {},
    arcTo : function(x1,y1,x2,y2,radius) {},
    rect : function(x,y,w,h) {},
    arc : function(x,y,radius,startAngle,endAngle,anticlockwise) {},

    fill : function() {},
    stroke : function() {},
    clip : function() {},
    isPointInPath : function(x,y) {},
    drawFocusRing : function(element,xCaret,yCaret,canDrawCustom) {},

    fillText : function(text,x,y,maxWidth) {},
    strokeText : function(text,x,y,maxWidth) {},
    measureText : function(text) {},

    drawImage : function(img_elem,dx_or_sx,dy_or_sy,dw_or_sw,dh_or_sh,dx,dy,dw,dh) {},

    createImageData : function(imagedata_or_sw,sh)
    {
        var _data = new _image_data();
        _data.length = imagedata_or_sw * sh * 4;
        _data.data = new Uint8Array(imagedata_or_sw * sh * 4);
        return _data;
    },
    getImageData : function(sx,sy,sw,sh) {},
    putImageData : function(image_data,dx,dy,dirtyX,dirtyY,dirtyWidth,dirtyHeight) {}
};

function native_canvas()
{
    this.id = "";
    this.width = 300;
    this.height = 150;

    this.nodeType = 1;
}
native_canvas.prototype =
{
    getContext : function(type)
    {
        if (type == "2d")
            return new native_context2d(this);
        return null;
    },

    toDataUrl : function(type)
    {
        return "";
    },

    addEventListener : function()
    {
    },

    attr : function()
    {
    }
};

window["Asc"] = new Object();

var _null_object = new Object();
_null_object.length = 0;
_null_object.nodeType = 1;
_null_object.offsetWidth = 1;
_null_object.offsetHeight = 1;
_null_object.clientWidth = 1;
_null_object.clientHeight = 1;
_null_object.scrollWidth = 1;
_null_object.scrollHeight = 1;
_null_object.style = new Object();
_null_object.documentElement = _null_object;
_null_object.body = _null_object;
_null_object.ownerDocument = _null_object;
_null_object.defaultView = _null_object;

_null_object.addEventListener = function(){};
_null_object.setAttribute = function(){};
_null_object.getElementsByTagName = function() { return []; };
_null_object.appendChild = function() {};
_null_object.removeChild = function() {};
_null_object.insertBefore = function() {};
_null_object.childNodes = [];
_null_object.parent = _null_object;
_null_object.parentNode = _null_object;
_null_object.find = function() { return this; };
_null_object.appendTo = function() { return this; };
_null_object.css = function() { return this; };
_null_object.width = function() { return 0; };
_null_object.height = function() { return 0; };
_null_object.attr = function() { return this; };
_null_object.prop = function() { return this; };
_null_object.val = function() { return this; };
_null_object.remove = function() {};
_null_object.getComputedStyle = function() { return null; };
_null_object.getContext = function(type) {
    if (type == "2d")
        return new native_context2d(this);
    return null;
};

window._null_object = _null_object;

document.createElement = function(type)
{
    if (type && type.toLowerCase)
    {
        if (type.toLowerCase() == "canvas")
            return new native_canvas();
    }

    return _null_object;
}

function _return_empty_html_element() { return _null_object; };

document.createDocumentFragment = _return_empty_html_element;
document.getElementsByTagName = function(tag) {
    var ret = [];
    if ("head" == tag)
        ret.push(_null_object);
    return ret;
};
document.insertBefore = function() {};
document.appendChild = function() {};
document.removeChild = function() {};
document.getElementById = function() { return _null_object; };
document.createComment = function() { return undefined; };

document.documentElement = _null_object;
document.body = _null_object;

var native = CreateNativeEngine();
window.native = native;
window["native"] = native;

function GetNativeEngine()
{
	return window.native;
}

var native_renderer = null;
var _api = null;
var Asc = null;

function NativeOpenFile()
{
    var doc_bin = window.native.GetFileString(g_file_path);
    if (NATIVE_DOCUMENT_TYPE == "presentation" || NATIVE_DOCUMENT_TYPE == "document")
    {
        _api = new window["asc_docs_api"]("");
        _api.asc_nativeOpenFile(doc_bin);
    }
    else
    {
        Asc = window["Asc"];
        _api = new window["Asc"]["spreadsheet_api"];
        var doc_bin = window.native.GetFileString(g_file_path);
        _api.asc_nativeOpenFile(doc_bin);
    }
}

function NativeOpenFile2()
{
	g_oTextMeasurer = new CTextMeasurerWrapper();
	g_oTextMeasurer.Init();

	window.g_file_path = "native_open_file";
	window.NATIVE_DOCUMENT_TYPE = window.native.GetEditorType();
    var doc_bin = window.native.GetFileString(window.g_file_path);
    if (window.NATIVE_DOCUMENT_TYPE == "presentation" || window.NATIVE_DOCUMENT_TYPE == "document")
    {
        _api = new window["asc_docs_api"]("");
        _api.asc_nativeOpenFile(doc_bin);

        if (_api.WordControl.m_oDrawingDocument.AfterLoad)
            _api.WordControl.m_oDrawingDocument.AfterLoad();
    }
    else
    {
        Asc = window["Asc"];
        _api = new window["Asc"]["spreadsheet_api"];
        var doc_bin = window.native.GetFileString(window.g_file_path);
        _api.asc_nativeOpenFile(doc_bin);
    }
}

function NativeCalculateFile()
{
	_api.asc_nativeCalculateFile();
}

function NativeApplyChanges()
{
    if (NATIVE_DOCUMENT_TYPE == "presentation" || NATIVE_DOCUMENT_TYPE == "document")
    {
        var __changes = [];
        var _count_main = window.native.GetCountChanges();
        for (var i = 0; i < _count_main; i++)
        {
            var _changes_file = window.native.GetChangesFile(i);
            var _changes = JSON.parse(window.native.GetFileString(_changes_file));

            for (var j = 0; j < _changes.length; j++)
            {
                __changes.push(_changes[j]);
            }
        }
        _api.asc_nativeApplyChanges(__changes);
    }
    else
    {
        var __changes = [];
        var _count_main = window.native.GetCountChanges();
        for (var i = 0; i < _count_main; i++)
        {
            var _changes_file = window.native.GetChangesFile(i);
            var _changes = JSON.parse(window.native.GetFileString(_changes_file));

            for (var j = 0; j < _changes.length; j++)
            {
                __changes.push(_changes[j]);
            }
        }

        _api.asc_nativeApplyChanges(__changes);
    }
}
function NativeGetFileString()
{
    return _api.asc_nativeGetFile();
}

function GetNativeCountPages()
{
    return _api.asc_nativePrintPagesCount();
}

window.memory1 = null;
window.memory2 = null;

function GetNativePageBase64(pageIndex)
{
    if (null == window.memory1)
        window.memory1 = CreateNativeMemoryStream();
    else
        window.memory1.ClearNoAttack();

    if (null == window.memory2)
        window.memory2 = CreateNativeMemoryStream();
    else
        window.memory2.ClearNoAttack();

    if (native_renderer == null)
    {
        native_renderer = _api.asc_nativeCheckPdfRenderer(window.memory1, window.memory2);
    }
    else
    {
        window.memory1.ClearNoAttack();
        window.memory2.ClearNoAttack();
    }

    _api.asc_nativePrint(native_renderer, pageIndex);
    return window.memory1;
}

function GetNativePageMeta(pageIndex)
{
	_api.WordControl.m_oDrawingDocument.LogicDocument = _api.WordControl.m_oDrawingDocument.m_oLogicDocument;
    _api.WordControl.m_oDrawingDocument.RenderPage(pageIndex);
}

function GetNativeId()
{
    return window.native.GetFileId();
}

function clearTimeout() {};
function setTimeout() {};
function clearInterval() {};
function setInterval() {};

window.clearTimeout = clearTimeout;
window.setTimeout = setTimeout;
window.clearInterval = clearInterval;
window.setInterval = setInterval;

window["OfficeExcel"] = {type:'common'};
var OfficeExcel = window["OfficeExcel"];

var console = {
	log : function(param) { window.native.ConsoleLog(param); }
};

// HTML page interface
window.native.Call_OnUpdateOverlay = function(param)
{
    _api.WordControl.m_oDrawingDocument.OnUpdateOverlay();
};

window.native.Call_OnMouseDown = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseDown(e);
};
window.native.Call_OnMouseUp = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseUp(e);
};
window.native.Call_OnMouseMove = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseMove(e);
};

window.native.Call_OnKeyDown = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyDown(e);
};
window.native.Call_OnKeyPress = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyPress(e);
};
window.native.Call_OnKeyUp = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyUp(e);
};

window.native.Call_CalculateResume = function()
{
    Document_Recalculate_Page();
};

window.native.Call_TurnOffRecalculate = function()
{
    _api.WordControl.m_oLogicDocument.TurnOffRecalc = true;
};
window.native.Call_TurnOnRecalculate = function()
{
    _api.WordControl.m_oLogicDocument.TurnOffRecalc = false;
};<commit_msg><commit_after>var editor = undefined;
var window = new Object();
var navigator = new Object();
navigator.userAgent = "chrome";
window.navigator = navigator;
window.location = new Object();

window.location.protocol = "";
window.location.host = "";
window.location.href = "";

window.NATIVE_EDITOR_ENJINE = true;
window.NATIVE_EDITOR_ENJINE_SYNC_RECALC = true;

var document = new Object();
window.document = document;

function Image()
{
    this.src = "";
    this.onload = function()
    {
    }
    this.onerror = function()
    {
    }
}

function _image_data()
{
    this.data = null;
    this.length = 0;
}

function native_context2d(parent)
{
    this.canvas = parent;

    this.globalAlpha = 0;
    this.globalCompositeOperation = "";
    this.fillStyle = "";
    this.strokeStyle = "";

    this.lineWidth = 0;
    this.lineCap = 0;
    this.lineJoin = 0;
    this.miterLimit = 0;
    this.shadowOffsetX = 0;
    this.shadowOffsetY = 0;
    this.shadowBlur = 0;
    this.shadowColor = 0;
    this.font = "";
    this.textAlign = 0;
    this.textBaseline = 0;
}
native_context2d.prototype =
{
    save : function() {},
    restore : function() {},

    scale : function(x,y) {},
    rotate : function(angle) {},
    translate : function(x,y) {},
    transform : function(m11,m12,m21,m22,dx,dy) {},
    setTransform : function(m11,m12,m21,m22,dx,dy) {},

    createLinearGradient : function(x0,y0,x1,y1) { return null; },
    createRadialGradient : function(x0,y0,r0,x1,y1,r1) { return null; },
    createPattern : function(image,repetition) { return null; },

    clearRect : function(x,y,w,h) {},
    fillRect : function(x,y,w,h) {},
    strokeRect : function(x,y,w,h) {},

    beginPath : function() {},
    closePath : function() {},
    moveTo : function(x,y) {},
    lineTo : function(x,y) {},
    quadraticCurveTo : function(cpx,cpy,x,y) {},
    bezierCurveTo : function(cp1x,cp1y,cp2x,cp2y,x,y) {},
    arcTo : function(x1,y1,x2,y2,radius) {},
    rect : function(x,y,w,h) {},
    arc : function(x,y,radius,startAngle,endAngle,anticlockwise) {},

    fill : function() {},
    stroke : function() {},
    clip : function() {},
    isPointInPath : function(x,y) {},
    drawFocusRing : function(element,xCaret,yCaret,canDrawCustom) {},

    fillText : function(text,x,y,maxWidth) {},
    strokeText : function(text,x,y,maxWidth) {},
    measureText : function(text) {},

    drawImage : function(img_elem,dx_or_sx,dy_or_sy,dw_or_sw,dh_or_sh,dx,dy,dw,dh) {},

    createImageData : function(imagedata_or_sw,sh)
    {
        var _data = new _image_data();
        _data.length = imagedata_or_sw * sh * 4;
        _data.data = new Uint8Array(imagedata_or_sw * sh * 4);
        return _data;
    },
    getImageData : function(sx,sy,sw,sh) {},
    putImageData : function(image_data,dx,dy,dirtyX,dirtyY,dirtyWidth,dirtyHeight) {}
};

function native_canvas()
{
    this.id = "";
    this.width = 300;
    this.height = 150;

    this.nodeType = 1;
}
native_canvas.prototype =
{
    getContext : function(type)
    {
        if (type == "2d")
            return new native_context2d(this);
        return null;
    },

    toDataUrl : function(type)
    {
        return "";
    },

    addEventListener : function()
    {
    },

    attr : function()
    {
    }
};

window["Asc"] = new Object();

var _null_object = new Object();
_null_object.length = 0;
_null_object.nodeType = 1;
_null_object.offsetWidth = 1;
_null_object.offsetHeight = 1;
_null_object.clientWidth = 1;
_null_object.clientHeight = 1;
_null_object.scrollWidth = 1;
_null_object.scrollHeight = 1;
_null_object.style = new Object();
_null_object.documentElement = _null_object;
_null_object.body = _null_object;
_null_object.ownerDocument = _null_object;
_null_object.defaultView = _null_object;

_null_object.addEventListener = function(){};
_null_object.setAttribute = function(){};
_null_object.getElementsByTagName = function() { return []; };
_null_object.appendChild = function() {};
_null_object.removeChild = function() {};
_null_object.insertBefore = function() {};
_null_object.childNodes = [];
_null_object.parent = _null_object;
_null_object.parentNode = _null_object;
_null_object.find = function() { return this; };
_null_object.appendTo = function() { return this; };
_null_object.css = function() { return this; };
_null_object.width = function() { return 0; };
_null_object.height = function() { return 0; };
_null_object.attr = function() { return this; };
_null_object.prop = function() { return this; };
_null_object.val = function() { return this; };
_null_object.remove = function() {};
_null_object.getComputedStyle = function() { return null; };
_null_object.getContext = function(type) {
    if (type == "2d")
        return new native_context2d(this);
    return null;
};

window._null_object = _null_object;

document.createElement = function(type)
{
    if (type && type.toLowerCase)
    {
        if (type.toLowerCase() == "canvas")
            return new native_canvas();
    }

    return _null_object;
}

function _return_empty_html_element() { return _null_object; };

document.createDocumentFragment = _return_empty_html_element;
document.getElementsByTagName = function(tag) {
    var ret = [];
    if ("head" == tag)
        ret.push(_null_object);
    return ret;
};
document.insertBefore = function() {};
document.appendChild = function() {};
document.removeChild = function() {};
document.getElementById = function() { return _null_object; };
document.createComment = function() { return undefined; };

document.documentElement = _null_object;
document.body = _null_object;

var native = CreateNativeEngine();
window.native = native;
window["native"] = native;

function GetNativeEngine()
{
	return window.native;
}

var native_renderer = null;
var _api = null;
var Asc = null;

function NativeOpenFile()
{
    var doc_bin = window.native.GetFileString(g_file_path);
    if (NATIVE_DOCUMENT_TYPE == "presentation" || NATIVE_DOCUMENT_TYPE == "document")
    {
        _api = new window["asc_docs_api"]("");
        _api.asc_nativeOpenFile(doc_bin);
    }
    else
    {
        Asc = window["Asc"];
        _api = new window["Asc"]["spreadsheet_api"];
        var doc_bin = window.native.GetFileString(g_file_path);
        _api.asc_nativeOpenFile(doc_bin);
    }
}

function NativeOpenFile2()
{
	g_oTextMeasurer = new CTextMeasurerWrapper();
	g_oTextMeasurer.Init();

	window.g_file_path = "native_open_file";
	window.NATIVE_DOCUMENT_TYPE = window.native.GetEditorType();
    var doc_bin = window.native.GetFileString(window.g_file_path);
    if (window.NATIVE_DOCUMENT_TYPE == "presentation" || window.NATIVE_DOCUMENT_TYPE == "document")
    {
        _api = new window["asc_docs_api"]("");
        _api.asc_nativeOpenFile(doc_bin);

        if (_api.WordControl.m_oDrawingDocument.AfterLoad)
            _api.WordControl.m_oDrawingDocument.AfterLoad();
    }
    else
    {
        Asc = window["Asc"];
        _api = new window["Asc"]["spreadsheet_api"];
        var doc_bin = window.native.GetFileString(window.g_file_path);
        _api.asc_nativeOpenFile(doc_bin);
    }
}

function NativeCalculateFile()
{
	_api.asc_nativeCalculateFile();
}

function NativeApplyChanges()
{
    if (NATIVE_DOCUMENT_TYPE == "presentation" || NATIVE_DOCUMENT_TYPE == "document")
    {
        var __changes = [];
        var _count_main = window.native.GetCountChanges();
        for (var i = 0; i < _count_main; i++)
        {
            var _changes_file = window.native.GetChangesFile(i);
            var _changes = JSON.parse(window.native.GetFileString(_changes_file));

            for (var j = 0; j < _changes.length; j++)
            {
                __changes.push(_changes[j]);
            }
        }
        _api.asc_nativeApplyChanges(__changes);
    }
    else
    {
        var __changes = [];
        var _count_main = window.native.GetCountChanges();
        for (var i = 0; i < _count_main; i++)
        {
            var _changes_file = window.native.GetChangesFile(i);
            var _changes = JSON.parse(window.native.GetFileString(_changes_file));

            for (var j = 0; j < _changes.length; j++)
            {
                __changes.push(_changes[j]);
            }
        }

        _api.asc_nativeApplyChanges(__changes);
    }
}
function NativeGetFileString()
{
    return _api.asc_nativeGetFile();
}

function GetNativeCountPages()
{
    return _api.asc_nativePrintPagesCount();
}

window.memory1 = null;
window.memory2 = null;

function GetNativePageBase64(pageIndex)
{
    if (null == window.memory1)
        window.memory1 = CreateNativeMemoryStream();
    else
        window.memory1.ClearNoAttack();

    if (null == window.memory2)
        window.memory2 = CreateNativeMemoryStream();
    else
        window.memory2.ClearNoAttack();

    if (native_renderer == null)
    {
        native_renderer = _api.asc_nativeCheckPdfRenderer(window.memory1, window.memory2);
    }
    else
    {
        window.memory1.ClearNoAttack();
        window.memory2.ClearNoAttack();
    }

    _api.asc_nativePrint(native_renderer, pageIndex);
    return window.memory1;
}

function GetNativePageMeta(pageIndex)
{
	_api.WordControl.m_oDrawingDocument.LogicDocument = _api.WordControl.m_oDrawingDocument.m_oLogicDocument;
    _api.WordControl.m_oDrawingDocument.RenderPage(pageIndex);
}

function GetNativeId()
{
    return window.native.GetFileId();
}

function clearTimeout() {};
function setTimeout() {};
function clearInterval() {};
function setInterval() {};

window.clearTimeout = clearTimeout;
window.setTimeout = setTimeout;
window.clearInterval = clearInterval;
window.setInterval = setInterval;

window["OfficeExcel"] = {type:'common'};
var OfficeExcel = window["OfficeExcel"];

var console = {
	log : function(param) { window.native.ConsoleLog(param); }
};

// HTML page interface
window.native.Call_OnUpdateOverlay = function(param)
{
    _api.WordControl.m_oDrawingDocument.OnUpdateOverlay();
};

window.native.Call_OnMouseDown = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseDown(e);
};
window.native.Call_OnMouseUp = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseUp(e);
};
window.native.Call_OnMouseMove = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnMouseMove(e);
};

window.native.Call_OnKeyDown = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyDown(e);
};
window.native.Call_OnKeyPress = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyPress(e);
};
window.native.Call_OnKeyUp = function(e)
{
    _api.WordControl.m_oDrawingDocument.OnKeyUp(e);
};

window.native.Call_CalculateResume = function()
{
    Document_Recalculate_Page();
};

window.native.Call_TurnOffRecalculate = function()
{
    _api.WordControl.m_oLogicDocument.TurnOffRecalc = true;
};
window.native.Call_TurnOnRecalculate = function()
{
    _api.WordControl.m_oLogicDocument.TurnOffRecalc = false;
    _api.WordControl.m_oLogicDocument.Recalculate();
};<|endoftext|>


<commit_before>var clock = 0.0;
var task_start = performance.now();
var tick = 0;
var lastTime = 0.0;

var alpha = 0.0;
var beta = 0.0;
var gamma = 0.0;

function startMeasurement() {

	if (Math.abs(beta) < 2.0 && Math.abs(gamma) < 2.0) {
		document.querySelector("#dist_acc").innerHTML = "Balanced";
		document.querySelector("#dist_acc").style.backgroundColor = 'green';
	}
}

window.ondevicemotion = function(event) {
	var ax = event.acceleration.x;
	var ay = event.acceleration.y;
	var az = event.acceleration.z;

	window.alert(ax);

	clock = performance.now() - task_start;
	tick = tick + 1;

	document.querySelector("#x_acc").innerHTML = "X = " + ax;
	document.querySelector("#y_acc").innerHTML = "Y = " + ay;
	document.querySelector("#z_acc").innerHTML = "Z = " + az;
	document.querySelector("#clock_acc").innerHTML = "Clock = " + clock;
	if (clock - lastTime >= 1000.0) {
		lastTime = Math.floor(clock);
		document.querySelector("#tick_acc").innerHTML = "Ticks per Second = " + tick;
		tick = 0;
	}
}

<commit_msg>changens<commit_after>var clock = 0.0;
var task_start = performance.now();
var tick = 0;
var lastTime = 0.0;

var alpha = 0.0;
var beta = 0.0;
var gamma = 0.0;

function startMeasurement() {

	if (Math.abs(beta) < 2.0 && Math.abs(gamma) < 2.0) {
		document.querySelector("#dist_acc").innerHTML = "Balanced";
		document.querySelector("#dist_acc").style.backgroundColor = 'green';
	}
}

window.ondevicemotion = function(event) {
	var acceleration = eventData.acceleration;
	var ax = acceleration.x;
	var ay = acceleration.y;
	var az = acceleration.z;

	window.alert(ax);

	clock = performance.now() - task_start;
	tick = tick + 1;

	document.querySelector("#x_acc").innerHTML = "X = " + ax;
	document.querySelector("#y_acc").innerHTML = "Y = " + ay;
	document.querySelector("#z_acc").innerHTML = "Z = " + az;
	document.querySelector("#clock_acc").innerHTML = "Clock = " + clock;
	if (clock - lastTime >= 1000.0) {
		lastTime = Math.floor(clock);
		document.querySelector("#tick_acc").innerHTML = "Ticks per Second = " + tick;
		tick = 0;
	}
}

<|endoftext|>


<commit_before>/* ***********************************************************************************************

    Kitchen Sink

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012 Sebastian Fastner, Mainz, Germany, http://unify-training.com

*********************************************************************************************** */

/**
 * UI view
 */
core.Class("kitchensink.view.Ui", {
  include : [unify.view.StaticView],

  construct : function() {
    unify.view.StaticView.call(this);
  },

  members :
  {
    // overridden
    getTitle : function(type, param) {
      return "UI Elements";
    },

    // overridden
    _createView : function() {
      /*var container = new unify.ui.container.Scroll(new unify.ui.layout.VBox(20));
      container.set({
        width: 500,
        alignX: "center",
        allowGrowX: false
      });
      this.add(container, {flex: 1});*/
      var container = this;

      var label = new unify.ui.basic.Label("Label");
      container.add(label);

      var button = new unify.ui.form.Button("Button");
      container.add(button);

      var combobox = new unify.ui.form.Combobox();
      combobox.set({
        width: 300,
        allowGrowX: false
      });
      combobox.setData([{
        id: 1,
        label: "Test1"
      }, {
        id: 2,
        label: "Test2"
      }, {
        id: 3,
        label: "Test3"
      }]);
      combobox.setValue(1);
      combobox.addListener("execute", function(e) {
        this.debug("COMBO BOX " + e.getData());
      }, this);
      container.add(combobox);

      // Show Empty Dialog --------------------------------------------------
      var dialogButton = new unify.ui.form.Button("Dialog");
      dialogButton.addListener("execute", this.__openDialog, this);
      container.add(dialogButton);

      // Show Alert message ------------------------------------------------
      var alertButton = new unify.ui.form.Button("Alert");
      alertButton.addListener("execute", function(e) {
        unify.ui.dialog.Dialog.alert(
            "Alert",
            "Be Alert!",
            function() { console.log("You have been alerted..."); }
          );
        }, this);
      container.add(alertButton);

      // Show Confirm Dialog ------------------------------------------------
      var confirmButton = new unify.ui.form.Button("Confirm");
      confirmButton.addListener("execute", function(e) {
        unify.ui.dialog.Dialog.confirm(
            "Please deside...",
            "Witch programming language is the best?",
            "JavaScript",
            "VisualBasic",
            function(e) {
              btnID = e.getData();
              if (btnID == 'YES')
                console.log("Good choice...")
              else
                console.log("You ignorant fool! Watch this: http://www.youtube.com/watch?v=hQVTIJBZook")
            }
          );
        }, this);
      container.add(confirmButton);

      // Open modal view
      var openModalButton = new unify.ui.basic.NavigationButton("Modal");
      openModalButton.set({
        goTo: "modal"
      });
      container.add(openModalButton);

      // Open activity indicator
      var startActivityIndicator = new unify.ui.form.Button("Activity indicator");
      startActivityIndicator.addListener("execute", function() {
        unify.ui.manager.ActivityIndicatorManager.getInstance().show();

        window.setTimeout(function() {
          unify.ui.manager.ActivityIndicatorManager.getInstance().hide();
        }, 3000);
      }, this);
      container.add(startActivityIndicator);
    },

    __dialog : null,

    __openDialog : function() {
      var dialog = this.__dialog = new unify.ui.dialog.GenericDialog("Das ist der Titel", []);
      dialog.addListener("execute", this.__onDialogExecute, this);

      unify.ui.core.PopOverManager.getInstance().show(dialog, "center");
    },

    __onDialogExecute : function(e) {
      this.debug("Dialog action : " + e.getData());

      unify.ui.core.PopOverManager.getInstance().hide(this.__dialog);
    }

  }
});

unify.core.Singleton.annotate(kitchensink.view.Ui);
<commit_msg>Readd scroll container<commit_after>/* ***********************************************************************************************

    Kitchen Sink

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012 Sebastian Fastner, Mainz, Germany, http://unify-training.com

*********************************************************************************************** */

/**
 * UI view
 */
core.Class("kitchensink.view.Ui", {
  include : [unify.view.StaticView],

  construct : function() {
    unify.view.StaticView.call(this);
  },

  members :
  {
    // overridden
    getTitle : function(type, param) {
      return "UI Elements";
    },

    // overridden
    _createView : function() {
      var container = new unify.ui.container.Scroll(new unify.ui.layout.VBox(20));
      container.set({
        width: 500,
        alignX: "center",
        allowGrowX: false
      });
      this.add(container, {flex: 1});

      var label = new unify.ui.basic.Label("Label");
      container.add(label);

      var button = new unify.ui.form.Button("Button");
      container.add(button);

      var combobox = new unify.ui.form.Combobox();
      combobox.set({
        width: 300,
        allowGrowX: false
      });
      combobox.setData([{
        id: 1,
        label: "Test1"
      }, {
        id: 2,
        label: "Test2"
      }, {
        id: 3,
        label: "Test3"
      }]);
      combobox.setValue(1);
      combobox.addListener("execute", function(e) {
        this.debug("COMBO BOX " + e.getData());
      }, this);
      container.add(combobox);

      // Show Empty Dialog --------------------------------------------------
      var dialogButton = new unify.ui.form.Button("Dialog");
      dialogButton.addListener("execute", this.__openDialog, this);
      container.add(dialogButton);

      // Show Alert message ------------------------------------------------
      var alertButton = new unify.ui.form.Button("Alert");
      alertButton.addListener("execute", function(e) {
        unify.ui.dialog.Dialog.alert(
            "Alert",
            "Be Alert!",
            function() { console.log("You have been alerted..."); }
          );
        }, this);
      container.add(alertButton);

      // Show Confirm Dialog ------------------------------------------------
      var confirmButton = new unify.ui.form.Button("Confirm");
      confirmButton.addListener("execute", function(e) {
        unify.ui.dialog.Dialog.confirm(
            "Please deside...",
            "Witch programming language is the best?",
            "JavaScript",
            "VisualBasic",
            function(e) {
              btnID = e.getData();
              if (btnID == 'YES')
                console.log("Good choice...")
              else
                console.log("You ignorant fool! Watch this: http://www.youtube.com/watch?v=hQVTIJBZook")
            }
          );
        }, this);
      container.add(confirmButton);

      // Open modal view
      var openModalButton = new unify.ui.basic.NavigationButton("Modal");
      openModalButton.set({
        goTo: "modal"
      });
      container.add(openModalButton);

      // Open activity indicator
      var startActivityIndicator = new unify.ui.form.Button("Activity indicator");
      startActivityIndicator.addListener("execute", function() {
        unify.ui.manager.ActivityIndicatorManager.getInstance().show();

        window.setTimeout(function() {
          unify.ui.manager.ActivityIndicatorManager.getInstance().hide();
        }, 3000);
      }, this);
      container.add(startActivityIndicator);
    },

    __dialog : null,

    __openDialog : function() {
      var dialog = this.__dialog = new unify.ui.dialog.GenericDialog("Das ist der Titel", []);
      dialog.addListener("execute", this.__onDialogExecute, this);

      unify.ui.core.PopOverManager.getInstance().show(dialog, "center");
    },

    __onDialogExecute : function(e) {
      this.debug("Dialog action : " + e.getData());

      unify.ui.core.PopOverManager.getInstance().hide(this.__dialog);
    }

  }
});

unify.core.Singleton.annotate(kitchensink.view.Ui);
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Mi Claro - Twiks
// @namespace    http://federicojm.com/
// @version      0.1
// @description  Remove annoying chat popup that ALWAYS shows up.
// @author       Federico JM
// @match        http://miclaro.claro.com.co/wps/myportal/co/mtmx/mi-telmex*
// @grant        none
// ==/UserScript==

(function () {
  'use strict'

  var deleteChat = function () {
    var chat = document.getElementById('inbenta')
    if (chat) {
      chat.remove()
      clearInterval(intervalId)
    }
  }
  var intervalId = setInterval(deleteChat, 500)
})()
<commit_msg>Fix code formatting.<commit_after>// ==UserScript==
// @name         Mi Claro - Tweaks
// @namespace    http://federicojm.com/
// @version      0.2
// @description  Remove annoying chat popup that ALWAYS shows up.
// @author       Federico JM
// @match        http://miclaro.claro.com.co/wps/myportal/co/mtmx/mi-telmex*
// @grant        none
// ==/UserScript==

;(function () {
  'use strict'

  var deleteChat = function () {
    var chat = document.getElementById('inbenta')
    if (chat) {
      chat.remove()
      clearInterval(intervalId)
    }
  }
  var intervalId = setInterval(deleteChat, 500)
})()
<|endoftext|>


<commit_before>const fs = require('fs')
const { green } = require('chalk')

const { warn } = require('./logger')
const appPaths = require('../app-paths')

module.exports = function (cfg) {
  let file
  let content
  let error = false

  file = appPaths.resolve.app(cfg.sourceFiles.indexHtmlTemplate)
  if (!fs.existsSync(file)) {
    warn('Missing /src/index.template.html file...\n')
    error = true
  }
  content = fs.readFileSync(file, 'utf-8')

  if (content.indexOf('<base href') > -1) {
    warn(`Please remove the <base> tag from /src/index.template.html
   This is taken care of by Quasar automatically.
  `)
    error = true
  }

  file = appPaths.resolve.app(cfg.sourceFiles.rootComponent)
  content = fs.readFileSync(file, 'utf-8')
  if (content.indexOf('q-app') === -1) {
    warn(`\n Quasar requires a minor change to the root component:
   ${file}

  Please add: id="q-app" (or write #q-app if using Pug)
  to the outermost HTML element of the template.

${green('Example:')}
  <template>

      ...

  </template>
`)
    error = true
  }

  if (error) {
    process.exit(1)
  }
}
<commit_msg>chore(app): small tweaks to app-files-validations<commit_after>const fs = require('fs')
const { green } = require('chalk')

const { warn } = require('./logger')
const appPaths = require('../app-paths')

module.exports = function (cfg) {
  let file
  let content
  let error = false

  file = appPaths.resolve.app(cfg.sourceFiles.indexHtmlTemplate)
  content = fs.readFileSync(file, 'utf-8')

  if (content.indexOf('<base href') > -1) {
    warn(`Please remove the <base> tag from /src/index.template.html
   This is taken care of by Quasar automatically.
  `)
    error = true
  }

  file = appPaths.resolve.app(cfg.sourceFiles.rootComponent)
  content = fs.readFileSync(file, 'utf-8')
  if (content.indexOf('q-app') === -1) {
    console.log()
    warn(`Quasar requires a minor change to the root component:
   ${file}

  Please add: id="q-app" (or write #q-app if using Pug)
  to the outermost HTML element of the template.

${green('Example:')}
  <template>

      ...

  </template>
`)
    error = true
  }

  if (error === true) {
    process.exit(1)
  }
}
<|endoftext|>


<commit_before>/**
 * Makes a list sortable
 *
 * Example:
 *

 *
{{item.name}}<button class="btn btn-mini btn-danger" style="float:right;" ng-click="remove(item)">X</button>

 *

 * <button ng-click="add()">Add</button>
 *
 * the add function defined in an sorounding controller:
 * $scope.add = function() {
 *     $scope.layer_list.push({"id": 99, "name": "New"});
 * }
 *
 * layer_list is a list of dicts
 * insiede the directive you must work with sortable_array
 * instead of the outer list layer_list
 *
 * if you wish to use functions inside the directive like
 * remove, they must be defined inside the directive
 *
 * ToDo:
 * figger out how to access methods of directive from
 * outside like add so the outer list layer_list hasn't
 * to manipulate by controller but by directive
 */

angular.module('mapproxy_gui.directives', []).
directive('sortable', function() {
    return {
        restrict: 'A',
        replace: false,
        scope: {
            sortable_array: '=toSort'
        },
        link: function(scope, element, attrs) {
            scope.dragStart = function(e, ui) {
                ui.item.data('start', ui.item.index());
            };

            scope.dragEnd = function(e, ui) {
                //old item list index
                var start = ui.item.data('start');
                //new item list index
                var end = ui.item.index();

                if(angular.isUndefined(scope.sortable_array)) {
                    scope.sortable_array = [];
                }
                //rearrange list
                scope.sortable_array.splice(end, 0,
                    scope.sortable_array.splice(start, 1)[0]);

                //tell angular $scope has changed
                scope.$apply();
            };

            scope.remove = function(item) {
                scope.sortable_array.splice(scope.sortable_array.indexOf(item), 1);
                if(scope.sortable_array.length == 0) {
                    scope.sortable_array = undefined;
                }
            };

            var sortable_element = $(element).sortable({
                start: scope.dragStart,
                update: scope.dragEnd
            });
        }
    };
}).

/* Drag&Drop directives */
directive('draggable', function() {
    return {
        // A = attribute, E = Element, C = Class and M = HTML Comment
        restrict:'A',
        //The link function is responsible for registering DOM listeners as well as updating the DOM.
        link: function(scope, element, attrs) {
            $(element).draggable({
                helper: 'clone',
                cursor: 'move',
                revert: false
            });
        }
    };
}).

/**
 * Insertable directive
 *
 * Usable as attribute: <div insertable ...
 * requires ng-model
 *
 * change: function
 * - fired on value change.
 * - must provide a callback parameter for callback function
 * - callback(true) accept change
 * - callback(false) reject change
 *
 * allow-array: boolean
 * - true to allow insert arrays
 * template-url: string
 * - url of template
 * accepts: string
 * - classname of elements allowed to insert
 */
 //TODO: allow setting accepts
directive('droppable', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            //create a new not isolated scope
            scope = scope.$new(false)

            scope.checkExist = function(item) {
                var exist = false;
                //because angular add a unique $$hashKey to objects
                angular.forEach(scope.items, function(scope_item) {
                    //angular.forEach doesn't support break
                    if(!exist) {
                        exist = angular.equals(scope_item, item);
                    }
                });
                if(!exist) {
                    scope.to_insert.push(item);
                }
            };
            scope.checkClass = function(elem) {
                var found = false;
                angular.forEach(scope.accepts, function(accept) {
                    if(!found) {
                        found = elem.hasClass(accept);
                    }
                });
                return found;
            };
            scope.insertItems = function() {
                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                if(attrs.allowArray) {
                    scope.items = scope.items.concat(scope.to_insert);
                } else {
                    scope.items = scope.to_insert[0];
                }
                delete(scope.ui);
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.changeCallback = function(change) {
                if(change) {
                    scope.insertItems();
                } else {
                    scope.j_ui.draggable('option', 'revert', true);
                }
            };
            if(angular.isUndefined(attrs.accepts)) {
                scope.accepts = [];
            } else {
                scope.accepts = attrs.accepts.split(',');
            }

            //look for callback function
            if(!angular.isUndefined(attrs.changeCallback)) {
                scope.change = $parse(attrs.changeCallback);
            }

            $(element).droppable({
                drop: function(event,ui) {
                    //get current items from model
                    scope.items = ngModelCtrl.$modelValue;
                    scope.inserted = false;
                    scope.ui = ui;
                    scope.j_ui = $(scope.ui.draggable);
                    //only process draggable elements
                    if(!scope.j_ui.hasClass('ui-draggable')) return;

                    //check element class against accepts
                    if(!scope.checkClass(scope.j_ui)) {
                        scope.j_ui.draggable('option', 'revert', true);
                        return;
                    }
                    //get data (string) of dopped element and convert it to an object
                    scope.new_item = angular.fromJson(scope.j_ui.attr('item-data'));
                    scope.to_insert = [];
                    //check for data
                    if(!angular.isUndefined(scope.new_item)) {
                        //check for existing items
                        if(angular.isArray(scope.new_item)) {
                            angular.forEach(scope.new_item, scope.checkExist);
                        } else {
                            scope.checkExist(scope.new_item);
                        }
                        //look if something to insert
                        if(scope.to_insert.length > 0) {
                            //run callback if present
                            if(angular.isFunction(scope.change)) {
                                scope.change(scope, {callback: scope.changeCallback, new_data: scope.new_item});
                            } else {
                                scope.insertItems();
                            }
                        } else {
                            scope.j_ui.draggable('option', 'revert', true);
                        }
                    }
                }
            });
        }
    };
}).

directive('toggleGroup', function() {
    return {
        restrict: 'E',
        controller: toggleGroupCtrl
    };
}).

directive('toggleElement', function() {
    return {
        restrict: 'A',
        require: '^toggleGroup',
        link: function(scope, element, attrs, toggleGroupCTRL) {
            toggleGroupCTRL.addElement(element);
            $(element).click(function() {
                toggleGroupCTRL.getToggleFunc()(element);
            });
        }
    }
}).

directive('tabs', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: {},
        controller: tabsCtrl,
        template:
            '
' +
            '
' +
            '
'+
            '{{pane.title}}' +
            '
' +
            '
' +
            '

' +
            '
',
        replace: true
    };
}).

directive('pane', function() {
    return {
        require: '^tabs',
        restrict: 'E',
        transclude: true,
        scope: { title: '@' },
        link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
        },
        template:
            '

',
        replace: true
    };
});

/* Controller for directives */

// used by toggleGroup
var toggleGroupCtrl = function($scope, $element) {
    var toggle_elements = [];

    var toToggle = function(element) {
        switch(element.attr('toggle-element')) {
            case 'next':
                return $(element).next();
                break;
            default:
                return $(element);
        }
    };

    this.addElement = function(element) {
        toggle_elements.push(element);
    };
    this.getElementCount = function() {
        return toggle_elements.length;
    };

    this.multiShow = function(element) {
        toToggle(element).toggle();
    };
    this.hideOther = function(element) {
        angular.forEach(toggle_elements, function(t_element) {
            if (t_element == element) {
                toToggle(t_element).show();
            } else {
                toToggle(t_element).hide();
            }
        });
    };
    this.getToggleFunc = function() {
        switch($element.attr('mode')) {
            case 'multiShow':
                return this.multiShow;
                break;
            case 'hideOther':
            default:
                return this.hideOther;
        }
    };
}

// used by tabs
var tabsCtrl = function($scope, $element) {

    this.addPane = function(pane) {
        if (panes.length == 0) $scope.select(pane);
        panes.push(pane);
    };

    $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
            pane.selected = false;
        });
        pane.selected = true;
    };

    var panes = $scope.panes = [];
};
<commit_msg>Moved drop handler into scope<commit_after>/**
 * Makes a list sortable
 *
 * Example:
 *

 *
{{item.name}}<button class="btn btn-mini btn-danger" style="float:right;" ng-click="remove(item)">X</button>

 *

 * <button ng-click="add()">Add</button>
 *
 * the add function defined in an sorounding controller:
 * $scope.add = function() {
 *     $scope.layer_list.push({"id": 99, "name": "New"});
 * }
 *
 * layer_list is a list of dicts
 * insiede the directive you must work with sortable_array
 * instead of the outer list layer_list
 *
 * if you wish to use functions inside the directive like
 * remove, they must be defined inside the directive
 *
 * ToDo:
 * figger out how to access methods of directive from
 * outside like add so the outer list layer_list hasn't
 * to manipulate by controller but by directive
 */

angular.module('mapproxy_gui.directives', []).
directive('sortable', function() {
    return {
        restrict: 'A',
        replace: false,
        scope: {
            sortable_array: '=toSort'
        },
        link: function(scope, element, attrs) {
            scope.dragStart = function(e, ui) {
                ui.item.data('start', ui.item.index());
            };

            scope.dragEnd = function(e, ui) {
                //old item list index
                var start = ui.item.data('start');
                //new item list index
                var end = ui.item.index();

                if(angular.isUndefined(scope.sortable_array)) {
                    scope.sortable_array = [];
                }
                //rearrange list
                scope.sortable_array.splice(end, 0,
                    scope.sortable_array.splice(start, 1)[0]);

                //tell angular $scope has changed
                scope.$apply();
            };

            scope.remove = function(item) {
                scope.sortable_array.splice(scope.sortable_array.indexOf(item), 1);
                if(scope.sortable_array.length == 0) {
                    scope.sortable_array = undefined;
                }
            };

            var sortable_element = $(element).sortable({
                start: scope.dragStart,
                update: scope.dragEnd
            });
        }
    };
}).

/* Drag&Drop directives */
directive('draggable', function() {
    return {
        // A = attribute, E = Element, C = Class and M = HTML Comment
        restrict:'A',
        //The link function is responsible for registering DOM listeners as well as updating the DOM.
        link: function(scope, element, attrs) {
            $(element).draggable({
                helper: 'clone',
                cursor: 'move',
                revert: false
            });
        }
    };
}).

/**
 * Insertable directive
 *
 * Usable as attribute: <div insertable ...
 * requires ng-model
 *
 * change: function
 * - fired on value change.
 * - must provide a callback parameter for callback function
 * - callback(true) accept change
 * - callback(false) reject change
 *
 * allow-array: boolean
 * - true to allow insert arrays
 * accepts: string - comma seppareted string for list
 * - classname(s) of elements allowed to insert
 */
 //TODO: allow setting accepts
directive('droppable', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            //create a new not isolated scope
            scope = scope.$new(false)

            scope.checkExist = function(item) {
                var exist = false;
                //because angular add a unique $$hashKey to objects
                angular.forEach(scope.items, function(scope_item) {
                    //angular.forEach doesn't support break
                    if(!exist) {
                        exist = angular.equals(scope_item, item);
                    }
                });
                if(!exist) {
                    scope.to_insert.push(item);
                }
            };
            scope.checkClass = function(elem) {
                var found = false;
                angular.forEach(scope.accepts, function(accept) {
                    if(!found) {
                        found = elem.hasClass(accept);
                    }
                });
                return found;
            };
            scope.insertItems = function() {
                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                if(attrs.allowArray) {
                    scope.items = scope.items.concat(scope.to_insert);
                } else {
                    scope.items = scope.to_insert[0];
                }
                delete(scope.ui);
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.changeCallback = function(change) {
                if(change) {
                    scope.insertItems();
                } else {
                    scope.j_ui.draggable('option', 'revert', true);
                }
            };
            scope.dropHanlder = function(event,ui) {
                //get current items from model
                scope.items = ngModelCtrl.$modelValue;
                scope.inserted = false;
                scope.ui = ui;
                scope.j_ui = $(scope.ui.draggable);
                //only process draggable elements
                if(!scope.j_ui.hasClass('ui-draggable')) return;

                //check element class against accepts
                if(!scope.checkClass(scope.j_ui)) {
                    scope.j_ui.draggable('option', 'revert', true);
                    return;
                }
                //get data (string) of dopped element and convert it to an object
                scope.new_item = angular.fromJson(scope.j_ui.attr('item-data'));
                scope.to_insert = [];
                //check for data
                if(!angular.isUndefined(scope.new_item)) {
                    //check for existing items
                    if(angular.isArray(scope.new_item)) {
                        angular.forEach(scope.new_item, scope.checkExist);
                    } else {
                        scope.checkExist(scope.new_item);
                    }
                    //look if something to insert
                    if(scope.to_insert.length > 0) {
                        //run callback if present
                        if(angular.isFunction(scope.change)) {
                            scope.change(scope, {callback: scope.changeCallback, new_data: scope.new_item});
                        } else {
                            scope.insertItems();
                        }
                    } else {
                        scope.j_ui.draggable('option', 'revert', true);
                    }
                }
            }
            if(angular.isUndefined(attrs.accepts)) {
                scope.accepts = [];
            } else {
                scope.accepts = attrs.accepts.split(',');
            }

            //look for callback function
            if(!angular.isUndefined(attrs.changeCallback)) {
                scope.change = $parse(attrs.changeCallback);
            }

            $(element).droppable({
                drop: scope.dropHandler
            });
        }
    };
}).

directive('toggleGroup', function() {
    return {
        restrict: 'E',
        controller: toggleGroupCtrl
    };
}).

directive('toggleElement', function() {
    return {
        restrict: 'A',
        require: '^toggleGroup',
        link: function(scope, element, attrs, toggleGroupCTRL) {
            toggleGroupCTRL.addElement(element);
            $(element).click(function() {
                toggleGroupCTRL.getToggleFunc()(element);
            });
        }
    }
}).

directive('tabs', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: {},
        controller: tabsCtrl,
        template:
            '
' +
            '
' +
            '
'+
            '{{pane.title}}' +
            '
' +
            '
' +
            '

' +
            '
',
        replace: true
    };
}).

directive('pane', function() {
    return {
        require: '^tabs',
        restrict: 'E',
        transclude: true,
        scope: { title: '@' },
        link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
        },
        template:
            '

',
        replace: true
    };
});

/* Controller for directives */

// used by toggleGroup
var toggleGroupCtrl = function($scope, $element) {
    var toggle_elements = [];

    var toToggle = function(element) {
        switch(element.attr('toggle-element')) {
            case 'next':
                return $(element).next();
                break;
            default:
                return $(element);
        }
    };

    this.addElement = function(element) {
        toggle_elements.push(element);
    };
    this.getElementCount = function() {
        return toggle_elements.length;
    };

    this.multiShow = function(element) {
        toToggle(element).toggle();
    };
    this.hideOther = function(element) {
        angular.forEach(toggle_elements, function(t_element) {
            if (t_element == element) {
                toToggle(t_element).show();
            } else {
                toToggle(t_element).hide();
            }
        });
    };
    this.getToggleFunc = function() {
        switch($element.attr('mode')) {
            case 'multiShow':
                return this.multiShow;
                break;
            case 'hideOther':
            default:
                return this.hideOther;
        }
    };
}

// used by tabs
var tabsCtrl = function($scope, $element) {

    this.addPane = function(pane) {
        if (panes.length == 0) $scope.select(pane);
        panes.push(pane);
    };

    $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
            pane.selected = false;
        });
        pane.selected = true;
    };

    var panes = $scope.panes = [];
};
<|endoftext|>


<commit_before>$( document ).ready(function() {
    $('.product-typeahead').typeahead({
        minLength: 3,
        source: function (query, process) {
            return $.getJSON('/app_dev.php/ajax_search/product/'+encodeURIComponent(query), {}, function (data) {
                var resultList = [];
                $.each(data, function(index, value) {
                    if(resultList.indexOf(value.product) == -1) {
                        resultList.push(value.product);
                    }
                });
                return process(resultList);
            });
        }
    });
    $('.area-typeahead').typeahead({
        minLength: 3,
        source: function (query, process) {
            return $.getJSON('/app_dev.php/ajax_search/store/'+encodeURIComponent(query), {}, function (data) {
                var resultList = [];
                $.each(data, function(index, value) {
                    $.each(value.store.split(/[\s\/]+/), function(sindex, svalue) {
                        if(resultList.indexOf(svalue) == -1 && svalue.length > 3) {
                            resultList.push(svalue);
                        }
                    });
                });
                return process(resultList);
            });
        }
    });
});<commit_msg>Remove app_dev calls<commit_after>$( document ).ready(function() {
    $('.product-typeahead').typeahead({
        minLength: 3,
        source: function (query, process) {
            return $.getJSON('/ajax_search/product/'+encodeURIComponent(query), {}, function (data) {
                var resultList = [];
                $.each(data, function(index, value) {
                    if(resultList.indexOf(value.product) == -1) {
                        resultList.push(value.product);
                    }
                });
                return process(resultList);
            });
        }
    });
    $('.area-typeahead').typeahead({
        minLength: 3,
        source: function (query, process) {
            return $.getJSON('/ajax_search/store/'+encodeURIComponent(query), {}, function (data) {
                var resultList = [];
                $.each(data, function(index, value) {
                    $.each(value.store.split(/[\s\/]+/), function(sindex, svalue) {
                        if(resultList.indexOf(svalue) == -1 && svalue.length > 3) {
                            resultList.push(svalue);
                        }
                    });
                });
                return process(resultList);
            });
        }
    });
});<|endoftext|>


<commit_before>gjDesignElements = {
  init:function()
  {
    $('.content > .positions_container')
      .sortable(
      {
        items:'li:not(.placeholder,.content_element_item)',
        axis:'y',
        sort:function(){$(this).removeClass('ui-state-default');},
        update:function(){$(this).find('input[name$=\[position\]]').not('input[name*=\[contents\]]').each(function(i,element){$(element).val(i);});}
      });
  }
}

gjContentElements = {
  init:function()
  {
    $('#design_element_items .positions_container')
      .sortable(
      {
        items:'li:.content_element_item',
        axis:'y',
        sort:function(){$(this).removeClass('ui-state-default');},
        update:function(){$(this).find('input[name$=\[position\]][name*=\[contents\]]').each(function(i,element){$(element).val(i);});}
      });
  }
}

jQuery(document).ready(gjDesignElements.init);
jQuery(document).ready(gjContentElements.init);
<commit_msg>* added design element togglers again<commit_after>gjDesignElements = {
  initDesignElements:function()
  {
    jQuery('.design-elements-head a').click(gjDesignElements.toggleDesignElement);
  },
  toggleDesignElement:function()
  {
    src = jQuery(this).children('img').attr('src');
    src = src.match(/more/) ? src.replace(/more/, 'less') : src.replace(/less/, 'more');
    jQuery(this).children('img').attr('src', src);
    jQuery(this).parent().next('.design-element-include').slideToggle();
  },
  init:function()
  {
    $('.content > .positions_container')
      .sortable(
      {
        items:'li:not(.placeholder,.content_element_item)',
        axis:'y',
        sort:function(){$(this).removeClass('ui-state-default');},
        update:function(){$(this).find('input[name$=\[position\]]').not('input[name*=\[contents\]]').each(function(i,element){$(element).val(i);});}
      });
    gjDesignElements.initDesignElements();
  }
}

gjContentElements = {
  init:function()
  {
    $('#design_element_items .positions_container')
      .sortable(
      {
        items:'li:.content_element_item',
        axis:'y',
        sort:function(){$(this).removeClass('ui-state-default');},
        update:function(){$(this).find('input[name$=\[position\]][name*=\[contents\]]').each(function(i,element){$(element).val(i);});}
      });
  }
}

jQuery(document).ready(gjDesignElements.init);
jQuery(document).ready(gjContentElements.init);
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */

'use strict';

/* globals PDFFindController, FindStates, mozL10n */

/**
 * Creates a "search bar" given set of DOM elements
 * that act as controls for searching, or for setting
 * search preferences in the UI. This object also sets
 * up the appropriate events for the controls. Actual
 * searching is done by PDFFindController
 */
var PDFFindBar = {

  opened: false,
  bar: null,
  toggleButton: null,
  findField: null,
  highlightAll: null,
  caseSensitive: null,
  findMsg: null,
  findStatusIcon: null,
  findPreviousButton: null,
  findNextButton: null,

  initialize: function(options) {
    if(typeof PDFFindController === 'undefined' || PDFFindController === null) {
        throw 'PDFFindBar cannot be initialized ' +
            'without a PDFFindController instance.';
    }

    this.bar = options.bar;
    this.toggleButton = options.toggleButton;
    this.findField = options.findField;
    this.highlightAll = options.highlightAllCheckbox;
    this.caseSensitive = options.caseSensitiveCheckbox;
    this.findMsg = options.findMsg;
    this.findStatusIcon = options.findStatusIcon;
    this.findPreviousButton = options.findPreviousButton;
    this.findNextButton = options.findNextButton;

    var self = this;
    this.toggleButton.addEventListener('click', function() {
      self.toggle();
    });

    this.findField.addEventListener('input', function() {
      self.dispatchEvent('');
    });

    this.bar.addEventListener('keydown', function(evt) {
      switch (evt.keyCode) {
        case 13: // Enter
          if (evt.target === self.findField) {
            self.dispatchEvent('again', evt.shiftKey);
          }
          break;
        case 27: // Escape
          self.close();
          break;
      }
    });

    this.findPreviousButton.addEventListener('click',
      function() { self.dispatchEvent('again', true); }
    );

    this.findNextButton.addEventListener('click', function() {
      self.dispatchEvent('again', false);
    });

    this.highlightAll.addEventListener('click', function() {
      self.dispatchEvent('highlightallchange');
    });

    this.caseSensitive.addEventListener('click', function() {
      self.dispatchEvent('casesensitivitychange');
    });
  },

  dispatchEvent: function(aType, aFindPrevious) {
    var event = document.createEvent('CustomEvent');
    event.initCustomEvent('find' + aType, true, true, {
      query: this.findField.value,
      caseSensitive: this.caseSensitive.checked,
      highlightAll: this.highlightAll.checked,
      findPrevious: aFindPrevious
    });
    return window.dispatchEvent(event);
  },

  updateUIState: function(state, previous) {
    var notFound = false;
    var findMsg = '';
    var status = '';

    switch (state) {
      case FindStates.FIND_FOUND:
        break;

      case FindStates.FIND_PENDING:
        status = 'pending';
        break;

      case FindStates.FIND_NOTFOUND:
        findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
        notFound = true;
        break;

      case FindStates.FIND_WRAPPED:
        if (previous) {
          findMsg = mozL10n.get('find_reached_top', null,
                      'Reached top of document, continued from bottom');
        } else {
          findMsg = mozL10n.get('find_reached_bottom', null,
                                'Reached end of document, continued from top');
        }
        break;
    }

    if (notFound) {
      this.findField.classList.add('notFound');
    } else {
      this.findField.classList.remove('notFound');
    }

    this.findField.setAttribute('data-status', status);
    this.findMsg.textContent = findMsg;
  },

  open: function() {
    if (!this.opened) {
      this.opened = true;
      this.toggleButton.classList.add('toggled');
      this.bar.classList.remove('hidden');
    }

    this.findField.select();
    this.findField.focus();
  },

  close: function() {
    if (!this.opened) return;

    this.opened = false;
    this.toggleButton.classList.remove('toggled');
    this.bar.classList.add('hidden');

    PDFFindController.active = false;
  },

  toggle: function() {
    if (this.opened) {
      this.close();
    } else {
      this.open();
    }
  }
};

<commit_msg>Fix coding style in web/pdf_find_bar.js<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */

'use strict';

/* globals PDFFindController, FindStates, mozL10n */

/**
 * Creates a "search bar" given set of DOM elements
 * that act as controls for searching, or for setting
 * search preferences in the UI. This object also sets
 * up the appropriate events for the controls. Actual
 * searching is done by PDFFindController
 */
var PDFFindBar = {
  opened: false,
  bar: null,
  toggleButton: null,
  findField: null,
  highlightAll: null,
  caseSensitive: null,
  findMsg: null,
  findStatusIcon: null,
  findPreviousButton: null,
  findNextButton: null,

  initialize: function(options) {
    if(typeof PDFFindController === 'undefined' || PDFFindController === null) {
      throw 'PDFFindBar cannot be initialized ' +
            'without a PDFFindController instance.';
    }

    this.bar = options.bar;
    this.toggleButton = options.toggleButton;
    this.findField = options.findField;
    this.highlightAll = options.highlightAllCheckbox;
    this.caseSensitive = options.caseSensitiveCheckbox;
    this.findMsg = options.findMsg;
    this.findStatusIcon = options.findStatusIcon;
    this.findPreviousButton = options.findPreviousButton;
    this.findNextButton = options.findNextButton;

    var self = this;
    this.toggleButton.addEventListener('click', function() {
      self.toggle();
    });

    this.findField.addEventListener('input', function() {
      self.dispatchEvent('');
    });

    this.bar.addEventListener('keydown', function(evt) {
      switch (evt.keyCode) {
        case 13: // Enter
          if (evt.target === self.findField) {
            self.dispatchEvent('again', evt.shiftKey);
          }
          break;
        case 27: // Escape
          self.close();
          break;
      }
    });

    this.findPreviousButton.addEventListener('click',
      function() { self.dispatchEvent('again', true); }
    );

    this.findNextButton.addEventListener('click', function() {
      self.dispatchEvent('again', false);
    });

    this.highlightAll.addEventListener('click', function() {
      self.dispatchEvent('highlightallchange');
    });

    this.caseSensitive.addEventListener('click', function() {
      self.dispatchEvent('casesensitivitychange');
    });
  },

  dispatchEvent: function(aType, aFindPrevious) {
    var event = document.createEvent('CustomEvent');
    event.initCustomEvent('find' + aType, true, true, {
      query: this.findField.value,
      caseSensitive: this.caseSensitive.checked,
      highlightAll: this.highlightAll.checked,
      findPrevious: aFindPrevious
    });
    return window.dispatchEvent(event);
  },

  updateUIState: function(state, previous) {
    var notFound = false;
    var findMsg = '';
    var status = '';

    switch (state) {
      case FindStates.FIND_FOUND:
        break;

      case FindStates.FIND_PENDING:
        status = 'pending';
        break;

      case FindStates.FIND_NOTFOUND:
        findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
        notFound = true;
        break;

      case FindStates.FIND_WRAPPED:
        if (previous) {
          findMsg = mozL10n.get('find_reached_top', null,
                      'Reached top of document, continued from bottom');
        } else {
          findMsg = mozL10n.get('find_reached_bottom', null,
                                'Reached end of document, continued from top');
        }
        break;
    }

    if (notFound) {
      this.findField.classList.add('notFound');
    } else {
      this.findField.classList.remove('notFound');
    }

    this.findField.setAttribute('data-status', status);
    this.findMsg.textContent = findMsg;
  },

  open: function() {
    if (!this.opened) {
      this.opened = true;
      this.toggleButton.classList.add('toggled');
      this.bar.classList.remove('hidden');
    }

    this.findField.select();
    this.findField.focus();
  },

  close: function() {
    if (!this.opened) {
      return;
    }
    this.opened = false;
    this.toggleButton.classList.remove('toggled');
    this.bar.classList.add('hidden');

    PDFFindController.active = false;
  },

  toggle: function() {
    if (this.opened) {
      this.close();
    } else {
      this.open();
    }
  }
};

<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import { Switch } from 'react-router'
import { StaticRouter, HashRouter, BrowserRouter, Route } from 'react-router-dom'
import URL from 'url-parse'
import { Data } from 'react-chunky'
import { createSectionRoutes } from './Router'
import Cache from './Cache'

export default class App extends PureComponent {
  constructor (props) {
    super(props)
    this.state = { loading: true }
    this._menu = []
    this._sidebar = []
    this._cache = new Cache(props)
    this._userLogout = this.userLogout.bind(this)
    this._userLoggedIn = this.userLoggedIn.bind(this)
  }

  componentDidMount () {
    this.checkAuth()
  }

  checkAuth () {
    return new Promise((resolve, reject) => {
      Data.Cache.retrieveAuth()
      .then(account => {
        this._resolve(account)
        resolve()
      })
      .catch((e) => {
        this._resolve()
        resolve()
      })
    })
  }

  get cache () {
    return this._cache
  }

  userLoggedIn (account) {
    return new Promise((resolve, reject) => {
      const user = firebase.auth().currentUser
      const combined = Object.assign({}, {
        uid: user.uid,
        emailVerified: user.emailVerified
      }, account)
      return Data.Cache.cacheAuth({ user: combined }).then(() => resolve(combined))
    })
    .then(() => this.checkAuth())
  }

  userLogout () {
    Data.Cache.clearAuth()
              .then(() => {
                this._resolve()
                firebase && firebase.auth().signOut()
              })
  }

  _resolveTransitionFromURI (uri) {
    const url = new URL(uri, true)
    return {
      name: `show${url.hostname.charAt(0).toUpperCase()}${url.hostname.substring(1).toLowerCase()}`,
      type: url.protocol.slice(0, -1).toLowerCase(),
      route: url.hostname
    }
  }

  _createSectionNavigatorRoutes (element, section) {
    // We want to look at a stack element and figure out its parent chunk;
    // Note that chunks may also have flavours so this looks for the flavor, if any
    const [ chunkName, chunkFlavorName ] = element.split('/')

    // This is our chunk, if it actually exists
    const chunk = this.props.chunks[chunkName]

    if (!chunk) {
      // Let's verify that it actually points to a real chunk
      return
    }

    if (chunkFlavorName && (!chunk.flavors || !chunk.flavors[chunkFlavorName])) {
      // Great, let's check the flavor now
      return
    }

    if (!chunk.routes || chunk.routes.length === 0) {
      // One last thing, let's also make sure the chunk has routes
      return
    }

    // These routes will be the ones we want to parse out of the chunk, as necessary
    var routes = []

    var rootRoute = {}

    // Let's build up global transitions, if any
    var globalTransitions = {}

    if (this.props.transitions) {
      this.props.transitions.forEach(transitionUri => {
          // Let's resolve global transitions
        const transition = this._resolveTransitionFromURI(transitionUri)
        globalTransitions[transition.name] = transition
      })
    }

    for (let routeName in chunk.routes) {
      // Great, this chunk has routes, let's look through all of them
      var route = chunk.routes[routeName]

      if (!route.screen) {
        // This route has no screens
        continue
      }

      if (route.private !== section.private) {
        continue
      }

      const screenId = `${chunkName}/${routeName}`
      const screenPath = route.path || `/${routeName}`
      const routeKey = `${screenId}${screenPath}`
      const routeMenuTitle = ((this.props.desktop && route.desktopTitle) ? route.desktopTitle : route.title)

      if (section.private && route.private) {
        route.sidebarIndex = this.sidebar.length
        this._sidebar.push({
          routeKey,
          id: `${this.sidebar.length}`,
          icon: route.icon,
          title: routeMenuTitle,
          alwaysShowIcon: route.alwaysShowIcon,
          action: route.action,
          path: route.path
        })
      }

      if (Object.keys(rootRoute).length === 0) {
        route.root = true
        route.menuTitle = routeMenuTitle

        rootRoute = Object.assign({}, route)

        // Construct a menu
        if (!route.skipMenu && !route.private && !section.private) {
          var link = `${this.menu.length === 0 ? '/' : route.path}`
          this._menu.push({
            id: `${this.menu.length}`,
            routeKey,
            icon: route.icon.replace('-', '_'),
            title: route.menuTitle,
            alwaysShowIcon: route.alwaysShowIcon,
            action: route.action,
            path: link
          })
          if (route.extendedMenu && !(route.skipExtendedMenuOnDesktop && this.props.desktop)) {
            this._menu = this._menu.concat(route.extendedMenu)
          }
        }
      } else {
        // route.icon = rootRoute.icon
        // route.menuTitle = rootRoute.menuTitle
      }

      // Let's build up the transitions, if any
      var transitions = {}

      if (chunk.transitions) {
        chunk.transitions.forEach(transitionUri => {
          // Parse this transition's URI
          const transition = this._resolveTransitionFromURI(transitionUri)
          const routeData = chunk.routes[transition.route]
          if (transition.route && routeData) {
            // This is a local transition, so let's resolve locally
            transition.data = Object.assign({}, routeData)
            transition.route = `${section.name}/${chunkName}/${transition.route}`
            transitions[transition.name] = transition
            return
          }

          if (globalTransitions[transition.name]) {
            // Let's look through the global transitions, if any
            transitions[transition.name] = Object.assign({}, globalTransitions[transition.name])
          }
        })
      }

      // Let's pass over the theme as well
      const theme = this.props.theme

      // For each route, we want to compose its properties
      const screenProps = Object.assign({
        // Defaults
        cache: this.cache,
        strings: {},
        desktop: this.props.desktop,
        account: section.account,
        env: this.props.env,
        provisioning: this.props.provisioning,
        analytics: this.props.analytics,
        onUserLogout: this._userLogout,
        onUserLoggedIn: this._userLoggedIn,
        info: this.props.info,
        session: this.props.session,
        startOperationsOnMount: true
      }, {
        theme,
        transitions,
        ...route,
        chunkName,
        menu: this.menu,
        sidebar: this.sidebar,
        private: route.private,
        sidebarIndex: route.sidebarIndex
      }, this.props.web)

      // Resolve strings
      var resolvedStrings = {}
      for (const string in screenProps.strings) {
        resolvedStrings[string] = this.props.strings[screenProps.strings[string]] || `??${screenProps.strings[string]}??`
      }
      screenProps.strings = Object.assign({}, this.props.strings, resolvedStrings)

      const ScreenRoute = this._makeScreenRoute(screenPath, screenId, route, screenProps)
      routes.push(ScreenRoute)

      if (route.variants) {
        const ScreenVariantRoute = this._makeScreenRoute(`${screenPath}/:variant`, screenId, route, screenProps)
        routes.push(ScreenVariantRoute)
      }
    }

    // We've got ourselves some routes so we should be done with this
    return routes
  }

  _makeScreenRoute (screenPath, screenId, route, screenProps) {
    const RouteScreen = route.screen
    const Screen = (props) => {
      var skip = false
      if (route.skipPaths) {
        route.skipPaths.forEach(r => {
          if (r === props.location.pathname.split('/')[1]) {
            skip = true
          }
        })
      }

      const allProps = Object.assign({}, props, screenProps, { session: this.props.session })
      return (skip ?
 : <RouteScreen {...allProps} />)
    }

    const routeKey = `${screenId}${screenPath}`

    return <Route
      exact
      refresh
      key={routeKey}
      path={screenPath}
      render={Screen} />
  }

  _createSectionNavigator (section) {
    return createSectionRoutes(section, this._createSectionNavigatorRoutes.bind(this))
  }

  _refreshRoutes (account) {
    this._routes = []
    this._sections = []
    this._menu = []
    this._sidebar = []

    for (const sectionName in this.props.sections) {
      // Look through all the app's sections and for each, build defaults if necessary
      var section = this.props.sections[sectionName]
      section.name = sectionName
      section.account = account
      section.layout = section.layout || 'default'
      section.navigator = this._createSectionNavigator(section)
      this._sections.push(section)
      this._routes = this._routes.concat(section.navigator.routes)
    }
  }

  _resolve (account) {
    this._refreshRoutes(account)
    this.setState({ loading: false, account: account || undefined, authstamp: `${Date.now()}` })
  }

  get menu () {
    return this._menu || {}
  }

  get routes () {
    return this._routes || []
  }

  get sidebar () {
    return this._sidebar || []
  }

  get sections () {
    return this._sections || []
  }

  renderStatic () {
    return (
      <StaticRouter location={this.props.route.location} context={this.props.route}>

          { this.routes }

      </StaticRouter>)
  }

  renderRoutes () {
    return this.routes
  }

  render () {
    if (this.props.route && !this.props.redirect) {
      return this.renderStatic()
    }

    if (!this.routes || this.routes.length === 0) {
      return (
)
    }

    if (this.props.autoRefresh) {
      this._refreshRoutes(this.state.account)
    }

    if (this.props.desktop) {
      return (<HashRouter>
        <Switch>
          { this.renderRoutes() }
        </Switch>
      </HashRouter>)
    }

    return (<BrowserRouter>

        { this.renderRoutes() }

    </BrowserRouter>)
  }
}
<commit_msg>Remove horizontal scroll<commit_after>import React, { PureComponent } from 'react'
import { Switch } from 'react-router'
import { StaticRouter, HashRouter, BrowserRouter, Route } from 'react-router-dom'
import URL from 'url-parse'
import { Data } from 'react-chunky'
import { createSectionRoutes } from './Router'
import Cache from './Cache'

export default class App extends PureComponent {
  constructor (props) {
    super(props)
    this.state = { loading: true }
    this._menu = []
    this._sidebar = []
    this._cache = new Cache(props)
    this._userLogout = this.userLogout.bind(this)
    this._userLoggedIn = this.userLoggedIn.bind(this)
  }

  componentDidMount () {
    this.checkAuth()
  }

  checkAuth () {
    return new Promise((resolve, reject) => {
      Data.Cache.retrieveAuth()
      .then(account => {
        this._resolve(account)
        resolve()
      })
      .catch((e) => {
        this._resolve()
        resolve()
      })
    })
  }

  get cache () {
    return this._cache
  }

  userLoggedIn (account) {
    return new Promise((resolve, reject) => {
      const user = firebase.auth().currentUser
      const combined = Object.assign({}, {
        uid: user.uid,
        emailVerified: user.emailVerified
      }, account)
      return Data.Cache.cacheAuth({ user: combined }).then(() => resolve(combined))
    })
    .then(() => this.checkAuth())
  }

  userLogout () {
    Data.Cache.clearAuth()
              .then(() => {
                this._resolve()
                firebase && firebase.auth().signOut()
              })
  }

  _resolveTransitionFromURI (uri) {
    const url = new URL(uri, true)
    return {
      name: `show${url.hostname.charAt(0).toUpperCase()}${url.hostname.substring(1).toLowerCase()}`,
      type: url.protocol.slice(0, -1).toLowerCase(),
      route: url.hostname
    }
  }

  _createSectionNavigatorRoutes (element, section) {
    // We want to look at a stack element and figure out its parent chunk;
    // Note that chunks may also have flavours so this looks for the flavor, if any
    const [ chunkName, chunkFlavorName ] = element.split('/')

    // This is our chunk, if it actually exists
    const chunk = this.props.chunks[chunkName]

    if (!chunk) {
      // Let's verify that it actually points to a real chunk
      return
    }

    if (chunkFlavorName && (!chunk.flavors || !chunk.flavors[chunkFlavorName])) {
      // Great, let's check the flavor now
      return
    }

    if (!chunk.routes || chunk.routes.length === 0) {
      // One last thing, let's also make sure the chunk has routes
      return
    }

    // These routes will be the ones we want to parse out of the chunk, as necessary
    var routes = []

    var rootRoute = {}

    // Let's build up global transitions, if any
    var globalTransitions = {}

    if (this.props.transitions) {
      this.props.transitions.forEach(transitionUri => {
          // Let's resolve global transitions
        const transition = this._resolveTransitionFromURI(transitionUri)
        globalTransitions[transition.name] = transition
      })
    }

    for (let routeName in chunk.routes) {
      // Great, this chunk has routes, let's look through all of them
      var route = chunk.routes[routeName]

      if (!route.screen) {
        // This route has no screens
        continue
      }

      if (route.private !== section.private) {
        continue
      }

      const screenId = `${chunkName}/${routeName}`
      const screenPath = route.path || `/${routeName}`
      const routeKey = `${screenId}${screenPath}`
      const routeMenuTitle = ((this.props.desktop && route.desktopTitle) ? route.desktopTitle : route.title)

      if (section.private && route.private) {
        route.sidebarIndex = this.sidebar.length
        this._sidebar.push({
          routeKey,
          id: `${this.sidebar.length}`,
          icon: route.icon,
          title: routeMenuTitle,
          alwaysShowIcon: route.alwaysShowIcon,
          action: route.action,
          path: route.path
        })
      }

      if (Object.keys(rootRoute).length === 0) {
        route.root = true
        route.menuTitle = routeMenuTitle

        rootRoute = Object.assign({}, route)

        // Construct a menu
        if (!route.skipMenu && !route.private && !section.private) {
          var link = `${this.menu.length === 0 ? '/' : route.path}`
          this._menu.push({
            id: `${this.menu.length}`,
            routeKey,
            icon: route.icon.replace('-', '_'),
            title: route.menuTitle,
            alwaysShowIcon: route.alwaysShowIcon,
            action: route.action,
            path: link
          })
          if (route.extendedMenu && !(route.skipExtendedMenuOnDesktop && this.props.desktop)) {
            this._menu = this._menu.concat(route.extendedMenu)
          }
        }
      } else {
        // route.icon = rootRoute.icon
        // route.menuTitle = rootRoute.menuTitle
      }

      // Let's build up the transitions, if any
      var transitions = {}

      if (chunk.transitions) {
        chunk.transitions.forEach(transitionUri => {
          // Parse this transition's URI
          const transition = this._resolveTransitionFromURI(transitionUri)
          const routeData = chunk.routes[transition.route]
          if (transition.route && routeData) {
            // This is a local transition, so let's resolve locally
            transition.data = Object.assign({}, routeData)
            transition.route = `${section.name}/${chunkName}/${transition.route}`
            transitions[transition.name] = transition
            return
          }

          if (globalTransitions[transition.name]) {
            // Let's look through the global transitions, if any
            transitions[transition.name] = Object.assign({}, globalTransitions[transition.name])
          }
        })
      }

      // Let's pass over the theme as well
      const theme = this.props.theme

      // For each route, we want to compose its properties
      const screenProps = Object.assign({
        // Defaults
        cache: this.cache,
        strings: {},
        desktop: this.props.desktop,
        account: section.account,
        env: this.props.env,
        provisioning: this.props.provisioning,
        analytics: this.props.analytics,
        onUserLogout: this._userLogout,
        onUserLoggedIn: this._userLoggedIn,
        info: this.props.info,
        session: this.props.session,
        startOperationsOnMount: true
      }, {
        theme,
        transitions,
        ...route,
        chunkName,
        menu: this.menu,
        sidebar: this.sidebar,
        private: route.private,
        sidebarIndex: route.sidebarIndex
      }, this.props.web)

      // Resolve strings
      var resolvedStrings = {}
      for (const string in screenProps.strings) {
        resolvedStrings[string] = this.props.strings[screenProps.strings[string]] || `??${screenProps.strings[string]}??`
      }
      screenProps.strings = Object.assign({}, this.props.strings, resolvedStrings)

      const ScreenRoute = this._makeScreenRoute(screenPath, screenId, route, screenProps)
      routes.push(ScreenRoute)

      if (route.variants) {
        const ScreenVariantRoute = this._makeScreenRoute(`${screenPath}/:variant`, screenId, route, screenProps)
        routes.push(ScreenVariantRoute)
      }
    }

    // We've got ourselves some routes so we should be done with this
    return routes
  }

  _makeScreenRoute (screenPath, screenId, route, screenProps) {
    const RouteScreen = route.screen
    const Screen = (props) => {
      var skip = false
      if (route.skipPaths) {
        route.skipPaths.forEach(r => {
          if (r === props.location.pathname.split('/')[1]) {
            skip = true
          }
        })
      }

      const allProps = Object.assign({}, props, screenProps, { session: this.props.session })
      return (skip ?
 : <RouteScreen {...allProps} />)
    }

    const routeKey = `${screenId}${screenPath}`

    return <Route
      exact
      refresh
      key={routeKey}
      path={screenPath}
      render={Screen} />
  }

  _createSectionNavigator (section) {
    return createSectionRoutes(section, this._createSectionNavigatorRoutes.bind(this))
  }

  _refreshRoutes (account) {
    this._routes = []
    this._sections = []
    this._menu = []
    this._sidebar = []

    for (const sectionName in this.props.sections) {
      // Look through all the app's sections and for each, build defaults if necessary
      var section = this.props.sections[sectionName]
      section.name = sectionName
      section.account = account
      section.layout = section.layout || 'default'
      section.navigator = this._createSectionNavigator(section)
      this._sections.push(section)
      this._routes = this._routes.concat(section.navigator.routes)
    }
  }

  _resolve (account) {
    this._refreshRoutes(account)
    this.setState({ loading: false, account: account || undefined, authstamp: `${Date.now()}` })
  }

  get menu () {
    return this._menu || {}
  }

  get routes () {
    return this._routes || []
  }

  get sidebar () {
    return this._sidebar || []
  }

  get sections () {
    return this._sections || []
  }

  renderStatic () {
    return (
      <StaticRouter location={this.props.route.location} context={this.props.route}>

          { this.routes }

      </StaticRouter>)
  }

  renderRoutes () {
    return this.routes
  }

  render () {
    if (this.props.route && !this.props.redirect) {
      return this.renderStatic()
    }

    if (!this.routes || this.routes.length === 0) {
      return (
)
    }

    if (this.props.autoRefresh) {
      this._refreshRoutes(this.state.account)
    }

    if (this.props.desktop) {
      return (<HashRouter>
        <Switch>
          { this.renderRoutes() }
        </Switch>
      </HashRouter>)
    }

    return (<BrowserRouter>

        { this.renderRoutes() }

    </BrowserRouter>)
  }
}
<|endoftext|>


<commit_before><commit_msg>30spin<commit_after><|endoftext|>


<commit_before>function createProcessGraphs(json_data)
{
	var graphs = ["bets", "elo", "spi", "fifa", "value"];
	var max_day = 32;
	var labels = [];
	for (var i = 0; i < max_day + 1; ++i)
	{
		var day = (12 + i - 1) % 30 + 1;
		var mon = Math.floor((12 + i - 1) / 30) + 6;
		if (i == 0 || day == 1 || i == max_day)
			mon = mon.toString() + ".";
		else
		{
			mon = "";
		}
		labels.push(day.toString() + "." + mon);
	}
	var colorstep = 360 / json_data.length;
	var legend = false;

	for (var i = 0; i < graphs.length; ++i)
	{
		var data = {
			labels : labels,
			datasets : []
		};

		for (var team_index = 0; team_index < json_data.length; ++team_index)
		{
			var team = json_data[team_index];
			var series = team[graphs[i]];
			if (!series)
				series = []
			var clr = ((colorstep * team_index + 120) % 360).toString();
			var l = 100;
			if (team_index % 2 == 0) l = 50;
			data.datasets.push({
				data: series,
				strokeColor : "hsla(" + clr + ",100%," + (l)/100 + "%,0.5)",
				pointColor : "hsla(" + clr + ",75%," + (75*l)/100 + "%,0.5)",
				pointStrokeColor : "hsla(" + clr + ",100%," + (75*l)/100 + "%,0.5)",
				title: team.name
				});
		}

		$("#" + graphs[i]).replaceWith('<canvas id="' + graphs[i] + '" width="600" height="100"></canvas>');
		$("#" + graphs[i]).attr("width", $("#graph_" + graphs[i]).width());
		var ctx = document.getElementById(graphs[i]).getContext("2d");
		var chart = new Chart(ctx).Line(data, {datasetFill : false});

		if (!legend)
		{
			legend = true;
			var legend_div = $("#graph_legend");
			legend_div.empty();
			for (var t = 0; t < data.datasets.length; ++t)
			{
				var info = data.datasets[t];
				legend_div.append(
				'
'
				+ info.title + '
'
				);
			}
		}
	}
}
<commit_msg>frontend: made ticker colours a little bit stronger for better visibility<commit_after>function createProcessGraphs(json_data)
{
	var graphs = ["bets", "elo", "spi", "fifa", "value"];
	var max_day = 32;
	var labels = [];
	for (var i = 0; i < max_day + 1; ++i)
	{
		var day = (12 + i - 1) % 30 + 1;
		var mon = Math.floor((12 + i - 1) / 30) + 6;
		if (i == 0 || day == 1 || i == max_day)
			mon = mon.toString() + ".";
		else
		{
			mon = "";
		}
		labels.push(day.toString() + "." + mon);
	}
	var colorstep = 360 / json_data.length;
	var legend = false;

	for (var i = 0; i < graphs.length; ++i)
	{
		var data = {
			labels : labels,
			datasets : []
		};

		for (var team_index = 0; team_index < json_data.length; ++team_index)
		{
			var team = json_data[team_index];
			var series = team[graphs[i]];
			if (!series)
				series = []
			var clr = ((colorstep * team_index + 120) % 360).toString();
			var l = 100;
			if (team_index % 2 == 0) l = 50;
			data.datasets.push({
				data: series,
				strokeColor : "hsla(" + clr + ",100%," + (50*l)/100 + "%,1.0)",
				pointColor : "hsla(" + clr + ",75%," + (75*l)/100 + "%,1.0)",
				pointStrokeColor : "hsla(" + clr + ",100%," + (75*l)/100 + "%,1.0)",
				title: team.name
				});
		}

		$("#" + graphs[i]).replaceWith('<canvas id="' + graphs[i] + '" width="600" height="100"></canvas>');
		$("#" + graphs[i]).attr("width", $("#graph_" + graphs[i]).width());
		var ctx = document.getElementById(graphs[i]).getContext("2d");
		var chart = new Chart(ctx).Line(data, {datasetFill : false});

		if (!legend)
		{
			legend = true;
			var legend_div = $("#graph_legend");
			legend_div.empty();
			for (var t = 0; t < data.datasets.length; ++t)
			{
				var info = data.datasets[t];
				legend_div.append(
				'
'
				+ info.title + '
'
				);
			}
		}
	}
}
<|endoftext|>