<commit_before>/*! NProgress (c) 2013, Rico Sta. Cruz
 *  http://ricostacruz.com/nprogress */

;(function(factory) {

  if (typeof module === 'function') {
    module.exports = factory(this.jQuery || require('jquery'));
  } else if (typeof define === 'function' && define.amd) {
    define(['jquery'], function($) {
      return factory($);
    });
  } else {
    this.NProgress = factory(this.jQuery);
  }

})(function($) {
  var NProgress = {};

  NProgress.version = '0.1.2';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    $.extend(Settings, options);
    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var $progress = NProgress.render(!started),
        $bar      = $progress.find('[role="bar"]'),
        speed     = Settings.speed,
        ease      = Settings.easing;

    $progress[0].offsetWidth; /* Repaint */

    $progress.queue(function(next) {
      // Set positionUsing if it hasn't already been set
      if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

      // Add transition
      $bar.css(barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        $progress.css({ transition: 'none', opacity: 1 });
        $progress[0].offsetWidth; /* Repaint */

        setTimeout(function() {
          $progress.css({ transition: 'all '+speed+'ms linear', opacity: 0 });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return $("#nprogress");
    $('html').addClass('nprogress-busy');

    var $el = $("
")
      .html(Settings.template);

    var perc = fromStart ? '-100' : toBarPerc(NProgress.status || 0);

    $el.find('[role="bar"]').css({
      transition: 'all 0 linear',
      transform: 'translate3d('+perc+'%,0,0)'
    });

    if (!Settings.showSpinner)
      $el.find('[role="spinner"]').remove();

    $el.appendTo(document.body);

    return $el;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    $('html').removeClass('nprogress-busy');
    $('#nprogress').remove();
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return ($("#nprogress").length > 0);
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  return NProgress;
});

<commit_msg>valid initial position in browsers without 3D support<commit_after>/*! NProgress (c) 2013, Rico Sta. Cruz
 *  http://ricostacruz.com/nprogress */

;(function(factory) {

  if (typeof module === 'function') {
    module.exports = factory(this.jQuery || require('jquery'));
  } else if (typeof define === 'function' && define.amd) {
    define(['jquery'], function($) {
      return factory($);
    });
  } else {
    this.NProgress = factory(this.jQuery);
  }

})(function($) {
  var NProgress = {};

  NProgress.version = '0.1.2';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    $.extend(Settings, options);
    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    // Set positionUsing if it hasn't already been set
    if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

    var $progress = NProgress.render(!started),
        $bar      = $progress.find('[role="bar"]'),
        speed     = Settings.speed,
        ease      = Settings.easing;

    $progress[0].offsetWidth; /* Repaint */

    $progress.queue(function(next) {
      // Add transition
      $bar.css(barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        $progress.css({ transition: 'none', opacity: 1 });
        $progress[0].offsetWidth; /* Repaint */

        setTimeout(function() {
          $progress.css({ transition: 'all '+speed+'ms linear', opacity: 0 });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return $("#nprogress");
    $('html').addClass('nprogress-busy');

    var $el = $("
")
      .html(Settings.template);

    var perc = fromStart ? '-100' : toBarPerc(NProgress.status || 0);

    $el.find('[role="bar"]').css({
      transition: 'all 0 linear',
      transform: Settings.positionUsing == 'translate' ? 'translate('+perc+'%,0)' : 'translate3d('+perc+'%,0,0)'
    });

    if (!Settings.showSpinner)
      $el.find('[role="spinner"]').remove();

    $el.appendTo(document.body);

    return $el;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    $('html').removeClass('nprogress-busy');
    $('#nprogress').remove();
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return ($("#nprogress").length > 0);
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  return NProgress;
});

<|endoftext|>


<commit_before>DroolsPlatformControllers.controller('assetPackagingController', function ($rootScope, $scope, $http, $log) {
    $scope.filters = {};
    $scope.isRelease = false;
    $scope.version = undefined;
    $scope.selectPackage = {allowClear: true};
    $scope.filtersOptions = {selectOnBlur: true};

    $http.get('./server/rules_package/list')
        .success(function (data) {
            $scope.packagesList = data;
        })
        .error(function (error) {
            console.log(error);
        });

    $http.get('./server/rule_status/all')
        .success(function (data) {
            $scope.statuses = data;
        })
        .error(function (error) {
            console.log(error);
        });
    $scope.searchPackageByName = function() {
        var packageSelected=$scope.package;
        var packageSnapshotRequest = {
            assetStatuses: $scope.filters,
            version: $scope.version,
            isRelease: $scope.isRelease
        };
        if(packageSelected == "") {
            $scope.namePackageSelectClass="form-group has-error has-feedback";

        }else{
            $scope.namePackageSelectClass="form-group";
            $http.post('./server/rules_package/build', packageSnapshotRequest)
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                    console.log(data);
                })
                .error(function (error, status) {
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                    $scope.status=status;
                    console.log(error);

                })
        }
    };
    $scope.createVersion = function() {
        var packageSelected=$scope.package;
        var packageSnapshotRequest = {
            assetStatuses: $scope.filters,
            version: $scope.version,
            isRelease: $scope.isRelease
        };
        if(packageSelected == "") {
            $scope.namePackageSelectClass="form-group has-error has-feedback";

        }else{
            $scope.namePackageSelectClass="form-group";
            $http.post('./server/rules_package/build', packageSnapshotRequest)
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                    console.log(data);
                })
                .error(function (error, status) {
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                    $scope.status=status;
                    console.log(error);

                })
        }
    };
    $scope.reset = function () {
        $scope.showCancelButton=false;
        $scope.noAssetSent = false;
        $scope.filters = undefined;
    }
});
<commit_msg>Some modifications in the UI.<commit_after>DroolsPlatformControllers.controller('assetPackagingController', function ($rootScope, $scope, $http, $log) {
    $scope.filters = {};
    $scope.isRelease = false;
    $scope.version = undefined;
    $scope.selectPackage = {allowClear: true};
    $scope.filtersOptions = {selectOnBlur: true};

    $http.get('./server/rules_package/list')
        .success(function (data) {
            $scope.packagesList = data;
        })
        .error(function (error) {
            console.log(error);
        });

    $http.get('./server/rule_status/all')
        .success(function (data) {
            $scope.statuses = data;
        })
        .error(function (error) {
            console.log(error);
        });
    $scope.searchPackageByName = function() {
        var packageSelected=$scope.package;
        if(packageSelected == "") {
            $scope.namePackageSelectClass="form-group has-error has-feedback";

        }else{
            $scope.namePackageSelectClass="form-group";
            $http.post('./server/rules_package/build', packageSnapshotRequest)
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                    console.log(data);
                })
                .error(function (error, status) {
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                    $scope.status=status;
                    console.log(error);

                })
        }
    };
    $scope.createVersion = function() {
        var packageSelected=$scope.package;
        var packageSnapshotRequest = {
            assetStatuses: $scope.filters,
            version: $scope.version,
            isRelease: $scope.isRelease
        };
        if(packageSelected == "") {
            $scope.namePackageSelectClass="form-group has-error has-feedback";

        }else{
            $scope.namePackageSelectClass="form-group";
            $http.post('./server/rules_package/build', packageSnapshotRequest)
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                    console.log(data);
                })
                .error(function (error, status) {
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                    $scope.status=status;
                    console.log(error);

                })
        }
    };
    $scope.reset = function () {
        $scope.showCancelButton=false;
        $scope.noAssetSent = false;
        $scope.filters = undefined;
    }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  // Create the list of image divs with papers using galpy
  //https://d2g2jw00kypyq.cloudfront.net = https://www.galpy.org (but latter doesn't work)
  $.getJSON("https://d2g2jw00kypyq.cloudfront.net/data/papers-using-galpy.json")
    .done(function(data) {
    // First update the number of papers using galpy listed on the page
    let paperSpan= document.getElementById("span-number-of-papers-using-galpy");
    paperSpan.innerHTML= (Math.floor((Object.keys(data).length-1)/50)*50).toFixed(0);
    // randomize array to create random starting point, https://stackoverflow.com/a/56448185/10195320
      function shuffle(obj){
        // new obj to return
        let newObj = {};
        // create keys array
        var keys = Object.keys(obj);
        // randomize keys array
        keys.sort(function(a,b){return Math.random()- 0.5;});
        // save in new array
        keys.forEach(function(k) {
          newObj[k] = obj[k];
        });
        return newObj;
      }
      $.each(shuffle(data),function(key,bibentry) {
        if ( key != "_template" && bibentry.hasOwnProperty("img")) {
	    $("
").attr("id",`${key}-div1`).addClass("responsive").appendTo("#papers-gallery");
	    $("
").attr("id",`${key}-div2`).addClass("gallery").appendTo(`#${key}-div1`);
	    $("").attr("id",`${key}-link`).attr("href",bibentry.url).attr("target","_blank")
		.attr("alt",`Figure from ${bibentry.title}, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}`)
		.attr("title",`Figure from ${bibentry.title}, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}`).appendTo(`#${key}-div2`);
	    $("
").attr("id",key).addClass("papers-gallery-item").appendTo(`#${key}-link`);
	    $("").attr("data-src","https://d2g2jw00kypyq.cloudfront.net/data/paper-figs/"+bibentry.img).attr("loading","lazy").addClass("lazyload").appendTo(`#${key}`);
	    $("
"+`<font size="-3"><i>${bibentry.title}</i>, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}</font>`+"
").addClass("desc").appendTo(`#${key}-div2`);
	}
	  });
      // Lazy loading of images...
      if ('loading' in HTMLImageElement.prototype) {
	  const images = document.querySelectorAll("img.lazyload");
	  images.forEach(img => {
		  img.src = img.dataset.src;
	      });
      } else {
	  // Dynamically import the LazySizes library
	  let script = document.createElement("script");
	  script.async = true;
	  script.src =
	      "https://cdnjs.cloudflare.com/ajax/libs/lazysizes/4.1.8/lazysizes.min.js";
	  document.body.appendChild(script);
      }
	})
      .fail(function(jqxhr, textStatus, error ) {
        console.log( "Failed to load JSON gallery file");
	// Add div with warning that the gallery failed to load
	$("
").attr("id","papers-warning").addClass("admonition warning").appendTo("#papers-gallery");
	$("
Warning
").addClass("admonition-title").appendTo("#papers-warning");
	$("
Failed to load papers gallery.
").appendTo("#papers-warning");
	// Make sure the warning spans the page
	$("#papers-gallery").css("width","100%");
      });
});
<commit_msg>Make sure to not cache the galpy papers JSON file in the docs [ci skip]<commit_after>$(document).ready(function() {
  // Create the list of image divs with papers using galpy
    //https://d2g2jw00kypyq.cloudfront.net = https://www.galpy.org (but latter doesn't work); ?+new Date etc. to make sure file isn't cached
    $.getJSON("https://d2g2jw00kypyq.cloudfront.net/data/papers-using-galpy.json?"+new Date().getTime())
    .done(function(data) {
    // First update the number of papers using galpy listed on the page
    let paperSpan= document.getElementById("span-number-of-papers-using-galpy");
    paperSpan.innerHTML= (Math.floor((Object.keys(data).length-1)/50)*50).toFixed(0);
    // randomize array to create random starting point, https://stackoverflow.com/a/56448185/10195320
      function shuffle(obj){
        // new obj to return
        let newObj = {};
        // create keys array
        var keys = Object.keys(obj);
        // randomize keys array
        keys.sort(function(a,b){return Math.random()- 0.5;});
        // save in new array
        keys.forEach(function(k) {
          newObj[k] = obj[k];
        });
        return newObj;
      }
      $.each(shuffle(data),function(key,bibentry) {
        if ( key != "_template" && bibentry.hasOwnProperty("img")) {
	    $("
").attr("id",`${key}-div1`).addClass("responsive").appendTo("#papers-gallery");
	    $("
").attr("id",`${key}-div2`).addClass("gallery").appendTo(`#${key}-div1`);
	    $("").attr("id",`${key}-link`).attr("href",bibentry.url).attr("target","_blank")
		.attr("alt",`Figure from ${bibentry.title}, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}`)
		.attr("title",`Figure from ${bibentry.title}, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}`).appendTo(`#${key}-div2`);
	    $("
").attr("id",key).addClass("papers-gallery-item").appendTo(`#${key}-link`);
	    $("").attr("data-src","https://d2g2jw00kypyq.cloudfront.net/data/paper-figs/"+bibentry.img).attr("loading","lazy").addClass("lazyload").appendTo(`#${key}`);
	    $("
"+`<font size="-3"><i>${bibentry.title}</i>, ${bibentry.author} (${bibentry.year}), ${bibentry.journal} ${bibentry.volume}, ${bibentry.pages}</font>`+"
").addClass("desc").appendTo(`#${key}-div2`);
	}
	  });
      // Lazy loading of images...
      if ('loading' in HTMLImageElement.prototype) {
	  const images = document.querySelectorAll("img.lazyload");
	  images.forEach(img => {
		  img.src = img.dataset.src;
	      });
      } else {
	  // Dynamically import the LazySizes library
	  let script = document.createElement("script");
	  script.async = true;
	  script.src =
	      "https://cdnjs.cloudflare.com/ajax/libs/lazysizes/4.1.8/lazysizes.min.js";
	  document.body.appendChild(script);
      }
	})
      .fail(function(jqxhr, textStatus, error ) {
        console.log( "Failed to load JSON gallery file");
	// Add div with warning that the gallery failed to load
	$("
").attr("id","papers-warning").addClass("admonition warning").appendTo("#papers-gallery");
	$("
Warning
").addClass("admonition-title").appendTo("#papers-warning");
	$("
Failed to load papers gallery.
").appendTo("#papers-warning");
	// Make sure the warning spans the page
	$("#papers-gallery").css("width","100%");
      });
});
<|endoftext|>


<commit_before>var cmdln = require('cmdln');
var fs = require('fs');
var util = require('util');
var format = util.format;
var sprintf = require('sprintf').sprintf;
var request = require('request');
var cheerio = require('cheerio');

var jenkins = require('jenkins');
var assert = require('assert-plus');
var async = require('async');
var tabula = require('tabula');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

function App() {
    this.blacklist = ['master', 'pkgsrc-pbulk-master'];

    cmdln.Cmdln.call(this, {
        name: 'sdc-jenkins',
        desc: 'SDC Jenkins Multitool',
        options: [
            {
                names: ['config', 'c'],
                helpArg: 'FILE',
                type: 'string',
                default: process.env.HOME + '/.sdcjenkins',
                help:
                    'Configuration JSON file. ' +
                    'Must contain keys: user, pass, host.'
            }
        ]
    });
}

util.inherits(App, cmdln.Cmdln);

App.prototype.do_create_node = function (subcmd, opts, args, callback) {

    var params = [ args[0] ];

    if (opts.image) {
        params.push(opts.image);
    }

    var spawnArgs = [
        __dirname + '/../create-jenkins-slave/copy-and-start.sh',
        params,
        {
            env: {
                JENKINS_USER: opts.jenkins_user
            }
        } ,
        function (error, stdout, stderr) {
            if (error) {
                console.warn('ERROR:');
                callback(error);
                return;
            }

            callback();
        }
    ];

    console.dir(spawnArgs);

    spawn.apply(null, spawnArgs);
};

App.prototype.do_create_node.help =
    'Create a new SDC Jenkins node\n'
    + '\n'
    + 'Usage:\n'
    + '     {{name}} create-node [OPTIONS] node-name\n'
    + '\n'
    + '{{options}}';

App.prototype.do_create_node.options = [
    {
        names: ['jenkins-user', 'u'],
        helpArg: 'USER',
        type: 'string',
        default: 'guest',
        help: 'Jenkins user for jenkins-ssh-api access.'
    },
    {
        names: ['image', 'i'],
        helpArg: 'IMAGE',
        type: 'string',
        default: 'sdc-smartos-1.6.3',
        help: 'Name of image to be used for provisioning Jenkins node'
    }
];

App.prototype.do_nodes = function (subcmd, opts, args, callback) {
    var self = this;

    var list, infos = {}, mdata, labels;

    self.initialize();

    async.waterfall([
        getNodeList,
        getNodesSystemInfo,
        getNodesMdata,
        getNodeLabels
    ],
    function (err) {
        if (err) {
            console.warn(err.message);
            return;
        }
        var input = [];

        list.computer.forEach(function (i) {
            if (self.blacklist.indexOf(i.displayName) !== -1) {
                return;
            }

            var item = {
                name: i.displayName,
                ip: (infos[i.displayName] &&
                     infos[i.displayName].JENKINS_IP_ADDR),
                dc: mdata[i.displayName].datacenter_name,
                'package': mdata[i.displayName].package_name,
                image: mdata[i.displayName].image_uuid,
                server: mdata[i.displayName].server_uuid,
                pi: mdata[i.displayName].platform,
                labels: labels[i.displayName]
            };

            input.push(item);
        });

        var tabOptions = {
            columns: [
                'name', 'ip', 'dc', 'server', 'pi', 'image', 'package',
                'labels'],
            validFields: [
                'name', 'ip', 'dc', 'server', 'pi', 'image', 'package',
                'labels']
        };

        tabula(input, tabOptions);
    });

    function getNodeList(cb) {
        self.jc.node.list(function (err, l) {
            if (err) {
                cb(err);
                return;
            }

            list = l;
            cb();
        });
    }

    function getNodesSystemInfo(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        cb(); return;

        self.getNodeSystemInfo(nodes, function (err, systemInfos) {
            if (err) {
                cb(err);
                return;
            }
            infos = systemInfos;

            cb();
        });
    }

    function getNodesMdata(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        self.getNodesMdata(nodes, function (err, nodeMdata) {
            if (err) {
                cb(err);
                return;
            }
            mdata = nodeMdata;

            cb();
        });
    }

    function getNodeLabels(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        self.getNodeLabels(nodes, function (err, nodeLabels) {
            if (err) {
                cb(err);
                return;
            }
            labels = nodeLabels;

            cb();
        });
    }
};

App.prototype.do_nodes.help = 'Return all Jenkins nodes (workers)';

App.prototype.initialize = function () {
    this.config = JSON.parse(fs.readFileSync(this.opts.config));
    this.jenkinsUrl = sprintf('https://%s:%s@%s',
        this.config.user, this.config.pass, this.config.host);

    this.jc = jenkins(this.jenkinsUrl);

    assert.string(this.config.user, 'options.user');
    assert.string(this.config.pass, 'options.pass');
    assert.string(this.config.host, 'options.host');
};

/*
 * HTML scrape the node environment variables from the Jenkins HTML off the
 * Jenkins admin site.
 */

App.prototype.getNodeSystemInfo = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            var url = sprintf(
                '%s/computer/%s/systemInfo', self.jenkinsUrl, node);
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }
            request(url, function (error, response, body) {
                if (error) {
                    console.warn(error.message);
                    callback(error);
                    return;
                }

                var re = '
(.*?)	\\s*'
                           + ']+>(.*?)	\\s*
';
                var m = body.match(new RegExp(re, 'g'));

                var $;

                for (var i = 1; i < m.length; i++) {
                    if (!dict[node]) {
                        dict[node] = {};
                    }

                    $ = cheerio.load(m[i]);
                    var key = $('tr > td').eq(0).text();
                    var value = $('tr > td').eq(1).text();

                    dict[node][key] = value;
                }

                cb();
            });
        },
        function (err) {
            if (err) {
                callback(err);
                return;
            }

            callback(null, dict);
        });
};

/*
 * HTML scrape the node environment variables from the Jenkins HTML off the
 * Jenkins admin site.
 */

App.prototype.getNodesMdata = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }

            var vals = [
                'sdc:image_uuid',
                'sdc:server_uuid',
                'sdc:package_name',
                'sdc:datacenter_name'
            ];

            exec('ssh ' + node +
                 ' \'for i in ' + vals.join(' ') +
                 '; do mdata-get $i || echo "-"; done; sysinfo |json "Live Image"\'',
                 { timeout: 5000 },
                 function (err, stdout, stderr) {
                     if (!dict[node]) {
                         dict[node] = {};
                     }

                     if (err) {
                         console.warn(err.message);
                         dict[node].image_uuid = '!';
                         dict[node].server_uuid = '!';
                         dict[node].datacenter_name = '!';
                         dict[node].platform = '!';
                         dict[node].package_name = '!';
                         cb();
                         return;
                     }

                     var parts = stdout.trim().split('\n');

                     dict[node].image_uuid = parts[0];
                     dict[node].server_uuid = parts[1];
                     dict[node].package_name = parts[2];
                     dict[node].datacenter_name = parts[3];
                     dict[node].platform = parts[4];

                     cb();
                });
        },
        function (err) {
            callback(err, dict);
        });
};

App.prototype.getNodeLabels = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }

            exec('ssh jenkins-ssh-api get-node ' + node,
                 { timeout: 5000 },
                 function (err, stdout, stderr) {
                     var re = '(.*)';
                     var m = (new RegExp(re, 'g')).exec(stdout.toString());

                     if (!dict[node]) {
                         dict[node] = {};
                     }

                     if (!m) {
                         console.log(stdout);
                     }
                     dict[node] = m[1];

                     cb();
                     return;
                 });
        },
        function (err) {
            callback(err, dict);
        });
};

module.exports = App;
<commit_msg>RELENG-529: Add 'ssh-config' command to sdc-jenkins<commit_after>var cmdln = require('cmdln');
var fs = require('fs');
var util = require('util');
var format = util.format;
var sprintf = require('sprintf').sprintf;
var request = require('request');
var cheerio = require('cheerio');

var jenkins = require('jenkins');
var assert = require('assert-plus');
var async = require('async');
var tabula = require('tabula');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

function App() {
    this.blacklist = ['master', 'pkgsrc-pbulk-master'];

    cmdln.Cmdln.call(this, {
        name: 'sdc-jenkins',
        desc: 'SDC Jenkins Multitool',
        options: [
            {
                names: ['config', 'c'],
                helpArg: 'FILE',
                type: 'string',
                default: process.env.HOME + '/.sdcjenkins',
                help:
                    'Configuration JSON file. ' +
                    'Must contain keys: user, pass, host.'
            }
        ]
    });
}

util.inherits(App, cmdln.Cmdln);

App.prototype.do_ssh_config = function (subcmd, opts, args, callback) {
    var self = this;
    var nodes = [];

    var infos = {}, mdata, labels;

    self.initialize();

    async.waterfall([
        getNodeList,
        getNodesSystemInfo
    ],
    function (err) {
        if (err) {
            console.warn(err.message);
            return;
        }

        var items = [];

        nodes.forEach(function (n) {
            var item = {
                name: n,
                ip: (infos[n] &&
                     infos[n].JENKINS_IP_ADDR)
            };

            if (!item.ip) {
                console.warn('Error: no IP address for %s', n);
                return;
            }
            console.log(sprintf(
                'Host %s\n'
              + '    Hostname %s\n'
              + '    StrictHostKeyChecking no\n'
              + '    UserKnownHostsFile /dev/null\n', n, item.ip));
        });

        callback();
    });

    function getNodeList(cb) {
        if (args.length) {
            nodes = args;
            nodes.sort();
        } else {
            self.jc.node.list(function (err, l) {
                if (err) {
                    cb(err);
                    return;
                }

                nodes = l.computer.map(function (i) { return i.displayName; });
                nodes.sort();
                cb();
            });
        }
    }

    function getNodesSystemInfo(cb) {
        self.getNodeSystemInfo(nodes, function (err, systemInfos) {
            if (err) {
                cb(err);
                return;
            }
            infos = systemInfos;

            cb();
        });
    }

    function getNodesMdata(cb) {
        self.getNodesMdata(nodes, function (err, nodeMdata) {
            if (err) {
                cb(err);
                return;
            }
            mdata = nodeMdata;

            cb();
        });
    }
};

App.prototype.do_ssh_config.help = 'Generate SSH config for given Jenkins nodes with defined addresses';

App.prototype.do_create_node = function (subcmd, opts, args, callback) {
    var params = [ args[0] ];

    if (opts.image) {
        params.push(opts.image);
    }

    var spawnArgs = [
        __dirname + '/../create-jenkins-slave/copy-and-start.sh',
        params,
        {
            env: {
                JENKINS_USER: opts.jenkins_user
            }
        } ,
        function (error, stdout, stderr) {
            if (error) {
                console.warn('ERROR:');
                callback(error);
                return;
            }

            callback();
        }
    ];

    console.dir(spawnArgs);

    spawn.apply(null, spawnArgs);
};

App.prototype.do_create_node.help =
    'Create a new SDC Jenkins node\n'
    + '\n'
    + 'Usage:\n'
    + '     {{name}} create-node [OPTIONS] node-name\n'
    + '\n'
    + '{{options}}';

App.prototype.do_create_node.options = [
    {
        names: ['jenkins-user', 'u'],
        helpArg: 'USER',
        type: 'string',
        default: 'guest',
        help: 'Jenkins user for jenkins-ssh-api access.'
    },
    {
        names: ['image', 'i'],
        helpArg: 'IMAGE',
        type: 'string',
        default: 'sdc-smartos-1.6.3',
        help: 'Name of image to be used for provisioning Jenkins node'
    }
];

App.prototype.do_nodes = function (subcmd, opts, args, callback) {
    var self = this;

    var list, infos = {}, mdata, labels;

    self.initialize();

    async.waterfall([
        getNodeList,
        getNodesSystemInfo,
        getNodesMdata,
        getNodeLabels
    ],
    function (err) {
        if (err) {
            console.warn(err.message);
            return;
        }
        var input = [];

        list.computer.forEach(function (i) {
            if (self.blacklist.indexOf(i.displayName) !== -1) {
                return;
            }

            var item = {
                name: i.displayName,
                ip: (infos[i.displayName] &&
                     infos[i.displayName].JENKINS_IP_ADDR),
                dc: mdata[i.displayName].datacenter_name,
                'package': mdata[i.displayName].package_name,
                image: mdata[i.displayName].image_uuid,
                server: mdata[i.displayName].server_uuid,
                pi: mdata[i.displayName].platform,
                labels: labels[i.displayName]
            };

            input.push(item);
        });

        var tabOptions = {
            columns: [
                'name', 'ip', 'dc', 'server', 'pi', 'image', 'package',
                'labels'],
            validFields: [
                'name', 'ip', 'dc', 'server', 'pi', 'image', 'package',
                'labels']
        };

        tabula(input, tabOptions);
    });

    function getNodeList(cb) {
        self.jc.node.list(function (err, l) {
            if (err) {
                cb(err);
                return;
            }

            list = l;
            cb();
        });
    }

    function getNodesSystemInfo(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        cb(); return;

        self.getNodeSystemInfo(nodes, function (err, systemInfos) {
            if (err) {
                cb(err);
                return;
            }
            infos = systemInfos;

            cb();
        });
    }

    function getNodesMdata(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        self.getNodesMdata(nodes, function (err, nodeMdata) {
            if (err) {
                cb(err);
                return;
            }
            mdata = nodeMdata;

            cb();
        });
    }

    function getNodeLabels(cb) {
        var nodes = list.computer.map(function (i) { return i.displayName; });

        self.getNodeLabels(nodes, function (err, nodeLabels) {
            if (err) {
                cb(err);
                return;
            }
            labels = nodeLabels;

            cb();
        });
    }
};

App.prototype.do_nodes.help = 'Return all Jenkins nodes (workers)';

App.prototype.initialize = function () {
    this.config = JSON.parse(fs.readFileSync(this.opts.config));
    this.jenkinsUrl = sprintf('https://%s:%s@%s',
        this.config.user, this.config.pass, this.config.host);

    this.jc = jenkins(this.jenkinsUrl);

    assert.string(this.config.user, 'options.user');
    assert.string(this.config.pass, 'options.pass');
    assert.string(this.config.host, 'options.host');
};

/*
 * HTML scrape the node environment variables from the Jenkins HTML off the
 * Jenkins admin site.
 */

App.prototype.getNodeSystemInfo = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            var url = sprintf(
                '%s/computer/%s/systemInfo', self.jenkinsUrl, node);
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }
            request(url, { rejectUnauthorized: false }, function (error, response, body) {
                if (error) {
                    console.warn(error.message);
                    callback(error);
                    return;
                }

                var re = '
(.*?)	\\s*'
                           + ']+>(.*?)	\\s*
';
                var m = body.match(new RegExp(re, 'g'));

                var $;

                for (var i = 1; i < m.length; i++) {
                    if (!dict[node]) {
                        dict[node] = {};
                    }

                    $ = cheerio.load(m[i]);
                    var key = $('tr > td').eq(0).text();
                    var value = $('tr > td').eq(1).text();

                    dict[node][key] = value;
                }

                cb();
            });
        },
        function (err) {
            if (err) {
                callback(err);
                return;
            }

            callback(null, dict);
        });
};

/*
 * HTML scrape the node environment variables from the Jenkins HTML off the
 * Jenkins admin site.
 */

App.prototype.getNodesMdata = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }

            var vals = [
                'sdc:image_uuid',
                'sdc:server_uuid',
                'sdc:package_name',
                'sdc:datacenter_name'
            ];

            exec('ssh ' + node +
                 ' \'for i in ' + vals.join(' ') +
                 '; do mdata-get $i || echo "-"; done; sysinfo |json "Live Image"\'',
                 { timeout: 5000 },
                 function (err, stdout, stderr) {
                     if (!dict[node]) {
                         dict[node] = {};
                     }

                     if (err) {
                         console.warn(err.message);
                         dict[node].image_uuid = '!';
                         dict[node].server_uuid = '!';
                         dict[node].datacenter_name = '!';
                         dict[node].platform = '!';
                         dict[node].package_name = '!';
                         cb();
                         return;
                     }

                     var parts = stdout.trim().split('\n');

                     dict[node].image_uuid = parts[0];
                     dict[node].server_uuid = parts[1];
                     dict[node].package_name = parts[2];
                     dict[node].datacenter_name = parts[3];
                     dict[node].platform = parts[4];

                     cb();
                });
        },
        function (err) {
            callback(err, dict);
        });
};

