<commit_before>
function toggle_heat_status() {

    send_url("{%url 'toggle_heat_status'%}", function(data){
        $("#heat_on_btn").toggleClass("btn-success btn-danger")

        })
}

function toggle_manual() {
    send_url("{%url 'toggle_heat_manual'%}", function(data){
        if(data.manual){
            $("#heat_manual_btn").html("Manual")
        }else{
            $("#heat_manual_btn").html("Program")
        }})
}

function read_heat_status() {
    $.ajax({
        url: "{%url 'read_heat_status'%}",

        success: function(data){
            if (data.status == "ON") {
                $("#heat_on_btn").removeClass("btn-danger")
                $("#heat_on_btn").addClass("btn-success")
            }
            if (data.status == "OFF") {
                $("#heat_on_btn").removeClass("btn-success")
                $("#heat_on_btn").addClass("btn-danger")
            }
            $("#economic").html(data.economic + " º")
            $("#confort").html(data.confort + " º")
            $("#tuned_temp").html("Tunned... " + data.tuned + " º")
            $("#time").html(data.time)
            if (data.flame == true) {
                $("#flame").removeClass("label-default")
                $("#flame").addClass("label-danger")
            }else{
                $("#flame").removeClass("label-danger")
                $("#flame").addClass("label-default")
            }
            if(data.manual){
                $("#heat_manual_btn").html("Manual")
                $("#heat_manual_btn").addClass("btn-warning")
            }else{
                $("#heat_manual_btn").html("Program")
                $("#heat_manual_btn").removeClass("btn-warning")
                }

            },

        error: function(ob){show_msg(ob.responseText)}
        });

    $.ajax({
        url: "{%url 'temperature' 'in'%}",

        success: function(data){window.console.log(data);$("#internal_temp").html("Current... " + data.internal + " º")}})
}

function dim(temp) {
    send_url("{%url 'dim_temp'%}" + temp, function(data){
        if (temp == "confort") {
            $("#confort").val(data.confort)
        }
        if (temp == "economic"){
            $("#economic").val(data.economic)
        }
        })
}

function bri(temp) {
    send_url("{%url 'bri_temp'%}" + temp, function(data){
        if (temp == "confort") {
            $("#confort").val(data.confort)
        }
        if (temp == "economic"){
            $("#economic").val(data.economic)
        }
        })
}
<commit_msg>added js to new thermometer, fixed a bug<commit_after>
function toggle_heat_status() {

    send_url("{%url 'toggle_heat_status'%}", function(data){
        $("#heat_on_btn").toggleClass("btn-success btn-danger")

        })
}

function toggle_manual() {
    send_url("{%url 'toggle_heat_manual'%}", function(data){
        if(data.manual){
            $("#heat_manual_btn").html("Manual")
        }else{
            $("#heat_manual_btn").html("Program")
        }})
}

function read_heat_status() {
    $.ajax({
        url: "{%url 'read_heat_status'%}",

        success: function(data){
            if (data.status == "ON") {
                $("#heat_on_btn").removeClass("btn-danger")
                $("#heat_on_btn").addClass("btn-success")
            }
            if (data.status == "OFF") {
                $("#heat_on_btn").removeClass("btn-success")
                $("#heat_on_btn").addClass("btn-danger")
            }
            $("#economic").html(data.economic + " º")
            $("#confort").html(data.confort + " º")
            $("#tuned_temp").html("Tunned... " + data.tuned + " º")
            $("#time").html(data.time)
            if (data.flame == true) {
                $("#flame").removeClass("label-default")
                $("#flame").addClass("label-danger")
            }else{
                $("#flame").removeClass("label-danger")
                $("#flame").addClass("label-default")
            }
            if(data.manual){
                $("#heat_manual_btn").html("Manual")
                $("#heat_manual_btn").addClass("btn-warning")
            }else{
                $("#heat_manual_btn").html("Program")
                $("#heat_manual_btn").removeClass("btn-warning")
                }

            },

        error: function(ob){show_msg(ob.responseText)}
        });

    $.ajax({
        url: "{%url 'temperature' 'in'%}",

        success: function(data){window.console.log(data);$("#internal_temp").html("Current... " + data.celsius + " º")}})
}

function dim(temp) {
    send_url("{%url 'dim_temp'%}" + temp, function(data){
        if (temp == "confort") {
            $("#confort").val(data.confort)
        }
        if (temp == "economic"){
            $("#economic").val(data.economic)
        }
        })
}

function bri(temp) {
    send_url("{%url 'bri_temp'%}" + temp, function(data){
        if (temp == "confort") {
            $("#confort").val(data.confort)
        }
        if (temp == "economic"){
            $("#economic").val(data.economic)
        }
        })
}
<|endoftext|>


<commit_before>/**
 * Angular LinkedIn Service
 *
 * For more info see official API Documentation:
 * https://developer.linkedin.com/documents/javascript-api-reference-0
 *
 * @author  Roman Alexeev <roman@boket.to>
 * @date    April 21, 2014
 * @version 0.1.0
 * @license MIT
 */
'use strict';

angular.module('ngLinkedIn', [])
    .provider('$linkedIn', function() {
        var config = {
            appKey: null,
            onLoad: null,
            authorize: false,
            lang: 'en_US',
            scope: 'r_basicprofile'
        };

        this.set = function(property, value) {
            if (!config.hasOwnProperty(property)) {
                throw 'Config does not support property: ' + key;
            }
            config[property] = value;
            return this;
        };

        this.get = function(property) {
            if (!config.hasOwnProperty(property)) {
                throw 'Config does not support property: ' + key;
            }
            return config[property];
        };

        this.$get = ['$rootScope', '$q', '$window', function($rootScope, $q, $window) {
            var $linkedIn = $q.defer();

            $rootScope.$on("in.load", function(e, IN) {
                $linkedIn.resolve(IN);

                var events = ['auth', 'logout'];
                angular.forEach(events, function(event) {
                    IN.Event.on(IN, event, function(response) {
                        $rootScope.$broadcast("in." + event, response);
                        if(!$rootScope.$$phase) {
                            $rootScope.$apply();
                        }
                    });
                });
            });

            $linkedIn.config = function(property) {
                return config[property];
            };

            // init
            $linkedIn.init = function() {
                if (!$linkedIn.config('appKey')) {
                    throw '$linkedInProvider: appKey is not set';
                }
                $window.IN.init(angular.extend({ api_key: $linkedIn.config('appKey') }, config));
                $rootScope.$broadcast("in.load", $window.IN);
            };

            // check auth
            $linkedIn.isAuthorized = function() {
                return IN.User.isAuthorized();
            };

            // authorize
            $linkedIn.authorize = function() {
                var defer = $q.defer();

                return $linkedIn.promise.then(function(IN) {
                    IN.User.authorize(function() {
                        defer.resolve();
                    });
                    return defer.promise;
                });
            };

            // refresh token
            $linkedIn.refresh = function() {
                IN.User.refresh();
            };

            // logout
            $linkedIn.logout = function() {
                var defer = $q.defer();
                return $linkedIn.promise.then(function(IN) {
                    IN.User.logout(function() {
                        defer.resolve();
                    });
                    return defer.promise;
                });
            };

            // share
            $linkedIn.share = function(url) {
                if (!url) {
                    throw 'Url is not specified';
                }
                IN.UI.Share()
                    .params({ url: url })
                    .place();
            };

            // general api request
            $linkedIn.api = function(api, ids, fields, params) {
                var defer = $q.defer();
                return $linkedIn.promise.then(function(IN) {
                    IN.API[api](ids.toString() || 'me')
                        .fields(fields || null)
                        .params(params || {})
                        .result(function(response) {
                            console.log('res', response);
                            defer.resolve(response);
                        });
                    return defer.promise;
                });
            };

            // api shortcut methods
            // profile
            $linkedIn.profile = function(ids, fields, params) {
                return $linkedIn.api('Profile', ids, fields, params);
            };

            // connections
            // requires 'r_network' and 'rw_nus' permissions
            $linkedIn.connections = function(ids, fields, params) {
                return $linkedIn.api('Connections', ids, fields, params);
            };

            // member updates
            // requires 'rw_nus' permission
            $linkedIn.memberUpdates = function(ids, fields, params) {
                return $linkedIn.api('MemberUpdates', ids, fields, params);
            };

            return $linkedIn;
        }];
    })
    .run(['$rootScope', '$linkedIn', function($rootScope, $linkedIn) {
        $.getScript("//platform.linkedin.com/in.js?async=true", function() {
            $linkedIn.init();
            if (!$rootScope.$$phase) {
                $rootScope.$apply();
            }
        });
    }]);
<commit_msg>bug fix<commit_after>/**
 * Angular LinkedIn Service
 *
 * For more info see official API Documentation:
 * https://developer.linkedin.com/documents/javascript-api-reference-0
 *
 * @author  Roman Alexeev <roman@boket.to>
 * @date    April 21, 2014
 * @version 0.1.0
 * @license MIT
 */
'use strict';

