<commit_before>function FC4()
		{
			var x = document.getElementById("num").value;
			var numlist = "";
			for (i=1; i<=Math.sqrt(x); i++)
			{
				if (x % i == 0)
				{
					numlist=numlist.concat(String(i), "
", String(x/i), "
-------------------
");
				}
			}
			numlist=numlist.concat("
")
			document.getElementById("output").innerHTML=numlist;
		}

function FC5()
		{
			var x = document.getElementById("num").value;
			x = x.toFixed(Math.floor(Math.log10(x)));
			var numlist = [1];
			while (x-1)
			{
				f = findFactor(x);
				x /= f;
				numlist+=numlist.map(numlist*3);
				numlist=Array.from(Set(numlist));
			}
			numlist.sort(function(a, b){return a-b});
			numlist=numlist.join("
").concat("
");
			document.getElementById("output").innerHTML=numlist;

			function findFactor(n)
				{
    					for (d=2; d<=Math.ceil(n.toFixed(Math.log10(n)).sqrt()); d++)
    					{
       						if (n % d == 0):
       						{
            						return(d);
       						}
    					}
    					return(n);
				}
		}

function BC()
		{
			var num = document.getElementById("num").value;
			var b1 = document.getElementById("b1").value;
			var b2 = document.getElementById("b2").value;
			document.getElementById("output").innerHTML=parseInt(num, b1).toString(b2);
		}

function TR()
		{
			var o = document.getElementById("num").value;
			var deg = document.getElementById("deg").checked;
			if (deg!=1)
			{
				var pi = document.getElementById("pi?").checked;
				if (pi==1) // If angle is in terms if pi...
				{
					o *= Math.atan(1)*4;
				}
			}
			else
			{
				o *= Math.atan(1)*4/180;
			}
			k = 1000
			output = 	"sin = "+String(Math.round(Math.sin(o)*k)/k)+"
"+
						"cos = "+String(Math.round(Math.cos(o)*k)/k)+"
"+
						"tan = "+String(Math.round(Math.tan(o)*k)/k)+"
"+
						"csc = "+String(Math.round(1/Math.sin(o)*k)/k)+"
"+
						"sec = "+String(Math.round(1/Math.cos(o)*k)/k)+"
"+
						"cot = "+String(Math.round(1/Math.tan(o)*k)/k)+"
";
			document.getElementById("output").innerHTML=output;
		}
function degr()
		{
			document.getElementById("pi").innerHTML="";
			return 0;
		}
function radi()
		{
			document.getElementById("pi").innerHTML='Is it in terms of pi?
<input type="radio" name="pi" value="1" id="pi?">Yes / <input type="radio" name="pi" value="0" id="nopi">No
';
			return 0;
		}
<commit_msg>Update StarMath.js<commit_after>function FC4()
		{
			var x = document.getElementById("num").value;
			var numlist = "";
			for (i=1; i<=Math.sqrt(x); i++)
			{
				if (x % i == 0)
				{
					numlist=numlist.concat(String(i), "
", String(x/i), "
-------------------
");
				}
			}
			numlist=numlist.concat("
")
			document.getElementById("output").innerHTML=numlist;
		}

function FC5()
		{
			var x = document.getElementById("num").value;
			x = x.toFixed(Math.floor(Math.log10(x)));
			var numlist = [1];
			while (x-1)
			{
				f = findFactor(x);
				x /= f;
				numlist+=numlist.map(numlist*3);
				numlist=Array.from(Set(numlist));
			}
			numlist.sort(function(a, b){return a-b});
			numlist=numlist.join("
").concat("
");
			document.getElementById("output").innerHTML=numlist;

			function findFactor(n)
				{
    					for (d=2; d<=Math.ceil(n.toFixed(Math.log10(n)).sqrt()); d++)
    					{
       						if (n % d == 0)
       						{
            						return(d);
       						}
    					}
    					return(n);
				}
		}

function BC()
		{
			var num = document.getElementById("num").value;
			var b1 = document.getElementById("b1").value;
			var b2 = document.getElementById("b2").value;
			document.getElementById("output").innerHTML=parseInt(num, b1).toString(b2);
		}

function TR()
		{
			var o = document.getElementById("num").value;
			var deg = document.getElementById("deg").checked;
			if (deg!=1)
			{
				var pi = document.getElementById("pi?").checked;
				if (pi==1) // If angle is in terms if pi...
				{
					o *= Math.atan(1)*4;
				}
			}
			else
			{
				o *= Math.atan(1)*4/180;
			}
			k = 1000
			output = 	"sin = "+String(Math.round(Math.sin(o)*k)/k)+"
"+
						"cos = "+String(Math.round(Math.cos(o)*k)/k)+"
"+
						"tan = "+String(Math.round(Math.tan(o)*k)/k)+"
"+
						"csc = "+String(Math.round(1/Math.sin(o)*k)/k)+"
"+
						"sec = "+String(Math.round(1/Math.cos(o)*k)/k)+"
"+
						"cot = "+String(Math.round(1/Math.tan(o)*k)/k)+"
";
			document.getElementById("output").innerHTML=output;
		}
function degr()
		{
			document.getElementById("pi").innerHTML="";
			return 0;
		}
function radi()
		{
			document.getElementById("pi").innerHTML='Is it in terms of pi?
<input type="radio" name="pi" value="1" id="pi?">Yes / <input type="radio" name="pi" value="0" id="nopi">No
';
			return 0;
		}
<|endoftext|>


<commit_before>define('require-config',[], function() {
  "use strict";

  console.log('require-config.');

  require.config({
    baseUrl: './static'
  });

  return {
    "paths": {
      "txt": "libs/require/plugins/text",
      "css": "libs/require/plugins/css",
      "jquery": "libs/jquery/jquery-2.1.0.min",
      "jquery.autosize": "libs/jquery/plugins/jquery.autosize.min",
      "bootstrap": "libs/bootstrap/bootstrap-3.1.1.min",
      "bootstrap.mods": "mods/bootstrap.mods",
      "bootbox": "libs/bootbox/bootbox.min",
      "underscore": "libs/underscore/underscore-1.6.0.min",
      "backbone": "libs/backbone/backbone-1.1.2.min",
      "sha256": "libs/movabletype/sha256",
      "aes": "libs/movabletype/aes",
      "add2home": "libs/add2home/add2home",
      "dropbox": "libs/dropbox/dropbox-0.10.2",
      "ace": "libs/ace/ace-1.1.3",
    },
    "shim": {
      "jquery": ["globals/console"],
      "jquery.autosize": ["jquery"],
      "backbone": ["underscore", "jquery"],
      "bootstrap": ["jquery"],
      "bootstrap.mods": ["bootstrap"],
    }
  };
});
<commit_msg>Update require-config.js<commit_after>define('require-config',[], function() {
  "use strict";

  console.log('require-config.');

  require.config({
    baseUrl: './static'
  });

  return {
    "paths": {
      "txt": "libs/require/plugins/text",
      "css": "libs/require/plugins/css",
      "jquery": "libs/jquery/jquery-2.1.0.min",
      "jquery.autosize": "libs/jquery/plugins/jquery.autosize.min",
      "bootstrap": "libs/bootstrap/bootstrap-3.1.1.min",
      "bootstrap.mods": "mods/bootstrap.mods",
      "bootbox": "libs/bootbox/bootbox.min",
      "underscore": "libs/underscore/underscore-1.6.0.min",
      "backbone": "libs/backbone/backbone-1.1.2.min",
      "sha256": "libs/movabletype/sha256",
      "aes": "libs/movabletype/aes",
      "add2home": "libs/add2home/add2home",
      "dropbox": "libs/dropbox/dropbox-0.10.2",
      "ace": "libs/ace/ace-1.1.3",
    },
    "shim": {
      "jquery": ["globals/console"],
      "jquery.autosize": ["jquery"],
      "backbone": ["underscore", "jquery"],
      "bootstrap": ["jquery"],
      "bootstrap.mods": ["bootstrap"],
      "ace": ["jquery"],
    }
  };
});
<|endoftext|>


<commit_before>import assert from 'assert'
import gpuMock from 'gpu-mock.js'
import {
  predict,
  compareBiases,
  compareFilterDeltas,
  compareInputDeltas,
} from '../../src/layer/fully-connected'

describe('FullyConnected Layer', () => {
  describe('.predict (forward propagation)', () => {
    it('can predict a simple matrix', () => {
      const weights = [
        [1,3],
        [2,4],
      ]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16],
      ]
      const biases = [0.2,0.2,0.2,0.2]
      const kernel = gpuMock(predict, {
        output: [4],
        constants: {
          inputDepth: 1,
          inputHeight: 2,
          inputWidth: 2,
        },
      })
      assert.deepEqual(kernel(weights, filters, biases), [29.2, 69.2, 109.2, 149.2])
    })
    it('can predict a matrix', () => {
      const results = gpuMock(predict, {
        output: [9],
        constants: {
          inputDepth: 1,
          inputHeight: 1,
          inputWidth: 9,
        },
      })(
        [[0, 1, 2, 3, 4, 5, 6, 7, 8]],
        [
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
        ],
        [0, 1, 2, 3, 4, 5, 6, 7, 8]
      )
      assert.deepEqual(results, [204, 205, 206, 207, 208, 209, 210, 211, 212])
    })
  })

  describe('.compareBiases (back propagation)', () => {
    it('can compare a simple matrix', () => {
      const biases = [[0,0,0,0]]
      const deltas = [[1,2,3,4]]
      const kernel = gpuMock(compareBiases, {
        output: [4],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(biases, deltas), [1,2,3,4])
    })
    it('can add a simple matrix', () => {
      const biases = [[1,2,3,4]]
      const deltas = [[1,2,3,4]]
      const kernel = gpuMock(compareBiases, {
        output: [4],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(biases, deltas), [2,4,6,8])
    })
  })

  describe('.compareFilterDeltas (back propagation)', () => {
    it('can compare a simplge matrix', () => {
      const inputWeights = [
        [1,3],
        [2,4]
      ]
      const deltas = [[1,2,3,4]]
      const filterDeltas = [
        [0,0,0,0],
        [0,0,0,0],
        [0,0,0,0],
        [0,0,0,0],
      ]
      const kernel = gpuMock(compareFilterDeltas, {
        output: [4,4],
        constants: {
          inputWidth: 2
        },
      })
      assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [
        [1,3,2,4],
        [2,6,4,8],
        [3,9,6,12],
        [4,12,8,16]
      ])
    })
    it('can add a simplge matrix', () => {
      const inputWeights = [
        [1,3],
        [2,4]
      ]
      const deltas = [[1,2,3,4]]
      const filterDeltas = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareFilterDeltas, {
        output: [4,4],
        constants: {
          inputWidth: 2
        },
      })
      assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [
        [2, 5, 5, 8],
        [7, 12, 11, 16],
        [12, 19, 17, 24],
        [17, 26, 23, 32]
      ])
    })
  })

  describe('.compareInputDeltas (back propagation)', () => {
    it('can compare a simple matrix', () => {
      const inputDeltas = [
        [0,0],
        [0,0]
      ]
      const deltas = [[1,2,3,4]]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareInputDeltas, {
        output: [2,2],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(inputDeltas, deltas, filters), [[90, 100], [110, 120]])
    })
    it('can add a simple matrix', () => {
      const inputDeltas = [
        [1,3],
        [2,4]
      ]
      const deltas = [[1,2,3,4]]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareInputDeltas, {
        output: [2,2],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(inputDeltas, deltas, filters), [[91, 103], [112, 124]])
    })
  })
})
<commit_msg>Make FullyConnected tests more incremental<commit_after>import assert from 'assert'
import gpuMock from 'gpu-mock.js'
import {
  predict,
  compareBiases,
  compareFilterDeltas,
  compareInputDeltas,
} from '../../src/layer/fully-connected'

describe('FullyConnected Layer', () => {
  describe('.predict (forward propagation)', () => {
    it('can predict a simple matrix', () => {
      const weights = [
        [1,3],
        [2,4],
      ]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16],
      ]
      const biases = [0.2,0.2,0.2,0.2]
      const kernel = gpuMock(predict, {
        output: [4],
        constants: {
          inputDepth: 1,
          inputHeight: 2,
          inputWidth: 2,
        },
      })
      assert.deepEqual(kernel(weights, filters, biases), [29.2, 69.2, 109.2, 149.2])
    })
    it('can predict a matrix', () => {
      const results = gpuMock(predict, {
        output: [9],
        constants: {
          inputDepth: 1,
          inputHeight: 1,
          inputWidth: 9,
        },
      })(
        [[0, 1, 2, 3, 4, 5, 6, 7, 8]],
        [
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
          [0, 1, 2, 3, 4, 5, 6, 7, 8],
        ],
        [0, 1, 2, 3, 4, 5, 6, 7, 8]
      )
      assert.deepEqual(results, [204, 205, 206, 207, 208, 209, 210, 211, 212])
    })
  })

  describe('.compareBiases (back propagation)', () => {
    it('can compare a simple matrix', () => {
      const biases = [[0,0,0,0]]
      const deltas = [[1,2,3,4]]
      const kernel = gpuMock(compareBiases, {
        output: [4],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(biases, deltas), [1,2,3,4])
    })
    it('can add a simple matrix', () => {
      const biases = [[1,2,3,4]]
      const deltas = [[1,2,3,4]]
      const kernel = gpuMock(compareBiases, {
        output: [4],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(biases, deltas), [2,4,6,8])
    })
  })

  describe('.compareFilterDeltas (back propagation)', () => {
    it('can compare a simplge matrix', () => {
      const inputWeights = [
        [1,2],
        [3,4]
      ]
      const deltas = [[1,2,3,4]]
      const filterDeltas = [
        [0,0,0,0],
        [0,0,0,0],
        [0,0,0,0],
        [0,0,0,0],
      ]
      const kernel = gpuMock(compareFilterDeltas, {
        output: [4,4],
        constants: {
          inputWidth: 2
        },
      })
      assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [
        [1,2,3,4],
        [2,4,6,8],
        [3,6,9,12],
        [4,8,12,16]
      ])
    })
    it('can add a simplge matrix', () => {
      const inputWeights = [
        [1,2],
        [3,4]
      ]
      const deltas = [[1,2,3,4]]
      const filterDeltas = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareFilterDeltas, {
        output: [4,4],
        constants: {
          inputWidth: 2
        },
      })
      assert.deepEqual(kernel(filterDeltas, inputWeights, deltas), [
        [2, 4, 6, 8],
        [7, 10, 13, 16],
        [12, 16, 20, 24],
        [17, 22, 27, 32]
      ])
    })
  })

  describe('.compareInputDeltas (back propagation)', () => {
    it('can compare a simple matrix', () => {
      const inputDeltas = [
        [0,0],
        [0,0]
      ]
      const deltas = [[1,2,3,4]]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareInputDeltas, {
        output: [2,2],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(inputDeltas, deltas, filters), [[90, 100], [110, 120]])
    })
    it('can add a simple matrix', () => {
      const inputDeltas = [
        [1,2],
        [3,4]
      ]
      const deltas = [[1,2,3,4]]
      const filters = [
        [1,2,3,4],
        [5,6,7,8],
        [9,10,11,12],
        [13,14,15,16]
      ]
      const kernel = gpuMock(compareInputDeltas, {
        output: [2,2],
        constants: {
          connectionCount: 4
        },
      })
      assert.deepEqual(kernel(inputDeltas, deltas, filters), [[91, 102], [113, 124]])
    })
  })
})
<|endoftext|>


<commit_before>// --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.Agent = Core.Agent || {};

/**
 * @namespace Core.Agent.Statistics
 * @memberof Core.Agent
 * @author OTRS AG
 * @description
 *      This namespace contains the special module functions for the Statistics module.
 */
Core.Agent.Statistics = (function (TargetNS) {

    /**
     * @name InitAddScreen
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      Initialize the add screen. Contains basically some logic to react on which
     *      of the big select buttons the agent uses. Afterwards, the specification widget
     *      is being loaded according to the clicked button.
     */
    TargetNS.InitAddScreen = function () {

        $('.BigButtons a').on('click', function () {
            var $Link = $(this);

            if ($Link.hasClass('Disabled')) {
                return false;
            }

            $('.BigButtons a').removeClass('Active');
            $Link.addClass('Active');

            $('#GeneralSpecifications').fadeIn(function() {
                var URL = Core.Config.Get('Baselink'),
                    Data = {
                        Action: 'AgentStatistics',
                        Subaction: 'GeneralSpecificationsWidgetAJAX',
                        StatisticPreselection: $Link.data('statistic-preselection')
                    };

                $('#GeneralSpecifications .Content').addClass('Center').html('');
                $('#SaveWidget').hide();

                Core.AJAX.FunctionCall(URL, Data, function(Response) {
                    $('#GeneralSpecifications .Content').removeClass('Center').html(Response);
                    Core.UI.InputFields.Activate($('#GeneralSpecifications .Content'));
                    $('#SaveWidget').show();
                }, 'html');
            });

            return false;
        });
    };

    TargetNS.ElementAdd = function(ConfigurationType, ElementName) {
        var $ContainerElement = $('#' + ConfigurationType + 'Container'),
            $FormFieldsElement = $('#' + ConfigurationType + 'FormFields'),
            $ContainerElementClone = $ContainerElement.find('.Element' + Core.App.EscapeSelector(ElementName)).clone();

        $ContainerElementClone.find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id").replace(/_orig/, '_selected'));
        });
        $ContainerElementClone.appendTo($FormFieldsElement);
    };

    /**
     * @name InitEditScreen
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      Initialize the edit screen.
     */
    TargetNS.InitEditScreen = function() {
        $('button.EditXAxis, button.EditYAxis, button.EditRestrictions').on('click', function() {
            var ConfigurationType = $(this).data('configuration-type'),
                ConfigurationLimit = $(this).data('configuration-limit'),
                DialogTitle = $(this).data('dialog-title'),
                $ContainerElement = $('#' + ConfigurationType + 'Container'),
                $FormFieldsElement = $('#' + ConfigurationType + 'FormFields'),
                $CloneFormFieldsElement;

            function RebuildEditDialogAddSelection() {
                $('#EditDialog .Add select').empty().append('<option>-</option>');
                $.each($ContainerElement.find('.Element'), function() {
                    var $Element = $(this),
                        ElementName = $Element.data('element');

                    if ($('#EditDialog .Fields .Element' + Core.App.EscapeSelector(ElementName)).length) {
                        return;
                    }

                    $($.parseHTML('<option></option>')).val(ElementName)
                        .text($Element.find('> legend > span').text().replace(/:\s*$/, ''))
                        .appendTo('#EditDialog .Add select');
                });
            }

            function EditDialogAdd(ElementName) {
                var $ElementClone = $ContainerElement.find('.Element' + Core.App.EscapeSelector(ElementName)).clone();

                // Remove the postfix from the IDs to get the real ids for the fields.
                $ElementClone.find("*[id]").each(function() {
                    $(this).attr("id", $(this).attr("id").replace(/_orig/, ''));
                });
                $ElementClone.appendTo($('#EditDialog .Fields'));

                if (ConfigurationLimit && $('#EditDialog .Fields .Element').length >= ConfigurationLimit) {
                    $('#EditDialog .Add').hide();
                }
                RebuildEditDialogAddSelection();
                Core.UI.InputFields.Activate($('#EditDialog .Fields'));
            }

            function EditDialogDelete(ElementName) {
                $('#EditDialog .Fields .Element' + Core.App.EscapeSelector(ElementName)).remove();
                $('#EditDialog .Add').show();
                RebuildEditDialogAddSelection();
            }

            function EditDialogSave() {
                $FormFieldsElement.empty();
                $('#EditDialog .Fields').children().appendTo($FormFieldsElement);
                Core.UI.Dialog.CloseDialog($('.Dialog'));
                $('form.StatsEditForm').submit();
            }

            function EditDialogCancel() {
                Core.UI.Dialog.CloseDialog($('.Dialog'));
            }

            Core.UI.Dialog.ShowContentDialog(
                '

',
                DialogTitle,
                100,
                'Center',
                true,
                [
                    { Label: Core.Language.Translate('Save'), Class: 'Primary', Type: '', Function: EditDialogSave },
                    { Label: Core.Language.Translate('Cancel'), Class: '', Type: 'Close', Function: EditDialogCancel }
                ],
                true
            );
            $('#EditDialogTemplate').children().clone().appendTo('#EditDialog');

            if ($FormFieldsElement.children().length) {
                $CloneFormFieldsElement = $FormFieldsElement.children().clone()
                $CloneFormFieldsElement.find("*[id]").each(function() {
                    $(this).attr("id", $(this).attr("id").replace(/_selected/, ''));
                });
                $CloneFormFieldsElement.appendTo('#EditDialog .Fields');

                Core.UI.InputFields.Activate($('#EditDialog .Fields'));
                if (ConfigurationLimit && $('#EditDialog .Fields .Element').length >= ConfigurationLimit) {
                    $('#EditDialog .Add').hide();
                }
            }
            else {
                $('#EditDialog .Add').show();
            }
            RebuildEditDialogAddSelection();

            $('#EditDialog .Add select').on('change', function(){
                EditDialogAdd($(this).val());
            });

            $('#EditDialog .Fields').on('click', '.RemoveButton', function(){
                EditDialogDelete($(this).parents('.Element').data('element'));
                return false;
            });

            // Selection helpers for time fields
            $('#EditDialog .Fields .ElementBlockTime .Field select').on('change', function() {
                $(this).parent('.Field').prev('label').find('input:radio').prop('checked', true);
            });

            Core.UI.TreeSelection.InitTreeSelection();

            // Datepickers don't work if added dynamically atm, so hide for now.
            $('a.DatepickerIcon').hide();

            return false;
        });

       $('.SwitchPreviewFormat').on('click', function() {
            var Format = $(this).data('format'),
                FormatCleaned = Format.replace('::', ''),
                StatsPreviewResult;

            StatsPreviewResult = Core.Data.CopyObject(Core.Config.Get('PreviewResult'));
            $('.SwitchPreviewFormat').removeClass('Active');
            $(this).addClass('Active');
            $('.PreviewContent:visible').hide();
            $('svg.PreviewContent').empty();
            $('#PreviewContent' + FormatCleaned).show();
            if (Format.match(/D3/)) {
                Core.UI.AdvancedChart.Init(
                    Format,
                    StatsPreviewResult,
                    'svg#PreviewContent' + FormatCleaned,
                    {
                        HideLegend: true
                    }
                );
            }
            return false;
        });
        $('.SwitchPreviewFormat').first().trigger('click');
    }

    /**
     * @name Init
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      This function initializes the module functionality.
     */
    TargetNS.Init = function () {
        var RestrictionElements,
            XAxisElements,
            YAxisElements,
            D3Data;

        // Set a postfix to the ids in the hidden container,
        //  because the fields will be cloned in the overlay.
        $('#XAxisContainer').find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id") + "_orig");
        });
        $('#YAxisContainer').find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id") + "_orig");
        });
        $('#RestrictionsContainer').find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id") + "_orig");
        });

        // Initialize the Add screen
        TargetNS.InitAddScreen();

        // Initialize the Edit screen
        TargetNS.InitEditScreen();

        // Bind event on delete stats button
        $('.StatDelete').on('click', function (Event) {
            var ConfirmText = '"' + $(this).data('stat-title') + '"\n\n' + Core.Language.Translate("Do you really want to delete this statistic?");
            if (!window.confirm(ConfirmText)) {
                Event.stopPropagation();
                Event.preventDefault();
                return false;
            }
        });

        // Bind event on start stats button
        $('#StartStatistic').on('click', function () {
            var Format = $('#Format').val(),
                $Form = $(this).parents('form');

            // Open both HTML and PDF output in a popup because PDF is shown inline
            if (Format === 'Print' || Format.match(/D3/)) {
                $Form.attr('target', '_blank');
            }
            else {
                $Form.removeAttr('target');
            }
        });

        RestrictionElements = Core.Config.Get('RestrictionElements');
        if (typeof RestrictionElements !== 'undefined') {
            $.each(RestrictionElements, function() {
                TargetNS.ElementAdd('Restrictions', this);
            });
        }

        XAxisElements = Core.Config.Get('XAxisElements');
        if (typeof XAxisElements !== 'undefined') {
            $.each(XAxisElements, function() {
                TargetNS.ElementAdd('XAxis', this);
            });
        }

        YAxisElements = Core.Config.Get('YAxisElements');
        if (typeof YAxisElements !== 'undefined') {
            $.each(YAxisElements, function() {
                TargetNS.ElementAdd('YAxis', this);
            });
        }

        D3Data = Core.Config.Get('D3Data');
        if (typeof D3Data !== 'undefined') {
            Core.UI.AdvancedChart.Init(
                D3Data.Format,
                D3Data.RawData,
                'svg#ChartContent',
                {
                    Duration: 250
                }
            );
        }
    };

    Core.Init.RegisterNamespace(TargetNS, 'APP_MODULE');

    return TargetNS;
}(Core.Agent.Statistics || {}));
<commit_msg>Small code style improvement.<commit_after>// --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.Agent = Core.Agent || {};

