<commit_before>// Sandstorm - Personal Cloud Sandbox
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var Crypto = Npm.require("crypto");
var HOSTNAME = process.env.ROOT_URL;
var stripe = Npm.require("stripe")(Meteor.settings.stripeKey);

BlackrockPayments = {};

var serveCheckout = Meteor.bindEnvironment(function (res) {
  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(Assets.getText("checkout.html").replace(
      "$STRIPE_KEY", Meteor.settings.public.stripePublicKey));
});

var serveSandcat = Meteor.bindEnvironment(function (res) {
  res.writeHead(200, { "Content-Type": "image/png" });
  // Meteor's buffer isn't a real buffer, so we have to do a copy
  res.end(new Buffer(Assets.getBinary("sandstorm-purplecircle.png")));
});

function hashId(id) {
  return Crypto.createHash("sha256").update(HOSTNAME + ":" + id).digest("base64");
}

function findOriginalId(hashedId, customerId) {
  var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
  if (data.sources && data.sources.data) {
    var sources = data.sources.data;
    for (var i = 0; i < sources.length; i++) {
      if (hashId(sources[i].id) === hashedId) {
        return sources[i].id;
      }
    }
  }

  throw new Meteor.Error(400, "Id not found");
}

function sanitizeSource(source, isPrimary) {
  var result = _.pick(source, "last4", "brand", "exp_year", "exp_month", "isPrimary");
  result.isPrimary = isPrimary;
  result.id = hashId(source.id);
  return result;
}

BlackrockPayments.makeConnectHandler = function (db) {
  return function (req, res, next) {
    if (req.headers.host == db.makeWildcardHost("payments")) {
      if (req.url == "/checkout") {
        serveCheckout(res);
      } else if (req.url == "/sandstorm-purplecircle.png") {
        serveSandcat(res);
      } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("404 not found: " + req.url);
      }
    } else {
      next();
    }
  };
}

function createUser(token, email) {
  var data = Meteor.wrapAsync(stripe.customers.create.bind(stripe.customers))({
    source: token,
    email: email,
    description: Meteor.userId()  // TODO(soon): Do we want to store backrefs to our database in stripe?
  });
  Meteor.users.update({_id: Meteor.userId()}, {$set: {payments: {id: data.id}}});
  return data;
}

var methods = {
  addCardForUser: function (token, email) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to add card");
    }
    check(token, String);
    check(email, String);

    var user = Meteor.user();

    if (user.payments && user.payments.id) {
      return sanitizeSource(Meteor.wrapAsync(stripe.customers.createSource.bind(stripe.customers))(
        user.payments.id,
        {source: token}
      ), false);
    } else {
      var data = createUser(token, email);
      if (data.sources && data.sources.data && data.sources.data.length >= 1) {
        return sanitizeSource(data.sources.data[0], true);
      }
    }
  },

  deleteCardForUser: function (id) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to delete card");
    }
    check(id, String);

    var customerId = Meteor.user().payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
    if (data.sources && data.sources.data && data.subscriptions && data.subscriptions.data) {
      var sources = data.sources.data;
      var subscriptions = data.subscriptions.data;
      if (sources.length == 1 && subscriptions.length > 0) {
        // TODO(soon): handle this better (client-side?)
        throw new Meteor.Error(400, "Can't delete last card if still subscribed");
      }
    }

    id = findOriginalId(id, customerId);

    Meteor.wrapAsync(stripe.customers.deleteCard.bind(stripe.customers))(
      customerId,
      id
    );
  },

  makeCardPrimary: function (id) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to change primary card");
    }
    check(id, String);

    var customerId = Meteor.user().payments.id;
    id = findOriginalId(id, customerId);

    Meteor.wrapAsync(stripe.customers.update.bind(stripe.customers))(
      customerId,
      {default_source: id}
    );
  },

  getStripeData: function () {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to get stripe data");
    }
    var payments = Meteor.user().payments;
    if (!payments) {
      return {};
    }
    var customerId = payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
    if (data.sources && data.sources.data) {
      var sources = data.sources.data;
      for (var i = 0; i < sources.length; i++) {
        sources[i] = sanitizeSource(sources[i], sources[i].id === data.default_source);
      }
    }

    var subscription;
    if (data.subscriptions && data.subscriptions.data[0]) {
      // Plan names end with "-beta".
      subscription = data.subscriptions.data[0].plan.id.split("-")[0];
    }
    return {
      email: data.email,
      subscription: subscription,
      sources: data.sources && data.sources.data,
      credit: -(data.account_balance || -0)
    };
  },

  updateUserSubscription: function (newPlan) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to update subscription");
    }
    check(newPlan, String);

    var planInfo = this.connection.sandstormDb.getPlan(newPlan);

    var payments = Meteor.user().payments;
    if (!payments) {
      throw new Meteor.Error(403, "User must have stripe data already");
    }
    var customerId = payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);

    if (newPlan === "free") {
      if (data.subscriptions && data.subscriptions.data.length > 0) {
        // TODO(someday): pass in at_period_end and properly handle pending cancelled subscriptions
        Meteor.wrapAsync(stripe.customers.cancelSubscription.bind(stripe.customers))(
          customerId,
          data.subscriptions.data[0].id
        );
      }
      // else: no subscriptions exist so we're already set to free
    } else {
      if (data.subscriptions && data.subscriptions.data.length > 0) {
        Meteor.wrapAsync(stripe.customers.updateSubscription.bind(stripe.customers))(
          customerId,
          data.subscriptions.data[0].id,
          {plan: newPlan + "-beta"}
        );
      } else {
        Meteor.wrapAsync(stripe.customers.createSubscription.bind(stripe.customers))(
          customerId,
          {plan: newPlan + "-beta"}
        );
      }
    }

    Meteor.users.update({_id: this.userId}, {$set: { plan: newPlan }});
  },

  createUserSubscription: function (token, email, plan) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to update subscription");
    }
    check(token, String);
    check(email, String);
    check(plan, String);

    var payments = Meteor.user().payments;
    var customerId;
    var sanitizedSource;
    if (!payments || !payments.id) {
      var data = createUser(token, email);
      customerId = data.id;
      if (data.sources && data.sources.data && data.sources.data.length >= 1) {
        sanitizedSource = sanitizeSource(data.sources.data[0]);
      }
    } else {
      customerId = payments.id;
      sanitizedSource = methods.addCardForUser.bind(this)(token, email);
    }
    Meteor.wrapAsync(stripe.customers.createSubscription.bind(stripe.customers))(
      customerId,
      {plan: plan + "-beta"}
    );
    Meteor.users.update({_id: this.userId}, {$set: { plan: plan }});
    return sanitizedSource;
  }
};
Meteor.methods(methods);

Meteor.publish("plans", function () {
  return this.connection.sandstormDb.listPlans();
});

function getAllStripeCustomers() {
  var hasMore = true;
  var results = [];

  var req = {limit: 100};
  while (hasMore) {
    var next = Meteor.wrapAsync(stripe.customers.list.bind(stripe.customers))(req);
    results = results.concat(next.data);
    hasMore = next.has_more;
    if (hasMore) {
      req.starting_after = results.slice(-1)[0];
    }
  }
  return results;
}

SandstormDb.paymentsMigrationHook = function (SignupKeys, plans) {
  var db = this;
  var customers = getAllStripeCustomers();
  console.log("got customers", customers.length);
  if (!customers) throw new Error("missing customers");

  var byEmail = {};
  for (var i in customers) {
    var customer = customers[i];
    byEmail[customer.email] = byEmail[customer.email] || [];
    byEmail[customer.email].push(customer);
  }

  var byQuota = {};
  for (var i in plans) {
    if (plans[i]._id !== "free") {
      byQuota[plans[i].storage] = plans[i]._id;
    }
  }

  function getCustomerByEmail(email, quota) {
    var customer = (byEmail[email] || []).shift();
    if (customer) {
      var plan;
      if (customer.subscriptions && customer.subscriptions.data[0]) {
        // Plan names end with "-beta".
        plan = customer.subscriptions.data[0].plan.id.split("-")[0];
      } else {
        plan = "free";
      }
      return {plan: plan, payments: {id: customer.id}};
    }
  }

  Meteor.users.find({quota: {$exists: true}}).forEach(function (user) {
    if (user.signupEmail) {
      var customer = getCustomerByEmail(user.signupEmail, user.quota);
      if (customer) {
        console.log("user", user._id, user.signupEmail, "=>", JSON.stringify(customer));
        Meteor.users.update({_id: user._id}, {$set: customer});
      } else {
        console.error("ERROR: missing customer for email (user):", email, user._id);
      }
    } else {
      console.warn("WARNING: user was not invited by email:",
          user._id, SandstormDb.getUserIdentities(user));
    }
  });

  SignupKeys.find({quota: {$exists: true}, used: false}).forEach(function (signupKey) {
    if (signupKey.email) {
      var customer = getCustomerByEmail(signupKey.email, signupKey.quota);
      if (customer) {
        console.log("invite", signupKey.email, "=>", JSON.stringify(customer));
        SignupKeys.update({_id: signupKey._id}, {$set: customer});
      } else {
        console.error("ERROR: missing customer for email (invite):", email, signupKey._id);
      }
    } else {
      console.warn("WARNING: non-email invite:", signupKey.note);
    }
  });

  for (var email in byEmail) {
    byEmail[email].forEach(function (customer) {
      console.error("ERROR: customer not used:", customer.id, email);
    });
  }
}
<commit_msg>aarrrggghhhhhh<commit_after>// Sandstorm - Personal Cloud Sandbox
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var Crypto = Npm.require("crypto");
var HOSTNAME = process.env.ROOT_URL;
var stripe = Npm.require("stripe")(Meteor.settings.stripeKey);

BlackrockPayments = {};

var serveCheckout = Meteor.bindEnvironment(function (res) {
  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(Assets.getText("checkout.html").replace(
      "$STRIPE_KEY", Meteor.settings.public.stripePublicKey));
});

var serveSandcat = Meteor.bindEnvironment(function (res) {
  res.writeHead(200, { "Content-Type": "image/png" });
  // Meteor's buffer isn't a real buffer, so we have to do a copy
  res.end(new Buffer(Assets.getBinary("sandstorm-purplecircle.png")));
});

function hashId(id) {
  return Crypto.createHash("sha256").update(HOSTNAME + ":" + id).digest("base64");
}

function findOriginalId(hashedId, customerId) {
  var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
  if (data.sources && data.sources.data) {
    var sources = data.sources.data;
    for (var i = 0; i < sources.length; i++) {
      if (hashId(sources[i].id) === hashedId) {
        return sources[i].id;
      }
    }
  }

  throw new Meteor.Error(400, "Id not found");
}

function sanitizeSource(source, isPrimary) {
  var result = _.pick(source, "last4", "brand", "exp_year", "exp_month", "isPrimary");
  result.isPrimary = isPrimary;
  result.id = hashId(source.id);
  return result;
}

BlackrockPayments.makeConnectHandler = function (db) {
  return function (req, res, next) {
    if (req.headers.host == db.makeWildcardHost("payments")) {
      if (req.url == "/checkout") {
        serveCheckout(res);
      } else if (req.url == "/sandstorm-purplecircle.png") {
        serveSandcat(res);
      } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("404 not found: " + req.url);
      }
    } else {
      next();
    }
  };
}