angular.module('ngLinkedIn', [])
    .provider('$linkedIn', function() {
        var config = {
            appKey: null,
            onLoad: null,
            authorize: false,
            lang: 'en_US',
            scope: 'r_basicprofile'
        };

        this.set = function(property, value) {
            if (!config.hasOwnProperty(property)) {
                throw 'Config does not support property: ' + property;
            }
            config[property] = value;
            return this;
        };

        this.get = function(property) {
            if (!config.hasOwnProperty(property)) {
                throw 'Config does not support property: ' + property;
            }
            return config[property];
        };

        this.$get = ['$rootScope', '$q', '$window', function($rootScope, $q, $window) {
            var $linkedIn = $q.defer();

            $rootScope.$on("in.load", function(e, IN) {
                $linkedIn.resolve(IN);

                var events = ['auth', 'logout'];
                angular.forEach(events, function(event) {
                    IN.Event.on(IN, event, function(response) {
                        $rootScope.$broadcast("in." + event, response);
                        if(!$rootScope.$$phase) {
                            $rootScope.$apply();
                        }
                    });
                });
            });

            $linkedIn.config = function(property) {
                return config[property];
            };

            // init
            $linkedIn.init = function() {
                if (!$linkedIn.config('appKey')) {
                    throw '$linkedInProvider: appKey is not set';
                }
                $window.IN.init(angular.extend({ api_key: $linkedIn.config('appKey') }, config));
                $rootScope.$broadcast("in.load", $window.IN);
            };

            // check auth
            $linkedIn.isAuthorized = function() {
                return IN.User.isAuthorized();
            };

            // authorize
            $linkedIn.authorize = function() {
                var defer = $q.defer();

                return $linkedIn.promise.then(function(IN) {
                    IN.User.authorize(function() {
                        defer.resolve();
                    });
                    return defer.promise;
                });
            };

            // refresh token
            $linkedIn.refresh = function() {
                IN.User.refresh();
            };

            // logout
            $linkedIn.logout = function() {
                var defer = $q.defer();
                return $linkedIn.promise.then(function(IN) {
                    IN.User.logout(function() {
                        defer.resolve();
                    });
                    return defer.promise;
                });
            };

            // share
            $linkedIn.share = function(url) {
                if (!url) {
                    throw 'Url is not specified';
                }
                IN.UI.Share()
                    .params({ url: url })
                    .place();
            };

            // general api request
            $linkedIn.api = function(api, ids, fields, params) {
                var defer = $q.defer();
                return $linkedIn.promise.then(function(IN) {
                    IN.API[api](ids.toString() || 'me')
                        .fields(fields || null)
                        .params(params || {})
                        .result(function(response) {
                            console.log('res', response);
                            defer.resolve(response);
                        });
                    return defer.promise;
                });
            };

            // api shortcut methods
            // profile
            $linkedIn.profile = function(ids, fields, params) {
                return $linkedIn.api('Profile', ids, fields, params);
            };

            // connections
            // requires 'r_network' and 'rw_nus' permissions
            $linkedIn.connections = function(ids, fields, params) {
                return $linkedIn.api('Connections', ids, fields, params);
            };

            // member updates
            // requires 'rw_nus' permission
            $linkedIn.memberUpdates = function(ids, fields, params) {
                return $linkedIn.api('MemberUpdates', ids, fields, params);
            };

            return $linkedIn;
        }];
    })
    .run(['$rootScope', '$linkedIn', function($rootScope, $linkedIn) {
        $.getScript("//platform.linkedin.com/in.js?async=true", function() {
            $linkedIn.init();
            if (!$rootScope.$$phase) {
                $rootScope.$apply();
            }
        });
    }]);
<|endoftext|>


<commit_before>function makeMainThreadBenchmark(name, args) {
  return {
    benchmark: 'main-thread-' + name,
    description: 'Responsiveness during poppler PDF rendering on the main thread',
    scale: 'seconds (lower numbers are better)',
    totalReps: args.cold ? 1 : 2,
    warmupReps: args.cold ? 0 : 1,
    createWorker: function() {
      return {
        postMessage: function() {
          var worker = this;
          // create the iframe and set up communication
          var frame = document.createElement('iframe');
          frame.width = document.body.clientWidth*0.9;
          frame.height = document.body.clientHeight*0.2;
          frame.src = 'responsiveness.html'
          window.onmessage = function(event) {
            document.getElementById('presentation-area').removeChild(frame);
            window.onmessage = null;
            event.data.benchmark = 'main-thread-' + name;
            worker.onmessage(event);
          };
          frame.onload = function() {
            frame.contentWindow.postMessage(args, '*');
          };
          document.getElementById('presentation-area').appendChild(frame);
        },
        terminate: function(){},
      };
    },
    calculate: function() {
      // care about both main thread pauses, and total time spent
      return Math.max(1/30, (this.msg.mainThread + this.msg.walltime)/1000);
    },
    normalized: function() {
      return (args.cold ? 2.5 : 1)/this.calculate();
    },
  };
}

var jobMap = {};

var jobs = [
  { title: 'Main thread responsiveness', description: 'Tests user-noticeable stalls as a large codebase is loaded' },

  // test of latency/smoothness on main thread as a large codebase loads and starts to run
  // build instructions: see below
  makeMainThreadBenchmark('poppler-cold', { cold: true }),
  makeMainThreadBenchmark('poppler-warm', { cold: false }),

  { title: 'Throughput', description: 'Tests performance in long-running computational code' },

  // box2d. build instructions: let emscripten benchmark suite generate it for you (non-fround)
  {
    benchmark: 'box2d-throughput',
    description: 'Box2D physics: average frame rate',
    scale: 'milliseconds (lower numbers are better)',
    args: ['3'],
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.average;
    },
    normalized: function() {
      return (10/this.calculate());
    },
  },
/*
  {
    benchmark: 'box2d-cold-startup',
    description: 'how long a cold startup takes for Box2D',
    scale: 'seconds (lower numbers are better)',
    args: 'cold',
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.runtime/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60);
    },
  },
  {
    benchmark: 'box2d-warm-startup',
    description: 'how long a warm startup takes for Box2D',
    scale: 'seconds (lower numbers are better)',
    args: ['0'],
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.runtime/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60);
    },
  },
*/

  // lua. build instructions: use lua.vm.js project build system
  {
    benchmark: 'lua-binarytrees',
    description: 'GC performance in compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: ['binarytrees.lua'],
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return Math.max(1/30, this.msg.runtime/1000);
    },
    normalized: function() {
      return (7/this.calculate());
    },
  },
  {
    benchmark: 'lua-scimark',
    description: 'numeric computation performance in compiled Lua VM',
    scale: 'MFLOPS (higher numbers are better)',
    args: ['scimark.lua'],
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.scimarkTime;
    },
    normalized: function() {
      return this.calculate()/10;
    },
  },
  // poppler. build instructions: run asm3.test_sqlite in emscripten test suite, then remove last 3 lines in source file that were appended, change shouldRunNow to true
  {
    benchmark: 'poppler',
    description: 'Poppler PDF performance: cold startup + rendering',
    scale: 'seconds (lower numbers are better)',
    args: [],
    createWorker: function() {
      return new Worker('poppler/benchmark-worker.js')
    },
    calculate: function() {
      return Math.max(1/30, this.msg.runtime/1000);
    },
    normalized: function() {
      return (7/this.calculate());
    },
  },

  // sqlite. build instructions: run asm3.test_sqlite in emscripten test suite
  {
    benchmark: 'sqlite',
    description: 'sqlite operations performance (create, inserts, selects)',
    scale: 'seconds (lower numbers are better)',
    args: ['20000', '25'],
    createWorker: function() {
      return new Worker('sqlite/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.calcTime;
    },
    normalized: function() {
      return 8.0/Math.max(this.calculate(), 1/60);
    },
  },

  { title: 'Parsing', description: 'Tests how fast a casebase is loaded and ready to run' },

  { // do startup last so there is no network access
    benchmark: 'lua-cold-parsing',
    description: 'how long a cold parsing takes the compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: null,
    createWorker: function() {
      return new Worker('lua/benchmark-worker-cold-startup.js')
    },
    calculate: function() {
      return this.msg.startup/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60); // resolution: 1 frame
    },
  },
  {
    benchmark: 'lua-warm-parsing',
    description: 'how long a warm parsing takes the compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: null,
    totalReps: 2,
    warmupReps: 1,
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.startup/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60); // resolution: 1 frame
    },
  },

  { title: 'Variance', description: 'Runs many frames of a long-running simulation and tests variability and the worst case among them' },

  {
    benchmark: 'box2d-variance',
    description: 'Box2D physics: frame rate variance',
    scale: 'milliseconds (lower numbers are better)',
    createWorker: function() {
      return {
        postMessage: function() {
          this.onmessage({ data: {
            benchmark: 'box2d-variance'
          }});
        },
        terminate: function(){},
      };
    },
    calculate: function() {
      var parsed = jobMap['box2d-throughput'].msg;
      return (2*parsed.variance + (parsed.highest - parsed.average))/3;
    },
    normalized: function() {
      return (1/this.calculate());
    },
  },
];

var ran = false;
function run() {
  if (ran) return;
  ran = true;

  document.getElementById('results_area').hidden = false;
  document.getElementById('warning').hidden = true;

  var tableBody = document.getElementById('table_body');
  tableBody.innerHTML = '';

  var theButton = document.getElementById('the_button');
  theButton.innerHTML = 'Running benchmarks... (this can take a while)';
  theButton.classList.remove('btn-primary');
  theButton.classList.add('btn-warning');

  function finalCalculation() {
    // normalize based on experimental data
    var normalized = jobs.filter(function(job) { return job.normalized }).map(function(job) { return job.normalized() });
    return Math.round(100 * normalized.reduce(function(x, y) { return x + y }, 0));
  }

  var curr = 0;

  function runJob() {

    var job = jobs[curr++];
    if (!job) {
      theButton.innerHTML = 'Score: ' + finalCalculation() + ' (higher numbers are better)';
      theButton.classList.remove('btn-warning');
      theButton.classList.add('btn-success');
      return;
    }
    if (job.title) {
      tableBody.innerHTML += '
' +
                             '  ' + job.title + '	' +
                             '  	' +
                             '  	' +
                             '  ' + (job.description ? job.description + ' (details)' : '') + '	' +
                             '  	' +
                             '
';
      setTimeout(runJob, 1);
      return;
    }

    jobMap[job.benchmark] = job;

    tableBody.innerHTML += '
' +
                           '  ' + job.benchmark + '	' +
                           '

	' +
                           '  ' + job.scale + '	' +
                           '  ' + (job.description || '') + '	' +
                           '

	' +
                           '
';

    document.getElementById(job.benchmark + '-output').innerHTML = '(..running..)';
    document.getElementById(job.benchmark + '-cell').style = 'background-color: #ffddaa';

    // Run the job the specified number of times
    var reps = 0;
    var totalReps = job.totalReps || 1;
    var warmupReps = job.warmupReps || 0;
    var results = [];

    function finish() {
      console.log('final: ' + JSON.stringify(results));
      var final = {};
      for (var i = warmupReps; i < totalReps; i++) {
        var result = results[i];
        for (var k in result) {
          if (typeof result[k] === 'number') {
            final[k] = (final[k] || 0) + result[k];
          }
        }
      }
      for (var k in final) {
        if (typeof final[k] === 'number') {
          final[k] /= totalReps - warmupReps;
        }
      }
      job.msg = final;
      console.log('final: ' + JSON.stringify(job.msg) + ' on ' + (totalReps - warmupReps));

      document.getElementById(job.benchmark + '-output').innerHTML = '' + job.calculate().toFixed(3) + '';
      document.getElementById(job.benchmark + '-cell').style = 'background-color: #bbccff';
      document.getElementById(job.benchmark + '-normalized-output').innerHTML = '' + (100*job.normalized()).toFixed(3) + '';
      document.getElementById(job.benchmark + '-normalized-cell').style = 'background-color: #ee9955';
      setTimeout(function() {
        runJob();
      }, 1);
    }

    function doRep() {
      var worker = job.createWorker();
      worker.onmessage = function(event) {
        var msg = event.data;
        console.log(JSON.stringify(msg));
        if (msg.benchmark != job.benchmark) throw 'invalid data from benchmark worker';
        results.push(msg);

        reps++;
        if (reps === totalReps) {
          worker.terminate(); // ensure the worker is cleaned up before the next starts
          finish();
        } else {
          setTimeout(doRep, 1);
        }
      };
      console.log('requesting benchmark ' + job.benchmark);
      worker.postMessage({
        benchmark: job.benchmark,
        args: job.args
      });
    }

    doRep();
  }
  runJob();
}

