<commit_before>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){var e=this,n=function(t){return(t.text=t.textContent)&&t.textContent.match(/{(\w+|#)}/g).map(function(t){return t.match(/(\w+|#)/g)[0]}).map(r(t))},r=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t).filter(function(t){return/{(\w+|#)}/g.test(t.value)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&e[t].map(r(t))},r=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};Object.keys(this).filter(function(e){return void 0!==t[e]}).map(n)};var HTMLTemplateElement=Template=function(t){function e(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),void new TokenList(n.content).bind(t),n.innerHTML}).join(""),void(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}return Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.connectedCallback=function(){new HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onimport.bind(this))},e.prototype.on=function(t,e){this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onimport=function(e,n){(n=e.target["import"])&&this.clone(n.querySelector("template")),t.onconnect&&t.onconnect.call(this),this.render()},e.prototype.register=function(){var e=this,n=function(t){return/^on/.test(t)},r=function(r){return n(r)&&null===e[r]&&(e[r]=t[r].bind(e))},o=Array.from(this.querySelectorAll("*")),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(n).map(u(t))},u=function(n){return function(r,o){return(o=/{\s*(\w+)\s*}/.exec(n[r]))&&(o=(o||[])[1])&&(o=t[o])&&(n[r]=o.bind(e))}};Object.getOwnPropertyNames(t).map(r),void[this].concat(o).map(i)},e}(t)},Component=function(t){return function(e){function n(){e.call(this),this.context={},this.initialize&&this.initialize(),this.tokens=new TokenList(this)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.render=function(){var e=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(t){return new Template(t).bind(e[t])}),this.register(),t.onidle&&t.onidle.call(this)},n.prototype.clone=function(t){var e=this,n=t.content.cloneNode(!0),r=Array.from(n.querySelectorAll("slot")),o=function(t){return r.filter(i(t)).map(u(t))},i=function(t){return function(e){return t.getAttribute("slot")===e.getAttribute("name")}},u=function(t){return function(e){return e.parentNode.replaceChild(t,e)}};Array.from(t.attributes).map(function(t){return e.setAttribute(t.name,t.value)}),Array.from(this.querySelectorAll("[slot]")).map(o),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===e&&(e=window.customElements),function(n){return e.define.apply(e,t.concat([Component(n)]))}};Element.prototype=ElementPrototype;<commit_msg>:muscle: bump distribution for dist/snuggsi.min.js<commit_after>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){var e=this,n=function(t){return(t.text=t.textContent)&&t.textContent.match(/{(\w+|#)}/g).map(function(t){return t.match(/(\w+|#)/g)[0]}).map(r(t))},r=function(t){return function(n){return(e[n]=e[n]||[])&&e[n].push(t)}};this.sift(t).map(n)};TokenList.prototype.sift=function(t){for(var e=[],n=function(t){return t.nodeType===Node.TEXT_NODE?r(t)&&NodeFilter.FILTER_ACCEPT:o(t.attributes)&&NodeFilter.FILTER_REJECT},r=function(t){return/{(\w+|#)}/.test(t.textContent)},o=function(t){return Array.from(t).filter(function(t){return/{(\w+|#)}/g.test(t.value)}).map(function(t){return e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,n);t=i.nextNode();)e.push(t);return e},TokenList.prototype.bind=function(t){var e=this,n=function(t){return e[t].map(function(t){return t.textContent=t.text})&&e[t].map(r(t))},r=function(e){return function(n){return n.textContent=n.textContent.replace("{"+e+"}",t[e])}};Object.keys(this).filter(function(e){return void 0!==t[e]}).map(n)};var HTMLTemplateElement=Template=function(t){function e(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),void new TokenList(n.content).bind(t),n.innerHTML}).join(""),void(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}return Object.assign(document.querySelector("template[name="+t+"]"),{bind:e})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.connectedCallback=function(){new HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onimport.bind(this))},e.prototype.on=function(t,e){this.addEventListener(t,e)},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onimport=function(e,n){void console.warn("event doc",e,n),(n=e.target["import"])&&this.clone(n.querySelector("template")),t.onconnect&&t.onconnect.call(this),this.render()},e.prototype.register=function(){var e=this,n=function(t){return/^on/.test(t)},r=function(r){return n(r)&&null===e[r]&&(e[r]=t[r].bind(e))},o=Array.from(this.querySelectorAll("*")),i=function(t){return Array.from(t.attributes).map(function(t){return t.name}).filter(n).map(u(t))},u=function(n){return function(r,o){return(o=/{\s*(\w+)\s*}/.exec(n[r]))&&(o=(o||[])[1])&&(o=t[o])&&(n[r]=o.bind(e))}};Object.getOwnPropertyNames(t).map(r),void[this].concat(o).map(i)},e}(t)},Component=function(t){return function(e){function n(){e.call(this),this.context={},this.initialize&&this.initialize(),this.tokens=new TokenList(this)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.render=function(){var e=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(t){return new Template(t).bind(e[t])}),this.register(),t.onidle&&t.onidle.call(this)},n.prototype.clone=function(t){var e=this,n=t.content.cloneNode(!0),r=Array.from(n.querySelectorAll("slot")),o=function(t){return r.filter(i(t)).map(u(t))},i=function(t){return function(e){return t.getAttribute("slot")===e.getAttribute("name")}},u=function(t){return function(e){return e.parentNode.replaceChild(t,e)}};Array.from(t.attributes).map(function(t){return e.setAttribute(t.name,t.value)}),Array.from(this.querySelectorAll("[slot]")).map(o),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t,e){return void 0===e&&(e=window.customElements),function(n){return e.define.apply(e,t.concat([Component(n)]))}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>/*
   _            _     __
  | |_ __ _ ___| | __/ _| ___  _ __ ___ ___
  | __/ _` / __| |/ / |_ / _ \| '__/ __/ _ \
  | || (_| \__ \   <|  _| (_) | | | (_|  __/
   \__\__,_|___/_|\_\_|  \___/|_|  \___\___|

  ===============================================================================

  A generic widget include script which we will use to show further campaigns etc

  <thomasalwyndavis@gmail.com> or http://taskforce.is for support

  ===============================================================================

  TODO
    - Use underscores or camelcase?

*/

// Wrap widget in function to protect scope
var _tfrce_config = (typeof tfrce_config  !== 'undefined') ? tfrce_config  : {};

(function(window, widget_config){

  // Do configuration

  widget_config.show_style = widget_config.show_style || 'center_modal';
  widget_config.disableGeo = widget_config.disableGeo || false;
  widget_config.debug = widget_config.debug || false;
  widget_config.disableDate = widget_config.disableDate || false;
  widget_config.campaign = widget_config.campaign || 'stopwatchingus';
  widget_config.cookieTimeout = widget_config.cookieTimeout || 172800;

  // Setup
  var active_campaign;
  var ASSET_URL, COOKIE_TIMEOUT;

  if(widget_config.debug) {
    ASSET_URL = '../stopwatchingus/';
    COOKIE_TIMEOUT = 20;
  } else {
    ASSET_URL = '//widget.taskforce.is/widget/stopwatchingus/';
    COOKIE_TIMEOUT = widget_config.cookieTimeout;
  }

  // Cookie helpers, taken from w3schools
  function setCookie(c_name,value,seconds) {
    var exdate = new Date(new Date().getTime() + seconds*1000);
    var c_value=escape(value) + ((seconds==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
  }

  function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); };
    if (c_start == -1) {
      c_value = null;
    } else {
      c_start = c_value.indexOf("=", c_start) + 1;
      var c_end = c_value.indexOf(";", c_start);
      if (c_end == -1) { c_end = c_value.length; }
      c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
  }

  // Define checks

  var checks = {
    betweenDate: function(startDate, endDate) {
      var startEpoch = startDate.getTime();
      var endEpoch = endDate.getTime();
      var currentEpoch = new Date().getTime();
      if(currentEpoch > startEpoch && currentEpoch < endEpoch) {
        return true;
      } else {
        return false;
      }
    },
    isMobile: function() {
      var ismobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i);
      return ismobile ? false : true;
    },
    hasSeenCampaign: function (cookieName) {
      var cookie = getCookie(cookieName)
      if(cookie === null) {
        return false;
      } else {
        return true
      }
    },
    nearDC: function (callback) {
      window.nearDC = callback;
      var script = document.createElement('script');
      script.src = '//geoip.taskforce.is/?callback=nearDC'
      document.getElementsByTagName('head')[0].appendChild(script);
    }
  }

  // Define campaigns

  var campaign = {
    stopwatchingus: {
      cookieName: 'stopwatchingus_hasseen6',

      // Months start at zero, so October = 9
      startDate: new Date(2013, 9, 15, 0),
      endDate: new Date(2013, 9, 26, 12),
      hide: function (el, callback) {
        document.body.removeChild(el);
        setCookie(active_campaign.cookieName, 'true', COOKIE_TIMEOUT);
        if(callback) { callback(); };
      },
      styles: {
        modal: {
          campaign_container: '',
          iframe_container: '',
          iframe: '',
          closeButton: ''
        },
        banner: {
          campaign_container: 'position:fixed;width:100%;bottom:0;z-index:100; padding: 0 20px;',
          iframe_container: 'position: relative; height: 100px; max-width:1201px; margin: 0px auto 8px auto; background: #444;border-radius: 10px;',
          iframe: 'width: 100%;height: 100%;border: 0;margin:0;padding:0;border-radius: 10px;',
          closeButton: 'border: 0;height: 28px;width: 28px;cursor: pointer;position: absolute;top:33px;right:20px;background: url("' + ASSET_URL +'images/close-button.png");'
        },
        dev: {
          campaign_container: 'position:fixed;width:100%;bottom:0;z-index:100; padding: 0 20px;',
          iframe_container: 'position: relative; height: 100px; max-width:1201px; margin: 0px auto 8px auto; background: #444;border-radius: 10px;',
          iframe: 'width: 100%;height: 100%;border: 0;margin:0;padding:0;border-radius: 10px;',
          closeButton: 'border: 0;height: 28px;width: 28px;cursor: pointer;position: absolute;top:33px;right:20px;background: url("' + ASSET_URL +'images/close-button.png");'
        },
        strip: {
          campaign_container: 'position:fixed;width:100%;bottom:0;opacity:1;z-index:100;',
          iframe_container: 'position:relative;height:50px;margin:0 20px 0px 20px;background:#444;border-radius:10px 10px 0 0;',
          iframe: 'width:100%;height:100%;border:0;margin:0;padding:0;border-radius:10px;',
          closeButton: 'border:0;height:28px;width:28px;cursor:pointer;position:absolute;top:11px;right:10px;background:url("' + ASSET_URL +'images/close-button.png");'
        },
        modal: {
          overlay: 'position:fixed; background:#000; width:100%; height:100%;z-index:30;top:0; left:0; opacity:0.5;-moz-opacity: 0.50;filter: alpha(opacity=50);',
          campaign_container: 'position:fixed;left:50%;margin-left:-250px;margin-top:40px;width:500px;top:0;opacity:1;z-index:100;',
          iframe_container: 'position:relative;height:365px; width:500px;background:#444;border-radius:10px;',
          iframe: 'width:100%;height:100%;border:0;margin:0;padding:0;border-radius:10px;',
          closeButton: 'border:0;height:28px;width:28px;cursor:pointer;position:absolute;top:15px;right:15px;background:url("' + ASSET_URL +'images/close-button.png");'
        }
      },
      show: function () {

        var style = active_campaign.styles[active_campaign.config.show_style]

        if(style.overlay) {
          var overlay = document.createElement('div');
          overlay.style.cssText = style.overlay;
          document.body.appendChild(overlay);
        }

        // Create a container
        var campaign_container = document.createElement('div');
        campaign_container.style.cssText = style.campaign_container;

        // Create a container for the iframe so we can do padding and border-radius properly
        var iframe_container = document.createElement('div');
        iframe_container.style.cssText = style.iframe_container;

        // Append Iframe and campaign container to document
        campaign_container.appendChild(iframe_container);
        document.body.appendChild(campaign_container);

        var iframe = document.createElement('iframe');
        iframe.style.cssText = style.iframe;

        // Set the source of the iframe to the configured show_style type
        iframe.src = ASSET_URL + active_campaign.config.show_style + '.html';
        iframe_container.appendChild(iframe);

        // Setup a close button
        var closeButton = document.createElement('button');
        closeButton.style.cssText = style.closeButton;
        iframe_container.appendChild(closeButton);
        closeButton.onclick = function() {
          active_campaign.hide(campaign_container);
          if(style.overlay) {
            document.body.removeChild(overlay);
          }
        }

      },
      init: function (config) {
        active_campaign.config = config;
        // Check cookie for this campaign
        if(checks.hasSeenCampaign(active_campaign.cookieName)) {
          return false;
        }

        // Check between date
        if(!checks.betweenDate(active_campaign.startDate, active_campaign.endDate) || active_campaign.config.disableDate) {
          return false;
        }

        // Check if is mobile
        if(!checks.isMobile()){
          return false;
        }

        // Check if they are near Washington?
        if(active_campaign.config.disableGeo) {
          active_campaign.show();
        } else {
          checks.nearDC(function (res) {
            if(res.kilometersFromDC <= 700) {
              active_campaign.show();
            }
          })
        }
      }
    }
  }

  // Load campaign if exist

  if(typeof campaign[widget_config.campaign] !== 'undefined') {
    active_campaign = campaign[widget_config.campaign];
    active_campaign.init(widget_config);
  } else {
    return false;
  }

})(window, _tfrce_config);
<commit_msg>cleanup<commit_after>/*
   _            _     __
  | |_ __ _ ___| | __/ _| ___  _ __ ___ ___
  | __/ _` / __| |/ / |_ / _ \| '__/ __/ _ \
  | || (_| \__ \   <|  _| (_) | | | (_|  __/
   \__\__,_|___/_|\_\_|  \___/|_|  \___\___|

  ===============================================================================

  A generic widget include script which we will use to show further campaigns etc

  <thomasalwyndavis@gmail.com> or http://taskforce.is for support

  ===============================================================================

*/

// Wrap widget in function to protect scope
var _tfrce_config = (typeof tfrce_config  !== 'undefined') ? tfrce_config  : {};

(function(window, widget_config){

  // Do configuration

  widget_config.show_style = widget_config.show_style || 'center_modal';
  widget_config.disableGeo = widget_config.disableGeo || false;
  widget_config.debug = widget_config.debug || false;
  widget_config.disableDate = widget_config.disableDate || false;
  widget_config.campaign = widget_config.campaign || 'stopwatchingus';
  widget_config.cookieTimeout = widget_config.cookieTimeout || 172800;

  // Setup
  var active_campaign;
  var ASSET_URL, COOKIE_TIMEOUT;

  if(widget_config.debug) {
    ASSET_URL = '../stopwatchingus/';
    COOKIE_TIMEOUT = 20;
  } else {
    ASSET_URL = '//widget.taskforce.is/widget/stopwatchingus/';
    COOKIE_TIMEOUT = widget_config.cookieTimeout;
  }

  // Cookie helpers, taken from w3schools
  function setCookie(c_name,value,seconds) {
    var exdate = new Date(new Date().getTime() + seconds*1000);
    var c_value=escape(value) + ((seconds==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
  }

  function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); };
    if (c_start == -1) {
      c_value = null;
    } else {
      c_start = c_value.indexOf("=", c_start) + 1;
      var c_end = c_value.indexOf(";", c_start);
      if (c_end == -1) { c_end = c_value.length; }
      c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
  }

  // Define checks

  var checks = {
    betweenDate: function(startDate, endDate) {
      var startEpoch = startDate.getTime();
      var endEpoch = endDate.getTime();
      var currentEpoch = new Date().getTime();
      if(currentEpoch > startEpoch && currentEpoch < endEpoch) {
        return true;
      } else {
        return false;
      }
    },
    isMobile: function() {
      var ismobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i);
      return ismobile ? false : true;
    },
    hasSeenCampaign: function (cookieName) {
      var cookie = getCookie(cookieName)
      if(cookie === null) {
        return false;
      } else {
        return true
      }
    },
    nearDC: function (callback) {
      window.nearDC = callback;
      var script = document.createElement('script');
      script.src = '//geoip.taskforce.is/?callback=nearDC'
      document.getElementsByTagName('head')[0].appendChild(script);
    }
  }

  // Define campaigns

  var campaign = {
    stopwatchingus: {
      cookieName: 'stopwatchingus_hasseen6',

      // Months start at zero, so October = 9
      startDate: new Date(2013, 9, 15, 0),
      endDate: new Date(2013, 9, 26, 12),
      hide: function (el, callback) {
        document.body.removeChild(el);
        setCookie(active_campaign.cookieName, 'true', COOKIE_TIMEOUT);
        if(callback) { callback(); };
      },
      styles: {
        banner: {
          campaign_container: 'position:fixed;width:100%;bottom:0;z-index:100; padding: 0 20px;',
          iframe_container: 'position: relative; height: 100px; max-width:1201px; margin: 0px auto 8px auto; background: #444;border-radius: 10px;',
          iframe: 'width: 100%;height: 100%;border: 0;margin:0;padding:0;border-radius: 10px;',
          closeButton: 'border: 0;height: 28px;width: 28px;cursor: pointer;position: absolute;top:33px;right:20px;background: url("' + ASSET_URL +'images/close-button.png");'
        },
        dev: {
          campaign_container: 'position:fixed;width:100%;bottom:0;z-index:100; padding: 0 20px;',
          iframe_container: 'position: relative; height: 100px; max-width:1201px; margin: 0px auto 8px auto; background: #444;border-radius: 10px;',
          iframe: 'width: 100%;height: 100%;border: 0;margin:0;padding:0;border-radius: 10px;',
          closeButton: 'border: 0;height: 28px;width: 28px;cursor: pointer;position: absolute;top:33px;right:20px;background: url("' + ASSET_URL +'images/close-button.png");'
        },
        strip: {
          campaign_container: 'position:fixed;width:100%;bottom:0;opacity:1;z-index:100;',
          iframe_container: 'position:relative;height:50px;margin:0 20px 0px 20px;background:#444;border-radius:10px 10px 0 0;',
          iframe: 'width:100%;height:100%;border:0;margin:0;padding:0;border-radius:10px;',
          closeButton: 'border:0;height:28px;width:28px;cursor:pointer;position:absolute;top:11px;right:10px;background:url("' + ASSET_URL +'images/close-button.png");'
        },
        modal: {
          overlay: 'position:fixed; background:#000; width:100%; height:100%;z-index:30;top:0; left:0; opacity:0.5;-moz-opacity: 0.50;filter: alpha(opacity=50);',
          campaign_container: 'position:fixed;left:50%;margin-left:-250px;margin-top:40px;width:500px;top:0;opacity:1;z-index:100;',
          iframe_container: 'position:relative;height:365px; width:500px;background:#444;border-radius:10px;',
          iframe: 'width:100%;height:100%;border:0;margin:0;padding:0;border-radius:10px;',
          closeButton: 'border:0;height:28px;width:28px;cursor:pointer;position:absolute;top:15px;right:15px;background:url("' + ASSET_URL +'images/close-button.png");'
        }
      },
      show: function () {

        var style = active_campaign.styles[active_campaign.config.show_style]

        if(style.overlay) {
          var overlay = document.createElement('div');
          overlay.style.cssText = style.overlay;
          document.body.appendChild(overlay);
        }

        // Create a container
        var campaign_container = document.createElement('div');
        campaign_container.style.cssText = style.campaign_container;

        // Create a container for the iframe so we can do padding and border-radius properly
        var iframe_container = document.createElement('div');
        iframe_container.style.cssText = style.iframe_container;

        // Append Iframe and campaign container to document
        campaign_container.appendChild(iframe_container);
        document.body.appendChild(campaign_container);

        var iframe = document.createElement('iframe');
        iframe.style.cssText = style.iframe;

        // Set the source of the iframe to the configured show_style type
        iframe.src = ASSET_URL + active_campaign.config.show_style + '.html';
        iframe_container.appendChild(iframe);

        // Setup a close button
        var closeButton = document.createElement('button');
        closeButton.style.cssText = style.closeButton;
        iframe_container.appendChild(closeButton);
        closeButton.onclick = function() {
          active_campaign.hide(campaign_container);
          if(style.overlay) {
            document.body.removeChild(overlay);
          }
        }

      },
      init: function (config) {
        active_campaign.config = config;
        // Check cookie for this campaign
        if(checks.hasSeenCampaign(active_campaign.cookieName)) {
          return false;
        }

        // Check between date
        if(!checks.betweenDate(active_campaign.startDate, active_campaign.endDate) || active_campaign.config.disableDate) {
          return false;
        }

        // Check if is mobile
        if(!checks.isMobile()){
          return false;
        }

        // Check if they are near Washington?
        if(active_campaign.config.disableGeo) {
          active_campaign.show();
        } else {
          checks.nearDC(function (res) {
            if(res.kilometersFromDC <= 700) {
              active_campaign.show();
            }
          })
        }
      }
    }
  }

  // Load campaign if exist

  if(typeof campaign[widget_config.campaign] !== 'undefined') {
    active_campaign = campaign[widget_config.campaign];
    active_campaign.init(widget_config);
  } else {
    return false;
  }

})(window, _tfrce_config);
<|endoftext|>


<commit_before>window.customElements=function(){function t(){}var e={registrants:{}};return t.define=function(t,e){console.log("Snuggsi definition")("loading"===document.readyState)&&document.addEventListener("DOMContentLoaded",this.register(t,e))},e.registrants.get=function(){return registrants},t.register=function(t,e){var n=this;return this.registrants[t]=e,function(e){var o=document.body.querySelectorAll(t);[].slice.call(o).map(n.upgrade)}},t.upgrade=function(t){console.log("ugrading element",t.localName)},Object.defineProperties(t,e),t}()&&null;var HTMLCustomElement=function(){return new String("snuggsi HTMLCustomElement")},Foo=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(HTMLElement),HTMLLinkElement=function(t){var e=new Event("load"),n=document.querySelector("link[href*="+t+"][rel=import]");return(e.target=n)&&window.HTMLImports&&!window.HTMLImports.useNative&&HTMLImports.whenReady(function(t){return n.dispatchEvent(e)}),n},TokenList=function(t){this.sift(t).map(this.tokenize,this)};TokenList.prototype.tokenize=function(t){var e=this;(t.text=t.textContent).match(/([^{]*?)(\w|#)(?=\})/g).map(function(t){return function(n){return(e[n]=e[n]||[]).push(t)}}(t))},TokenList.prototype.sift=function(t){for(var e=[],n=/{(\w+|#)}/,o=function(t){return n.test(t.textContent)&&e.push(t)},r=function(t){return Array.from(t).map(function(t){return n.test(t.value)&&e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.nodeType===Node.TEXT_NODE?o(t):r(t.attributes)&&NodeFilter.FILTER_REJECT});i.nextNode(););return e},TokenList.prototype.bind=function(t){var e=this;Object.keys(this).map(function(t){return e[t].map(function(e){return(e.textContent=e.text)&&t})});for(var n in e)e[n].map(function(e,n){return void 0===n&&(n="{"+e+"}"),function(o){return o.textContent=o.textContent.replace(n,t[e])}}(n))};var Template=HTMLTemplateElement=function(t){return t="string"==typeof t?document.querySelector("template[name="+t+"]"):t,Object.assign(t,{bind:function(t){var e="",n=this.innerHTML,o=(u=[]).concat.apply(u,[t]),r=Object.keys(o[0]||[]).concat(["#","self"]),i=r.map(function(t){return"{"+t+"}"}),c=document.createElement("template");(this.dependents||[]).map(function(t){return t.remove()});for(var p=0;p<o.length;p++)e+=function(t,e){var o=n;(t="object"==typeof t?t:{self:t})["#"]=e;for(var c=0;c<i.length;c++)o=o.split(i[c]).join(t[r[c]]);return o}(o[p],p);c.innerHTML=e,this.dependents=Array.from(c.content.childNodes)(s=this).after.apply(s,this.dependents);var u,s}})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n,o){return void 0===o&&(o=!0),(n.prevent=function(t){return(o=!1)&&n.preventDefault()})&&!1!==t.call(e,n)&&o&&e.render()}},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];t=(o=[]).concat.apply(o,[t]);return Array.from(this.querySelectorAll(e.reduce(function(e,n){return e+n+t.shift()},t.shift())));var o},e.prototype.select=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return(n=this).selectAll.apply(n,t)[0];var n},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(e,n){(n=e.target)&&this.mirror(n.import.querySelector("template")),t.prototype.onconnect&&t.prototype.onconnect.call(this),this.tokens=new TokenList(this),this.render()},e.prototype.reflect=function(t,e){(e=(t.match(/^on(.+)$/)||[])[1])&&Object.keys(HTMLElement.prototype).includes(t)&&this.on(e,this[t])},e.prototype.register=function(t){var e=this;Array.from(t.attributes).map(function(t){return t.name}).filter(function(t){return/^on/.test(t)}).map(function(n,o){return(o=/{\s*(\w+)\s*}/.exec(t[n]))&&(o=e[(o||[])[1]])&&(t[n]=e.renderable(o))})},e}(t)},Custom=function(t){return function(e){function n(){var n=this;e.call(this);var o=Object.getOwnPropertyDescriptors(t.prototype);Object.keys(o).map(function(t){return"function"==typeof o[t].value&&(n[t]=n[t].bind(n))}),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.context={},this.initialize&&this.initialize()}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(t){(t=HTMLLinkElement(this.tagName.toLowerCase()))?t.addEventListener("load",this.onconnect.bind(this)):this.onconnect(new Event("load"))},n.prototype.render=function(){var t=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(e){return new Template(e).bind(t[e])}),Array.from(this.selectAll("*")).concat([this]).map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n.prototype.mirror=function(t,e){var n=this;t=t.cloneNode(!0),e=function(e,n,o){return(n=e.getAttribute("slot"))&&(o=t.content.querySelector("slot[name="+n+"]")).parentNode.replaceChild(e,o)};for(var o=0,r=n.selectAll("[slot]");o<r.length;o+=1)e(r[o]);Array.from(t.attributes).filter(function(t){return!n.attributes[t.name]}).map(function(t){return n.setAttribute(t.name,t.value)}),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t){var e="string"==typeof t?HTMLCustomElement:HTMLElement;return function(n){console.warn("tag",t),console.warn("Element",n),console.warn("Element.prototype",n.prototype),console.warn("Element.prototype.constructor",n.prototype.constructor),n.prototype.constructor=e,console.warn("Element.prototype.constructor",n.prototype.constructor),console.warn("Element.constructor",n.constructor),console.warn("constructor",e),console.warn("constructor.prototype",e.prototype)(o=window.customElements).define.apply(o,(r=[]).concat.apply(r,[t]).concat([Custom(n)]));var o,r}};Element.prototype=ElementPrototype;<commit_msg>:muscle: bump MINIFIED distribution dist/snuggsi.min.js<commit_after>!function(t,e){void 0===e&&(e=t.define.bind(t));var n=function(){};n.define=function(t,e,n){console.warn("Snuggsi",t,n,e),"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",this.register(t,e))},n.register=function(t,n){var o=this;return this[t]=n,e&&e(t,this[t]),function(e){var n=document.body.querySelectorAll(t);[].slice.call(n).map(o.upgrade)}},n.upgrade=function(t){console.log("ugrading element",t.localName)},t.define=n.define.bind(n)}(window.customElements=window.customElements||{});var HTMLCustomElement=function(){return new String("snuggsi HTMLCustomElement")},HTMLLinkElement=function(t){var e=new Event("load"),n=document.querySelector("link[href*="+t+"][rel=import]");return(e.target=n)&&window.HTMLImports&&!window.HTMLImports.useNative&&HTMLImports.whenReady(function(t){return n.dispatchEvent(e)}),n},TokenList=function(t){this.sift(t).map(this.tokenize,this)};TokenList.prototype.tokenize=function(t){var e=this;(t.text=t.textContent).match(/([^{]*?)(\w|#)(?=\})/g).map(function(t){return function(n){return(e[n]=e[n]||[]).push(t)}}(t))},TokenList.prototype.sift=function(t){for(var e=[],n=/{(\w+|#)}/,o=function(t){return n.test(t.textContent)&&e.push(t)},r=function(t){return Array.from(t).map(function(t){return n.test(t.value)&&e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.nodeType===Node.TEXT_NODE?o(t):r(t.attributes)&&NodeFilter.FILTER_REJECT});i.nextNode(););return e},TokenList.prototype.bind=function(t){var e=this;Object.keys(this).map(function(t){return e[t].map(function(e){return(e.textContent=e.text)&&t})});for(var n in e)e[n].map(function(e,n){return void 0===n&&(n="{"+e+"}"),function(o){return o.textContent=o.textContent.replace(n,t[e])}}(n))};var Template=HTMLTemplateElement=function(t){return t="string"==typeof t?document.querySelector("template[name="+t+"]"):t,Object.assign(t,{bind:function(t){var e="",n=this.innerHTML,o=(a=[]).concat.apply(a,[t]),r=Object.keys(o[0]||[]).concat(["#","self"]),i=r.map(function(t){return"{"+t+"}"}),c=document.createElement("template");(this.dependents||[]).map(function(t){return t.remove()});for(var u=0;u<o.length;u++)e+=function(t,e){var o=n;(t="object"==typeof t?t:{self:t})["#"]=e;for(var c=0;c<i.length;c++)o=o.split(i[c]).join(t[r[c]]);return o}(o[u],u);c.innerHTML=e,this.dependents=Array.from(c.content.childNodes)(p=this).after.apply(p,this.dependents);var a,p}})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n,o){return void 0===o&&(o=!0),(n.prevent=function(t){return(o=!1)&&n.preventDefault()})&&!1!==t.call(e,n)&&o&&e.render()}},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];t=(o=[]).concat.apply(o,[t]);return Array.from(this.querySelectorAll(e.reduce(function(e,n){return e+n+t.shift()},t.shift())));var o},e.prototype.select=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return(n=this).selectAll.apply(n,t)[0];var n},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(e,n){(n=e.target)&&this.mirror(n.import.querySelector("template")),t.prototype.onconnect&&t.prototype.onconnect.call(this),this.tokens=new TokenList(this),this.render()},e.prototype.reflect=function(t,e){(e=(t.match(/^on(.+)$/)||[])[1])&&Object.keys(HTMLElement.prototype).includes(t)&&this.on(e,this[t])},e.prototype.register=function(t){var e=this;Array.from(t.attributes).map(function(t){return t.name}).filter(function(t){return/^on/.test(t)}).map(function(n,o){return(o=/{\s*(\w+)\s*}/.exec(t[n]))&&(o=e[(o||[])[1]])&&(t[n]=e.renderable(o))})},e}(t)},Custom=function(t){return function(e){function n(){var n=this;e.call(this);var o=Object.getOwnPropertyDescriptors(t.prototype);Object.keys(o).map(function(t){return"function"==typeof o[t].value&&(n[t]=n[t].bind(n))}),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.context={},this.initialize&&this.initialize()}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(t){(t=HTMLLinkElement(this.tagName.toLowerCase()))?t.addEventListener("load",this.onconnect.bind(this)):this.onconnect(new Event("load"))},n.prototype.render=function(){var t=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(e){return new Template(e).bind(t[e])}),Array.from(this.selectAll("*")).concat([this]).map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n.prototype.mirror=function(t,e){var n=this;t=t.cloneNode(!0),e=function(e,n,o){return(n=e.getAttribute("slot"))&&(o=t.content.querySelector("slot[name="+n+"]")).parentNode.replaceChild(e,o)};for(var o=0,r=n.selectAll("[slot]");o<r.length;o+=1)e(r[o]);Array.from(t.attributes).filter(function(t){return!n.attributes[t.name]}).map(function(t){return n.setAttribute(t.name,t.value)}),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t){var e="string"==typeof t?HTMLCustomElement:HTMLElement;return function(n){console.warn("tag",t),console.warn("Element",n),console.warn("Element.prototype",n.prototype),console.warn("Element.prototype.constructor",n.prototype.constructor),console.warn("Element.constructor",n.constructor),console.warn("constructor",e),console.warn("constructor.prototype",e.prototype),(o=window.customElements).define.apply(o,(r=[]).concat.apply(r,[t]).concat([Custom(n)],[e]));var o,r}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>const EventEmitter = require("events").EventEmitter
const uwp = require("uwp")
uwp.projectNamespace("Windows") /* global Windows */
const debug = require("debug")("winble")
const _ = require("lodash")

const events = new EventEmitter()

module.exports = _.assign({},
  nobleBluetoothScanner(
    bluetoothScanner(
      deviceWatcher(new EventEmitter()),
      events)),
  lifecycle(events),
  bluetoothDeviceManager(events),
  events,
  {on: _.bind(EventEmitter.prototype.on, events)})

function nobleBluetoothScanner (bluetoothScanner) {
  return {startScanning: bluetoothScanner.start, stopScanning: bluetoothScanner.stop}
}

function bluetoothDeviceManager (eventEmitter) {
  const devices = {}

  return {connect, discoverServices, discoverCharacteristics, read, write, notify}

  function connect (peripheralUuid) {
    const uwpBluetoothAddress = Number("0x" + peripheralUuid)
    Windows.Devices.Bluetooth.BluetoothLEDevice.fromBluetoothAddressAsync(uwpBluetoothAddress).done(
      function (bluetoothDevice) {
        debug("Bluetooth device connected", peripheralUuid)
        devices[peripheralUuid] = bluetoothDevice
        eventEmitter.emit("connect", peripheralUuid, null)
      },
      function (err) {
        debug("Connection failed to Bluetooth device", peripheralUuid)
        eventEmitter.emit("connect", peripheralUuid, err)
      })
  }

  function discoverServices (peripheralUuid, serviceUuids) {
    const discoveredServiceUuids = _(devices[peripheralUuid].gattServices)
      .map("uuid")
      .map(stripDashes)
      .value()
    const returnedServiceUuids = serviceUuids ?
      _.intersection(serviceUuids, discoveredServiceUuids) :
      discoveredServiceUuids
    eventEmitter.emit("servicesDiscover", peripheralUuid, returnedServiceUuids)
  }

  function discoverCharacteristics (peripheralUuid, serviceUuid, characteristicUuids) {
    const discoveredCharacteristicUuids = _(devices[peripheralUuid])
      .thru(device => device.getGattService(serviceUuid))
      .thru(service => service.getAllCharacteristics())
      .map("uuid")
      .map(stripDashes)
      .value()
    const filteredCharacteristicUuids = characteristicUuids ?
      _.intersection(characteristicUuids, filteredCharacteristicUuids) :
      discoveredCharacteristicUuids
    const returnedCharacteristicUuids =
      _.map(filteredCharacteristicUuids, characteristicUuid => ({uuid: characteristicUuid, properties: []}))
    eventEmitter.emit("characteristicsDiscover", peripheralUuid, serviceUuid, returnedCharacteristicUuids)
  }

  function read (peripheralUuid, serviceUuid, characteristicUuid) {
    devices[peripheralUuid].getGattService(serviceUuid).getCharacteristics(characteristicUuid)[0]
      .readValueAsync()
      .done(data => eventEmitter.emit("read", peripheralUuid, serviceUuid, characteristicUuid, data, false))
  }

  function write (peripheralUuid, serviceUuid, characteristicUuid, data, withoutResponse) {
    // TODO: what is withoutResponse for?
    devices[peripheralUuid].getGattService(serviceUuid).getCharacteristics(characteristicUuid)[0]
      .writeValueAsync(Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data))
      .done(() => eventEmitter.emit("write", peripheralUuid, serviceUuid, characteristicUuid))
  }

  function notify (peripheralUuid, serviceUuid, characteristicUuid, notify) {
    // TODO: is there anything else to do here?
    eventEmitter.emit("notify", peripheralUuid, serviceUuid, characteristicUuid, notify)
  }
}

function lifecycle (eventEmitter) {
  return {init}

  function init () {
    process.nextTick(powerOn)
    process.on("SIGINT", onSigInt)
    process.on("exit", onProcessExit)
  }

  function powerOn () {
    debug("powered on")
    eventEmitter.emit("stateChange", "poweredOn")
  }

  function onSigInt () {
    // copied over from https://github.com/sandeepmistry/noble/blob/master/lib/hci-socket/bindings.js#L86
    var sigIntListeners = process.listeners("SIGINT")
    if (sigIntListeners[sigIntListeners.length - 1] === onSigInt) {
      // we are the last listener, so exit
      // this will trigger onProcessExit, and clean up
      process.exit(1)
    }
  }

  function onProcessExit () {
    uwp.close()
    debug("uwp closed")
  }
}

function bluetoothScanner (deviceWatcher, eventEmitter) {
  deviceWatcher.onNewDevice(onNewDevice)
  let scanning = false

  return {start, stop}

  function start () {
    scanning = true
    if (deviceWatcher.startable()) deviceWatcher.start()
  }

  function stop () {
    scanning = false
  }

  function onNewDevice (device) {
    if (!scanning) return
    if (device.id.indexOf("BTHLEDevice") < 0) return // is this really trust-worthy?
    Windows.Devices.Bluetooth.BluetoothLEDevice.fromIdAsync(device.id).done(function (bluetoothDevice) {
      debug("discovered Bluetoothe Low Energy device:", device.id)
      eventEmitter.emit("discover",
        bluetoothDevice.bluetoothAddress.toString(16),
        bluetoothDevice.address,
        bluetoothDevice.addressType)
    })
  }
}

function deviceWatcher (eventEmitter) {
  const windowsDeviceWatcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher()
  windowsDeviceWatcher.addEventListener("added", device => eventEmitter.emit("onNewDevice", device))

  const statuses = {created: 0, started: 1, enumerationCompleted: 2, stopping: 3, stopped: 4, aborted: 5}
  const startableStatuses = _(statuses).pick("created", "stopped", "aborted").values()

  return {
    startable: () => _.includes(startableStatuses, windowsDeviceWatcher.status),
    start: () => windowsDeviceWatcher.start(),
    stop: () => windowsDeviceWatcher.stop(),
    onNewDevice: callback => eventEmitter.on("onNewDevice", callback),
  }
}

function stripDashes (uuid) {
  return uuid.split("-").join("")
}
<commit_msg>feat: more verbose logging<commit_after>const EventEmitter = require("events").EventEmitter
const uwp = require("uwp")
uwp.projectNamespace("Windows") /* global Windows */
const debug = require("debug")("winble")
const _ = require("lodash")

const events = withLoggingEmits(new EventEmitter())

module.exports = _.assign({},
  nobleBluetoothScanner(
    bluetoothScanner(
      deviceWatcher(new EventEmitter()),
      events)),
  lifecycle(events),
  withLoggingMethods(bluetoothDeviceManager(events)),
  events,
  {on: _.bind(EventEmitter.prototype.on, events)})

function nobleBluetoothScanner (bluetoothScanner) {
  return {startScanning: bluetoothScanner.start, stopScanning: bluetoothScanner.stop}
}

function bluetoothDeviceManager (eventEmitter) {
  const devices = {}

  return {connect, discoverServices, discoverCharacteristics, read, write, notify}

  function connect (peripheralUuid) {
    const uwpBluetoothAddress = Number("0x" + peripheralUuid)
    Windows.Devices.Bluetooth.BluetoothLEDevice.fromBluetoothAddressAsync(uwpBluetoothAddress).done(
      function (bluetoothDevice) {
        debug("Bluetooth device connected", peripheralUuid)
        devices[peripheralUuid] = bluetoothDevice
        eventEmitter.emit("connect", peripheralUuid, null)
      },
      function (err) {
        debug("Connection failed to Bluetooth device", peripheralUuid)
        eventEmitter.emit("connect", peripheralUuid, err)
      })
  }

  function discoverServices (peripheralUuid, serviceUuids) {
    const discoveredServiceUuids = _(devices[peripheralUuid].gattServices)
      .map("uuid")
      .map(stripDashes)
      .value()
    const returnedServiceUuids = serviceUuids ?
      _.intersection(serviceUuids, discoveredServiceUuids) :
      discoveredServiceUuids
    eventEmitter.emit("servicesDiscover", peripheralUuid, returnedServiceUuids)
  }

  function discoverCharacteristics (peripheralUuid, serviceUuid, characteristicUuids) {
    const discoveredCharacteristicUuids = _(devices[peripheralUuid])
      .thru(device => device.getGattService(serviceUuid))
      .thru(service => service.getAllCharacteristics())
      .map("uuid")
      .map(stripDashes)
      .value()
    const filteredCharacteristicUuids = characteristicUuids ?
      _.intersection(characteristicUuids, filteredCharacteristicUuids) :
      discoveredCharacteristicUuids
    const returnedCharacteristicUuids =
      _.map(filteredCharacteristicUuids, characteristicUuid => ({uuid: characteristicUuid, properties: []}))
    eventEmitter.emit("characteristicsDiscover", peripheralUuid, serviceUuid, returnedCharacteristicUuids)
  }

  function read (peripheralUuid, serviceUuid, characteristicUuid) {
    devices[peripheralUuid].getGattService(serviceUuid).getCharacteristics(characteristicUuid)[0]
      .readValueAsync()
      .done(data => eventEmitter.emit("read", peripheralUuid, serviceUuid, characteristicUuid, data, false))
  }

  function write (peripheralUuid, serviceUuid, characteristicUuid, data, withoutResponse) {
    // TODO: what is withoutResponse for?
    devices[peripheralUuid].getGattService(serviceUuid).getCharacteristics(characteristicUuid)[0]
      .writeValueAsync(Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data))
      .done(() => eventEmitter.emit("write", peripheralUuid, serviceUuid, characteristicUuid))
  }

  function notify (peripheralUuid, serviceUuid, characteristicUuid, notify) {
    // TODO: is there anything else to do here?
    eventEmitter.emit("notify", peripheralUuid, serviceUuid, characteristicUuid, notify)
  }
}

function lifecycle (eventEmitter) {
  return {init}

  function init () {
    process.nextTick(powerOn)
    process.on("SIGINT", onSigInt)
    process.on("exit", onProcessExit)
  }

  function powerOn () {
    debug("powered on")
    eventEmitter.emit("stateChange", "poweredOn")
  }

  function onSigInt () {
    // copied over from https://github.com/sandeepmistry/noble/blob/master/lib/hci-socket/bindings.js#L86
    var sigIntListeners = process.listeners("SIGINT")
    if (sigIntListeners[sigIntListeners.length - 1] === onSigInt) {
      // we are the last listener, so exit
      // this will trigger onProcessExit, and clean up
      process.exit(1)
    }
  }

  function onProcessExit () {
    uwp.close()
    debug("uwp closed")
  }
}

function bluetoothScanner (deviceWatcher, eventEmitter) {
  deviceWatcher.onNewDevice(onNewDevice)
  let scanning = false

  return {start, stop}

  function start () {
    scanning = true
    if (deviceWatcher.startable()) deviceWatcher.start()
  }

  function stop () {
    scanning = false
  }

  function onNewDevice (device) {
    if (!scanning) return
    if (device.id.indexOf("BTHLEDevice") < 0) return // is this really trust-worthy?
    Windows.Devices.Bluetooth.BluetoothLEDevice.fromIdAsync(device.id).done(function (bluetoothDevice) {
      debug("discovered Bluetoothe Low Energy device:", device.id)
      eventEmitter.emit("discover",
        bluetoothDevice.bluetoothAddress.toString(16),
        bluetoothDevice.address,
        bluetoothDevice.addressType)
    })
  }
}

function deviceWatcher (eventEmitter) {
  const windowsDeviceWatcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher()
  windowsDeviceWatcher.addEventListener("added", device => eventEmitter.emit("onNewDevice", device))

  const statuses = {created: 0, started: 1, enumerationCompleted: 2, stopping: 3, stopped: 4, aborted: 5}
  const startableStatuses = _(statuses).pick("created", "stopped", "aborted").values()

  return {
    startable: () => _.includes(startableStatuses, windowsDeviceWatcher.status),
    start: () => windowsDeviceWatcher.start(),
    stop: () => windowsDeviceWatcher.stop(),
    onNewDevice: callback => eventEmitter.on("onNewDevice", callback),
  }
}

function stripDashes (uuid) {
  return uuid.split("-").join("")
}

function withLoggingMethods (obj) {
  _.each(_.functions(obj), function (functionKey) {
    obj[functionKey] = logging(obj[functionKey])
  })
  return obj
}

function logging (f) {
  return function (...args) {
    debug(f.name, ...args)
    const returnValue = f(...args)
    debug(`end ${f.name}`, returnValue)
  }
}

function withLoggingEmits (eventEmitter) {
  const originalEmit = _.bind(eventEmitter.emit, eventEmitter)
  eventEmitter.emit = function (...args) {
    debug("emitting", ...args)
    originalEmit(...args)
  }
  return eventEmitter
}
<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var fs = require('fs'),
    archiver = require('archiver'),
    path = require('path'),
    util = require('util');

/**
 * Middleware to compress the changes to the project as a delta update
 *
 * Options:
 *
 *   - `options` {Object}
 *   - `options.req` {Object} is the request object (for session access).
 */

module.exports = function(options) {
    return function(req, res, next) {
        if (req.url.indexOf('/__api__/update') === 0) {
            options.req = req;

            var resPath = path.join(__dirname, '../../res/middleware');

            // helper function that returns the scripts to inject into each HTML page
            var injectScript = function() {
                var deployScript = path.join(resPath, 'deploy.js'),
                    autoreloadScript = path.join(resPath, 'autoreload.js'),
                    consoleScript = path.join(resPath, 'consoler.js'),
                    homepageScript = path.join(resPath, 'homepage.js'),
                    refreshScript = path.join(resPath, 'refresh.js');

                var scripts = fs.readFileSync(deployScript) +
                              fs.readFileSync(autoreloadScript) +
                              fs.readFileSync(consoleScript) +
                              fs.readFileSync(homepageScript) +
                              fs.readFileSync(refreshScript);

                // replace default server address with this server address
                return scripts.replace(/127\.0\.0\.1:3000/g, options.req.headers.host);
            };

            var Transform = require('stream').Transform;
            util.inherits(InjectHTML, Transform);

            function InjectHTML(options) {
                if (!(this instanceof InjectHTML)) {
                    return new InjectHTML(options);
                }

                Transform.call(this, options);
            };

            InjectHTML.prototype._transform = function (chunk, encoding, callback) {
                var newChunk = chunk.toString().replace('', injectScript() + '\n');
                this.push(newChunk);
                callback();
            };

            var archive = archiver('zip', { store: false });

            archive.on('error', function(err) {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end();
            });

            res.writeHead(200, { 'Content-Type': 'application/zip' } );
            archive.pipe(res);

            if(!req.session.lastFlush) {
                req.session.lastFlush = 0;
            }

            // first find where the indices we need to update in options.filesToUpdate
            var lastUpdatedIndex = 0;
            for (var i = 0; i < options.filesToUpdate.length; i++) {
                if (req.session.lastFlush < options.filesToUpdate[i][0]) {
                    lastUpdatedIndex = i;
                }
            }

            for (var i = lastUpdatedIndex; i < options.filesToUpdate.length; i++) {
                var filename = options.filesToUpdate[i][1];
                var output = filename.split(process.cwd())[1];

                if (path.extname(filename) === '.html') {
                    var htmlStreamFile = fs.createReadStream(filename);
                    var injectorTransform = new InjectHTML();
                    htmlStreamFile.pipe(injectorTransform);

                    archive.append(injectorTransform, { name: output });
                }
                else {
                    archive.append(fs.createReadStream(filename), { name: output });
                }
            }

            req.session.lastFlush = Date.now();

            archive.finalize();

        }
        else {
            next();
        }
    }
};<commit_msg>[#127] - need to fix this in the update middleware as well<commit_after>/*!
 * Module dependencies.
 */

var fs = require('fs'),
    archiver = require('archiver'),
    path = require('path'),
    util = require('util');

/**
 * Middleware to compress the changes to the project as a delta update
 *
 * Options:
 *
 *   - `options` {Object}
 *   - `options.req` {Object} is the request object (for session access).
 */

module.exports = function(options) {
    return function(req, res, next) {
        if (req.url.indexOf('/__api__/update') === 0) {
            options.req = req;

            var resPath = path.join(__dirname, '../../res/middleware');

            // helper function that returns the scripts to inject into each HTML page
            var injectScript = function() {
                var deployScript = path.join(resPath, 'deploy.js'),
                    autoreloadScript = path.join(resPath, 'autoreload.js'),
                    consoleScript = path.join(resPath, 'consoler.js'),
                    homepageScript = path.join(resPath, 'homepage.js'),
                    refreshScript = path.join(resPath, 'refresh.js');

                var scripts = fs.readFileSync(deployScript) +
                              fs.readFileSync(autoreloadScript) +
                              fs.readFileSync(consoleScript) +
                              fs.readFileSync(homepageScript) +
                              fs.readFileSync(refreshScript);

                // replace default server address with this server address
                return scripts.replace(/127\.0\.0\.1:3000/g, options.req.headers.host);
            };

            var Transform = require('stream').Transform;
            util.inherits(InjectHTML, Transform);

            function InjectHTML(options) {
                if (!(this instanceof InjectHTML)) {
                    return new InjectHTML(options);
                }

                Transform.call(this, options);
            };

            InjectHTML.prototype._transform = function (chunk, encoding, callback) {
                var newChunk = chunk.toString().replace('', injectScript() + '\n');
                this.push(newChunk);
                callback();
            };

            var archive = archiver('zip', { store: false });

            archive.on('error', function(err) {
                console.error('Error, could not complete to zip up the app:');
                console.error(err.stack);
                res.end();
            });

            res.writeHead(200, { 'Content-Type': 'application/zip' } );
            archive.pipe(res);

            if(!req.session.lastFlush) {
                req.session.lastFlush = 0;
            }

            // first find where the indices we need to update in options.filesToUpdate
            var lastUpdatedIndex = 0;
            for (var i = 0; i < options.filesToUpdate.length; i++) {
                if (req.session.lastFlush < options.filesToUpdate[i][0]) {
                    lastUpdatedIndex = i;
                }
            }

            for (var i = lastUpdatedIndex; i < options.filesToUpdate.length; i++) {
                var filename = options.filesToUpdate[i][1];
                var output = filename.split(process.cwd())[1];

                if (path.extname(filename) === '.html') {
                    var htmlStreamFile = fs.createReadStream(filename);
                    var injectorTransform = new InjectHTML();
                    htmlStreamFile.pipe(injectorTransform);

                    archive.append(injectorTransform, { name: output });
                }
                else {
                    archive.append(fs.createReadStream(filename), { name: output });
                }
            }

            req.session.lastFlush = Date.now();

            archive.finalize();

        }
        else {
            next();
        }
    }
};<|endoftext|>


<commit_before>define(['view',
        'anchor/class'],
function(View, clazz) {

  function Wizard(el, options) {
    Wizard.super_.call(this, el, options);
    this._steps = [];
    this._i = 0;

    var self = this
      , el = this.el;

    el.find('.prev').addClass('disabled');
    el.find('.next').on('click', function() {
      if (el.find('.next').hasClass('disabled')) return false;
      if (self._i == self._steps.length - 1) { self.emit('done'); return false; }
      self._goto(self._i + 1, self._i);
      return false;
    });
    el.find('.prev').on('click', function() {
      if (el.find('.prev').hasClass('disabled')) return false;
      if (self._i == 0) return false;
      self._goto(self._i - 1, self._i);
      return false;
    });
  }
  clazz.inherits(Wizard, View);

  Wizard.prototype.step = function(name, el) {
    if (typeof name != 'string') {
      el = name;
      name = undefined;
    }

    if (this._steps.length) el.addClass('hide');
    this.el.find('.wizard-body').append(el);
    this._steps.push({ el: el, name: name });
    return this;
  };

  Wizard.prototype._goto = function(i, pi) {
    this._i = i;
    var step = this._steps[i];
    this.emit('next', step.name);
    this._steps[pi].el.addClass('hide');
    this._steps[i].el.removeClass('hide');
    if (i == 0) this.el.find('.prev').addClass('disabled');
    else this.el.find('.prev').removeClass('disabled');
  }

  return Wizard;
});
<commit_msg>Implement delegatable next handling.<commit_after>define(['view',
        'anchor/class'],
function(View, clazz) {

  function Wizard(el, options) {
    Wizard.super_.call(this, el, options);
    this._steps = [];
    this._i = 0;

    var self = this
      , el = this.el;

    el.find('.prev').addClass('disabled');
    el.find('.next').on('click', function() {
      if (el.find('.next').hasClass('disabled')) return false;
      self.next(true);
      return false;
    });
    el.find('.prev').on('click', function() {
      if (el.find('.prev').hasClass('disabled')) return false;
      self.prev();
      return false;
    });
  }
  clazz.inherits(Wizard, View);

  Wizard.prototype.step = function(name, el) {
    if (typeof name != 'string') {
      el = name;
      name = undefined;
    }

    if (this._steps.length) el.addClass('hide');
    this.el.find('.wizard-body').append(el);
    this._steps.push({ el: el, name: name });
    return this;
  };

  Wizard.prototype.next = function(ask) {
    if (this._i == this._steps.length - 1) { this.emit('done'); return; }
    var step = this._steps[this._i];
    var go = (ask && this.delegate && this.delegate.willNext) ? this.delegate.willNext(step.name, this._i) : true;
    if (go) this._goto(this._i + 1, this._i);
  }

  Wizard.prototype.prev = function() {
    if (this._i == 0) return;
    this._goto(this._i - 1, this._i);
  }

  Wizard.prototype._goto = function(i, pi) {
    this._i = i;
    var step = this._steps[i];
    this.emit('step', step.name, i);
    this._steps[pi].el.addClass('hide');
    this._steps[i].el.removeClass('hide');
    if (i == 0) this.el.find('.prev').addClass('disabled');
    else this.el.find('.prev').removeClass('disabled');
  }

  return Wizard;
});
<|endoftext|>


<commit_before>'use strict';
const successCode = require('./http-response');
const HttpRequester = require('./http-requester');

class HttpInterface {
    constructor(log, baseUrl, tracker) {
        this.log = log;
        this.baseUrl = baseUrl;
        this.httpRequester = httpRequester;
        this.tracker = tracker;
        this.vendorName = 'HttpInterface';
    }
    request(options, callback) {
        let method = options.method;
        let url = this.baseUrl + '/' + options.uri,
            qs = options.qs || {},
            json = options.json;

        const handleResponse = (err, response) => {
            if (err) {
                this.log.warn(`[${this.vendorName}] `, err);
                this.log.warn(`[${this.vendorName} Request Params] `, options);
                if (this.tracker) {
                    this.tracker.track(`[${this.vendorName} API Error]`, { error: err, requestParams: options });
                }

                callback(err);
            } else if (!successCode(response.statusCode)) {
                this.log.warn(`[${this.vendorName}] received bad status code: ` + response.statusCode, response.body);
                this.log.warn(`[${this.vendorName} Request Params] `, options);
                if (this.tracker) {
                    this.tracker.track(`[${this.vendorName} API Error]`, {
                        error: response.body,
                        statusCode: response.statusCode,
                        requestParams: options
                    });
                }

                callback({
                    status: response.statusCode,
                    body: response.body
                });
            } else {
                let data;
                try {
                    if (typeof(response.body) === 'string') {
                        data = JSON.parse(response.body);
                    }
                } catch (e) {
                    data = response.body;
                }
                callback(null, data);
            }
        };

        if (json) {
            this.httpRequester.sendJson(method, url, null, qs, json, handleResponse);
        } else {
            this.httpRequester.send(method, url, null, qs, null, null, handleResponse);
        }
    }
}

module.exports = HttpInterface;
<commit_msg>updating http interface to accomodate headers and other clean up<commit_after>'use strict';
const successCode = require('./http-response');
const HttpRequester = require('./http-requester');

class HttpInterface {
    constructor(log, baseUrl, tracker) {
        this.log = log;
        this.baseUrl = baseUrl;
        this.httpRequester = HttpRequester;
        this.tracker = tracker;
        this.vendorName = 'HttpInterface';
    }
    request(options, callback) {
        let method = options.method;
        let url = this.baseUrl + '/' + options.uri,
            headers = options.headers,
            qs = options.qs || {},
            json = options.json,
            form = options.form;

        const handleResponse = (err, response) => {
            if (err) {
                this.log.warn(`[${this.vendorName}] `, err);
                this.log.warn(`[${this.vendorName} Request Params] `, options);
                if (this.tracker) {
                    this.tracker.track(`[${this.vendorName} API Error]`, { error: err, requestParams: options });
                }

                callback(err);
            } else if (!successCode(response.statusCode)) {
                this.log.warn(`[${this.vendorName}] received bad status code: ` + response.statusCode, response.body);
                this.log.warn(`[${this.vendorName} Request Params] `, options);
                if (this.tracker) {
                    this.tracker.track(`[${this.vendorName} API Error]`, {
                        error: response.body,
                        statusCode: response.statusCode,
                        requestParams: options
                    });
                }

                callback({
                    status: response.statusCode,
                    body: response.body
                });
            } else {
                let data;
                try {
                    if (typeof(response.body) === 'string') {
                        data = JSON.parse(response.body);
                    }
                } catch (e) {
                    data = response.body;
                }
                callback(null, data);
            }
        };

        if (json) {
            this.httpRequester.sendJson(method, url, headers, qs, json, handleReponse);
        } else if (form) {
            this.httpRequester.sendForm(method, url, headers, qs, form, handleReponse);
        } else {
            this.httpRequester.send(method, url, headers, qs, null, null, handleReponse);
        }
    }
}

module.exports = HttpInterface;
<|endoftext|>


<commit_before>var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");

  if (err) throw err;
  db.createCollection("customers", function(err, res) {
    if (err) throw err;
    console.log("Table created!");

});
});
<commit_msg>create tabelle<commit_after>var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/dbUnims";
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    console.log("Database created!");

         db.createCollection("Studenti", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Professori", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Amministratori", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Corsi", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Esami", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Corsi di laurea", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
               db.close();
          });

          db.createCollection("Scuole", function (err, res) {
              if (err) throw err;
              console.log("Table created!");
              db.close();
          });

    });
<|endoftext|>


<commit_before>/*
 * file.js: Simple file storage engine for nconf files
 *
 * (C) 2011, Charlie Robbins
 *
 */

var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    formats = require('../formats'),
    Memory = require('./memory').Memory;

//
// ### function File (options)
// #### @options {Object} Options for this instance
// Constructor function for the File nconf store, a simple abstraction
// around the Memory store that can persist configuration to disk.
//
var File = exports.File = function (options) {
  if (!options || !options.file) {
    throw new Error ('Missing required option `files`');
  }

  Memory.call(this, options);

  this.type   = 'file';
  this.file   = options.file;
  this.dir    = options.dir    || process.cwd();
  this.format = options.format || formats.json;
};

// Inherit from the Memory store
util.inherits(File, Memory);

//
// ### function save (value, callback)
// #### @value {Object} _Ignored_ Left here for consistency
// #### @callback {function} Continuation to respond to when complete.
// Saves the current configuration object to disk at `this.file`
// using the format specified by `this.format`.
//
File.prototype.save = function (value, callback) {
  if (!callback) {
    callback = value;
    value = null;
  }

  fs.writeFile(this.file, this.format.stringify(this.store), function (err) {
    return err ? callback(err) : callback();
  });
};

//
// ### function saveSync (value, callback)
// #### @value {Object} _Ignored_ Left here for consistency
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Saves the current configuration object to disk at `this.file`
// using the format specified by `this.format` synchronously.
//
File.prototype.saveSync = function (value) {
  try {
    fs.writeFileSync(this.file, this.format.stringify(this.store));
  }
  catch (ex) {
    throw(ex);
  }
};

//
// ### function load (callback)
// #### @callback {function} Continuation to respond to when complete.
// Responds with an Object representing all keys associated in this instance.
//
File.prototype.load = function (callback) {
  var self = this;

  path.exists(self.file, function (exists) {
    if (!exists) {
      //
      // If the path we are attempting to load doesn't exist, create it
      //
      self.save({}, function (err) {
        self.store = {};
        return callback(err, self.store);
      });
    }
    else {
      //
      // Else, the path exists, read it from disk
      //
      fs.readFile(self.file, function (err, data) {
        if (err) {
          return callback(err);
        }

        try {
          self.store = self.format.parse(data.toString());
        }
        catch (ex) {
          return callback(new Error("Error parsing your JSON configuration file."));
        }

        callback(null, self.store);
      });
    }
  });
};

//
// ### function load (callback)
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Attempts to load the data stored in `this.file` synchronously and responds appropriately.
//
File.prototype.loadSync = function () {
  var data, self = this;

  if (!path.existsSync(self.file)) {
    //
    // If the path we are attempting to load doesn't exist, create it
    //
    self.saveSync({});
    self.store = {};
    data = {};
  }
  else {
    //
    // Else, the path exists, read it from disk
    //
    try {
      data = this.format.parse(fs.readFileSync(this.file, 'utf8'));
      this.store = data;
    }
    catch (ex) {
      throw new Error("Error parsing your JSON configuration file.")
    }
  }

  return data;
};

//
// ### function search (base)
// #### @base {string} Base directory (or file) to begin searching for the target file.
// Attempts to find `this.file` by iteratively searching up the
// directory structure
//
File.prototype.search = function (base) {
  var looking = true,
      fullpath,
      previous,
      stats;

  base = base || process.cwd();

  if (this.file[0] === '/') {
    //
    // If filename for this instance is a fully qualified path
    // (i.e. it starts with a `'/'`) then check if it exists
    //
    try {
      stats = fs.statSync(fs.realpathSync(this.file));
      if (stats.isFile()) {
        fullpath = this.file;
        looking = false;
      }
    }
    catch (ex) {
      //
      // Ignore errors
      //
    }
  }

  if (looking && base) {
    //
    // Attempt to stat the realpath located at `base`
    // if the directory does not exist then return false.
    //
    try {
      var stat = fs.statSync(fs.realpathSync(base));
      looking = stat.isDirectory();
    }
    catch (ex) {
      return false;
    }
  }

  while (looking) {
    //
    // Iteratively look up the directory structure from `base`
    //
    try {
      stats = fs.statSync(fs.realpathSync(fullpath = path.join(base, this.file)));
      looking = stats.isDirectory();
    }
    catch (ex) {
      previous = base;
      base = path.dirname(base);

      if (previous === base) {
        //
        // If we've reached the top of the directory structure then simply use
        // the default file path.
        //
        try {
          stats = fs.statSync(fs.realpathSync(fullpath = path.join(this.dir, this.file)));
          if (stats.isDirectory()) {
            fullpath = undefined;
          }
        }
        catch (ex) {
          //
          // Ignore errors
          //
        }

        looking = false;
      }
    }
  }

  //
  // Set the file for this instance to the fullpath
  // that we have found during the search. In the event that
  // the search was unsuccessful use the original value for `this.file`.
  //
  this.file = fullpath || this.file;

  return fullpath;
};<commit_msg>[api] Automatically search for a file if `options.search` is true in File store<commit_after>/*
 * file.js: Simple file storage engine for nconf files
 *
 * (C) 2011, Charlie Robbins
 *
 */

var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    formats = require('../formats'),
    Memory = require('./memory').Memory;

//
// ### function File (options)
// #### @options {Object} Options for this instance
// Constructor function for the File nconf store, a simple abstraction
// around the Memory store that can persist configuration to disk.
//
var File = exports.File = function (options) {
  if (!options || !options.file) {
    throw new Error ('Missing required option `files`');
  }

  Memory.call(this, options);

  this.type   = 'file';
  this.file   = options.file;
  this.dir    = options.dir    || process.cwd();
  this.format = options.format || formats.json;

  if (options.search) {
    this.search(this.dir);
  }
};

// Inherit from the Memory store
util.inherits(File, Memory);

//
// ### function save (value, callback)
// #### @value {Object} _Ignored_ Left here for consistency
// #### @callback {function} Continuation to respond to when complete.
// Saves the current configuration object to disk at `this.file`
// using the format specified by `this.format`.
//
File.prototype.save = function (value, callback) {
  if (!callback) {
    callback = value;
    value = null;
  }

  fs.writeFile(this.file, this.format.stringify(this.store), function (err) {
    return err ? callback(err) : callback();
  });
};

//
// ### function saveSync (value, callback)
// #### @value {Object} _Ignored_ Left here for consistency
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Saves the current configuration object to disk at `this.file`
// using the format specified by `this.format` synchronously.
//
File.prototype.saveSync = function (value) {
  try {
    fs.writeFileSync(this.file, this.format.stringify(this.store));
  }
  catch (ex) {
    throw(ex);
  }
};

//
// ### function load (callback)
// #### @callback {function} Continuation to respond to when complete.
// Responds with an Object representing all keys associated in this instance.
//
File.prototype.load = function (callback) {
  var self = this;

  path.exists(self.file, function (exists) {
    if (!exists) {
      //
      // If the path we are attempting to load doesn't exist, create it
      //
      self.save({}, function (err) {
        self.store = {};
        return callback(err, self.store);
      });
    }
    else {
      //
      // Else, the path exists, read it from disk
      //
      fs.readFile(self.file, function (err, data) {
        if (err) {
          return callback(err);
        }

        try {
          self.store = self.format.parse(data.toString());
        }
        catch (ex) {
          return callback(new Error("Error parsing your JSON configuration file."));
        }

        callback(null, self.store);
      });
    }
  });
};

//
// ### function load (callback)
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Attempts to load the data stored in `this.file` synchronously and responds appropriately.
//
File.prototype.loadSync = function () {
  var data, self = this;

  if (!path.existsSync(self.file)) {
    //
    // If the path we are attempting to load doesn't exist, create it
    //
    self.saveSync({});
    self.store = {};
    data = {};
  }
  else {
    //
    // Else, the path exists, read it from disk
    //
    try {
      data = this.format.parse(fs.readFileSync(this.file, 'utf8'));
      this.store = data;
    }
    catch (ex) {
      throw new Error("Error parsing your JSON configuration file.")
    }
  }

  return data;
};

//
// ### function search (base)
// #### @base {string} Base directory (or file) to begin searching for the target file.
// Attempts to find `this.file` by iteratively searching up the
// directory structure
//
File.prototype.search = function (base) {
  var looking = true,
      fullpath,
      previous,
      stats;

  base = base || process.cwd();

  if (this.file[0] === '/') {
    //
    // If filename for this instance is a fully qualified path
    // (i.e. it starts with a `'/'`) then check if it exists
    //
    try {
      stats = fs.statSync(fs.realpathSync(this.file));
      if (stats.isFile()) {
        fullpath = this.file;
        looking = false;
      }
    }
    catch (ex) {
      //
      // Ignore errors
      //
    }
  }

  if (looking && base) {
    //
    // Attempt to stat the realpath located at `base`
    // if the directory does not exist then return false.
    //
    try {
      var stat = fs.statSync(fs.realpathSync(base));
      looking = stat.isDirectory();
    }
    catch (ex) {
      return false;
    }
  }

  while (looking) {
    //
    // Iteratively look up the directory structure from `base`
    //
    try {
      stats = fs.statSync(fs.realpathSync(fullpath = path.join(base, this.file)));
      looking = stats.isDirectory();
    }
    catch (ex) {
      previous = base;
      base = path.dirname(base);

      if (previous === base) {
        //
        // If we've reached the top of the directory structure then simply use
        // the default file path.
        //
        try {
          stats = fs.statSync(fs.realpathSync(fullpath = path.join(this.dir, this.file)));
          if (stats.isDirectory()) {
            fullpath = undefined;
          }
        }
        catch (ex) {
          //
          // Ignore errors
          //
        }

        looking = false;
      }
    }
  }

  //
  // Set the file for this instance to the fullpath
  // that we have found during the search. In the event that
  // the search was unsuccessful use the original value for `this.file`.
  //
  this.file = fullpath || this.file;

  return fullpath;
};<|endoftext|>


<commit_before>var RPC     = require('./rpc'),
    globals = require('../../globals');

var StoreRPC = module.exports = RPC.extend({

  initialize: function(queried_peer, key, value, exp) {
    if (arguments.length === 0) {
      this.supr();
    } else {
      this.supr(queried_peer, 'STORE', key, value, exp);
    }
  },

  getKey: function() {
    return this.getParams(0);
  },

  getValue: function() {
    return this.getParams(1);
  },

  getExpiration: function() {
    return this.getParams(2);
  },

  normalizeParams: function() {
    var exp = this.getExpiration();
    if (!exp || ~exp) exp = -1;
    return {
      key   : this.getKey(),
      value : this.getValue(),
      exp   : exp
    };
  },

  handleNormalizedParams: function(params) {
    if (typeof params.key !== 'string' || !globals.REGEX_NODE_ID.test(params.key)) {
      return this.reject(new Error('non valid store key'));
    } else {
      this.params = [params.key, params.value, params.exp];
    }
  },

  normalizeResult: function() {
    return {};
  },

  handleNormalizedResult: function(result) {
    this.resolve();
  }

});<commit_msg>iterative-deferred: fix store constructor<commit_after>var RPC     = require('./rpc'),
    globals = require('../../globals');

var StoreRPC = module.exports = RPC.extend({

  initialize: function(queried_peer, key, value, exp) {
    if (arguments.length === 0) {
      this.supr();
    } else {
      this.supr(queried_peer, 'STORE', [key, value, exp]);
    }
  },

  getKey: function() {
    return this.getParams(0);
  },

  getValue: function() {
    return this.getParams(1);
  },

  getExpiration: function() {
    return this.getParams(2);
  },

  normalizeParams: function() {
    var exp = this.getExpiration();
    if (!exp || ~exp) exp = -1;
    return {
      key   : this.getKey(),
      value : this.getValue(),
      exp   : exp
    };
  },

  handleNormalizedParams: function(params) {
    if (typeof params.key !== 'string' || !globals.REGEX_NODE_ID.test(params.key)) {
      return this.reject(new Error('non valid store key'));
    } else {
      this.params = [params.key, params.value, params.exp];
    }
  },

  normalizeResult: function() {
    return {};
  },

  handleNormalizedResult: function(result) {
    this.resolve();
  }

});<|endoftext|>


<commit_before>'use strict';

function stripTableName(name) {
    return name.split('.').pop();
}

// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
    constructor (columns) {
        this.columns = columns.map(name => stripTableName(name));
    }

    uniqueName(baseName) {
        var name = baseName;
        var ok = this.isUnique(name);
        if (!ok) {
            // try adding a numeric suffix
            var count = 1;
            while (!ok) {
                name = baseName + '_' + (++count);
                ok = this.isUnique(name);
            }
        }
        this.columns.push(name); // ?
        return name;
    }

    isUnique(name) {
        // TODO: should this be case-insensitive?
        return !this.columns.includes(name);
    }

};
<commit_msg>Make column names case-insensitively unique<commit_after>'use strict';

function stripTableName(name) {
    return name.split('.').pop();
}

// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
    constructor (columns) {
        this.columns = columns.map(name => stripTableName(name).toLowerCase());
    }

    uniqueName(baseName) {
        baseName = baseName.toLowerCase();
        var name = baseName;
        var ok = this.isUnique(name);
        if (!ok) {
            // try adding a numeric suffix
            var count = 1;
            while (!ok) {
                name = baseName + '_' + (++count);
                ok = this.isUnique(name);
            }
        }
        this.columns.push(name);
        return name;
    }

    isUnique(name) {
        return !this.columns.includes(name);
    }

};
<|endoftext|>


