<commit_before>/* See license.txt for terms of usage */

"use strict";

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js");
const { Domplate } = require("../core/domplate.js");
const { Rep } = require("./rep.js");
const { Reps } = require("./reps.js");
const { prefs } = require("sdk/simple-prefs");
const { Locale } = require("../core/locale.js");
const { Str } = require("../core/string.js");
const { Url } = require("../core/url.js");

// Domplate
const { domplate, SPAN, FOR, TAG } = Domplate;
const { OBJECTLINK } = Rep.tags;

/**
 * @rep Generic DOM element template.
 */
var Element = domplate(Rep,
/** @lends Element */
{
  className: "element",

  tag:
    OBJECTLINK(
      "<",
      SPAN({"class": "nodeTag"}, "$object|getLocalName"),
      FOR("attr", "$object|attrIterator",
        " $attr.localName="",
        SPAN({"class": "nodeValue"}, "$attr|getAttrValue"),
        """
      ),
      ">"
     ),

  shortTag:
    OBJECTLINK(
      SPAN({"class": "$object|getVisible"},
        SPAN({"class": "selectorTag"}, "$object|getSelectorTag"),
        SPAN({"class": "selectorId"}, "$object|getSelectorId"),
        SPAN({"class": "selectorClass"}, "$object|getSelectorClasses"),
        TAG("$object|getValueTag", {object: "$object"})
      )
     ),

  // Generic template for various element values
  valueTag:
    SPAN({"class": "selectorValue"}, "$object|getValue"),

  // Template for <input> element with a single value coming from attribute.
  singleInputTag:
    SPAN(
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.attribute_value") + " = "
      ),
      SPAN({"class": "attributeValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromAttribute"})
      )
    ),

  // Template for <input> element with two different values (attribute and property)
  multipleInputTag:
    SPAN(
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.property_value") + " = "
      ),
      SPAN({"class": "propertyValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromProperty"})
      ),
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.attribute_value") + " = "
      ),
      SPAN({"class": "attributeValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromAttribute"})
      )
    ),

  getValueTag: function(elt) {
    // Use proprietary template for <input> elements that can have two
    // different values. One coming from attribute 'value' and one coming
    // from property 'value'.

    //xxxHonza: FIX ME
    /*if (elt instanceof window.HTMLInputElement)
    {
        var attrValue = elt.getAttribute("value");
        var propValue = elt.value;

        if (attrValue != propValue)
            return this.multipleInputTag;
        else
            return this.singleInputTag;
    }*/

    return this.valueTag;
  },

  getValueFromAttribute: function(elt) {
    let limit = Options.get("stringCropLength");
    let value = elt.getAttribute("value");
    return Str.cropString(value, limit);
  },

  getValueFromProperty: function(elt) {
    return Str.cropString(elt.value);
  },

  getValue: function(grip) {
    let preview = grip.preview;
    let value;

    if (grip.class == "HTMLImageElement")
      value = Url.getFileName(preview.attributes["src"]);
    else if (grip.class == "HTMLAnchorElement")
      value = Url.getFileName(preview.attributes["href"]);
    else if (grip.class == "HTMLInputElement")
      value = preview.attributes["value"];
    else if (grip.class == "HTMLFormElement")
      value = Url.getFileName(preview.attributes["action"]);
    else if (grip.class == "HTMLScriptElement")
      value = Url.getFileName(preview.attributes["src"]);

    return value ? " " + Str.cropMultipleLines(value, 20) : " ";
  },

  getLocalName: function(object) {
    return object.preview.nodeName;
  },

  getAttrValue: function(attr) {
    let limit = prefs["displayedAttributeValueLimit"];
    return (limit > 0) ? Str.cropString(attr.value, limit) : attr.value;
  },

  getAttrTitle: function(attr) {
    let newValue = this.getAttrValue(attr);
    return (attr.value != newValue) ? attr.value : undefined;
  },

  getVisible: function(elt) {
    // xxxHonza: FIX ME
    // Use built-in support for determining element visibility.
    //return Xml.isVisible(elt) ? "" : "selectorHidden";
    return "";
  },

  getSelectorTag: function(elt) {
    return this.getLocalName(elt);
  },

  getSelectorId: function(grip) {
    let preview = grip.preview;
    try {
      let id = preview.attributes["id"];
      return id ? ("#" + id) : "";
    }
    catch (e) {
      return "";
    }
  },

  getSelectorClasses: function(elt) {
    // xxxHonza: we need the classList in the preview
    try {
      let selectorClasses = "";
      for (let i = 0, len = elt.classList.length; i < len; i++)
        selectorClasses += "." + elt.classList[i];
      return selectorClasses;
    }
    catch (err) {
      return "";
    }
  },

  attrIterator: function(elt) {
    let attrs = [];
    let idAttr, classAttr;
    if (elt.attributes) {
      for (let i = 0; i < elt.attributes.length; i++) {
        let attr = elt.attributes[i];
        if (attr.localName == "id")
          idAttr = attr;
        else if (attr.localName == "class")
          classAttr = attr;
        else
          attrs.push(attr);
      }
    }

    // Make sure 'id' and 'class' attributes are displayed first.
    if (classAttr)
      attrs.splice(0, 0, classAttr);
    if (idAttr)
      attrs.splice(0, 0, idAttr);

    return attrs;
  },

  shortAttrIterator: function(elt) {
    // Short version returns only 'id' and 'class' attributes.
    let attrs = [];
    if (elt.attributes) {
      for (let i = 0; i < elt.attributes.length; i++) {
        let attr = elt.attributes[i];
        if (attr.localName == "id" || attr.localName == "class")
          attrs.push(attr);
      }
    }

    return attrs;
  },

  getHidden: function(elt) {
    // xxxHonza: FIX ME
    // Use built-in API to determine node visibility
    //return Xml.isVisible(elt) ? "" : "nodeHidden";
  },

  supportsObject: function(object, type) {
    return /^HTML.*Element$/.test(type);
  },

  browseObject: function(elt, context) {
    let tag = elt.localName.toLowerCase();
    if (tag == "script" || tag == "img" || tag == "iframe" || tag == "frame")
      Win.openNewTab(elt.src);
    else if (tag == "link" || tag == "a")
      Win.openNewTab(elt.href);

    return true;
  },

  highlightObject: function(object, context, target) {
    Inspector.highlightObject(object, context);
  },

  getTitle: function(grip, context) {
    return getElementCSSSelector(grip);
  },

  getTooltip: function(elt, context, target) {
    // xxxHonza: FIX ME

    /*
    // If the mouse cursor hovers over cropped value of an input element
    // display the full value in the tooltip.
    if (Css.hasClass(target, "objectBox-string"))
    {
        var inputValue = Dom.getAncestorByClass(target, "inputValue");
        if (inputValue)
        {
            var limit = Options.get("stringCropLength");
            var value;
            if (Css.hasClass(inputValue, "attributeValue"))
                value = elt.getAttribute("value");
            else if (Css.hasClass(inputValue, "propertyValue"))
                value = elt.value;

            if (value && value.length > limit)
                return value;
        }
    }*/

    return "";
  },
});

// xxxHonza: should be shared lib API (was in css.js)
function getElementCSSSelector(grip) {
  let preview = grip.preview;
  if (!preview)
    return;

  let label = preview.nodeName;
  let id = preview.attributes["id"];
  if (id)
    label += "#" + id;

  // xxxHonza: we need to instrument the actor to send the class list
  // (or this might be supported natively)
  if (preview.classList) {
    for (let i = 0, len = preview.classList.length; i < len; i++)
      label += "." + preview.classList[i];
  }

  return label;
};

// Registration
Reps.registerRep(Element);

// Exports from this module
exports.Element = Element;
<commit_msg>Properly display attributes for DOM element grip<commit_after>/* See license.txt for terms of usage */

"use strict";

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js");
const { Domplate } = require("../core/domplate.js");
const { Rep } = require("./rep.js");
const { Reps } = require("./reps.js");
const { prefs } = require("sdk/simple-prefs");
const { Locale } = require("../core/locale.js");
const { Str } = require("../core/string.js");
const { Url } = require("../core/url.js");

// Domplate
const { domplate, SPAN, FOR, TAG } = Domplate;
const { OBJECTLINK } = Rep.tags;

/**
 * @rep Generic DOM element template.
 */
var Element = domplate(Rep,
/** @lends Element */
{
  className: "element",

  tag:
    OBJECTLINK(
      "<",
      SPAN({"class": "nodeTag"}, "$object|getLocalName"),
      FOR("attr", "$object|attrIterator",
        " $attr.localName="",
        SPAN({"class": "nodeValue"}, "$attr|getAttrValue"),
        """
      ),
      ">"
     ),

  shortTag:
    OBJECTLINK(
      SPAN({"class": "$object|getVisible"},
        SPAN({"class": "selectorTag"}, "$object|getSelectorTag"),
        SPAN({"class": "selectorId"}, "$object|getSelectorId"),
        SPAN({"class": "selectorClass"}, "$object|getSelectorClasses"),
        TAG("$object|getValueTag", {object: "$object"})
      )
     ),

  // Generic template for various element values
  valueTag:
    SPAN({"class": "selectorValue"}, "$object|getValue"),

  // Template for <input> element with a single value coming from attribute.
  singleInputTag:
    SPAN(
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.attribute_value") + " = "
      ),
      SPAN({"class": "attributeValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromAttribute"})
      )
    ),

  // Template for <input> element with two different values (attribute and property)
  multipleInputTag:
    SPAN(
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.property_value") + " = "
      ),
      SPAN({"class": "propertyValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromProperty"})
      ),
      SPAN(" "),
      SPAN({"class": "selectorValue"},
        Locale.$STR("firebug.reps.element.attribute_value") + " = "
      ),
      SPAN({"class": "attributeValue inputValue"},
        TAG(Reps.String.tag, {object: "$object|getValueFromAttribute"})
      )
    ),

  getValueTag: function(elt) {
    // Use proprietary template for <input> elements that can have two
    // different values. One coming from attribute 'value' and one coming
    // from property 'value'.

    //xxxHonza: FIX ME
    /*if (elt instanceof window.HTMLInputElement)
    {
        var attrValue = elt.getAttribute("value");
        var propValue = elt.value;

        if (attrValue != propValue)
            return this.multipleInputTag;
        else
            return this.singleInputTag;
    }*/

    return this.valueTag;
  },

  getValueFromAttribute: function(elt) {
    let limit = Options.get("stringCropLength");
    let value = elt.getAttribute("value");
    return Str.cropString(value, limit);
  },

  getValueFromProperty: function(elt) {
    return Str.cropString(elt.value);
  },

  getValue: function(grip) {
    let preview = grip.preview;
    let value;

    if (grip.class == "HTMLImageElement")
      value = Url.getFileName(preview.attributes["src"]);
    else if (grip.class == "HTMLAnchorElement")
      value = Url.getFileName(preview.attributes["href"]);
    else if (grip.class == "HTMLInputElement")
      value = preview.attributes["value"];
    else if (grip.class == "HTMLFormElement")
      value = Url.getFileName(preview.attributes["action"]);
    else if (grip.class == "HTMLScriptElement")
      value = Url.getFileName(preview.attributes["src"]);

    return value ? " " + Str.cropMultipleLines(value, 20) : " ";
  },

  getLocalName: function(object) {
    return object.preview.nodeName;
  },

  getAttrValue: function(attr) {
    let limit = prefs["displayedAttributeValueLimit"];
    return (limit > 0) ? Str.cropString(attr.value, limit) : attr.value;
  },

  getAttrTitle: function(attr) {
    let newValue = this.getAttrValue(attr);
    return (attr.value != newValue) ? attr.value : undefined;
  },

  getVisible: function(elt) {
    // xxxHonza: FIX ME
    // Use built-in support for determining element visibility.
    //return Xml.isVisible(elt) ? "" : "selectorHidden";
    return "";
  },

  getSelectorTag: function(elt) {
    return this.getLocalName(elt);
  },

  getSelectorId: function(grip) {
    let preview = grip.preview;
    try {
      let id = preview.attributes["id"];
      return id ? ("#" + id) : "";
    }
    catch (e) {
      return "";
    }
  },

  getSelectorClasses: function(elt) {
    // xxxHonza: we need the classList in the preview
    try {
      let selectorClasses = "";
      for (let i = 0, len = elt.classList.length; i < len; i++)
        selectorClasses += "." + elt.classList[i];
      return selectorClasses;
    }
    catch (err) {
      return "";
    }
  },

  attrIterator: function(grip) {
    let attrs = [];
    let idAttr, classAttr;
    if (grip.preview.attributes) {
      for (let name in grip.preview.attributes) {
        let attr = {
          localName: name,
          value: grip.preview.attributes[name]
        };

        if (name == "id")
          idAttr = attr;
        else if (name == "class")
          classAttr = attr;
        else
          attrs.push(attr);
      }
    }

    // Make sure 'id' and 'class' attributes are displayed first.
    if (classAttr)
      attrs.splice(0, 0, classAttr);
    if (idAttr)
      attrs.splice(0, 0, idAttr);

    return attrs;
  },

  shortAttrIterator: function(grip) {
    // Short version returns only 'id' and 'class' attributes.
    let attrs = [];
    if (grip.preview.attributes) {
      for (let name in grip.preview.attributes) {
        let attr = {
          localName: name,
          value: grip.preview.attributes[name]
        };

        if (attr.localName == "id" || attr.localName == "class")
          attrs.push(attr);
      }
    }

    return attrs;
  },

  getHidden: function(elt) {
    // xxxHonza: FIX ME
    // Use built-in API to determine node visibility
    //return Xml.isVisible(elt) ? "" : "nodeHidden";
  },

  supportsObject: function(object, type) {
    return /^HTML.*Element$/.test(type);
  },

  browseObject: function(elt, context) {
    let tag = elt.localName.toLowerCase();
    if (tag == "script" || tag == "img" || tag == "iframe" || tag == "frame")
      Win.openNewTab(elt.src);
    else if (tag == "link" || tag == "a")
      Win.openNewTab(elt.href);

    return true;
  },

  highlightObject: function(object, context, target) {
    Inspector.highlightObject(object, context);
  },

  getTitle: function(grip, context) {
    return getElementCSSSelector(grip);
  },

  getTooltip: function(elt, context, target) {
    // xxxHonza: FIX ME

    /*
    // If the mouse cursor hovers over cropped value of an input element
    // display the full value in the tooltip.
    if (Css.hasClass(target, "objectBox-string"))
    {
        var inputValue = Dom.getAncestorByClass(target, "inputValue");
        if (inputValue)
        {
            var limit = Options.get("stringCropLength");
            var value;
            if (Css.hasClass(inputValue, "attributeValue"))
                value = elt.getAttribute("value");
            else if (Css.hasClass(inputValue, "propertyValue"))
                value = elt.value;

            if (value && value.length > limit)
                return value;
        }
    }*/

    return "";
  },
});

