<commit_before>/**
 * jspsych-preload
 * documentation: docs.jspsych.org
 **/

jsPsych.plugins['preload'] = (function() {

    var plugin = {};

    plugin.info = {
      name: 'preload',
      description: '',
      parameters: {
        auto_preload: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to automatically preload any media files based on the timeline passed to jsPsych.init.'
        },
        trials: {
          type: jsPsych.plugins.parameterType.TIMELINE,
          default: [],
          description: 'Array with a timeline of trials to automatically preload. If one or more trial objects is provided, '+
          'then the plugin will attempt to preload the media files used in the trial(s).'
        },
        images: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more image files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into an image plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the image is embedded in an HTML string.'
        },
        audio: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more audio files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into an audio plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the audio is embedded in an HTML string.'
        },
        video: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more video files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into a video plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the video is embedded in an HTML string.'
        },
        message: {
          type: jsPsych.plugins.parameterType.HTML_STRING,
          default: null,
          description: 'HTML-formatted message to be shown above the progress bar while the files are loading.'
        },
        show_progress_bar: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: true,
          description: 'Whether or not to show the loading progress bar.'
        },
        continue_after_error: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to continue with the experiment if a loading error occurs. If false, then if a loading error occurs, '+
          'the error_message will be shown on the page and the trial will not end. If true, then if if a loading error occurs, the trial will end '+
          'and preloading failure will be logged in the trial data.'
        },
        error_message: {
          type: jsPsych.plugins.parameterType.HTML_STRING,
          default: 'The experiment failed to load.',
          description: 'Error message to show on the page in case of any loading errors. This parameter is only relevant when continue_after_error is false.'
        },
        show_detailed_errors: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to show a detailed error message on the page. If true, then detailed error messages will be shown on the '+
          'page for all files that failed to load, along with the general error_message. This parameter is only relevant when continue_after_error is false.'
        },
        max_load_time: {
          type: jsPsych.plugins.parameterType.INT,
          default: null,
          description: 'The maximum amount of time that the plugin should wait before stopping the preload and either ending the trial '+
          '(if continue_after_error is true) or stopping the experiment with an error message (if continue_after_error is false). '+
          'If null, the plugin will wait indefintely for the files to load.'
        },
        on_error: {
          type: jsPsych.plugins.parameterType.FUNCTION,
          default: null,
          description: 'Function to be called after a file fails to load. The function takes the file name as its only argument.'
        },
        on_success: {
          type: jsPsych.plugins.parameterType.FUNCTION,
          default: null,
          description: 'Function to be called after a file loads successfully. The function takes the file name as its only argument.'
        }
      }
    }

    plugin.trial = function(display_element, trial) {

      var success = null;
      var timeout = false;
      var failed_images = [];
      var failed_audio = [];
      var failed_video = [];
      var detailed_errors = [];
      var in_safe_mode = jsPsych.getSafeModeStatus();

      // create list of media to preload //

      var images = [];
      var audio = [];
      var video = [];

      if(trial.auto_preload){
        var auto_preload = jsPsych.pluginAPI.getAutoPreloadList();
        images = images.concat(auto_preload.images);
        audio = audio.concat(auto_preload.audio);
        video = video.concat(auto_preload.video);
      }

      if(trial.trials.length > 0){
        var trial_preloads = jsPsych.pluginAPI.getAutoPreloadList(trial.trials);
        images = images.concat(trial_preloads.images);
        audio = audio.concat(trial_preloads.audio);
        video = video.concat(trial_preloads.video);
      }

      images = images.concat(trial.images);
      audio = audio.concat(trial.audio);
      video = video.concat(trial.video);

      images = jsPsych.utils.unique(jsPsych.utils.flatten(images));
      audio = jsPsych.utils.unique(jsPsych.utils.flatten(audio));
      video = jsPsych.utils.unique(jsPsych.utils.flatten(video));

      if (in_safe_mode) {
        // don't preload video if in safe mode (experiment is running via file protocol)
        video = [];
      }

      // render display of message and progress bar

      var html = '';

      if(trial.message !== null){
        html += trial.message;
      }

      if(trial.show_progress_bar){
        html += `

`;
      }

      display_element.innerHTML = html;

      // do preloading

      if(trial.max_load_time !== null){
        jsPsych.pluginAPI.setTimeout(on_timeout, trial.max_load_time);
      }

      var total_n = images.length + audio.length + video.length;
      var loaded = 0;  // success or error count
      var loaded_success = 0; // success count

      function load_video(cb){
        jsPsych.pluginAPI.preloadVideo(video, cb, file_loading_success, file_loading_error);
      }

      function load_audio(cb){
        jsPsych.pluginAPI.preloadAudio(audio, cb, file_loading_success, file_loading_error);
      }

      function load_images(cb){
        jsPsych.pluginAPI.preloadImages(images, cb, file_loading_success, file_loading_error);
      }

      load_video(function() {})
      load_audio(function() {})
      load_images(function() {})

      // helper functions and callbacks

      function update_loading_progress_bar(){
        loaded++;
        if(trial.show_progress_bar){
          var percent_loaded = (loaded/total_n)*100;
          var preload_progress_bar = jsPsych.getDisplayElement().querySelector('#jspsych-loading-progress-bar');
          if (preload_progress_bar !== null) {
            preload_progress_bar.style.width = percent_loaded+"%";
          }
        }
      }

      // called when a single file loading fails
      function file_loading_error(e) {
        // update progress bar even if there's an error
        update_loading_progress_bar();
        // change success flag after first file loading error
        if (success == null) {
          success = false;
        }
        // add file to failed media list
        var source = "unknown file";
        if (e.source) {
          source = e.source;
        }
        if (e.error && e.error.path && e.error.path.length > 0) {
          if (e.error.path[0].localName == "img") {
            failed_images.push(source);
          } else if (e.error.path[0].localName == "audio") {
            failed_audio.push(source);
          } else if (e.error.path[0].localName == "video") {
            failed_video.push(source);
          }
        }
        // construct detailed error message
        var err_msg = '
Error loading file: '+source+'
';
        if (e.error.statusText) {
          err_msg += 'File request response status: '+e.error.statusText+'
';
        }
        if (e.error == "404") {
          err_msg += '404 - file not found.
';
        }
        if (typeof e.error.loaded !== 'undefined' && e.error.loaded !== null && e.error.loaded !== 0) {
          err_msg += e.error.loaded+' bytes transferred.';
        } else {
          err_msg += 'File did not begin loading. Check that file path is correct and reachable by the browser,
'+
          'and that loading is not blocked by cross-origin resource sharing (CORS) errors.';
        }
        err_msg += '
';
        detailed_errors.push(err_msg);
        // call trial's on_error function
        after_error(source);
        // if this is the last file
        if (loaded == total_n) {
          if (trial.continue_after_error) {
            // if continue_after_error is false, then stop with an error
            end_trial();
          } else {
            // otherwise end the trial and continue
            stop_with_error_message();
          }
        }
      }

      // called when a single file loads successfully
      function file_loading_success(source) {
        update_loading_progress_bar();
        // call trial's on_success function
        after_success(source);
        loaded_success++;
        if (loaded_success == total_n) {
          // if this is the last file and all loaded successfully, call success function
          on_success();
        } else if (loaded == total_n) {
          // if this is the last file and there was at least one error
          if (trial.continue_after_error) {
            // end the trial and continue with experiment
            end_trial();
          } else {
            // if continue_after_error is false, then stop with an error
            stop_with_error_message();
          }
        }
      }

      // called if all files load successfully
      function on_success() {
        if (typeof timeout !== 'undefined' && timeout === false) {
          // clear timeout immediately after finishing, to handle race condition with max_load_time
          jsPsych.pluginAPI.clearAllTimeouts();
          // need to call cancel preload function to clear global jsPsych preload_request list, even when they've all succeeded
          jsPsych.pluginAPI.cancelPreloads();
          success = true;
          end_trial();
        }
      }

      // called if all_files haven't finished loading when max_load_time is reached
      function on_timeout() {
        console.log('timeout fired');
        jsPsych.pluginAPI.cancelPreloads();
        if (typeof success !== 'undefined' && (success === false || success === null)) {
          timeout = true;
          if (loaded_success < total_n) {
            success = false;
          }
          after_error('timeout'); // call trial's on_error event handler here, in case loading timed out with no file errors
          detailed_errors.push('
Loading timed out.
'+
              'Consider compressing your stimuli files, loading your files in smaller batches,
'+
              'and/or increasing the max_load_time parameter.
');
          if (trial.continue_after_error) {
            end_trial();
          } else {
            stop_with_error_message();
          }
        }
      }

      function stop_with_error_message() {
        jsPsych.pluginAPI.clearAllTimeouts();
        jsPsych.pluginAPI.cancelPreloads();
        // show error message
        display_element.innerHTML = trial.error_message;
        // show detailed errors, if necessary
        if (trial.show_detailed_errors) {
          display_element.innerHTML += '
Error details:
';
          detailed_errors.forEach(function(e) {
            display_element.innerHTML += e;
          });
        }
      }

      function after_error(source) {
        // call on_error function and pass file name
        if (trial.on_error !== null) {
          trial.on_error(source);
        }
      }
      function after_success(source) {
        // call on_success function and pass file name
        if (trial.on_success !== null) {
          trial.on_success(source);
        }
      }

      function end_trial(){
        // clear timeout again when end_trial is called, to handle race condition with max_load_time
        jsPsych.pluginAPI.clearAllTimeouts();
        var trial_data = {
          success: success,
          timeout: timeout,
          failed_images: failed_images,
          failed_audio: failed_audio,
          failed_video: failed_video
        };
        // clear the display
        display_element.innerHTML = '';
        jsPsych.finishTrial(trial_data);
      }
    };

    return plugin;
  })();
  <commit_msg>don't call preload methods if no files to load<commit_after>/**
 * jspsych-preload
 * documentation: docs.jspsych.org
 **/