function createUser(token, email) {
  var data = Meteor.wrapAsync(stripe.customers.create.bind(stripe.customers))({
    source: token,
    email: email,
    description: Meteor.userId()  // TODO(soon): Do we want to store backrefs to our database in stripe?
  });
  Meteor.users.update({_id: Meteor.userId()}, {$set: {payments: {id: data.id}}});
  return data;
}

var methods = {
  addCardForUser: function (token, email) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to add card");
    }
    check(token, String);
    check(email, String);

    var user = Meteor.user();

    if (user.payments && user.payments.id) {
      return sanitizeSource(Meteor.wrapAsync(stripe.customers.createSource.bind(stripe.customers))(
        user.payments.id,
        {source: token}
      ), false);
    } else {
      var data = createUser(token, email);
      if (data.sources && data.sources.data && data.sources.data.length >= 1) {
        return sanitizeSource(data.sources.data[0], true);
      }
    }
  },

  deleteCardForUser: function (id) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to delete card");
    }
    check(id, String);

    var customerId = Meteor.user().payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
    if (data.sources && data.sources.data && data.subscriptions && data.subscriptions.data) {
      var sources = data.sources.data;
      var subscriptions = data.subscriptions.data;
      if (sources.length == 1 && subscriptions.length > 0) {
        // TODO(soon): handle this better (client-side?)
        throw new Meteor.Error(400, "Can't delete last card if still subscribed");
      }
    }

    id = findOriginalId(id, customerId);

    Meteor.wrapAsync(stripe.customers.deleteCard.bind(stripe.customers))(
      customerId,
      id
    );
  },

  makeCardPrimary: function (id) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to change primary card");
    }
    check(id, String);

    var customerId = Meteor.user().payments.id;
    id = findOriginalId(id, customerId);

    Meteor.wrapAsync(stripe.customers.update.bind(stripe.customers))(
      customerId,
      {default_source: id}
    );
  },

  getStripeData: function () {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to get stripe data");
    }
    var payments = Meteor.user().payments;
    if (!payments) {
      return {};
    }
    var customerId = payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);
    if (data.sources && data.sources.data) {
      var sources = data.sources.data;
      for (var i = 0; i < sources.length; i++) {
        sources[i] = sanitizeSource(sources[i], sources[i].id === data.default_source);
      }
    }

    var subscription;
    if (data.subscriptions && data.subscriptions.data[0]) {
      // Plan names end with "-beta".
      subscription = data.subscriptions.data[0].plan.id.split("-")[0];
    }
    return {
      email: data.email,
      subscription: subscription,
      sources: data.sources && data.sources.data,
      credit: -(data.account_balance || -0)
    };
  },

  updateUserSubscription: function (newPlan) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to update subscription");
    }
    check(newPlan, String);

    var planInfo = this.connection.sandstormDb.getPlan(newPlan);

    var payments = Meteor.user().payments;
    if (!payments) {
      throw new Meteor.Error(403, "User must have stripe data already");
    }
    var customerId = payments.id;
    var data = Meteor.wrapAsync(stripe.customers.retrieve.bind(stripe.customers))(customerId);

    if (newPlan === "free") {
      if (data.subscriptions && data.subscriptions.data.length > 0) {
        // TODO(someday): pass in at_period_end and properly handle pending cancelled subscriptions
        Meteor.wrapAsync(stripe.customers.cancelSubscription.bind(stripe.customers))(
          customerId,
          data.subscriptions.data[0].id
        );
      }
      // else: no subscriptions exist so we're already set to free
    } else {
      if (data.subscriptions && data.subscriptions.data.length > 0) {
        Meteor.wrapAsync(stripe.customers.updateSubscription.bind(stripe.customers))(
          customerId,
          data.subscriptions.data[0].id,
          {plan: newPlan + "-beta"}
        );
      } else {
        Meteor.wrapAsync(stripe.customers.createSubscription.bind(stripe.customers))(
          customerId,
          {plan: newPlan + "-beta"}
        );
      }
    }

    Meteor.users.update({_id: this.userId}, {$set: { plan: newPlan }});
  },

  createUserSubscription: function (token, email, plan) {
    if (!this.userId) {
      throw new Meteor.Error(403, "Must be logged in to update subscription");
    }
    check(token, String);
    check(email, String);
    check(plan, String);

    var payments = Meteor.user().payments;
    var customerId;
    var sanitizedSource;
    if (!payments || !payments.id) {
      var data = createUser(token, email);
      customerId = data.id;
      if (data.sources && data.sources.data && data.sources.data.length >= 1) {
        sanitizedSource = sanitizeSource(data.sources.data[0]);
      }
    } else {
      customerId = payments.id;
      sanitizedSource = methods.addCardForUser.bind(this)(token, email);
    }
    Meteor.wrapAsync(stripe.customers.createSubscription.bind(stripe.customers))(
      customerId,
      {plan: plan + "-beta"}
    );
    Meteor.users.update({_id: this.userId}, {$set: { plan: plan }});
    return sanitizedSource;
  }
};
Meteor.methods(methods);

Meteor.publish("plans", function () {
  return this.connection.sandstormDb.listPlans();
});

function getAllStripeCustomers() {
  var hasMore = true;
  var results = [];

  var req = {limit: 100};
  while (hasMore) {
    var next = Meteor.wrapAsync(stripe.customers.list.bind(stripe.customers))(req);
    results = results.concat(next.data);
    hasMore = next.has_more;
    if (hasMore) {
      req.starting_after = results.slice(-1)[0].id;
    }
  }
  return results;
}