// xxxHonza: should be shared lib API (was in css.js)
function getElementCSSSelector(grip) {
  let preview = grip.preview;
  if (!preview)
    return;

  let label = preview.nodeName;
  let id = preview.attributes["id"];
  if (id)
    label += "#" + id;

  // xxxHonza: we need to instrument the actor to send the class list
  // (or this might be supported natively)
  if (preview.classList) {
    for (let i = 0, len = preview.classList.length; i < len; i++)
      label += "." + preview.classList[i];
  }

  return label;
};

// Registration
Reps.registerRep(Element);

// Exports from this module
exports.Element = Element;
<|endoftext|>


<commit_before>'use strict';

if(process.env.API_ANALYTICS_KEY) { // eslint-disable-line
  var aac = require('@jbpionnier/api-analytics-client'); // eslint-disable-line
  var analytics = require('@jbpionnier/api-analytics-client/express'); // eslint-disable-line
} // eslint-disable-line

var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var initRoutes = require('./app/routes');
var Promise = require('bluebird');
var winston = require('winston');
var TokenService = require('sf-token');
var nodemailer = require('nodemailer');
var nodemailerMailgunTransport = require('nodemailer-mailgun-transport');
var Pusher = require('pusher');
var Twitter = require('twitter');

var initFacebookWorker = require('./workers/facebook/facebook.bin.js');
var initXeeWorker = require('./workers/xee/xee.bin.js');
var initPSAWorker = require('./workers/psa/psa.bin.js');
var initTwitterWorker = require('./workers/twitter/twitter.bin.js');
var initEmailWorker = require('./workers/email/email.bin.js');
var initPusherWorker = require('./workers/pusher/pusher.bin.js');

var context = {};