<commit_msg>use geometric mean, like octane/v8<commit_after>function makeMainThreadBenchmark(name, args) {
  return {
    benchmark: 'main-thread-' + name,
    description: 'Responsiveness during poppler PDF rendering on the main thread',
    scale: 'seconds (lower numbers are better)',
    totalReps: args.cold ? 1 : 2,
    warmupReps: args.cold ? 0 : 1,
    createWorker: function() {
      return {
        postMessage: function() {
          var worker = this;
          // create the iframe and set up communication
          var frame = document.createElement('iframe');
          frame.width = document.body.clientWidth*0.9;
          frame.height = document.body.clientHeight*0.2;
          frame.src = 'responsiveness.html'
          window.onmessage = function(event) {
            document.getElementById('presentation-area').removeChild(frame);
            window.onmessage = null;
            event.data.benchmark = 'main-thread-' + name;
            worker.onmessage(event);
          };
          frame.onload = function() {
            frame.contentWindow.postMessage(args, '*');
          };
          document.getElementById('presentation-area').appendChild(frame);
        },
        terminate: function(){},
      };
    },
    calculate: function() {
      // care about both main thread pauses, and total time spent
      return Math.max(1/30, (this.msg.mainThread + this.msg.walltime)/1000);
    },
    normalized: function() {
      return (args.cold ? 2.5 : 1)/this.calculate();
    },
  };
}

var jobMap = {};

var jobs = [
  { title: 'Main thread responsiveness', description: 'Tests user-noticeable stalls as a large codebase is loaded' },

  // test of latency/smoothness on main thread as a large codebase loads and starts to run
  // build instructions: see below
  makeMainThreadBenchmark('poppler-cold', { cold: true }),
  makeMainThreadBenchmark('poppler-warm', { cold: false }),

  { title: 'Throughput', description: 'Tests performance in long-running computational code' },

  // box2d. build instructions: let emscripten benchmark suite generate it for you (non-fround)
  {
    benchmark: 'box2d-throughput',
    description: 'Box2D physics: average frame rate',
    scale: 'milliseconds (lower numbers are better)',
    args: ['3'],
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.average;
    },
    normalized: function() {
      return (10/this.calculate());
    },
  },
/*
  {
    benchmark: 'box2d-cold-startup',
    description: 'how long a cold startup takes for Box2D',
    scale: 'seconds (lower numbers are better)',
    args: 'cold',
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.runtime/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60);
    },
  },
  {
    benchmark: 'box2d-warm-startup',
    description: 'how long a warm startup takes for Box2D',
    scale: 'seconds (lower numbers are better)',
    args: ['0'],
    createWorker: function() {
      return new Worker('box2d/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.runtime/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60);
    },
  },
*/

  // lua. build instructions: use lua.vm.js project build system
  {
    benchmark: 'lua-binarytrees',
    description: 'GC performance in compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: ['binarytrees.lua'],
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return Math.max(1/30, this.msg.runtime/1000);
    },
    normalized: function() {
      return (7/this.calculate());
    },
  },
  {
    benchmark: 'lua-scimark',
    description: 'numeric computation performance in compiled Lua VM',
    scale: 'MFLOPS (higher numbers are better)',
    args: ['scimark.lua'],
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.scimarkTime;
    },
    normalized: function() {
      return this.calculate()/10;
    },
  },
  // poppler. build instructions: run asm3.test_sqlite in emscripten test suite, then remove last 3 lines in source file that were appended, change shouldRunNow to true
  {
    benchmark: 'poppler',
    description: 'Poppler PDF performance: cold startup + rendering',
    scale: 'seconds (lower numbers are better)',
    args: [],
    createWorker: function() {
      return new Worker('poppler/benchmark-worker.js')
    },
    calculate: function() {
      return Math.max(1/30, this.msg.runtime/1000);
    },
    normalized: function() {
      return (7/this.calculate());
    },
  },

  // sqlite. build instructions: run asm3.test_sqlite in emscripten test suite
  {
    benchmark: 'sqlite',
    description: 'sqlite operations performance (create, inserts, selects)',
    scale: 'seconds (lower numbers are better)',
    args: ['20000', '25'],
    createWorker: function() {
      return new Worker('sqlite/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.calcTime;
    },
    normalized: function() {
      return 8.0/Math.max(this.calculate(), 1/60);
    },
  },

  { title: 'Parsing', description: 'Tests how fast a casebase is loaded and ready to run' },

  { // do startup last so there is no network access
    benchmark: 'lua-cold-parsing',
    description: 'how long a cold parsing takes the compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: null,
    createWorker: function() {
      return new Worker('lua/benchmark-worker-cold-startup.js')
    },
    calculate: function() {
      return this.msg.startup/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60); // resolution: 1 frame
    },
  },
  {
    benchmark: 'lua-warm-parsing',
    description: 'how long a warm parsing takes the compiled Lua VM',
    scale: 'seconds (lower numbers are better)',
    args: null,
    totalReps: 2,
    warmupReps: 1,
    createWorker: function() {
      return new Worker('lua/benchmark-worker.js')
    },
    calculate: function() {
      return this.msg.startup/1000;
    },
    normalized: function() {
      return 0.10/Math.max(this.calculate(), 1/60); // resolution: 1 frame
    },
  },

  { title: 'Variance', description: 'Runs many frames of a long-running simulation and tests variability and the worst case among them' },

  {
    benchmark: 'box2d-variance',
    description: 'Box2D physics: frame rate variance',
    scale: 'milliseconds (lower numbers are better)',
    createWorker: function() {
      return {
        postMessage: function() {
          this.onmessage({ data: {
            benchmark: 'box2d-variance'
          }});
        },
        terminate: function(){},
      };
    },
    calculate: function() {
      var parsed = jobMap['box2d-throughput'].msg;
      return (2*parsed.variance + (parsed.highest - parsed.average))/3;
    },
    normalized: function() {
      return (1/this.calculate());
    },
  },
];

function normalize(job) {
  return Math.round(1000 * job.normalized());
}

var ran = false;
function run() {
  if (ran) return;
  ran = true;

  document.getElementById('results_area').hidden = false;
  document.getElementById('warning').hidden = true;

  var tableBody = document.getElementById('table_body');
  tableBody.innerHTML = '';

  var theButton = document.getElementById('the_button');
  theButton.innerHTML = 'Running benchmarks... (this can take a while)';
  theButton.classList.remove('btn-primary');
  theButton.classList.add('btn-warning');

  function finalCalculation() {
    // normalize based on experimental data
    var normalized = jobs.filter(function(job) { return job.normalized }).map(function(job) { return normalize(job) });
    return Math.round(
      normalized.map(function(x) { return Math.pow(x, 1/normalized.length) }).reduce(function(x, y) { return x * y }, 1)
    );
  }

  var curr = 0;

  function runJob() {

    var job = jobs[curr++];
    if (!job) {
      theButton.innerHTML = 'Score: ' + finalCalculation() + ' (higher numbers are better)';
      theButton.classList.remove('btn-warning');
      theButton.classList.add('btn-success');
      return;
    }
    if (job.title) {
      tableBody.innerHTML += '
' +
                             '  ' + job.title + '	' +
                             '  	' +
                             '  	' +
                             '  ' + (job.description ? job.description + ' (details)' : '') + '	' +
                             '  	' +
                             '
';
      setTimeout(runJob, 1);
      return;
    }

    jobMap[job.benchmark] = job;

    tableBody.innerHTML += '
' +
                           '  ' + job.benchmark + '	' +
                           '

	' +
                           '  ' + job.scale + '	' +
                           '  ' + (job.description || '') + '	' +
                           '

	' +
                           '
';

    document.getElementById(job.benchmark + '-output').innerHTML = '(..running..)';
    document.getElementById(job.benchmark + '-cell').style = 'background-color: #ffddaa';

    // Run the job the specified number of times
    var reps = 0;
    var totalReps = job.totalReps || 1;
    var warmupReps = job.warmupReps || 0;
    var results = [];

    function finish() {
      console.log('final: ' + JSON.stringify(results));
      var final = {};
      for (var i = warmupReps; i < totalReps; i++) {
        var result = results[i];
        for (var k in result) {
          if (typeof result[k] === 'number') {
            final[k] = (final[k] || 0) + result[k];
          }
        }
      }
      for (var k in final) {
        if (typeof final[k] === 'number') {
          final[k] /= totalReps - warmupReps;
        }
      }
      job.msg = final;
      console.log('final: ' + JSON.stringify(job.msg) + ' on ' + (totalReps - warmupReps));

      document.getElementById(job.benchmark + '-output').innerHTML = '' + job.calculate().toFixed(3) + '';
      document.getElementById(job.benchmark + '-cell').style = 'background-color: #bbccff';
      document.getElementById(job.benchmark + '-normalized-output').innerHTML = '' + normalize(job) + '';
      document.getElementById(job.benchmark + '-normalized-cell').style = 'background-color: #ee9955';
      setTimeout(function() {
        runJob();
      }, 1);
    }

    function doRep() {
      var worker = job.createWorker();
      worker.onmessage = function(event) {
        var msg = event.data;
        console.log(JSON.stringify(msg));
        if (msg.benchmark != job.benchmark) throw 'invalid data from benchmark worker';
        results.push(msg);

        reps++;
        if (reps === totalReps) {
          worker.terminate(); // ensure the worker is cleaned up before the next starts
          finish();
        } else {
          setTimeout(doRep, 1);
        }
      };
      console.log('requesting benchmark ' + job.benchmark);
      worker.postMessage({
        benchmark: job.benchmark,
        args: job.args
      });
    }

    doRep();
  }
  runJob();
}

<|endoftext|>


<commit_before>
var AudioHandler = ElementHandler.createComponent("AudioHandler");

AudioHandler.defineAlias("element", "audio");

AudioHandler.defineMethod("construct", function construct() {
  this.paused = true;
});