/**
 * @namespace Core.Agent.Statistics
 * @memberof Core.Agent
 * @author OTRS AG
 * @description
 *      This namespace contains the special module functions for the Statistics module.
 */
Core.Agent.Statistics = (function (TargetNS) {

    /**
     * @name InitAddScreen
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      Initialize the add screen. Contains basically some logic to react on which
     *      of the big select buttons the agent uses. Afterwards, the specification widget
     *      is being loaded according to the clicked button.
     */
    TargetNS.InitAddScreen = function () {

        $('.BigButtons a').on('click', function () {
            var $Link = $(this);

            if ($Link.hasClass('Disabled')) {
                return false;
            }

            $('.BigButtons a').removeClass('Active');
            $Link.addClass('Active');

            $('#GeneralSpecifications').fadeIn(function() {
                var URL = Core.Config.Get('Baselink'),
                    Data = {
                        Action: 'AgentStatistics',
                        Subaction: 'GeneralSpecificationsWidgetAJAX',
                        StatisticPreselection: $Link.data('statistic-preselection')
                    };

                $('#GeneralSpecifications .Content').addClass('Center').html('');
                $('#SaveWidget').hide();

                Core.AJAX.FunctionCall(URL, Data, function(Response) {
                    $('#GeneralSpecifications .Content').removeClass('Center').html(Response);
                    Core.UI.InputFields.Activate($('#GeneralSpecifications .Content'));
                    $('#SaveWidget').show();
                }, 'html');
            });

            return false;
        });
    };

    TargetNS.ElementAdd = function(ConfigurationType, ElementName) {
        var $ContainerElement = $('#' + ConfigurationType + 'Container'),
            $FormFieldsElement = $('#' + ConfigurationType + 'FormFields'),
            $ContainerElementClone = $ContainerElement.find('.Element' + Core.App.EscapeSelector(ElementName)).clone();

        $ContainerElementClone.find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id").replace(/_orig/, '_selected'));
        });
        $ContainerElementClone.appendTo($FormFieldsElement);
    };

    /**
     * @name InitEditScreen
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      Initialize the edit screen.
     */
    TargetNS.InitEditScreen = function() {
        $('button.EditXAxis, button.EditYAxis, button.EditRestrictions').on('click', function() {
            var ConfigurationType = $(this).data('configuration-type'),
                ConfigurationLimit = $(this).data('configuration-limit'),
                DialogTitle = $(this).data('dialog-title'),
                $ContainerElement = $('#' + ConfigurationType + 'Container'),
                $FormFieldsElement = $('#' + ConfigurationType + 'FormFields'),
                $CloneFormFieldsElement;

            function RebuildEditDialogAddSelection() {
                $('#EditDialog .Add select').empty().append('<option>-</option>');
                $.each($ContainerElement.find('.Element'), function() {
                    var $Element = $(this),
                        ElementName = $Element.data('element');

                    if ($('#EditDialog .Fields .Element' + Core.App.EscapeSelector(ElementName)).length) {
                        return;
                    }

                    $($.parseHTML('<option></option>')).val(ElementName)
                        .text($Element.find('> legend > span').text().replace(/:\s*$/, ''))
                        .appendTo('#EditDialog .Add select');
                });
            }

            function EditDialogAdd(ElementName) {
                var $ElementClone = $ContainerElement.find('.Element' + Core.App.EscapeSelector(ElementName)).clone();

                // Remove the postfix from the IDs to get the real ids for the fields.
                $ElementClone.find("*[id]").each(function() {
                    $(this).attr("id", $(this).attr("id").replace(/_orig/, ''));
                });
                $ElementClone.appendTo($('#EditDialog .Fields'));

                if (ConfigurationLimit && $('#EditDialog .Fields .Element').length >= ConfigurationLimit) {
                    $('#EditDialog .Add').hide();
                }
                RebuildEditDialogAddSelection();
                Core.UI.InputFields.Activate($('#EditDialog .Fields'));
            }

            function EditDialogDelete(ElementName) {
                $('#EditDialog .Fields .Element' + Core.App.EscapeSelector(ElementName)).remove();
                $('#EditDialog .Add').show();
                RebuildEditDialogAddSelection();
            }

            function EditDialogSave() {
                $FormFieldsElement.empty();
                $('#EditDialog .Fields').children().appendTo($FormFieldsElement);
                Core.UI.Dialog.CloseDialog($('.Dialog'));
                $('form.StatsEditForm').submit();
            }

            function EditDialogCancel() {
                Core.UI.Dialog.CloseDialog($('.Dialog'));
            }

            Core.UI.Dialog.ShowContentDialog(
                '

',
                DialogTitle,
                100,
                'Center',
                true,
                [
                    { Label: Core.Language.Translate('Save'), Class: 'Primary', Type: '', Function: EditDialogSave },
                    { Label: Core.Language.Translate('Cancel'), Class: '', Type: 'Close', Function: EditDialogCancel }
                ],
                true
            );
            $('#EditDialogTemplate').children().clone().appendTo('#EditDialog');

            if ($FormFieldsElement.children().length) {
                $CloneFormFieldsElement = $FormFieldsElement.children().clone()
                $CloneFormFieldsElement.find("*[id]").each(function() {
                    $(this).attr("id", $(this).attr("id").replace(/_selected/, ''));
                });
                $CloneFormFieldsElement.appendTo('#EditDialog .Fields');

                Core.UI.InputFields.Activate($('#EditDialog .Fields'));
                if (ConfigurationLimit && $('#EditDialog .Fields .Element').length >= ConfigurationLimit) {
                    $('#EditDialog .Add').hide();
                }
            }
            else {
                $('#EditDialog .Add').show();
            }
            RebuildEditDialogAddSelection();

            $('#EditDialog .Add select').on('change', function(){
                EditDialogAdd($(this).val());
            });

            $('#EditDialog .Fields').on('click', '.RemoveButton', function(){
                EditDialogDelete($(this).parents('.Element').data('element'));
                return false;
            });

            // Selection helpers for time fields
            $('#EditDialog .Fields .ElementBlockTime .Field select').on('change', function() {
                $(this).parent('.Field').prev('label').find('input:radio').prop('checked', true);
            });

            Core.UI.TreeSelection.InitTreeSelection();

            // Datepickers don't work if added dynamically atm, so hide for now.
            $('a.DatepickerIcon').hide();

            return false;
        });

       $('.SwitchPreviewFormat').on('click', function() {
            var Format = $(this).data('format'),
                FormatCleaned = Format.replace('::', ''),
                StatsPreviewResult;

            StatsPreviewResult = Core.Data.CopyObject(Core.Config.Get('PreviewResult'));
            $('.SwitchPreviewFormat').removeClass('Active');
            $(this).addClass('Active');
            $('.PreviewContent:visible').hide();
            $('svg.PreviewContent').empty();
            $('#PreviewContent' + FormatCleaned).show();
            if (Format.match(/D3/)) {
                Core.UI.AdvancedChart.Init(
                    Format,
                    StatsPreviewResult,
                    'svg#PreviewContent' + FormatCleaned,
                    {
                        HideLegend: true
                    }
                );
            }
            return false;
        });
        $('.SwitchPreviewFormat').first().trigger('click');
    }

    /**
     * @name Init
     * @memberof Core.Agent.Statistics
     * @function
     * @description
     *      This function initializes the module functionality.
     */
    TargetNS.Init = function () {
        var RestrictionElements,
            XAxisElements,
            YAxisElements,
            D3Data;

        // Set a postfix to the ids in the hidden container,
        //  because the fields will be cloned in the overlay.
        $('#XAxisContainer, #YAxisContainer, #RestrictionsContainer').find("*[id]").each(function() {
            $(this).attr("id", $(this).attr("id") + "_orig");
        });

        // Initialize the Add screen
        TargetNS.InitAddScreen();

        // Initialize the Edit screen
        TargetNS.InitEditScreen();

        // Bind event on delete stats button
        $('.StatDelete').on('click', function (Event) {
            var ConfirmText = '"' + $(this).data('stat-title') + '"\n\n' + Core.Language.Translate("Do you really want to delete this statistic?");
            if (!window.confirm(ConfirmText)) {
                Event.stopPropagation();
                Event.preventDefault();
                return false;
            }
        });

        // Bind event on start stats button
        $('#StartStatistic').on('click', function () {
            var Format = $('#Format').val(),
                $Form = $(this).parents('form');

            // Open both HTML and PDF output in a popup because PDF is shown inline
            if (Format === 'Print' || Format.match(/D3/)) {
                $Form.attr('target', '_blank');
            }
            else {
                $Form.removeAttr('target');
            }
        });

        RestrictionElements = Core.Config.Get('RestrictionElements');
        if (typeof RestrictionElements !== 'undefined') {
            $.each(RestrictionElements, function() {
                TargetNS.ElementAdd('Restrictions', this);
            });
        }

        XAxisElements = Core.Config.Get('XAxisElements');
        if (typeof XAxisElements !== 'undefined') {
            $.each(XAxisElements, function() {
                TargetNS.ElementAdd('XAxis', this);
            });
        }

        YAxisElements = Core.Config.Get('YAxisElements');
        if (typeof YAxisElements !== 'undefined') {
            $.each(YAxisElements, function() {
                TargetNS.ElementAdd('YAxis', this);
            });
        }

        D3Data = Core.Config.Get('D3Data');
        if (typeof D3Data !== 'undefined') {
            Core.UI.AdvancedChart.Init(
                D3Data.Format,
                D3Data.RawData,
                'svg#ChartContent',
                {
                    Duration: 250
                }
            );
        }
    };

    Core.Init.RegisterNamespace(TargetNS, 'APP_MODULE');

    return TargetNS;
}(Core.Agent.Statistics || {}));
<|endoftext|>