// Preparing services
context.env = process.env;
Promise.all([
  MongoClient.connect(context.env.MONGODB_URL),
]).spread(function handleServerServices(db) {
  // Services
  context.time = Date.now.bind(Date);
  context.db = db;
  context.bus = {
    consume: function busConsume(callback) {
      process.on('bus-event', callback);
    },
    trigger: function busTrigger(event) {
      process.emit('bus-event', event);
    },
  };
  if(context.env.PUSHER_APP_ID) {
    context.pusher = new Pusher({
      appId: context.env.PUSHER_APP_ID,
      key: context.env.PUSHER_KEY,
      secret: context.env.PUSHER_SECRET,
      cluster: context.env.PUSHER_CLUSTER,
      encrypted: true,
    });
  }
  if(context.env.TWITTER_ID) {
    context.twitter = new Twitter({
      consumer_key: process.env.TWITTER_ID,
      consumer_secret: process.env.TWITTER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });
  }

  context.app = express();
  context.createObjectId = ObjectId;
  context.logger = new (winston.Logger)({
    transports: [new (winston.transports.Console)({ level: 'silly' })],
  });
  context.tokens = new TokenService({
    uniqueId: function createTokenUniqueId() {
      return context.createObjectId().toString();
    },
    secret: context.env.TOKEN_SECRET,
    time: context.time,
  });

  if(context.env.API_ANALYTICS_KEY) {
    context.analyticsAgent = analytics({
      apiKey: context.env.API_ANALYTICS_KEY,
      uuidResolver: function agentUuidResolver(req) {
        return req.user ? req.user._id : null;
      },
    });
  }

  if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {

    context.sendMail = function initSendMail() {
      var mailer = nodemailer.createTransport(
        nodemailerMailgunTransport({
          auth: {
            api_key: context.env.MAILGUN_KEY,
            domain: context.env.MAILGUN_DOMAIN,
          },
        })
      );

      return function sendEmail(contents) {
        return new Promise(function(resolve, reject) {
          mailer.sendMail(contents, function sendMailHandler(err, info) {
            if(err) {
              return reject(err);
            }
            resolve(info);
          });
        });
      };
    }();
  }

  context.protocol = context.env.PROTOCOL || 'http';
  context.host = context.env.HOST || 'localhost';
  context.domain = context.env.DOMAIN || '';
  context.port = 'undefined' !== typeof context.env.PORT ?
    parseInt(context.env.PORT, 10) :
    3000;
  context.base = context.protocol + '://' + (
    context.domain ?
    context.domain :
    context.host + ':' + context.port
  );
  context.logger.debug('Env', context.env);

  // Workers
  initPSAWorker(context);
  initFacebookWorker(context);
  initTwitterWorker(context);
  initXeeWorker(context);
  if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
    initEmailWorker(context);
  }
  if(context.env.PUSHER_APP_ID) {
    initPusherWorker(context);
  }

  // Routes
  initRoutes(context);

  // Starting the server
  return new Promise(function handleServerPromise(resolve, reject) {
    context.server = context.app.listen(context.port, function handleServerCb(err) {
      if(err) {
        return reject(err);
      }

      context.logger.debug(
        'Server listening to \\o/ -> http://%s:%s - Pid: %s',
        context.host, context.port, process.pid
      );
      resolve();
    });
  });
});
<commit_msg>(api-analytics) uuid must be a string or a number<commit_after>'use strict';

if(process.env.API_ANALYTICS_KEY) { // eslint-disable-line
  var aac = require('@jbpionnier/api-analytics-client'); // eslint-disable-line
  var analytics = require('@jbpionnier/api-analytics-client/express'); // eslint-disable-line
} // eslint-disable-line

var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var initRoutes = require('./app/routes');
var Promise = require('bluebird');
var winston = require('winston');
var TokenService = require('sf-token');
var nodemailer = require('nodemailer');
var nodemailerMailgunTransport = require('nodemailer-mailgun-transport');
var Pusher = require('pusher');
var Twitter = require('twitter');

var initFacebookWorker = require('./workers/facebook/facebook.bin.js');
var initXeeWorker = require('./workers/xee/xee.bin.js');
var initPSAWorker = require('./workers/psa/psa.bin.js');
var initTwitterWorker = require('./workers/twitter/twitter.bin.js');
var initEmailWorker = require('./workers/email/email.bin.js');
var initPusherWorker = require('./workers/pusher/pusher.bin.js');

var context = {};

// Preparing services
context.env = process.env;
Promise.all([
  MongoClient.connect(context.env.MONGODB_URL),
]).spread(function handleServerServices(db) {
  // Services
  context.time = Date.now.bind(Date);
  context.db = db;
  context.bus = {
    consume: function busConsume(callback) {
      process.on('bus-event', callback);
    },
    trigger: function busTrigger(event) {
      process.emit('bus-event', event);
    },
  };
  if(context.env.PUSHER_APP_ID) {
    context.pusher = new Pusher({
      appId: context.env.PUSHER_APP_ID,
      key: context.env.PUSHER_KEY,
      secret: context.env.PUSHER_SECRET,
      cluster: context.env.PUSHER_CLUSTER,
      encrypted: true,
    });
  }
  if(context.env.TWITTER_ID) {
    context.twitter = new Twitter({
      consumer_key: process.env.TWITTER_ID,
      consumer_secret: process.env.TWITTER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });
  }

  context.app = express();
  context.createObjectId = ObjectId;
  context.logger = new (winston.Logger)({
    transports: [new (winston.transports.Console)({ level: 'silly' })],
  });
  context.tokens = new TokenService({
    uniqueId: function createTokenUniqueId() {
      return context.createObjectId().toString();
    },
    secret: context.env.TOKEN_SECRET,
    time: context.time,
  });

  if(context.env.API_ANALYTICS_KEY) {
    context.analyticsAgent = analytics({
      apiKey: context.env.API_ANALYTICS_KEY,
      uuidResolver: function agentUuidResolver(req) {
        return req.user && req.user._id ? req.user._id.toString() : null;
      },
    });
  }

  if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {

    context.sendMail = function initSendMail() {
      var mailer = nodemailer.createTransport(
        nodemailerMailgunTransport({
          auth: {
            api_key: context.env.MAILGUN_KEY,
            domain: context.env.MAILGUN_DOMAIN,
          },
        })
      );

      return function sendEmail(contents) {
        return new Promise(function(resolve, reject) {
          mailer.sendMail(contents, function sendMailHandler(err, info) {
            if(err) {
              return reject(err);
            }
            resolve(info);
          });
        });
      };
    }();
  }

  context.protocol = context.env.PROTOCOL || 'http';
  context.host = context.env.HOST || 'localhost';
  context.domain = context.env.DOMAIN || '';
  context.port = 'undefined' !== typeof context.env.PORT ?
    parseInt(context.env.PORT, 10) :
    3000;
  context.base = context.protocol + '://' + (
    context.domain ?
    context.domain :
    context.host + ':' + context.port
  );
  context.logger.debug('Env', context.env);

  // Workers
  initPSAWorker(context);
  initFacebookWorker(context);
  initTwitterWorker(context);
  initXeeWorker(context);
  if(context.env.MAILGUN_KEY && context.env.MAILGUN_DOMAIN) {
    initEmailWorker(context);
  }
  if(context.env.PUSHER_APP_ID) {
    initPusherWorker(context);
  }

  // Routes
  initRoutes(context);

  // Starting the server
  return new Promise(function handleServerPromise(resolve, reject) {
    context.server = context.app.listen(context.port, function handleServerCb(err) {
      if(err) {
        return reject(err);
      }

      context.logger.debug(
        'Server listening to \\o/ -> http://%s:%s - Pid: %s',
        context.host, context.port, process.pid
      );
      resolve();
    });
  });
});
<|endoftext|>


<commit_before>var _ = require('lodash');

function selectFields(user, main) {

	function inex(str, val) {
		var obj = {};
		_.each(str.split(','), function(v) {
			obj[v] = val;
		});
		return obj;
	}
	if(_.isString(user.exclude)) {
		var select = inex(user.exclude, 0);
	} else if(_.isString(user.include)) {
		var select = inex(user.include, 1);
	} else if(_.isString(main.exclude)) {
		var select = inex(main.exclude, 0);
	} else if(_.isString(main.include)) {
		var select = inex(main.include, 1);
	}

	return select;
}

/**
 * List Posts
 */
exports.list = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for list',err,data);
	};
	var list = data.list;
	var options = data;
	if(!data.list) return callback('list required');
	if(!options) options = {};
	var find = options.find || options.query;
	if(!_.isObject(find)) find = {};
	if(_.isNaN(parseFloat(options.limit))) options.limit = 10;
	if(_.isNaN(parseFloat(options.skip))) options.skip = 0;
	if(!_.isObject(options.sort)) options.sort = {};

	var q = list.model.find(find);
	q.limit(options.limit);
	q.skip(options.skip);
	q.sort(options.sort);

	if(options.populate) {
		q.populate(options.populate);
	} else {
		q.populate('createdBy updatedBy');
	}
	var select = selectFields(options,list.apiOptions);
	if(select) q.select(select);

	q.exec(function(err, items) {

		if (err) return callback(err);

		var data = {};
		data[list.path] = items;
		callback(null, data);

	});
}