jsPsych.plugins['preload'] = (function() {

    var plugin = {};

    plugin.info = {
      name: 'preload',
      description: '',
      parameters: {
        auto_preload: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to automatically preload any media files based on the timeline passed to jsPsych.init.'
        },
        trials: {
          type: jsPsych.plugins.parameterType.TIMELINE,
          default: [],
          description: 'Array with a timeline of trials to automatically preload. If one or more trial objects is provided, '+
          'then the plugin will attempt to preload the media files used in the trial(s).'
        },
        images: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more image files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into an image plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the image is embedded in an HTML string.'
        },
        audio: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more audio files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into an audio plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the audio is embedded in an HTML string.'
        },
        video: {
          type: jsPsych.plugins.parameterType.STRING,
          default: [],
          description: 'Array with one or more video files to load. This parameter is often used in cases where media files cannot '+
          'be automatically preloaded based on the timeline, e.g. because the media files are passed into a video plugin/parameter with '+
          'timeline variables or dynamic parameters, or because the video is embedded in an HTML string.'
        },
        message: {
          type: jsPsych.plugins.parameterType.HTML_STRING,
          default: null,
          description: 'HTML-formatted message to be shown above the progress bar while the files are loading.'
        },
        show_progress_bar: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: true,
          description: 'Whether or not to show the loading progress bar.'
        },
        continue_after_error: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to continue with the experiment if a loading error occurs. If false, then if a loading error occurs, '+
          'the error_message will be shown on the page and the trial will not end. If true, then if if a loading error occurs, the trial will end '+
          'and preloading failure will be logged in the trial data.'
        },
        error_message: {
          type: jsPsych.plugins.parameterType.HTML_STRING,
          default: 'The experiment failed to load.',
          description: 'Error message to show on the page in case of any loading errors. This parameter is only relevant when continue_after_error is false.'
        },
        show_detailed_errors: {
          type: jsPsych.plugins.parameterType.BOOL,
          default: false,
          description: 'Whether or not to show a detailed error message on the page. If true, then detailed error messages will be shown on the '+
          'page for all files that failed to load, along with the general error_message. This parameter is only relevant when continue_after_error is false.'
        },
        max_load_time: {
          type: jsPsych.plugins.parameterType.INT,
          default: null,
          description: 'The maximum amount of time that the plugin should wait before stopping the preload and either ending the trial '+
          '(if continue_after_error is true) or stopping the experiment with an error message (if continue_after_error is false). '+
          'If null, the plugin will wait indefintely for the files to load.'
        },
        on_error: {
          type: jsPsych.plugins.parameterType.FUNCTION,
          default: null,
          description: 'Function to be called after a file fails to load. The function takes the file name as its only argument.'
        },
        on_success: {
          type: jsPsych.plugins.parameterType.FUNCTION,
          default: null,
          description: 'Function to be called after a file loads successfully. The function takes the file name as its only argument.'
        }
      }
    }

    plugin.trial = function(display_element, trial) {

      var success = null;
      var timeout = false;
      var failed_images = [];
      var failed_audio = [];
      var failed_video = [];
      var detailed_errors = [];
      var in_safe_mode = jsPsych.getSafeModeStatus();

      // create list of media to preload //

      var images = [];
      var audio = [];
      var video = [];

      if(trial.auto_preload){
        var auto_preload = jsPsych.pluginAPI.getAutoPreloadList();
        images = images.concat(auto_preload.images);
        audio = audio.concat(auto_preload.audio);
        video = video.concat(auto_preload.video);
      }

      if(trial.trials.length > 0){
        var trial_preloads = jsPsych.pluginAPI.getAutoPreloadList(trial.trials);
        images = images.concat(trial_preloads.images);
        audio = audio.concat(trial_preloads.audio);
        video = video.concat(trial_preloads.video);
      }

      images = images.concat(trial.images);
      audio = audio.concat(trial.audio);
      video = video.concat(trial.video);

      images = jsPsych.utils.unique(jsPsych.utils.flatten(images));
      audio = jsPsych.utils.unique(jsPsych.utils.flatten(audio));
      video = jsPsych.utils.unique(jsPsych.utils.flatten(video));

      if (in_safe_mode) {
        // don't preload video if in safe mode (experiment is running via file protocol)
        video = [];
      }

      // render display of message and progress bar

      var html = '';

      if(trial.message !== null){
        html += trial.message;
      }

      if(trial.show_progress_bar){
        html += `

`;
      }

      display_element.innerHTML = html;

      // do preloading

      if(trial.max_load_time !== null){
        jsPsych.pluginAPI.setTimeout(on_timeout, trial.max_load_time);
      }

      var total_n = images.length + audio.length + video.length;
      var loaded = 0;  // success or error count
      var loaded_success = 0; // success count

      function load_video(cb){
        jsPsych.pluginAPI.preloadVideo(video, cb, file_loading_success, file_loading_error);
      }

      function load_audio(cb){
        jsPsych.pluginAPI.preloadAudio(audio, cb, file_loading_success, file_loading_error);
      }

      function load_images(cb){
        jsPsych.pluginAPI.preloadImages(images, cb, file_loading_success, file_loading_error);
      }

      if (video.length > 0) { load_video(function () { }) }
      if (audio.length > 0) { load_audio(function () { }) }
      if (images.length > 0) { load_images(function () { }) }

      // helper functions and callbacks

      function update_loading_progress_bar(){
        loaded++;
        if(trial.show_progress_bar){
          var percent_loaded = (loaded/total_n)*100;
          var preload_progress_bar = jsPsych.getDisplayElement().querySelector('#jspsych-loading-progress-bar');
          if (preload_progress_bar !== null) {
            preload_progress_bar.style.width = percent_loaded+"%";
          }
        }
      }

      // called when a single file loading fails
      function file_loading_error(e) {
        // update progress bar even if there's an error
        update_loading_progress_bar();
        // change success flag after first file loading error
        if (success == null) {
          success = false;
        }
        // add file to failed media list
        var source = "unknown file";
        if (e.source) {
          source = e.source;
        }
        if (e.error && e.error.path && e.error.path.length > 0) {
          if (e.error.path[0].localName == "img") {
            failed_images.push(source);
          } else if (e.error.path[0].localName == "audio") {
            failed_audio.push(source);
          } else if (e.error.path[0].localName == "video") {
            failed_video.push(source);
          }
        }
        // construct detailed error message
        var err_msg = '
Error loading file: '+source+'
';
        if (e.error.statusText) {
          err_msg += 'File request response status: '+e.error.statusText+'
';
        }
        if (e.error == "404") {
          err_msg += '404 - file not found.
';
        }
        if (typeof e.error.loaded !== 'undefined' && e.error.loaded !== null && e.error.loaded !== 0) {
          err_msg += e.error.loaded+' bytes transferred.';
        } else {
          err_msg += 'File did not begin loading. Check that file path is correct and reachable by the browser,
'+
          'and that loading is not blocked by cross-origin resource sharing (CORS) errors.';
        }
        err_msg += '
';
        detailed_errors.push(err_msg);
        // call trial's on_error function
        after_error(source);
        // if this is the last file
        if (loaded == total_n) {
          if (trial.continue_after_error) {
            // if continue_after_error is false, then stop with an error
            end_trial();
          } else {
            // otherwise end the trial and continue
            stop_with_error_message();
          }
        }
      }

      // called when a single file loads successfully
      function file_loading_success(source) {
        update_loading_progress_bar();
        // call trial's on_success function
        after_success(source);
        loaded_success++;
        if (loaded_success == total_n) {
          // if this is the last file and all loaded successfully, call success function
          on_success();
        } else if (loaded == total_n) {
          // if this is the last file and there was at least one error
          if (trial.continue_after_error) {
            // end the trial and continue with experiment
            end_trial();
          } else {
            // if continue_after_error is false, then stop with an error
            stop_with_error_message();
          }
        }
      }

      // called if all files load successfully
      function on_success() {
        if (typeof timeout !== 'undefined' && timeout === false) {
          // clear timeout immediately after finishing, to handle race condition with max_load_time
          jsPsych.pluginAPI.clearAllTimeouts();
          // need to call cancel preload function to clear global jsPsych preload_request list, even when they've all succeeded
          jsPsych.pluginAPI.cancelPreloads();
          success = true;
          end_trial();
        }
      }

      // called if all_files haven't finished loading when max_load_time is reached
      function on_timeout() {
        console.log('timeout fired');
        jsPsych.pluginAPI.cancelPreloads();
        if (typeof success !== 'undefined' && (success === false || success === null)) {
          timeout = true;
          if (loaded_success < total_n) {
            success = false;
          }
          after_error('timeout'); // call trial's on_error event handler here, in case loading timed out with no file errors
          detailed_errors.push('
Loading timed out.
'+
              'Consider compressing your stimuli files, loading your files in smaller batches,
'+
              'and/or increasing the max_load_time parameter.
');
          if (trial.continue_after_error) {
            end_trial();
          } else {
            stop_with_error_message();
          }
        }
      }

      function stop_with_error_message() {
        jsPsych.pluginAPI.clearAllTimeouts();
        jsPsych.pluginAPI.cancelPreloads();
        // show error message
        display_element.innerHTML = trial.error_message;
        // show detailed errors, if necessary
        if (trial.show_detailed_errors) {
          display_element.innerHTML += '
Error details:
';
          detailed_errors.forEach(function(e) {
            display_element.innerHTML += e;
          });
        }
      }

      function after_error(source) {
        // call on_error function and pass file name
        if (trial.on_error !== null) {
          trial.on_error(source);
        }
      }
      function after_success(source) {
        // call on_success function and pass file name
        if (trial.on_success !== null) {
          trial.on_success(source);
        }
      }

      function end_trial(){
        // clear timeout again when end_trial is called, to handle race condition with max_load_time
        jsPsych.pluginAPI.clearAllTimeouts();
        var trial_data = {
          success: success,
          timeout: timeout,
          failed_images: failed_images,
          failed_audio: failed_audio,
          failed_video: failed_video
        };
        // clear the display
        display_element.innerHTML = '';
        jsPsych.finishTrial(trial_data);
      }
    };

    return plugin;
  })();
  <|endoftext|>