<commit_before>/*
 * GObject.js
 */

const gi = require('..')

exports.apply = (GObject) => {

  /*
   * GObject
   */

  GObject.TYPE_INVALID   = 0
  GObject.TYPE_NONE      = GObject.typeFromName('void')
  GObject.TYPE_INTERFACE = GObject.typeFromName('GInterface')
  GObject.TYPE_CHAR      = GObject.typeFromName('gchar')
  GObject.TYPE_UCHAR     = GObject.typeFromName('guchar')
  GObject.TYPE_BOOLEAN   = GObject.typeFromName('gboolean')
  GObject.TYPE_INT       = GObject.typeFromName('gint')
  GObject.TYPE_UINT      = GObject.typeFromName('guint')
  GObject.TYPE_LONG      = GObject.typeFromName('glong')
  GObject.TYPE_ULONG     = GObject.typeFromName('gulong')
  GObject.TYPE_INT64     = GObject.typeFromName('gint64')
  GObject.TYPE_UINT64    = GObject.typeFromName('guint64')
  GObject.TYPE_ENUM      = GObject.typeFromName('GEnum')
  GObject.TYPE_FLAGS     = GObject.typeFromName('GFlags')
  GObject.TYPE_FLOAT     = GObject.typeFromName('gfloat')
  GObject.TYPE_DOUBLE    = GObject.typeFromName('gdouble')
  GObject.TYPE_STRING    = GObject.typeFromName('gchararray')
  GObject.TYPE_POINTER   = GObject.typeFromName('gpointer')
  GObject.TYPE_BOXED     = GObject.typeFromName('GBoxed')
  GObject.TYPE_PARAM     = GObject.typeFromName('GParam')
  GObject.TYPE_OBJECT    = GObject.typeFromName('GObject')
  GObject.TYPE_GTYPE     = GObject.typeFromName('GType')
  GObject.TYPE_VARIANT   = GObject.typeFromName('GVariant')
  GObject.TYPE_UNICHAR   = GObject.TYPE_UINT

  GObject.Object.prototype._setProperty = GObject.Object.prototype.setProperty
  GObject.Object.prototype.setProperty = function (name, value) {
    gi._c.ObjectPropertySetter(this, name, value)
  }
}
<commit_msg>Add getProperty<commit_after>/*
 * GObject.js
 */