AudioHandler.prototype.play = function () {
  if (this.paused && this.audio) {
    this.paused = false;

    if (!(this.audio instanceof Audio)) {
      this.audio = new Audio(this.audio);
    }

    // Stop audio fade out
    if (this.fadeOutRoutine) {
      this.fadeOutRoutine.end();
    }

    // Play audio
    this.audio.volume = 1.0;
    this.audio.play();

    console.log("AudioHandler: Playing audio");
  }
};

AudioHandler.prototype.stop = function (fadeOut = 0) {
  if (!this.paused) {
    if (this.audio && this.audio instanceof Audio) {

      var dVolume = this.audio.volume, dVolumeStep = 0.05;
      this.fadeOutRoutine = new Routine(function () {
        if (this.audio && this.audio instanceof Audio && !this.audio.paused) {
          if (this.audio.volume > 0.0) {
            this.audio.volume = Math.max(0.0, this.audio.volume - dVolumeStep);
          } else {
            // End audio fade out
            this.fadeOutRoutine.end();

            // Pause audio
            this.audio.pause();
            this.audio.currentTime = 0;

            console.log("AudioHandler: Audio paused");
          }
        }
      }.bind(this), fadeOut / (dVolume / dVolumeStep));

      console.log("AudioHandler: Audio fading out", fadeOut);

    }

    this.paused = true;
  }
};
<commit_msg>Sync paused state from audio object<commit_after>
var AudioHandler = ElementHandler.createComponent("AudioHandler");

AudioHandler.defineAlias("element", "audio");

AudioHandler.defineMethod("construct", function construct() {
  this.paused = true;
});

AudioHandler.prototype.play = function () {
  if (this.audio) {
    // If the audio handler is not paused, sync the state of the audio handler to that of the audio object
    // Otherwise, the audio handler is paused, and should start playing the audio
    this.paused |= this.audio.paused;

    if (this.paused) {
      this.paused = false;

      if (!(this.audio instanceof Audio)) {
        this.audio = new Audio(this.audio);
      }

      // Stop audio fade out
      if (this.fadeOutRoutine) {
        this.fadeOutRoutine.end();
      }

      // Play audio
      this.audio.volume = 1.0;
      this.audio.play();

      console.log("AudioHandler: Playing audio");
    }
  }
};

AudioHandler.prototype.stop = function (fadeOut = 0) {
  if (!this.paused) {
    if (this.audio && this.audio instanceof Audio) {

      var dVolume = this.audio.volume, dVolumeStep = 0.05;
      this.fadeOutRoutine = new Routine(function () {
        if (this.audio && this.audio instanceof Audio && !this.audio.paused) {
          if (this.audio.volume > 0.0) {
            this.audio.volume = Math.max(0.0, this.audio.volume - dVolumeStep);
          } else {
            // End audio fade out
            this.fadeOutRoutine.end();

            // Pause audio
            this.audio.pause();
            this.audio.currentTime = 0;

            console.log("AudioHandler: Audio paused");
          }
        }
      }.bind(this), fadeOut / (dVolume / dVolumeStep));

      console.log("AudioHandler: Audio fading out", fadeOut);

    }

    this.paused = true;
  }
};
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "menus", "tabManager", "commands", "apf"
    ];
    main.provides = ["undo"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var menus = imports.menus;
        var commands = imports.commands;
        var tabs = imports.tabManager;
        var apf = imports.apf;

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

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        function canDo (actionName) {
            return function () {
                var tab = tabs.focussedTab;
                return  tab && tab.document.undoManager[actionName]();
            };
        }

        var canUndo = canDo("canUndo");
        var canRedo = canDo("canRedo");

        var loaded = false;
        function load(callback) {
            if (loaded) return false;
            loaded = true;

            commands.addCommand({
                name: "c9_undo",
                exec: undo,
                isAvailable: canUndo,
                bindKey: {mac: "Command-Z", win: "Ctrl-Z"}
            }, plugin);
            commands.addCommand({
                name: "c9_redo",
                exec: redo,
                isAvailable: canRedo,
                bindKey: {mac: "Command-Shift-Z|Command-Y", win: "Ctrl-Shift-Z|Ctrl-Y"}
            }, plugin);

            menus.addItemByPath("Edit/Undo", new apf.item({
                command: "c9_undo"
            }), 100, plugin);
            menus.addItemByPath("Edit/Redo", new apf.item({
                command: "c9_redo"
            }), 200, plugin);
        }

        /***** Methods *****/
        function undo(editor) {
            if (editor && editor.ace)
                editor.ace.execCommand("undo");
            else if (canUndo() && apf.isChildOf(tabs.container, apf.activeElement, true))
                tabs.focussedTab.document.undoManager.undo();
            // else if (apf.activeElement == self.trFiles) {
                //@todo the way undo is implemented doesn't work right now
                //trFiles.getActionTracker().undo();
            // }
        }

        function redo(editor) {
            if (editor && editor.ace)
                editor.ace.execCommand("redo");
            else if (canRedo() && apf.isChildOf(tabs.container, apf.activeElement, true))
                tabs.focussedTab.document.undoManager.redo();
            // else if (apf.activeElement == self.trFiles) {
                //@todo the way undo is implemented doesn't work right now
                //trFiles.getActionTracker().redo();
            // }
        }

        /***** Lifecycle *****/
        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

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

        });
        plugin.on("unload", function(){
            loaded = false;
        });

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

        /**
         * Undo module for Cloud9
         * @singleton
         */
        plugin.freezePublicAPI({
            /**
             * Reverts the last edit made to the currently focussed tab document
             */
            undo: undo,

            /**
             * Re-executes the last reverted edit in the currently focussed tab document
             */
            redo: redo
        });

        register(null, {
            undo: plugin
        });
    }
});
<commit_msg>fix undo in dialogs<commit_after>define(function(require, exports, module) {
    "use strict";

    main.consumes = [
        "Plugin", "menus", "tabManager", "commands", "apf"
    ];
    main.provides = ["undo"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var menus = imports.menus;
        var commands = imports.commands;
        var tabs = imports.tabManager;
        var apf = imports.apf;

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

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        function canDo (actionName) {
            return function (editor, args, event) {
                var tab = tabs.focussedTab;
                if (!tab) return;
                if (event instanceof KeyboardEvent && !tabs.focussed)
                    return false;
                return  tab && tab.document.undoManager[actionName]();
            };
        }

        var canUndo = canDo("canUndo");
        var canRedo = canDo("canRedo");

        var loaded = false;
        function load(callback) {
            if (loaded) return false;
            loaded = true;

            commands.addCommand({
                name: "undo",
                exec: undo,
                isAvailable: canUndo,
                bindKey: {mac: "Command-Z", win: "Ctrl-Z"}
            }, plugin);
            commands.addCommand({
                name: "redo",
                exec: redo,
                isAvailable: canRedo,
                bindKey: {mac: "Command-Shift-Z|Command-Y", win: "Ctrl-Shift-Z|Ctrl-Y"}
            }, plugin);

            menus.addItemByPath("Edit/Undo", new apf.item({
                command: "undo"
            }), 100, plugin);
            menus.addItemByPath("Edit/Redo", new apf.item({
                command: "redo"
            }), 200, plugin);
        }

        /***** Methods *****/
        function undo(editor) {
            if (editor && editor.ace)
                editor.ace.execCommand("undo");
            else if (canUndo() && apf.isChildOf(tabs.container, apf.activeElement, true))
                tabs.focussedTab.document.undoManager.undo();
        }

        function redo(editor) {
            if (editor && editor.ace)
                editor.ace.execCommand("redo");
            else if (canRedo() && apf.isChildOf(tabs.container, apf.activeElement, true))
                tabs.focussedTab.document.undoManager.redo();
        }

        /***** Lifecycle *****/
        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

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

        });
        plugin.on("unload", function(){
            loaded = false;
        });

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

        /**
         * Undo module for Cloud9
         * @singleton
         */
        plugin.freezePublicAPI({
            /**
             * Reverts the last edit made to the currently focussed tab document
             */
            undo: undo,

            /**
             * Re-executes the last reverted edit in the currently focussed tab document
             */
            redo: redo
        });

        register(null, {
            undo: plugin
        });
    }
});
<|endoftext|>


<commit_before>"use strict";

var xml2js = require('xml2js'),
    findType = /(.+\/[^;]+)/;

//Make JSON.parse async
function parseJSON(str, callback) {
  try {
    var parsed = JSON.parse(str);
  } catch (e) {
    return callback(e);
  }

  callback(null, parsed);
}

var supportedParsers = {
  'application/json': parseJSON,
  'text/json': parseJSON,
  'text/x-json': parseJSON,
  'application/xml': xml2js.parseString,
  'text/xml': xml2js.parseString,
  'application/atom+xml': xml2js.parseString
};

module.exports = function parser(res, next) {
  var matchedContentType = (res.headers['content-type'] || '').match(findType),
      parserLib;

  if (!(matchedContentType && (parserLib = supportedParsers[matchedContentType[0]]))) return next();

  parserLib(res.body, function(err, parsed) {
    res.parsedBody = parsed;
    next(err); //If there's an error, it will be passed to the callback
  });
};
<commit_msg>safe parsing for empty strings on 204<commit_after>"use strict";

var xml2js = require('xml2js'),
    findType = /(.+\/[^;]+)/;

//Make JSON.parse async
function parseJSON(str, callback) {
  try {
    var parsed = JSON.parse(str);
  } catch (e) {
    return callback(e);
  }

  callback(null, parsed);
}

var unsupportedCodes = {
  204: true
}

var supportedParsers = {
  'application/json': parseJSON,
  'text/json': parseJSON,
  'text/x-json': parseJSON,
  'application/xml': xml2js.parseString,
  'text/xml': xml2js.parseString,
  'application/atom+xml': xml2js.parseString
};

module.exports = function parser(res, next) {
  //Check headers before performing parse
  if(unsuporedCodes[res.statusCode]) return next();

  var matchedContentType = (res.headers['content-type'] || '').match(findType),
      parserLib;

  if (!(matchedContentType && (parserLib = supportedParsers[matchedContentType[0]]))) return next();

  parserLib(res.body, function(err, parsed) {
    res.parsedBody = parsed;
    next(err); //If there's an error, it will be passed to the callback
  });
};
<|endoftext|>