SandstormDb.paymentsMigrationHook = function (SignupKeys, plans) {
  var db = this;
  var customers = getAllStripeCustomers();
  console.log("got customers", customers.length);
  if (!customers) throw new Error("missing customers");

  var byEmail = {};
  for (var i in customers) {
    var customer = customers[i];
    byEmail[customer.email] = byEmail[customer.email] || [];
    byEmail[customer.email].push(customer);
  }

  var byQuota = {};
  for (var i in plans) {
    if (plans[i]._id !== "free") {
      byQuota[plans[i].storage] = plans[i]._id;
    }
  }

  function getCustomerByEmail(email, quota) {
    var customer = (byEmail[email] || []).shift();
    if (customer) {
      var plan;
      if (customer.subscriptions && customer.subscriptions.data[0]) {
        // Plan names end with "-beta".
        plan = customer.subscriptions.data[0].plan.id.split("-")[0];
      } else {
        plan = "free";
      }
      return {plan: plan, payments: {id: customer.id}};
    }
  }

  Meteor.users.find({quota: {$exists: true}}).forEach(function (user) {
    if (user.signupEmail) {
      var customer = getCustomerByEmail(user.signupEmail, user.quota);
      if (customer) {
        console.log("user", user._id, user.signupEmail, "=>", JSON.stringify(customer));
        Meteor.users.update({_id: user._id}, {$set: customer});
      } else {
        console.error("ERROR: missing customer for email (user):", email, user._id);
      }
    } else {
      console.warn("WARNING: user was not invited by email:",
          user._id, SandstormDb.getUserIdentities(user));
    }
  });

  SignupKeys.find({quota: {$exists: true}, used: false}).forEach(function (signupKey) {
    if (signupKey.email) {
      var customer = getCustomerByEmail(signupKey.email, signupKey.quota);
      if (customer) {
        console.log("invite", signupKey.email, "=>", JSON.stringify(customer));
        SignupKeys.update({_id: signupKey._id}, {$set: customer});
      } else {
        console.error("ERROR: missing customer for email (invite):", email, signupKey._id);
      }
    } else {
      console.warn("WARNING: non-email invite:", signupKey.note);
    }
  });

  for (var email in byEmail) {
    byEmail[email].forEach(function (customer) {
      console.error("ERROR: customer not used:", customer.id, email);
    });
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PublicTopBarV2 from '../../containers/PublicTopBarV2';

export default class PublicGroupHero extends React.Component {
  render() {
    const { group, i18n } = this.props;
    const collectiveBg = '/static/images/collectives/default-header-bg.jpg';

    return (
      <section className='PublicGroupHero relative px2 bg-black bg-cover white' style={{backgroundImage: `url(${collectiveBg})`}}>

          <PublicTopBarV2 loginRedirectTo={`/${group.slug}`} className='pt3 absolute top-0 left-0 right-0' />

{i18n.getString('hiThisIs')} {group.name} {i18n.getString('openCollective')}.

{i18n.getString('missionTo')} {group.mission}

            {i18n.getString('bePart')}

{i18n.getString('scrollDown')}

            <svg width='14' height='9'>
              <use xlinkHref='#svg-arrow-down' stroke='#fff'/>
            </svg>

                {i18n.getString('menuWho')}

                {i18n.getString('menuWhy')}

                {i18n.getString('menuExpensesAndActivities')}

                {i18n.getString('menuMembersWall')}

              {/*

                Share

*/}

    );
  }
};
<commit_msg>using the background image of the collective if any (#156)<commit_after>import React from 'react';
import PublicTopBarV2 from '../../containers/PublicTopBarV2';

export default class PublicGroupHero extends React.Component {
  render() {
    const { group, i18n } = this.props;
    const collectiveBg = group.backgroundImage || '/static/images/collectives/default-header-bg.jpg';

    return (
      <section className='PublicGroupHero relative px2 bg-black bg-cover white' style={{backgroundImage: `url(${collectiveBg})`}}>

          <PublicTopBarV2 loginRedirectTo={`/${group.slug}`} className='pt3 absolute top-0 left-0 right-0' />

{i18n.getString('hiThisIs')} {group.name} {i18n.getString('openCollective')}.

{i18n.getString('missionTo')} {group.mission}

            {i18n.getString('bePart')}

{i18n.getString('scrollDown')}

            <svg width='14' height='9'>
              <use xlinkHref='#svg-arrow-down' stroke='#fff'/>
            </svg>

                {i18n.getString('menuWho')}

                {i18n.getString('menuWhy')}

                {i18n.getString('menuExpensesAndActivities')}

                {i18n.getString('menuMembersWall')}

              {/*

                Share

*/}

    );
  }
};
<|endoftext|>


<commit_before>var cronJob = require('cron').CronJob;
var teleinfo = require('teleinfo');
var util = require('util');

var infosCompteur = {};

function tarifbleu(port, cronTime, datalogger, errorcb) {

  var trameEvents = teleinfo(port);
  razinfosCompteur();
  trameEvents.on('tramedecodee', function (data) {
    majData(data);
  });

  trameEvents.on('error', function(err) {
    if (typeof errorcb === 'function') {
      errorcb(err);
    }
    else {
      console.log(err);
    }
  });

  var job = new cronJob(cronTime, function(){
      // Fonction exécutée toutes les minutes
      if (typeof datalogger === 'function') {
        // Suppression propriétés internes
        delete infosCompteur.psum;
        delete infosCompteur.isum;
        delete infosCompteur.nb_mesure;
        datalogger(infosCompteur);
      }
      else {
        console.log(util.inspect(infosCompteur));
      }
      // Raz moyenne
      razinfosCompteur();
    }, function () {
      // Fonction exécutée lorsque le job s'arrête
      console.log('Job stoppé');
    },
    true
  );
}

function getPapp() {
  return infosCompteur.pinst;
}

function getIntensite() {
  return infosCompteur.iinst;
}

function getIndex() {
  return infosCompteur.index;
}

function razinfosCompteur() {
  infosCompteur.imini = 30; // max de la souscription
  infosCompteur.imaxi= 0;
  infosCompteur.imoy= 0;
  infosCompteur.isum= 0;
  infosCompteur.pmini= 8000; // max la souscription
  infosCompteur.pmaxi= 0;
  infosCompteur.pmoy= 0;
  infosCompteur.psum= 0;
  infosCompteur.nb_mesure= 0;
}

function majData(data) {
  infosCompteur.nb_mesure += 1;
  if (data['IINST']<infosCompteur.imini) {
    infosCompteur.imini = data['IINST'];
  }
  if (data['IINST']>infosCompteur.imaxi) {
    infosCompteur.imaxi = data['IINST'];
  }
  infosCompteur.isum += data['IINST'];
  infosCompteur.imoy = infosCompteur.isum / infosCompteur.nb_mesure;
  if (data['PAPP']<infosCompteur.pmini) {
    infosCompteur.pmini = data['PAPP'];
  }
  if (data['PAPP']>infosCompteur.pmaxi) {
    infosCompteur.pmaxi = data['PAPP'];
  }
  infosCompteur.psum += data['PAPP'];
  infosCompteur.pmoy = infosCompteur.psum / infosCompteur.nb_mesure;
  // Index compteur en Wh
  infosCompteur.index = data['BASE'];
  // puissance apparente instantannée en VA
  infosCompteur.pinst = data['PAPP'];
  // intensité instantannée en A
  infosCompteur.iinst = data['IINST'];
}

exports.tarifbleu = tarifbleu;
exports.getPuissanceApparente = getPapp;
exports.getIntensite = getIntensite;
exports.getIndex = getIndex;
<commit_msg>fix code style<commit_after>var cronJob = require('cron').CronJob;
var teleinfo = require('teleinfo');
var util = require('util');

var infosCompteur = {};

function tarifbleu(port, cronTime, datalogger, errorcb) {

  var trameEvents = teleinfo(port);
  razinfosCompteur();
  trameEvents.on('tramedecodee', function (data) {
    majData(data);
  });

  trameEvents.on('error', function(err) {
    if (typeof errorcb === 'function') {
      errorcb(err);
    }
    else {
      console.log(err);
    }
  });

  var job = new cronJob(cronTime, function(){
      // Fonction exécutée toutes les minutes
      if (typeof datalogger === 'function') {
        // Suppression propriétés internes
        delete infosCompteur.psum;
        delete infosCompteur.isum;
        delete infosCompteur.nbMesure;
        datalogger(infosCompteur);
      }
      else {
        console.log(util.inspect(infosCompteur));
      }
      // Raz moyenne
      razinfosCompteur();
    }, function () {
      // Fonction exécutée lorsque le job s'arrête
      console.log('Job stoppé');
    },
    true
  );
}

function getPapp() {
  return infosCompteur.pinst;
}

function getIntensite() {
  return infosCompteur.iinst;
}

function getIndex() {
  return infosCompteur.index;
}

function razinfosCompteur() {
  infosCompteur.imini = 30; // max de la souscription
  infosCompteur.imaxi= 0;
  infosCompteur.imoy= 0;
  infosCompteur.isum= 0;
  infosCompteur.pmini= 8000; // max la souscription
  infosCompteur.pmaxi= 0;
  infosCompteur.pmoy= 0;
  infosCompteur.psum= 0;
  infosCompteur.nbMesure= 0;
}

function majData(data) {
  infosCompteur.nbMesure += 1;
  if (data.IINST<infosCompteur.imini) {
    infosCompteur.imini = data.IINST;
  }
  if (data.IINST>infosCompteur.imaxi) {
    infosCompteur.imaxi = data.IINST;
  }
  infosCompteur.isum += data.IINST;
  infosCompteur.imoy = infosCompteur.isum / infosCompteur.nbMesure;
  if (data.PAPP<infosCompteur.pmini) {
    infosCompteur.pmini = data.PAPP;
  }
  if (data.PAPP>infosCompteur.pmaxi) {
    infosCompteur.pmaxi = data.PAPP;
  }
  infosCompteur.psum += data.PAPP;
  infosCompteur.pmoy = infosCompteur.psum / infosCompteur.nbMesure;
  // Index compteur en Wh
  infosCompteur.index = data.BASE;
  // puissance apparente instantannée en VA
  infosCompteur.pinst = data.PAPP;
  // intensité instantannée en A
  infosCompteur.iinst = data.IINST;
}

exports.tarifbleu = tarifbleu;
exports.getPuissanceApparente = getPapp;
exports.getIntensite = getIntensite;
exports.getIndex = getIndex;
<|endoftext|>


<commit_before>exports = module.exports = new Build();

var path = require('path');
var fs = require('fs');
var Q = require('q');

function mkdir(dirPath) {
	var defer = Q.defer();
	fs.mkdir(dirPath, function() {
		defer.resolve(true);
	});
	return defer.promise;
}

function unloadModules(basePath) {
	var name = require.resolve('fire');
	if(typeof require.cache[name] != 'undefined') {
		delete require.cache[name];
	}

	var moduleName = require.resolve(path.join(basePath, 'index.js'));
	if(typeof require.cache[moduleName] != 'undefined') {
		delete require.cache[moduleName];
	}

	Object.keys(require.cache).forEach(function(requireName) {
		if(requireName.indexOf(basePath) === 0) {
			delete require.cache[requireName];
		}
	});
}

function loadApp(basePath, stage) {
	unloadModules(basePath);

	var fire = require('../../../');
	fire.stage = stage;
	fire.disabled = true;
	fire.appsContainerMap = {};

	require(path.join(basePath, 'index.js'));

	var appContainerIds = Object.keys(fire.appsContainerMap);
	if(appContainerIds.length > 1) {
		throw new Error('More than 1 app container found. This is currently not supported. You can create multiple apps by using the same id but different names. Please check `fire#app()`.');
	}
	if(!appContainerIds.length) {
		throw new Error('Could not find any app. Did you create an app in index.js by calling `fire#app()`? Is the current working directory correct?');
	}

	var appContainer = fire.appsContainerMap[appContainerIds[0]];
	return appContainer.getActiveApp();
}

function Build() {
	this.app = null;
}

Build.prototype.extendConfig = function(gruntConfig, grunt) {
	if(!gruntConfig.firebuild) {
		gruntConfig.firebuild = {};
	}

	gruntConfig.firebuild.migrations = {};
	gruntConfig.firebuild.api = {};
	gruntConfig.firebuild.scripts = {};
	gruntConfig.firebuild.procfile = {};
	gruntConfig.firebuild.version = {};

	var optionsApp = loadApp(process.cwd());

	this.app = optionsApp;

	if(optionsApp.container.numberOfApps() == 1) {
		gruntConfig.less = {
			options: {
				compress: true,
				sourceMap: false
			},
			src: {
				expand: true,
				src: ['./styles/*.less'],
				dest: '.fire/public/',
				ext: '.css'
			}
		};

		gruntConfig.jade = {
			compile: {
				options: {
					data: optionsApp._settings
				},
				files: [{
					expand: true,
					src: 'templates/**/*.jade',
					dest: '.fire/public/',
					ext: '.html'
				}]
			}
		};

		gruntConfig.uglify = {
			options: {
				sourceMap: true
			},
			build: {
				src: '.fire/public/scripts/fire.js',
				dest: '.fire/public/scripts/fire.min.js'
			}
		};
	}
	else {
		gruntConfig.less = {
			options: {
				compress: true,
				sourceMap: false
			},
			_shared: {
				dest: '.fire/public/styles/default.css',
				src: 'styles/_shared/default.less'
			}
		};

		gruntConfig.less[optionsApp.name] = {
			src: 'styles/' + optionsApp.name + '/default.less',
			dest: '.fire/public/' + optionsApp.name + '/styles/default.css'
		};

		gruntConfig.jade = {
			compile: {
				options: {
					data: optionsApp._settings
				},
				files: [{
					expand: true,
					cwd: 'templates/_shared/',
					src: '**/*.jade',
					dest: '.fire/public/' + optionsApp.name + '/templates/',
					ext: '.html'
				}, {
					expand: true,
					cwd: 'templates/' + optionsApp.name + '/',
					src: '**/*.jade',
					dest: '.fire/public/' + optionsApp.name + '/templates/',
					ext: '.html'
				}]
			}
		};

		gruntConfig.uglify = {
			options: {
				sourceMap: true
			},
			build: {
				src: '.fire/public/' + optionsApp.name + '/scripts/fire.js',
				dest: '.fire/public/' + optionsApp.name + '/scripts/fire.min.js'
			}
		};
	}

	if(!gruntConfig.release) {
		gruntConfig.release = {};
	}

	gruntConfig.release.migrate = {};
	gruntConfig.release.tests = {};

	if(!gruntConfig.run) {
		gruntConfig.run = {};
	}

	grunt.registerMultiTask('release', function(version) {
		var dotenv = require('dotenv');
		dotenv.load();

		var Migrations = require('../migrations');

		var basePath = process.cwd();
		var app = loadApp(basePath, 'release');

		app.models.forEach(function(model, modelName) {
			delete app.models.internals[modelName];
			delete app.models[modelName];
		});

		var done = this.async();

		if(this.target == 'tests') {
			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return app.tests.setup(basePath);
				})
				.then(function() {
					return app.tests.createTests();
				})
				.then(done)
				.catch(done)
				.done();
		}
		else if(this.target == 'migrate') {
			var models = app.models;
			var migrations = new Migrations(app, models);

			var targetVersion = version;

			// Set-up without reading any of the models
			// We will create the models based on all migrations

			models.setup(null)
				.then(function() {
					return migrations.setup(app.container.numberOfApps() > 1 ? path.join(basePath, '.fire', 'migrations', app.name) : path.join(basePath, '.fire', 'migrations'));
				})
				.then(function() {
					if(migrations._.length === 0) {
						throw new Error('There are 0 migration files. Did you run `grunt build`?');
					}
				})
				.then(function() {
					// Let's find which database version we're at
					return migrations.currentVersion();
				})
				.then(function(currentVersion) {
					if(!targetVersion) {
						targetVersion = migrations._[migrations._.length - 1].version;
					}

					if(targetVersion == currentVersion) {
						console.log('*** Database is up-to-date.');
					}
					else {
						console.log('*** Migrating from `' + currentVersion + '` to `' + targetVersion + '`.');

						return migrations.migrate(currentVersion, targetVersion)
							.then(function() {
								return migrations.currentVersion();
							})
							.then(function(newVersion) {
								if(newVersion == targetVersion) {
									//everything went alright
									console.log('*** Migration successful to `' + targetVersion + '`.');
								}
								else {
									throw new Error('Database version after migration `' + newVersion + '` does not match target version `' + targetVersion + '`.');
								}
							});
					}
				})
				.then(function() {
					done();
				})
				.catch(function(error) {
					console.log(error.message);
					console.log(error.stack);

					throw error;
				})
				.done();
		}
	});

	grunt.registerMultiTask('firebuild', function() {
		var done = this.async();
		var basePath = process.cwd();
		var app = null;

		if(this.target == 'version') {
			var packageJSON = require(path.join(__dirname, '..', '..', '..', 'package.json'));

			fs.writeFile(path.join('.fire', 'VERSION'), packageJSON.version, function(error) {
				done(error);
			});
		}
		else if(this.target == 'procfile') {
			app = loadApp(basePath, 'build');

			var processes = [];
			processes.push('web: node index.js --web');

			if(app.workers.numberOfWorkers() > 0) {
				processes.push('worker: node index.js --workers');
			}

			if(app.schedulers.numberOfSchedulers() > 0) {
				processes.push('worker: node index.js --schedulers');
			}

			if(app.triggers.numberOfTriggers() > 0) {
				processes.push('worker: node index.js --triggers');
			}

			if(app.triggers.numberOfTriggers() > 0 || app.schedulers.numberOfSchedulers() > 0) {
				processes.push('clock: node index.js --clock');
			}

			fs.writeFile('Procfile', processes.join('\n'), function(error) {
				done(error);
			});
		}
		else if(this.target == 'migrations') {
			app = loadApp(basePath, 'build');

			mkdir(path.join(basePath, '.fire'))
				.then(function() {
					return mkdir(path.join(basePath, '.fire', 'migrations'));
				})
				.then(function() {
					if(app.container.numberOfApps() > 1) {
						return mkdir(path.join(basePath, '.fire', 'migrations', app.name));
					}
				})
				.then(function() {
					var Generate = require('../migrations/generate');
					var generate = new Generate(app, basePath);
					generate.delegate = {
						addMigration: function(fileName, stream) {
							var savePath = (app.container.numberOfApps() > 1 ? path.join(basePath, '.fire', 'migrations', app.name, fileName) : path.join(basePath, '.fire', 'migrations', fileName));

							var writeStream = fs.createWriteStream(savePath);
							stream.pipe(writeStream);

							writeStream.once('finish', function() {
								done();
							});
						}
					};

					return generate.createMigrations(true);
				})
				.then(function(result) {
					if(!result) {
						// If the result is false, there are no migrations so we'll call done.
						done();
					}
				})
				.done();
		}
		else if(this.target == 'api') {
			app = loadApp(basePath, 'build');

			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return mkdir(path.join(basePath, '.fire'));
				})
				.then(function() {
					return mkdir(path.join(basePath, '.fire', 'api'));
				})
				.then(function() {
					if(app.container.numberOfApps() > 1) {
						return mkdir(path.join(basePath, '.fire', 'api', app.name));
					}
				})
				.then(function() {
					var result = Q.when(true);

					app.models.forEach(function(model) {
						result = result.then(function() {
							if(model.isShared() && !app.settings('isMaster')) {

							}
							else {
								var savePath = (app.container.numberOfApps() > 1) ? path.join(basePath, '.fire', 'api', app.name, model.getFileName() + '.js') : path.join(basePath, '.fire', 'api', model.getFileName() + '.js');
								var writeStream = fs.createWriteStream(savePath);
								return app.API.generateModelController(model, writeStream);
							}
						});
					});

					return result;
				})
				.then(function() {
					done();
				})
				.done();
		}
		else if(this.target == 'scripts') {
			app = loadApp(basePath, 'build');

			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return app.tests.setup(basePath);
				})
				.then(function() {
					setImmediate(function() {
						return mkdir(path.join(basePath, '.fire'))
							.then(function() {
								return mkdir(path.join(basePath, '.fire', 'public'));
							})
							.then(function() {
								if(app.container.numberOfApps() > 1) {
									return mkdir(path.join(basePath, '.fire', 'public', app.name));
								}
							})
							.then(function() {
								if(app.container.numberOfApps() > 1) {
									return mkdir(path.join(basePath, '.fire', 'public', app.name, 'scripts'));
								}
								else {
									return mkdir(path.join(basePath, '.fire', 'public', 'scripts'));
								}
							})
							.then(function() {
								var savePath = (app.container.numberOfApps() > 1) ? path.join(basePath, '.fire', 'public', app.name, 'scripts', 'fire.js') : path.join(basePath, '.fire', 'public', 'scripts', 'fire.js');
								var writeStream = fs.createWriteStream(savePath);

								app.bridge.generate(writeStream)
									.then(function() {
										done();
									})
									.done();
							});
					});
				})
				.done();
		}
		else {
			done();
		}
	});

	grunt.registerTask('build', ['firebuild', 'less', 'jade', 'uglify']);
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jade');
	return gruntConfig;
};
<commit_msg>adds includeAPI setting<commit_after>exports = module.exports = new Build();