<commit_before>/**
 * Go through all loaded jQuery instances and assign the first one on the page with a version >=1.8.0 to kQuery
 */
if (typeof window.kQuery === 'undefined' && typeof window.jQuery !== 'undefined') {
    var kQuery,
        tmp,
        version,
        // Save current global references
        old_$ = window.$,
        old_jQuery = window.jQuery;

    while (typeof window.jQuery !== 'undefined') {
        version = window.jQuery.fn.jquery.split('.');
        tmp = window.jQuery.noConflict(true);

        // Do not use versions older than 1.8
        if (!(version[0] == '1' && parseInt(version[1], 10) < 8)) {
            kQuery = tmp;
        }
    }

    // Revert references
    window.$ = old_$;
    window.jQuery = old_jQuery;

    window.kQuery = kQuery;
}<commit_msg>re #118 throw exception instead of silently failing when jQuery version isn’t new enough<commit_after>/**
 * Go through all loaded jQuery instances and assign the first one on the page with a version >=1.8.0 to kQuery
 */
if (typeof window.kQuery === 'undefined' && typeof window.jQuery !== 'undefined') {
    var kQuery,
        tmp,
        version,
        // Save current global references
        old_$ = window.$,
        old_jQuery = window.jQuery;

    while (typeof window.jQuery !== 'undefined') {
        version = window.jQuery.fn.jquery.split('.');
        tmp = window.jQuery.noConflict(true);

        // Do not use versions older than 1.8
        if (!(version[0] == '1' && parseInt(version[1], 10) < 8)) {
            kQuery = tmp;
            throw new TypeError('jQuery 1.8 or newer is required!');
        }
    }

    // Revert references
    window.$ = old_$;
    window.jQuery = old_jQuery;

    window.kQuery = kQuery;
}<|endoftext|>