/**
 * Get doc by ID
 */
exports.get = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for get',err,data);
	};
	if(!data.list) return callback('list required');
	var id = data.id  || data._id;
	var find = data.find || data.query;

	if(!id && !find) return callback('id or find required');

	var q = data.list.model;

	if(_.isObject(find)) {
		q.find(find);
	} else {
		q.findById(id);
	}

	var select = selectFields(data,data.list.apiOptions);
	if(select) q.select(select);
	if(data.populate) {
		q.populate(data.populate);
	} else {
		q.populate('createdBy updatedBy');
	}
	q.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		var send = {}
		send[data.list.path] = item;

		callback(null, send);

	});
}

/**
 * Create a Post
 */
exports.create = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for create',err,data);
	};
	var list = data.list;
	var doc = data.doc;
	var item = new list.model();

	if(!list) return callback('list required');
	if(!_.isObject(doc)) return callback('doc required');
	if(!_.isObject(req)) req = {};

	item.getUpdateHandler(req).process(doc, function(err) {

		if (err) {
			return callback(err);
		}
		var data2 = {}
		data2[list.path] = item;

		callback(null, data2);

	});
}

/**
 * Update Post by ID
 */
exports.update = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for update',err,data);
	};

	var list = data.list;
	var id = data.id || data._id;
	var doc = data.doc;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('id required');
	if(!_.isObject(doc)) return callback('data required');
	if(!_.isObject(req)) req = {};

	var lookup = list.model;
	if(_.isObject(find)) {
		lookup.find(find);
	} else {
		lookup.findById(id);
	}
	lookup.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		item.getUpdateHandler(req).process(doc, function(err) {

			if (err) return callback(err);

			var data2 = {}
			data2[list.path] = item;

			callback(null, data2);

		});

	});
}

/**
 * Update Post Field
 */
exports.updateField = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for updateFIeld',err,data);
	};

	var list = data.list;
	var id = data.id  || data._id;
	var field = data.field;
	var value = data.value;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('find required');
	if(!field) return callback('field path required');
	//if(!value) callback('value required');
	if(!_.isObject(req)) req = {};

	var lookup = list.model;
	if(_.isObject(find)) {
		lookup.find(find);
	} else {
		lookup.findById(id);
	}
	lookup.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		var data = {}
		data[field] = value;

		item.getUpdateHandler(req).process(data, function(err) {

			if (err) return callback(err);

			callback(null, data);

		});

	});
}

/**
 * Delete Post by ID
 */
exports.remove = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for remove',err,data);
	};

	var list = data.list;
	var id = data.id  || data._id;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('id required');

	var lookup = list.model;
	if(_.isObject(find)) {
		lookup.find(find);
	} else {
		lookup.findById(id);
	}
	lookup.exec(function (err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		item.remove(function (err) {
			if (err) return callback(err);

			return callback(null,{
				success: true
			});
		});

	});
}
<commit_msg>0.1.12<commit_after>var _ = require('lodash');

function selectFields(user, main) {

	function inex(str, val) {
		var obj = {};
		_.each(str.split(','), function(v) {
			obj[v] = val;
		});
		return obj;
	}
	if(_.isString(user.exclude)) {
		var select = inex(user.exclude, 0);
	} else if(_.isString(user.include)) {
		var select = inex(user.include, 1);
	} else if(_.isString(main.exclude)) {
		var select = inex(main.exclude, 0);
	} else if(_.isString(main.include)) {
		var select = inex(main.include, 1);
	}

	return select;
}

/**
 * List Posts
 */
exports.list = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for list',err,data);
	};
	var list = data.list;
	var options = data;
	if(!data.list) return callback('list required');
	if(!options) options = {};
	var find = options.find || options.query;
	if(!_.isObject(find)) find = {};
	if(_.isNaN(parseFloat(options.limit))) options.limit = 10;
	if(_.isNaN(parseFloat(options.skip))) options.skip = 0;
	if(!_.isObject(options.sort)) options.sort = {};

	var q = list.model.find(find);
	q.limit(options.limit);
	q.skip(options.skip);
	q.sort(options.sort);

	if(options.populate) {
		q.populate(options.populate);
	} else {
		q.populate('createdBy updatedBy');
	}
	var select = selectFields(options,list.apiOptions);
	if(select) q.select(select);

	q.exec(function(err, items) {

		if (err) return callback(err);

		var data = {};
		data[list.path] = items;
		callback(null, data);

	});
}

/**
 * Get doc by ID
 */
exports.get = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for get',err,data);
	};

	if(!data.list) return callback('list required');

	var id = data.id  || data._id;
	var find = data.find || data.query;

	if(!id && !find) return callback('id or find required');

	if(_.isObject(find)) {
		var q = data.list.model.find(find);
	} else {
		var q = data.list.model.findById(id);
	}

	var select = selectFields(data,data.list.apiOptions);
	if(select) q.select(select);
	if(data.populate) {
		q.populate(data.populate);
	} else {
		q.populate('createdBy updatedBy');
	}
	q.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		var send = {}
		send[data.list.path] = item;

		callback(null, send);

	});
}

/**
 * Create a Post
 */
exports.create = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for create',err,data);
	};
	var list = data.list;
	var doc = data.doc;
	var item = new list.model();

	if(!list) return callback('list required');
	if(!_.isObject(doc)) return callback('doc required');
	if(!_.isObject(req)) req = {};

	item.getUpdateHandler(req).process(doc, function(err) {

		if (err) {
			return callback(err);
		}
		var data2 = {}
		data2[list.path] = item;

		callback(null, data2);

	});
}

/**
 * Update Post by ID
 */
exports.update = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for update',err,data);
	};

	var list = data.list;
	var id = data.id || data._id;
	var doc = data.doc;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('id required');
	if(!_.isObject(doc)) return callback('data required');
	if(!_.isObject(req)) req = {};

	if(_.isObject(find)) {
		var lookup = list.model.find(find);
	} else {
		var lookup = list.model.findById(id);
	}

	lookup.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		item.getUpdateHandler(req).process(doc, function(err) {

			if (err) return callback(err);

			var data2 = {}
			data2[list.path] = item;

			callback(null, data2);

		});

	});
}

/**
 * Update Post Field
 */
exports.updateField = function(data, req, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for updateFIeld',err,data);
	};

	var list = data.list;
	var id = data.id  || data._id;
	var field = data.field;
	var value = data.value;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('find required');
	if(!field) return callback('field path required');
	//if(!value) callback('value required');
	if(!_.isObject(req)) req = {};

	if(_.isObject(find)) {
		var lookup = list.model.find(find);
	} else {
		var lookup = list.model.findById(id);
	}
	lookup.exec(function(err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		var data = {}
		data[field] = value;

		item.getUpdateHandler(req).process(data, function(err) {

			if (err) return callback(err);

			callback(null, data);

		});

	});
}

/**
 * Delete Post by ID
 */
exports.remove = function(data, socket, callback) {

	if(!_.isFunction(callback)) callback = function(err,data){
		console.log('callback not specified for remove',err,data);
	};

	var list = data.list;
	var id = data.id  || data._id;
	var find = data.find || data.query;

	if(!list) return callback('list required');
	if(!id && !find) return callback('id required');

	if(_.isObject(find)) {
		var lookup = list.model.find(find);
	} else {
		var lookup = list.model.findById(id);
	}
	lookup.exec(function (err, item) {

		if (err) return callback(err);
		if (!item) return callback('not found');

		item.remove(function (err) {
			if (err) return callback(err);

			return callback(null,{
				success: true
			});
		});

	});
}
<|endoftext|>


<commit_before>// Controller for user pages

UserPageController = RouteController.extend({

  waitOn: function() {
    return [
      coreSubscriptions.subscribe('singleUser', this.params._idOrSlug)
    ]
  },

  getUser: function () {
    return Meteor.users.findOne({slug: this.params._idOrSlug});
  },

  data: function() {
    var findById = Meteor.users.findOne(this.params._idOrSlug);
    var findBySlug = Meteor.users.findOne({slug: this.params._idOrSlug});
    if (typeof findById !== 'undefined') {
      // redirect to slug-based URL
      Router.go(getProfileUrl(findById), {replaceState: true});
    } else {
      return {
        user: (typeof findById == 'undefined') ? findBySlug : findById
      };
    }
  },

  getTitle: function () {
    return getDisplayName(this.getUser()) + ' - ' + getSetting('title', "Telescope");
  },

  getDescription: function () {
    return i18n.t('the_profile_of') + ' ' + getDisplayName(this.getUser());
  },

  fastRender: true

});