var path = require('path');
var fs = require('fs');
var Q = require('q');

function mkdir(dirPath) {
	var defer = Q.defer();
	fs.mkdir(dirPath, function() {
		defer.resolve(true);
	});
	return defer.promise;
}

function unloadModules(basePath) {
	var name = require.resolve('fire');
	if(typeof require.cache[name] != 'undefined') {
		delete require.cache[name];
	}

	var moduleName = require.resolve(path.join(basePath, 'index.js'));
	if(typeof require.cache[moduleName] != 'undefined') {
		delete require.cache[moduleName];
	}

	Object.keys(require.cache).forEach(function(requireName) {
		if(requireName.indexOf(basePath) === 0) {
			delete require.cache[requireName];
		}
	});
}

function loadApp(basePath, stage) {
	unloadModules(basePath);

	var fire = require('../../../');
	fire.stage = stage;
	fire.disabled = true;
	fire.appsContainerMap = {};

	require(path.join(basePath, 'index.js'));

	var appContainerIds = Object.keys(fire.appsContainerMap);
	if(appContainerIds.length > 1) {
		throw new Error('More than 1 app container found. This is currently not supported. You can create multiple apps by using the same id but different names. Please check `fire#app()`.');
	}
	if(!appContainerIds.length) {
		throw new Error('Could not find any app. Did you create an app in index.js by calling `fire#app()`? Is the current working directory correct?');
	}

	var appContainer = fire.appsContainerMap[appContainerIds[0]];
	return appContainer.getActiveApp();
}

function Build() {
	this.app = null;
}

Build.prototype.extendConfig = function(gruntConfig, grunt) {
	if(!gruntConfig.firebuild) {
		gruntConfig.firebuild = {};
	}

	gruntConfig.firebuild.migrations = {};
	gruntConfig.firebuild.api = {};
	gruntConfig.firebuild.scripts = {};
	gruntConfig.firebuild.procfile = {};
	gruntConfig.firebuild.version = {};

	var optionsApp = loadApp(process.cwd());

	this.app = optionsApp;

	if(optionsApp.container.numberOfApps() == 1) {
		gruntConfig.less = {
			options: {
				compress: true,
				sourceMap: false
			},
			src: {
				expand: true,
				src: ['./styles/*.less'],
				dest: '.fire/public/',
				ext: '.css'
			}
		};

		gruntConfig.jade = {
			compile: {
				options: {
					data: optionsApp._settings
				},
				files: [{
					expand: true,
					src: 'templates/**/*.jade',
					dest: '.fire/public/',
					ext: '.html'
				}]
			}
		};

		gruntConfig.uglify = {
			options: {
				sourceMap: true
			},
			build: {
				src: '.fire/public/scripts/fire.js',
				dest: '.fire/public/scripts/fire.min.js'
			}
		};
	}
	else {
		gruntConfig.less = {
			options: {
				compress: true,
				sourceMap: false
			},
			_shared: {
				dest: '.fire/public/styles/default.css',
				src: 'styles/_shared/default.less'
			}
		};

		gruntConfig.less[optionsApp.name] = {
			src: 'styles/' + optionsApp.name + '/default.less',
			dest: '.fire/public/' + optionsApp.name + '/styles/default.css'
		};

		gruntConfig.jade = {
			compile: {
				options: {
					data: optionsApp._settings
				},
				files: [{
					expand: true,
					cwd: 'templates/_shared/',
					src: '**/*.jade',
					dest: '.fire/public/' + optionsApp.name + '/templates/',
					ext: '.html'
				}, {
					expand: true,
					cwd: 'templates/' + optionsApp.name + '/',
					src: '**/*.jade',
					dest: '.fire/public/' + optionsApp.name + '/templates/',
					ext: '.html'
				}]
			}
		};

		gruntConfig.uglify = {
			options: {
				sourceMap: true
			},
			build: {
				src: '.fire/public/' + optionsApp.name + '/scripts/fire.js',
				dest: '.fire/public/' + optionsApp.name + '/scripts/fire.min.js'
			}
		};
	}

	if(!gruntConfig.release) {
		gruntConfig.release = {};
	}

	gruntConfig.release.migrate = {};
	gruntConfig.release.tests = {};

	if(!gruntConfig.run) {
		gruntConfig.run = {};
	}

	grunt.registerMultiTask('release', function(version) {
		var dotenv = require('dotenv');
		dotenv.load();

		var Migrations = require('../migrations');

		var basePath = process.cwd();
		var app = loadApp(basePath, 'release');

		app.models.forEach(function(model, modelName) {
			delete app.models.internals[modelName];
			delete app.models[modelName];
		});

		var done = this.async();

		if(this.target == 'tests') {
			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return app.tests.setup(basePath);
				})
				.then(function() {
					return app.tests.createTests();
				})
				.then(done)
				.catch(done)
				.done();
		}
		else if(this.target == 'migrate') {
			var models = app.models;
			var migrations = new Migrations(app, models);

			var targetVersion = version;

			// Set-up without reading any of the models
			// We will create the models based on all migrations

			models.setup(null)
				.then(function() {
					return migrations.setup(app.container.numberOfApps() > 1 ? path.join(basePath, '.fire', 'migrations', app.name) : path.join(basePath, '.fire', 'migrations'));
				})
				.then(function() {
					if(migrations._.length === 0) {
						throw new Error('There are 0 migration files. Did you run `grunt build`?');
					}
				})
				.then(function() {
					// Let's find which database version we're at
					return migrations.currentVersion();
				})
				.then(function(currentVersion) {
					if(!targetVersion) {
						targetVersion = migrations._[migrations._.length - 1].version;
					}

					if(targetVersion == currentVersion) {
						console.log('*** Database is up-to-date.');
					}
					else {
						console.log('*** Migrating from `' + currentVersion + '` to `' + targetVersion + '`.');

						return migrations.migrate(currentVersion, targetVersion)
							.then(function() {
								return migrations.currentVersion();
							})
							.then(function(newVersion) {
								if(newVersion == targetVersion) {
									//everything went alright
									console.log('*** Migration successful to `' + targetVersion + '`.');
								}
								else {
									throw new Error('Database version after migration `' + newVersion + '` does not match target version `' + targetVersion + '`.');
								}
							});
					}
				})
				.then(function() {
					done();
				})
				.catch(function(error) {
					console.log(error.message);
					console.log(error.stack);

					throw error;
				})
				.done();
		}
	});

	grunt.registerMultiTask('firebuild', function() {
		var done = this.async();
		var basePath = process.cwd();
		var app = null;

		if(this.target == 'version') {
			var packageJSON = require(path.join(__dirname, '..', '..', '..', 'package.json'));

			fs.writeFile(path.join('.fire', 'VERSION'), packageJSON.version, function(error) {
				done(error);
			});
		}
		else if(this.target == 'procfile') {
			app = loadApp(basePath, 'build');

			var processes = [];
			processes.push('web: node index.js --web');

			if(app.workers.numberOfWorkers() > 0) {
				processes.push('worker: node index.js --workers');
			}

			if(app.schedulers.numberOfSchedulers() > 0) {
				processes.push('worker: node index.js --schedulers');
			}

			if(app.triggers.numberOfTriggers() > 0) {
				processes.push('worker: node index.js --triggers');
			}

			if(app.triggers.numberOfTriggers() > 0 || app.schedulers.numberOfSchedulers() > 0) {
				processes.push('clock: node index.js --clock');
			}

			fs.writeFile('Procfile', processes.join('\n'), function(error) {
				done(error);
			});
		}
		else if(this.target == 'migrations') {
			app = loadApp(basePath, 'build');

			mkdir(path.join(basePath, '.fire'))
				.then(function() {
					return mkdir(path.join(basePath, '.fire', 'migrations'));
				})
				.then(function() {
					if(app.container.numberOfApps() > 1) {
						return mkdir(path.join(basePath, '.fire', 'migrations', app.name));
					}
				})
				.then(function() {
					var Generate = require('../migrations/generate');
					var generate = new Generate(app, basePath);
					generate.delegate = {
						addMigration: function(fileName, stream) {
							var savePath = (app.container.numberOfApps() > 1 ? path.join(basePath, '.fire', 'migrations', app.name, fileName) : path.join(basePath, '.fire', 'migrations', fileName));

							var writeStream = fs.createWriteStream(savePath);
							stream.pipe(writeStream);

							writeStream.once('finish', function() {
								done();
							});
						}
					};

					return generate.createMigrations(true);
				})
				.then(function(result) {
					if(!result) {
						// If the result is false, there are no migrations so we'll call done.
						done();
					}
				})
				.done();
		}
		else if(this.target == 'api') {
			app = loadApp(basePath, 'build');

			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return mkdir(path.join(basePath, '.fire'));
				})
				.then(function() {
					return mkdir(path.join(basePath, '.fire', 'api'));
				})
				.then(function() {
					if(app.container.numberOfApps() > 1) {
						return mkdir(path.join(basePath, '.fire', 'api', app.name));
					}
				})
				.then(function() {
					var result = Q.when(true);

					app.models.forEach(function(model) {
						result = result.then(function() {
							if(model.isShared() && !app.settings('isMaster') && !app.settings('includeAPI')) {

							}
							else {
								var savePath = (app.container.numberOfApps() > 1) ? path.join(basePath, '.fire', 'api', app.name, model.getFileName() + '.js') : path.join(basePath, '.fire', 'api', model.getFileName() + '.js');
								var writeStream = fs.createWriteStream(savePath);
								return app.API.generateModelController(model, writeStream);
							}
						});
					});

					return result;
				})
				.then(function() {
					done();
				})
				.done();
		}
		else if(this.target == 'scripts') {
			app = loadApp(basePath, 'build');

			app.controllers.setup(basePath)
				.then(function() {
					return app.models.setup(basePath);
				})
				.then(function() {
					return app.tests.setup(basePath);
				})
				.then(function() {
					setImmediate(function() {
						return mkdir(path.join(basePath, '.fire'))
							.then(function() {
								return mkdir(path.join(basePath, '.fire', 'public'));
							})
							.then(function() {
								if(app.container.numberOfApps() > 1) {
									return mkdir(path.join(basePath, '.fire', 'public', app.name));
								}
							})
							.then(function() {
								if(app.container.numberOfApps() > 1) {
									return mkdir(path.join(basePath, '.fire', 'public', app.name, 'scripts'));
								}
								else {
									return mkdir(path.join(basePath, '.fire', 'public', 'scripts'));
								}
							})
							.then(function() {
								var savePath = (app.container.numberOfApps() > 1) ? path.join(basePath, '.fire', 'public', app.name, 'scripts', 'fire.js') : path.join(basePath, '.fire', 'public', 'scripts', 'fire.js');
								var writeStream = fs.createWriteStream(savePath);

								app.bridge.generate(writeStream)
									.then(function() {
										done();
									})
									.done();
							});
					});
				})
				.done();
		}
		else {
			done();
		}
	});

	grunt.registerTask('build', ['firebuild', 'less', 'jade', 'uglify']);
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jade');
	return gruntConfig;
};
<|endoftext|>