<commit_before>import _ from 'underscore';
import {Configuration} from './Configuration';
import {EntryMetadataConfiguration} from './EntryMetadataConfiguration';

export const EntryMetadata = Configuration.extend({
  modelName: 'entry',
  i18nKey: 'pageflow/entry',

  defaults: {},

  initialize: function(attributes, options) {
    Configuration.prototype.initialize.apply(this, attributes, options);
    this.configuration =
      new EntryMetadataConfiguration(_.clone(attributes.configuration) || {});

    this.listenTo(this.configuration, 'change', function() {
      this.trigger('change');
      this.parent.save();
    });
  },

  // Pageflow Scrolled only synchronizes saved records to entry state.
  isNew() {
    return false;
  }
});
<commit_msg>Fix signature of metadata change event<commit_after>import _ from 'underscore';
import {Configuration} from './Configuration';
import {EntryMetadataConfiguration} from './EntryMetadataConfiguration';

export const EntryMetadata = Configuration.extend({
  modelName: 'entry',
  i18nKey: 'pageflow/entry',

  defaults: {},

  initialize: function(attributes, options) {
    Configuration.prototype.initialize.apply(this, attributes, options);
    this.configuration =
      new EntryMetadataConfiguration(_.clone(attributes.configuration) || {});

    this.listenTo(this.configuration, 'change', function(model, options) {
      this.trigger('change', model, options);
      this.parent.save();
    });
  },

  // Pageflow Scrolled only synchronizes saved records to entry state.
  isNew() {
    return false;
  }
});
<|endoftext|>