App.prototype.getNodeLabels = function (n, callback) {
    var self = this;
    var dict = {};

    var nodes = [];

    if (!Array.isArray(n)) {
        nodes.push(n);
    } else {
        nodes = n;
    }

    async.each(
        nodes,
        function (node, cb) {
            if (self.blacklist.indexOf(node) !== -1) {
                cb();
                return;
            }

            exec('ssh jenkins-ssh-api get-node ' + node,
                 { timeout: 5000 },
                 function (err, stdout, stderr) {
                     var re = '(.*)';
                     var m = (new RegExp(re, 'g')).exec(stdout.toString());

                     if (!dict[node]) {
                         dict[node] = {};
                     }

                     if (!m) {
                         console.log(stdout);
                     }
                     dict[node] = m[1];

                     cb();
                     return;
                 });
        },
        function (err) {
            callback(err, dict);
        });
};

module.exports = App;
<|endoftext|>


<commit_before>/* global define: false, angular: false */
define(['text!./variable-instance-upload-dialog.html', 'text!./variable-instance-inspect-dialog.html', 'text!./variable-instances-tab.html'],
function(uploadTemplate, inspectTemplate, instancesTemplate) {
  'use strict';

  return function(ngModule) {
    ngModule.controller('VariableInstancesController', [
              '$scope', '$sce', '$http', 'search', 'Uri', 'LocalExecutionVariableResource', 'Notifications', '$modal', '$q', 'camAPI',
      function($scope,   $sce,   $http,   search,   Uri,   LocalExecutionVariableResource,   Notifications,   $modal,   $q,   camAPI) {

        // input: processInstance, processData

        var variableInstanceData = $scope.processData.newChild($scope),
            processInstance = $scope.processInstance,
            variableInstanceIdexceptionMessageMap,
            variableCopies;

        var executionService = camAPI.resource('execution');

        var DEFAULT_PAGES = { size: 50, total: 0, current: 1 };

        var pages = $scope.pages = angular.copy(DEFAULT_PAGES);

        var filter = null;

        $scope.$watch('pages.current', function(newValue, oldValue) {
          if (newValue == oldValue) {
            return;
          }

          search('page', !newValue || newValue == 1 ? null : newValue);
        });

        variableInstanceData.observe([ 'filter', 'instanceIdToInstanceMap' ], function(newFilter, instanceIdToInstanceMap) {
          pages.current = newFilter.page || 1;

          updateView(newFilter, instanceIdToInstanceMap);
        });

        $scope.uploadVariable = function(info) {
          var promise = $q.defer();
          $modal.open({
            resolve: {
              variableInstance: function() { return info.variable; }
            },
            controller: 'VariableInstanceUploadController',
            template: uploadTemplate
          })
          .result.then(function() {
            // updated the variable, need to get the new data
            // reject the promise anyway
            promise.reject();

            // but then update the filter to force re-get of variables
            variableInstanceData.set('filter', angular.copy($scope.filter));
          }, function() {
            // did not update the variable, reject the promise
            promise.reject();
          });

          return promise.promise;
        };

        $scope.deleteVariable = function(info) {
          var promise = $q.defer();

          executionService.deleteVariable({
            id: info.variable.executionId,
            varId: info.variable.name
          }, function() {
            promise.resolve(info.variable);
          });

          return promise.promise;
        };

        $scope.editVariable = function(info) {
          var promise = $q.defer();

          $modal.open({
            template: inspectTemplate,

            controller: 'VariableInstanceInspectController',

            windowClass: 'cam-widget-variable-dialog',

            resolve: {
              variableInstance: function () { return info.variable; }
            }
          })
          .result.then(function() {
            // updated the variable, need to get the new data
            // reject the promise anyway
            promise.reject();

            // but then update the filter to force re-get of variables
            variableInstanceData.set('filter', angular.copy($scope.filter));
          }, function() {
            // did not update the variable, reject the promise
            promise.reject();
          });

          return promise.promise;
        };

        $scope.saveVariable = function (info) {
          var promise = $q.defer();
          var variable = info.variable;
          var modifiedVariable = {};

          var newValue = variable.value;//$scope.getCopy(variable.id).value;
          var newType = variable.type;//$scope.getCopy(variable.id).type;

          var newVariable = { value: newValue, type: newType };
          modifiedVariable[variable.name] = newVariable;

          LocalExecutionVariableResource.updateVariables({
            executionId: variable.executionId
          }, {
            modifications : modifiedVariable
          }).$promise.then(
            // success
            function() {
              Notifications.addMessage({
                status: 'Variable',
                message: 'The variable \'' + variable.name + '\' has been changed successfully.',
                duration: 5000
              });
              angular.extend(variable, newVariable);
              promise.resolve(info.variable);
              // $scope.closeInPlaceEditing(variable);
            },
            // error
            function (error) {
              // set the exception
              Notifications.addError({
                status: 'Variable',
                message: 'The variable \'' + variable.name + '\' could not be changed successfully.',
                exclusive: true,
                duration: 5000
              });
              variableInstanceIdexceptionMessageMap[variable.id] = error.data;
              promise.reject();
            });
          return promise.promise;
        };

        function updateView(newFilter, instanceIdToInstanceMap) {
          filter = $scope.filter = angular.copy(newFilter);

          delete filter.page;
          delete filter.activityIds;
          delete filter.scrollToBpmnElement;

          var page = pages.current,
              count = pages.size,
              firstResult = (page - 1) * count;

          var defaultParams = {
            processInstanceIdIn: [ processInstance.id ]
          };

          var pagingParams = {
            firstResult: firstResult,
            maxResults: count,
            deserializeValues: false
          };

          var params = angular.extend({}, filter, defaultParams);

          // fix missmatch -> activityInstanceIds -> activityInstanceIdIn
          params.activityInstanceIdIn = params.activityInstanceIds;
          delete params.activityInstanceIds;

          $scope.variables = null;
          $scope.loadingState = 'LOADING';

          // get the 'count' of variables
          $http.post(Uri.appUri('engine://engine/:engine/variable-instance/count'), params).success(function(data) {
            pages.total = data.count;
          });

          variableInstanceIdexceptionMessageMap = {};
          variableCopies = {};

          $http.post(Uri.appUri('engine://engine/:engine/variable-instance/'), params, { params: pagingParams }).success(function(data) {

            $scope.variables = data.map(function (item) {
              var instance = instanceIdToInstanceMap[item.activityInstanceId];
              item.instance = instance;
              variableCopies[item.id] = angular.copy(item);

              return {
                variable: {
                  id:           item.id,
                  name:         item.name,
                  type:         item.type,
                  value:        item.value,
                  valueInfo:    item.valueInfo,
                  executionId:  item.executionId
                },
                additions: {
                  scope: {
                    html:  '<a cam-select-activity-instance="\'' +
                                      instance.id +
                                      '\'" ng-href="#/process-instance/' +
                                      processInstance.id +
                                      '?detailsTab=variables-tab&activityInstanceIds=' +
                                      instance.id +
                                      '" title="' +
                                      instance.id +
                                      '">' +
                                        instance.name  +
                                      '',
                    scopeVariables: {
                      processData: $scope.processData
                    }
                  }
                }
              };
            });

            $scope.loadingState = data.length ? 'LOADED' : 'EMPTY';
          });
        }

        $scope.getCopy = function (variableId) {
          var copy = variableCopies[variableId];
          if (isNull(copy)) {
            copy.type = 'String';
          }
          return copy;
        };

        var isNull = $scope.isNull = function (variable) {
          return variable.type === 'null' || variable.type === 'Null';
        };

        $scope.getBinaryVariableDownloadLink = function (variable) {
          return Uri.appUri('engine://engine/:engine/variable-instance/'+variable.id+'/data');
        };

        $scope.openUploadDialog = function (variableInstance) {
          $modal.open({
            resolve: {
              variableInstance: function() { return variableInstance; }
            },
            controller: 'VariableInstanceUploadController',
            template: uploadTemplate
          });
        };

        $scope.openInspectDialog = function (variableInstance) {
          $modal.open({
            resolve: {
              variableInstance: function() { return variableInstance; }
            },
            controller: 'VariableInstanceInspectController',
            template: inspectTemplate
          }).result.then(function() {
            variableInstanceData.set('filter', angular.copy($scope.filter));
          });
        };
      }]);

      var Configuration = function PluginConfiguration(ViewsProvider) {

        ViewsProvider.registerDefaultView('cockpit.processInstance.runtime.tab', {
          id: 'variables-tab',
          label: 'Variables',
          template: instancesTemplate,
          controller: 'VariableInstancesController',
          priority: 20
        });
      };

      Configuration.$inject = ['ViewsProvider'];
      ngModule.config(Configuration);
  };
});
<commit_msg>fix(variables): allow modification of local task variables<commit_after>/* global define: false, angular: false */
define(['text!./variable-instance-upload-dialog.html', 'text!./variable-instance-inspect-dialog.html', 'text!./variable-instances-tab.html'],
function(uploadTemplate, inspectTemplate, instancesTemplate) {
  'use strict';

  return function(ngModule) {
    ngModule.controller('VariableInstancesController', [
              '$scope', '$sce', '$http', 'search', 'Uri', 'LocalExecutionVariableResource', 'Notifications', '$modal', '$q', 'camAPI',
      function($scope,   $sce,   $http,   search,   Uri,   LocalExecutionVariableResource,   Notifications,   $modal,   $q,   camAPI) {

        // input: processInstance, processData

        var variableInstanceData = $scope.processData.newChild($scope),
            processInstance = $scope.processInstance,
            variableInstanceIdexceptionMessageMap,
            variableCopies;

        var executionService = camAPI.resource('execution'),
            taskService = camAPI.resource('task');

        var DEFAULT_PAGES = { size: 50, total: 0, current: 1 };

        var pages = $scope.pages = angular.copy(DEFAULT_PAGES);

        var filter = null;

        $scope.$watch('pages.current', function(newValue, oldValue) {
          if (newValue == oldValue) {
            return;
          }

          search('page', !newValue || newValue == 1 ? null : newValue);
        });

        variableInstanceData.observe([ 'filter', 'instanceIdToInstanceMap' ], function(newFilter, instanceIdToInstanceMap) {
          pages.current = newFilter.page || 1;

          updateView(newFilter, instanceIdToInstanceMap);
        });

        $scope.uploadVariable = function(info) {
          var promise = $q.defer();
          $modal.open({
            resolve: {
              variableInstance: function() { return info.variable; }
            },
            controller: 'VariableInstanceUploadController',
            template: uploadTemplate
          })
          .result.then(function() {
            // updated the variable, need to get the new data
            // reject the promise anyway
            promise.reject();

            // but then update the filter to force re-get of variables
            variableInstanceData.set('filter', angular.copy($scope.filter));
          }, function() {
            // did not update the variable, reject the promise
            promise.reject();
          });

          return promise.promise;
        };

        $scope.deleteVariable = function(info) {
          var promise = $q.defer();

          if(info.original.taskId) {
            taskService.deleteVariable({
              id: info.original.taskId,
              varId: info.variable.name
            }, function(){
              promise.resolve(info.variable);
            });
          } else {
            executionService.deleteVariable({
              id: info.variable.executionId,
              varId: info.variable.name
            }, function() {
              promise.resolve(info.variable);
            });
          }

          return promise.promise;
        };

        $scope.editVariable = function(info) {
          var promise = $q.defer();

          $modal.open({
            template: inspectTemplate,

            controller: 'VariableInstanceInspectController',

            windowClass: 'cam-widget-variable-dialog',

            resolve: {
              variableInstance: function () { return info.variable; }
            }
          })
          .result.then(function() {
            // updated the variable, need to get the new data
            // reject the promise anyway
            promise.reject();

            // but then update the filter to force re-get of variables
            variableInstanceData.set('filter', angular.copy($scope.filter));
          }, function() {
            // did not update the variable, reject the promise
            promise.reject();
          });

          return promise.promise;
        };

        $scope.saveVariable = function (info) {
          var promise = $q.defer();
          var variable = info.variable;
          var modifiedVariable = {};

          var newValue = variable.value;//$scope.getCopy(variable.id).value;
          var newType = variable.type;//$scope.getCopy(variable.id).type;

          var newVariable = { value: newValue, type: newType };
          modifiedVariable[variable.name] = newVariable;

          var callback = function(error, data) {
            if(error) {
              Notifications.addError({
                status: 'Variable',
                message: 'The variable \'' + variable.name + '\' could not be changed successfully.',
                exclusive: true,
                duration: 5000
              });
              variableInstanceIdexceptionMessageMap[variable.id] = error.data;
              promise.reject();
            } else {
              Notifications.addMessage({
                status: 'Variable',
                message: 'The variable \'' + variable.name + '\' has been changed successfully.',
                duration: 5000
              });
              angular.extend(variable, newVariable);
              promise.resolve(info.variable);
            }
          };

          if(info.original.taskId) {
            taskService.modifyVariables({
              id: info.original.taskId,
              modifications: modifiedVariable
            }, callback);
          } else {
            executionService.modifyVariables({
              id: variable.executionId,
              modifications: modifiedVariable
            }, callback);
          }

          return promise.promise;
        };

        function updateView(newFilter, instanceIdToInstanceMap) {
          filter = $scope.filter = angular.copy(newFilter);

          delete filter.page;
          delete filter.activityIds;
          delete filter.scrollToBpmnElement;

          var page = pages.current,
              count = pages.size,
              firstResult = (page - 1) * count;

          var defaultParams = {
            processInstanceIdIn: [ processInstance.id ]
          };

          var pagingParams = {
            firstResult: firstResult,
            maxResults: count,
            deserializeValues: false
          };

          var params = angular.extend({}, filter, defaultParams);

          // fix missmatch -> activityInstanceIds -> activityInstanceIdIn
          params.activityInstanceIdIn = params.activityInstanceIds;
          delete params.activityInstanceIds;

          $scope.variables = null;
          $scope.loadingState = 'LOADING';

          // get the 'count' of variables
          $http.post(Uri.appUri('engine://engine/:engine/variable-instance/count'), params).success(function(data) {
            pages.total = data.count;
          });

          variableInstanceIdexceptionMessageMap = {};
          variableCopies = {};

          $http.post(Uri.appUri('engine://engine/:engine/variable-instance/'), params, { params: pagingParams }).success(function(data) {

            $scope.variables = data.map(function (item) {
              var instance = instanceIdToInstanceMap[item.activityInstanceId];
              item.instance = instance;
              variableCopies[item.id] = angular.copy(item);

              return {
                variable: {
                  id:           item.id,
                  name:         item.name,
                  type:         item.type,
                  value:        item.value,
                  valueInfo:    item.valueInfo,
                  executionId:  item.executionId
                },
                original: item,
                additions: {
                  scope: {
                    html:  '<a cam-select-activity-instance="\'' +
                                      instance.id +
                                      '\'" ng-href="#/process-instance/' +
                                      processInstance.id +
                                      '?detailsTab=variables-tab&activityInstanceIds=' +
                                      instance.id +
                                      '" title="' +
                                      instance.id +
                                      '">' +
                                        instance.name  +
                                      '',
                    scopeVariables: {
                      processData: $scope.processData
                    }
                  }
                }
              };
            });

            $scope.loadingState = data.length ? 'LOADED' : 'EMPTY';
          });
        }

        $scope.getCopy = function (variableId) {
          var copy = variableCopies[variableId];
          if (isNull(copy)) {
            copy.type = 'String';
          }
          return copy;
        };

        var isNull = $scope.isNull = function (variable) {
          return variable.type === 'null' || variable.type === 'Null';
        };

        $scope.getBinaryVariableDownloadLink = function (variable) {
          return Uri.appUri('engine://engine/:engine/variable-instance/'+variable.id+'/data');
        };

        $scope.openUploadDialog = function (variableInstance) {
          $modal.open({
            resolve: {
              variableInstance: function() { return variableInstance; }
            },
            controller: 'VariableInstanceUploadController',
            template: uploadTemplate
          });
        };

        $scope.openInspectDialog = function (variableInstance) {
          $modal.open({
            resolve: {
              variableInstance: function() { return variableInstance; }
            },
            controller: 'VariableInstanceInspectController',
            template: inspectTemplate
          }).result.then(function() {
            variableInstanceData.set('filter', angular.copy($scope.filter));
          });
        };
      }]);

      var Configuration = function PluginConfiguration(ViewsProvider) {

        ViewsProvider.registerDefaultView('cockpit.processInstance.runtime.tab', {
          id: 'variables-tab',
          label: 'Variables',
          template: instancesTemplate,
          controller: 'VariableInstancesController',
          priority: 20
        });
      };

      Configuration.$inject = ['ViewsProvider'];
      ngModule.config(Configuration);
  };
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var validate = require( './../lib/validate.js' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof validate, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an error if provided an `options` argument which is not an object', function test( t ) {
	var values;
	var err;
	var i;

	values = [
		'5',
		5,
		true,
		false,
		undefined,
		null,
		NaN,
		[],
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		err = validate( {}, values[ i ] );
		t.strictEqual( err instanceof TypeError, true, 'returns a type error when provided '+values[i] );
	}
	t.end();
});

// TODO: add tests

tape( 'the function returns `null` if all options are valid', function test( t ) {
	var options;
	var opts;
	var err;

	opts = {};
	options = {}; // TODO: add options

	err = validate( opts, options );
	t.strictEqual( err, null, 'returns null' );
	t.deepEqual( opts, options, 'sets options' );

	t.end();
});

tape( 'the function will ignore unrecognized options', function test( t ) {
	var options;
	var opts;
	var err;

	opts = {};
	options = {
		'beep': true,
		'boop': 'bop'
	};

	err = validate( opts, options );
	t.strictEqual( err, null, 'returns null' );
	t.deepEqual( opts, {}, 'ignores unrecognized options' );

	t.end();
});
<commit_msg>Update test value<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var validate = require( './../lib/validate.js' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof validate, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an error if provided an `options` argument which is not an object', function test( t ) {
	var values;
	var err;
	var i;

	values = [
		'5',
		5,
		true,
		false,
		void 0,
		null,
		NaN,
		[],
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		err = validate( {}, values[ i ] );
		t.strictEqual( err instanceof TypeError, true, 'returns a type error when provided '+values[i] );
	}
	t.end();
});

// TODO: add tests

tape( 'the function returns `null` if all options are valid', function test( t ) {
	var options;
	var opts;
	var err;

	opts = {};
	options = {}; // TODO: add options

	err = validate( opts, options );
	t.strictEqual( err, null, 'returns null' );
	t.deepEqual( opts, options, 'sets options' );

	t.end();
});

tape( 'the function will ignore unrecognized options', function test( t ) {
	var options;
	var opts;
	var err;

	opts = {};
	options = {
		'beep': true,
		'boop': 'bop'
	};

	err = validate( opts, options );
	t.strictEqual( err, null, 'returns null' );
	t.deepEqual( opts, {}, 'ignores unrecognized options' );

	t.end();
});
<|endoftext|>