<commit_before>'use strict'

var assign = require('../common/assign')
var initializeContext = require('./http_initialize_context')

/**
 * `HttpSerializer` is an abstract base class containing methods to be
 * implemented.
 */
function HttpSerializer (properties) {
  assign(this, properties)
}

/**
 * The `HttpSerializer` should not be instantiated directly, since the
 * constructor function accepts dependencies. The keys which are injected are:
 *
 * - `methods`: same as static property on Fortune class.
 * - `errors`: same as static property on Fortune class.
 * - `keys`: an object which enumerates reserved constants for record type
 * definitions.
 * - `recordTypes`: an object which enumerates record types and their
 * definitions.
 * - `castValue`: a function with the signature (`value`, `type`, `options`),
 * useful for casting arbitrary values to a particular type.
 * - `options`: the options passed to the serializer.
 * - `adapter`: a reference to the adapter instance.
 * - `message`: a function with the signature (`id`, `language`, `data`).
 * - `Promise`: the Promise implementation.
 *
 * These keys are accessible on the instance (`this`).
 */
HttpSerializer.prototype.constructor = function () {
  // This exists here only for documentation purposes.
}

delete HttpSerializer.prototype.constructor

/**
 * This method is run first, and it is optional to implement. The default
 * implementation is typically used so that it may interoperate with other
 * serializers. The purpose is typically to read and mutate the request
 * before anything else happens. For example, it can handle URI routing and
 * query string parsing. The arguments that it accepts beyond the required
 * `contextRequest` are the `request` and `response` arguments from the Node.js
 * HTTP listener.
 *
 * It should return either the context request or a promise that resolves to
 * the context request. *The expectation is that the request is mutated except
 * for the payload*, which should be handled separately.
 *
 * @param {Object} contextRequest
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object}
 */
HttpSerializer.prototype.processRequest = initializeContext

/**
 * This gets run last. The purpose is typically to read and mutate the response
 * at the very end, for example, stringifying an object to be sent over the
 * network. The arguments that it accepts beyond the required `contextResponse`
 * are the `request` and `response` arguments from the Node.js HTTP listener.
 *
 * It should return either the context response or a promise that resolves to
 * the context response. *The expectation is that there is a key on the
 * context response, `payload`, which is either a string or a buffer*, or else
 * Node.js doesn't know how to respond.
 *
 * @param {Object} contextResponse
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object}
 */
HttpSerializer.prototype.processResponse = function (contextResponse) {
  return contextResponse
}

/**
 * Parse a request payload for creating or updating records. This method should
 * return either an array of records as expected from the `adapter.create`
 * method, or an array of update object as expected from the `adapter.update`.
 * method. It may also mutate the context request object.
 *
 * @param {Object} contextRequest
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object[]}
 */
HttpSerializer.prototype.parsePayload = function () {
  return []
}

/**
 * A serializer must have a static property `mediaType`, which **MUST** be a
 * string.
 */
HttpSerializer.mediaType = null

module.exports = HttpSerializer
<commit_msg>fix documentation<commit_after>'use strict'

var assign = require('../common/assign')
var initializeContext = require('./http_initialize_context')

/**
 * `HttpSerializer` is an abstract base class containing methods to be
 * implemented.
 */
function HttpSerializer (properties) {
  assign(this, properties)
}

/**
 * The `HttpSerializer` should not be instantiated directly, since the
 * constructor function accepts dependencies. The keys which are injected are:
 *
 * - `methods`: same as static property on Fortune class.
 * - `errors`: same as static property on Fortune class.
 * - `keys`: an object which enumerates reserved constants for record type
 * definitions.
 * - `recordTypes`: an object which enumerates record types and their
 * definitions.
 * - `castValue`: a function with the signature (`value`, `type`, `options`),
 * useful for casting arbitrary values to a particular type.
 * - `options`: the options passed to the serializer.
 * - `adapter`: a reference to the adapter instance.
 * - `message`: a function with the signature (`id`, `language`, `data`).
 * - `Promise`: the Promise implementation.
 *
 * These keys are accessible on the instance (`this`).
 */
HttpSerializer.prototype.constructor = function () {
  // This exists here only for documentation purposes.
}

delete HttpSerializer.prototype.constructor

/**
 * This method is run first, and it is optional to implement. The default
 * implementation is typically used so that it may interoperate with other
 * serializers. The purpose is typically to read and mutate the request
 * before anything else happens. For example, it can handle URI routing and
 * query string parsing. The arguments that it accepts beyond the required
 * `contextRequest` are the `request` and `response` arguments from the Node.js
 * HTTP listener.
 *
 * It should return either the context request or a promise that resolves to
 * the context request. *The expectation is that the request is mutated except
 * for the payload*, which should be handled separately.
 *
 * @param {Object} contextRequest
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object}
 */
HttpSerializer.prototype.processRequest = function () {
  // This is a no-op for documentation purposes.
}

// This is the real function call.
HttpSerializer.prototype.processRequest = initializeContext

/**
 * This gets run last. The purpose is typically to read and mutate the response
 * at the very end, for example, stringifying an object to be sent over the
 * network. The arguments that it accepts beyond the required `contextResponse`
 * are the `request` and `response` arguments from the Node.js HTTP listener.
 *
 * It should return either the context response or a promise that resolves to
 * the context response. *The expectation is that there is a key on the
 * context response, `payload`, which is either a string or a buffer*, or else
 * Node.js doesn't know how to respond.
 *
 * @param {Object} contextResponse
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object}
 */
HttpSerializer.prototype.processResponse = function (contextResponse) {
  return contextResponse
}

/**
 * Parse a request payload for creating or updating records. This method should
 * return either an array of records as expected from the `adapter.create`
 * method, or an array of update object as expected from the `adapter.update`.
 * method. It may also mutate the context request object.
 *
 * @param {Object} contextRequest
 * @param {Object} request
 * @param {Object} response
 * @return {Promise|Object[]}
 */
HttpSerializer.prototype.parsePayload = function () {
  return []
}

/**
 * A serializer must have a static property `mediaType`, which **MUST** be a
 * string.
 */
HttpSerializer.mediaType = null

module.exports = HttpSerializer
<|endoftext|>


<commit_before>'use strict';

var through = require('through2');
var log = require('fancy-log');
var exec = require('child_process').exec;
var escape = require('any-shell-escape');
var path = require('path');

// want to get the current git hash instead?
// git.revParse({args:'--short HEAD'})