<commit_before>// Mathieu Jacomy @ Sciences Po Médialab & WebAtlas
// (requires sigma.js to be loaded)
sigma.publicPrototype.parseGexf = function(gexfPath) {
  // Load XML file:
  var gexfhttp, gexf;
  var sigmaInstance = this;
  gexfhttp = window.XMLHttpRequest ?
    new XMLHttpRequest() :
    new ActiveXObject('Microsoft.XMLHTTP');

  gexfhttp.overrideMimeType('text/xml');
  gexfhttp.open('GET', gexfPath, false);
  gexfhttp.send();
  gexf = gexfhttp.responseXML;

  var viz='http://www.gexf.net/1.2draft/viz'; // Vis namespace
  var i, j, k;

  // Parse Attributes
  // This is confusing, so I'll comment heavily
  var nodesAttributes = [];   // The list of attributes of the nodes of the graph that we build in json
  var edgesAttributes = [];   // The list of attributes of the edges of the graph that we build in json
  var attributesNodes = gexf.getElementsByTagName('attributes');  // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')

  for(i = 0; i<attributesNodes.length; i++){
    var attributesNode = attributesNodes[i];  // attributesNode is each xml node 'attributes' (plural)
    if(attributesNode.getAttribute('class') == 'node'){
      var attributeNodes = attributesNode.getElementsByTagName('attribute');  // The list of xml nodes 'attribute' (no 's')
      for(j = 0; j<attributeNodes.length; j++){
        var attributeNode = attributeNodes[j];  // Each xml node 'attribute'

        var id = attributeNode.getAttribute('id'),
          title = attributeNode.getAttribute('title'),
          type = attributeNode.getAttribute('type');

        var attribute = {id:id, title:title, type:type};
        nodesAttributes.push(attribute);

      }
    } else if(attributesNode.getAttribute('class') == 'edge'){
      var attributeNodes = attributesNode.getElementsByTagName('attribute');  // The list of xml nodes 'attribute' (no 's')
      for(j = 0; j<attributeNodes.length; j++){
        var attributeNode = attributeNodes[j];  // Each xml node 'attribute'

        var id = attributeNode.getAttribute('id'),
          title = attributeNode.getAttribute('title'),
          type = attributeNode.getAttribute('type');

        var attribute = {id:id, title:title, type:type};
        edgesAttributes.push(attribute);

      }
    }
  }

  var nodes = []; // The nodes of the graph
  var nodesNodes = gexf.getElementsByTagName('nodes') // The list of xml nodes 'nodes' (plural)
  var getElementsByTagNameNS = function(node, ns, tagName) {
	  if (node.getElementsByTagNameNS) {
		  return node.getElementsByTagNameNS(ns, tagName);
	  }

	  return node.getElementsByTagName(ns + ':' + tagName);
  };

  for(i=0; i<nodesNodes.length; i++){
    var nodesNode = nodesNodes[i];  // Each xml node 'nodes' (plural)
    var nodeNodes = nodesNode.getElementsByTagName('node'); // The list of xml nodes 'node' (no 's')

    for(j=0; j<nodeNodes.length; j++){
      var nodeNode = nodeNodes[j];  // Each xml node 'node' (no 's')

      window.NODE = nodeNode;

      var id = nodeNode.getAttribute('id');
      var label = nodeNode.getAttribute('label') || id;

      //viz
      var size = 1;
      var x = 100 - 200*Math.random();
      var y = 100 - 200*Math.random();
      var color;

      var sizeNodes = nodeNode.getElementsByTagName('size');
      sizeNodes = sizeNodes.length ?
                  sizeNodes :
                  getElementsByTagNameNS(nodeNode, 'viz','size');
      if(sizeNodes.length>0){
        sizeNode = sizeNodes[0];
        size = parseFloat(sizeNode.getAttribute('value'));
      }

      var positionNodes = nodeNode.getElementsByTagName('position');
      positionNodes = positionNodes.length ?
                      positionNodes :
                      getElementsByTagNameNS(nodeNode, 'viz','position');
      if(positionNodes.length>0){
        var positionNode = positionNodes[0];
        x = parseFloat(positionNode.getAttribute('x'));
        y = parseFloat(positionNode.getAttribute('y'));
      }

      var colorNodes = nodeNode.getElementsByTagName('color');
      colorNodes = colorNodes.length ?
                   colorNodes :
                   getElementsByTagNameNS(nodeNode, 'viz','color');
      if(colorNodes.length>0){
        colorNode = colorNodes[0];
        color = '#'+sigma.tools.rgbToHex(parseFloat(colorNode.getAttribute('r')),
                                         parseFloat(colorNode.getAttribute('g')),
                                         parseFloat(colorNode.getAttribute('b')));
      }

      // Create Node
      var node = {label:label, size:size, x:x, y:y, attributes:[], color:color};  // The graph node

      // Attribute values
      var attvalueNodes = nodeNode.getElementsByTagName('attvalue');
      for(k=0; k<attvalueNodes.length; k++){
        var attvalueNode = attvalueNodes[k];
        var attr = attvalueNode.getAttribute('for');
        var val = attvalueNode.getAttribute('value');
        node.attributes.push({attr:attr, val:val});
      }

      sigmaInstance.addNode(id,node);
    }
  }

  var edges = [];
  var edgesNodes = gexf.getElementsByTagName('edges');
  for(i=0; i<edgesNodes.length; i++){
    var edgesNode = edgesNodes[i];
    var edgeNodes = edgesNode.getElementsByTagName('edge');
    for(j=0; j<edgeNodes.length; j++){
      var edgeNode = edgeNodes[j];
      var id = edgeNode.getAttribute('id');
      var source = edgeNode.getAttribute('source');
      var target = edgeNode.getAttribute('target');
      var label = edgeNode.getAttribute('label');
      var edge = {
        id:         id,
        sourceID:   source,
        targetID:   target,
        label:      label,
        attributes: []
      };

      var weight = edgeNode.getAttribute('weight');
      if(weight!=undefined){
        edge['weight'] = weight;
        edge['size'] = weight;
      }

      var attvalueNodes = edgeNode.getElementsByTagName('attvalue');
      for(k=0; k<attvalueNodes.length; k++){
        var attvalueNode = attvalueNodes[k];
        var attr = attvalueNode.getAttribute('for');
        var val = attvalueNode.getAttribute('value');
        edge.attributes.push({attr:attr, val:val});
      }

      sigmaInstance.addEdge(id,source,target,edge);
    }
  }
};<commit_msg>FireFox needs a URI, but all browsers support the viz:* syntax as it turns out, so use that<commit_after>// Mathieu Jacomy @ Sciences Po Médialab & WebAtlas
// (requires sigma.js to be loaded)
sigma.publicPrototype.parseGexf = function(gexfPath) {
  // Load XML file:
  var gexfhttp, gexf;
  var sigmaInstance = this;
  gexfhttp = window.XMLHttpRequest ?
    new XMLHttpRequest() :
    new ActiveXObject('Microsoft.XMLHTTP');

  gexfhttp.overrideMimeType('text/xml');
  gexfhttp.open('GET', gexfPath, false);
  gexfhttp.send();
  gexf = gexfhttp.responseXML;

  var i, j, k;

  // Parse Attributes
  // This is confusing, so I'll comment heavily
  var nodesAttributes = [];   // The list of attributes of the nodes of the graph that we build in json
  var edgesAttributes = [];   // The list of attributes of the edges of the graph that we build in json
  var attributesNodes = gexf.getElementsByTagName('attributes');  // In the gexf (that is an xml), the list of xml nodes 'attributes' (note the plural 's')

  for(i = 0; i<attributesNodes.length; i++){
    var attributesNode = attributesNodes[i];  // attributesNode is each xml node 'attributes' (plural)
    if(attributesNode.getAttribute('class') == 'node'){
      var attributeNodes = attributesNode.getElementsByTagName('attribute');  // The list of xml nodes 'attribute' (no 's')
      for(j = 0; j<attributeNodes.length; j++){
        var attributeNode = attributeNodes[j];  // Each xml node 'attribute'

        var id = attributeNode.getAttribute('id'),
          title = attributeNode.getAttribute('title'),
          type = attributeNode.getAttribute('type');

        var attribute = {id:id, title:title, type:type};
        nodesAttributes.push(attribute);

      }
    } else if(attributesNode.getAttribute('class') == 'edge'){
      var attributeNodes = attributesNode.getElementsByTagName('attribute');  // The list of xml nodes 'attribute' (no 's')
      for(j = 0; j<attributeNodes.length; j++){
        var attributeNode = attributeNodes[j];  // Each xml node 'attribute'

        var id = attributeNode.getAttribute('id'),
          title = attributeNode.getAttribute('title'),
          type = attributeNode.getAttribute('type');

        var attribute = {id:id, title:title, type:type};
        edgesAttributes.push(attribute);

      }
    }
  }

  var nodes = []; // The nodes of the graph
  var nodesNodes = gexf.getElementsByTagName('nodes') // The list of xml nodes 'nodes' (plural)

  for(i=0; i<nodesNodes.length; i++){
    var nodesNode = nodesNodes[i];  // Each xml node 'nodes' (plural)
    var nodeNodes = nodesNode.getElementsByTagName('node'); // The list of xml nodes 'node' (no 's')

    for(j=0; j<nodeNodes.length; j++){
      var nodeNode = nodeNodes[j];  // Each xml node 'node' (no 's')

      window.NODE = nodeNode;

      var id = nodeNode.getAttribute('id');
      var label = nodeNode.getAttribute('label') || id;

      //viz
      var size = 1;
      var x = 100 - 200*Math.random();
      var y = 100 - 200*Math.random();
      var color;

      var sizeNodes = nodeNode.getElementsByTagName('size');
      sizeNodes = sizeNodes.length ?
                  sizeNodes :
                  nodeNode.getElementsByTagName('viz:size');
      if(sizeNodes.length>0){
        sizeNode = sizeNodes[0];
        size = parseFloat(sizeNode.getAttribute('value'));
      }

      var positionNodes = nodeNode.getElementsByTagName('position');
      positionNodes = positionNodes.length ?
                      positionNodes :
                      nodeNode.getElementsByTagName('viz:position');
      if(positionNodes.length>0){
        var positionNode = positionNodes[0];
        x = parseFloat(positionNode.getAttribute('x'));
        y = parseFloat(positionNode.getAttribute('y'));
      }

      var colorNodes = nodeNode.getElementsByTagName('color');
      colorNodes = colorNodes.length ?
                   colorNodes :
                   nodeNode.getElementsByTagName('viz:color');
      if(colorNodes.length>0){
        colorNode = colorNodes[0];
        color = '#'+sigma.tools.rgbToHex(parseFloat(colorNode.getAttribute('r')),
                                         parseFloat(colorNode.getAttribute('g')),
                                         parseFloat(colorNode.getAttribute('b')));
      }

      // Create Node
      var node = {label:label, size:size, x:x, y:y, attributes:[], color:color};  // The graph node

      // Attribute values
      var attvalueNodes = nodeNode.getElementsByTagName('attvalue');
      for(k=0; k<attvalueNodes.length; k++){
        var attvalueNode = attvalueNodes[k];
        var attr = attvalueNode.getAttribute('for');
        var val = attvalueNode.getAttribute('value');
        node.attributes.push({attr:attr, val:val});
      }

      sigmaInstance.addNode(id,node);
    }
  }

  var edges = [];
  var edgesNodes = gexf.getElementsByTagName('edges');
  for(i=0; i<edgesNodes.length; i++){
    var edgesNode = edgesNodes[i];
    var edgeNodes = edgesNode.getElementsByTagName('edge');
    for(j=0; j<edgeNodes.length; j++){
      var edgeNode = edgeNodes[j];
      var id = edgeNode.getAttribute('id');
      var source = edgeNode.getAttribute('source');
      var target = edgeNode.getAttribute('target');
      var label = edgeNode.getAttribute('label');
      var edge = {
        id:         id,
        sourceID:   source,
        targetID:   target,
        label:      label,
        attributes: []
      };

      var weight = edgeNode.getAttribute('weight');
      if(weight!=undefined){
        edge['weight'] = weight;
        edge['size'] = weight;
      }

      var attvalueNodes = edgeNode.getElementsByTagName('attvalue');
      for(k=0; k<attvalueNodes.length; k++){
        var attvalueNode = attvalueNodes[k];
        var attr = attvalueNode.getAttribute('for');
        var val = attvalueNode.getAttribute('value');
        edge.attributes.push({attr:attr, val:val});
      }

      sigmaInstance.addEdge(id,source,target,edge);
    }
  }
};<|endoftext|>