<commit_before>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/
!function PDFViewClosure() {
    'use strict';
    var xform = 'transform';
    ['', 'webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
        var e = prefix + (prefix ? 'T' : 't') + 'ransform';
        if (typeof document.body.style[e] !== 'undefined') {
            xform = e;
            return false;
        }
        return true;
    });

    function getPixelRatio() {
        //On mobile devices this is the ratio css pixel height / device pixel height, whilst at 1.0 scale
        //On desktop devices this is typically the current scale.
        var dpr = window.devicePixelRatio || 1;
        //On mobile devices this adequately measures scale on a page using viewport width=device-width.
        //On desktop devices it is 1 (or slightly less to compensate for a scroll bar.)
        var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
        scale = scale < 1 ? 1 : scale;
        return dpr * scale;
    }

    function getOutputScale(ctx) {
        var canvas;
        if (ctx === undefined) {
            if (canvas === undefined) {
                canvas = document.createElement('canvas');
            }
            ctx = canvas.getContext('2d');
        }
        var devicePixelRatio = getPixelRatio();
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1; //backing store ratio is deprecated and will likely always be 1.
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }
    /*
    !function () {
        PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
            var pageDivs = [];
            function createPage(n) {
                if (n > pdf.numPages) {
                    return;
                }
                var div = document.createElement('div');
                pageDivs.push(div);
                var promise = new Promise(function (resolve, reject) {

                    pdf.getPage(n).then(function (page) {
                        var scale = 1;
                        var viewport = page.getViewport(scale * CSS_UNITS);

                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');

                        var outputScale = getOutputScale(canvas);
                        if (PDFJS.maxCanvasPixels > 0) {
                            var pixelsInViewport = viewport.width * viewport.height;
                            var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
                            if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
                                outputScale.sx = maxScale;
                                outputScale.sy = maxScale;
                                outputScale.scaled = true;
                                var hasRestrictedScaling = true;//TODO: use this to css transform element larger.
                            } else {
                                hasRestrictedScaling = false;
                            }
                        }

                        canvas.height = viewport.height * outputScale.sy;
                        canvas.width = viewport.width * outputScale.sx;
                        canvas.style.height = viewport.height;
                        canvas.style.width = viewport.width;

                        div.appendChild(canvas);
                        var transform = !outputScale.scaled ? null :
                            [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
                        page.render({
                            canvasContext: context,
                            transform: transform,
                            viewport: viewport
                        }).then(resolve(), reject());
                    });
                });
                return promise;
            }
            createPage(1).then(function () {
                return createPage(2);
            }).then(function () {
                pageDivs.forEach(function (div) {
                    document.body.appendChild(div);
                });
            });
        });
    } ();
    */

    window.PdfView = function PdfView(container, pdfLocation) {
        var page_gap = 10;

        var pdfViewModel = {
            pages: [],
            scale: scale,
            position: position,
            container: container,
        };
        var _scale = 1;
        var _position = { x: 0, y: 0 };

        container.style.postion = 'relative';
        var finalPageInitialisedResolve;
        var promise = new Promise(function (resolve) {
            finalPageInitialisedResolve = resolve;
        });
        PDFJS.getDocument(pdfLocation).then(function (pdf) {
            var totalWidth = 0;
            function initPage(pageNum) {
                if (pageNum === pdf.numPages){
                    finalPageInitialisedResolve(pdfViewModel);
                    return;
                }
                pdf.getPage(pageNum+1).then(function (page) {
                    var pageView = PdfPageView(page);
                    pageView.pageNo = pageNum;
                    pageView.baseTotalPrevPagesWidth = totalWidth;
                    totalWidth += pageView.baseSize.w;
                    pdfViewModel.pages.push(pageView);
                    pdfViewModel.container.appendChild(pageView.div);
                    initPage(pageNum + 1);
                });
            }
            initPage(0);
        });

        function render() {
            var pages = pdfViewModel.pages;
            var scale = _scale;
            pages.forEach(function (page) {
                page.scale(scale);
                var index = page.pageNo;
                var x = scale * page.baseTotalPrevPagesWidth + index * page_gap - _position.x;
                var y = scale * (-_position.y);
                var transformText = 'translate( ' + x + 'px, ' + y + ' )';
                page.div.style[xform] = transformText;

                var inView = false;
                if (x + page.baseSize.w * scale > 0 //the right of the page is not to the left of the container
                    && x < pdfViewModel.container.clientWidth //the left of the page is not to the right of the container
                ) {
                    inView = true;
                }
                page.onMove(inView); //trigger the page to hide/draw itself if necessary
            });
        }

        function scale(value) {
            if (value) {
                _scale = value;
                render();
                return;
            }
            return _scale;
        }
        function position(value) {
            if (value) {
                if (value.x) {
                    _position.x = value.x;
                }
                if (value.y) {
                    _position.y = value.y;
                }
                render();
            }
            return {
                x: _position.x,
                y: _position.y
            };
        }

        var zres = ZoomResizeEventSource();
        zres.start();
        return promise;
    };

    function PdfPageView(pdfPage) {
        var CLASS_LOADING = 'pdfview-loading';
        var CLASS_DIV = 'pdfview-pageContainer';
        var RENDER_INIT = 'inital';
        var RENDER_RUNNING = 'running';
        var RENDER_COMPLETE = 'complete';
        var RENDER_PAUSED = 'paused';
        var _scale = 0;
        var pageView = {
            pdfPage: pdfPage, //the PdfPageProxy object
            baseSize: { w: 0, h: 0 }, //the unscaled natural css size for the canvas
            size: { w: 0, h: 0 }, //the current space that this wants to take up
            scale: function (value) {
                if (value) {
                    _scale = value;
                    return;
                }
                return _scale;
            }, //the current scale to draw at. can be different to previous render.
            baseTotalPrevPagesWidth: 0, //total width of pages before this one. used in conjunction with scaling to position page.
            pageNo: 0, //the 0-indexed page number.
            renderStatus: RENDER_INIT,
            renderScale: 0, //the previous scale * outputscale this page was rendered at.
            renderTask: null, //the current rendertask for this page.
            canvas: null,
            context: null,
            div: null,
            onMove: onMove,
            inView: false,
        };

        function onMove(inView) {
            if (inView === pageView.inView) {
                //page hasn't moved in or out of view, but might have rescaled enough to redraw.
                if (!pageView.renderScale) {
                    return;
                }
                if (!pageView.scale()) {
                    return;
                }
                if (!pageView.context) {
                    return;
                }
                var newScale = pageView.scale() * getOutputScale(pageView.context);
                if (newScale / pageView.renderScale > 1.3
                    || pageView.renderScale / newScale > 1.3) {
                    render();
                } else {
                    //ensure that current size is correct.
                    var canvas = pageView.canvas;
                    var viewport = pageView.viewport;
                    var scale = pageView.scale();
                    var height = viewport.height * scale / pageView.renderScale;
                    var width = viewport.width * scale / pageView.renderScale;
                    canvas.style.height = height + 'px';
                    canvas.style.width = width + 'px';
                    pageView.size.h = height;
                    pageView.size.w = width;

                }
            }
            //has changed visibility;
            pageView.inView = inView;
            if (pageView.inView) {
                render();
            } else {
                reset();
            }
        }

        function initialise() {
            var vp = pdfPage.getViewport(1);
            pageView.baseSize.w = vp.width;
            pageView.baseSize.h = vp.height;
            pageView.div = document.createElement('div');
            pageView.div.classList.add(CLASS_DIV);
        }

        function render() {
            reset();
            pageView.renderStatus = RENDER_RUNNING;
            var scale = pageView.scale();
            var page = pageView.pdfPage;
            var viewport = page.getViewport(scale);
            pageView.viewport = viewport;
            var canvas = document.createElement('canvas');
            pageView.canvas = canvas;
            pageView.div.appendChild(canvas);
            var context = canvas.getContext('2d');
            pageView.context = context;

            var outputScale = getOutputScale(context);
            if (PDFJS.maxCanvasPixels > 0) {
                var pixelsInViewport = viewport.width * viewport.height;
                var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
                if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
                    outputScale.sx = maxScale;
                    outputScale.sy = maxScale;
                    outputScale.scaled = true;
                    var hasRestrictedScaling = true;//TODO: use this to css element to be larger
                } else {
                    hasRestrictedScaling = false;
                }
            }

            pageView.renderScale = scale * outputScale.sx;
            canvas.height = viewport.height * outputScale.sy;
            canvas.width = viewport.width * outputScale.sx;
            canvas.style.height = viewport.height + 'px';
            canvas.style.width = viewport.width + 'px';
            pageView.size.h = viewport.height;
            pageView.size.w = viewport.width;
            canvas.setAttribute('hidden', 'hidden');

            var transform = !outputScale.scaled ? null :
                [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
            var renderTask = page.render({
                canvasContext: context,
                transform: transform,
                viewport: viewport
            });
            pageView.renderTask = renderTask;
            var resolveRenderPromise, rejectRenderPromise;
            var promise = new Promise(function (resolve, reject) {
                resolveRenderPromise = resolve;
                rejectRenderPromise = reject;
            });

            function renderComplete(error) {
                if (pageView.renderTask === renderTask) {
                    pageView.renderTask = null;
                }
                if (error === 'cancelled') {
                    rejectRenderPromise(error);
                    return;
                }
                pageView.renderStatus = RENDER_COMPLETE;
                pageView.canvas.removeAttribute('hidden');
                pageView.div.classList.remove(CLASS_LOADING);
                resolveRenderPromise();
            }

            renderTask.promise.then(function () {
                renderComplete(null);
            }, function (error) {
                renderComplete(error);
            });

            return promise;
        }

        function reset() {
            if (pageView.renderTask && (
                pageView.renderStatus === RENDER_RUNNING
                || pageView.renderStatus === RENDER_INIT
                || pageView.renderStatus === RENDER_PAUSED)
            ) {
                pageView.renderTask.cancel();
            }
            pageView.renderStatus = RENDER_INIT;

            if (pageView.div && pageView.canvas) {
                pageView.div.removeChild(pageView.canvas);
                pageView.div.classList.add(CLASS_LOADING);
                delete pageView.canvas;
            }
        }

        initialise();
        return pageView;
    }

    var zoomResizeTimeout;
    /**
     * Sets up a source of resize events for when a mobile browser
     */
    function ZoomResizeEventSource() {
        if (zoomResizeTimeout) {
            return;
        }
        var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
        if (scale < 1) {
            scale = 1;
        }
        var started = false;
        function zoomResizeEventTick() {
            if (started) {
                return;
            }
            started = true;
            var newScale = (document.documentElement.clientWidth / window.innerWidth) || 1;
            if (newScale < 1) {
                newScale = 1;
            }
            if (Math.abs(scale - newScale) > 0.02) {
                var event = document.createEvent('Event');
                event.initEvent('resize', true, true);
                window.dispatchEvent(event);
            }
            scale = newScale;
            zoomResizeTimeout = window.setTimeout(150, zoomResizeEventTick); //150 ms period. Might feel a little sluggish, but prevents
        }
        return {
            start: zoomResizeEventTick,
            stop: function () {
                if (zoomResizeTimeout) {
                    window.clearTimeout(zoomResizeTimeout);
                }
                zoomResizeTimeout = undefined;
                started = false;
            }
        };
    }
} ();<commit_msg>Don't try to rescale hidden page<commit_after>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/
!function PDFViewClosure() {
    'use strict';
    var xform = 'transform';
    ['', 'webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
        var e = prefix + (prefix ? 'T' : 't') + 'ransform';
        if (typeof document.body.style[e] !== 'undefined') {
            xform = e;
            return false;
        }
        return true;
    });

    function getPixelRatio() {
        //On mobile devices this is the ratio css pixel height / device pixel height, whilst at 1.0 scale
        //On desktop devices this is typically the current scale.
        var dpr = window.devicePixelRatio || 1;
        //On mobile devices this adequately measures scale on a page using viewport width=device-width.
        //On desktop devices it is 1 (or slightly less to compensate for a scroll bar.)
        var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
        scale = scale < 1 ? 1 : scale;
        return dpr * scale;
    }

    function getOutputScale(ctx) {
        var canvas;
        if (ctx === undefined) {
            if (canvas === undefined) {
                canvas = document.createElement('canvas');
            }
            ctx = canvas.getContext('2d');
        }
        var devicePixelRatio = getPixelRatio();
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1; //backing store ratio is deprecated and will likely always be 1.
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }
    /*
    !function () {
        PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
            var pageDivs = [];
            function createPage(n) {
                if (n > pdf.numPages) {
                    return;
                }
                var div = document.createElement('div');
                pageDivs.push(div);
                var promise = new Promise(function (resolve, reject) {

                    pdf.getPage(n).then(function (page) {
                        var scale = 1;
                        var viewport = page.getViewport(scale * CSS_UNITS);

                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');

                        var outputScale = getOutputScale(canvas);
                        if (PDFJS.maxCanvasPixels > 0) {
                            var pixelsInViewport = viewport.width * viewport.height;
                            var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
                            if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
                                outputScale.sx = maxScale;
                                outputScale.sy = maxScale;
                                outputScale.scaled = true;
                                var hasRestrictedScaling = true;//TODO: use this to css transform element larger.
                            } else {
                                hasRestrictedScaling = false;
                            }
                        }

                        canvas.height = viewport.height * outputScale.sy;
                        canvas.width = viewport.width * outputScale.sx;
                        canvas.style.height = viewport.height;
                        canvas.style.width = viewport.width;

                        div.appendChild(canvas);
                        var transform = !outputScale.scaled ? null :
                            [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
                        page.render({
                            canvasContext: context,
                            transform: transform,
                            viewport: viewport
                        }).then(resolve(), reject());
                    });
                });
                return promise;
            }
            createPage(1).then(function () {
                return createPage(2);
            }).then(function () {
                pageDivs.forEach(function (div) {
                    document.body.appendChild(div);
                });
            });
        });
    } ();
    */

    window.PdfView = function PdfView(container, pdfLocation) {
        var page_gap = 10;

        var pdfViewModel = {
            pages: [],
            scale: scale,
            position: position,
            container: container,
        };
        var _scale = 1;
        var _position = { x: 0, y: 0 };

        container.style.postion = 'relative';
        container.style.overflow = 'hidden';
        container.style.pespective = '500px';
        var finalPageInitialisedResolve;
        var promise = new Promise(function (resolve) {
            finalPageInitialisedResolve = resolve;
        });
        PDFJS.getDocument(pdfLocation).then(function (pdf) {
            var totalWidth = 0;
            function initPage(pageNum) {
                if (pageNum === pdf.numPages){
                    finalPageInitialisedResolve(pdfViewModel);
                    return;
                }
                pdf.getPage(pageNum+1).then(function (page) {
                    var pageView = PdfPageView(page);
                    pageView.pageNo = pageNum;
                    pageView.baseTotalPrevPagesWidth = totalWidth;
                    totalWidth += pageView.baseSize.w;
                    pdfViewModel.pages.push(pageView);
                    pdfViewModel.container.appendChild(pageView.div);
                    initPage(pageNum + 1);
                });
            }
            initPage(0);
        });

        function render() {
            var pages = pdfViewModel.pages;
            var scale = _scale;
            pages.forEach(function (page) {
                page.scale(scale);
                var index = page.pageNo;
                var x = scale * page.baseTotalPrevPagesWidth + index * page_gap - _position.x;
                var y = scale * (-_position.y);
                var transformText = 'translate( ' + x + 'px, ' + y + ' )';
                page.div.style[xform] = transformText;

                var inView = false;
                if (x + page.baseSize.w * scale > 0 //the right of the page is not to the left of the container
                    && x < pdfViewModel.container.clientWidth //the left of the page is not to the right of the container
                ) {
                    inView = true;
                }
                page.onMove(inView); //trigger the page to hide/draw itself if necessary
            });
        }

        function scale(value) {
            if (value) {
                _scale = value;
                render();
                return;
            }
            return _scale;
        }
        function position(value) {
            if (value) {
                if (value.x) {
                    _position.x = value.x;
                }
                if (value.y) {
                    _position.y = value.y;
                }
                render();
            }
            return {
                x: _position.x,
                y: _position.y
            };
        }

        var zres = ZoomResizeEventSource();
        zres.start();
        return promise;
    };

    function PdfPageView(pdfPage) {
        var CLASS_LOADING = 'pdfview-loading';
        var CLASS_DIV = 'pdfview-pageContainer';
        var RENDER_INIT = 'inital';
        var RENDER_RUNNING = 'running';
        var RENDER_COMPLETE = 'complete';
        var RENDER_PAUSED = 'paused';
        var _scale = 0;
        var pageView = {
            pdfPage: pdfPage, //the PdfPageProxy object
            baseSize: { w: 0, h: 0 }, //the unscaled natural css size for the canvas
            size: { w: 0, h: 0 }, //the current space that this wants to take up
            scale: function (value) {
                if (value) {
                    _scale = value;
                    return;
                }
                return _scale;
            }, //the current scale to draw at. can be different to previous render.
            baseTotalPrevPagesWidth: 0, //total width of pages before this one. used in conjunction with scaling to position page.
            pageNo: 0, //the 0-indexed page number.
            renderStatus: RENDER_INIT,
            renderScale: 0, //the previous scale * outputscale this page was rendered at.
            renderTask: null, //the current rendertask for this page.
            canvas: null,
            context: null,
            div: null,
            onMove: onMove,
            inView: false,
        };

        function onMove(inView) {
            if (inView === pageView.inView) {
                //page hasn't moved in or out of view, but might have rescaled enough to redraw.
                if (!pageView.renderScale) {
                    return;
                }
                if (!pageView.scale()) {
                    return;
                }
                if (!pageView.context) {
                    return;
                }
                var newScale = pageView.scale() * getOutputScale(pageView.context);
                if (newScale / pageView.renderScale > 1.3
                    || pageView.renderScale / newScale > 1.3) {
                    render();
                } else if(inView && pageView.canvas) {
                    //ensure that current size is correct.
                    var canvas = pageView.canvas;
                    var viewport = pageView.viewport;
                    var scale = pageView.scale();
                    var height = viewport.height * scale / pageView.renderScale;
                    var width = viewport.width * scale / pageView.renderScale;
                    canvas.style.height = height + 'px';
                    canvas.style.width = width + 'px';
                    pageView.size.h = height;
                    pageView.size.w = width;

                }
            }
            //has changed visibility;
            pageView.inView = inView;
            if (pageView.inView) {
                render();
            } else {
                reset();
            }
        }

        function initialise() {
            var vp = pdfPage.getViewport(1);
            pageView.baseSize.w = vp.width;
            pageView.baseSize.h = vp.height;
            pageView.div = document.createElement('div');
            pageView.div.classList.add(CLASS_DIV);
        }

        function render() {
            reset();
            pageView.renderStatus = RENDER_RUNNING;
            var scale = pageView.scale();
            var page = pageView.pdfPage;
            var viewport = page.getViewport(scale);
            pageView.viewport = viewport;
            var canvas = document.createElement('canvas');
            pageView.canvas = canvas;
            pageView.div.appendChild(canvas);
            var context = canvas.getContext('2d');
            pageView.context = context;

            var outputScale = getOutputScale(context);
            if (PDFJS.maxCanvasPixels > 0) {
                var pixelsInViewport = viewport.width * viewport.height;
                var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
                if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
                    outputScale.sx = maxScale;
                    outputScale.sy = maxScale;
                    outputScale.scaled = true;
                    var hasRestrictedScaling = true;//TODO: use this to css element to be larger
                } else {
                    hasRestrictedScaling = false;
                }
            }

            pageView.renderScale = scale * outputScale.sx;
            canvas.height = viewport.height * outputScale.sy;
            canvas.width = viewport.width * outputScale.sx;
            canvas.style.height = viewport.height + 'px';
            canvas.style.width = viewport.width + 'px';
            pageView.size.h = viewport.height;
            pageView.size.w = viewport.width;
            canvas.setAttribute('hidden', 'hidden');

            var transform = !outputScale.scaled ? null :
                [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
            var renderTask = page.render({
                canvasContext: context,
                transform: transform,
                viewport: viewport
            });
            pageView.renderTask = renderTask;
            var resolveRenderPromise, rejectRenderPromise;
            var promise = new Promise(function (resolve, reject) {
                resolveRenderPromise = resolve;
                rejectRenderPromise = reject;
            });

            function renderComplete(error) {
                if (pageView.renderTask === renderTask) {
                    pageView.renderTask = null;
                }
                if (error === 'cancelled') {
                    rejectRenderPromise(error);
                    return;
                }
                pageView.renderStatus = RENDER_COMPLETE;
                pageView.canvas.removeAttribute('hidden');
                pageView.div.classList.remove(CLASS_LOADING);
                resolveRenderPromise();
            }

            renderTask.promise.then(function () {
                renderComplete(null);
            }, function (error) {
                renderComplete(error);
            });

            return promise;
        }

        function reset() {
            if (pageView.renderTask && (
                pageView.renderStatus === RENDER_RUNNING
                || pageView.renderStatus === RENDER_INIT
                || pageView.renderStatus === RENDER_PAUSED)
            ) {
                pageView.renderTask.cancel();
            }
            pageView.renderStatus = RENDER_INIT;

            if (pageView.div && pageView.canvas) {
                pageView.div.removeChild(pageView.canvas);
                pageView.div.classList.add(CLASS_LOADING);
                delete pageView.canvas;
            }
        }

        initialise();
        return pageView;
    }

    var zoomResizeTimeout;
    /**
     * Sets up a source of resize events for when a mobile browser
     */
    function ZoomResizeEventSource() {
        if (zoomResizeTimeout) {
            return;
        }
        var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
        if (scale < 1) {
            scale = 1;
        }
        var started = false;
        function zoomResizeEventTick() {
            if (started) {
                return;
            }
            started = true;
            var newScale = (document.documentElement.clientWidth / window.innerWidth) || 1;
            if (newScale < 1) {
                newScale = 1;
            }
            if (Math.abs(scale - newScale) > 0.02) {
                var event = document.createEvent('Event');
                event.initEvent('resize', true, true);
                window.dispatchEvent(event);
            }
            scale = newScale;
            zoomResizeTimeout = window.setTimeout(150, zoomResizeEventTick); //150 ms period. Might feel a little sluggish, but prevents
        }
        return {
            start: zoomResizeEventTick,
            stop: function () {
                if (zoomResizeTimeout) {
                    window.clearTimeout(zoomResizeTimeout);
                }
                zoomResizeTimeout = undefined;
                started = false;
            }
        };
    }
} ();<|endoftext|>