module.exports = function(message, opt) {
  if (!opt) opt = {};
  if (!message) {
    if (opt.args.indexOf('--amend') === -1 && opt.disableMessageRequirement !== true) {
      throw new Error('gulp-git: Commit message is required git.commit("commit message") or --amend arg must be given');
    }
  }
  if (!opt.cwd) opt.cwd = process.cwd();
  if (!opt.maxBuffer) opt.maxBuffer = 200 * 1024; // Default buffer value for child_process.exec
  if (!opt.args) opt.args = ' ';

  var files = [];
  var paths = [];

  var write = function(file, enc, cb) {
    files.push(file);
    paths.push(path.relative(opt.cwd, file.path).replace('\\', '/'));
    cb();
  };

  var messageEntry = function(entry) {
    return '-m "' + entry + '" ';
  };

  var flush = function(cb) {
    var writeStdin = false;
    var cmd = 'git commit ';
    // Allow delayed execution to determine the message
    if (typeof message === 'function') {
      message = message();
    }

    if (message && opt.args.indexOf('--amend') === -1) {

      // Check if the message is multiline
      if (message && message instanceof Array) {

        if (opt.multiline) {
          writeStdin = true;
          message = message.join('\n');
        } else {
          var messageExpanded = '';

          // repeat -m as needed
          for (var i = 0; i < message.length; i++) {
            messageExpanded += messageEntry(message[i]);
          }
          cmd += messageExpanded + opt.args;
        }
        if (!opt.disableAppendPaths) {
          cmd += ' ' + escape(paths);
        }
      } else {
        if (~message.indexOf('\n')) {
          writeStdin = true;
        } else {
          cmd += '-m "' + message + '" ' + opt.args;
        }
        if (!opt.disableAppendPaths) {
          cmd += ' ' + escape(paths);
        }
      }
    } else if (opt.disableMessageRequirement === true) {
      cmd += opt.args;
    } else {
      // When amending, just add the file automatically and do not include the message not the file.
      // Also, add all the files and avoid lauching the editor (even if --no-editor was added)
      cmd += '-a ' + opt.args + (opt.args.indexOf('--no-edit') === -1 ? ' --no-edit' : '');
    }
    var self = this;

    // If `message` was an array and `opt.multiline` was true
    // or was a string containing newlines, we append '-F -'
    if (writeStdin) {
      cmd += ' -F -';
    }
    cmd += ' .';

    var execChildProcess = exec(cmd, opt, function(err, stdout, stderr) {
      if (err && (String(stdout).indexOf('no changes added to commit') === 0)) return cb(err);
      if (!opt.quiet) log(stdout, stderr);
      files.forEach(self.push.bind(self));
      self.emit('end');
      return cb();
    });

    if (writeStdin) {
      execChildProcess.stdin.write(message);
      execChildProcess.stdin.end();
    }

    // If the user wants, we'll emit data events during exec
    // they can listen to them with .on('data',function(data){ });
    // in their task
    if (opt.emitData) {
      execChildProcess.stdout.on('data', function(data) {
        self.emit('data', data);
      });
      execChildProcess.stderr.on('data', function(data) {
        self.emit('data', data);
      });
    }
  };

  return through.obj(write, flush);
};
<commit_msg>Error creating commit on new git version #180 (#183)<commit_after>'use strict';

var through = require('through2');
var log = require('fancy-log');
var exec = require('child_process').exec;
var escape = require('any-shell-escape');
var path = require('path');

// want to get the current git hash instead?
// git.revParse({args:'--short HEAD'})

module.exports = function(message, opt) {
  if (!opt) opt = {};
  if (!message) {
    if (opt.args.indexOf('--amend') === -1 && opt.disableMessageRequirement !== true) {
      throw new Error('gulp-git: Commit message is required git.commit("commit message") or --amend arg must be given');
    }
  }
  if (!opt.cwd) opt.cwd = process.cwd();
  if (!opt.maxBuffer) opt.maxBuffer = 200 * 1024; // Default buffer value for child_process.exec
  if (!opt.args) opt.args = ' ';

  var files = [];
  var paths = [];

  var write = function(file, enc, cb) {
    files.push(file);
    paths.push(path.relative(opt.cwd, file.path).replace('\\', '/') || '.');
    cb();
  };

  var messageEntry = function(entry) {
    return '-m "' + entry + '" ';
  };

  var flush = function(cb) {
    var writeStdin = false;
    var cmd = 'git commit ';
    // Allow delayed execution to determine the message
    if (typeof message === 'function') {
      message = message();
    }

    if (message && opt.args.indexOf('--amend') === -1) {

      // Check if the message is multiline
      if (message && message instanceof Array) {

        if (opt.multiline) {
          writeStdin = true;
          message = message.join('\n');
        } else {
          var messageExpanded = '';

          // repeat -m as needed
          for (var i = 0; i < message.length; i++) {
            messageExpanded += messageEntry(message[i]);
          }
          cmd += messageExpanded + opt.args;
        }
        if (!opt.disableAppendPaths) {
          cmd += ' ' + escape(paths);
        }
      } else {
        if (~message.indexOf('\n')) {
          writeStdin = true;
        } else {
          cmd += '-m "' + message + '" ' + opt.args;
        }
        if (!opt.disableAppendPaths) {
          cmd += ' ' + escape(paths);
        }
      }
    } else if (opt.disableMessageRequirement === true) {
      cmd += opt.args;
    } else {
      // When amending, just add the file automatically and do not include the message not the file.
      // Also, add all the files and avoid lauching the editor (even if --no-editor was added)
      cmd += '-a ' + opt.args + (opt.args.indexOf('--no-edit') === -1 ? ' --no-edit' : '');
    }
    var self = this;

    // If `message` was an array and `opt.multiline` was true
    // or was a string containing newlines, we append '-F -'
    if (writeStdin) {
      cmd += ' -F -';
    }
    cmd += ' .';

    var execChildProcess = exec(cmd, opt, function(err, stdout, stderr) {
      if (err && (String(stdout).indexOf('no changes added to commit') === 0)) return cb(err);
      if (!opt.quiet) log(stdout, stderr);
      files.forEach(self.push.bind(self));
      self.emit('end');
      return cb();
    });

    if (writeStdin) {
      execChildProcess.stdin.write(message);
      execChildProcess.stdin.end();
    }

    // If the user wants, we'll emit data events during exec
    // they can listen to them with .on('data',function(data){ });
    // in their task
    if (opt.emitData) {
      execChildProcess.stdout.on('data', function(data) {
        self.emit('data', data);
      });
      execChildProcess.stderr.on('data', function(data) {
        self.emit('data', data);
      });
    }
  };

  return through.obj(write, flush);
};
<|endoftext|>


<commit_before>'use strict';
const crypto = require('crypto')
    , os          = require('os')
    , zmq         = require('zmq')
    , tcp_exp     = /tcp:\/\/[\d.]+:(\d+)\/?/
    , vm_exp      = /VMware/
    , localip_exp = /0\.0\.0\.0/
    , tcp_proto   = 'tcp://'
    ;

exports.get_random = function(){
    return crypto.randomBytes(20).toString('hex')
};

exports.list_local_ips = function(){
    let ips = [];
    let interfaces = os.networkInterfaces()
    for(let iface_name in interfaces){
        if(vm_exp.test(iface_name)){ continue }
        let addrs = interfaces[ iface_name ];
        for(let a in addrs){
            let iface = addrs[a]
            if(!iface.internal && iface.family == 'IPv4'){
                ips.push(iface.address)
            }
        }
    }
    return ips;
};
exports.get_local_endpoint = function(sock){
    let addr, ip;
    addr = sock.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
    if(tcp_proto.test( addr )){
        return addr
    }

    // resolve to a locally reachable IP if tcp://
    ip = this.list_local_ips()[0];
    return addr.replace(localip_exp, `${ip}`);
}
exports.get_port = function(addr){
    let m = addr.match(tcp_exp);
    return m ? Number(m[1]) : -1
}

exports.bindAndGetAddr = function(sock_type, addr){
    let sock, endpoint, port;

    sock = zmq.socket(sock_type);
    sock.bindSync(addr);
    endpoint = sock.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
    port = exports.get_port(addr);
    return [sock, endpoint, port];
}

exports.lpad = function(value, padding){
    zeroes = '0'
    zeroes += '0' for i in [1..padding]
    return (zeroes + value).slice(padding * - 1)
}
<commit_msg>add method to generate a random id of a given length<commit_after>/*jshint laxcomma: true, smarttabs: true, node: true, esnext: true*/
'use strict';
const crypto = require('crypto')
    , os          = require('os')
    , zmq         = require('zmq')
    , tcp_exp     = /tcp:\/\/[\d.]+:(\d+)\/?/
    , vm_exp      = /VMware/
    , localip_exp = /0\.0\.0\.0/
    , tcp_proto   = 'tcp://'
    ;

exports.get_random = function(){
    return crypto.randomBytes(20).toString('hex');
};

exports.list_local_ips = function(){
    let ips = [];
    let interfaces = os.networkInterfaces();
    for(let iface_name in interfaces){
        if(vm_exp.test(iface_name)){ continue; }
        let addrs = interfaces[ iface_name ];
        for(let a in addrs){
            let iface = addrs[a];
            if(!iface.internal && iface.family == 'IPv4'){
                ips.push(iface.address);
            }
        }
    }
    return ips;
};
exports.get_local_endpoint = function(sock){
    let addr, ip;
    addr = sock.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
    if(tcp_proto.test( addr )){
        return addr;
    }

    // resolve to a locally reachable IP if tcp://
    ip = this.list_local_ips()[0];
    return addr.replace(localip_exp, `${ip}`);
};

exports.get_port = function(addr){
    let m = addr.match(tcp_exp);
    return m ? Number(m[1]) : -1;
};

exports.bindAndGetAddr = function(sock_type, addr){
    let sock, endpoint, port;

    sock = zmq.socket(sock_type);
    sock.bindSync(addr);
    endpoint = sock.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
    port = exports.get_port(addr);
    return [sock, endpoint, port];
};

exports.lpad = function(value, padding){
    let zeroes = '0', idx = padding;
    while( idx ){
        zeroes += '0';
        idx--;
    }
    return (zeroes + value).slice(padding * - 1);
};

exports.random = function( length = 10 ){
    return crypto
        .createHash('sha1')
        .update( crypto.randomBytes(6) )
        .update( process.hrtime().join() )
        .digest( 'hex' )
        .substring( 0, length );
};
<|endoftext|>


<commit_before>var colors;
var winningColor;
var numOfSquares = 6;
var colorRange = "Full"; // 0 = full, 1 = david
var background = window.getComputedStyle(document.querySelector("body"), null).getPropertyValue("background-color");
var squares = document.querySelectorAll(".square");
var messageDisplay = document.querySelector("#message");
var resetButton = document.getElementById("reset");
var modeButtons = document.querySelectorAll(".modeButton");
var rangeButtons = document.querySelectorAll(".rangeButton");

init();

function init() {
    for (var i = 0; i < squares.length; i++) {
        squares[i].addEventListener("click", function() {
            if (this.style.background === winningColor) {
                messageDisplay.textContent = "Correct!";
                resetButton.textContent = "Play again";
                changeAllSquareColors(winningColor);
                document.querySelector("h1").style.background = winningColor;
            } else {
                messageDisplay.textContent = "Try Again";
                this.style.background = background;
            }
        });
    }

    for (var i = 0; i < modeButtons.length; i++) {
        modeButtons[i].addEventListener("click", changeMode);
    }

    for (var i = 0; i < rangeButtons.length; i++) {
        rangeButtons[i].addEventListener("click", changeRange);
    }

    resetButton.addEventListener("click", function() {
        messageDisplay.textContent = "";
        this.textContent = "New Colors";
        document.querySelector("h1").style.background = "steelblue";
        setColors(numOfSquares);
    });

    setColors(numOfSquares);
}

function setColors(num) {
    colors = generateRandomColors(num);
    winningColor = colors[Math.floor(Math.random() * colors.length)];
    document.getElementById("colorToGuess").textContent = winningColor;
    for (var i = 0; i < squares.length; i++) {
        if (colors[i]) {
            squares[i].style.display = "block";
            squares[i].style.background = colors[i];
        } else {
            squares[i].style.display = "none";
        }
    }
}