<commit_before>function cam_ar() {
	container  = {};
	container.win = Titanium.UI.createWindow();

	container.button = Titanium.UI.createButton({
		color:'#fff',
		backgroundImage:'/images/BUTT_grn_on.png',
		backgroundSelectedImage:'/images/BUTT_grn_off.png',
		backgroundDisabledImage: '/images/BUTT_gry_on.png',
		bottom:10,
		width:301,
		height:57,
		font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		title:'Cancel'
	});

	container.button.addEventListener('click',function()
	{
		alert("Close the camera");
		Ti.Media.hideCamera();
		container.close();
	});

	container.messageView = Titanium.UI.createView({
		height:60,
		width:250,
		top:10
	});

	container.indView = Titanium.UI.createView({
		height:60,
		width:270,
		backgroundColor:'#000',
		borderRadius:10,
		opacity:0.7
	});
	container.messageView.add(container.indView);

	// message
	container.message = Titanium.UI.createLabel({
		text:'Calculating...',
		color:'#fff',
		font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:270,
		height:'auto'
	});
	container.messageView.add(container.message);

	container.overlay = Titanium.UI.createView();
	container.overlay.add(container.button);
	container.overlay.add(container.messageView);

	container.heading;
	container.gps='...';
	container.address='calculating address';

	container.refreshLabel = function ()
	{
		var text = "Heading: "+Math.round(container.heading)+"°, Location: "+container.gps;
		if (container.address)
		{
			text+="\n"+container.address;
		}
		container.message.text = text;
	}

	Titanium.Geolocation.purpose = "AR Demo";

	Titanium.Geolocation.addEventListener('location',function(e)
	{
		var longitude = e.coords.longitude;
		var latitude = e.coords.latitude;
		container.gps = Math.round(longitude)+' x '+Math.round(latitude);
		Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
		{
			var places = evt.places[0];
			container.address = places.street ? places.street : places.address;
			container.refreshLabel();
		});
		container.refreshLabel();
	});

	Titanium.Geolocation.addEventListener('heading',function(e)
	{
		if (e.error)
		{
			container.updatedHeading.text = 'error: ' + e.error;
			return;
		}

		container.heading = e.heading.magneticHeading;
		container.refreshLabel();
	});

	Titanium.Media.showCamera({

		success:function(event)
		{
		},
		cancel:function()
		{
		},
		error:function(error)
		{
			var a = Titanium.UI.createAlertDialog({title:'Camera'});
			if (error.code == Titanium.Media.NO_CAMERA)
			{
				a.setMessage('Please run this test on device');
			}
			else
			{
				a.setMessage('Unexpected error: ' + error.code);
			}
			a.show();
		},
		overlay:container.overlay,
		showControls:false,	// don't show system controls
		mediaTypes:Ti.Media.MEDIA_TYPE_PHOTO,
		autohide:false	// tell the system not to auto-hide and we'll do it ourself
	});

	container.open = function(){
		container.win.open();
	};

	container.close = function(){
		container.win.close();
	}

	return container;
};

module.exports = cam_ar;<commit_msg>[TIMOB-10133] Replacing the accidentally removed code.<commit_after>function cam_ar() {
	container  = {};
	container.win = Titanium.UI.createWindow();

	container.button = Titanium.UI.createButton({
		color:'#fff',
		backgroundImage:'/images/BUTT_grn_on.png',
		backgroundSelectedImage:'/images/BUTT_grn_off.png',
		backgroundDisabledImage: '/images/BUTT_gry_on.png',
		bottom:10,
		width:301,
		height:57,
		font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		title:'Cancel'
	});

	container.button.addEventListener('click',function()
	{
		alert("Close the camera");
		Ti.Media.hideCamera();
		container.close();
	});

	container.messageView = Titanium.UI.createView({
		height:60,
		width:250,
		top:10
	});

	container.indView = Titanium.UI.createView({
		height:60,
		width:270,
		backgroundColor:'#000',
		borderRadius:10,
		opacity:0.7
	});
	container.messageView.add(container.indView);

	// message
	container.message = Titanium.UI.createLabel({
		text:'Calculating...',
		color:'#fff',
		font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:270,
		height:'auto'
	});
	container.messageView.add(container.message);

	container.overlay = Titanium.UI.createView();
	container.overlay.add(container.button);
	container.overlay.add(container.messageView);

	container.heading;
	container.gps='...';
	container.address='calculating address';

	container.refreshLabel = function ()
	{
		var text = "Heading: "+Math.round(container.heading)+"°, Location: "+container.gps;
		if (container.address)
		{
			text+="\n"+container.address;
		}
		container.message.text = text;
	}

	Ti.include("/etc/version.js");
	if (isIPhone3_2_Plus())
	{
		Titanium.Geolocation.purpose = "AR Demo";
	}

	Titanium.Geolocation.addEventListener('location',function(e)
	{
		var longitude = e.coords.longitude;
		var latitude = e.coords.latitude;
		container.gps = Math.round(longitude)+' x '+Math.round(latitude);
		Titanium.Geolocation.reverseGeocoder(latitude,longitude,function(evt)
		{
			var places = evt.places[0];
			container.address = places.street ? places.street : places.address;
			container.refreshLabel();
		});
		container.refreshLabel();
	});

	Titanium.Geolocation.addEventListener('heading',function(e)
	{
		if (e.error)
		{
			container.updatedHeading.text = 'error: ' + e.error;
			return;
		}

		container.heading = e.heading.magneticHeading;
		container.refreshLabel();
	});

	Titanium.Media.showCamera({

		success:function(event)
		{
		},
		cancel:function()
		{
		},
		error:function(error)
		{
			var a = Titanium.UI.createAlertDialog({title:'Camera'});
			if (error.code == Titanium.Media.NO_CAMERA)
			{
				a.setMessage('Please run this test on device');
			}
			else
			{
				a.setMessage('Unexpected error: ' + error.code);
			}
			a.show();
		},
		overlay:container.overlay,
		showControls:false,	// don't show system controls
		mediaTypes:Ti.Media.MEDIA_TYPE_PHOTO,
		autohide:false	// tell the system not to auto-hide and we'll do it ourself
	});

	container.open = function(){
		container.win.open();
	};

	container.close = function(){
		container.win.close();
	}

	return container;
};

module.exports = cam_ar;<|endoftext|>


<commit_before>import React from 'react';
import CharacterSlider from './slider/';
import BuyButton from './BuyButton';
import AssetsConfig from './AssetsConfig';

export default (
  () => (

      <CharacterSlider />
      <BuyButton />
      <AssetsConfig />

  )
);
<commit_msg>Hide assets config<commit_after>import React from 'react';
import CharacterSlider from './slider/';
import BuyButton from './BuyButton';
// import AssetsConfig from './AssetsConfig';

export default (
  () => (

      <CharacterSlider />
      <BuyButton />
      {/*<AssetsConfig />*/}

  )
);
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// 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.

const {group} = require('./messages/common-strings');

const PLUGIN_PATH = 'lighthouse-plugin-publisher-ads';

