<commit_before>(function($) {
  "use strict";
  /**
   * @constructor
   * Create a GitHub event object.
   * @param {String} id Event ID.
   * @param {String} url Event url.
   * @param {String} sha Event SHA value or branch name.
   * @param {String} date Event date.
   * @param {String} repo Event repo.
   * @param {String} event Event type.
   * @param {String} msg Event message.
   */
  function GHEvent(id, url, sha, date, repo, repoUrl, event, msg) {
    this.id    = id;
    this.msg   = msg;
    this.url   = url;
    this.sha   = sha;
    this.date  = date;
    this.repo  = repo;
    this.event = event;
    this.repoUrl = repoUrl;
    this.selector = "#gh-" + id;
    this.container = "

";
  }

  /**
   * @constant
   * @type {Number}
   * The number of characters the commit message should be limited to.
   * This is a hard limit and may increase cut off part of a word.
   */
  GHEvent.prototype.charLimit = 80;

  /**
   * Summarize a commit messgae.
   * @returns {Boolean} true.
   */
  GHEvent.prototype.summarize = function() {
    if (this.msg.length > this.charLimit) {
      this.msg = this.msg.substr(0, this.charLimit) + "...";
    }

    // Preserve any new lines
    this.msg = this.msg.replace(/\n/, "
");
    return true;
  };

  var EventUtils = {
    /**
     * Convert an API url into a web interface one.
     * @param {String} url
     * @returns {Sring}
     */
    makeURL: function(url) {
      return url.replace(/(?:api\.|repos\/)/gi, "").replace(/commits/gi, "commit");
    },

    /**
     * Capitalize the first letter of the given text.
     * @param {String} text
     * @returns {String}
     */
    capitalFirst: function(text) {
      return text.charAt(0).toUpperCase() + text.substr(1);
    },

    /**
     * Construct a proper event name.
     * @param {String}  name The event name.
     * @param {Boolean} [activeTense=false] If true, the event name
     *     will be converted to an active tense verb.
     * @returns {String} The corrected name.
     */
    makeEventName: function(name, activeTense) {
      // Default to leaving verb tense as-is
      if (activeTense === undefined) {
        activeTense = false;
      }

      // Capitalize the first letter
      name = this.capitalFirst(name);

      // Convert verb to active tense
      if (activeTense) {
        var changeTense = {
          "Closed": "Close",
          "Opened": "Open",
          "Published": "Publish"
        };

        // If a replacement is defined, use it
        if (changeTense[name] !== undefined) {
          name = changeTense[name];
        }
      }
      return name;
    }
  };

  /**
   * Create a date stamp in the format "DD Month, YYYY".
   * @param {String} rawDate GitHub timestamp.
   * @returns {String}.
   */
  function _createDate(rawDate) {
    var months = {"01": "January", "02": "February", "03": "March", "04": "April",
                  "05": "May", "06": "June", "07": "July", "08": "August", "09": "September",
                  "10": "October", "11": "November", "12": "December"
                 };

    var dateParts  = rawDate.split("T")[0].split("-"),
        dateFormat = "{0} {1} {2}".format(dateParts[2], dateParts[1], dateParts[0]).split(" ");
    dateFormat[1]  = months[dateFormat[1]] + ",";
    return dateFormat.join(" ");
  }

  var events = [];

  /**
   * Process the fetched GitHub event feed.
   * @param {Object} data [[Description]].
   */
  function loadEvents(data) {
    for (var i = 0, limit = 7; i < limit; i += 1) {
      var curEvent  = data[i],
          id        = curEvent.id,
          url       = "#",
          sha       = "",
          repo      = curEvent.repo.name,
          date      = _createDate(curEvent.created_at).substring(0, curEvent.created_at.length - 1),
          repoUrl   = EventUtils.makeURL(curEvent.repo.url),
          message   = "No commit message available.",
          eventName = curEvent.type.replace(/event/i, "");

      // Do not report certain events
      if (/comment|fork|watch/gi.test(eventName)) {
        limit += 1;
        continue;
      }

      switch(eventName) {
          // Create event
          case "Create":
          // Filter out create tag events
          var _eventType = curEvent.payload.ref_type;
            if (/tag/.test(_eventType))  {
              continue;
            }

            sha = curEvent.payload.ref;
            message = "Create " + curEvent.payload.ref_type;

            // New branch
            if (/branch/.test(_eventType)) {
              url = EventUtils.makeURL(curEvent.repo.url) + "/tree/" + curEvent.payload.ref;
            }

            // TODO New repo
            break;

          // New release
          case "Release":
            eventName = EventUtils.makeEventName(curEvent.payload.action, true);
            sha = curEvent.payload.release.tag_name;
            url = curEvent.payload.release.html_url;
            message = "\"" + curEvent.payload.release.name + "\"";
            break;

          // Open/close issue
          case "Issues":
            eventName = EventUtils.makeEventName(curEvent.payload.action, true);
            sha = "#" + curEvent.payload.issue.number;
            url = curEvent.payload.issue.html_url;
            message = EventUtils.makeEventName(curEvent.payload.action) + " \"" + curEvent.payload.issue.title + "\"";
            break;

          // Delete event
          case "Delete":
            eventName = "Delete";
            sha = curEvent.payload.ref;
            url = EventUtils.makeURL(curEvent.repo.url);
            message = "Delete " + curEvent.payload.ref_type;
            break;

          // Wiki edit
          case "Gollum":
            eventName = "Wiki Edit";
            sha = curEvent.payload.pages[0].sha.substr(0, 10);
            url = curEvent.payload.pages[0].html_url;

            message = EventUtils.capitalFirst(curEvent.payload.pages[0].action);
            message += " \"" + curEvent.payload.pages[0].title + "\"";
            break;

          // Pull request
          case "PullRequest":
            eventName = "Pull Request";
            sha = "#" + curEvent.payload.number;
            url = curEvent.payload.pull_request.html_url;
            message = EventUtils.capitalFirst(curEvent.payload.pull_request.state);
            message += " \"" + curEvent.payload.pull_request.title + "\"";
            break;

          // Push event
          default:
            url = EventUtils.makeURL(curEvent.payload.commits[0].url);
            sha = curEvent.payload.commits[0].sha.substr(0, 10);
            message = curEvent.payload.commits[0].message;
            break;
      }

      // Create a new event object
      var ghEvent = new GHEvent(id, url, sha, date, repo, repoUrl, eventName, message);
      ghEvent.summarize();
      events.push(ghEvent);
//      console.log(ghEvent);
    }
  }

  /**
   * Display the feed results.
   * @returns {Boolean} Always returns true.
   */
  function displayEvents() {
    var $container = $(".gh-events");
    events.forEach(function(value) {
      $container.append(value.container);
      $(value.selector).append("
");
      $(value.selector).append("
");

      $(value.selector + " .gh-title").html(value.event + "  @ " + value.repo + " on " + value.date);
      $(value.selector + " .gh-url").html(value.sha);
      $(value.selector + " .gh-url").attr("href", value.url);
      $(value.selector + " dd").html("" + value.msg + "");
    });
    return true;
  }

  // Poll the GitHub API
  $.ajax({
    dataType: "json",
    url: "https://api.github.com/users/le717/events/public",
    success: [loadEvents, displayEvents],
    error: function() {
      var msg = "Unfortunately that information cannot be loaded right now";
      $(".gh-events").html(msg);
      return false;
    }
  });
})(jQuery);
<commit_msg>Detect and create links to issues in commit message<commit_after>(function($) {
  "use strict";
  /**
   * @constructor
   * Create a GitHub event object.
   * @param {String} id Event ID.
   * @param {String} url Event url.
   * @param {String} sha Event SHA value or branch name.
   * @param {String} date Event date.
   * @param {String} repo Event repo.
   * @param {String} event Event type.
   * @param {String} msg Event message.
   */
  function GHEvent(id, url, sha, date, repo, repoUrl, event, msg) {
    this.id    = id;
    this.msg   = msg;
    this.url   = url;
    this.sha   = sha;
    this.date  = date;
    this.repo  = repo;
    this.event = event;
    this.repoUrl = repoUrl;
    this.selector = "#gh-" + id;
    this.container = "

";
  }

  /**
   * @constant
   * @type {Number}
   * The number of characters the commit message should be limited to.
   * This is a hard limit and may increase cut off part of a word.
   */
  GHEvent.prototype.charLimit = 80;

  /**
   * Summarize a commit message.
   * @returns {Boolean} true.
   */
  GHEvent.prototype.summarize = function() {
    if (this.msg.length > this.charLimit) {
      this.msg = this.msg.substr(0, this.charLimit) + "...";
    }

    // Preserve any new lines
    this.msg = this.msg.replace(/\n/, "
");

    // Check for any issue/PR references and generate links
    var issueRef = this.msg.match( /(?:gh-|#)(\d+)/);
    if (issueRef) {
      var issueLink = "" + issueRef[0] + "";
      this.msg = this.msg.replace(issueRef[0], issueLink);
    }
    return true;
  };

  var EventUtils = {
    /**
     * Convert an API url into a web interface one.
     * @param {String} url
     * @returns {Sring}
     */
    makeURL: function(url) {
      return url.replace(/(?:api\.|repos\/)/gi, "").replace(/commits/gi, "commit");
    },

    /**
     * Capitalize the first letter of the given text.
     * @param {String} text
     * @returns {String}
     */
    capitalFirst: function(text) {
      return text.charAt(0).toUpperCase() + text.substr(1);
    },

    /**
     * Construct a proper event name.
     * @param {String}  name The event name.
     * @param {Boolean} [activeTense=false] If true, the event name
     *     will be converted to an active tense verb.
     * @returns {String} The corrected name.
     */
    makeEventName: function(name, activeTense) {
      // Default to leaving verb tense as-is
      if (activeTense === undefined) {
        activeTense = false;
      }

      // Capitalize the first letter
      name = this.capitalFirst(name);

      // Convert verb to active tense
      if (activeTense) {
        var changeTense = {
          "Closed": "Close",
          "Opened": "Open",
          "Published": "Publish"
        };

        // If a replacement is defined, use it
        if (changeTense[name] !== undefined) {
          name = changeTense[name];
        }
      }
      return name;
    }
  };

  /**
   * Create a date stamp in the format "DD Month, YYYY".
   * @param {String} rawDate GitHub timestamp.
   * @returns {String}.
   */
  function _createDate(rawDate) {
    var months = {"01": "January", "02": "February", "03": "March", "04": "April",
                  "05": "May", "06": "June", "07": "July", "08": "August", "09": "September",
                  "10": "October", "11": "November", "12": "December"
                 };

    var dateParts  = rawDate.split("T")[0].split("-"),
        dateFormat = "{0} {1} {2}".format(dateParts[2], dateParts[1], dateParts[0]).split(" ");
    dateFormat[1]  = months[dateFormat[1]] + ",";
    return dateFormat.join(" ");
  }

  var events = [];

  /**
   * Process the fetched GitHub event feed.
   * @param {Object} data [[Description]].
   */
  function loadEvents(data) {
    for (var i = 0, limit = 7; i < limit; i += 1) {
      var curEvent  = data[i],
          id        = curEvent.id,
          url       = "#",
          sha       = "",
          repo      = curEvent.repo.name,
          date      = _createDate(curEvent.created_at).substring(0, curEvent.created_at.length - 1),
          repoUrl   = EventUtils.makeURL(curEvent.repo.url),
          message   = "No commit message available.",
          eventName = curEvent.type.replace(/event/i, "");

      // Do not report certain events
      if (/comment|fork|watch/gi.test(eventName)) {
        limit += 1;
        continue;
      }

      switch(eventName) {
          // Create event
          case "Create":
          // Filter out create tag events
          var _eventType = curEvent.payload.ref_type;
            if (/tag/.test(_eventType))  {
              continue;
            }

            sha = curEvent.payload.ref;
            message = "Create " + curEvent.payload.ref_type;

            // New branch
            if (/branch/.test(_eventType)) {
              url = EventUtils.makeURL(curEvent.repo.url) + "/tree/" + curEvent.payload.ref;
            }

            // TODO New repo
            break;

          // New release
          case "Release":
            eventName = EventUtils.makeEventName(curEvent.payload.action, true);
            sha = curEvent.payload.release.tag_name;
            url = curEvent.payload.release.html_url;
            message = "\"" + curEvent.payload.release.name + "\"";
            break;

          // Open/close issue
          case "Issues":
            eventName = EventUtils.makeEventName(curEvent.payload.action, true);
            sha = "#" + curEvent.payload.issue.number;
            url = curEvent.payload.issue.html_url;
            message = EventUtils.makeEventName(curEvent.payload.action) +
                      " \"" + curEvent.payload.issue.title + "\"";
            break;

          // Delete event
          case "Delete":
            eventName = "Delete";
            sha = curEvent.payload.ref;
            url = EventUtils.makeURL(curEvent.repo.url);
            message = "Delete " + curEvent.payload.ref_type;
            break;

          // Wiki edit
          case "Gollum":
            eventName = "Wiki Edit";
            sha = curEvent.payload.pages[0].sha.substr(0, 10);
            url = curEvent.payload.pages[0].html_url;

            message = EventUtils.capitalFirst(curEvent.payload.pages[0].action);
            message += " \"" + curEvent.payload.pages[0].title + "\"";
            break;

          // Pull request
          case "PullRequest":
            eventName = "Pull Request";
            sha = "#" + curEvent.payload.number;
            url = curEvent.payload.pull_request.html_url;
            message = EventUtils.capitalFirst(curEvent.payload.pull_request.state);
            message += " \"" + curEvent.payload.pull_request.title + "\"";
            break;

          // Push event
          default:
            url = EventUtils.makeURL(curEvent.payload.commits[0].url);
            sha = curEvent.payload.commits[0].sha.substr(0, 10);
            message = curEvent.payload.commits[0].message;
            break;
      }

      // Create a new event object
      var ghEvent = new GHEvent(id, url, sha, date, repo, repoUrl, eventName, message);
      ghEvent.summarize();
      events.push(ghEvent);
    }
  }

  /**
   * Display the feed results.
   * @returns {Boolean} Always returns true.
   */
  function displayEvents() {
    var $container = $(".gh-events");
    events.forEach(function(event) {
      $container.append(event.container);
      $(event.selector).append("
");
      $(event.selector).append("
");

      $(event.selector + " .gh-title").html(event.event +
                                            "  @ " +
                                            event.repo + " on " + event.date);
      $(event.selector + " .gh-url").html(event.sha);
      $(event.selector + " .gh-url").attr("href", event.url);
      $(event.selector + " dd").html("" + event.msg + "");
    });
    return true;
  }

  // Poll the GitHub API
  $.ajax({
    dataType: "json",
    url: "https://api.github.com/users/le717/events/public",
    success: [loadEvents, displayEvents],
    error: function() {
      var msg = "Unfortunately that information cannot be loaded right now";
      $(".gh-events").html(msg);
      return false;
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>/**
 * Knob - jQuery Plugin
 * Backward compatible, touchable dial
 *
 * Version: 1.1.0 (10/05/2012)
 * Requires: jQuery v1.7+
 *
 * Copyright (c) 2011 Anthony Terrien
 * Under MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to vor, eskimoblood, spiffistan
 */
$(function() {

    $.fn.knob = $.fn.dial = function( gopt ) {

        return this.each(

                    function() {

                        var $this = $(this);

                        if( $this.data('dialed') ) return $this;
                        $this.data('dialed',true);

                        var opt = $.extend(
                                        {
                                            'min' : $this.data('min') || 0
                                            ,'max' : $this.data('max') || 100
                                            ,'cursor' : $this.data('cursor')
                                            ,'thickness' : $this.data('thickness') || .3
                                            ,'width' : $this.data('width') || 200
                                            ,'displayInput' : $this.data('displayinput')==null || $this.data('displayinput')
                                            ,'fgColor' : $this.data('fgcolor') || '#87CEEB' //#222222'
                                            ,'bgColor' : $this.data('bgcolor') || '#EEEEEE'
                                            ,'tickColor' : $this.data('tickColor') || $this.data('fgcolor') || '#DDDDDD'
                                            ,'ticks' : $this.data('ticks') || 0
                                            ,'tickLength' : $this.data('tickLength') || 0
                                            ,'tickWidth' : $this.data('tickWidth') || 0.02
                                            ,'tickColorizeValues' : $this.data('tickColorizeValues') || true
                                            ,'readOnly' : $this.data('readonly')
                                            ,'skin' : $this.data('skin') || 'default'
                                            ,'draw' :
                                                    /**
                                                     * @param int a angle
                                                     * @param int v current value
                                                     * @param array opt plugin options
                                                     * @param context ctx Canvas context 2d
                                                     */
                                                    function( a, v, opt, ctx ) {
                                                            var sa = 1.5*Math.PI        // Start angle
                                                                ,ea = sa+a              // End angle
                                                                ,r = opt.width/2        // Radius
                                                                ,lw = r*opt.thickness;  // Line width

                                                            ctx.clearRect(0, 0, opt.width, opt.width);
                                                            ctx.lineWidth = lw;

                                                            opt.cursor
                                                                && ( sa = ea-0.3 )
                                                                && ( ea = ea+0.3 );

                                                            var ticks = opt.ticks;
                                                            var tl = opt.tickLength;
                                                            var tw = opt.tickWidth;

                                                            for(tick = 0; tick < ticks; tick++) {

                                                                ctx.beginPath();

                                                                if(a > (((2 * Math.PI) / ticks) * tick) && opt.tickColorizeValues) {
                                                                    ctx.strokeStyle = opt.fgColor;
                                                                }else{
                                                                    ctx.strokeStyle = opt.tickColor;
                                                                }

                                                                var tick_sa = (((2 * Math.PI) / ticks) * tick) - (0.5 * Math.PI);
                                                                ctx.arc( r, r, r-lw-tl, tick_sa, tick_sa + tw , false);
                                                                ctx.stroke();
                                                            }

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.fgColor;
                                                            ctx.arc( r, r, r-lw, sa, ea, false);
                                                            ctx.stroke();

                                                            switch(opt.skin){

                                                                case 'default' :
                                                                    ctx.beginPath();
                                                                    ctx.strokeStyle = opt.bgColor;
                                                                    ctx.arc(
                                                                                r, r, r-lw ,sa
                                                                                ,(v==opt.min && !opt.cursor)
                                                                                ? sa+0.0001
                                                                                : ea
                                                                                , true
                                                                            );
                                                                    ctx.stroke();
                                                                    break;

                                                                case 'tron' :
                                                                    ctx.lineWidth = 2;
                                                                    ctx.beginPath();
                                                                    ctx.strokeStyle = opt.fgColor;
                                                                    ctx.arc( r, r, r-lw+1+lw*2/3, 0, 2*Math.PI, false);
                                                                    ctx.stroke();
                                                                    break;
                                                            }
                                                        }
                                            ,'change' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                            ,'release' :
                                                    /**
                                                     * @param int v Current value
                                                     * @param jQuery ipt Input
                                                     */
                                                    function(v,ipt) {}
                                        }
                                        ,gopt
                                    );

                        var c = $('<canvas width="'+opt.width+'" height="'+opt.width+'"></canvas>')
                            ,wd = $('

')
                            ,k;

                        $this.wrap( wd ).before( c );

                        opt.displayInput
                        && $this.css(
                                    {
                                    'width' : opt.width/2+'px'
                                    ,'position' : 'absolute'
                                    ,'margin-top' : (opt.width*5/13)+'px'
                                    ,'margin-left' : '-'+3*opt.width/4+'px'
                                    ,'font-size' : opt.width/5+'px'
                                    ,'border' : 'none'
                                    ,'background' : 'none'
                                    ,'font-family' : 'Arial'
                                    ,'font-weight' : 'bold'
                                    ,'text-align' : 'center'
                                    ,'color' : opt.fgColor
                                    ,'padding' : '0px'
                                    ,'-webkit-appearance': 'none'
                                    }
                                )
                        || $this.css(
                                    {
                                    'width' : '0px'
                                    , 'visibility' : 'hidden'
                                    }
                                );

                        k = new Dial( c, opt );
                        k.onRelease = function(v) {
                                                    opt.release(v,$this);
                                                };
                        k.val( parseInt($this.val()) || 0 );
                        k.onChange = function(v) {
                                                    $this.val(v);
                                                    opt.change(v);
                                                 };

                        // bind change on input
                        $this.bind(
                                'change'
                                ,function( e ) {
                                    k.val( $this.val() );
                                }
                            );

                        if( !opt.readOnly ){

                            // canvas
                            c.bind(
                                            "mousedown touchstart"
                                            ,function( e ) {
                                                e.preventDefault();
                                                k.startDrag( e );
                                                //$this.focus();
                                            }
                                  )
                             .bind(
                                            "mousewheel DOMMouseScroll"
                                            ,mw = function(e) {
                                                e.preventDefault();
                                                var ori = e.originalEvent
                                                    ,deltaX = ori.detail || ori.wheelDeltaX
                                                    ,deltaY = ori.detail || ori.wheelDeltaY
                                                    ,val = parseInt($this.val()) + (deltaX>0 || deltaY>0 ? 1 : deltaX<0 || deltaY<0 ? -1 : 0);
                                                (val>opt.max && (val=opt.max)) || (val<opt.min && (val=opt.min));
                                                k.val(val);
                                            }
                                );

                            // input
                            var kval,val,to,tocb,m=1,kv={37:-1,38:1,39:1,40:-1}
                            $this.bind(
                                            "keydown"
                                            ,function(e) {
                                                var kc = e.keyCode;
                                                kval = parseInt(String.fromCharCode(kc));

                                                if (isNaN(kval)) {

                                                    kc!=13      // enter
                                                    && kc!=8    // bs
                                                    && kc!=189  // -
                                                    && e.preventDefault();

                                                    // arrows
                                                    if($.inArray(kc,[37,38,39,40])>-1){
                                                        val=parseInt($this.val())+kv[kc]*m;

                                                        //if(to){ // long time keydown = limited min or max
                                                            (val<opt.min && kv[kc]<0 && (val=opt.min))
                                                            || (val>opt.max && kv[kc]>0 && (val=opt.max));
                                                        //}else{
                                                        //    // allow infinite loop
                                                        //    (val<opt.min && (val=opt.max))
                                                        //    || (val>opt.max && (val=opt.min));
                                                        //}
                                                        k.val(val);

                                                        // long time keydown speed-up
                                                        tocb = function(){m<20 && m++;};
                                                        to = setTimeout(tocb,50);

                                                        e.preventDefault();
                                                    }
                                                }
                                            }
                                        )
                                  .bind(
                                            "keyup"
                                            ,function(e) {
                                                if (isNaN(kval)) {
                                                    if(to){
                                                        clearTimeout(to);
                                                        to=null;
                                                        m=1;
                                                        k.onRelease($this.val(),$this);
                                                    }else{
                                                        // enter
                                                        if(e.keyCode==13) {
                                                            k.onRelease($this.val(),$this);
                                                        }
                                                    }
                                                }else{
                                                    // kval postcond
                                                    ($this.val()>opt.max && $this.val(opt.max))
                                                    || ($this.val()<opt.min && $this.val(opt.min));
                                                }

                                            }
                                        )
                                   .bind(
                                            "mousewheel DOMMouseScroll"
                                            ,mw
                                            // @todo Must call "onRelease"
                                        );
                        }else{
                            $this.attr('readonly','readonly');
                        }
                    }
                ).parent();
    }

    Dial = function( c, opt ) {

        var v = null
            ,ctx = c[0].getContext("2d")
            ,a = Math.PI*0.0001
            ,PI2 = 2*Math.PI
            ,mx ,my ,x ,y
            ,_self = this;

        this.onChange = function() {}
        this.onRelease = function() {}

        this.val = function(_v) {
            if(null!=_v){
                if( v==_v ) return;
                v=_v;
                this.onChange(_v);
                a = (_v-opt.min)*PI2/(opt.max-opt.min);
                opt.draw( a, _v, opt, ctx );
            }else{
                var b = a = Math.atan2( mx-x, -(my-y-opt.width/2) );
                (a<0) && (b=a+PI2);
                 _v = Math.round( b*(opt.max-opt.min)/PI2 ) + opt.min;
                return ( _v>opt.max ) ? opt.max : _v;
            }
        }

        this.capture = function(e) {
            switch( e.type ){
                case 'mousemove' :
                case 'mousedown' :
                    mx = e.pageX;
                    my = e.pageY;
                    break;
                case 'touchmove' :
                case 'touchstart' :
                    mx = e.originalEvent.touches[0].pageX;
                    my = e.originalEvent.touches[0].pageY;
                    break;
            }
            this.val( this.val() );
        }

        this.startDrag = function(e) {

            var p = c.position();
            x = p.left+(opt.width/2);
            y = p.top;

            this.capture(e);

            $(document).bind(
                            "mousemove.dial touchmove.dial"
                            ,function(e) {
                                _self.capture(e);
                            }
                        )
                        .bind(
                            "mouseup.dial touchend.dial"
                            ,function() {
                                $(document).unbind('mousemove.dial touchmove.dial mouseup.dial touchend.dial');
                                _self.onRelease(v);
                            }
                        );
        }
    }
});<commit_msg>code factorization<commit_after>/**
 * Knob - jQuery Plugin
 * Downward compatible, touchable dial
 *
 * Version: 1.1.0 (10/05/2012)
 * Requires: jQuery v1.7+
 *
 * Copyright (c) 2011 Anthony Terrien
 * Under MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to vor, eskimoblood, spiffistan
 */
$(function() {

    $.fn.knob = $.fn.dial = function( gopt ) {

        return this.each(

                    function() {

                        var $this = $(this);

                        if( $this.data('dialed') ) return $this;
                        $this.data('dialed',true);

                        var opt = $.extend(
                                        {
                                            'min' : $this.data('min') || 0
                                            ,'max' : $this.data('max') || 100
                                            ,'cursor' : $this.data('cursor')
                                            ,'thickness' : $this.data('thickness') || .3
                                            ,'width' : $this.data('width') || 200
                                            ,'displayInput' : $this.data('displayinput')==null || $this.data('displayinput')
                                            ,'fgColor' : $this.data('fgcolor') || '#87CEEB' //#222222'
                                            ,'bgColor' : $this.data('bgcolor') || '#EEEEEE'
                                            ,'tickColor' : $this.data('tickColor') || $this.data('fgcolor') || '#DDDDDD'
                                            ,'ticks' : $this.data('ticks') || 0
                                            ,'tickLength' : $this.data('tickLength') || 0
                                            ,'tickWidth' : $this.data('tickWidth') || 0.02
                                            ,'tickColorizeValues' : $this.data('tickColorizeValues') || true
                                            ,'readOnly' : $this.data('readonly')
                                            ,'skin' : $this.data('skin') || 'default'
                                            ,'draw' :
                                                    /**
                                                     * @param int a angle
                                                     * @param int v current value
                                                     * @param array opt plugin options
                                                     * @param context ctx Canvas context 2d
                                                     */
                                                    function( a, v, opt, ctx ) {
                                                            var sa = 1.5*Math.PI        // Start angle
                                                                ,ea = sa+a              // End angle
                                                                ,r = opt.width/2        // Radius
                                                                ,lw = r*opt.thickness;  // Line width

                                                            ctx.clearRect(0, 0, opt.width, opt.width);
                                                            ctx.lineWidth = lw;

                                                            opt.cursor
                                                                && ( sa = ea-0.3 )
                                                                && ( ea = ea+0.3 );

                                                            var ticks = opt.ticks;
                                                            var tl = opt.tickLength;
                                                            var tw = opt.tickWidth;

                                                            for(tick = 0; tick < ticks; tick++) {

                                                                ctx.beginPath();

                                                                if(a > (((2 * Math.PI) / ticks) * tick) && opt.tickColorizeValues) {
                                                                    ctx.strokeStyle = opt.fgColor;
                                                                }else{
                                                                    ctx.strokeStyle = opt.tickColor;
                                                                }

                                                                var tick_sa = (((2 * Math.PI) / ticks) * tick) - (0.5 * Math.PI);
                                                                ctx.arc( r, r, r-lw-tl, tick_sa, tick_sa + tw , false);
                                                                ctx.stroke();
                                                            }

                                                            ctx.beginPath();
                                                            ctx.strokeStyle = opt.fgColor;
                                                            ctx.arc( r, r, r-lw, sa, ea, false);
                                                            ctx.stroke();

                                                            switch(opt.skin){

                                                                case 'default' :
                                                                    ctx.beginPath();
                                                                    ctx.strokeStyle = opt.bgColor;
                                                                    ctx.arc(
                                                                                r, r, r-lw ,sa
                                                                                ,(v==opt.min && !opt.cursor)
                                                                                ? sa+0.0001
                                                                                : ea
                                                                                , true
                                                                            );
                                                                    ctx.stroke();
                                                                    break;

                                                                case 'tron' :
                                                                    ctx.lineWidth = 2;
                                                                    ctx.beginPath();
                                                                    ctx.strokeStyle = opt.fgColor;
                                                                    ctx.arc( r, r, r-lw+1+lw*2/3, 0, 2*Math.PI, false);
                                                                    ctx.stroke();
                                                                    break;
                                                            }
                                                        }
                                            ,'change' :
                                                    /**
                                                     * @param int v Current value
                                                     */
                                                    function(v) {}
                                            ,'release' :
                                                    /**
                                                     * @param int v Current value
                                                     * @param jQuery ipt Input
                                                     */
                                                    function(v,ipt) {}
                                        }
                                        ,gopt
                                    );

                        var c = $('<canvas width="'+opt.width+'" height="'+opt.width+'"></canvas>')
                            ,wd = $('

')
                            ,k;

                        $this.wrap( wd ).before( c );

                        opt.displayInput
                        && $this.css(
                                    {
                                    'width' : opt.width/2+'px'
                                    ,'position' : 'absolute'
                                    ,'margin-top' : (opt.width*5/13)+'px'
                                    ,'margin-left' : '-'+3*opt.width/4+'px'
                                    ,'font-size' : opt.width/5+'px'
                                    ,'border' : 'none'
                                    ,'background' : 'none'
                                    ,'font-family' : 'Arial'
                                    ,'font-weight' : 'bold'
                                    ,'text-align' : 'center'
                                    ,'color' : opt.fgColor
                                    ,'padding' : '0px'
                                    ,'-webkit-appearance': 'none'
                                    }
                                )
                        || $this.css(
                                    {
                                    'width' : '0px'
                                    , 'visibility' : 'hidden'
                                    }
                                );

                        k = new Dial( c, opt );
                        k.onRelease = function(v) {
                                                    opt.release(v,$this);
                                                };
                        k.val( parseInt($this.val()) || 0 );
                        k.onChange = function(v) {
                                                    $this.val(v);
                                                    opt.change(v);
                                                 };

                        // bind change on input
                        $this.bind(
                                'change'
                                ,function( e ) {
                                    k.val( $this.val() );
                                }
                            );

                        if( !opt.readOnly ){

                            // canvas
                            c.bind(
                                            "mousedown touchstart"
                                            ,function( e ) {
                                                e.preventDefault();
                                                k.startDrag( e );
                                                //$this.focus();
                                            }
                                  )
                             .bind(
                                            "mousewheel DOMMouseScroll"
                                            ,mw = function(e) {
                                                e.preventDefault();
                                                var ori = e.originalEvent
                                                    ,deltaX = ori.detail || ori.wheelDeltaX
                                                    ,deltaY = ori.detail || ori.wheelDeltaY
                                                    ,val = parseInt($this.val()) + (deltaX>0 || deltaY>0 ? 1 : deltaX<0 || deltaY<0 ? -1 : 0);
                                                k.val(val);
                                            }
                                );

                            // input
                            var kval,val,to,tocb,m=1,kv={37:-1,38:1,39:1,40:-1}
                            $this.bind(
                                            "keydown"
                                            ,function(e) {
                                                var kc = e.keyCode;
                                                kval = parseInt(String.fromCharCode(kc));

                                                if (isNaN(kval)) {

                                                    kc!=13      // enter
                                                    && kc!=8    // bs
                                                    && kc!=189  // -
                                                    && e.preventDefault();

                                                    // arrows
                                                    if($.inArray(kc,[37,38,39,40])>-1){
                                                        k.val(parseInt($this.val())+kv[kc]*m);

                                                        // long time keydown speed-up
                                                        tocb = function(){m<20 && m++;};
                                                        to = setTimeout(tocb,50);

                                                        e.preventDefault();
                                                    }
                                                }
                                            }
                                        )
                                  .bind(
                                            "keyup"
                                            ,function(e) {
                                                if (isNaN(kval)) {
                                                    if(to){
                                                        clearTimeout(to);
                                                        to=null;
                                                        m=1;
                                                        k.onRelease($this.val(),$this);
                                                    }else{
                                                        // enter
                                                        if(e.keyCode==13) {
                                                            k.onRelease($this.val(),$this);
                                                        }
                                                    }
                                                }else{
                                                    // kval postcond
                                                    ($this.val()>opt.max && $this.val(opt.max))
                                                    || ($this.val()<opt.min && $this.val(opt.min));
                                                }

                                            }
                                        )
                                   .bind(
                                            "mousewheel DOMMouseScroll"
                                            ,mw
                                            // @todo Must call "onRelease"
                                        );
                        }else{
                            $this.attr('readonly','readonly');
                        }
                    }
                ).parent();
    }

    Dial = function( c, opt ) {

        var v = null
            ,ctx = c[0].getContext("2d")
            ,a = Math.PI*0.0001
            ,PI2 = 2*Math.PI
            ,mx ,my ,x ,y
            ,_self = this;

        this.onChange = function() {}
        this.onRelease = function() {}

        this.val = function(_v) {
            if(null!=_v){
                _v=Math.max(Math.min(_v, opt.max), opt.min); // limiter
                if( v==_v ) return;
                v=_v;
                this.onChange(_v);
                a = (_v-opt.min)*PI2/(opt.max-opt.min);
                opt.draw( a, _v, opt, ctx );
            }else{
                var b = a = Math.atan2( mx-x, -(my-y-opt.width/2) );
                (a<0) && (b=a+PI2);
                 _v = Math.round( b*(opt.max-opt.min)/PI2 ) + opt.min;
                return ( _v>opt.max ) ? opt.max : _v;
            }
        }

        this.capture = function(e) {
            switch( e.type ){
                case 'mousemove' :
                case 'mousedown' :
                    mx = e.pageX;
                    my = e.pageY;
                    break;
                case 'touchmove' :
                case 'touchstart' :
                    mx = e.originalEvent.touches[0].pageX;
                    my = e.originalEvent.touches[0].pageY;
                    break;
            }
            this.val( this.val() );
        }

        this.startDrag = function(e) {

            var p = c.position();
            x = p.left+(opt.width/2);
            y = p.top;

            this.capture(e);

            $(document).bind(
                            "mousemove.dial touchmove.dial"
                            ,function(e) {
                                _self.capture(e);
                            }
                        )
                        .bind(
                            "mouseup.dial touchend.dial"
                            ,function() {
                                $(document).unbind('mousemove.dial touchmove.dial mouseup.dial touchend.dial');
                                _self.onRelease(v);
                            }
                        );
        }
    }
});<|endoftext|>


<commit_before>define([ "AurebeshRune", "EnglishAurebeshTranscriber" ], function(AurebeshRune, EnglishAurebeshTranscriber)
{
    "use strict";
    var AurebeshRuneFormat =
    {
        format: function(runes)
        {
            var answer = "";

            var properties = AurebeshRune.properties;

            for (var i = 0; i < runes.length; i++)
            {
                var rune = runes[i];

                if (!rune)
                {
                    LOGGER.error("Missing rune at position " + i + "; runes.length = " + runes.length + " runes = " +
                            runes);
                }

                answer += properties[rune].name;

                if (i < runes.length - 1)
                {
                    answer += "-";
                }
            }

            return answer;
        },

        parse: function(string)
        {
            var answer = [];

            var names = string.split("-");

            for (var i = 0; i < names.length; i++)
            {
                var name = names[i];
                answer[answer.length] = AurebeshRune[name];
            }

            return answer;
        },

        getFontLetters: function(runes)
        {
            var answer = "";

            var transcriber = new EnglishAurebeshTranscriber();
            var properties = AurebeshRune.properties;

            for (var i = 0; i < runes.length; i++)
            {
                var rune = runes[i];

                var letter = transcriber.determineFontLetter(rune);

                if (Array.isArray(letter))
                {
                    for (var j = 0; j < letter.length; j++)
                    {
                        answer += letter[j];
                    }
                }
                else
                {
                    answer += letter;
                }
            }

            return answer;
        }
    }

    return AurebeshRuneFormat;
});
<commit_msg>Removed a circular dependency.<commit_after>define([ "AurebeshRune" ], function(AurebeshRune)
{
    "use strict";
    var AurebeshRuneFormat =
    {
        format: function(runes)
        {
            var answer = "";

            var properties = AurebeshRune.properties;

            for (var i = 0; i < runes.length; i++)
            {
                var rune = runes[i];

                if (!rune)
                {
                    LOGGER.error("Missing rune at position " + i + "; runes.length = " + runes.length + " runes = " +
                            runes);
                }

                answer += properties[rune].name;

                if (i < runes.length - 1)
                {
                    answer += "-";
                }
            }

            return answer;
        },

        parse: function(string)
        {
            var answer = [];

            var names = string.split("-");

            for (var i = 0; i < names.length; i++)
            {
                var name = names[i];
                answer[answer.length] = AurebeshRune[name];
            }

            return answer;
        },

        getFontLetters: function(runes)
        {
            var answer = "";

            var properties = AurebeshRune.properties;

            for (var i = 0; i < runes.length; i++)
            {
                var rune = runes[i];
                answer += properties[rune].fontLetter;
            }

            return answer;
        }
    }

    return AurebeshRuneFormat;
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('users')
    .controller('InviteController', InviteController);

  /* @ngInject */
  function InviteController(InvitationService, Authentication, $window, $location, $timeout, $state) {

    // ViewModel
    var vm = this;

    // Exposed to the view
    vm.invitation = InvitationService.get();

    configureAddThis();

    /**
     * Configure add this share buttons
     * https://www.addthis.com/academy/category/developer-documentation/
     */
    function configureAddThis() {

      // Ensure we have code and continue only then
      vm.invitation.$promise.then(function(invitation) {

        var code = invitation.code.toUpperCase();

        // Build full domain dynamically
        var domain =
          $location.protocol() +
          '://' +
          $location.host() +
          ($location.port() !== '80' ? ':' + $location.port() : '');

        // Build full signup URL dynamically (including domain and path)
        var signUpUrl = domain + $state.href('signup', { code: invitation.code });

        var inviteTextPersonal =
          'Would you like to join me on Trustroots.org? ' +
          'It\'s an invitation only travellers community where we ' +
          'host and meet each other.';

        var inviteSingupUrlText =
          'You can sign up at ' + signUpUrl +
          ' (link is valid for 24 hours)';

        var inviteTextGeneric =
          'You have been invited to join Trustroots, an invite only ' +
          'travellers community where people host and meet each other.' +
          inviteSingupUrlText;

        // UI Configuration
        // @link https://www.addthis.com/academy/addthis-email-sharing-service/
        // @link https://www.addthis.com/academy/the-addthis_config-variable/
        $window.addthis_config = {
          ui_email_from: Authentication.user.email,
          ui_email_note: inviteTextPersonal,
          data_track_clickback: false,
          data_track_addressbar: false
        };

        // Configure AddThis to send GA data
        // @link https://www.addthis.com/academy/integrating-with-google-analytics/
        if ($window.gaId) {
          $window.addthis_config.data_ga_property = $window.gaId;
        }

        // Sharing Configuration
        // https://www.addthis.com/academy/the-addthis_share-variable/
        $window.addthis_share = {
          url: signUpUrl,
          title: Authentication.user.displayName + ' invites you to join Trustroots.org',
          description: inviteTextGeneric,
          media: domain + '/modules/core/img/og_image.jpg',
          email_template: 'invite',
          email_vars: {
            'code': code,
            'invitee': Authentication.user.displayName
          }
        };

      });
    }

  }

}());
<commit_msg>Remove media parameter for addthis sharing<commit_after>(function () {
  'use strict';

  angular
    .module('users')
    .controller('InviteController', InviteController);

  /* @ngInject */
  function InviteController(InvitationService, Authentication, $window, $location, $timeout, $state) {

    // ViewModel
    var vm = this;

    // Exposed to the view
    vm.invitation = InvitationService.get();

    configureAddThis();

    /**
     * Configure add this share buttons
     * https://www.addthis.com/academy/category/developer-documentation/
     */
    function configureAddThis() {

      // Ensure we have code and continue only then
      vm.invitation.$promise.then(function(invitation) {

        var code = invitation.code.toUpperCase();

        // Build full domain dynamically
        var domain =
          $location.protocol() +
          '://' +
          $location.host() +
          ($location.port() !== '80' ? ':' + $location.port() : '');

        // Build full signup URL dynamically (including domain and path)
        var signUpUrl = domain + $state.href('signup', { code: invitation.code });

        var inviteTextPersonal =
          'Would you like to join me on Trustroots.org? ' +
          'It\'s an invitation only travellers community where we ' +
          'host and meet each other.';

        var inviteSingupUrlText =
          'You can sign up at ' + signUpUrl +
          ' (link is valid for 24 hours)';

        var inviteTextGeneric =
          'You have been invited to join Trustroots, an invite only ' +
          'travellers community where people host and meet each other.' +
          inviteSingupUrlText;

        // UI Configuration
        // @link https://www.addthis.com/academy/addthis-email-sharing-service/
        // @link https://www.addthis.com/academy/the-addthis_config-variable/
        $window.addthis_config = {
          ui_email_from: Authentication.user.email,
          ui_email_note: inviteTextPersonal,
          data_track_clickback: false,
          data_track_addressbar: false
        };

        // Configure AddThis to send GA data
        // @link https://www.addthis.com/academy/integrating-with-google-analytics/
        if ($window.gaId) {
          $window.addthis_config.data_ga_property = $window.gaId;
        }

        // Sharing Configuration
        // https://www.addthis.com/academy/the-addthis_share-variable/
        $window.addthis_share = {
          url: signUpUrl,
          title: Authentication.user.displayName + ' invites you to join Trustroots.org',
          description: inviteTextGeneric,
          // Image used for sharing
          // Image URL would be appended to "note" section in invite emails as well
          // media: domain + '/modules/core/img/og_image.jpg',
          email_template: 'invite',
          email_vars: {
            'code': code,
            'invitee': Authentication.user.displayName
          }
        };

      });
    }

  }

}());
<|endoftext|>


<commit_before>/* Description:
 *   pushes a default URL to screens when /reset is hit
 *
 * Dependencies:
 *   settings
 *
 * Optional Dependencies:
 *   command - if present, the reset lines can be commands.
 *
 *
 * Configuration:
 *   defaultUrl
 *
 * Author:
 *    lonnen, mythmon, potch
 */

module.exports = function (corsica) {
  var useCommand = corsica.config.plugins.indexOf('command') >= 0;

  var settings = corsica.settings.setup('reset', {
    defaultUrl: ['http://xkcd.com'],
  });

  var urlIndex = 0;

  corsica.on('reset', function(content) {
    settings.get().then(function (settings) {
      var nextLine = settings.defaultUrl[urlIndex];
      urlIndex = (urlIndex + 1) % settings.defaultUrl.length;

      if (useCommand) {
        if ('screen' in content) {
          nextLine += ' screen=' + content.screen;
        }
        corsica.sendMessage('command', {raw: nextLine});
      } else {
        content.type = 'url';
        content.url = nextLine;
        corsica.sendMessage('content', content);
      }
    });

    return content;
  });
};
<commit_msg>Remove bit-rotted reset plugin.<commit_after><|endoftext|>


<commit_before>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _jquery = __webpack_require__(1);

	var _jquery2 = _interopRequireDefault(_jquery);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	window.$.lePlayer.plugin('ga', function (pluginOptions) {
		var player = this;

		if (window.ga) {
			console.error('Google Analytics does not exist');
			return;
		}

		player.on('firstplay', function (e) {
			window.ga('send', 'event', 'Player Video Started');
		});

		player.on('controlclick', function (e, data) {
			var control = data.control;
			var _control$options = control.options,
			    name = _control$options.name,
			    collection = _control$options.collection;

			if (name) {
				window.ga('send', 'event', 'Player Control Click', name, collection);
			}
		});

		player.on('sectionsclick', function (e, data) {
			window.ga('send', 'event', 'Player Sections', 'Click', player.getView());
		});

		player.on('timeupdate', function () {
			var percent = player.video.playedPercentage;
			var delta = 5;
			if (Math.abs(percent - 100) < delta) {
				window.ga('send', 'event', 'Player Video Played', '95-100%');
			}
		});
	});

/***/ },
/* 1 */
/***/ function(module, exports) {

	module.exports = $;

/***/ }
/******/ ]);<commit_msg>🚀  DIST<commit_after>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _jquery = __webpack_require__(1);

	var _jquery2 = _interopRequireDefault(_jquery);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	var Player = window.$.lePlayer;

	Player.plugin('ga', function (pluginOptions) {
		var player = this;

		if (!window.ga) {
			console.error('Google Analytics does not exist');
			return;
		}

		player.on('firstplay', function (e) {
			window.ga('send', 'event', 'Player Video Started');
		});

		player.on('controlclick', function (e, data) {
			var control = data.control;
			var _control$options = control.options,
			    name = _control$options.name,
			    collection = _control$options.collection;

			if (name) {
				window.ga('send', 'event', 'Player Control Click', name, collection);
			}
		});

		player.on('sectionsclick', function (e, data) {
			window.ga('send', 'event', 'Player Sections', 'Click', player.getView());
		});

		player.on('timeupdate', function () {
			var percent = player.video.playedPercentage;
			var delta = 5;
			if (Math.abs(percent - 100) < delta) {
				window.ga('send', 'event', 'Player Video Played', '95-100%');
			}
		});
	});

/***/ },
/* 1 */
/***/ function(module, exports) {

	module.exports = $;

/***/ }
/******/ ]);<|endoftext|>


<commit_before>
// made for: https://github.com/jgstew/bigfix-content/blob/master/dashboards/ClientSettingsManager.ojo
// tested in nodejs v7.5.0
// target: IE11  (secondarily nodejs and all other recent browsers)

function fnCreateClientSettingsXML(name, value, dateRelease, userName) {
	// http://www.codereadability.com/javascript-default-parameters-with-or-operator/
	if (dateRelease === undefined) {
		dateRelease = new Date();
	}
	if (userName === undefined) {
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
		try {
			// https://developer.bigfix.com/relevance/reference/bes-user.html#current-console-user-bes-user
			// https://developer.bigfix.com/relevance/reference/string.html#bes-current-wruser-string
			testGetUserName = bigfix.relevance.evaluate(' if (in web reports context AND exists properties "bes current wruser") then (bes current wruser) else (name of current console user | "") ');
			userName = testGetUserName;
		} catch (e) {
			if (e instanceof ReferenceError && e.message == "bigfix is not defined") {
				// pass
			} else {
				throw e;
			}
		}
	}
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
	return `<?xml version="1.0" encoding="UTF-8"?>
<BES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="BES.xsd">
	<Task>
		<Title>Set "${ name }" to "${ value }" - Universal</Title>
		<Description><![CDATA[
This task will set a client setting

This task was automatically generated using the Dashboard: "Custom - Client Settings Manager"

]]></Description>
		<Relevance>not exists settings "${ name }" whose("${ value }" = value of it) of client</Relevance>
		<Category>Configuration: Client Settings</Category>
		<DownloadSize>0</DownloadSize>
		<Source>Custom Dashboard - Client Settings Manager</Source>
		<SourceID>jgstew${ (userName) ? "; " + userName : "" }</SourceID>
		<SourceReleaseDate>${ dateRelease.toISOString().slice(0,10) }</SourceReleaseDate>
		<SourceSeverity></SourceSeverity>
		<CVENames></CVENames>
		<SANSID></SANSID>
		<Domain>BESC</Domain>
		<DefaultAction ID="Action1">
			<Description>
				<PreLink>Click </PreLink>
				<Link>here</Link>
				<PostLink> to set the Client Setting</PostLink>
			</Description>
			<ActionScript MIMEType="application/x-Fixlet-Windows-Shell">
setting "${ name }"="${ value }" on "{ parameter "action issue date" of action}" for client
			</ActionScript>
			<SuccessCriteria Option="OriginalRelevance"></SuccessCriteria>
		</DefaultAction>
	</Task>
</BES>`;
}

// if this file is run directly, do the following:
if (require.main === module) {
	console.log( fnCreateClientSettingsXML("testSettingName", "testSettingValue") );
	// http://stackoverflow.com/a/16714931/861745
	// https://github.com/jgstew/tools/blob/master/JS/YYYY-MM-DD.js
}
<commit_msg>Update createActionClientSettings.js<commit_after>
// made for: https://github.com/jgstew/bigfix-content/blob/master/dashboards/ClientSettingsManager.ojo
// tested in nodejs v7.5.0
// target: IE11  (secondarily nodejs and all other recent browsers)

function fnCreateClientSettingsXML(name, value, dateRelease, userName) {
	"use strict"; // http://www.w3schools.com/js/js_strict.asp
	// http://www.codereadability.com/javascript-default-parameters-with-or-operator/
	if (dateRelease === undefined) {
		dateRelease = new Date();
	}
	if (userName === undefined) {
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
		try {
			// https://developer.bigfix.com/relevance/reference/bes-user.html#current-console-user-bes-user
			// https://developer.bigfix.com/relevance/reference/string.html#bes-current-wruser-string
			testGetUserName = bigfix.relevance.evaluate(' if (in web reports context AND exists properties "bes current wruser") then (bes current wruser) else (name of current console user | "") ');
			userName = testGetUserName;
		} catch (e) {
			if (e instanceof ReferenceError && e.message == "bigfix is not defined") {
				// pass
			} else {
				throw e;
			}
		}
	}
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
	return `<?xml version="1.0" encoding="UTF-8"?>
<BES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="BES.xsd">
	<Task>
		<Title>Set "${ name }" to "${ value }" - Universal</Title>
		<Description><![CDATA[
This task will set a client setting

This task was automatically generated using the Dashboard: "Custom - Client Settings Manager"

]]></Description>
		<Relevance>not exists settings "${ name }" whose("${ value }" = value of it) of client</Relevance>
		<Category>Configuration: Client Settings</Category>
		<DownloadSize>0</DownloadSize>
		<Source>Custom Dashboard - Client Settings Manager</Source>
		<SourceID>jgstew${ (userName) ? "; " + userName : "" }</SourceID>
		<SourceReleaseDate>${ dateRelease.toISOString().slice(0,10) }</SourceReleaseDate>
		<SourceSeverity></SourceSeverity>
		<CVENames></CVENames>
		<SANSID></SANSID>
		<Domain>BESC</Domain>
		<DefaultAction ID="Action1">
			<Description>
				<PreLink>Click </PreLink>
				<Link>here</Link>
				<PostLink> to set the Client Setting</PostLink>
			</Description>
			<ActionScript MIMEType="application/x-Fixlet-Windows-Shell">
setting "${ name }"="${ value }" on "{ parameter "action issue date" of action}" for client
			</ActionScript>
			<SuccessCriteria Option="OriginalRelevance"></SuccessCriteria>
		</DefaultAction>
	</Task>
</BES>`;
}

// if this file is run directly, do the following:
if (require.main === module) {
	console.log( fnCreateClientSettingsXML("testSettingName", "testSettingValue") );
	// http://stackoverflow.com/a/16714931/861745
	// https://github.com/jgstew/tools/blob/master/JS/YYYY-MM-DD.js
}
<|endoftext|>


<commit_before>var bubbles = [];
var bubble_index = {};
var placed  = false;
var now     = function(){return+new Date};
var channel = 'pubnub-demo-channel';

var large_circle = new Path.Circle([676, 433], 100);
large_circle.fillColor = '#000';
large_circle.strokeColor = '#000';
large_circle.strokeWidth = 8;

var text = new PointText(view.center);
text.fillColor = '#fff';
text.characterStyle.fontSize = 35;
text.paragraphStyle.justification = 'center';
text.content = 'PubNub';
text.position = large_circle.center;

var group = new Group([large_circle, text]);
group.visible = false;

function onMouseMove(event) {
}

function onFrame(event) {
  for (var i = 0; i < bubbles.length; i++) {
    console.log("aoeuaueo");
    bubbles[i].scale(.99);
    console.log(bubbles[i].children[0].bounds);
    /*
    if (bubbles[i].bounds.width <= 50) {
      console.log('pop!');
    }
    */
  }
}

function onMouseDown(event) {
  var uuid = 'uuid' in event && event.uuid;
  //if (onMouseDown.last + 800 > now()) return;

  // Publish Fun For All
  /*
  uuid || PUBNUB.publish({
     channel  : channel,
     callback : function(i){console.log(i)},
     message  : {
       name  : 'bubble-click',
       point : event.point,
     }
  });
  */

  uuid || console.log('NETWORK EVETNT!!!');

  //console.log(event.point);

  for (var i = 0; i < bubbles.length; i++) {
      hit_result = bubbles[i].hitTest(event.point);
      if ((hit_result !== null) && (hit_result !== undefined)) {
        bubbles[i].scale(1.5);
        onMouseDown.last = now();
      }
  }
}
onMouseDown.last = now();

$("#place").click( function(e) {
  e.preventDefault();

  var new_bubble = group.clone();

  new_bubble.children[1].content = $("#bubble_text").val();
  new_bubble.visible = true;
  var bubble_pos = generateRandomLocation();
  new_bubble.children[0].position = bubble_pos;
  new_bubble.children[1].position = bubble_pos;

  bubbles.push(new_bubble);

  // Create New Bubble Entity Lookup
  PUBNUB.uuid(function(uuid) {
    new_bubble.uuid = uuid;
    bubble_index[uuid] = { bubble : new_bubble, uuid : uuid };
  } );

});

// ---------------------------------------------------------------------------
// PubNub Networking
// ---------------------------------------------------------------------------
PUBNUB.subscribe({
  channel  : channel,
  connect  : function() {},
  callback : function(event) {
      PUBNUB.events.fire( event.name, event );
  }
});

// ---------------------------------------------------------------------------
// PubNub Events
// ---------------------------------------------------------------------------
PUBNUB.events.bind( 'bubble-click', function(event) {
  onMouseDown(event);
} );

function generateRandomLocation() {
  return new Point(Math.random() * view.size.width, Math.random() * view.size.height);
}
<commit_msg>added more networking semi-working to KRT Conf Demo.<commit_after>var bubbles = [];
var bubble_index = {};
var placed  = false;
var now     = function(){return+new Date};
var channel = 'pubnub-demo-channel';

var large_circle = new Path.Circle([676, 433], 100);
large_circle.fillColor = '#000';
large_circle.strokeColor = '#000';
large_circle.strokeWidth = 8;

var text = new PointText(view.center);
text.fillColor = '#fff';
text.characterStyle.fontSize = 35;
text.paragraphStyle.justification = 'center';
text.content = 'PubNub';
text.position = large_circle.center;

var group = new Group([large_circle, text]);
group.visible = false;

function onMouseMove(event) {
}

function onFrame(event) {
  for (var i = 0; i < bubbles.length; i++) {
    //console.log("aoeuaueo");
    bubbles[i].scale(.99);
    //console.log(bubbles[i].children[0].bounds);
    /*
    if (bubbles[i].bounds.width <= 50) {
      console.log('pop!');
    }
    */
  }
}

function send_bubble_click( uuid, event ) {
  PUBNUB.publish({
     channel  : channel,
     callback : function(i){console.log(i)},
     message  : {
       name  : 'bubble-click',
       point : event.point,
       uuid  : uuid
     }
  });
}

function onMouseDown(event) {
  var uuid = 'uuid' in event && event.uuid;
  //if (onMouseDown.last + 800 > now()) return;

  uuid && console.log('NETWORK EVETNT!!!',uuid);

  uuid && !(uuid in bubble_index) && add_new_bubble(uuid);

  for (var i = 0; i < bubbles.length; i++) {
      hit_result = bubbles[i].hitTest(event.point);
      if (hit_result) {
        if (uuid) {
          bubbles[i].scale(1.5);
          continue;
        }
        // Publish Fun For All
        send_bubble_click( bubbles[i].uuid, event );
        onMouseDown.last = now();
      }
  }
}
onMouseDown.last = now();

// ---------------------------------------------------------------------------
// Make New Bubble
// ---------------------------------------------------------------------------
function add_new_bubble(uuid) {
  var new_bubble = group.clone();

  new_bubble.children[1].content = $("#bubble_text").val();
  new_bubble.visible = true;
  var bubble_pos = generateRandomLocation();
  new_bubble.children[0].position = bubble_pos;
  new_bubble.children[1].position = bubble_pos;

  bubbles.push(new_bubble);

  // Create New Bubble Entity Lookup
  new_bubble.uuid = uuid;
  bubble_index[uuid] = { bubble : new_bubble, uuid : uuid };

  uuid || PUBNUB.uuid(function(uuid) {
    new_bubble.uuid = uuid;
    bubble_index[uuid] = { bubble : new_bubble, uuid : uuid };
  } );
}

$("#place").click( function(e) {
  e.preventDefault();
  add_new_bubble();
});

// ---------------------------------------------------------------------------
// PubNub Networking
// ---------------------------------------------------------------------------
PUBNUB.subscribe({
  channel  : channel,
  connect  : function() {},
  callback : function(event) {
    console.log(event);
    PUBNUB.events.fire( event.name, event );
  }
});

// ---------------------------------------------------------------------------
// PubNub Events
// ---------------------------------------------------------------------------
PUBNUB.events.bind( 'bubble-click', function(event) {
  onMouseDown(event);
} );

function generateRandomLocation() {
  return new Point(Math.random() * view.size.width, Math.random() * view.size.height);
}
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe('requisition-search run', function() {

    var loginServiceSpy, requisitionSearchServiceSpy, postLoginAction, postLogoutAction,  $q, $rootScope;

    beforeEach(function() {
        module('requisition-search', function($provide) {
            loginServiceSpy = jasmine.createSpyObj('loginService', [
                'registerPostLoginAction', 'registerPostLogoutAction'
            ]);
            $provide.value('loginService', loginServiceSpy);

            requisitionSearchServiceSpy = jasmine.createSpyObj('requisitionSearchService', [
                'getFacilities', 'clearCachedFacilities'
            ]);
            $provide.value('requisitionSearchService', requisitionSearchServiceSpy);
        });

        inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $q = $injector.get('$q');
        });

        postLoginAction = loginServiceSpy.registerPostLoginAction.calls[2].args[0];
        postLogoutAction = loginServiceSpy.registerPostLogoutAction.calls[2].args[0];
    });

    describe('run block', function() {

        beforeEach(function() {
            inject();
        });

        it('should register post login action', function() {
            expect(loginServiceSpy.registerPostLoginAction).toHaveBeenCalled();
        });

        it('should register post logout action', function() {
            expect(loginServiceSpy.registerPostLogoutAction).toHaveBeenCalled();
        });

    });

    describe('post login action', function() {

        it('should cache facilities', function() {
            requisitionSearchServiceSpy.getFacilities.andReturn($q.resolve());

            postLoginAction();

            expect(requisitionSearchServiceSpy.getFacilities).toHaveBeenCalled();
        });

    });

    describe('post logout action', function() {

        it('should clear current user cache', function() {
            requisitionSearchServiceSpy.clearCachedFacilities.andReturn($q.resolve());

            var success;
            postLogoutAction()
                .then(function() {
                    success = true;
                });
            $rootScope.$apply();

            expect(success).toBe(true);
            expect(requisitionSearchServiceSpy.clearCachedFacilities).toHaveBeenCalled();
        });

    });

});<commit_msg>OLMIS-5837: Made run test less fragile for adding run blocks in other modules<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

describe('requisition-search run', function() {

    var loginServiceSpy, requisitionSearchServiceSpy, postLoginAction, postLogoutAction,  $q, $rootScope;

    beforeEach(function() {
        module('requisition-search', function($provide) {
            loginServiceSpy = jasmine.createSpyObj('loginService', [
                'registerPostLoginAction', 'registerPostLogoutAction'
            ]);
            $provide.value('loginService', loginServiceSpy);

            requisitionSearchServiceSpy = jasmine.createSpyObj('requisitionSearchService', [
                'getFacilities', 'clearCachedFacilities'
            ]);
            $provide.value('requisitionSearchService', requisitionSearchServiceSpy);
        });

        inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $q = $injector.get('$q');
        });

        postLoginAction = getLastCall(loginServiceSpy.registerPostLoginAction).args[0];
        postLogoutAction = getLastCall(loginServiceSpy.registerPostLogoutAction).args[0];
    });

    describe('run block', function() {

        beforeEach(function() {
            inject();
        });

        it('should register post login action', function() {
            expect(loginServiceSpy.registerPostLoginAction).toHaveBeenCalled();
        });

        it('should register post logout action', function() {
            expect(loginServiceSpy.registerPostLogoutAction).toHaveBeenCalled();
        });

    });

    describe('post login action', function() {

        it('should cache facilities', function() {
            requisitionSearchServiceSpy.getFacilities.andReturn($q.resolve());

            postLoginAction();

            expect(requisitionSearchServiceSpy.getFacilities).toHaveBeenCalled();
        });

    });

    describe('post logout action', function() {

        it('should clear current user cache', function() {
            requisitionSearchServiceSpy.clearCachedFacilities.andReturn($q.resolve());

            var success;
            postLogoutAction()
                .then(function() {
                    success = true;
                });
            $rootScope.$apply();

            expect(success).toBe(true);
            expect(requisitionSearchServiceSpy.clearCachedFacilities).toHaveBeenCalled();
        });

    });

    function getLastCall(method) {
        return method.calls[method.calls.length - 1];
    }

});<|endoftext|>