function changeAllSquareColors(color) {
    for (var i = 0; i < squares.length; i++) {
        squares[i].style.background = color;
    }
}

function generateRandomColors(num) {
    var arr = [];
    arr.push(randomColor());
    console.log("Color 0: " + arr[0]);
    for (var i = 1; i < num; i++) {
        if(colorRange === "Full"){
            arr.push(randomColor());
            console.log("Color "+i+": " + arr[i]);
        } else {
            arr.push(closeRandomColor(arr[i-1]));
            console.log("Color "+i+": " + arr[i]);
        }
    }
    arr = shuffleColors(arr);
    return arr;
}

function randomColor() {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    return "rgb(" + r + ", " + g + ", " + b + ")";
}

function closeRandomColor(str) {
    var rgb = str.match(/\d+/g);
    for (var i = 0; i < rgb.length; i++) {
        rgb[i] = Number(rgb[i]);
        var variance = Math.floor(Math.random() * 60) * (Math.random() < 0.5 ? -1 : 1);
        console.log(rgb[i] + "+" + variance);

        if(rgb[i] + variance > 255 || rgb[i] + variance < 0) {
            rgb[i] = rgb[i] - variance;
        } else {
            rgb[i] = rgb[i] + variance;
        }
    }
    return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
}

//Using Durstenfeld shuffle algorithm.
function shuffleColors(arr) {
    for (var i = arr.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

function changeMode() {
    document.querySelector(".mode").innerHTML = this.textContent + " ";
    setModeOptions(this.textContent);
    resetText();
}

function setModeOptions(str) {
    if (str === "Easy") {
        numOfSquares = 3;
        document.querySelector("#container").style.maxWidth = "600px";
    } else if (str === "Hard") {
        numOfSquares = 6;
        document.querySelector("#container").style.maxWidth = "600px";
    } else {
        numOfSquares = 16;
        document.querySelector(".mode").innerHTML = "Hardest ";
        document.querySelector("#container").style.maxWidth = "800px";
    }
}

function changeRange() {
    if(this.textContent === "Full") {
        document.querySelector(".range").innerHTML = "Full Colors ";
    } else {
        document.querySelector(".range").innerHTML = "Close Colors ";
    }
    colorRange = this.textContent;
    resetText();
}

function resetText() {
    resetButton.textContent = "New Colors";
    messageDisplay.textContent = "";
    document.querySelector("h1").style.background = "steelblue";
    setColors(numOfSquares);
}
<commit_msg>Remove console.logs<commit_after>var colors;
var winningColor;
var numOfSquares = 6;
var colorRange = "Full"; // 0 = full, 1 = david
var background = window.getComputedStyle(document.querySelector("body"), null).getPropertyValue("background-color");
var squares = document.querySelectorAll(".square");
var messageDisplay = document.querySelector("#message");
var resetButton = document.getElementById("reset");
var modeButtons = document.querySelectorAll(".modeButton");
var rangeButtons = document.querySelectorAll(".rangeButton");

init();

function init() {
    for (var i = 0; i < squares.length; i++) {
        squares[i].addEventListener("click", function() {
            if (this.style.background === winningColor) {
                messageDisplay.textContent = "Correct!";
                resetButton.textContent = "Play again";
                changeAllSquareColors(winningColor);
                document.querySelector("h1").style.background = winningColor;
            } else {
                messageDisplay.textContent = "Try Again";
                this.style.background = background;
            }
        });
    }

    for (var i = 0; i < modeButtons.length; i++) {
        modeButtons[i].addEventListener("click", changeMode);
    }

    for (var i = 0; i < rangeButtons.length; i++) {
        rangeButtons[i].addEventListener("click", changeRange);
    }

    resetButton.addEventListener("click", function() {
        messageDisplay.textContent = "";
        this.textContent = "New Colors";
        document.querySelector("h1").style.background = "steelblue";
        setColors(numOfSquares);
    });

    setColors(numOfSquares);
}

function setColors(num) {
    colors = generateRandomColors(num);
    winningColor = colors[Math.floor(Math.random() * colors.length)];
    document.getElementById("colorToGuess").textContent = winningColor;
    for (var i = 0; i < squares.length; i++) {
        if (colors[i]) {
            squares[i].style.display = "block";
            squares[i].style.background = colors[i];
        } else {
            squares[i].style.display = "none";
        }
    }
}

function changeAllSquareColors(color) {
    for (var i = 0; i < squares.length; i++) {
        squares[i].style.background = color;
    }
}

function generateRandomColors(num) {
    var arr = [];
    arr.push(randomColor());
    for (var i = 1; i < num; i++) {
        if(colorRange === "Full"){
            arr.push(randomColor());
        } else {
            arr.push(closeRandomColor(arr[i-1]));
        }
    }
    arr = shuffleColors(arr);
    return arr;
}

function randomColor() {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    return "rgb(" + r + ", " + g + ", " + b + ")";
}

function closeRandomColor(str) {
    var rgb = str.match(/\d+/g);
    for (var i = 0; i < rgb.length; i++) {
        rgb[i] = Number(rgb[i]);
        var variance = Math.floor(Math.random() * 60) * (Math.random() < 0.5 ? -1 : 1);
        console.log(rgb[i] + "+" + variance);

        if(rgb[i] + variance > 255 || rgb[i] + variance < 0) {
            rgb[i] = rgb[i] - variance;
        } else {
            rgb[i] = rgb[i] + variance;
        }
    }
    return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
}

//Using Durstenfeld shuffle algorithm.
function shuffleColors(arr) {
    for (var i = arr.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

function changeMode() {
    document.querySelector(".mode").innerHTML = this.textContent + " ";
    setModeOptions(this.textContent);
    resetText();
}

function setModeOptions(str) {
    if (str === "Easy") {
        numOfSquares = 3;
        document.querySelector("#container").style.maxWidth = "600px";
    } else if (str === "Hard") {
        numOfSquares = 6;
        document.querySelector("#container").style.maxWidth = "600px";
    } else {
        numOfSquares = 16;
        document.querySelector(".mode").innerHTML = "Hardest ";
        document.querySelector("#container").style.maxWidth = "800px";
    }
}

function changeRange() {
    if(this.textContent === "Full") {
        document.querySelector(".range").innerHTML = "Full Colors ";
    } else {
        document.querySelector(".range").innerHTML = "Close Colors ";
    }
    colorRange = this.textContent;
    resetText();
}

function resetText() {
    resetButton.textContent = "New Colors";
    messageDisplay.textContent = "";
    document.querySelector("h1").style.background = "steelblue";
    setColors(numOfSquares);
}
<|endoftext|>


<commit_before>/*!
 * concat
 * Version: 0.0.1
 * Date: 2017/05/19
 * https://github.com/nuintun/gulp-css
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/nuintun/gulp-css/blob/master/LICENSE
 */

'use strict';

var util = require('./util');
var gutil = require('@nuintun/gulp-util');
var through = require('@nuintun/through');

/**
 * is concat start
 *
 * @param {Vinyl} vinyl
 * @returns {Boolean}
 */
function isStart(vinyl) {
  return vinyl.concat === gutil.CONCAT_STATUS.START;
}

/**
 * is concat end
 *
 * @param {Vinyl} vinyl
 * @returns {Boolean}
 */
function isEnd(vinyl) {
  return vinyl.concat === gutil.CONCAT_STATUS.END;
}

/**
 * concat
 * @returns {Stream}
 */
module.exports = function concat() {
  var code = [];
  var imports = '';

  return through({ objectMode: true }, function(vinyl, encoding, next) {
    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(gutil.throwError('streaming not supported.'));
    }

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // package
    var pkg = vinyl.package;

    // remote uri
    if (pkg && Array.isArray(pkg.remote)) {
      var current = '';

      pkg.remote.forEach(function(uri) {
        // compile remote uri
        current += '@import ' + JSON.stringify(uri) + ';\n';
      });

      imports = current + imports;
    }

    // start concat
    if (isStart(vinyl)) {
      return next();
    }

    // end concat
    if (isEnd(vinyl)) {
      // has remote imports
      if (imports) {
        code.unshift(new Buffer(imports));
      }

      vinyl.contents = Buffer.concat(code);

      // clean vinyl
      delete vinyl.concat;

      this.push(vinyl);

      code = [];
      imports = '';

      return next();
    }

    // concat
    code.push(vinyl.contents);
    next();
  });
};
<commit_msg>update files<commit_after>/*!
 * concat
 * Version: 0.0.1
 * Date: 2017/05/19
 * https://github.com/nuintun/gulp-css
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/nuintun/gulp-css/blob/master/LICENSE
 */

'use strict';

var util = require('./util');
var gutil = require('@nuintun/gulp-util');
var through = require('@nuintun/through');

/**
 * concat
 *
 * @returns {Stream}
 */
module.exports = function concat() {
  var code = [];
  var imports = '';

  return through({ objectMode: true }, function(vinyl, encoding, next) {
    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(gutil.throwError('streaming not supported.'));
    }

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // package
    var pkg = vinyl.package;
    var concat = vinyl.concat;

    // remote uri
    if (pkg && Array.isArray(pkg.remote)) {
      var current = '';

      pkg.remote.forEach(function(uri) {
        // compile remote uri
        current += '@import ' + JSON.stringify(uri) + ';\n';
      });

      imports = current + imports;
    }

    // start concat
    if (concat === gutil.CONCAT_STATUS.START) {
      return next();
    }

    // end concat
    if (concat === gutil.CONCAT_STATUS.END) {
      // has remote imports
      if (imports) {
        code.unshift(new Buffer(imports));
      }

      vinyl.contents = Buffer.concat(code);

      // clean vinyl
      delete vinyl.concat;

      this.push(vinyl);

      code = [];
      imports = '';

      return next();
    }

    // concat
    code.push(vinyl.contents);
    next();
  });
};
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */

import path from 'path'
import _ from 'underscore-plus'
import {Disposable, CompositeDisposable} from 'atom'
import etch from 'etch'
import KeybindingsPanel from './keybindings-panel'

// Displays the keybindings for a package namespace
export default class PackageKeymapView {
  constructor (pack) {
    this.pack = pack
    this.otherPlatformPattern = new RegExp(`\\.platform-(?!${_.escapeRegExp(process.platform)}\\b)`)
    this.namespace = this.pack.name
    this.disposables = new CompositeDisposable()
    etch.initialize(this)

    const packagesWithKeymapsDisabled = atom.config.get('core.packagesWithKeymapsDisabled') || []
    this.refs.keybindingToggle.checked = !packagesWithKeymapsDisabled.includes(this.namespace)

    const changeHandler = (event) => {
      event.stopPropagation()
      const value = this.refs.keybindingToggle.checked
      if (value) {
        atom.config.removeAtKeyPath('core.packagesWithKeymapsDisabled', this.namespace)
      } else {
        atom.config.pushAtKeyPath('core.packagesWithKeymapsDisabled', this.namespace)
      }

      this.updateKeyBindingView()
    }
    this.refs.keybindingToggle.addEventListener('change', changeHandler)
    this.disposables.add(new Disposable(() => { this.refs.keybindingToggle.removeEventListener('change', changeHandler) }))

    const copyIconClickHandler = (event) => {
      const target = event.target.closest('.copy-icon')
      if (target) {
        event.preventDefault()
        event.stopPropagation()
        this.writeKeyBindingToClipboard(target.closest('tr').dataset)
      }
    }
    this.element.addEventListener('click', copyIconClickHandler)
    this.disposables.add(new Disposable(() => { this.element.removeEventListener('click', copyIconClickHandler) }))

    this.updateKeyBindingView()

    let hasKeymaps = false
    for (let [packageKeymapsPath, map] of atom.packages.getLoadedPackage(this.namespace).keymaps) {
      if (map.length > 0) {
        hasKeymaps = true
        break
      }
    }

    if (this.refs.keybindingItems.children.length === 0 && !hasKeymaps) {
      this.element.style.display = 'none'
    }
  }

  update () {}

  destroy () {
    this.disposables.dispose()
    return etch.destroy(this)
  }

  render () {
    return (

Keybindings

            <input id='toggleKeybindings' className='input-checkbox' type='checkbox' ref='keybindingToggle'></input>

Enable

            {"Disable this if you want to bind your own keystrokes for this package's commands in your keymap."}

              Keystroke
              Command
              Selector
              Source

    )
  }

  updateKeyBindingView () {
    this.refs.keybindingItems.innerHTML = ''

    const keyBindings = []
    for (const [keymapPath, keymap] of atom.packages.getLoadedPackage(this.namespace).keymaps) {
      keyBindings.push(...atom.keymaps.build(this.namespace, keymap, 0, false))
    }

    for (const keyBinding of keyBindings) {
      const {command, keystrokes, selector, source} = keyBinding
      if (!command) {
        continue
      }

      if (this.otherPlatformPattern.test(selector)) {
        continue
      }

      const keyBindingRow = document.createElement('tr')
      keyBindingRow.dataset.selector = selector
      keyBindingRow.dataset.keystrokes = keystrokes
      keyBindingRow.dataset.command = command

      const keystrokesTd = document.createElement('td')

      const copyIconSpan = document.createElement('span')
      copyIconSpan.classList.add('icon', 'icon-clippy', 'copy-icon')
      keystrokesTd.appendChild(copyIconSpan)

      const keystrokesSpan = document.createElement('span')
      keystrokesSpan.textContent = keystrokes
      keystrokesTd.appendChild(keystrokesSpan)

      keyBindingRow.appendChild(keystrokesTd)

      const commandTd = document.createElement('td')
      commandTd.textContent = command
      keyBindingRow.appendChild(commandTd)

      const selectorTd = document.createElement('td')
      selectorTd.textContent = selector
      keyBindingRow.appendChild(selectorTd)

      const sourceTd = document.createElement('td')
      sourceTd.textContent = KeybindingsPanel.determineSource(source)
      keyBindingRow.appendChild(sourceTd)

      this.refs.keybindingItems.appendChild(keyBindingRow)
    }
  }

  writeKeyBindingToClipboard ({selector, keystrokes, command}) {
    let content
    const keymapExtension = path.extname(atom.keymaps.getUserKeymapPath())
    if (keymapExtension === '.cson') {
      content = `\
'${selector}':
  '${keystrokes}': '${command}'\
`
    } else {
      content = `\
"${selector}": {
  "${keystrokes}": "${command}"
}\
`
    }

    atom.clipboard.write(content)
  }
}
<commit_msg>Add .text-subtle to the keybindings table when disabled<commit_after>/** @babel */
/** @jsx etch.dom */

import path from 'path'
import _ from 'underscore-plus'
import {Disposable, CompositeDisposable} from 'atom'
import etch from 'etch'
import KeybindingsPanel from './keybindings-panel'

// Displays the keybindings for a package namespace
export default class PackageKeymapView {
  constructor (pack) {
    this.pack = pack
    this.otherPlatformPattern = new RegExp(`\\.platform-(?!${_.escapeRegExp(process.platform)}\\b)`)
    this.namespace = this.pack.name
    this.disposables = new CompositeDisposable()
    etch.initialize(this)

    const packagesWithKeymapsDisabled = atom.config.get('core.packagesWithKeymapsDisabled') || []
    this.refs.keybindingToggle.checked = !packagesWithKeymapsDisabled.includes(this.namespace)

    const changeHandler = (event) => {
      event.stopPropagation()
      const value = this.refs.keybindingToggle.checked
      if (value) {
        atom.config.removeAtKeyPath('core.packagesWithKeymapsDisabled', this.namespace)
      } else {
        atom.config.pushAtKeyPath('core.packagesWithKeymapsDisabled', this.namespace)
      }

      this.updateKeyBindingView()
    }
    this.refs.keybindingToggle.addEventListener('change', changeHandler)
    this.disposables.add(new Disposable(() => { this.refs.keybindingToggle.removeEventListener('change', changeHandler) }))

    const copyIconClickHandler = (event) => {
      const target = event.target.closest('.copy-icon')
      if (target) {
        event.preventDefault()
        event.stopPropagation()
        this.writeKeyBindingToClipboard(target.closest('tr').dataset)
      }
    }
    this.element.addEventListener('click', copyIconClickHandler)
    this.disposables.add(new Disposable(() => { this.element.removeEventListener('click', copyIconClickHandler) }))

    this.updateKeyBindingView()

    let hasKeymaps = false
    for (let [packageKeymapsPath, map] of atom.packages.getLoadedPackage(this.namespace).keymaps) {
      if (map.length > 0) {
        hasKeymaps = true
        break
      }
    }

    if (this.refs.keybindingItems.children.length === 0 && !hasKeymaps) {
      this.element.style.display = 'none'
    }
  }

  update () {}

  destroy () {
    this.disposables.dispose()
    return etch.destroy(this)
  }

  render () {
    return (

Keybindings

            <input id='toggleKeybindings' className='input-checkbox' type='checkbox' ref='keybindingToggle'></input>

Enable

            {"Disable this if you want to bind your own keystrokes for this package's commands in your keymap."}

              Keystroke
              Command
              Selector
              Source

    )
  }

  updateKeyBindingView () {
    this.refs.keybindingItems.innerHTML = ''

    const packagesWithKeymapsDisabled = atom.config.get('core.packagesWithKeymapsDisabled') || []
    const keybindingsDisabled = packagesWithKeymapsDisabled.includes(this.namespace)
    if (keybindingsDisabled) {
      this.refs.keybindingItems.classList.add('text-subtle')
    } else {
      this.refs.keybindingItems.classList.remove('text-subtle')
    }

    const keyBindings = []
    for (const [keymapPath, keymap] of atom.packages.getLoadedPackage(this.namespace).keymaps) {
      keyBindings.push(...atom.keymaps.build(this.namespace, keymap, 0, false))
    }

    for (const keyBinding of keyBindings) {
      const {command, keystrokes, selector, source} = keyBinding
      if (!command) {
        continue
      }

      if (this.otherPlatformPattern.test(selector)) {
        continue
      }

      const keyBindingRow = document.createElement('tr')
      keyBindingRow.dataset.selector = selector
      keyBindingRow.dataset.keystrokes = keystrokes
      keyBindingRow.dataset.command = command

      const keystrokesTd = document.createElement('td')

      const copyIconSpan = document.createElement('span')
      copyIconSpan.classList.add('icon', 'icon-clippy', 'copy-icon')
      keystrokesTd.appendChild(copyIconSpan)

      const keystrokesSpan = document.createElement('span')
      keystrokesSpan.textContent = keystrokes
      keystrokesTd.appendChild(keystrokesSpan)

      keyBindingRow.appendChild(keystrokesTd)

      const commandTd = document.createElement('td')
      commandTd.textContent = command
      keyBindingRow.appendChild(commandTd)

      const selectorTd = document.createElement('td')
      selectorTd.textContent = selector
      keyBindingRow.appendChild(selectorTd)

      const sourceTd = document.createElement('td')
      sourceTd.textContent = KeybindingsPanel.determineSource(source)
      keyBindingRow.appendChild(sourceTd)

      this.refs.keybindingItems.appendChild(keyBindingRow)
    }
  }

  writeKeyBindingToClipboard ({selector, keystrokes, command}) {
    let content
    const keymapExtension = path.extname(atom.keymaps.getUserKeymapPath())
    if (keymapExtension === '.cson') {
      content = `\
'${selector}':
  '${keystrokes}': '${command}'\
`
    } else {
      content = `\
"${selector}": {
  "${keystrokes}": "${command}"
}\
`
    }

    atom.clipboard.write(content)
  }
}
<|endoftext|>


<commit_before>/**
 * Created by Newton on 2015/5/10.
 */

'use strict';

var through = require('./through');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;

function concat(){
  var code = [];
  var imports = '';

  return through({ objectMode: true }, function (vinyl, encoding, next){
    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(util.throwError('streaming not supported.'));
    }

    // package
    var pkg = vinyl.package;

    // remote uri
    if (pkg && Array.isArray(pkg.remote)) {
      var current = '';

      pkg.remote.forEach(function (uri){
        // compile remote uri
        current += '@import ' + JSON.stringify(uri) + ';\n';
      });

      imports = current + imports;
    }

    // start concat
    if (isStart(vinyl)) {
      // debug
      debug('concat: %s start', colors.magenta(util.pathFromCwd(vinyl.path)));

      return next();
    }

    // debug
    debug('include: %s', colors.magenta(util.pathFromCwd(vinyl.path)));
    // concat
    code.push(vinyl.contents);

    // end concat
    if (isEnd(vinyl)) {
      // debug
      debug('concat: %s ...ok', colors.magenta(util.pathFromCwd(vinyl.path)));

      // has remote imports
      if (imports) {
        code.unshift(new Buffer(imports));
      }

      vinyl.contents = Buffer.concat(code);

      this.push(vinyl);

      code = [];
      imports = '';
    }

    next();
  });
}

function isStart(vinyl){
  return vinyl.startConcat;
}

function isEnd(vinyl){
  return vinyl.endConcat;
}

/**
 * exports module.
 */
module.exports = concat;
<commit_msg>modify debug log<commit_after>/**
 * Created by Newton on 2015/5/10.
 */

'use strict';

var through = require('./through');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;

function concat(){
  var code = [];
  var imports = '';

  return through({ objectMode: true }, function (vinyl, encoding, next){
    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(util.throwError('streaming not supported.'));
    }

    // package
    var pkg = vinyl.package;

    // remote uri
    if (pkg && Array.isArray(pkg.remote)) {
      var current = '';

      pkg.remote.forEach(function (uri){
        // compile remote uri
        current += '@import ' + JSON.stringify(uri) + ';\n';
      });

      imports = current + imports;
    }

    // start concat
    if (isStart(vinyl)) {
      // debug
      debug('concat: %s start', colors.magenta(util.pathFromCwd(vinyl.path)));

      return next();
    }

    // concat
    code.push(vinyl.contents);

    // end concat
    if (isEnd(vinyl)) {
      // has remote imports
      if (imports) {
        code.unshift(new Buffer(imports));
      }

      vinyl.contents = Buffer.concat(code);

      this.push(vinyl);
      // debug
      debug('concat: %s ...ok', colors.magenta(util.pathFromCwd(vinyl.path)));

      code = [];
      imports = '';
    } else {
      // debug
      debug('include: %s', colors.magenta(util.pathFromCwd(vinyl.path)));
    }

    next();
  });
}

function isStart(vinyl){
  return vinyl.startConcat;
}

function isEnd(vinyl){
  return vinyl.endConcat;
}

/**
 * exports module.
 */
module.exports = concat;
<|endoftext|>