// Controller for user account editing

UserEditController = RouteController.extend({
  waitOn: function() {
    return [
      coreSubscriptions.subscribe('singleUser', this.params.slug)
    ]
  },
  data: function() {
    var user = Meteor.users.findOne({slug: this.params.slug});
    return {
      user: user
    };
  },
  fastRender: true
});

Meteor.startup(function () {

// User Logout

  Router.route('/sign-out', {
    name: 'signOut',
    template: getTemplate('sign_out'),
    onBeforeAction: function() {
      Meteor.logout(function() {
      });
      this.next();
    }
  });

  // User Profile

  Router.route('/users/:_idOrSlug', {
    name: 'user_profile',
    template: getTemplate('user_profile'),
    controller: UserPageController
  });

  // User Edit

  Router.route('/users/:slug/edit', {
    name: 'user_edit',
    template: getTemplate('user_edit'),
    controller: UserEditController,
    onBeforeAction: function () {
      // Only allow users with permissions to see the user edit page.
      if (Meteor.user() && (
        isAdmin(Meteor.user()) ||
        this.params.slug === Meteor.user().slug
      )) {
        this.next();
      } else {
        this.render(getTemplate('no_rights'));
      }
    }
  });

  // All Users

  Router.route('/all-users/:limit?', {
    name: 'all-users',
    template: getTemplate('users'),
    waitOn: function() {
      var limit = parseInt(this.params.limit) || 20;
      return coreSubscriptions.subscribe('allUsers', this.params.filterBy, this.params.sortBy, limit);
    },
    data: function() {
      var limit = parseInt(this.params.limit) || 20,
          parameters = getUsersParameters(this.params.query.filterBy, this.params.query.sortBy, limit),
          filterBy = (typeof this.params.query.filterBy === 'string') ? this.params.query.filterBy : 'all',
          sortBy = (typeof this.params.query.sortBy === 'string') ? this.params.query.sortBy : 'createdAt';
      Session.set('usersLimit', limit);
      return {
        users: Meteor.users.find(parameters.find, parameters.options),
        filterBy: filterBy,
        sortBy: sortBy
      };
    },
    fastRender: true
  });

  // Unsubscribe (from notifications)

  Router.route('/unsubscribe/:hash', {
    name: 'unsubscribe',
    template: getTemplate('unsubscribe'),
    data: function() {
      return {
        hash: this.params.hash
      };
    }
  });

});<commit_msg>Fix bug in profile page introduced from sandstorm's slug == _id<commit_after>// Controller for user pages

UserPageController = RouteController.extend({

  waitOn: function() {
    return [
      coreSubscriptions.subscribe('singleUser', this.params._idOrSlug)
    ]
  },

  getUser: function () {
    return Meteor.users.findOne({slug: this.params._idOrSlug});
  },

  data: function() {
    var findById = Meteor.users.findOne(this.params._idOrSlug);
    console.log('id: ' + findById);
    var findBySlug = Meteor.users.findOne({slug: this.params._idOrSlug});
    console.log('slig: ' + findBySlug);
    if (typeof findById !== 'undefined') {
      return {
        user: findById
      };
    } else {
      return {
        user: (typeof findById == 'undefined') ? findBySlug : findById
      };
    }
  },

  getTitle: function () {
    return getDisplayName(this.getUser()) + ' - ' + getSetting('title', "Telescope");
  },

  getDescription: function () {
    return i18n.t('the_profile_of') + ' ' + getDisplayName(this.getUser());
  },

  fastRender: true

});

// Controller for user account editing

UserEditController = RouteController.extend({
  waitOn: function() {
    return [
      coreSubscriptions.subscribe('singleUser', this.params.slug)
    ]
  },
  data: function() {
    var user = Meteor.users.findOne({slug: this.params.slug});
    return {
      user: user
    };
  },
  fastRender: true
});

Meteor.startup(function () {

// User Logout

  Router.route('/sign-out', {
    name: 'signOut',
    template: getTemplate('sign_out'),
    onBeforeAction: function() {
      Meteor.logout(function() {
      });
      this.next();
    }
  });

  // User Profile

  Router.route('/users/:_idOrSlug', {
    name: 'user_profile',
    template: getTemplate('user_profile'),
    controller: UserPageController
  });

  // User Edit

  Router.route('/users/:slug/edit', {
    name: 'user_edit',
    template: getTemplate('user_edit'),
    controller: UserEditController,
    onBeforeAction: function () {
      // Only allow users with permissions to see the user edit page.
      if (Meteor.user() && (
        isAdmin(Meteor.user()) ||
        this.params.slug === Meteor.user().slug
      )) {
        this.next();
      } else {
        this.render(getTemplate('no_rights'));
      }
    }
  });

  // All Users

  Router.route('/all-users/:limit?', {
    name: 'all-users',
    template: getTemplate('users'),
    waitOn: function() {
      var limit = parseInt(this.params.limit) || 20;
      return coreSubscriptions.subscribe('allUsers', this.params.filterBy, this.params.sortBy, limit);
    },
    data: function() {
      var limit = parseInt(this.params.limit) || 20,
          parameters = getUsersParameters(this.params.query.filterBy, this.params.query.sortBy, limit),
          filterBy = (typeof this.params.query.filterBy === 'string') ? this.params.query.filterBy : 'all',
          sortBy = (typeof this.params.query.sortBy === 'string') ? this.params.query.sortBy : 'createdAt';
      Session.set('usersLimit', limit);
      return {
        users: Meteor.users.find(parameters.find, parameters.options),
        filterBy: filterBy,
        sortBy: sortBy
      };
    },
    fastRender: true
  });

  // Unsubscribe (from notifications)

  Router.route('/unsubscribe/:hash', {
    name: 'unsubscribe',
    template: getTemplate('unsubscribe'),
    data: function() {
      return {
        hash: this.params.hash
      };
    }
  });

});
<|endoftext|>


<commit_before>// Blog routes
exports.blog = require('./blog');

// Portfolio page
exports.projects = function (req, res) {
  res.render('projects', {
    page: 'projects',
    title: 'Todd Wolfson - Projects',
    seoKeywords: 'dev tools, web tools, spritesmith, sexy-bash-prompt, File Watcher, jsmin-sourcemap, Find++',
    seoDescription: 'Projects by Todd Wolfson: spritesmith, sexy-bash-prompt, File Watcher, jsmin-sourcemap, Find++'
  });
};

// Contact route
exports.contact = require('./contact');

// Kaleido page
var yaml = require('js-yaml');
exports.kaleido = function (req, res) {
  var urls = require('../../test/perceptual-tests/urls');
  res.render('kaleido', {layout: false, urls: urls});
};

// Render a LICENSE page
var fs = require('fs'),
    license = fs.readFileSync(__dirname + '/../../LICENSE-MIT', 'utf8');
exports.license = function (req, res) {
  res.render('license', {
    page: 'license',
    license: license,
    title: 'Todd Wolfson - License',
    seoKeywords: 'license, mit',
    seoDescription: 'twolfson.com uses the MIT License'
  });
};

// Render a health page
var pkg = require('../../package.json'),
    pkgVersion = pkg.version;
exports.health = function (req, res) {
  var retObj = {
        'version': pkgVersion,
        'uptime': process.uptime(),
        'memory': process.memoryUsage(),
        'pid': process.pid
      };
  res.send(retObj);
};

// 404 page (no SEO here)
exports['404'] = function (req, res) {
  res.status(404);
  res.render('404', {'page': '404'});
};<commit_msg>Fixing dev dependency setup<commit_after>// Blog routes
exports.blog = require('./blog');

// Portfolio page
exports.projects = function (req, res) {
  res.render('projects', {
    page: 'projects',
    title: 'Todd Wolfson - Projects',
    seoKeywords: 'dev tools, web tools, spritesmith, sexy-bash-prompt, File Watcher, jsmin-sourcemap, Find++',
    seoDescription: 'Projects by Todd Wolfson: spritesmith, sexy-bash-prompt, File Watcher, jsmin-sourcemap, Find++'
  });
};

// Contact route
exports.contact = require('./contact');

// Kaleido page
exports.kaleido = function (req, res) {
  // DEV: Relocate js-yaml inside route for dev-only dependencies
  var yaml = require('js-yaml'),
      urls = require('../../test/perceptual-tests/urls');
  res.render('kaleido', {layout: false, urls: urls});
};

// Render a LICENSE page
var fs = require('fs'),
    license = fs.readFileSync(__dirname + '/../../LICENSE-MIT', 'utf8');
exports.license = function (req, res) {
  res.render('license', {
    page: 'license',
    license: license,
    title: 'Todd Wolfson - License',
    seoKeywords: 'license, mit',
    seoDescription: 'twolfson.com uses the MIT License'
  });
};