<commit_before>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

function getPixelRatio() {
    //On mobile devices this is the ratio css pixel height / device pixel height, whilst at 1.0 scale
    //On desktop devices this is typically the current scale.
    var dpr = window.devicePixelRatio || 1;
    //On mobile devices this adequately measures scale on a page using viewport width=device-width.
    //On desktop devices it is 1 (or slightly less to compensate for a scroll bar.)
    var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
    scale = scale < 1 ? 1 : scale;
    return dpr * scale;
}

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = getPixelRatio();
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1; //backing store ratio is deprecated and will likely always be 1.
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}
!function (w) {
    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 1;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;
                canvas.style.height = viewport.height;
                canvas.style.width = viewport.width;

                div.appendChild(canvas);
                var transform = !outputScale.scaled ? null :
                    [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
                page.render({
                    canvasContext: context,
                    transform: transform,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);<commit_msg>respect max canvas pixels<commit_after>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

function getPixelRatio() {
    //On mobile devices this is the ratio css pixel height / device pixel height, whilst at 1.0 scale
    //On desktop devices this is typically the current scale.
    var dpr = window.devicePixelRatio || 1;
    //On mobile devices this adequately measures scale on a page using viewport width=device-width.
    //On desktop devices it is 1 (or slightly less to compensate for a scroll bar.)
    var scale = (document.documentElement.clientWidth / window.innerWidth) || 1;
    scale = scale < 1 ? 1 : scale;
    return dpr * scale;
}

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = getPixelRatio();
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1; //backing store ratio is deprecated and will likely always be 1.
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}
!function (w) {
    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 1;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                if (PDFJS.maxCanvasPixels > 0) {
                    var pixelsInViewport = viewport.width * viewport.height;
                    var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
                    if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
                        outputScale.sx = maxScale;
                        outputScale.sy = maxScale;
                        outputScale.scaled = true;
                        var hasRestrictedScaling = true;
                    } else {
                        hasRestrictedScaling = false;
                    }
                }

                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;
                canvas.style.height = viewport.height;
                canvas.style.width = viewport.width;

                div.appendChild(canvas);
                var transform = !outputScale.scaled ? null :
                    [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
                page.render({
                    canvasContext: context,
                    transform: transform,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);<|endoftext|>