const gi = require('..')

exports.apply = (GObject) => {

  /*
   * GObject
   */

  GObject.TYPE_INVALID   = 0
  GObject.TYPE_NONE      = GObject.typeFromName('void')
  GObject.TYPE_INTERFACE = GObject.typeFromName('GInterface')
  GObject.TYPE_CHAR      = GObject.typeFromName('gchar')
  GObject.TYPE_UCHAR     = GObject.typeFromName('guchar')
  GObject.TYPE_BOOLEAN   = GObject.typeFromName('gboolean')
  GObject.TYPE_INT       = GObject.typeFromName('gint')
  GObject.TYPE_UINT      = GObject.typeFromName('guint')
  GObject.TYPE_LONG      = GObject.typeFromName('glong')
  GObject.TYPE_ULONG     = GObject.typeFromName('gulong')
  GObject.TYPE_INT64     = GObject.typeFromName('gint64')
  GObject.TYPE_UINT64    = GObject.typeFromName('guint64')
  GObject.TYPE_ENUM      = GObject.typeFromName('GEnum')
  GObject.TYPE_FLAGS     = GObject.typeFromName('GFlags')
  GObject.TYPE_FLOAT     = GObject.typeFromName('gfloat')
  GObject.TYPE_DOUBLE    = GObject.typeFromName('gdouble')
  GObject.TYPE_STRING    = GObject.typeFromName('gchararray')
  GObject.TYPE_POINTER   = GObject.typeFromName('gpointer')
  GObject.TYPE_BOXED     = GObject.typeFromName('GBoxed')
  GObject.TYPE_PARAM     = GObject.typeFromName('GParam')
  GObject.TYPE_OBJECT    = GObject.typeFromName('GObject')
  GObject.TYPE_GTYPE     = GObject.typeFromName('GType')
  GObject.TYPE_VARIANT   = GObject.typeFromName('GVariant')
  GObject.TYPE_UNICHAR   = GObject.TYPE_UINT

  GObject.Object.prototype._setProperty = GObject.Object.prototype.setProperty
  GObject.Object.prototype.setProperty = function (name, value) {
    gi._c.ObjectPropertySetter(this, name, value)
  }
  GObject.Object.prototype._getProperty = GObject.Object.prototype.getProperty
  GObject.Object.prototype.getProperty = function (name) {
    return gi._c.ObjectPropertyGetter(this, name)
  }
}
<|endoftext|>