// Render a health page
var pkg = require('../../package.json'),
    pkgVersion = pkg.version;
exports.health = function (req, res) {
  var retObj = {
        'version': pkgVersion,
        'uptime': process.uptime(),
        'memory': process.memoryUsage(),
        'pid': process.pid
      };
  res.send(retObj);
};

// 404 page (no SEO here)
exports['404'] = function (req, res) {
  res.status(404);
  res.render('404', {'page': '404'});
};<|endoftext|>


<commit_before>import { config } from './config';
import instrument from './instrument';
import then from './then';
import {
  isFunction,
  now
} from './utils';

import {
  noop,
  initializePromise
} from './-internal';

import all from './promise/all';
import race from './promise/race';
import Resolve from './promise/resolve';
import Reject from './promise/reject';

var guidKey = 'rsvp_' + now() + '-';
var counter = 0;

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise’s eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.

  Basic Usage:
  ------------

  ```js
  var promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      var xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class RSVP.Promise
  @param {function} resolver
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @constructor
*/
export default function Promise(resolver, label) {
  this._id = counter++;
  this._label = label;
  this._state = undefined;
  this._result = undefined;
  this._subscribers = [];

  config.instrument && instrument('created', this);

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
}

Promise.cast = Resolve; // deprecated
Promise.all = all;
Promise.race = race;
Promise.resolve = Resolve;
Promise.reject = Reject;

Promise.prototype = {
  constructor: Promise,

  _guidKey: guidKey,

  _onError: function (reason) {
    var promise = this;
    config.after(function() {
      if (promise._onError) {
        config['trigger']('error', reason, promise._label);
      }
    });
  },

/**
  The primary way of interacting with a promise is through its `then` method,
  which registers callbacks to receive either a promise's eventual value or the
  reason why the promise cannot be fulfilled.

  ```js
  findUser().then(function(user){
    // user is available
  }, function(reason){
    // user is unavailable, and you are given the reason why
  });
  ```

  Chaining
  --------

  The return value of `then` is itself a promise.  This second, 'downstream'
  promise is resolved with the return value of the first promise's fulfillment
  or rejection handler, or rejected if the handler throws an exception.

  ```js
  findUser().then(function (user) {
    return user.name;
  }, function (reason) {
    return 'default name';
  }).then(function (userName) {
    // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
    // will be `'default name'`
  });

  findUser().then(function (user) {
    throw new Error('Found user, but still unhappy');
  }, function (reason) {
    throw new Error('`findUser` rejected and we're unhappy');
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
    // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  });
  ```
  If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.

  ```js
  findUser().then(function (user) {
    throw new PedagogicalException('Upstream error');
  }).then(function (value) {
    // never reached
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // The `PedgagocialException` is propagated all the way down to here
  });
  ```

  Assimilation
  ------------

  Sometimes the value you want to propagate to a downstream promise can only be
  retrieved asynchronously. This can be achieved by returning a promise in the
  fulfillment or rejection handler. The downstream promise will then be pending
  until the returned promise is settled. This is called *assimilation*.

  ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // The user's comments are now available
  });
  ```

  If the assimliated promise rejects, then the downstream promise will also reject.

  ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // If `findCommentsByAuthor` fulfills, we'll have the value here
  }, function (reason) {
    // If `findCommentsByAuthor` rejects, we'll have the reason here
  });
  ```

  Simple Example
  --------------

  Synchronous Example

  ```javascript
  var result;

  try {
    result = findResult();
    // success
  } catch(reason) {
    // failure
  }
  ```

  Errback Example

  ```js
  findResult(function(result, err){
    if (err) {
      // failure
    } else {
      // success
    }
  });
  ```

  Promise Example;

  ```javascript
  findResult().then(function(result){
    // success
  }, function(reason){
    // failure
  });
  ```

  Advanced Example
  --------------

  Synchronous Example

  ```javascript
  var author, books;

  try {
    author = findAuthor();
    books  = findBooksByAuthor(author);
    // success
  } catch(reason) {
    // failure
  }
  ```

  Errback Example

  ```js

  function foundBooks(books) {

  }

  function failure(reason) {

  }

  findAuthor(function(author, err){
    if (err) {
      failure(err);
      // failure
    } else {
      try {
        findBoooksByAuthor(author, function(books, err) {
          if (err) {
            failure(err);
          } else {
            try {
              foundBooks(books);
            } catch(reason) {
              failure(reason);
            }
          }
        });
      } catch(error) {
        failure(err);
      }
      // success
    }
  });
  ```

  Promise Example;

  ```javascript
  findAuthor().
    then(findBooksByAuthor).
    then(function(books){
      // found books
  }).catch(function(reason){
    // something went wrong
  });
  ```

  @method then
  @param {Function} onFulfillment
  @param {Function} onRejection
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  then: then,

/**
  `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  as the catch block of a try/catch statement.

  ```js
  function findAuthor(){
    throw new Error('couldn't find that author');
  }

  // synchronous
  try {
    findAuthor();
  } catch(reason) {
    // something went wrong
  }

  // async with promises
  findAuthor().catch(function(reason){
    // something went wrong
  });
  ```

  @method catch
  @param {Function} onRejection
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  'catch': function(onRejection, label) {
    return this.then(undefined, onRejection, label);
  },

/**
  `finally` will be invoked regardless of the promise's fate just as native
  try/catch/finally behaves

  Synchronous example:

  ```js
  findAuthor() {
    if (Math.random() > 0.5) {
      throw new Error();
    }
    return new Author();
  }

  try {
    return findAuthor(); // succeed or fail
  } catch(error) {
    return findOtherAuther();
  } finally {
    // always runs
    // doesn't affect the return value
  }
  ```

  Asynchronous example:

  ```js
  findAuthor().catch(function(reason){
    return findOtherAuther();
  }).finally(function(){
    // author was either found, or not
  });
  ```

  @method finally
  @param {Function} callback
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  'finally': function(callback, label) {
    var promise = this;
    var constructor = promise.constructor;

    return promise.then(function(value) {
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    }, function(reason) {
      return constructor.resolve(callback()).then(function() {
        return constructor.reject(reason);
      });
    }, label);
  }
};
<commit_msg>Escape single quotes (apostrophes) in contractions<commit_after>import { config } from './config';
import instrument from './instrument';
import then from './then';
import {
  isFunction,
  now
} from './utils';

import {
  noop,
  initializePromise
} from './-internal';

import all from './promise/all';
import race from './promise/race';
import Resolve from './promise/resolve';
import Reject from './promise/reject';

var guidKey = 'rsvp_' + now() + '-';
var counter = 0;

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise’s eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.

  Basic Usage:
  ------------

  ```js
  var promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      var xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class RSVP.Promise
  @param {function} resolver
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @constructor
*/
export default function Promise(resolver, label) {
  this._id = counter++;
  this._label = label;
  this._state = undefined;
  this._result = undefined;
  this._subscribers = [];

  config.instrument && instrument('created', this);

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
}

Promise.cast = Resolve; // deprecated
Promise.all = all;
Promise.race = race;
Promise.resolve = Resolve;
Promise.reject = Reject;

Promise.prototype = {
  constructor: Promise,

  _guidKey: guidKey,

  _onError: function (reason) {
    var promise = this;
    config.after(function() {
      if (promise._onError) {
        config['trigger']('error', reason, promise._label);
      }
    });
  },

/**
  The primary way of interacting with a promise is through its `then` method,
  which registers callbacks to receive either a promise's eventual value or the
  reason why the promise cannot be fulfilled.

  ```js
  findUser().then(function(user){
    // user is available
  }, function(reason){
    // user is unavailable, and you are given the reason why
  });
  ```

  Chaining
  --------

  The return value of `then` is itself a promise.  This second, 'downstream'
  promise is resolved with the return value of the first promise's fulfillment
  or rejection handler, or rejected if the handler throws an exception.

  ```js
  findUser().then(function (user) {
    return user.name;
  }, function (reason) {
    return 'default name';
  }).then(function (userName) {
    // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
    // will be `'default name'`
  });

  findUser().then(function (user) {
    throw new Error('Found user, but still unhappy');
  }, function (reason) {
    throw new Error('`findUser` rejected and we\'re unhappy');
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
    // If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'.
  });
  ```
  If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.

  ```js
  findUser().then(function (user) {
    throw new PedagogicalException('Upstream error');
  }).then(function (value) {
    // never reached
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // The `PedgagocialException` is propagated all the way down to here
  });
  ```

  Assimilation
  ------------

  Sometimes the value you want to propagate to a downstream promise can only be
  retrieved asynchronously. This can be achieved by returning a promise in the
  fulfillment or rejection handler. The downstream promise will then be pending
  until the returned promise is settled. This is called *assimilation*.

  ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // The user's comments are now available
  });
  ```

  If the assimliated promise rejects, then the downstream promise will also reject.

  ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // If `findCommentsByAuthor` fulfills, we'll have the value here
  }, function (reason) {
    // If `findCommentsByAuthor` rejects, we'll have the reason here
  });
  ```

  Simple Example
  --------------

  Synchronous Example

  ```javascript
  var result;

  try {
    result = findResult();
    // success
  } catch(reason) {
    // failure
  }
  ```

  Errback Example

  ```js
  findResult(function(result, err){
    if (err) {
      // failure
    } else {
      // success
    }
  });
  ```

  Promise Example;

  ```javascript
  findResult().then(function(result){
    // success
  }, function(reason){
    // failure
  });
  ```

  Advanced Example
  --------------

  Synchronous Example

  ```javascript
  var author, books;

  try {
    author = findAuthor();
    books  = findBooksByAuthor(author);
    // success
  } catch(reason) {
    // failure
  }
  ```

  Errback Example

  ```js

  function foundBooks(books) {

  }

  function failure(reason) {

  }

  findAuthor(function(author, err){
    if (err) {
      failure(err);
      // failure
    } else {
      try {
        findBoooksByAuthor(author, function(books, err) {
          if (err) {
            failure(err);
          } else {
            try {
              foundBooks(books);
            } catch(reason) {
              failure(reason);
            }
          }
        });
      } catch(error) {
        failure(err);
      }
      // success
    }
  });
  ```

  Promise Example;

  ```javascript
  findAuthor().
    then(findBooksByAuthor).
    then(function(books){
      // found books
  }).catch(function(reason){
    // something went wrong
  });
  ```

  @method then
  @param {Function} onFulfillment
  @param {Function} onRejection
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  then: then,

/**
  `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  as the catch block of a try/catch statement.

  ```js
  function findAuthor(){
    throw new Error('couldn\'t find that author');
  }

  // synchronous
  try {
    findAuthor();
  } catch(reason) {
    // something went wrong
  }

  // async with promises
  findAuthor().catch(function(reason){
    // something went wrong
  });
  ```

  @method catch
  @param {Function} onRejection
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  'catch': function(onRejection, label) {
    return this.then(undefined, onRejection, label);
  },

/**
  `finally` will be invoked regardless of the promise's fate just as native
  try/catch/finally behaves

  Synchronous example:

  ```js
  findAuthor() {
    if (Math.random() > 0.5) {
      throw new Error();
    }
    return new Author();
  }

  try {
    return findAuthor(); // succeed or fail
  } catch(error) {
    return findOtherAuther();
  } finally {
    // always runs
    // doesn't affect the return value
  }
  ```

  Asynchronous example:

  ```js
  findAuthor().catch(function(reason){
    return findOtherAuther();
  }).finally(function(){
    // author was either found, or not
  });
  ```

  @method finally
  @param {Function} callback
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise}
*/
  'finally': function(callback, label) {
    var promise = this;
    var constructor = promise.constructor;

    return promise.then(function(value) {
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    }, function(reason) {
      return constructor.resolve(callback()).then(function() {
        return constructor.reject(reason);
      });
    }, label);
  }
};
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Promise = require('bluebird');
const Runner = require('./runner');
const TestSessionRunner = require('./test-session-runner');
const Coverage = require('../coverage');
const Events = require('../constants/events');

module.exports = class TestsRunner extends Runner {
    static create(config, stateProcessor) {
        return new TestsRunner(config, stateProcessor);
    }

    constructor(config, stateProcessor) {
        super();

        this.config = config;
        this._stateProcessor = stateProcessor;
        this.coverage = this.config.isCoverageEnabled() && new Coverage(config);
    }

    setTestBrowsers(browsers) {
        this._testBrowsers = browsers;
    }

    /**
     * @param {SuiteCollection} SuiteCollection
     * @returns {*}
     */
    run(suiteCollection) {
        const suites = suiteCollection.allSuites();

        return Promise.try(() => {
            this.emitAndWait(Events.START_RUNNER, this);
            this.emit(Events.BEGIN, {
                config: this.config,
                totalStates: _.reduce(suites, (result, suite) => {
                    return result + suite.states.length;
                }, 0),
                browserIds: this.config.getBrowserIds()
            });
        })
        .then(() => this._prepare())
        .then(() => this._runTestSession(suiteCollection))
        .then(() => this.coverage && this.coverage.processStats())
        .finally(() => {
            this.emit(Events.END);
            this.emitAndWait(Events.END_RUNNER, this);
        });
    }

    _runTestSession(suiteCollection) {
        const sessionRunner = TestSessionRunner.create(this.config, this._testBrowsers);

        this.passthroughEvent(sessionRunner, [
            Events.BEGIN_SESSION,
            Events.END_SESSION,
            Events.START_BROWSER,
            Events.STOP_BROWSER,
            Events.INFO,
            Events.BEGIN_SUITE,
            Events.END_SUITE,
            Events.SKIP_STATE,
            Events.BEGIN_STATE,
            Events.END_STATE,
            Events.ERROR,
            Events.WARNING,
            Events.RETRY
        ]);

        sessionRunner.on(Events.TEST_RESULT, (result) => this._handleTestResult(result));
        sessionRunner.on(Events.CAPTURE, (result) => this._handleCapture(result));
        sessionRunner.on(Events.UPDATE_RESULT, (result) => this._handleUpdateResult(result));

        return sessionRunner.run(suiteCollection, this._stateProcessor);
    }

    _prepare() {
        return this._stateProcessor.prepare(this);
    }

    _handleTestResult(result) {
        this._saveCoverage(result);

        this.emit(Events.END_TEST, result);
        this.emit(Events.TEST_RESULT, result);
    }

    _handleCapture(result) {
        this._saveCoverage(result);
        this.emit(Events.CAPTURE, result);
    }

    _handleUpdateResult(result) {
        this._saveCoverage(result);
        this.emit(Events.UPDATE_RESULT, result);
    }

    _saveCoverage(data) {
        if (this.coverage) {
            this.coverage.addStatsForBrowser(data.coverage, data.browserId);
        }
    }
};
<commit_msg>Actually wait for START_RUNNER event to complete<commit_after>'use strict';

const _ = require('lodash');
const Promise = require('bluebird');
const Runner = require('./runner');
const TestSessionRunner = require('./test-session-runner');
const Coverage = require('../coverage');
const Events = require('../constants/events');

module.exports = class TestsRunner extends Runner {
    static create(config, stateProcessor) {
        return new TestsRunner(config, stateProcessor);
    }

    constructor(config, stateProcessor) {
        super();

        this.config = config;
        this._stateProcessor = stateProcessor;
        this.coverage = this.config.isCoverageEnabled() && new Coverage(config);
    }

    setTestBrowsers(browsers) {
        this._testBrowsers = browsers;
    }

    /**
     * @param {SuiteCollection} SuiteCollection
     * @returns {*}
     */
    run(suiteCollection) {
        const suites = suiteCollection.allSuites();

        return Promise.resolve(this.emitAndWait(Events.START_RUNNER, this))
            .then(() => {
                this.emit(Events.BEGIN, {
                    config: this.config,
                    totalStates: _.reduce(suites, (result, suite) => {
                        return result + suite.states.length;
                    }, 0),
                    browserIds: this.config.getBrowserIds()
                });
            })
            .then(() => this._prepare())
            .then(() => this._runTestSession(suiteCollection))
            .then(() => this.coverage && this.coverage.processStats())
            .finally(() => {
                this.emit(Events.END);
                this.emitAndWait(Events.END_RUNNER, this);
            });
    }

    _runTestSession(suiteCollection) {
        const sessionRunner = TestSessionRunner.create(this.config, this._testBrowsers);

        this.passthroughEvent(sessionRunner, [
            Events.BEGIN_SESSION,
            Events.END_SESSION,
            Events.START_BROWSER,
            Events.STOP_BROWSER,
            Events.INFO,
            Events.BEGIN_SUITE,
            Events.END_SUITE,
            Events.SKIP_STATE,
            Events.BEGIN_STATE,
            Events.END_STATE,
            Events.ERROR,
            Events.WARNING,
            Events.RETRY
        ]);

        sessionRunner.on(Events.TEST_RESULT, (result) => this._handleTestResult(result));
        sessionRunner.on(Events.CAPTURE, (result) => this._handleCapture(result));
        sessionRunner.on(Events.UPDATE_RESULT, (result) => this._handleUpdateResult(result));

        return sessionRunner.run(suiteCollection, this._stateProcessor);
    }

    _prepare() {
        return this._stateProcessor.prepare(this);
    }

    _handleTestResult(result) {
        this._saveCoverage(result);

        this.emit(Events.END_TEST, result);
        this.emit(Events.TEST_RESULT, result);
    }

    _handleCapture(result) {
        this._saveCoverage(result);
        this.emit(Events.CAPTURE, result);
    }

    _handleUpdateResult(result) {
        this._saveCoverage(result);
        this.emit(Events.UPDATE_RESULT, result);
    }

    _saveCoverage(data) {
        if (this.coverage) {
            this.coverage.addStatsForBrowser(data.coverage, data.browserId);
        }
    }
};
<|endoftext|>


<commit_before>var Database = require("./Database");
var Log = require("./Log");

var tools = {
    setpremium: function(email, premium) {
        Database.connect(process.env.MONGO_URL, function(err) {
            if (err) {
                throw err;
            }
            Database.models.Account.findOne({email: email}, function (err, acc) {
                if (err) {
                    throw  err;
                }
                if (!acc) {
                    throw "Not found";
                }
                acc.isPremium = !!premium;
                acc.save(function(err) {
                    if (err) {
                        throw  err;
                    }
                    process.exit();
                });
            });
        });
    },

    userlist: function() {
        Database.connect(process.env.MONGO_URL, function(err) {
            if (err) {
                throw err;
            }
            Database.models.Account.find({}, function (err, accounts) {
                if (err) {
                    throw  err;
                }
                accounts.forEach(function(account) {
                    Logger.info(account.email, account.name, account.isPremium);
                });
            });
        });
    }
};

tools[process.argv[2]].apply(null, process.argv.slice(3));
<commit_msg>tools fix<commit_after>var Database = require("./Database");
var Log = require("./Log");

var tools = {
    setpremium: function(email, premium) {
        Database.connect(process.env.MONGO_URL, function(err) {
            if (err) {
                throw err;
            }
            Database.models.Account.findOne({email: email}, function (err, acc) {
                if (err) {
                    throw  err;
                }
                if (!acc) {
                    throw "Not found";
                }
                acc.isPremium = !!premium;
                acc.save(function(err) {
                    if (err) {
                        throw  err;
                    }
                    process.exit();
                });
            });
        });
    },

    userlist: function() {
        Database.connect(process.env.MONGO_URL, function(err) {
            if (err) {
                throw err;
            }
            Database.models.Account.find({}, function (err, accounts) {
                if (err) {
                    throw  err;
                }
                accounts.forEach(function(account) {
                    Log.info(account.email, account.name, account.isPremium);
                });
            });
        });
    }
};

tools[process.argv[2]].apply(null, process.argv.slice(3));
<|endoftext|>


<commit_before>(function ($) {

  Drupal.CultureFeed = Drupal.CultureFeed || {};
  Drupal.CultureFeed.Agenda = {};

  $(document).ready(function() {

    var $nearby_checkbox = $('#culturefeed-agenda-search-block-form').find('input[name="nearby"]');
    if (navigator.geolocation) {

     $nearby_checkbox.bind('change', function() {

       if (this.checked) {
         Drupal.CultureFeed.geolocate('#current-location', 'input[id="geolocate-coordinates"]', 'input[id="geolocate-city"]');
       }

     });

     if ($nearby_checkbox.is(':checked')) {
       $nearby_checkbox.trigger('change');
     }

    }
    else {
      $nearby_checkbox.parent().hide();
    }

  });

})(jQuery);
<commit_msg>CFK-32 make it possible to theme loading state<commit_after>(function ($) {

  Drupal.CultureFeed = Drupal.CultureFeed || {};
  Drupal.CultureFeed.Agenda = {};

  $(document).ready(function() {

    var $nearby_checkbox = $('#culturefeed-agenda-search-block-form').find('input[name="nearby"]');
    if (navigator.geolocation) {

      $nearby_checkbox.bind('change', function() {

        if (this.checked) {
          $('#current-location').html('');
          Drupal.CultureFeed.geolocate('#current-location', 'input[id="geolocate-coordinates"]', 'input[id="geolocate-city"]');
       }

     });

     if ($nearby_checkbox.is(':checked')) {
       $nearby_checkbox.trigger('change');
     }

    }
    else {
      $nearby_checkbox.parent().hide();
    }

  });

})(jQuery);
<|endoftext|>


<commit_before>(function($) {
  $(Screw)
    .bind('loaded', function() {
      $('.describe, .it')
        .click(function() {
          document.location = location.href.split('?')[0] + '?' + $(this).fn('selector');
          return false;
        })
        .focus(function() {
          return $(this).addClass('focused');
        })
        .bind('scroll', function() {
          document.body.scrollTop = $(this).offset().top;
        });

      $('.it')
        .bind('enqueued', function() {
          $(this).addClass('enqueued');
        })
        .bind('running', function() {
          $(this).addClass('running');
        })
        .bind('passed', function() {
          $(this).addClass('passed');
        })
        .bind('failed', function(e, reason) {
          $(this)
            .addClass('failed')
            .append($('
').text(reason.toString()));
          if (reason.fileName || reason.lineNumber) {
            $(this)
              .append($('
').text(reason.fileName + " : " + reason.lineNumber));
          }
        })
    })
    .bind('before', function() {
      $('.status').text('Running...');
    })
    .bind('after', function() {
      $('.status').fn('display')
    })
})(jQuery);<commit_msg>handling filename and linenumbers of exceptions for ff and safari<commit_after>(function($) {
  $(Screw)
    .bind('loaded', function() {
      $('.describe, .it')
        .click(function() {
          document.location = location.href.split('?')[0] + '?' + $(this).fn('selector');
          return false;
        })
        .focus(function() {
          return $(this).addClass('focused');
        })
        .bind('scroll', function() {
          document.body.scrollTop = $(this).offset().top;
        });

      $('.it')
        .bind('enqueued', function() {
          $(this).addClass('enqueued');
        })
        .bind('running', function() {
          $(this).addClass('running');
        })
        .bind('passed', function() {
          $(this).addClass('passed');
        })
        .bind('failed', function(e, reason) {
          $(this)
            .addClass('failed')
            .append($('
').text(reason.toString()))

          var file = reason.fileName || reason.sourceURL;
          var line = reason.lineNumber || reason.line;
          if (file || line) {
            $(this).append($('
').text('line ' + line + ', ' + file));
          }
        })
    })
    .bind('before', function() {
      $('.status').text('Running...');
    })
    .bind('after', function() {
      $('.status').fn('display')
    })
})(jQuery);<|endoftext|>


<commit_before>'use strict'
module.exports = function(gulp, plugins, config, name, file) { // eslint-disable-line func-names
  const theme = config.themes[name]
  const srcBase = plugins.path.join(config.config.tempPath, theme.dest)
  const sassLintConfig = require('../helper/config-loader')('sass-lint.yml', plugins, config)

  return gulp.src(file || plugins.globby.sync(srcBase + '/**/*.scss'))
    .pipe(plugins.if(
      !plugins.util.env.ci,
      plugins.plumber({
        errorHandler: plugins.notify.onError('Error: <%= error.message %>')
      })
    ))
    .pipe(plugins.sassLint(sassLintConfig))
    .pipe(plugins.sassLint.format())
    .pipe(plugins.if(plugins.util.env.ci, plugins.sassLint.failOnError()))
    .pipe(plugins.logger({
      display   : 'name',
      beforeEach: 'Theme: ' + name + ' ' + 'File: ',
      afterEach : ' - SASS Lint finished.'
    }))
}
<commit_msg>sasslint task typo fix<commit_after>'use strict'
module.exports = function(gulp, plugins, config, name, file) { // eslint-disable-line func-names
  const theme = config.themes[name]
  const srcBase = plugins.path.join(config.tempPath, theme.dest)
  const sassLintConfig = require('../helper/config-loader')('sass-lint.yml', plugins, config)

  return gulp.src(file || plugins.globby.sync(srcBase + '/**/*.scss'))
    .pipe(plugins.if(
      !plugins.util.env.ci,
      plugins.plumber({
        errorHandler: plugins.notify.onError('Error: <%= error.message %>')
      })
    ))
    .pipe(plugins.sassLint(sassLintConfig))
    .pipe(plugins.sassLint.format())
    .pipe(plugins.if(plugins.util.env.ci, plugins.sassLint.failOnError()))
    .pipe(plugins.logger({
      display   : 'name',
      beforeEach: 'Theme: ' + name + ' ' + 'File: ',
      afterEach : ' - SASS Lint finished.'
    }))
}
<|endoftext|>