<commit_before>(function(window, document) {

  /** Cache used by various methods */
  var cache = {
    'counter': 0,
    'lastAction': 'load',
    'timers': { 'cleanup': null, 'load': null, 'post': null },
    'trash': createElement('div')
  },

  interpolate = Benchmark.interpolate;

  /*--------------------------------------------------------------------------*/

  /**
   * Registers an event listener.
   * @private
   * @param {Object} element The element.
   * @param {String} eventName The name of the event to listen to.
   * @param {Function} handler The event handler.
   */
  function addListener(element, eventName, handler) {
    if (typeof element.addEventListener != 'undefined') {
      element.addEventListener(eventName, handler, false);
    } else if (element.attachEvent != 'undefined') {
      element.attachEvent('on' + eventName, handler);
    }
  }

  /**
   * Shortcut for document.createElement().
   * @private
   * @param {String} tag The tag name of the element to create.
   * @returns {Object} A new of the given tag name element.
   */
  function createElement(tagName) {
    return document.createElement(tagName);
  }

  /**
   * Creates a Browserscope results object.
   * @private
   * @returns {Object|Null} Browserscope results object or null.
   */
  function createSnapshot() {
    // remove unrun, errored, or Infinity hz
    var benches = Benchmark.filter(ui.benchmarks, function(bench) {
      return bench.cycles && isFinite(bench.hz);
    });

    // clone benchmarks using the upper limit of the confidence interval to compute hz
    benches = Benchmark.map(benches, function(bench) {
      var clone = bench.clone(),
          stats = bench.stats;

      clone.hz = Math.round(1 / (stats.mean + stats.ME));
      clone.id || (clone.id = Benchmark.indexOf(ui.benchmarks, bench) + 1);
      return clone;
    });

    return Benchmark.reduce(benches, function(result, bench, key) {
      key = (bench.name.match(/[a-z0-9]+/ig) || []).join(' ');
      result || (result = { });

      // duplicate and non alphanumeric benchmark names have their ids appended
      result[key && !result[key] ? key : key + bench.id ] = bench.hz;
      return result;
    }, null);
  }

  /**
   * Injects a script into the document.
   * @private
   * @param {String} src The external script source.
   * @param {Object} sibling The element to inject the script after.
   * @returns {Object} The new script element.
   */
  function loadScript(src, sibling) {
    var script = createElement('script'),
        nextSibling = sibling ? sibling.nextSibling : query('script').pop();

    script.src = src;
    return (sibling || nextSibling).parentNode.insertBefore(script,  nextSibling);
  }

  /**
   * Returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
   * @private
   * @returns {Number} Number of milliseconds.
   */
  function now() {
    return +new Date;
  }

  /**
   * Queries the document for elements by id or tagName.
   * @private
   * @param {String} selector The css selector to match.
   * @returns {Array} The array of results.
   */
  function query(selector) {
    var i = -1,
        result = [],
        nodes = /^#/.test(selector)
          ? [document.getElementById(selector.slice(1))]
          : document.getElementsByTagName(selector);

    while (result[++i] = nodes[i]) { }
    return result.length-- && result;
  }

  /**
   * Set an element's innerHTML property.
   * @private
   * @param {Object} element The element.
   * @param {String} html The HTML to set.
   * @param {Object} object The template object used to modify the html.
   */
  function setHTML(element, html, object) {
    element.innerHTML = interpolate(html, object);
  }

  /**
   * Displays a message in the "results" element.
   * @private
   * @param {String} text The text to display.
   */
  function setMessage(text) {
    var me = ui.browserscope,
        cont = me.container;
    if (cont) {
      cont.className = 'bs-rt-message';
      cont.innerHTML = text;
    }
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Periodically executed callback that removes injected script and iframe elements.
   * @private
   */
  function onCleanup() {
    var expire,
        name,
        me = ui.browserscope,
        delay = me.CLEANUP_INTERVAL * 1e3,
        timers = cache.timers,
        trash = cache.trash;

    // remove injected scripts and old iframes
    if (timers.cleanup) {
      Benchmark.each(query('script').concat(query('iframe')), function(element) {
        // check if element is expired
        name = element.name;
        expire = +(/^browserscope-\d+-(\d+)$/.exec(name) || 0)[1] +
                 Math.max(delay, me.REQUEST_TIMEOUT * 1e3);

        // destroy the element to prevent pseudo memory leaks.
        // http://dl.dropbox.com/u/513327/removechild_ie_leak.html
        if (now() > expire || /browserscope\.org/.test(element.src)) {
          trash.appendChild(element);
          trash.innerHTML = '';
        }
      });
    }
    // schedule another round
    timers.cleanup = setTimeout(onCleanup, delay);
  }

  /**
   * The window load event handler used to initialize the results table.
   * @private
   */
  function onLoad() {
    var cont,
        me = ui.browserscope,
        key = me.KEY,
        placeholder = query(me.PLACEHOLDER_SELECTOR)[0];

    if (placeholder) {
      // set html of placeholder using a template
      setHTML(placeholder,
        '
' +
        'Browserscope<\/span><\/a><\/h1>' +
        '

<\/div><\/div>',
        {
          'key': key
        }
      );

      // resolve container
      cont = me.container = query('#bs-rt-usertest_' + key)[0];

      // load ua script
      loadScript('//www.browserscope.org/ua?o=js', cont).id = 'bs-ua-script';

      // load google visualization script
      // http://code.google.com/apis/loader/autoloader-wizard.html
      loadScript('//www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22visualization%22%2C%22version%22%3A%221%22%2C%22packages%22%3A%5B%22table%22%5D%2C%22callback%22%3Aui.browserscope.load%7D%5D%7D');
    }

    // init garbage collector
    onCleanup();
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Loads Browserscope's cumulative results table.
   * @static
   * @member ui.browserscope
   */
  function load() {
    var me = ui.browserscope,
        cont = me.container,
        timers = cache.timers;

    function onComplete(response) {
      clearTimeout(timers.load);
      me.render(response);
    }

    cache.lastAction = 'load';
    clearTimeout(timers.load);
    timers.load = setTimeout(onComplete, me.REQUEST_TIMEOUT * 1e3);

    // request data
    if (cont) {
      setMessage(me.LOADING_TEXT);
      (new google.visualization.Query(
        '//www.browserscope.org/gviz_table_data?' +
        'category=usertest_' + me.KEY + '&' +
        'ua=&' +
        'v=3&' +
        'o=gviz_data&' +
        'highlight=&' +
        'score=&' +
        'tqx=reqId:0&' +
        'rid=' + now(),
        {'sendMethod': 'scriptInjection'}))
        .send(onComplete);
    }
  }

  /**
   * Creates a Browserscope beacon and posts the benchmark results.
   * @static
   * @member ui.browserscope
   */
  function post() {
    var idoc,
        iframe,
        body = document.body,
        me = ui.browserscope,
        key = me.KEY,
        name = 'browserscope-' + (cache.counter++) + '-' + now(),
        snapshot = createSnapshot();

    cache.lastAction = 'post';
    clearTimeout(cache.timers.post);

    if (key && snapshot && !/Simulator/i.test(Benchmark.platform)) {
      // create new beacon
      try {
        iframe = createElement('');
      } catch(e) {
        (iframe = createElement('iframe')).name = name;
      }
      // inject beacon
      body.insertBefore(iframe, body.firstChild);
      idoc = frames[name].document;
      iframe.style.display = 'none';

      // expose results snapshot
      me.snapshot = snapshot;
      setMessage(me.POST_TEXT);

      // perform inception :3
      idoc.write(interpolate(
        '


<commit_before>BOOMR.t_end = new Date().getTime();

/*jslint continue: true, plusplus: true, regexp: true, unparam: true, sloppy: true, white: true, browser: true, devel: true */
/*properties BOOMR, BOOMR_lstart, BOOMR_start, BOOMR_configt*/

<commit_msg>extra blank line at end of file<commit_after>BOOMR.t_end = new Date().getTime();

/*jslint continue: true, plusplus: true, regexp: true, unparam: true, sloppy: true, white: true, browser: true, devel: true */
/*properties BOOMR, BOOMR_lstart, BOOMR_start, BOOMR_configt*/
<|endoftext|>


<commit_before>/**
 * @file
 * this file contains the code that renders and deals with the demo archives
 * associated with ipol_demo.html and ipol_demo.js
 * @author  Karl Krissian
 * @version 0.1
 */

"use strict";

// ipol application namespace
var ipol = ipol || {};

//------------------------------------------------------------------------------
/**
 * Display demo archives
 * @constructor
 */
ipol.ArchiveDisplay = function()
{

    /**
     * Enable/Disable display of (tracing/debugging)
     * information in browser console.
     * @var {boolean} _verbose
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _verbose=false;

    /**
     * number of current displayed page
     * @var {number} _current_page
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _current_page=0;

    //--------------------------------------------------------------------------
    /**
     * Displays message in console if verbose is true
     * @function _infoMessage
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _infoMessage = function( ) {
        if (_verbose) {
            var args = [].slice.call( arguments ); //Convert to array
            args.unshift("---- ArchiveDisplay ----");
            console.info.apply(console,args);
        }
    }

    //--------------------------------------------------------------------------
    /**
     * Adds the links to the different archive pages
     * @function _archivePages
     * @memberOf ipol.ArchiveDisplay~
     * @param   {object} res
     * @returns {string} HTML code to display the page links
     * @private
     */
    var _archivePages = function(res) {
        var html = "pages ";
        for(var p=1;p<=res.meta.number_of_pages;p++)
        {
            html += ""+p+" ";
        }
        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Displays the contents of one experiment
     * @function _oneArchive
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id    demo id
     * @param   {object} exp        experiment information
     * @returns {string} HTML code to display one archive experiment
     * @private
     */
    var _oneArchive = function(demo_id,exp) {
        var html = "";
        html += '
';
        //style="display:inline-block;vertical-align: top;">';

        // html code for files without visual representation (VR)
        var html_files  = '';
        // html code for files with visual representation
        var html_images = '';

        var HasVisualRepresentation = function(file) {
            // for the moment, just check if the file ends with png
            // later use url_thumb property to decide
            _infoMessage("file.url = ", file.url, " png?",file.url.endsWith('.png'));
            return file.url.endsWith('.png');
        }.bind(this);

        $.each(exp.files,
            function(index,file) {
                if (HasVisualRepresentation(file)) {
                // if VR
                    html_images += '';
                    html_images += '';
                } else {
                // if no VR
                    html_files += '' + file.name+'  ';
                    if (file.name=="results from experiment") {
                        $.getJSON(file.url,
                            function(data){
                                console.info("got results :", data);
                            }
                        );
                    }
                }
            }
        );

        _infoMessage("exp=",exp);

        // info table
        html += '
';
            html += '
';
            html += 'Experiment	';
            // todo link to experiment details ...
            html += 'Experiment '+exp.id+'';
            html += '	';
            html += '
';
            html += '
';
            html += 'date 	';
            html += ' '+exp.date+'	';
            html += '
';
            $.each(exp.parameters,
                function(param,value) {
                    html += '
';
                    html += '      '+
                            param+'	';
                    html += '      '+value+'	';
                    html += '
';
                }
            );

            html += '
';
            html += '  files	';
            html += '  ';
            html += html_files;
            html += '  	';
            html += '
';
        html += '
';
        // thumbnails table
        html += '
';
            html += '
';
            html += '  Images	';
            html += '
';
            html += '
';
            html += '  ';
            html += html_images;
            html += '  	';
            html += '
';
        html += '
';
        html += '
';
        html += '
';
        html += '
';

        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Create the HTML code for the current page
     * @function _createCurrentPage
     * @memberOf ipol.ArchiveDisplay~
     * @param   {object} res          result object obtained from archive module
     * @param   {number} demo_id      demo id
     * @param   {number} page_number  page number to display
     * @returns {string} HTML code to display the current archive page
     * @private
     */
    var _createCurrentPage = function(res,demo_id,page_number) {

        var meta_info       = res["meta"];
        var nb_experiments  = meta_info["number_of_experiments"];

        //             if number_of_experiments == '0':
        //                 #Empty list. No experiments in the archive
        //                 archive_experiments = []
        //                 return self.tmpl_out("archive_index.html", archive_list=archive_experiments, page=0,
        //                                      number_of_experiments=0, nbpage=0,first_date='never')
        /*
                    else:*/

        var first_date              = meta_info["first_date_of_an_experiment"];
        var nb_pages                = meta_info["number_of_pages"];

        if (page_number===undefined) {
            page_number = nb_pages;
        }
        // the last page is displayed if the page_number is out of range
        if ((page_number<1)||(page_number>nb_pages))  {
            page_number=nb_pages;
        }
        _current_page=page_number;

        var nb_experiments_per_page = meta_info["number_of_experiments_in_a_page"];

        var html = "";

        // need to have id=content for CSS compatibility ...
        html += '
';
        html += '
'+
                ' Please cite the reference article'+
                ' if you publish results obtained with this online demo.'+
                '
';

        html += '
';
        html += '
';
        html += nb_experiments+' public experiments since '+first_date+'.
';
        html += 'This archive is not moderated.';
        html += 'In case you uploaded images that you don\'t want that appear in'+
                'the archive, you can remove them by clicking on the corresponding key '+
                'and then clicking over the "delete this entry" button. '+
                'This button appears only for the experiments performed by the user '+
                'during the last 24 hours.
';
        html += 'In case of copyright infringement or similar problem, please '+
                ''+
                'contact us to request the removal of some images.'+
                'Some archived content may be deleted by the editorial board for size '+
                'matters, inadequate content, user requests, or other reasons.';
        html += '
';
//         html += '<button id="ReloadArchive">Reload</button>
';

        var html_pages = _archivePages(res);
        html += html_pages;

        html += '
';
        $.each(res.experiments,
               function(index,exp) {
                    html += _oneArchive(demo_id,exp);
               }.bind(this));

        html += html_pages;
        html += '
';
        html += '
';
        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Create the page events
     * @function _createPageEvents
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id      demo id
     * @param   {object} res          result object obtained from archive module
     * @private
     */
    var _createPageEvents = function(demo_id,res) {
        var meta_info = res["meta"];
        var nb_pages  = meta_info["number_of_pages"];

        $(".set_page_"+_current_page).css("font-weight","bold");
        for(var i=1;i<=nb_pages;i++) {
            $(".set_page_"+i).unbind().click(
                function(obj,demoid,page) {
                    return function()
                    {
                        obj.getArchive(demoid,page);
                    }
                } (this,demo_id,i)
            );
            // underline on hover
            $(".set_page_"+i).hover(
                function(){ $(this).css("text-decoration", "underline"); },
                function(){ $(this).css("text-decoration", "none");    }
            );
        }

        // commented reload button
        // // $( "#ReloadArchive" ).unbind("click");
        // $("#ReloadArchive").button().on("click",
        //             function(obj,demoid) {
        //                 return function()
        //                 {
        //                     obj.getArchive(demoid,this.current_page);
        //                 }
        //             } (this,demo_id)
        // );
    }

    //--------------------------------------------------------------------------
    /**
     * Gets and displays archive contents for the given demo and page number
     * if the page number is undefined or out of range,
     * the last page is displayed.
     * @function getArchive
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id      demo id
     * @param   {number} page_number  page number
     * @public
     */
    this.getArchive = function(demo_id,page_number) {

        var url_params =    'demo_id='    + demo_id + '&page='+page_number;
        ipol.utils.ModuleService("archive","get_page",url_params,
            function(res) {
                _infoMessage("archive result : ",res);
                if (res['status']==='OK') {
                    var html = _createCurrentPage(res,demo_id,page_number);
                    $("#tabs-archive").html(html);
                    _createPageEvents(demo_id,res);
                }
            }.bind(this));
    }
}

//------------------------------------------------------------------------------
/**
 * search and returns the url in archive of a given result filename
 * if not found returns undefined
 * @function staticFindArchiveUrl
 * @memberOf ipol.ArchiveDisplay
 * @static
 * @param {string} filename        filename to seach for in archive experiment
 * @param {object} ddl_archive_files list of archive files and their descriptions
 * @param {object[]} experiment_files array containing the experiment files
 * @returns {string} url of the found file or undefined
 */
ipol.ArchiveDisplay.staticFindArchiveUrl = function(filename,ddl_archive_files,
                                                experiment_files) {
    var archive_input_description = ddl_archive_files[filename];
    if (archive_input_description) {
        // find file url in archive
        for(var i=0; i<experiment_files.length;i++) {
            if (experiment_files[i].name === archive_input_description) {
                return experiment_files[i].url;
            }
        }
    }
    return undefined;
}
<commit_msg>[static/JQueryApp] fixed problem with archive.js page selection<commit_after>/**
 * @file
 * this file contains the code that renders and deals with the demo archives
 * associated with ipol_demo.html and ipol_demo.js
 * @author  Karl Krissian
 * @version 0.1
 */

"use strict";

// ipol application namespace
var ipol = ipol || {};

//------------------------------------------------------------------------------
/**
 * Display demo archives
 * @constructor
 */
ipol.ArchiveDisplay = function()
{

    /**
     * By convention, we create a private variable '_this' to
     * make the object available to the private methods.
     * @var {object} _this
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _this = this;

    /**
     * Enable/Disable display of (tracing/debugging)
     * information in browser console.
     * @var {boolean} _verbose
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _verbose=false;

    /**
     * number of current displayed page
     * @var {number} _current_page
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _current_page=0;

    //--------------------------------------------------------------------------
    /**
     * Displays message in console if verbose is true
     * @function _infoMessage
     * @memberOf ipol.ArchiveDisplay~
     * @private
     */
    var _infoMessage = function( ) {
        if (_verbose) {
            var args = [].slice.call( arguments ); //Convert to array
            args.unshift("---- ArchiveDisplay ----");
            console.info.apply(console,args);
        }
    }

    //--------------------------------------------------------------------------
    /**
     * Adds the links to the different archive pages
     * @function _archivePages
     * @memberOf ipol.ArchiveDisplay~
     * @param   {object} res
     * @returns {string} HTML code to display the page links
     * @private
     */
    var _archivePages = function(res) {
        var html = "pages ";
        for(var p=1;p<=res.meta.number_of_pages;p++)
        {
            html += ""+p+" ";
        }
        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Displays the contents of one experiment
     * @function _oneArchive
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id    demo id
     * @param   {object} exp        experiment information
     * @returns {string} HTML code to display one archive experiment
     * @private
     */
    var _oneArchive = function(demo_id,exp) {
        var html = "";
        html += '
';
        //style="display:inline-block;vertical-align: top;">';

        // html code for files without visual representation (VR)
        var html_files  = '';
        // html code for files with visual representation
        var html_images = '';

        var HasVisualRepresentation = function(file) {
            // for the moment, just check if the file ends with png
            // later use url_thumb property to decide
            _infoMessage("file.url = ", file.url, " png?",file.url.endsWith('.png'));
            return file.url.endsWith('.png');
        }.bind(this);

        $.each(exp.files,
            function(index,file) {
                if (HasVisualRepresentation(file)) {
                // if VR
                    html_images += '';
                    html_images += '';
                } else {
                // if no VR
                    html_files += '' + file.name+'  ';
                    if (file.name=="results from experiment") {
                        $.getJSON(file.url,
                            function(data){
                                console.info("got results :", data);
                            }
                        );
                    }
                }
            }
        );

        _infoMessage("exp=",exp);

        // info table
        html += '
';
            html += '
';
            html += 'Experiment	';
            // todo link to experiment details ...
            html += 'Experiment '+exp.id+'';
            html += '	';
            html += '
';
            html += '
';
            html += 'date 	';
            html += ' '+exp.date+'	';
            html += '
';
            $.each(exp.parameters,
                function(param,value) {
                    html += '
';
                    html += '      '+
                            param+'	';
                    html += '      '+value+'	';
                    html += '
';
                }
            );

            html += '
';
            html += '  files	';
            html += '  ';
            html += html_files;
            html += '  	';
            html += '
';
        html += '
';
        // thumbnails table
        html += '
';
            html += '
';
            html += '  Images	';
            html += '
';
            html += '
';
            html += '  ';
            html += html_images;
            html += '  	';
            html += '
';
        html += '
';
        html += '
';
        html += '
';
        html += '
';

        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Create the HTML code for the current page
     * @function _createCurrentPage
     * @memberOf ipol.ArchiveDisplay~
     * @param   {object} res          result object obtained from archive module
     * @param   {number} demo_id      demo id
     * @param   {number} page_number  page number to display
     * @returns {string} HTML code to display the current archive page
     * @private
     */
    var _createCurrentPage = function(res,demo_id,page_number) {

        var meta_info       = res["meta"];
        var nb_experiments  = meta_info["number_of_experiments"];

        //             if number_of_experiments == '0':
        //                 #Empty list. No experiments in the archive
        //                 archive_experiments = []
        //                 return self.tmpl_out("archive_index.html", archive_list=archive_experiments, page=0,
        //                                      number_of_experiments=0, nbpage=0,first_date='never')
        /*
                    else:*/

        var first_date              = meta_info["first_date_of_an_experiment"];
        var nb_pages                = meta_info["number_of_pages"];

        if (page_number===undefined) {
            page_number = nb_pages;
        }
        // the last page is displayed if the page_number is out of range
        if ((page_number<1)||(page_number>nb_pages))  {
            page_number=nb_pages;
        }
        _current_page=page_number;

        var nb_experiments_per_page = meta_info["number_of_experiments_in_a_page"];

        var html = "";

        // need to have id=content for CSS compatibility ...
        html += '
';
        html += '
'+
                ' Please cite the reference article'+
                ' if you publish results obtained with this online demo.'+
                '
';

        html += '
';
        html += '
';
        html += nb_experiments+' public experiments since '+first_date+'.
';
        html += 'This archive is not moderated.';
        html += 'In case you uploaded images that you don\'t want that appear in'+
                'the archive, you can remove them by clicking on the corresponding key '+
                'and then clicking over the "delete this entry" button. '+
                'This button appears only for the experiments performed by the user '+
                'during the last 24 hours.
';
        html += 'In case of copyright infringement or similar problem, please '+
                ''+
                'contact us to request the removal of some images.'+
                'Some archived content may be deleted by the editorial board for size '+
                'matters, inadequate content, user requests, or other reasons.';
        html += '
';
//         html += '<button id="ReloadArchive">Reload</button>
';

        var html_pages = _archivePages(res);
        html += html_pages;

        html += '
';
        $.each(res.experiments,
               function(index,exp) {
                    html += _oneArchive(demo_id,exp);
               }.bind(this));

        html += html_pages;
        html += '
';
        html += '
';
        return html;
    }

    //--------------------------------------------------------------------------
    /**
     * Create the page events
     * @function _createPageEvents
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id      demo id
     * @param   {object} res          result object obtained from archive module
     * @private
     */
    var _createPageEvents = function(demo_id,res) {
        var meta_info = res["meta"];
        var nb_pages  = meta_info["number_of_pages"];

        $(".set_page_"+_current_page).css("font-weight","bold");
        for(var i=1;i<=nb_pages;i++) {
            $(".set_page_"+i).unbind().click(
                function(demoid,page) {
                    return function()
                    {
                        _this.getArchive(demoid,page);
                    }
                } (demo_id,i)
            );
            // underline on hover
            $(".set_page_"+i).hover(
                function(){ $(this).css("text-decoration", "underline"); },
                function(){ $(this).css("text-decoration", "none");    }
            );
        }

        // commented reload button
        // // $( "#ReloadArchive" ).unbind("click");
        // $("#ReloadArchive").button().on("click",
        //             function(obj,demoid) {
        //                 return function()
        //                 {
        //                     obj.getArchive(demoid,this.current_page);
        //                 }
        //             } (this,demo_id)
        // );
    }

    //--------------------------------------------------------------------------
    /**
     * Gets and displays archive contents for the given demo and page number
     * if the page number is undefined or out of range,
     * the last page is displayed.
     * @function getArchive
     * @memberOf ipol.ArchiveDisplay~
     * @param   {number} demo_id      demo id
     * @param   {number} page_number  page number
     * @public
     */
    this.getArchive = function(demo_id,page_number) {

        var url_params =    'demo_id='    + demo_id + '&page='+page_number;
        ipol.utils.ModuleService("archive","get_page",url_params,
            function(res) {
                _infoMessage("archive result : ",res);
                if (res['status']==='OK') {
                    var html = _createCurrentPage(res,demo_id,page_number);
                    $("#tabs-archive").html(html);
                    _createPageEvents(demo_id,res);
                }
            }.bind(this));
    }
}

//------------------------------------------------------------------------------
/**
 * search and returns the url in archive of a given result filename
 * if not found returns undefined
 * @function staticFindArchiveUrl
 * @memberOf ipol.ArchiveDisplay
 * @static
 * @param {string} filename        filename to seach for in archive experiment
 * @param {object} ddl_archive_files list of archive files and their descriptions
 * @param {object[]} experiment_files array containing the experiment files
 * @returns {string} url of the found file or undefined
 */
ipol.ArchiveDisplay.staticFindArchiveUrl = function(filename,ddl_archive_files,
                                                experiment_files) {
    var archive_input_description = ddl_archive_files[filename];
    if (archive_input_description) {
        // find file url in archive
        for(var i=0; i<experiment_files.length;i++) {
            if (experiment_files[i].name === archive_input_description) {
                return experiment_files[i].url;
            }
        }
    }
    return undefined;
}
<|endoftext|>


<commit_before>var events = new (Npm.require('events').EventEmitter)(),
	collectionName = process.env.MULTIPLE_INSTANCES_COLLECTION_NAME || 'instances',
	defaultPingInterval = (process.env.MULTIPLE_INSTANCES_PING_INTERVAL || 10) * 1000; // default to 10s

var Intances = new Meteor.Collection(collectionName);

var InstancesRaw = Intances.rawCollection();
var indexExpire = Math.ceil(defaultPingInterval * 3 / 60000) * 60000;

// ensures at least 3 ticks before expiring
InstancesRaw.indexes()
	.then(function(result) {
		return result.some(function(index) {
			if (index.key && index.key['_updatedAt'] === 1) {
				if (index.expireAfterSeconds !== indexExpire) {
					InstancesRaw.dropIndex(index.name);
					return false;
				}
				return true;
			}
		})
	})
	.then(function(created) {
		if (!created) {
			InstancesRaw.createIndex({_updatedAt: 1}, {expireAfterSeconds: indexExpire});
		}
	});

InstanceStatus = {
	name: undefined,
	extraInformation: undefined,

	events: events,

	getCollection: function() {
		return Intances;
	},

	registerInstance: function(name, extraInformation) {
		InstanceStatus.name = name;
		InstanceStatus.extraInformation = extraInformation;

		if (InstanceStatus.id() === undefined || InstanceStatus.id() === null) {
			return console.error('[multiple-instances-status] only can be called after Meteor.startup');
		}

		var now = new Date(),
			instance = {
				$set: {
					pid: process.pid,
					name: name
				},
				$currentDate: {
					_createdAt: true,
					_updatedAt: true
				}
			};

		if (extraInformation) {
			instance.$set.extraInformation = extraInformation;
		}

		try {
			Intances.upsert({_id: InstanceStatus.id()}, instance);
			var result = Intances.findOne({_id: InstanceStatus.id()});
			InstanceStatus.start();

			events.emit('registerInstance', result, instance);

			process.on('exit', InstanceStatus.onExit);

			return result;
		} catch (e) {
			return e;
		}
	},

	unregisterInstance: function() {
		try {
			var result = Intances.remove({_id: InstanceStatus.id()});
			InstanceStatus.stop();

			events.emit('unregisterInstance', InstanceStatus.id());

			process.removeListener('exit', InstanceStatus.onExit);

			return result;
		} catch (e) {
			return e;
		}
	},

	start: function(interval) {
		InstanceStatus.stop();

		interval = interval || defaultPingInterval;

		InstanceStatus.interval = Meteor.setInterval(function() {
			InstanceStatus.ping();
		}, interval);
	},

	stop: function(interval) {
		if (InstanceStatus.interval) {
			InstanceStatus.interval.close();
			delete InstanceStatus.interval;
		}
	},

	ping: function() {
		var count = Intances.update(
			{
				_id: InstanceStatus.id()
			},
			{
				$currentDate: {
					_updatedAt: true
				}
			});

		if (count === 0) {
			InstanceStatus.registerInstance(InstanceStatus.name, InstanceStatus.extraInformation);
		}
	},

	onExit: function() {
		InstanceStatus.unregisterInstance();
	},

	activeLogs: function() {
		Intances.find().observe({
			added: function(record) {
				var log = '[multiple-instances-status] Server connected: ' + record.name + ' - ' + record._id;
				if (record._id == InstanceStatus.id()) {
					log += ' (me)';
				}
				console.log(log.green);
			},
			removed: function(record) {
				var log = '[multiple-instances-status] Server disconnected: ' + record.name + ' - ' + record._id;
				console.log(log.red);
			}
		});
	},

	id: function() {}
};

Meteor.startup(function() {
	var ID = Random.id();

	InstanceStatus.id = function() {
		return ID;
	};
});
<commit_msg>Fix when collection does not exists<commit_after>var events = new (Npm.require('events').EventEmitter)(),
	collectionName = process.env.MULTIPLE_INSTANCES_COLLECTION_NAME || 'instances',
	defaultPingInterval = (process.env.MULTIPLE_INSTANCES_PING_INTERVAL || 10); // default to 10s

var Instances = new Meteor.Collection(collectionName);

var InstancesRaw = Instances.rawCollection();

// if not set via env var ensures at least 3 ticks before expiring (multiple of 60s)
var indexExpire = process.env.MULTIPLE_INSTANCES_EXPIRE || (Math.ceil(defaultPingInterval * 3 / 60) * 60);

InstancesRaw.indexes()
	.catch(function() {
		// the collection should not exists yet, return empty then
		return [];
	})
	.then(function(result) {
		return result.some(function(index) {
			if (index.key && index.key['_updatedAt'] === 1) {
				if (index.expireAfterSeconds !== indexExpire) {
					InstancesRaw.dropIndex(index.name);
					return false;
				}
				return true;
			}
		})
	})
	.then(function(created) {
		if (!created) {
			InstancesRaw.createIndex({_updatedAt: 1}, {expireAfterSeconds: indexExpire});
		}
	});

InstanceStatus = {
	name: undefined,
	extraInformation: undefined,

	events: events,

	getCollection: function() {
		return Instances;
	},

	registerInstance: function(name, extraInformation) {
		InstanceStatus.name = name;
		InstanceStatus.extraInformation = extraInformation;

		if (InstanceStatus.id() === undefined || InstanceStatus.id() === null) {
			return console.error('[multiple-instances-status] only can be called after Meteor.startup');
		}

		var now = new Date(),
			instance = {
				$set: {
					pid: process.pid,
					name: name
				},
				$currentDate: {
					_createdAt: true,
					_updatedAt: true
				}
			};

		if (extraInformation) {
			instance.$set.extraInformation = extraInformation;
		}

		try {
			Instances.upsert({_id: InstanceStatus.id()}, instance);
			var result = Instances.findOne({_id: InstanceStatus.id()});
			InstanceStatus.start();

			events.emit('registerInstance', result, instance);

			process.on('exit', InstanceStatus.onExit);

			return result;
		} catch (e) {
			return e;
		}
	},

	unregisterInstance: function() {
		try {
			var result = Instances.remove({_id: InstanceStatus.id()});
			InstanceStatus.stop();

			events.emit('unregisterInstance', InstanceStatus.id());

			process.removeListener('exit', InstanceStatus.onExit);

			return result;
		} catch (e) {
			return e;
		}
	},

	start: function(interval) {
		InstanceStatus.stop();

		interval = interval || defaultPingInterval;

		InstanceStatus.interval = Meteor.setInterval(function() {
			InstanceStatus.ping();
		}, interval * 1000);
	},

	stop: function(interval) {
		if (InstanceStatus.interval) {
			InstanceStatus.interval.close();
			delete InstanceStatus.interval;
		}
	},

	ping: function() {
		var count = Instances.update(
			{
				_id: InstanceStatus.id()
			},
			{
				$currentDate: {
					_updatedAt: true
				}
			});

		if (count === 0) {
			InstanceStatus.registerInstance(InstanceStatus.name, InstanceStatus.extraInformation);
		}
	},

	onExit: function() {
		InstanceStatus.unregisterInstance();
	},

	activeLogs: function() {
		Instances.find().observe({
			added: function(record) {
				var log = '[multiple-instances-status] Server connected: ' + record.name + ' - ' + record._id;
				if (record._id == InstanceStatus.id()) {
					log += ' (me)';
				}
				console.log(log.green);
			},
			removed: function(record) {
				var log = '[multiple-instances-status] Server disconnected: ' + record.name + ' - ' + record._id;
				console.log(log.red);
			}
		});
	},

	id: function() {}
};

Meteor.startup(function() {
	var ID = Random.id();

	InstanceStatus.id = function() {
		return ID;
	};
});
<|endoftext|>


<commit_before>(function() {
	var imports = new JavaImporter(java.io, java.util, java.lang,
			com.xafero.jaddle.web, com.xafero.sfs.Hoster,
			java.util.concurrent, java.net, java.awt);

	with (imports) {
		var getAddresses = function() {
			var results = new LinkedHashSet();
			for each (var ni in Collections.list(NetworkInterface.getNetworkInterfaces()))
				for each (var ia in Collections.list(ni.getInetAddresses())) {
					if (ia.isLoopbackAddress() || ia.isLinkLocalAddress())
						continue;
					results.add(ia);
				}
			return results;
		};
		// Set up container
		var hostedFiles = new LinkedHashMap();
		// Serve function
		var serve = function(root, key, val) {
			var file = new File(root, val);
			hostedFiles.put(key, file);
		};
		return {
			exec : function(work, args, env) {
				// Loop for all files
				for (var i = 0; i < args.length; i = i + 2) {
					var link = args[i];
					var target = args[i+1];
					serve(work, link, target);
				}
				// Start up server
				var port = 8080;
				var allNet = "0.0.0.0";
				var server = new ServePlugin(hostedFiles);
				var hoster = new Hoster(allNet, port, new File(""), server);
				var pool = Executors.newCachedThreadPool();
				pool.submit(hoster);
				// Open browser
				for each (var addr in getAddresses()) {
					var endpoint = (hoster.getEndpoint() + "").replace(allNet, addr.getHostAddress());
					var uri = URI.create(endpoint);
					print(" Endpoint = " + uri);
					Desktop.getDesktop().browse(uri);
				}
				// Wait for exit
				print("Press any key to quit...");
				System.in.read();
				pool.shutdown();
				// System.exit(0);
				print("Done.");
			}
		}
	}
});
<commit_msg>Fixed IPv6 http address errrors<commit_after>(function() {
	var imports = new JavaImporter(java.io, java.util, java.lang,
			com.xafero.jaddle.web, com.xafero.sfs.Hoster,
			java.util.concurrent, java.net, java.awt);

	with (imports) {
		var getAddresses = function() {
			var results = new LinkedHashSet();
			for each (var ni in Collections.list(NetworkInterface.getNetworkInterfaces()))
				for each (var ia in Collections.list(ni.getInetAddresses())) {
					if (ia.isLoopbackAddress() || ia.isLinkLocalAddress())
						continue;
					results.add(ia);
				}
			return results;
		};
		// Set up container
		var hostedFiles = new LinkedHashMap();
		// Serve function
		var serve = function(root, key, val) {
			var file = new File(root, val);
			hostedFiles.put(key, file);
		};
		return {
			exec : function(work, args, env) {
				// Loop for all files
				for (var i = 0; i < args.length; i = i + 2) {
					var link = args[i];
					var target = args[i+1];
					serve(work, link, target);
				}
				// Start up server
				var port = 8080;
				var allNet = "0.0.0.0";
				var server = new ServePlugin(hostedFiles);
				var hoster = new Hoster(allNet, port, new File(""), server);
				var pool = Executors.newCachedThreadPool();
				pool.submit(hoster);
				// Open browser
				for each (var addr in getAddresses()) {
					var escapedAddr = addr.getHostAddress();
					if (escapedAddr.contains(":"))
						escapedAddr = '['+escapedAddr+']';
					var endpoint = (hoster.getEndpoint() + "").replace(allNet, escapedAddr);
					var uri = URI.create(endpoint);
					print(" Endpoint = " + uri);
					Desktop.getDesktop().browse(uri);
				}
				// Wait for exit
				print("Press any key to quit...");
				System.in.read();
				pool.shutdown();
				// System.exit(0);
				print("Done.");
				return pool;
			}
		}
	}
});<|endoftext|>


<commit_before>Ember.TEMPLATES['application'] = Ember.Handlebars.compile('

Snapshot

Cluster

Ring

Objects

Map/Reduce

Graphs

Logs

Support

            	            {{ outlet }}

');<commit_msg>Add compiled templates.<commit_after>Ember.TEMPLATES['application'] = Ember.Handlebars.compile('

Snapshot

Cluster

Ring

Objects

Map/Reduce

Graphs

Logs

Support

            	            {{ outlet }}

');
Ember.TEMPLATES['snapshot'] = Ember.Handlebars.compile('
Current Snapshot...

Your cluster is healthy.

You currently have...

0 Unreachable nodes

0 Incompatible nodes

0 Nodes marked as down

0 Nodes experiencing low memory

Nothing to worry about because Riak is your friend

Your cluster has problems.

The following nodes are currently unreachable:

The following nodes are currently incompatible with Riak Control:

The following nodes are currently marked down:

The following nodes are currently experiencing low memory:

');
Ember.TEMPLATES['cluster'] = Ember.Handlebars.compile('
Cluster View

Add Nodes to the Cluster...

                        <input id="node-to-add" class="gui-field-input gui-text" type="text" name="nodeName" />

            	                                                Add Node

    Node List

Status

Name

Actions

Partitions

Memory Usage

                    Joining...

View Actions

Hide Actions

                                        Stop Node

                                        Leave Cluster

                                        Mark Down

');
Ember.TEMPLATES['ring'] = Ember.Handlebars.compile('

Filter

        <select id="filter" class="gui-dropdown">            <option value="/admin/ring/partitions">All</option>        </select>

    Ring View

#

Owner Node

KV

Pipe

Search

            No partitions matched your filter.

        	                                    Disabled                                    	                                    Disabled                                    	                                    Disabled

');
<|endoftext|>


<commit_before>export default () => ({
  0: ['gain', 'output'],
});
<commit_msg>code style tweak<commit_after>export default () => ({0: ['gain', 'output']});
<|endoftext|>


<commit_before>var utils = require('./utils.js');

describe('globaLeaks setup wizard', function() {
  it('should allow the user to setup the wizard', function() {
    browser.get('/#/wizard');

    // Test language selector switching to italian and then re-switching to english
    element(by.model('GLTranslate.indirect.appLanguage')).element(by.xpath(".//*[text()='Italiano']")).click();
    expect(browser.isElementPresent(element(by.cssContainingText("div", "Benvenuto su GlobaLeaks!")))).toBe(true);
    element(by.model('GLTranslate.indirect.appLanguage')).element(by.xpath(".//*[text()='English']")).click();
    expect(browser.isElementPresent(element(by.cssContainingText("div", "Welcome to GlobaLeaks!")))).toBe(true);

    element.all(by.id('ButtonNext')).get(0).click();

    element(by.model('wizard.node.name')).sendKeys('E2E Test Instance');
    element(by.model('wizard.node.description')).sendKeys('This instance is for E2E testing');

    element.all(by.id('ButtonNext')).get(1).click();

    element(by.model('wizard.admin.mail_address')).sendKeys('globaleaks-admin@mailinator.com');
    element(by.model('wizard.admin.password')).sendKeys(utils.vars['user_password']);
    element(by.model('admin_check_password')).sendKeys(utils.vars['user_password']);

    element.all(by.id('ButtonNext')).get(2).click();

    element(by.model('wizard.context.name')).sendKeys('Context 1');

    element.all(by.id('ButtonNext')).get(3).click();

    element(by.model('wizard.receiver.name')).sendKeys('Recipient1');
    element(by.model('wizard.receiver.mail_address')).sendKeys('globaleaks-receiver1@mailinator.com');

    element.all(by.id('ButtonNext')).get(4).click();

    expect(element(by.css('.congratulations')).isPresent()).toBe(true);

    element.all(by.id('ButtonNext')).get(5).click();

    utils.waitForUrl('/admin/landing');

    utils.logout('/admin');
  });
});
<commit_msg>Replace expect browser.isElementPresent with utils.waitUntilPresent<commit_after>var utils = require('./utils.js');

describe('globaLeaks setup wizard', function() {
  it('should allow the user to setup the wizard', function() {
    browser.get('/#/wizard');

    // Test language selector switching to italian and then re-switching to english
    element(by.model('GLTranslate.indirect.appLanguage')).element(by.xpath(".//*[text()='Italiano']")).click();
    utils.waitUntilPresent(by.cssContainingText("div", "Benvenuto su GlobaLeaks!"));
    element(by.model('GLTranslate.indirect.appLanguage')).element(by.xpath(".//*[text()='English']")).click();
    utils.waitUntilPresent(by.cssContainingText("div", "Welcome to GlobaLeaks!"));

    element.all(by.id('ButtonNext')).get(0).click();

    element(by.model('wizard.node.name')).sendKeys('E2E Test Instance');
    element(by.model('wizard.node.description')).sendKeys('This instance is for E2E testing');

    element.all(by.id('ButtonNext')).get(1).click();

    element(by.model('wizard.admin.mail_address')).sendKeys('globaleaks-admin@mailinator.com');
    element(by.model('wizard.admin.password')).sendKeys(utils.vars['user_password']);
    element(by.model('admin_check_password')).sendKeys(utils.vars['user_password']);

    element.all(by.id('ButtonNext')).get(2).click();

    element(by.model('wizard.context.name')).sendKeys('Context 1');

    element.all(by.id('ButtonNext')).get(3).click();

    element(by.model('wizard.receiver.name')).sendKeys('Recipient1');
    element(by.model('wizard.receiver.mail_address')).sendKeys('globaleaks-receiver1@mailinator.com');

    element.all(by.id('ButtonNext')).get(4).click();

    expect(element(by.css('.congratulations')).isPresent()).toBe(true);

    element.all(by.id('ButtonNext')).get(5).click();

    utils.waitForUrl('/admin/landing');

    utils.logout('/admin');
  });
});
<|endoftext|>


<commit_before>var calc = function () {
  document.body.appendChild(calc.display)
  document.body.appendChild(calc.keypad)
}

!function () {

var html = {};

['tr', 'td', 'input', 'div', 'table'].forEach(function (a) {
  html[a] = function() { return document.createElement(a) }
})

Complex.precision = 6

var
c = new Complex(Math.log(299792458)),      //         m   s^{-1}
G = new Complex(Math.log(6.67408e-11)),    // kg^{-1} m^3 s^{-2}
h = new Complex(Math.log(6.626070040e-34)), // kg      m^2 s^{-1}
Boltzmann = new Complex(Math.log(1.38064852e-23)), // J K^{-1}
/*
   2014 CODATA recommended values
   http://physics.nist.gov/constants
 */
tau = new Complex(Math.log(2 * Math.PI), 0.25),
two = new Complex(Math.log(2)),

kg = c.inv()        .mul(G)      .mul(h.inv()).mul(tau).log().mul(two.inv()).exp(),
m  = c.mul(c).mul(c).mul(G.inv()).mul(h.inv()).mul(tau).log().mul(two.inv()).exp(),
s  = m.mul(c)

var
e, touch,
isFixed = function() {
  return e.hasOwnProperty('value')
},
fix = function() {
  e.value || set(parseComplex(e.data.textContent))
},
fixAsIs = function() {
  set(e.value ? e.value.exp() : parseComplex(e.data.textContent + 'X'))
},
moveFocus = function() {
  e.classList.remove('focus')
  e = this.cell
  e.classList.add('focus')
},
makeCell = function() {
  var
  cell  = html.tr(),
  label = html.td(),
  input = html.input(),
  data  = html.td()

  label.appendChild(input)
  cell.appendChild(label)
  cell.appendChild(data)

  cell.label = input
  cell.data = data

  input.cell = cell
  input.onchange = function() {
    if (this.value === '') {
      this.cell.data[touch] = moveFocus
      while (this.cell.previousSibling.label.value !== '') {
        calc.display.insertBefore(this.cell, this.cell.previousSibling)
      }
      this.cell.classList.remove('button')
    } else
    {
      this.cell.data[touch] = function() {
        fix(); e.value && push(); set(this.cell.value)
      }
      if (e === this.cell) {
        fix()
        e.previousSibling ? e.previousSibling.data[touch]() : push()
      }
      this.cell.classList.add('button')
      while (this.cell.nextSibling && this.cell.nextSibling.label.value === '') {
        calc.display.insertBefore(this.cell, this.cell.nextSibling.nextSibling)
      }
      while (this.cell.nextSibling && this.cell.nextSibling.value.ord < this.cell.value.ord) {
        calc.display.insertBefore(this.cell, this.cell.nextSibling.nextSibling)
      }
    }
  }
  data.cell = cell
  data.textContent = '0'
  data[touch] = moveFocus

  return cell
},
push = function() {
  calc.display.insertBefore(makeCell(), e.nextSibling)
  e.nextSibling.data[touch]()
},
pop = function() {
  var _ = e.value

  e.previousSibling &&
  (e.previousSibling.data[touch](), calc.display.removeChild(e.nextSibling))

  return _
},
set = function(a) {
  e.value = a; e.data.textContent = a.toString()
},
numeric = function() {
  var label = this.textContent, _

  e.value && push()
  _ = e.data
  _.textContent = (_.textContent === '0' ? '' : _.textContent) + label
},
keys = {
  '0': numeric,
  '1': numeric,
  '2': numeric, '3': numeric, '4': numeric, '5': numeric,
  '6': numeric, '7': numeric, '8': numeric, '9': numeric,
  '.': function() {
    e.value && push()
    e.data.textContent += '.'
  },
  '↑': function() {
    if (e.value) {
      push(); set(e.previousSibling.value)
    } else
    {
      set(parseComplex(e.data.textContent))
    }
  },
  '↓': function() {
    if (e.previousSibling) {
      pop()
    } else
    {
      delete e.value
      e.data.textContent = '0'
    }
  },
  '←': function() {
    var _ = e.data

    if (e.value) {
      delete e.value
      _.textContent = '0'
    } else
    {
      _.textContent = _.textContent.slice(0, -1)
      _.textContent === '' && (_.textContent = '0')
    }
  },
  'kg': function() {
    fix(); e.value && push(); set(kg)
  },
  'm': function() {
    fix(); e.value && push(); set(m)
  },
  's': function() {
    fix(); e.value && push(); set(s)
  },
  'exp': function() {
    fixAsIs()
  },
  'log': function() {
    e.value || set(parseComplex(e.data.textContent)); e.value && set(e.value.log())
  },
  '/': function() {
    fix(); e.value && set(e.value.inv())
  },
  '−': function() {
    fix(); e.value && set(e.value.neg())
  },
  '†': function() {
    fix(); e.value && set(e.value.conjugate())
  },
  ' ': function() {
    var _
    if (e.previousSibling) {
      fix(); _ = pop()
      if (e.value) {
        set(e.value.mul(_))
      } else
      {
        set(0)
      }
    }
  },
  '+': function() {
    var _
    if (e.previousSibling) {
      fix(); _ = pop()
      if (e.value) {
        set(e.value.add(_))
      } else
      {
        set(_)
      }
    }
  }
}

touch = html.div().hasOwnProperty('ontouchend') ? 'ontouchend' : 'onmouseup';

calc.display = html.table()
calc.keypad  = html.table()

e = makeCell()
calc.display.appendChild(e)
calc.display.classList.add('display');

[ ['↑'  , '↓', '←', '7', '8', '9'],
  ['kg' , 'm', 's', '4', '5', '6'],
  ['log', ' ', '/', '1', '2', '3'],
  ['exp', '+', '−', '0', '.', '†'] ].forEach(function (tds) {
  var tr = html.tr()

  tds.forEach(function (td) {
    var _ = html.td()

    _.textContent = td
    _[touch] = keys[td]
    tr.appendChild(_)
  })
  calc.keypad.appendChild(tr)
})
calc.keypad.classList.add('keypad')

}()

onload = calc
<commit_msg>G to 4πG<commit_after>var calc = function () {
  document.body.appendChild(calc.display)
  document.body.appendChild(calc.keypad)
}

!function () {

var html = {};

['tr', 'td', 'input', 'div', 'table'].forEach(function (a) {
  html[a] = function() { return document.createElement(a) }
})

Complex.precision = 6

var
c = new Complex(Math.log(299792458)),      //         m   s^{-1}
G = new Complex(Math.log(4 * Math.PI * 6.67408e-11)),    // kg^{-1} m^3 s^{-2}
h = new Complex(Math.log(6.626070040e-34)), // kg      m^2 s^{-1}
Boltzmann = new Complex(Math.log(1.38064852e-23)), // J K^{-1}
/*
   2014 CODATA recommended values
   http://physics.nist.gov/constants
 */
tau = new Complex(Math.log(2 * Math.PI), 0.25),
two = new Complex(Math.log(2)),

kg = c.inv()        .mul(G)      .mul(h.inv()).mul(tau).log().mul(two.inv()).exp(),
m  = c.mul(c).mul(c).mul(G.inv()).mul(h.inv()).mul(tau).log().mul(two.inv()).exp(),
s  = m.mul(c)

var
e, touch,
isFixed = function() {
  return e.hasOwnProperty('value')
},
fix = function() {
  e.value || set(parseComplex(e.data.textContent))
},
fixAsIs = function() {
  set(e.value ? e.value.exp() : parseComplex(e.data.textContent + 'X'))
},
moveFocus = function() {
  e.classList.remove('focus')
  e = this.cell
  e.classList.add('focus')
},
makeCell = function() {
  var
  cell  = html.tr(),
  label = html.td(),
  input = html.input(),
  data  = html.td()

  label.appendChild(input)
  cell.appendChild(label)
  cell.appendChild(data)

  cell.label = input
  cell.data = data

  input.cell = cell
  input.onchange = function() {
    if (this.value === '') {
      this.cell.data[touch] = moveFocus
      while (this.cell.previousSibling.label.value !== '') {
        calc.display.insertBefore(this.cell, this.cell.previousSibling)
      }
      this.cell.classList.remove('button')
    } else
    {
      this.cell.data[touch] = function() {
        fix(); e.value && push(); set(this.cell.value)
      }
      if (e === this.cell) {
        fix()
        e.previousSibling ? e.previousSibling.data[touch]() : push()
      }
      this.cell.classList.add('button')
      while (this.cell.nextSibling && this.cell.nextSibling.label.value === '') {
        calc.display.insertBefore(this.cell, this.cell.nextSibling.nextSibling)
      }
      while (this.cell.nextSibling && this.cell.nextSibling.value.ord < this.cell.value.ord) {
        calc.display.insertBefore(this.cell, this.cell.nextSibling.nextSibling)
      }
    }
  }
  data.cell = cell
  data.textContent = '0'
  data[touch] = moveFocus

  return cell
},
push = function() {
  calc.display.insertBefore(makeCell(), e.nextSibling)
  e.nextSibling.data[touch]()
},
pop = function() {
  var _ = e.value

  e.previousSibling &&
  (e.previousSibling.data[touch](), calc.display.removeChild(e.nextSibling))

  return _
},
set = function(a) {
  e.value = a; e.data.textContent = a.toString()
},
numeric = function() {
  var label = this.textContent, _

  e.value && push()
  _ = e.data
  _.textContent = (_.textContent === '0' ? '' : _.textContent) + label
},
keys = {
  '0': numeric,
  '1': numeric,
  '2': numeric, '3': numeric, '4': numeric, '5': numeric,
  '6': numeric, '7': numeric, '8': numeric, '9': numeric,
  '.': function() {
    e.value && push()
    e.data.textContent += '.'
  },
  '↑': function() {
    if (e.value) {
      push(); set(e.previousSibling.value)
    } else
    {
      set(parseComplex(e.data.textContent))
    }
  },
  '↓': function() {
    if (e.previousSibling) {
      pop()
    } else
    {
      delete e.value
      e.data.textContent = '0'
    }
  },
  '←': function() {
    var _ = e.data

    if (e.value) {
      delete e.value
      _.textContent = '0'
    } else
    {
      _.textContent = _.textContent.slice(0, -1)
      _.textContent === '' && (_.textContent = '0')
    }
  },
  'kg': function() {
    fix(); e.value && push(); set(kg)
  },
  'm': function() {
    fix(); e.value && push(); set(m)
  },
  's': function() {
    fix(); e.value && push(); set(s)
  },
  'exp': function() {
    fixAsIs()
  },
  'log': function() {
    e.value || set(parseComplex(e.data.textContent)); e.value && set(e.value.log())
  },
  '/': function() {
    fix(); e.value && set(e.value.inv())
  },
  '−': function() {
    fix(); e.value && set(e.value.neg())
  },
  '†': function() {
    fix(); e.value && set(e.value.conjugate())
  },
  ' ': function() {
    var _
    if (e.previousSibling) {
      fix(); _ = pop()
      if (e.value) {
        set(e.value.mul(_))
      } else
      {
        set(0)
      }
    }
  },
  '+': function() {
    var _
    if (e.previousSibling) {
      fix(); _ = pop()
      if (e.value) {
        set(e.value.add(_))
      } else
      {
        set(_)
      }
    }
  }
}

touch = html.div().hasOwnProperty('ontouchend') ? 'ontouchend' : 'onmouseup';

calc.display = html.table()
calc.keypad  = html.table()

e = makeCell()
calc.display.appendChild(e)
calc.display.classList.add('display');

[ ['↑'  , '↓', '←', '7', '8', '9'],
  ['kg' , 'm', 's', '4', '5', '6'],
  ['log', ' ', '/', '1', '2', '3'],
  ['exp', '+', '−', '0', '.', '†'] ].forEach(function (tds) {
  var tr = html.tr()

  tds.forEach(function (td) {
    var _ = html.td()

    _.textContent = td
    _[touch] = keys[td]
    tr.appendChild(_)
  })
  calc.keypad.appendChild(tr)
})
calc.keypad.classList.add('keypad')

}()

onload = calc
<|endoftext|>