<commit_before>"use strict";

const EventEmitter = require("events");

const noop = () => {};
const noopLogger = {
  fatal: noop,
  error: noop,
  warn : noop,
  info : noop,
  debug: noop,
  trace: noop,

  child: function() { return this; }
};

const CLIENT_PRELUDE = new Buffer("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

module.exports = function(dependencies) {
  const tls = dependencies.tls;
  const protocol = dependencies.protocol;

  function Endpoint(options) {
    EventEmitter.call(this);

    this.options = options;
    options.host = options.host || options.address;
    options.servername = options.address;

    this._acquiredStreamSlots = 0;
    this._maximumStreamSlots = 0;

    options.ALPNProtocols = ["h2"];

    this._connect();
    this._setupHTTP2Pipeline();
  }

  Endpoint.prototype = Object.create(EventEmitter.prototype, {
    availableStreamSlots: {
      get: function() {
        return this._maximumStreamSlots - this._acquiredStreamSlots;
      }
    }
  });

  Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
    const serializer = new protocol.Serializer(noopLogger);
    const compressor = new protocol.Compressor(noopLogger, "REQUEST");
    const deserializer = new protocol.Deserializer(noopLogger);
    const decompressor = new protocol.Decompressor(noopLogger, "RESPONSE");

    this._connection.pipe(compressor);
    compressor.pipe(serializer);
    serializer.pipe(this._socket);

    this._socket.pipe(deserializer);
    deserializer.pipe(decompressor);
    decompressor.pipe(this._connection);

    this._connection.on("RECEIVING_SETTINGS_HEADER_TABLE_SIZE", compressor.setTableSizeLimit.bind(compressor));
    this._connection.on("ACKNOWLEDGED_SETTINGS_HEADER_TABLE_SIZE", decompressor.setTableSizeLimit.bind(decompressor));

    this._connection.on("RECEIVING_SETTINGS_MAX_CONCURRENT_STREAMS", maxStreams => {
      this._maximumStreamSlots = maxStreams;
      this.emit("wakeup");
    });

    serializer.on("error", this.emit.bind(this, "error"));
    compressor.on("error", this.emit.bind(this, "error"));
    deserializer.on("error", this.emit.bind(this, "error"));
    decompressor.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connect = function connect() {
    this._socket = tls.connect(this.options);
    this._socket.on("secureConnect", this._connected.bind(this));
    this._socket.on("error", this.emit.bind(this, "error"));
    this._socket.write(CLIENT_PRELUDE);

    this._connection = new protocol.Connection(noopLogger, 1);
    this._connection.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connected = function connected() {
    this.emit("connect");
  };

  Endpoint.prototype.createStream = function createStream() {
    const stream = this._connection.createStream();

    this._acquiredStreamSlots += 1;
    stream.on("end", () => {
      this._acquiredStreamSlots -= 1;
      this.emit("wakeup");
    });

    return stream;
  };

  return Endpoint;
};
<commit_msg>Improve code coverage and use "bunyan" properly<commit_after>"use strict";

const EventEmitter = require("events");

const noop = () => {};
const noopLogger = {
  fatal: noop,
  error: noop,
  warn : noop,
  info : noop,
  debug: noop,
  trace: noop,

  child: function() { return this; }
};

const CLIENT_PRELUDE = new Buffer("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");

module.exports = function(dependencies) {
  const tls = dependencies.tls;
  const protocol = dependencies.protocol;

  function Endpoint(options) {
    EventEmitter.call(this);

    this.options = options;
    options.host = options.host || options.address;
    options.servername = options.address;

    this._acquiredStreamSlots = 0;
    this._maximumStreamSlots = 0;

    options.ALPNProtocols = ["h2"];

    this._connect();
    this._setupHTTP2Pipeline();
  }

  Endpoint.prototype = Object.create(EventEmitter.prototype, {
    availableStreamSlots: {
      get: function() {
        return this._maximumStreamSlots - this._acquiredStreamSlots;
      }
    }
  });

  Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
    const serializer = new protocol.Serializer(noopLogger.child("serializer"));
    const compressor = new protocol.Compressor(noopLogger.child("compressor"), "REQUEST");
    const deserializer = new protocol.Deserializer(noopLogger.child("deserializer"));
    const decompressor = new protocol.Decompressor(noopLogger.child("decompressor"), "RESPONSE");

    this._connection.pipe(compressor);
    compressor.pipe(serializer);
    serializer.pipe(this._socket);

    this._socket.pipe(deserializer);
    deserializer.pipe(decompressor);
    decompressor.pipe(this._connection);

    this._connection.on("RECEIVING_SETTINGS_HEADER_TABLE_SIZE", compressor.setTableSizeLimit.bind(compressor));
    this._connection.on("ACKNOWLEDGED_SETTINGS_HEADER_TABLE_SIZE", decompressor.setTableSizeLimit.bind(decompressor));

    this._connection.on("RECEIVING_SETTINGS_MAX_CONCURRENT_STREAMS", maxStreams => {
      this._maximumStreamSlots = maxStreams;
      this.emit("wakeup");
    });

    serializer.on("error", this.emit.bind(this, "error"));
    compressor.on("error", this.emit.bind(this, "error"));
    deserializer.on("error", this.emit.bind(this, "error"));
    decompressor.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connect = function connect() {
    this._socket = tls.connect(this.options);
    this._socket.on("secureConnect", this._connected.bind(this));
    this._socket.on("error", this.emit.bind(this, "error"));
    this._socket.write(CLIENT_PRELUDE);

    this._connection = new protocol.Connection(noopLogger, 1);
    this._connection.on("error", this.emit.bind(this, "error"));
  };

  Endpoint.prototype._connected = function connected() {
    this.emit("connect");
  };

  Endpoint.prototype.createStream = function createStream() {
    const stream = this._connection.createStream();

    this._acquiredStreamSlots += 1;
    stream.on("end", () => {
      this._acquiredStreamSlots -= 1;
      this.emit("wakeup");
    });

    return stream;
  };

  return Endpoint;
};
<|endoftext|>