/** @type {LH.Config.Plugin} */
module.exports = {
  audits: [
    {path: `${PLUGIN_PATH}/audits/ad-blocking-tasks`},
    {path: `${PLUGIN_PATH}/audits/ad-render-blocking-resources`},
    {path: `${PLUGIN_PATH}/audits/ad-request-critical-path`},
    {path: `${PLUGIN_PATH}/audits/ad-request-from-page-start`},
    {path: `${PLUGIN_PATH}/audits/ad-request-from-tag-load`},
    {path: `${PLUGIN_PATH}/audits/ad-top-of-viewport`},
    {path: `${PLUGIN_PATH}/audits/ads-in-viewport`},
    {path: `${PLUGIN_PATH}/audits/async-ad-tags`},
    {path: `${PLUGIN_PATH}/audits/blocking-load-events`},
    {path: `${PLUGIN_PATH}/audits/bottleneck-requests`},
    {path: `${PLUGIN_PATH}/audits/duplicate-tags`},
    {path: `${PLUGIN_PATH}/audits/first-ad-render`},
    {path: `${PLUGIN_PATH}/audits/full-width-slots`},
    {path: `${PLUGIN_PATH}/audits/gpt-bids-parallel`},
    {path: `${PLUGIN_PATH}/audits/idle-network-times`},
    {path: `${PLUGIN_PATH}/audits/loads-gpt-from-sgdn`},
    {path: `${PLUGIN_PATH}/audits/loads-ad-tag-over-https`},
    {path: `${PLUGIN_PATH}/audits/script-injected-tags`},
    {path: `${PLUGIN_PATH}/audits/serial-header-bidding`},
    {path: `${PLUGIN_PATH}/audits/tag-load-time`},
    {path: `${PLUGIN_PATH}/audits/viewport-ad-density`},
  ],
  groups: {
    'metrics': {
      title: group.Metrics,
    },
    'ads-performance': {
      title: group.AdsPerformance,
    },
    'ads-best-practices': {
      title: group.AdsBestPractices,
    },
  },
  category: {
    title: 'Publisher Ads [Beta]',
    auditRefs: [
      // Measurements group.
      {id: 'tag-load-time', weight: 4, group: 'metrics'},
      {id: 'ad-request-from-tag-load', weight: 4, group: 'metrics'},
      {id: 'ad-request-from-page-start', weight: 4, group: 'metrics'},
      {id: 'first-ad-render', weight: 8, group: 'metrics'},
      // Performance group.
      {id: 'bottleneck-requests', weight: 1, group: 'ads-performance'},
      {id: 'gpt-bids-parallel', weight: 1, group: 'ads-performance'},
      {id: 'serial-header-bidding', weight: 1, group: 'ads-performance'},
      {id: 'script-injected-tags', weight: 1, group: 'ads-performance'},
      {id: 'blocking-load-events', weight: 1, group: 'ads-performance'},
      {id: 'ad-render-blocking-resources', weight: 1, group: 'ads-performance'},
      {id: 'ad-blocking-tasks', weight: 1, group: 'ads-performance'},
      {id: 'ad-request-critical-path', weight: 1, group: 'ads-performance'},
      // Best Practices group.
      {id: 'ads-in-viewport', weight: 4, group: 'ads-best-practices'},
      {id: 'async-ad-tags', weight: 2, group: 'ads-best-practices'},
      {id: 'loads-ad-tag-over-https', weight: 1, group: 'ads-best-practices'},
      {id: 'loads-gpt-from-sgdn', weight: 1, group: 'ads-best-practices'},
      {id: 'viewport-ad-density', weight: 1, group: 'ads-best-practices'},
      {id: 'ad-top-of-viewport', weight: 2, group: 'ads-best-practices'},
      {id: 'duplicate-tags', weight: 1, group: 'ads-best-practices'},
      // The following audits are run but not shown. We include them to be able
      // collect metadata about the audit, but decide to hide them since they
      // aren't actionable to end users.
      {id: 'idle-network-times', weight: 0},
    ],
  },
};
<commit_msg>Remove `idle-network-times` audit from config. (#136)<commit_after>// Copyright 2018 Google LLC
//
// 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.

const {group} = require('./messages/common-strings');

const PLUGIN_PATH = 'lighthouse-plugin-publisher-ads';

/** @type {LH.Config.Plugin} */
module.exports = {
  audits: [
    {path: `${PLUGIN_PATH}/audits/ad-blocking-tasks`},
    {path: `${PLUGIN_PATH}/audits/ad-render-blocking-resources`},
    {path: `${PLUGIN_PATH}/audits/ad-request-critical-path`},
    {path: `${PLUGIN_PATH}/audits/ad-request-from-page-start`},
    {path: `${PLUGIN_PATH}/audits/ad-request-from-tag-load`},
    {path: `${PLUGIN_PATH}/audits/ad-top-of-viewport`},
    {path: `${PLUGIN_PATH}/audits/ads-in-viewport`},
    {path: `${PLUGIN_PATH}/audits/async-ad-tags`},
    {path: `${PLUGIN_PATH}/audits/blocking-load-events`},
    {path: `${PLUGIN_PATH}/audits/bottleneck-requests`},
    {path: `${PLUGIN_PATH}/audits/duplicate-tags`},
    {path: `${PLUGIN_PATH}/audits/first-ad-render`},
    {path: `${PLUGIN_PATH}/audits/full-width-slots`},
    {path: `${PLUGIN_PATH}/audits/gpt-bids-parallel`},
    {path: `${PLUGIN_PATH}/audits/loads-gpt-from-sgdn`},
    {path: `${PLUGIN_PATH}/audits/loads-ad-tag-over-https`},
    {path: `${PLUGIN_PATH}/audits/script-injected-tags`},
    {path: `${PLUGIN_PATH}/audits/serial-header-bidding`},
    {path: `${PLUGIN_PATH}/audits/tag-load-time`},
    {path: `${PLUGIN_PATH}/audits/viewport-ad-density`},
  ],
  groups: {
    'metrics': {
      title: group.Metrics,
    },
    'ads-performance': {
      title: group.AdsPerformance,
    },
    'ads-best-practices': {
      title: group.AdsBestPractices,
    },
  },
  category: {
    title: 'Publisher Ads [Beta]',
    auditRefs: [
      // Measurements group.
      {id: 'tag-load-time', weight: 4, group: 'metrics'},
      {id: 'ad-request-from-tag-load', weight: 4, group: 'metrics'},
      {id: 'ad-request-from-page-start', weight: 4, group: 'metrics'},
      {id: 'first-ad-render', weight: 8, group: 'metrics'},
      // Performance group.
      {id: 'bottleneck-requests', weight: 1, group: 'ads-performance'},
      {id: 'gpt-bids-parallel', weight: 1, group: 'ads-performance'},
      {id: 'serial-header-bidding', weight: 1, group: 'ads-performance'},
      {id: 'script-injected-tags', weight: 1, group: 'ads-performance'},
      {id: 'blocking-load-events', weight: 1, group: 'ads-performance'},
      {id: 'ad-render-blocking-resources', weight: 1, group: 'ads-performance'},
      {id: 'ad-blocking-tasks', weight: 1, group: 'ads-performance'},
      {id: 'ad-request-critical-path', weight: 1, group: 'ads-performance'},
      // Best Practices group.
      {id: 'ads-in-viewport', weight: 4, group: 'ads-best-practices'},
      {id: 'async-ad-tags', weight: 2, group: 'ads-best-practices'},
      {id: 'loads-ad-tag-over-https', weight: 1, group: 'ads-best-practices'},
      {id: 'loads-gpt-from-sgdn', weight: 1, group: 'ads-best-practices'},
      {id: 'viewport-ad-density', weight: 1, group: 'ads-best-practices'},
      {id: 'ad-top-of-viewport', weight: 2, group: 'ads-best-practices'},
      {id: 'duplicate-tags', weight: 1, group: 'ads-best-practices'},
    ],
  },
};
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd.
Copyright 2017 New Vector Ltd

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';

import utils from 'matrix-js-sdk/lib/utils';
import EventTimeline from 'matrix-js-sdk/lib/models/event-timeline';
import EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set';
import createMatrixClient from './utils/createMatrixClient';
import SettingsStore from './settings/SettingsStore';
import MatrixActionCreators from './actions/MatrixActionCreators';

interface MatrixClientCreds {
    homeserverUrl: string,
    identityServerUrl: string,
    userId: string,
    deviceId: string,
    accessToken: string,
    guest: boolean,
}

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;

        // These are the default options used when when the
        // client is started in 'start'. These can be altered
        // at any time up to after the 'will_start_client'
        // event is finished processing.
        this.opts = {
            initialSyncLimit: 20,
        };
    }

    /**
     * Sets the script href passed to the IndexedDB web worker
     * If set, a separate web worker will be started to run the IndexedDB
     * queries on.
     *
     * @param {string} script href to the script to be passed to the web worker
     */
    setIndexedDbWorkerScript(script) {
        createMatrixClient.indexedDbWorkerScript = script;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;

        MatrixActionCreators.stop();
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs and active credentials
     */
    replaceUsingCreds(creds: MatrixClientCreds) {
        this._createClient(creds);
    }

    async start() {
        // try to initialise e2e on the new client
        try {
            // check that we have a version of the js-sdk which includes initCrypto
            if (this.matrixClient.initCrypto) {
                await this.matrixClient.initCrypto();
            }
        } catch (e) {
            // this can happen for a number of reasons, the most likely being
            // that the olm library was missing. It's not fatal.
            console.warn("Unable to initialise e2e: " + e);
        }

        const opts = utils.deepCopy(this.opts);
        // the react sdk doesn't work without this, so don't allow
        opts.pendingEventOrdering = "detached";

        try {
            const promise = this.matrixClient.store.startup();
            console.log(`MatrixClientPeg: waiting for MatrixClient store to initialise`);
            await promise;
        } catch (err) {
            // log any errors when starting up the database (if one exists)
            console.error(`Error starting matrixclient store: ${err}`);
        }

        // regardless of errors, start the client. If we did error out, we'll
        // just end up doing a full initial /sync.

        // Connect the matrix client to the dispatcher
        MatrixActionCreators.start(this.matrixClient);

        console.log(`MatrixClientPeg: really starting MatrixClient`);
        this.get().startClient(opts);
        console.log(`MatrixClientPeg: MatrixClient started`);
    }

    getCredentials(): MatrixClientCreds {
        return {
            homeserverUrl: this.matrixClient.baseUrl,
            identityServerUrl: this.matrixClient.idBaseUrl,
            userId: this.matrixClient.credentials.userId,
            deviceId: this.matrixClient.getDeviceId(),
            accessToken: this.matrixClient.getAccessToken(),
            guest: this.matrixClient.isGuest(),
        };
    }

    /**
     * Return the server name of the user's home server
     * Throws an error if unable to deduce the home server name
     * (eg. if the user is not logged in)
     */
    getHomeServerName() {
        const matches = /^@.+:(.+)$/.exec(this.matrixClient.credentials.userId);
        if (matches === null || matches.length < 1) {
            throw new Error("Failed to derive home server name from user ID!");
        }
        return matches[1];
    }

    _createClient(creds: MatrixClientCreds) {
        const opts = {
            baseUrl: creds.homeserverUrl,
            idBaseUrl: creds.identityServerUrl,
            accessToken: creds.accessToken,
            userId: creds.userId,
            deviceId: creds.deviceId,
            timelineSupport: true,
            forceTURN: SettingsStore.getValue('webRtcForceTURN', false),
        };

        this.matrixClient = createMatrixClient(opts, this.indexedDbWorkerScript);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);

        this.matrixClient.setGuest(Boolean(creds.guest));

        const notifTimelineSet = new EventTimelineSet(null, {
            timelineSupport: true,
        });
        // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
        notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
        this.matrixClient.setNotifTimelineSet(notifTimelineSet);
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
}
export default global.mxMatrixClientPeg;
<commit_msg>[WIP] Send lazy_load_memberers filter when syncing<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd.
Copyright 2017 New Vector Ltd

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';

import utils from 'matrix-js-sdk/lib/utils';
import EventTimeline from 'matrix-js-sdk/lib/models/event-timeline';
import EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set';
import createMatrixClient from './utils/createMatrixClient';
import SettingsStore from './settings/SettingsStore';
import MatrixActionCreators from './actions/MatrixActionCreators';

interface MatrixClientCreds {
    homeserverUrl: string,
    identityServerUrl: string,
    userId: string,
    deviceId: string,
    accessToken: string,
    guest: boolean,
}

const FILTER_CONTENT = {
    room: {
        state: {
            lazy_load_members: true,
        },
    },
};

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;

        // These are the default options used when when the
        // client is started in 'start'. These can be altered
        // at any time up to after the 'will_start_client'
        // event is finished processing.
        this.opts = {
            initialSyncLimit: 20,
        };
    }

    /**
     * Sets the script href passed to the IndexedDB web worker
     * If set, a separate web worker will be started to run the IndexedDB
     * queries on.
     *
     * @param {string} script href to the script to be passed to the web worker
     */
    setIndexedDbWorkerScript(script) {
        createMatrixClient.indexedDbWorkerScript = script;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;

        MatrixActionCreators.stop();
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * Home Server / Identity Server URLs and active credentials
     */
    replaceUsingCreds(creds: MatrixClientCreds) {
        this._createClient(creds);
    }

    async start() {
        // try to initialise e2e on the new client
        try {
            // check that we have a version of the js-sdk which includes initCrypto
            if (this.matrixClient.initCrypto) {
                await this.matrixClient.initCrypto();
            }
        } catch (e) {
            // this can happen for a number of reasons, the most likely being
            // that the olm library was missing. It's not fatal.
            console.warn("Unable to initialise e2e: " + e);
        }

        const opts = utils.deepCopy(this.opts);
        // the react sdk doesn't work without this, so don't allow
        opts.pendingEventOrdering = "detached";

        opts.filter = await this.matrixClient.createFilter(FILTER_CONTENT);

        try {
            const promise = this.matrixClient.store.startup();
            console.log(`MatrixClientPeg: waiting for MatrixClient store to initialise`);
            await promise;
        } catch (err) {
            // log any errors when starting up the database (if one exists)
            console.error(`Error starting matrixclient store: ${err}`);
        }

        // regardless of errors, start the client. If we did error out, we'll
        // just end up doing a full initial /sync.

        // Connect the matrix client to the dispatcher
        MatrixActionCreators.start(this.matrixClient);

        console.log(`MatrixClientPeg: really starting MatrixClient`);
        this.get().startClient(opts);
        console.log(`MatrixClientPeg: MatrixClient started`);
    }

    getCredentials(): MatrixClientCreds {
        return {
            homeserverUrl: this.matrixClient.baseUrl,
            identityServerUrl: this.matrixClient.idBaseUrl,
            userId: this.matrixClient.credentials.userId,
            deviceId: this.matrixClient.getDeviceId(),
            accessToken: this.matrixClient.getAccessToken(),
            guest: this.matrixClient.isGuest(),
        };
    }

    /**
     * Return the server name of the user's home server
     * Throws an error if unable to deduce the home server name
     * (eg. if the user is not logged in)
     */
    getHomeServerName() {
        const matches = /^@.+:(.+)$/.exec(this.matrixClient.credentials.userId);
        if (matches === null || matches.length < 1) {
            throw new Error("Failed to derive home server name from user ID!");
        }
        return matches[1];
    }

    _createClient(creds: MatrixClientCreds) {
        const opts = {
            baseUrl: creds.homeserverUrl,
            idBaseUrl: creds.identityServerUrl,
            accessToken: creds.accessToken,
            userId: creds.userId,
            deviceId: creds.deviceId,
            timelineSupport: true,
            forceTURN: SettingsStore.getValue('webRtcForceTURN', false),
        };

        this.matrixClient = createMatrixClient(opts, this.indexedDbWorkerScript);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);

        this.matrixClient.setGuest(Boolean(creds.guest));

        const notifTimelineSet = new EventTimelineSet(null, {
            timelineSupport: true,
        });
        // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
        notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
        this.matrixClient.setNotifTimelineSet(notifTimelineSet);
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
}
export default global.mxMatrixClientPeg;
<|endoftext|>


<commit_before>/*global $ */
/*jslint
 white: true */

"use strict";

/**
 * @name GOVUK
 * @namespace
 * @description Global namespace for gov.uk
 * @requires jquery 1.6.2
*/
var GOVUK = GOVUK || {};

/**
  @name GOVUK.HmrcContacts
  @memberOf GOVUK
  @namespace
  @description A set of methods for handling behaviours with HMRC Contacts app functionality
  @requires jquery 1.6.2
*/
GOVUK.HmrcContacts = {
  /**
    @name GOVUK.HmrcContacts.contactGroupList
    @object
    @description container for contact group list behaviour
  */
  chosenSelect : {
    initialize: function () {
      $(".js-chosen-select").chosen();
    }
  },
  /**
    @name GOVUK.HmrcContacts.commonQuestionsSelect
    @object
    @description common questions select functionality in landing page
  */
  commonQuestionsSelect : {
    initialize: function () {
      var $select = $("#commonly-asked-questions .js-chosen-select"),
          namespace = this;

      this.hideAllSections();
      this.showSection($select.chosen().val());

      $select.chosen().change(function(){
        namespace.hideAllSections();
        namespace.showSection($(this).val());
      });
    },

    hideAllSections : function () {
      $(".common-sections").addClass("common-sections-hidden");
    },

    showSection : function (sectionIdentifier) {
      $('#section-' + sectionIdentifier).removeClass("common-sections-hidden");
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactGroupList
    @object
    @description container for contact group list behaviour
  */
  contactGroupList : {
      /**
        @name GOVUK.HmrcContacts.toggledControl.initialize
        @function
        @description initializes namespace
      */
      toggledControl: {
        initialize: function(control) {
          var $control = $(control),
              $controlledElement = $($control.data('expand')),
              $container = $control.closest('.department');

          // hide all expandables unless asked to open
          if (window.location.hash != $control.attr('href')) {
            $controlledElement.addClass('js-hidden');
            $container.addClass('js-hiding-children');
          }

          $control.on('click', function (e) {
            var isOpen = $container.hasClass("js-hiding-children");

            if ($control.hasClass("view-all")) {
              $control.text((isOpen) ? 'hide all' : 'view all');
            } else {
              $container.find(".view-all").text((isOpen) ? 'hide all' : 'view all');
            }

            $controlledElement.toggleClass('js-hidden');
            $container.toggleClass('js-hiding-children');
          });
        }
      },
      /**
        @name GOVUK.contactGroupList.initialize
        @function
        @description initializes namespace
      */
      initialize : function () {
        var contactGroupToggle = '[data-expand]',
            namespace = this;

        $(contactGroupToggle).each(function(idx, element){
          namespace.toggledControl.initialize(element);
        })
      }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailList
    @object
    @description the list that includes email addresses, phone numbers etc
  */
  contactDetailList : {
    initialize: function () {
      var $contactDetailList = $('.contact-detail'),
          $groupHideLinks = $contactDetailList.find('.js-hide-link');

      $groupHideLinks.on('click', function(event){
        $(this).closest(".js-hide-container").toggleClass("js-hide");

        return false;
      });
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailPrivacyInfoShow
    @object
    @description show the email privacy info for contact details
  */
  contactDetailPrivacyInfoShow : {
    initialize: function () {
      var privacySecurityInfo = $(".privacy-security-info");
      if (privacySecurityInfo.size() > 0){
        privacySecurityInfo.addClass("js-hidden");

        privacySecurityInfo.find("a").click(function(e){
          e.preventDefault();
          $(this).closest(".privacy-security-info").removeClass("js-hidden");
        });
      }
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailPrivacyInfoShow
    @object
    @description show the contact details navigation when viewed with slim browsers
  */
  contactDetailNavigationShow : {
    initialize: function () {
      var navigationShowLink = $(".show-all-parts");

      navigationShowLink.click(function(e){
        e.preventDefault();
        $(this).toggleClass("show-all-parts-open");
        $(this).parent().find(".page-navigation").toggleClass("page-navigation-closed").toggleClass("page-navigation-open");

        if ($(this).hasClass("show-all-parts-open")){
          $(this).text("Hide all parts of this guide");
        }else{
          $(this).text("Show all parts of this guide");
        }
      });
    }
  },
  /**
    @name onLoad
    @function
    @description behaviour init point
  */
  onLoad : function () {
    this.contactGroupList.initialize();
    this.contactDetailList.initialize();
    this.contactDetailPrivacyInfoShow.initialize();
    this.contactDetailNavigationShow.initialize();
    this.chosenSelect.initialize();
    this.commonQuestionsSelect.initialize();
  }
};
<commit_msg>COPY tweak when a contact group is already open by default it says hide all<commit_after>/*global $ */
/*jslint
 white: true */

"use strict";

/**
 * @name GOVUK
 * @namespace
 * @description Global namespace for gov.uk
 * @requires jquery 1.6.2
*/
var GOVUK = GOVUK || {};

/**
  @name GOVUK.HmrcContacts
  @memberOf GOVUK
  @namespace
  @description A set of methods for handling behaviours with HMRC Contacts app functionality
  @requires jquery 1.6.2
*/
GOVUK.HmrcContacts = {
  /**
    @name GOVUK.HmrcContacts.contactGroupList
    @object
    @description container for contact group list behaviour
  */
  chosenSelect : {
    initialize: function () {
      $(".js-chosen-select").chosen();
    }
  },
  /**
    @name GOVUK.HmrcContacts.commonQuestionsSelect
    @object
    @description common questions select functionality in landing page
  */
  commonQuestionsSelect : {
    initialize: function () {
      var $select = $("#commonly-asked-questions .js-chosen-select"),
          namespace = this;

      this.hideAllSections();
      this.showSection($select.chosen().val());

      $select.chosen().change(function(){
        namespace.hideAllSections();
        namespace.showSection($(this).val());
      });
    },

    hideAllSections : function () {
      $(".common-sections").addClass("common-sections-hidden");
    },

    showSection : function (sectionIdentifier) {
      $('#section-' + sectionIdentifier).removeClass("common-sections-hidden");
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactGroupList
    @object
    @description container for contact group list behaviour
  */
  contactGroupList : {
      /**
        @name GOVUK.HmrcContacts.toggledControl.initialize
        @function
        @description initializes namespace
      */
      toggledControl: {
        initialize: function(control) {
          var $control = $(control),
              $controlledElement = $($control.data('expand')),
              $container = $control.closest('.department');

          // hide all expandables unless asked to open
          if (window.location.hash != $control.attr('href')) {
            $controlledElement.addClass('js-hidden');
            $container.addClass('js-hiding-children');
          }else{
            $container.find(".view-all").text('hide all');
          }

          $control.on('click', function (e) {
            var isOpen = $container.hasClass("js-hiding-children");

            if ($control.hasClass("view-all")) {
              $control.text((isOpen) ? 'hide all' : 'view all');
            } else {
              $container.find(".view-all").text((isOpen) ? 'hide all' : 'view all');
            }

            $controlledElement.toggleClass('js-hidden');
            $container.toggleClass('js-hiding-children');
          });
        }
      },
      /**
        @name GOVUK.contactGroupList.initialize
        @function
        @description initializes namespace
      */
      initialize : function () {
        var contactGroupToggle = '[data-expand]',
            namespace = this;

        $(contactGroupToggle).each(function(idx, element){
          namespace.toggledControl.initialize(element);
        })
      }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailList
    @object
    @description the list that includes email addresses, phone numbers etc
  */
  contactDetailList : {
    initialize: function () {
      var $contactDetailList = $('.contact-detail'),
          $groupHideLinks = $contactDetailList.find('.js-hide-link');

      $groupHideLinks.on('click', function(event){
        $(this).closest(".js-hide-container").toggleClass("js-hide");

        return false;
      });
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailPrivacyInfoShow
    @object
    @description show the email privacy info for contact details
  */
  contactDetailPrivacyInfoShow : {
    initialize: function () {
      var privacySecurityInfo = $(".privacy-security-info");
      if (privacySecurityInfo.size() > 0){
        privacySecurityInfo.addClass("js-hidden");

        privacySecurityInfo.find("a").click(function(e){
          e.preventDefault();
          $(this).closest(".privacy-security-info").removeClass("js-hidden");
        });
      }
    }
  },
  /**
    @name GOVUK.HmrcContacts.contactDetailPrivacyInfoShow
    @object
    @description show the contact details navigation when viewed with slim browsers
  */
  contactDetailNavigationShow : {
    initialize: function () {
      var navigationShowLink = $(".show-all-parts");

      navigationShowLink.click(function(e){
        e.preventDefault();
        $(this).toggleClass("show-all-parts-open");
        $(this).parent().find(".page-navigation").toggleClass("page-navigation-closed").toggleClass("page-navigation-open");

        if ($(this).hasClass("show-all-parts-open")){
          $(this).text("Hide all parts of this guide");
        }else{
          $(this).text("Show all parts of this guide");
        }
      });
    }
  },
  /**
    @name onLoad
    @function
    @description behaviour init point
  */
  onLoad : function () {
    this.contactGroupList.initialize();
    this.contactDetailList.initialize();
    this.contactDetailPrivacyInfoShow.initialize();
    this.contactDetailNavigationShow.initialize();
    this.chosenSelect.initialize();
    this.commonQuestionsSelect.initialize();
  }
};
<|endoftext|>


<commit_before>function debounce(func, wait) {
  var timeout;

  return function () {
    var context = this;
    var args = arguments;
    clearTimeout(timeout);

    timeout = setTimeout(function () {
      timeout = null;
      func.apply(context, args);
    }, wait);
  };
}

// Taken from mdbook
// The strategy is as follows:
// First, assign a value to each word in the document:
//  Words that correspond to search terms (stemmer aware): 40
//  Normal words: 2
//  First word in a sentence: 8
// Then use a sliding window with a constant number of words and count the
// sum of the values of the words within the window. Then use the window that got the
// maximum sum. If there are multiple maximas, then get the last one.
// Enclose the terms in .
function makeTeaser(body, terms) {
  var TERM_WEIGHT = 40;
  var NORMAL_WORD_WEIGHT = 2;
  var FIRST_WORD_WEIGHT = 8;
  var TEASER_MAX_WORDS = 30;

  var stemmedTerms = terms.map(function (w) {
    return elasticlunr.stemmer(w.toLowerCase());
  });
  var termFound = false;
  var index = 0;
  var weighted = []; // contains elements of ["word", weight, index_in_document]

  // split in sentences, then words
  var sentences = body.toLowerCase().split(". ");

  for (var i in sentences) {
    var words = sentences[i].split(" ");
    var value = FIRST_WORD_WEIGHT;

    for (var j in words) {
      var word = words[j];

      if (word.length > 0) {
        for (var k in stemmedTerms) {
          if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
            value = TERM_WEIGHT;
            termFound = true;
          }
        }
        weighted.push([word, value, index]);
        value = NORMAL_WORD_WEIGHT;
      }

      index += word.length;
      index += 1;  // ' ' or '.' if last word in sentence
    }

    index += 1;  // because we split at a two-char boundary '. '
  }

  if (weighted.length === 0) {
    return body;
  }

  var windowWeights = [];
  var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS);
  // We add a window with all the weights first
  var curSum = 0;
  for (var i = 0; i < windowSize; i++) {
    curSum += weighted[i][1];
  }
  windowWeights.push(curSum);

  for (var i = 0; i < weighted.length - windowSize; i++) {
    curSum -= weighted[i][1];
    curSum += weighted[i + windowSize][1];
    windowWeights.push(curSum);
  }

  // If we didn't find the term, just pick the first window
  var maxSumIndex = 0;
  if (termFound) {
    var maxFound = 0;
    // backwards
    for (var i = windowWeights.length - 1; i >= 0; i--) {
      if (windowWeights[i] > maxFound) {
        maxFound = windowWeights[i];
        maxSumIndex = i;
      }
    }
  }

  var teaser = [];
  var startIndex = weighted[maxSumIndex][2];
  for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
    var word = weighted[i];
    if (startIndex < word[2]) {
      // missing text from index to start of `word`
      teaser.push(body.substring(startIndex, word[2]));
      startIndex = word[2];
    }

    // add  around search terms
    if (word[1] === TERM_WEIGHT) {
      teaser.push("");
    }
    startIndex = word[2] + word[0].length;
    teaser.push(body.substring(word[2], startIndex));

    if (word[1] === TERM_WEIGHT) {
      teaser.push("");
    }
  }
  teaser.push("…");
  return teaser.join("");
}

function formatSearchResultItem(item, terms) {
  return '
'
  + `<a href="${item.ref}">${item.doc.title}</a>`
  + `<div>${makeTeaser(item.doc.body, terms)}</div>`
  + '
';
}

function initSearch() {
  var $searchInput = document.getElementById("search");
  var $searchResults = document.querySelector(".search-results");
  var $searchResultsItems = document.querySelector(".search-results__items");
  var MAX_ITEMS = 10;

  var options = {
    bool: "AND",
    fields: {
      title: {boost: 2},
      body: {boost: 1},
    }
  };
  var currentTerm = "";
  var index = elasticlunr.Index.load(window.searchIndex);

  $searchInput.addEventListener("keyup", debounce(function() {
    var term = $searchInput.value.trim();
    if (term === currentTerm || !index) {
      return;
    }
    $searchResults.style.display = term === "" ? "none" : "block";
    $searchResultsItems.innerHTML = "";
    if (term === "") {
      return;
    }

    var results = index.search(term, options);
    if (results.length === 0) {
      $searchResults.style.display = "none";
      return;
    }

    currentTerm = term;
    for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
      var item = document.createElement("li");
      item.innerHTML = formatSearchResultItem(results[i], term.split(" "));
      $searchResultsItems.appendChild(item);
    }
  }, 150));
}

if (document.readyState === "complete" ||
    (document.readyState !== "loading" && !document.documentElement.doScroll)
) {
  initSearch();
} else {
  document.addEventListener("DOMContentLoaded", initSearch);
}
<commit_msg>hide search-results on blur (#1488)<commit_after>function debounce(func, wait) {
  var timeout;

  return function () {
    var context = this;
    var args = arguments;
    clearTimeout(timeout);

    timeout = setTimeout(function () {
      timeout = null;
      func.apply(context, args);
    }, wait);
  };
}

// Taken from mdbook
// The strategy is as follows:
// First, assign a value to each word in the document:
//  Words that correspond to search terms (stemmer aware): 40
//  Normal words: 2
//  First word in a sentence: 8
// Then use a sliding window with a constant number of words and count the
// sum of the values of the words within the window. Then use the window that got the
// maximum sum. If there are multiple maximas, then get the last one.
// Enclose the terms in .
function makeTeaser(body, terms) {
  var TERM_WEIGHT = 40;
  var NORMAL_WORD_WEIGHT = 2;
  var FIRST_WORD_WEIGHT = 8;
  var TEASER_MAX_WORDS = 30;

  var stemmedTerms = terms.map(function (w) {
    return elasticlunr.stemmer(w.toLowerCase());
  });
  var termFound = false;
  var index = 0;
  var weighted = []; // contains elements of ["word", weight, index_in_document]

  // split in sentences, then words
  var sentences = body.toLowerCase().split(". ");

  for (var i in sentences) {
    var words = sentences[i].split(" ");
    var value = FIRST_WORD_WEIGHT;

    for (var j in words) {
      var word = words[j];

      if (word.length > 0) {
        for (var k in stemmedTerms) {
          if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
            value = TERM_WEIGHT;
            termFound = true;
          }
        }
        weighted.push([word, value, index]);
        value = NORMAL_WORD_WEIGHT;
      }

      index += word.length;
      index += 1;  // ' ' or '.' if last word in sentence
    }

    index += 1;  // because we split at a two-char boundary '. '
  }

  if (weighted.length === 0) {
    return body;
  }

  var windowWeights = [];
  var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS);
  // We add a window with all the weights first
  var curSum = 0;
  for (var i = 0; i < windowSize; i++) {
    curSum += weighted[i][1];
  }
  windowWeights.push(curSum);

  for (var i = 0; i < weighted.length - windowSize; i++) {
    curSum -= weighted[i][1];
    curSum += weighted[i + windowSize][1];
    windowWeights.push(curSum);
  }

  // If we didn't find the term, just pick the first window
  var maxSumIndex = 0;
  if (termFound) {
    var maxFound = 0;
    // backwards
    for (var i = windowWeights.length - 1; i >= 0; i--) {
      if (windowWeights[i] > maxFound) {
        maxFound = windowWeights[i];
        maxSumIndex = i;
      }
    }
  }

  var teaser = [];
  var startIndex = weighted[maxSumIndex][2];
  for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
    var word = weighted[i];
    if (startIndex < word[2]) {
      // missing text from index to start of `word`
      teaser.push(body.substring(startIndex, word[2]));
      startIndex = word[2];
    }

    // add  around search terms
    if (word[1] === TERM_WEIGHT) {
      teaser.push("");
    }
    startIndex = word[2] + word[0].length;
    teaser.push(body.substring(word[2], startIndex));

    if (word[1] === TERM_WEIGHT) {
      teaser.push("");
    }
  }
  teaser.push("…");
  return teaser.join("");
}

function formatSearchResultItem(item, terms) {
  return '
'
  + `<a href="${item.ref}">${item.doc.title}</a>`
  + `<div>${makeTeaser(item.doc.body, terms)}</div>`
  + '
';
}

function initSearch() {
  var $searchInput = document.getElementById("search");
  var $searchResults = document.querySelector(".search-results");
  var $searchResultsItems = document.querySelector(".search-results__items");
  var MAX_ITEMS = 10;

  var options = {
    bool: "AND",
    fields: {
      title: {boost: 2},
      body: {boost: 1},
    }
  };
  var currentTerm = "";
  var index = elasticlunr.Index.load(window.searchIndex);

  $searchInput.addEventListener("keyup", debounce(function() {
    var term = $searchInput.value.trim();
    if (term === currentTerm || !index) {
      return;
    }
    $searchResults.style.display = term === "" ? "none" : "block";
    $searchResultsItems.innerHTML = "";
    if (term === "") {
      return;
    }

    var results = index.search(term, options);
    if (results.length === 0) {
      $searchResults.style.display = "none";
      return;
    }

    currentTerm = term;
    for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
      var item = document.createElement("li");
      item.innerHTML = formatSearchResultItem(results[i], term.split(" "));
      $searchResultsItems.appendChild(item);
    }
  }, 150));

  window.addEventListener('click', function(e) {
    if ($searchResults.style.display == "block" && !$searchResults.contains(e.target)) {
      $searchResults.style.display = "none";
    }
  });
}

if (document.readyState === "complete" ||
    (document.readyState !== "loading" && !document.documentElement.doScroll)
) {
  initSearch();
} else {
  document.addEventListener("DOMContentLoaded", initSearch);
}
<|endoftext|>