Add delete method on document datastore

Add delete method on document datastore

--- src/datastores/document/index.js
+++ src/datastores/document/index.js
@@ -2,6 +2,7 @@
 import client from 'part:@sanity/base/client'
 import {omit} from 'lodash'
 import {Observable} from 'rxjs'
+
 const serverConnection = {
   byId(id) {
     return Observable
@@ -43,6 +44,10 @@
       .commit({returnDocuments: false}))
   },

+  delete(id) {
+    return Observable.from(client.delete(id))
+  },
+
   create(doc) {
     return Observable.from(client.create(doc))
   }

<|original_code|>
import createDocumentStore from '@sanity/document-store'
import client from 'part:@sanity/base/client'
import {omit} from 'lodash'
import {Observable} from 'rxjs'
const serverConnection = {
  byId(id) {
    return Observable
      .from(
        // todo can be removed when gradient supports emitting current snapshot on subscribe
        client.getDocument(id)
          .then(document => {
            return {
              type: 'snapshot',
              document: document
            }
          })
      )
      .merge(
        Observable.from(client.listen('*[_id == $id]', {id: id}))
          .filter(event => ('mutation' in event))
          // .filter(event => event.type === 'mutation') // todo replace above with this when fixed in gradient
          .map(event => {
            return {
              type: 'update',
              patch: omit(event.mutation.patch, 'id')
            }
          })
      )
  },

  query(query, params) {
    return Observable.timer(0, 50000)
      .flatMap(() => client.fetch(query, params))
      .map(documents => ({
        type: 'snapshot',
        documents: documents
      }))
  },

  update(id, patch) {
    return Observable.from(client
      .patch(id, patch)
      .commit({returnDocuments: false}))
  },

  create(doc) {
    return Observable.from(client.create(doc))
  }
}

export default createDocumentStore({serverConnection})

<|edits_diff|>
--- src/datastores/document/index.js
+++ src/datastores/document/index.js
@@ -2,6 +2,7 @@
 import client from 'part:@sanity/base/client'
 import {omit} from 'lodash'
 import {Observable} from 'rxjs'
+
 const serverConnection = {
   byId(id) {
     return Observable
<|current_version|>
import createDocumentStore from '@sanity/document-store'
import client from 'part:@sanity/base/client'
import {omit} from 'lodash'
import {Observable} from 'rxjs'

const serverConnection = {
  byId(id) {
    return Observable
      .from(
        // todo can be removed when gradient supports emitting current snapshot on subscribe
        client.getDocument(id)
          .then(document => {
            return {
              type: 'snapshot',
              document: document
            }
          })
      )
      .merge(
        Observable.from(client.listen('*[_id == $id]', {id: id}))
          .filter(event => ('mutation' in event))
          // .filter(event => event.type === 'mutation') // todo replace above with this when fixed in gradient
          .map(event => {
            return {
              type: 'update',
              patch: omit(event.mutation.patch, 'id')
            }
          })
      )
  },

  query(query, params) {
    return Observable.timer(0, 50000)
      .flatMap(() => client.fetch(query, params))
      .map(documents => ({
        type: 'snapshot',
        documents: documents
      }))
  },

  update(id, patch) {
    return Observable.from(client
      .patch(id, patch)
      .commit({returnDocuments: false}))
  },

  create(doc) {
    return Observable.from(client.create(doc))
  }
}

export default createDocumentStore({serverConnection})

<|next_version|>
import createDocumentStore from '@sanity/document-store'
import client from 'part:@sanity/base/client'
import {omit} from 'lodash'
import {Observable} from 'rxjs'

const serverConnection = {
  byId(id) {
    return Observable
      .from(
        // todo can be removed when gradient supports emitting current snapshot on subscribe
        client.getDocument(id)
          .then(document => {
            return {
              type: 'snapshot',
              document: document
            }
          })
      )
      .merge(
        Observable.from(client.listen('*[_id == $id]', {id: id}))
          .filter(event => ('mutation' in event))
          // .filter(event => event.type === 'mutation') // todo replace above with this when fixed in gradient
          .map(event => {
            return {
              type: 'update',
              patch: omit(event.mutation.patch, 'id')
            }
          })
      )
  },

  query(query, params) {
    return Observable.timer(0, 50000)
      .flatMap(() => client.fetch(query, params))
      .map(documents => ({
        type: 'snapshot',
        documents: documents
      }))
  },

  update(id, patch) {
    return Observable.from(client
      .patch(id, patch)
      .commit({returnDocuments: false}))
  },

  delete(id) {
    return Observable.from(client.delete(id))
  },

  create(doc) {
    return Observable.from(client.create(doc))
  }
}

export default createDocumentStore({serverConnection})


Allow single argument calls to methods

Allow single argument calls to methods

--- src/exported.js
+++ src/exported.js
@@ -10,12 +10,24 @@
 const Query = global["Query"] = {}

 Query["one"] = function(elem, selector) {
+  if (arguments.length === 1) {
+    selector = elem
+    elem = document
+  }
   return new SelectorGroup(selector).selectFirstFrom(elem)
 }
 Query["all"] = function(elem, selector) {
+  if (arguments.length === 1) {
+    selector = elem
+    elem = document
+  }
   return new SelectorGroup(selector).selectFrom(elem)
 }
 Query["matches"] = function(elem, selector) {
+  if (arguments.length === 1) {
+    selector = elem
+    elem = document
+  }
   return new SelectorGroup(selector).matches(elem)
 }

<|original_code|>
/* TODO:
  Cache individual objects, like ATTR and NTH simple selectors.
  Reorder pseudos so that the ones with highest overhead (like :hover) come last.
*/

/** @define {boolean} */
const DEBUG_MODE = false, LEGACY = false

const Query = global["Query"] = {}

Query["one"] = function(elem, selector) {
  return new SelectorGroup(selector).selectFirstFrom(elem)
}
Query["all"] = function(elem, selector) {
  return new SelectorGroup(selector).selectFrom(elem)
}
Query["matches"] = function(elem, selector) {
  return new SelectorGroup(selector).matches(elem)
}

//const e_proto = (global.HTMLElement || global.Element || {}).prototype
//if (e_proto && !e_proto.matches) {
//  e_proto.matches =
//    e_proto.matchesSelector ||
//    e_proto.webkitMatchesSelector ||
//    e_proto.mozMatchesSelector ||
//    e_proto.msMatchesSelector ||
//    e_proto.oMatchesSelector ||
//    function(sel) {
//      return Query["matches"](/**{!Element}*/(this), sel)
//    }
//}

<|edits_diff|>
--- src/exported.js
+++ src/exported.js
@@ -10,9 +10,17 @@
 const Query = global["Query"] = {}

 Query["one"] = function(elem, selector) {
+  if (arguments.length === 1) {
+    selector = elem
+    elem = document
+  }
   return new SelectorGroup(selector).selectFirstFrom(elem)
 }
 Query["all"] = function(elem, selector) {
+  if (arguments.length === 1) {
+    selector = elem
+    elem = document
+  }
   return new SelectorGroup(selector).selectFrom(elem)
 }
 Query["matches"] = function(elem, selector) {
<|current_version|>
/* TODO:
  Cache individual objects, like ATTR and NTH simple selectors.
  Reorder pseudos so that the ones with highest overhead (like :hover) come last.
*/

/** @define {boolean} */
const DEBUG_MODE = false, LEGACY = false

const Query = global["Query"] = {}

Query["one"] = function(elem, selector) {
  if (arguments.length === 1) {
    selector = elem
    elem = document
  }
  return new SelectorGroup(selector).selectFirstFrom(elem)
}
Query["all"] = function(elem, selector) {
  if (arguments.length === 1) {
    selector = elem
    elem = document
  }
  return new SelectorGroup(selector).selectFrom(elem)
}
Query["matches"] = function(elem, selector) {
  return new SelectorGroup(selector).matches(elem)
}

//const e_proto = (global.HTMLElement || global.Element || {}).prototype
//if (e_proto && !e_proto.matches) {
//  e_proto.matches =
//    e_proto.matchesSelector ||
//    e_proto.webkitMatchesSelector ||
//    e_proto.mozMatchesSelector ||
//    e_proto.msMatchesSelector ||
//    e_proto.oMatchesSelector ||
//    function(sel) {
//      return Query["matches"](/**{!Element}*/(this), sel)
//    }
//}

<|next_version|>
/* TODO:
  Cache individual objects, like ATTR and NTH simple selectors.
  Reorder pseudos so that the ones with highest overhead (like :hover) come last.
*/

/** @define {boolean} */
const DEBUG_MODE = false, LEGACY = false

const Query = global["Query"] = {}

Query["one"] = function(elem, selector) {
  if (arguments.length === 1) {
    selector = elem
    elem = document
  }
  return new SelectorGroup(selector).selectFirstFrom(elem)
}
Query["all"] = function(elem, selector) {
  if (arguments.length === 1) {
    selector = elem
    elem = document
  }
  return new SelectorGroup(selector).selectFrom(elem)
}
Query["matches"] = function(elem, selector) {
  if (arguments.length === 1) {
    selector = elem
    elem = document
  }
  return new SelectorGroup(selector).matches(elem)
}

//const e_proto = (global.HTMLElement || global.Element || {}).prototype
//if (e_proto && !e_proto.matches) {
//  e_proto.matches =
//    e_proto.matchesSelector ||
//    e_proto.webkitMatchesSelector ||
//    e_proto.mozMatchesSelector ||
//    e_proto.msMatchesSelector ||
//    e_proto.oMatchesSelector ||
//    function(sel) {
//      return Query["matches"](/**{!Element}*/(this), sel)
//    }
//}


Make sure `didDestroyElement` hook is called

--- packages/ember-glimmer/tests/integration/components/will-destroy-element-hook-test.js
+++ packages/ember-glimmer/tests/integration/components/will-destroy-element-hook-test.js
@@ -4,9 +4,11 @@

 moduleFor('Component willDestroyElement hook', class extends RenderingTest {
   ['@htmlbars it calls willDestroyElement when removed by if'](assert) {
+    let didInsertElementCount = 0;
     let willDestroyElementCount = 0;
     let FooBarComponent = Component.extend({
       didInsertElement() {
+        didInsertElementCount++;
         assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
       },
       willDestroyElement() {
@@ -19,6 +21,8 @@

     this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });

+    assert.equal(didInsertElementCount, 1, 'didInsertElement was called once');
+
     this.assertComponentElement(this.firstChild, { content: 'hello' });

     this.runTask(() => set(this.context, 'switch', false));

<|original_code|>
import { set } from 'ember-metal/property_set';
import Component from 'ember-views/components/component';
import { moduleFor, RenderingTest } from '../../utils/test-case';

moduleFor('Component willDestroyElement hook', class extends RenderingTest {
  ['@htmlbars it calls willDestroyElement when removed by if'](assert) {
    let willDestroyElementCount = 0;
    let FooBarComponent = Component.extend({
      didInsertElement() {
        assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
      },
      willDestroyElement() {
        willDestroyElementCount++;
        assert.notEqual(this.element.parentNode, null, 'has not been removed from DOM yet');
      }
    });

    this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: 'hello' });

    this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });

    this.assertComponentElement(this.firstChild, { content: 'hello' });

    this.runTask(() => set(this.context, 'switch', false));

    assert.equal(willDestroyElementCount, 1, 'willDestroyElement was called once');

    this.assertText('');
  }
});

<|edits_diff|>
--- packages/ember-glimmer/tests/integration/components/will-destroy-element-hook-test.js
+++ packages/ember-glimmer/tests/integration/components/will-destroy-element-hook-test.js
@@ -4,9 +4,11 @@

 moduleFor('Component willDestroyElement hook', class extends RenderingTest {
   ['@htmlbars it calls willDestroyElement when removed by if'](assert) {
+    let didInsertElementCount = 0;
     let willDestroyElementCount = 0;
     let FooBarComponent = Component.extend({
       didInsertElement() {
+        didInsertElementCount++;
         assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
       },
       willDestroyElement() {
<|current_version|>
import { set } from 'ember-metal/property_set';
import Component from 'ember-views/components/component';
import { moduleFor, RenderingTest } from '../../utils/test-case';

moduleFor('Component willDestroyElement hook', class extends RenderingTest {
  ['@htmlbars it calls willDestroyElement when removed by if'](assert) {
    let didInsertElementCount = 0;
    let willDestroyElementCount = 0;
    let FooBarComponent = Component.extend({
      didInsertElement() {
        didInsertElementCount++;
        assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
      },
      willDestroyElement() {
        willDestroyElementCount++;
        assert.notEqual(this.element.parentNode, null, 'has not been removed from DOM yet');
      }
    });

    this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: 'hello' });

    this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });

    this.assertComponentElement(this.firstChild, { content: 'hello' });

    this.runTask(() => set(this.context, 'switch', false));

    assert.equal(willDestroyElementCount, 1, 'willDestroyElement was called once');

    this.assertText('');
  }
});

<|next_version|>
import { set } from 'ember-metal/property_set';
import Component from 'ember-views/components/component';
import { moduleFor, RenderingTest } from '../../utils/test-case';

moduleFor('Component willDestroyElement hook', class extends RenderingTest {
  ['@htmlbars it calls willDestroyElement when removed by if'](assert) {
    let didInsertElementCount = 0;
    let willDestroyElementCount = 0;
    let FooBarComponent = Component.extend({
      didInsertElement() {
        didInsertElementCount++;
        assert.notEqual(this.element.parentNode, null, 'precond component is in DOM');
      },
      willDestroyElement() {
        willDestroyElementCount++;
        assert.notEqual(this.element.parentNode, null, 'has not been removed from DOM yet');
      }
    });

    this.registerComponent('foo-bar', { ComponentClass: FooBarComponent, template: 'hello' });

    this.render('{{#if switch}}{{foo-bar}}{{/if}}', { switch: true });

    assert.equal(didInsertElementCount, 1, 'didInsertElement was called once');

    this.assertComponentElement(this.firstChild, { content: 'hello' });

    this.runTask(() => set(this.context, 'switch', false));

    assert.equal(willDestroyElementCount, 1, 'willDestroyElement was called once');

    this.assertText('');
  }
});


Fix bug where color selector's inputs'd be out of sync

--- app/assets/javascripts/views/shared/colorSelectorView.js
+++ app/assets/javascripts/views/shared/colorSelectorView.js
@@ -3,6 +3,7 @@

   App.View.ColorSelectorView = Backbone.View.extend({
     events: {
+      'change input[type="text"]': '_updateColor',
       'change input[type="color"]': '_updateColor'
     },

@@ -13,8 +14,10 @@
     _updateColor: function (e) {
       var color = e.currentTarget.value;
       var textInput = this.el.querySelector('input[type="text"]');
+      var colorInput = this.el.querySelector('input[type="color"]');

       textInput.value = color;
+      colorInput.value = color;
     }
   });
 })(this.App);

<|original_code|>
(function (App) {
  'use strict';

  App.View.ColorSelectorView = Backbone.View.extend({
    events: {
      'change input[type="color"]': '_updateColor'
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var color = e.currentTarget.value;
      var textInput = this.el.querySelector('input[type="text"]');

      textInput.value = color;
    }
  });
})(this.App);

<|edits_diff|>
--- app/assets/javascripts/views/shared/colorSelectorView.js
+++ app/assets/javascripts/views/shared/colorSelectorView.js
@@ -3,6 +3,7 @@

   App.View.ColorSelectorView = Backbone.View.extend({
     events: {
+      'change input[type="text"]': '_updateColor',
       'change input[type="color"]': '_updateColor'
     },

@@ -13,6 +14,7 @@
     _updateColor: function (e) {
       var color = e.currentTarget.value;
       var textInput = this.el.querySelector('input[type="text"]');
+      var colorInput = this.el.querySelector('input[type="color"]');

       textInput.value = color;
     }
<|current_version|>
(function (App) {
  'use strict';

  App.View.ColorSelectorView = Backbone.View.extend({
    events: {
      'change input[type="text"]': '_updateColor',
      'change input[type="color"]': '_updateColor'
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var color = e.currentTarget.value;
      var textInput = this.el.querySelector('input[type="text"]');
      var colorInput = this.el.querySelector('input[type="color"]');

      textInput.value = color;
    }
  });
})(this.App);

<|next_version|>
(function (App) {
  'use strict';

  App.View.ColorSelectorView = Backbone.View.extend({
    events: {
      'change input[type="text"]': '_updateColor',
      'change input[type="color"]': '_updateColor'
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var color = e.currentTarget.value;
      var textInput = this.el.querySelector('input[type="text"]');
      var colorInput = this.el.querySelector('input[type="color"]');

      textInput.value = color;
      colorInput.value = color;
    }
  });
})(this.App);


Hide certain values from initial view to logged in user

--- modules/core/server/controllers/core.server.controller.js
+++ modules/core/server/controllers/core.server.controller.js
@@ -13,7 +13,11 @@
   if(req.user) {
     currentUser = req.user;
     // Don't just expose everything to the view...
+    delete currentUser.resetPasswordToken;
+    delete currentUser.resetPasswordExpires;
     delete currentUser.emailToken;
+    delete currentUser.password;
+    delete currentUser.salt;
   }

   res.render('modules/core/server/views/index', {

<|original_code|>
'use strict';

var errorHandler = require('./errors.server.controller');

/**
 * Render the main application page
 */
exports.renderIndex = function(req, res) {

  var currentUser = null;

  // Expose user
  if(req.user) {
    currentUser = req.user;
    // Don't just expose everything to the view...
    delete currentUser.emailToken;
  }

  res.render('modules/core/server/views/index', {
    user: currentUser
  });
};

/**
 * Render the server not found responses
 * Performs content-negotiation on the Accept HTTP header
 */
exports.renderNotFound = function(req, res) {
  res.status(404).format({
    'text/html': function() {
      res.render('modules/core/server/views/404');
    },
    'application/json': function() {
      res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
    },
    'default': function() {
      res.send( errorHandler.getErrorMessageByKey('not-found') );
    }
  });
};

<|edits_diff|>
--- modules/core/server/controllers/core.server.controller.js
+++ modules/core/server/controllers/core.server.controller.js
@@ -13,6 +13,8 @@
   if(req.user) {
     currentUser = req.user;
     // Don't just expose everything to the view...
+    delete currentUser.resetPasswordToken;
+    delete currentUser.resetPasswordExpires;
     delete currentUser.emailToken;
   }

<|current_version|>
'use strict';

var errorHandler = require('./errors.server.controller');

/**
 * Render the main application page
 */
exports.renderIndex = function(req, res) {

  var currentUser = null;

  // Expose user
  if(req.user) {
    currentUser = req.user;
    // Don't just expose everything to the view...
    delete currentUser.resetPasswordToken;
    delete currentUser.resetPasswordExpires;
    delete currentUser.emailToken;
  }

  res.render('modules/core/server/views/index', {
    user: currentUser
  });
};

/**
 * Render the server not found responses
 * Performs content-negotiation on the Accept HTTP header
 */
exports.renderNotFound = function(req, res) {
  res.status(404).format({
    'text/html': function() {
      res.render('modules/core/server/views/404');
    },
    'application/json': function() {
      res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
    },
    'default': function() {
      res.send( errorHandler.getErrorMessageByKey('not-found') );
    }
  });
};

<|next_version|>
'use strict';

var errorHandler = require('./errors.server.controller');

/**
 * Render the main application page
 */
exports.renderIndex = function(req, res) {

  var currentUser = null;

  // Expose user
  if(req.user) {
    currentUser = req.user;
    // Don't just expose everything to the view...
    delete currentUser.resetPasswordToken;
    delete currentUser.resetPasswordExpires;
    delete currentUser.emailToken;
    delete currentUser.password;
    delete currentUser.salt;
  }

  res.render('modules/core/server/views/index', {
    user: currentUser
  });
};

/**
 * Render the server not found responses
 * Performs content-negotiation on the Accept HTTP header
 */
exports.renderNotFound = function(req, res) {
  res.status(404).format({
    'text/html': function() {
      res.render('modules/core/server/views/404');
    },
    'application/json': function() {
      res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
    },
    'default': function() {
      res.send( errorHandler.getErrorMessageByKey('not-found') );
    }
  });
};


Add proptype validation to PostTile component

--- resources/assets/components/PostTile/index.js
+++ resources/assets/components/PostTile/index.js
@@ -1,4 +1,5 @@
 import React from 'react';
+import PropTypes from 'prop-types';
 import { getImageUrlFromProp } from '../../helpers';

 class PostTile extends React.Component {
@@ -13,4 +14,8 @@
   }
 }

+PostTile.propTypes = {
+  details: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
+};
+
 export default PostTile;

<|original_code|>
import React from 'react';
import { getImageUrlFromProp } from '../../helpers';

class PostTile extends React.Component {
  render() {
    const post = this.props.details;

    return (

    )
  }
}

export default PostTile;

<|edits_diff|>
--- resources/assets/components/PostTile/index.js
+++ resources/assets/components/PostTile/index.js
@@ -1,4 +1,5 @@
 import React from 'react';
+import PropTypes from 'prop-types';
 import { getImageUrlFromProp } from '../../helpers';

 class PostTile extends React.Component {
<|current_version|>
import React from 'react';
import PropTypes from 'prop-types';
import { getImageUrlFromProp } from '../../helpers';

class PostTile extends React.Component {
  render() {
    const post = this.props.details;

    return (

    )
  }
}

export default PostTile;

<|next_version|>
import React from 'react';
import PropTypes from 'prop-types';
import { getImageUrlFromProp } from '../../helpers';

class PostTile extends React.Component {
  render() {
    const post = this.props.details;

    return (

    )
  }
}

PostTile.propTypes = {
  details: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default PostTile;


Add tracking event when clicking on Cookie Accept Button

--- Kwc/Statistics/OptBox/Component.defer.js
+++ Kwc/Statistics/OptBox/Component.defer.js
@@ -1,6 +1,7 @@
 var $ = require('jQuery');
 var onReady = require('kwf/on-ready');
 var cookieOpt = require('kwf/cookie-opt');
+var statistics = require('kwf/statistics');

 onReady.onRender('.kwcClass', function (el, config) {
     cookieOpt.load(function(api) {
@@ -13,6 +14,7 @@
             el.find('.kwcBem__accept').click(function(e) {
                 e.preventDefault();
                 api.setOpt('in');
+                statistics.trackEvent('Cookies', location.pathname, 'Click on Accept in Cookie Banner');
                 el.hide();
                 $('body').removeClass('kwfUp-showCookieBanner').addClass('kwfUp-cookieAccepted');
                 onReady.callOnContentReady($('body'), { action: 'widthChange' });

<|original_code|>
var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var cookieOpt = require('kwf/cookie-opt');

onReady.onRender('.kwcClass', function (el, config) {
    cookieOpt.load(function(api) {
        if (!api.getCookieIsSet()) {
            if (config.showBanner) {
                $('body').addClass('kwfUp-showCookieBanner');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            }
            el.show();
            el.find('.kwcBem__accept').click(function(e) {
                e.preventDefault();
                api.setOpt('in');
                el.hide();
                $('body').removeClass('kwfUp-showCookieBanner').addClass('kwfUp-cookieAccepted');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            });
        }
        api.onOptChanged(function (value) {
            $('body').find('.kwcClass').hide();
        });
    });
});

<|edits_diff|>
--- Kwc/Statistics/OptBox/Component.defer.js
+++ Kwc/Statistics/OptBox/Component.defer.js
@@ -1,6 +1,7 @@
 var $ = require('jQuery');
 var onReady = require('kwf/on-ready');
 var cookieOpt = require('kwf/cookie-opt');
+var statistics = require('kwf/statistics');

 onReady.onRender('.kwcClass', function (el, config) {
     cookieOpt.load(function(api) {
<|current_version|>
var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var cookieOpt = require('kwf/cookie-opt');
var statistics = require('kwf/statistics');

onReady.onRender('.kwcClass', function (el, config) {
    cookieOpt.load(function(api) {
        if (!api.getCookieIsSet()) {
            if (config.showBanner) {
                $('body').addClass('kwfUp-showCookieBanner');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            }
            el.show();
            el.find('.kwcBem__accept').click(function(e) {
                e.preventDefault();
                api.setOpt('in');
                el.hide();
                $('body').removeClass('kwfUp-showCookieBanner').addClass('kwfUp-cookieAccepted');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            });
        }
        api.onOptChanged(function (value) {
            $('body').find('.kwcClass').hide();
        });
    });
});

<|next_version|>
var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var cookieOpt = require('kwf/cookie-opt');
var statistics = require('kwf/statistics');

onReady.onRender('.kwcClass', function (el, config) {
    cookieOpt.load(function(api) {
        if (!api.getCookieIsSet()) {
            if (config.showBanner) {
                $('body').addClass('kwfUp-showCookieBanner');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            }
            el.show();
            el.find('.kwcBem__accept').click(function(e) {
                e.preventDefault();
                api.setOpt('in');
                statistics.trackEvent('Cookies', location.pathname, 'Click on Accept in Cookie Banner');
                el.hide();
                $('body').removeClass('kwfUp-showCookieBanner').addClass('kwfUp-cookieAccepted');
                onReady.callOnContentReady($('body'), { action: 'widthChange' });
            });
        }
        api.onOptChanged(function (value) {
            $('body').find('.kwcClass').hide();
        });
    });
});


Add missing entry in Core module

fix(InfoViz): Add missing entry in Core module

--- src/InfoViz/Core/index.js
+++ src/InfoViz/Core/index.js
@@ -1,15 +1,23 @@
 import D3MultiClick from './D3MultiClick';
 import FieldProvider from './FieldProvider';
+import Histogram1DProvider from './Histogram1DProvider';
 import Histogram2DProvider from './Histogram2DProvider';
+import HistogramBinHoverProvider from './HistogramBinHoverProvider';
 import LegendProvider from './LegendProvider';
+import MutualInformationProvider from './MutualInformationProvider';
+import PartitionProvider from './PartitionProvider';
 import ScoresProvider from './ScoresProvider';
 import SelectionProvider from './SelectionProvider';

 export default {
   D3MultiClick,
   FieldProvider,
+  Histogram1DProvider,
   Histogram2DProvider,
+  HistogramBinHoverProvider,
   LegendProvider,
+  MutualInformationProvider,
+  PartitionProvider,
   ScoresProvider,
   SelectionProvider,
 };

<|original_code|>
import D3MultiClick from './D3MultiClick';
import FieldProvider from './FieldProvider';
import Histogram2DProvider from './Histogram2DProvider';
import LegendProvider from './LegendProvider';
import ScoresProvider from './ScoresProvider';
import SelectionProvider from './SelectionProvider';

export default {
  D3MultiClick,
  FieldProvider,
  Histogram2DProvider,
  LegendProvider,
  ScoresProvider,
  SelectionProvider,
};

<|edits_diff|>
--- src/InfoViz/Core/index.js
+++ src/InfoViz/Core/index.js
@@ -1,14 +1,20 @@
 import D3MultiClick from './D3MultiClick';
 import FieldProvider from './FieldProvider';
+import Histogram1DProvider from './Histogram1DProvider';
 import Histogram2DProvider from './Histogram2DProvider';
+import HistogramBinHoverProvider from './HistogramBinHoverProvider';
 import LegendProvider from './LegendProvider';
+import MutualInformationProvider from './MutualInformationProvider';
+import PartitionProvider from './PartitionProvider';
 import ScoresProvider from './ScoresProvider';
 import SelectionProvider from './SelectionProvider';

 export default {
   D3MultiClick,
   FieldProvider,
+  Histogram1DProvider,
   Histogram2DProvider,
+  HistogramBinHoverProvider,
   LegendProvider,
   ScoresProvider,
   SelectionProvider,
<|current_version|>
import D3MultiClick from './D3MultiClick';
import FieldProvider from './FieldProvider';
import Histogram1DProvider from './Histogram1DProvider';
import Histogram2DProvider from './Histogram2DProvider';
import HistogramBinHoverProvider from './HistogramBinHoverProvider';
import LegendProvider from './LegendProvider';
import MutualInformationProvider from './MutualInformationProvider';
import PartitionProvider from './PartitionProvider';
import ScoresProvider from './ScoresProvider';
import SelectionProvider from './SelectionProvider';

export default {
  D3MultiClick,
  FieldProvider,
  Histogram1DProvider,
  Histogram2DProvider,
  HistogramBinHoverProvider,
  LegendProvider,
  ScoresProvider,
  SelectionProvider,
};

<|next_version|>
import D3MultiClick from './D3MultiClick';
import FieldProvider from './FieldProvider';
import Histogram1DProvider from './Histogram1DProvider';
import Histogram2DProvider from './Histogram2DProvider';
import HistogramBinHoverProvider from './HistogramBinHoverProvider';
import LegendProvider from './LegendProvider';
import MutualInformationProvider from './MutualInformationProvider';
import PartitionProvider from './PartitionProvider';
import ScoresProvider from './ScoresProvider';
import SelectionProvider from './SelectionProvider';

export default {
  D3MultiClick,
  FieldProvider,
  Histogram1DProvider,
  Histogram2DProvider,
  HistogramBinHoverProvider,
  LegendProvider,
  MutualInformationProvider,
  PartitionProvider,
  ScoresProvider,
  SelectionProvider,
};


Change views directory to a relative path.

--- backend/index.js
+++ backend/index.js
@@ -2,6 +2,7 @@

 var debug = require('debug')('server');
 var express = require('express');
+var path = require('path');

 var routes = require('./routes/index');

@@ -10,6 +11,7 @@
 app.use('/', routes);

 app.set('view engine', 'jade');
+app.set('views', path.join(__dirname, 'views'));

 var server = app.listen(process.env.PORT || 3000, function () {
   var host = server.address().address;

<|original_code|>
"use strict";

var debug = require('debug')('server');
var express = require('express');

var routes = require('./routes/index');

var app = express();

app.use('/', routes);

app.set('view engine', 'jade');

var server = app.listen(process.env.PORT || 3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  debug('listening at http://%s:%s', host, port);
});

<|edits_diff|>
--- backend/index.js
+++ backend/index.js
@@ -2,6 +2,7 @@

 var debug = require('debug')('server');
 var express = require('express');
+var path = require('path');

 var routes = require('./routes/index');

<|current_version|>
"use strict";

var debug = require('debug')('server');
var express = require('express');
var path = require('path');

var routes = require('./routes/index');

var app = express();

app.use('/', routes);

app.set('view engine', 'jade');

var server = app.listen(process.env.PORT || 3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  debug('listening at http://%s:%s', host, port);
});

<|next_version|>
"use strict";

var debug = require('debug')('server');
var express = require('express');
var path = require('path');

var routes = require('./routes/index');

var app = express();

app.use('/', routes);

app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'views'));

var server = app.listen(process.env.PORT || 3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  debug('listening at http://%s:%s', host, port);
});


Fix tests for browsers that support native custom elements.

--- test/unit/lifecycle-scenarios.js
+++ test/unit/lifecycle-scenarios.js
@@ -18,6 +18,7 @@

     if (supportCustomElements()) {
       expect(called).to.equal(true);
+      done();
     } else {
       expect(called).to.equal(false);
       helperReady(function () {
@@ -41,6 +42,7 @@
     // We have to debounce in non-native for performance.
     if (supportCustomElements()) {
       expect(called).to.equal(true);
+      done();
     } else {
       expect(called).to.equal(false);
       helperReady(function () {

<|original_code|>
import helperElement from '../lib/element';
import helperFixture from '../lib/fixture';
import helperReady from '../lib/ready';
import skate from '../../src/index';
import supportCustomElements from '../../src/support/custom-elements';

describe('lifecycle-scenarios', function () {
  it('definition is registered before the element is created', function (done) {
    var el = helperElement();
    var called = false;

    skate(el.safe, {
      created () {
        called = true;
      }
    });
    helperFixture(document.createElement(el.safe));

    if (supportCustomElements()) {
      expect(called).to.equal(true);
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });

  it('definition is registered after the element is created', function (done) {
    var el = helperElement();
    var called = false;

    helperFixture(el.create());
    skate(el.safe, {
      created () {
        called = true;
      }
    });

    // We have to debounce in non-native for performance.
    if (supportCustomElements()) {
      expect(called).to.equal(true);
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });
});

<|edits_diff|>
--- test/unit/lifecycle-scenarios.js
+++ test/unit/lifecycle-scenarios.js
@@ -18,6 +18,7 @@

     if (supportCustomElements()) {
       expect(called).to.equal(true);
+      done();
     } else {
       expect(called).to.equal(false);
       helperReady(function () {
<|current_version|>
import helperElement from '../lib/element';
import helperFixture from '../lib/fixture';
import helperReady from '../lib/ready';
import skate from '../../src/index';
import supportCustomElements from '../../src/support/custom-elements';

describe('lifecycle-scenarios', function () {
  it('definition is registered before the element is created', function (done) {
    var el = helperElement();
    var called = false;

    skate(el.safe, {
      created () {
        called = true;
      }
    });
    helperFixture(document.createElement(el.safe));

    if (supportCustomElements()) {
      expect(called).to.equal(true);
      done();
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });

  it('definition is registered after the element is created', function (done) {
    var el = helperElement();
    var called = false;

    helperFixture(el.create());
    skate(el.safe, {
      created () {
        called = true;
      }
    });

    // We have to debounce in non-native for performance.
    if (supportCustomElements()) {
      expect(called).to.equal(true);
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });
});

<|next_version|>
import helperElement from '../lib/element';
import helperFixture from '../lib/fixture';
import helperReady from '../lib/ready';
import skate from '../../src/index';
import supportCustomElements from '../../src/support/custom-elements';

describe('lifecycle-scenarios', function () {
  it('definition is registered before the element is created', function (done) {
    var el = helperElement();
    var called = false;

    skate(el.safe, {
      created () {
        called = true;
      }
    });
    helperFixture(document.createElement(el.safe));

    if (supportCustomElements()) {
      expect(called).to.equal(true);
      done();
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });

  it('definition is registered after the element is created', function (done) {
    var el = helperElement();
    var called = false;

    helperFixture(el.create());
    skate(el.safe, {
      created () {
        called = true;
      }
    });

    // We have to debounce in non-native for performance.
    if (supportCustomElements()) {
      expect(called).to.equal(true);
      done();
    } else {
      expect(called).to.equal(false);
      helperReady(function () {
        expect(called).to.equal(true);
        done();
      });
    }
  });
});


Add some debug output for convenience.

Add some debug output for convenience.

--- lib/web/rest/v1/mqtt.js
+++ lib/web/rest/v1/mqtt.js
@@ -1,5 +1,6 @@
 'use strict';

+var debug = require('debug')('frontend:mqtt');
 var express = require('express');
 var router = express.Router();
 var auth = require('../../passport');
@@ -22,6 +23,8 @@
   req.app.get('service').facet('amqp').then(function(amqp) {
   	amqp.publish('amq.topic', routingKey, new Buffer(payload));

+  	debug('Publishing to routing key', routingKey, 'payload', payload);
+
   	restUtils.standardResponse(res, { "success": true }, {type: 'object'});
   });
 });

<|original_code|>
'use strict';

var express = require('express');
var router = express.Router();
var auth = require('../../passport');

var restUtils = require('../utils');

var os = require('os');

router.post('/mqtt', auth.requireAPIAuth(), function(req, res) {
  var userId = req.user.id;
  var topic = req.query.topic;
  var payload = req.body;

  if (typeof payload === 'object') {
  	payload = JSON.stringify(payload);
  }

  var routingKey = userId + '.' + topic.replace('/', '.');

  req.app.get('service').facet('amqp').then(function(amqp) {
  	amqp.publish('amq.topic', routingKey, new Buffer(payload));

  	restUtils.standardResponse(res, { "success": true }, {type: 'object'});
  });
});

module.exports = function(parent) {
  parent.use(router);
};

<|edits_diff|>
--- lib/web/rest/v1/mqtt.js
+++ lib/web/rest/v1/mqtt.js
@@ -1,5 +1,6 @@
 'use strict';

+var debug = require('debug')('frontend:mqtt');
 var express = require('express');
 var router = express.Router();
 var auth = require('../../passport');
<|current_version|>
'use strict';

var debug = require('debug')('frontend:mqtt');
var express = require('express');
var router = express.Router();
var auth = require('../../passport');

var restUtils = require('../utils');

var os = require('os');

router.post('/mqtt', auth.requireAPIAuth(), function(req, res) {
  var userId = req.user.id;
  var topic = req.query.topic;
  var payload = req.body;

  if (typeof payload === 'object') {
  	payload = JSON.stringify(payload);
  }

  var routingKey = userId + '.' + topic.replace('/', '.');

  req.app.get('service').facet('amqp').then(function(amqp) {
  	amqp.publish('amq.topic', routingKey, new Buffer(payload));

  	restUtils.standardResponse(res, { "success": true }, {type: 'object'});
  });
});

module.exports = function(parent) {
  parent.use(router);
};

<|next_version|>
'use strict';

var debug = require('debug')('frontend:mqtt');
var express = require('express');
var router = express.Router();
var auth = require('../../passport');

var restUtils = require('../utils');

var os = require('os');

router.post('/mqtt', auth.requireAPIAuth(), function(req, res) {
  var userId = req.user.id;
  var topic = req.query.topic;
  var payload = req.body;

  if (typeof payload === 'object') {
  	payload = JSON.stringify(payload);
  }

  var routingKey = userId + '.' + topic.replace('/', '.');

  req.app.get('service').facet('amqp').then(function(amqp) {
  	amqp.publish('amq.topic', routingKey, new Buffer(payload));

  	debug('Publishing to routing key', routingKey, 'payload', payload);

  	restUtils.standardResponse(res, { "success": true }, {type: 'object'});
  });
});

module.exports = function(parent) {
  parent.use(router);
};


Add logging to show store injected into routes is a DS.Store

--- addon/routes/index.js
+++ addon/routes/index.js
@@ -1,9 +1,12 @@
 import Ember from 'ember';
+import DS from 'ember-data';

 export default Ember.Route.extend({
   blogData: Ember.inject.service(),

   model() {
+    console.log('store service is an instanceof DS.Store', this.get('store') instanceof DS.Store);
+
     return this.get('blogData').posts;
   }
 });

<|original_code|>
import Ember from 'ember';

export default Ember.Route.extend({
  blogData: Ember.inject.service(),

  model() {
    return this.get('blogData').posts;
  }
});

<|edits_diff|>
--- addon/routes/index.js
+++ addon/routes/index.js
@@ -1,4 +1,5 @@
 import Ember from 'ember';
+import DS from 'ember-data';

 export default Ember.Route.extend({
   blogData: Ember.inject.service(),
<|current_version|>
import Ember from 'ember';
import DS from 'ember-data';

export default Ember.Route.extend({
  blogData: Ember.inject.service(),

  model() {
    return this.get('blogData').posts;
  }
});

<|next_version|>
import Ember from 'ember';
import DS from 'ember-data';

export default Ember.Route.extend({
  blogData: Ember.inject.service(),

  model() {
    console.log('store service is an instanceof DS.Store', this.get('store') instanceof DS.Store);

    return this.get('blogData').posts;
  }
});


Add missing number and object static methods

Took from "Object static methods" and "Number properties" sections here

https://kangax.github.io/compat-table/es6/

--- src/rules/no-es6-static-methods.js
+++ src/rules/no-es6-static-methods.js
@@ -31,8 +31,14 @@
       'Math.sign',
       'Number.isNaN',
       'Number.isFinite',
+      'Number.isInteger',
       'Number.isSafeInteger',
+      'Number.parseFloat',
+      'Number.parseInt',
       'Object.assign',
+      'Object.is',
+      'Object.getOwnPropertySymbols',
+      'Object.setPrototypeOf',
     ];
     const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name));

<|original_code|>
'use strict';

module.exports = {
  meta: {
    docs: {
      description: 'Forbid methods added in ES6'
    },
    schema: [{
      type: 'object',
      properties: {
        exceptMethods: {
          type: 'array',
          items: {
            type: 'string'
          }
        }
      }
    }]
  },
  create(context) {
    const options = Object.assign({ exceptMethods: [] }, context.options[0]);
    const exceptMethods = new Set(options.exceptMethods);

    const es6StaticFunctions = [
      'Array.from',
      'Array.of',
      'Math.acosh',
      'Math.hypot',
      'Math.trunc',
      'Math.imul',
      'Math.sign',
      'Number.isNaN',
      'Number.isFinite',
      'Number.isSafeInteger',
      'Object.assign',
    ];
    const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name));

    return {
      CallExpression(node) {
        if(node.callee && node.callee.property && node.callee.object) {
          const functionName = node.callee.object.name + '.' + node.callee.property.name;
          if(staticFunctions.includes(functionName)) {
            context.report({
              node: node.callee.property,
              message: 'ES6 static methods not allowed: ' + functionName
            });
          }
        }
      }
    };
  }
};

<|edits_diff|>
--- src/rules/no-es6-static-methods.js
+++ src/rules/no-es6-static-methods.js
@@ -31,7 +31,10 @@
       'Math.sign',
       'Number.isNaN',
       'Number.isFinite',
+      'Number.isInteger',
       'Number.isSafeInteger',
+      'Number.parseFloat',
+      'Number.parseInt',
       'Object.assign',
     ];
     const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name));
<|current_version|>
'use strict';

module.exports = {
  meta: {
    docs: {
      description: 'Forbid methods added in ES6'
    },
    schema: [{
      type: 'object',
      properties: {
        exceptMethods: {
          type: 'array',
          items: {
            type: 'string'
          }
        }
      }
    }]
  },
  create(context) {
    const options = Object.assign({ exceptMethods: [] }, context.options[0]);
    const exceptMethods = new Set(options.exceptMethods);

    const es6StaticFunctions = [
      'Array.from',
      'Array.of',
      'Math.acosh',
      'Math.hypot',
      'Math.trunc',
      'Math.imul',
      'Math.sign',
      'Number.isNaN',
      'Number.isFinite',
      'Number.isInteger',
      'Number.isSafeInteger',
      'Number.parseFloat',
      'Number.parseInt',
      'Object.assign',
    ];
    const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name));

    return {
      CallExpression(node) {
        if(node.callee && node.callee.property && node.callee.object) {
          const functionName = node.callee.object.name + '.' + node.callee.property.name;
          if(staticFunctions.includes(functionName)) {
            context.report({
              node: node.callee.property,
              message: 'ES6 static methods not allowed: ' + functionName
            });
          }
        }
      }
    };
  }
};

<|next_version|>
'use strict';

module.exports = {
  meta: {
    docs: {
      description: 'Forbid methods added in ES6'
    },
    schema: [{
      type: 'object',
      properties: {
        exceptMethods: {
          type: 'array',
          items: {
            type: 'string'
          }
        }
      }
    }]
  },
  create(context) {
    const options = Object.assign({ exceptMethods: [] }, context.options[0]);
    const exceptMethods = new Set(options.exceptMethods);

    const es6StaticFunctions = [
      'Array.from',
      'Array.of',
      'Math.acosh',
      'Math.hypot',
      'Math.trunc',
      'Math.imul',
      'Math.sign',
      'Number.isNaN',
      'Number.isFinite',
      'Number.isInteger',
      'Number.isSafeInteger',
      'Number.parseFloat',
      'Number.parseInt',
      'Object.assign',
      'Object.is',
      'Object.getOwnPropertySymbols',
      'Object.setPrototypeOf',
    ];
    const staticFunctions = es6StaticFunctions.filter((name) => !exceptMethods.has(name));

    return {
      CallExpression(node) {
        if(node.callee && node.callee.property && node.callee.object) {
          const functionName = node.callee.object.name + '.' + node.callee.property.name;
          if(staticFunctions.includes(functionName)) {
            context.report({
              node: node.callee.property,
              message: 'ES6 static methods not allowed: ' + functionName
            });
          }
        }
      }
    };
  }
};


Send TokenError when we need a refresh

Send TokenError when we need a refresh

--- lib/update.js
+++ lib/update.js
@@ -1,6 +1,7 @@
 'use strict';

 var async = require('async');
+var TokenError = require('anyfetch-provider').TokenError;

 var retrieve = require('./helpers/retrieve.js');
 var retrieveCards = retrieve.retrieveCards;
@@ -20,6 +21,9 @@
     },
   }, function handleCards(err, cardsAndDates) {
     if(err) {
+      if(err.toString().match(/token/i)) {
+        return cb(new TokenError());
+      }
       return cb(err);
     }

<|original_code|>
'use strict';

var async = require('async');

var retrieve = require('./helpers/retrieve.js');
var retrieveCards = retrieve.retrieveCards;
var retrieveDeletedCards = retrieve.retrieveDeletedCards;

var defaultCursor = retrieve.defaultCursor;

module.exports = function updateAccount(serviceData, cursor, queues, cb) {
  // Retrieve all contacts since last call
  async.parallel({
    newCards: function RetrieveNewCards(cb) {
      retrieveCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
    deletedCards: function RetrieveDeletedCards(cb) {
      retrieveDeletedCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
  }, function handleCards(err, cardsAndDates) {
    if(err) {
      return cb(err);
    }

    var newCursor = new Date(Math.max(cardsAndDates.newCards[1], cardsAndDates.deletedCards[1]) + 1000);
    cardsAndDates.newCards[0].forEach(function(card) {
      queues.addition.push(card);
    });
    cardsAndDates.deletedCards[0].forEach(function(card) {
      queues.deletion.push(card);
    });

    cb(null, newCursor);
  });
};

<|edits_diff|>
--- lib/update.js
+++ lib/update.js
@@ -1,6 +1,7 @@
 'use strict';

 var async = require('async');
+var TokenError = require('anyfetch-provider').TokenError;

 var retrieve = require('./helpers/retrieve.js');
 var retrieveCards = retrieve.retrieveCards;
<|current_version|>
'use strict';

var async = require('async');
var TokenError = require('anyfetch-provider').TokenError;

var retrieve = require('./helpers/retrieve.js');
var retrieveCards = retrieve.retrieveCards;
var retrieveDeletedCards = retrieve.retrieveDeletedCards;

var defaultCursor = retrieve.defaultCursor;

module.exports = function updateAccount(serviceData, cursor, queues, cb) {
  // Retrieve all contacts since last call
  async.parallel({
    newCards: function RetrieveNewCards(cb) {
      retrieveCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
    deletedCards: function RetrieveDeletedCards(cb) {
      retrieveDeletedCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
  }, function handleCards(err, cardsAndDates) {
    if(err) {
      return cb(err);
    }

    var newCursor = new Date(Math.max(cardsAndDates.newCards[1], cardsAndDates.deletedCards[1]) + 1000);
    cardsAndDates.newCards[0].forEach(function(card) {
      queues.addition.push(card);
    });
    cardsAndDates.deletedCards[0].forEach(function(card) {
      queues.deletion.push(card);
    });

    cb(null, newCursor);
  });
};

<|next_version|>
'use strict';

var async = require('async');
var TokenError = require('anyfetch-provider').TokenError;

var retrieve = require('./helpers/retrieve.js');
var retrieveCards = retrieve.retrieveCards;
var retrieveDeletedCards = retrieve.retrieveDeletedCards;

var defaultCursor = retrieve.defaultCursor;

module.exports = function updateAccount(serviceData, cursor, queues, cb) {
  // Retrieve all contacts since last call
  async.parallel({
    newCards: function RetrieveNewCards(cb) {
      retrieveCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
    deletedCards: function RetrieveDeletedCards(cb) {
      retrieveDeletedCards(serviceData.accessToken, cursor || defaultCursor, cb);
    },
  }, function handleCards(err, cardsAndDates) {
    if(err) {
      if(err.toString().match(/token/i)) {
        return cb(new TokenError());
      }
      return cb(err);
    }

    var newCursor = new Date(Math.max(cardsAndDates.newCards[1], cardsAndDates.deletedCards[1]) + 1000);
    cardsAndDates.newCards[0].forEach(function(card) {
      queues.addition.push(card);
    });
    cardsAndDates.deletedCards[0].forEach(function(card) {
      queues.deletion.push(card);
    });

    cb(null, newCursor);
  });
};


Add nospacing attribute to Grid

Add nospacing attribute to Grid

--- src/grid.js
+++ src/grid.js
@@ -5,8 +5,10 @@
 	view(ctrl, args, ...children) {
 		args = args || {};
 		let attr = attributes(args);
+		let {nospacing} = args;

 		attr.class.push('mdl-grid');
+		if (nospacing) attr.class.push('mdl-grid--no-spacing');
 		return <div {...attr}>{children}</div>;
 	}
 };

<|original_code|>
import m from 'mithril';
import attributes from './attributes';

export let Grid = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);

		attr.class.push('mdl-grid');
		return
{children}
;
	}
};

export let Cell = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);
		let {align, width, phone, tablet, desktop, nophone, notablet, nodesktop} = args;

		attr.class.push('mdl-cell');
		if(align) attr.class.push(`mdl-cell--${align}`);
		if(width) attr.class.push(`mdl-cell--${width}-col`);
		if(phone) attr.class.push(`mdl-cell--${phone}-col-phone`);
		if(tablet) attr.class.push(`mdl-cell--${tablet}-col-tablet`);
		if(desktop) attr.class.push(`mdl-cell--${desktop}-col-desktop`);
		if(nophone) attr.class.push('mdl-cell--hide-phone');
		if(notablet) attr.class.push('mdl-cell--hide-tablet');
		if(nodesktop) attr.class.push('mdl-cell--hide-desktop');

		return
{children}
;
	}
};

<|edits_diff|>
--- src/grid.js
+++ src/grid.js
@@ -5,6 +5,7 @@
 	view(ctrl, args, ...children) {
 		args = args || {};
 		let attr = attributes(args);
+		let {nospacing} = args;

 		attr.class.push('mdl-grid');
 		return
{children}
;
<|current_version|>
import m from 'mithril';
import attributes from './attributes';

export let Grid = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);
		let {nospacing} = args;

		attr.class.push('mdl-grid');
		return
{children}
;
	}
};

export let Cell = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);
		let {align, width, phone, tablet, desktop, nophone, notablet, nodesktop} = args;

		attr.class.push('mdl-cell');
		if(align) attr.class.push(`mdl-cell--${align}`);
		if(width) attr.class.push(`mdl-cell--${width}-col`);
		if(phone) attr.class.push(`mdl-cell--${phone}-col-phone`);
		if(tablet) attr.class.push(`mdl-cell--${tablet}-col-tablet`);
		if(desktop) attr.class.push(`mdl-cell--${desktop}-col-desktop`);
		if(nophone) attr.class.push('mdl-cell--hide-phone');
		if(notablet) attr.class.push('mdl-cell--hide-tablet');
		if(nodesktop) attr.class.push('mdl-cell--hide-desktop');

		return
{children}
;
	}
};

<|next_version|>
import m from 'mithril';
import attributes from './attributes';

export let Grid = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);
		let {nospacing} = args;

		attr.class.push('mdl-grid');
		if (nospacing) attr.class.push('mdl-grid--no-spacing');
		return
{children}
;
	}
};

export let Cell = {
	view(ctrl, args, ...children) {
		args = args || {};
		let attr = attributes(args);
		let {align, width, phone, tablet, desktop, nophone, notablet, nodesktop} = args;

		attr.class.push('mdl-cell');
		if(align) attr.class.push(`mdl-cell--${align}`);
		if(width) attr.class.push(`mdl-cell--${width}-col`);
		if(phone) attr.class.push(`mdl-cell--${phone}-col-phone`);
		if(tablet) attr.class.push(`mdl-cell--${tablet}-col-tablet`);
		if(desktop) attr.class.push(`mdl-cell--${desktop}-col-desktop`);
		if(nophone) attr.class.push('mdl-cell--hide-phone');
		if(notablet) attr.class.push('mdl-cell--hide-tablet');
		if(nodesktop) attr.class.push('mdl-cell--hide-desktop');

		return
{children}
;
	}
};


Add extra Counter component in spec to show the result with value '0'

--- spec/components/counter.js
+++ spec/components/counter.js
@@ -16,8 +16,10 @@
             <p>
               <Counter className={style.counter} count={999} />
               <Counter className={style.counter} count={9} size="small" />
+              <Counter className={style.counter} count={0} size="small" />
               <Counter className={style.counter} color="ruby" count={100} maxCount={99} />
               <Counter className={style.counter} color="ruby" count={9} size="small" />
+              <Counter className={style.counter} color="ruby" count={0} size="small" />
               <Counter className={style.counter} color="ruby" />
               <Counter className={style.counter} color="ruby" size="small" />
             </p>

<|original_code|>
import React, { PureComponent } from 'react';
import { Counter, Heading1, Section } from '../../components';
import style from './counter.css';

class CounterTest extends PureComponent {

  render () {
    return (

          <Heading1>Counters</Heading1>

              <Counter className={style.counter} count={999} />
              <Counter className={style.counter} count={9} size="small" />
              <Counter className={style.counter} color="ruby" count={100} maxCount={99} />
              <Counter className={style.counter} color="ruby" count={9} size="small" />
              <Counter className={style.counter} color="ruby" />
              <Counter className={style.counter} color="ruby" size="small" />

    );
  }
}

export default CounterTest;

<|edits_diff|>
--- spec/components/counter.js
+++ spec/components/counter.js
@@ -16,6 +16,7 @@

               <Counter className={style.counter} count={999} />
               <Counter className={style.counter} count={9} size="small" />
+              <Counter className={style.counter} count={0} size="small" />
               <Counter className={style.counter} color="ruby" count={100} maxCount={99} />
               <Counter className={style.counter} color="ruby" count={9} size="small" />
               <Counter className={style.counter} color="ruby" />
<|current_version|>
import React, { PureComponent } from 'react';
import { Counter, Heading1, Section } from '../../components';
import style from './counter.css';

class CounterTest extends PureComponent {

  render () {
    return (

          <Heading1>Counters</Heading1>

              <Counter className={style.counter} count={999} />
              <Counter className={style.counter} count={9} size="small" />
              <Counter className={style.counter} count={0} size="small" />
              <Counter className={style.counter} color="ruby" count={100} maxCount={99} />
              <Counter className={style.counter} color="ruby" count={9} size="small" />
              <Counter className={style.counter} color="ruby" />
              <Counter className={style.counter} color="ruby" size="small" />

    );
  }
}

export default CounterTest;

<|next_version|>
import React, { PureComponent } from 'react';
import { Counter, Heading1, Section } from '../../components';
import style from './counter.css';

class CounterTest extends PureComponent {

  render () {
    return (

          <Heading1>Counters</Heading1>

              <Counter className={style.counter} count={999} />
              <Counter className={style.counter} count={9} size="small" />
              <Counter className={style.counter} count={0} size="small" />
              <Counter className={style.counter} color="ruby" count={100} maxCount={99} />
              <Counter className={style.counter} color="ruby" count={9} size="small" />
              <Counter className={style.counter} color="ruby" count={0} size="small" />
              <Counter className={style.counter} color="ruby" />
              <Counter className={style.counter} color="ruby" size="small" />

    );
  }
}

export default CounterTest;


Return unmodified source immediately if no generator functions detected.

Closes #13.

--- main.js
+++ main.js
@@ -4,6 +4,7 @@
 var guessTabWidth = require("./lib/util").guessTabWidth;
 var recast = require("recast");
 var esprimaHarmony = require("esprima");
+var genFunExp = /\bfunction\s*\*/;

 assert.ok(
   /harmony/.test(esprimaHarmony.version),
@@ -11,12 +12,17 @@
 );

 function regenerate(source) {
+  if (!genFunExp.test(source)) {
+    return source; // Shortcut: no generators to transform.
+  }
+
   var options = {
     tabWidth: guessTabWidth(source),
     // Use the harmony branch of Esprima that installs with regenerator
     // instead of the master branch that recast provides.
     esprima: esprimaHarmony
   };
+
   var ast = recast.parse(source, options);
   return recast.print(transform(ast), options);
 }

<|original_code|>
var assert = require("assert");
var path = require("path");
var transform = require("./lib/visit").transform;
var guessTabWidth = require("./lib/util").guessTabWidth;
var recast = require("recast");
var esprimaHarmony = require("esprima");

assert.ok(
  /harmony/.test(esprimaHarmony.version),
  "Bad esprima version: " + esprimaHarmony.version
);

function regenerate(source) {
  var options = {
    tabWidth: guessTabWidth(source),
    // Use the harmony branch of Esprima that installs with regenerator
    // instead of the master branch that recast provides.
    esprima: esprimaHarmony
  };
  var ast = recast.parse(source, options);
  return recast.print(transform(ast), options);
}

// To modify an AST directly, call require("regenerator").transform(ast).
regenerate.transform = transform;

regenerate.runtime = {
  dev: path.join(__dirname, "runtime", "dev.js"),
  min: path.join(__dirname, "runtime", "min.js")
};

// To transform a string of ES6 code, call require("regenerator")(source);
module.exports = regenerate;

<|edits_diff|>
--- main.js
+++ main.js
@@ -4,6 +4,7 @@
 var guessTabWidth = require("./lib/util").guessTabWidth;
 var recast = require("recast");
 var esprimaHarmony = require("esprima");
+var genFunExp = /\bfunction\s*\*/;

 assert.ok(
   /harmony/.test(esprimaHarmony.version),
@@ -11,6 +12,10 @@
 );

 function regenerate(source) {
+  if (!genFunExp.test(source)) {
+    return source; // Shortcut: no generators to transform.
+  }
+
   var options = {
     tabWidth: guessTabWidth(source),
     // Use the harmony branch of Esprima that installs with regenerator
<|current_version|>
var assert = require("assert");
var path = require("path");
var transform = require("./lib/visit").transform;
var guessTabWidth = require("./lib/util").guessTabWidth;
var recast = require("recast");
var esprimaHarmony = require("esprima");
var genFunExp = /\bfunction\s*\*/;

assert.ok(
  /harmony/.test(esprimaHarmony.version),
  "Bad esprima version: " + esprimaHarmony.version
);

function regenerate(source) {
  if (!genFunExp.test(source)) {
    return source; // Shortcut: no generators to transform.
  }

  var options = {
    tabWidth: guessTabWidth(source),
    // Use the harmony branch of Esprima that installs with regenerator
    // instead of the master branch that recast provides.
    esprima: esprimaHarmony
  };
  var ast = recast.parse(source, options);
  return recast.print(transform(ast), options);
}

// To modify an AST directly, call require("regenerator").transform(ast).
regenerate.transform = transform;

regenerate.runtime = {
  dev: path.join(__dirname, "runtime", "dev.js"),
  min: path.join(__dirname, "runtime", "min.js")
};

// To transform a string of ES6 code, call require("regenerator")(source);
module.exports = regenerate;

<|next_version|>
var assert = require("assert");
var path = require("path");
var transform = require("./lib/visit").transform;
var guessTabWidth = require("./lib/util").guessTabWidth;
var recast = require("recast");
var esprimaHarmony = require("esprima");
var genFunExp = /\bfunction\s*\*/;

assert.ok(
  /harmony/.test(esprimaHarmony.version),
  "Bad esprima version: " + esprimaHarmony.version
);

function regenerate(source) {
  if (!genFunExp.test(source)) {
    return source; // Shortcut: no generators to transform.
  }

  var options = {
    tabWidth: guessTabWidth(source),
    // Use the harmony branch of Esprima that installs with regenerator
    // instead of the master branch that recast provides.
    esprima: esprimaHarmony
  };

  var ast = recast.parse(source, options);
  return recast.print(transform(ast), options);
}

// To modify an AST directly, call require("regenerator").transform(ast).
regenerate.transform = transform;

regenerate.runtime = {
  dev: path.join(__dirname, "runtime", "dev.js"),
  min: path.join(__dirname, "runtime", "min.js")
};

// To transform a string of ES6 code, call require("regenerator")(source);
module.exports = regenerate;


Add TextEncoder polyfill for test run

Add TextEncoder polyfill for test run

--- test/setupTests.js
+++ test/setupTests.js
@@ -1,6 +1,12 @@
 import * as languageHandler from "../src/languageHandler";
+import { TextEncoder, TextDecoder } from 'util';

 languageHandler.setLanguage('en');
 languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);

 require('jest-fetch-mock').enableMocks();
+
+// polyfilling TextEncoder as it is not available on JSDOM
+// view https://github.com/facebook/jest/issues/9983
+global.TextEncoder = TextEncoder;
+global.TextDecoder = TextDecoder;

<|original_code|>
import * as languageHandler from "../src/languageHandler";

languageHandler.setLanguage('en');
languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);

require('jest-fetch-mock').enableMocks();

<|edits_diff|>
--- test/setupTests.js
+++ test/setupTests.js
@@ -1,4 +1,5 @@
 import * as languageHandler from "../src/languageHandler";
+import { TextEncoder, TextDecoder } from 'util';

 languageHandler.setLanguage('en');
 languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);
<|current_version|>
import * as languageHandler from "../src/languageHandler";
import { TextEncoder, TextDecoder } from 'util';

languageHandler.setLanguage('en');
languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);

require('jest-fetch-mock').enableMocks();

<|next_version|>
import * as languageHandler from "../src/languageHandler";
import { TextEncoder, TextDecoder } from 'util';

languageHandler.setLanguage('en');
languageHandler.setMissingEntryGenerator(key => key.split("|", 2)[1]);

require('jest-fetch-mock').enableMocks();

// polyfilling TextEncoder as it is not available on JSDOM
// view https://github.com/facebook/jest/issues/9983
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;


Add redirect to details page after creating question

--- frontend/src/components/Question/UpdateForm.js
+++ frontend/src/components/Question/UpdateForm.js
@@ -3,6 +3,7 @@
 import QuestionForm from './Form';
 import { formValuesToRequest, responseToFormValues } from './transforms';
 import QuestionDetailsConnector from './DetailsConnector';
+import Router from 'next/router';

 export const createSubmitHandler = (question, updateQuestion) => (values, addHandlers) => {
   console.log('UPDATE VALUES: ');
@@ -16,6 +17,7 @@
         console.log('UpdateForm addHandlers OK:');
         console.log(resp);
         // this.props.showNotification();
+        Router.push(`/admin/questao?id=${question.id}`);
       })
       .catch(error => {
         // The component is and should not be aware of this being a GraphQL error.

<|original_code|>
import React from 'react';
import PropTypes from 'prop-types';
import QuestionForm from './Form';
import { formValuesToRequest, responseToFormValues } from './transforms';
import QuestionDetailsConnector from './DetailsConnector';

export const createSubmitHandler = (question, updateQuestion) => (values, addHandlers) => {
  console.log('UPDATE VALUES: ');
  console.log(values);
  // This is where `addHandlers` comes in handy as the form controls its state
  addHandlers(
    updateQuestion({
      variables: { input: { id: question.id, patch: formValuesToRequest(values) } },
    })
      .then(resp => {
        console.log('UpdateForm addHandlers OK:');
        console.log(resp);
        // this.props.showNotification();
      })
      .catch(error => {
        // The component is and should not be aware of this being a GraphQL error.
        console.log('UpdateForm addHandlers ERROR:');
        console.log(error);
        // this.props.showApiErrorNotification(error);
      }),
  );
};

const QuestionUpdateForm = ({ id }) => (
  <QuestionDetailsConnector id={id}>
    {({ isLoading, question, updateQuestion }) => (
      <QuestionForm
        initialValues={responseToFormValues(question)}
        onSubmit={createSubmitHandler(question, updateQuestion)}
      />
    )}
  </QuestionDetailsConnector>
);

QuestionUpdateForm.propTypes = {
  id: PropTypes.string.isRequired,
};

export default QuestionUpdateForm;

<|edits_diff|>
--- frontend/src/components/Question/UpdateForm.js
+++ frontend/src/components/Question/UpdateForm.js
@@ -3,6 +3,7 @@
 import QuestionForm from './Form';
 import { formValuesToRequest, responseToFormValues } from './transforms';
 import QuestionDetailsConnector from './DetailsConnector';
+import Router from 'next/router';

 export const createSubmitHandler = (question, updateQuestion) => (values, addHandlers) => {
   console.log('UPDATE VALUES: ');
<|current_version|>
import React from 'react';
import PropTypes from 'prop-types';
import QuestionForm from './Form';
import { formValuesToRequest, responseToFormValues } from './transforms';
import QuestionDetailsConnector from './DetailsConnector';
import Router from 'next/router';

export const createSubmitHandler = (question, updateQuestion) => (values, addHandlers) => {
  console.log('UPDATE VALUES: ');
  console.log(values);
  // This is where `addHandlers` comes in handy as the form controls its state
  addHandlers(
    updateQuestion({
      variables: { input: { id: question.id, patch: formValuesToRequest(values) } },
    })
      .then(resp => {
        console.log('UpdateForm addHandlers OK:');
        console.log(resp);
        // this.props.showNotification();
      })
      .catch(error => {
        // The component is and should not be aware of this being a GraphQL error.
        console.log('UpdateForm addHandlers ERROR:');
        console.log(error);
        // this.props.showApiErrorNotification(error);
      }),
  );
};

const QuestionUpdateForm = ({ id }) => (
  <QuestionDetailsConnector id={id}>
    {({ isLoading, question, updateQuestion }) => (
      <QuestionForm
        initialValues={responseToFormValues(question)}
        onSubmit={createSubmitHandler(question, updateQuestion)}
      />
    )}
  </QuestionDetailsConnector>
);

QuestionUpdateForm.propTypes = {
  id: PropTypes.string.isRequired,
};

export default QuestionUpdateForm;

<|next_version|>
import React from 'react';
import PropTypes from 'prop-types';
import QuestionForm from './Form';
import { formValuesToRequest, responseToFormValues } from './transforms';
import QuestionDetailsConnector from './DetailsConnector';
import Router from 'next/router';

export const createSubmitHandler = (question, updateQuestion) => (values, addHandlers) => {
  console.log('UPDATE VALUES: ');
  console.log(values);
  // This is where `addHandlers` comes in handy as the form controls its state
  addHandlers(
    updateQuestion({
      variables: { input: { id: question.id, patch: formValuesToRequest(values) } },
    })
      .then(resp => {
        console.log('UpdateForm addHandlers OK:');
        console.log(resp);
        // this.props.showNotification();
        Router.push(`/admin/questao?id=${question.id}`);
      })
      .catch(error => {
        // The component is and should not be aware of this being a GraphQL error.
        console.log('UpdateForm addHandlers ERROR:');
        console.log(error);
        // this.props.showApiErrorNotification(error);
      }),
  );
};

const QuestionUpdateForm = ({ id }) => (
  <QuestionDetailsConnector id={id}>
    {({ isLoading, question, updateQuestion }) => (
      <QuestionForm
        initialValues={responseToFormValues(question)}
        onSubmit={createSubmitHandler(question, updateQuestion)}
      />
    )}
  </QuestionDetailsConnector>
);

QuestionUpdateForm.propTypes = {
  id: PropTypes.string.isRequired,
};

export default QuestionUpdateForm;


Create form: prevent refresh, clean forms after enter.

--- client/templates/bets/create.js
+++ client/templates/bets/create.js
@@ -9,6 +9,8 @@

 Template.createBetForm.events({
   "submit .create-bet" : function(event){
+    event.preventDefault();
+
     var status = "open",
         title = event.target.betTitle.value;
         wager = event.target.betWager.value;
@@ -23,6 +25,10 @@
       wager: wager
     });

+    event.target.betTitle.value = '';
+    event.target.betWager.value = '';
+    event.target.defender.value = '';
+
     createBetNotification(bet);
   }
 });

<|original_code|>
var createBetNotification = function(bet){
  var bet = Bets.findOne({ _id: bet });

  BetNotifications.insert({
    toNotify: bet.bettors[1],
    betBy: bet.bettors[0]
  });
}

Template.createBetForm.events({
  "submit .create-bet" : function(event){
    var status = "open",
        title = event.target.betTitle.value;
        wager = event.target.betWager.value;
        user = Meteor.user(),
        defender_requested = event.target.defender.value;
        defender = Meteor.users.findOne({ username: defender_requested });

    var bet = Bets.insert({
      bettors: [ user.username, defender.username ],
      status: status,
      title: title,
      wager: wager
    });

    createBetNotification(bet);
  }
});

<|edits_diff|>
--- client/templates/bets/create.js
+++ client/templates/bets/create.js
@@ -9,6 +9,8 @@

 Template.createBetForm.events({
   "submit .create-bet" : function(event){
+    event.preventDefault();
+
     var status = "open",
         title = event.target.betTitle.value;
         wager = event.target.betWager.value;
<|current_version|>
var createBetNotification = function(bet){
  var bet = Bets.findOne({ _id: bet });

  BetNotifications.insert({
    toNotify: bet.bettors[1],
    betBy: bet.bettors[0]
  });
}

Template.createBetForm.events({
  "submit .create-bet" : function(event){
    event.preventDefault();

    var status = "open",
        title = event.target.betTitle.value;
        wager = event.target.betWager.value;
        user = Meteor.user(),
        defender_requested = event.target.defender.value;
        defender = Meteor.users.findOne({ username: defender_requested });

    var bet = Bets.insert({
      bettors: [ user.username, defender.username ],
      status: status,
      title: title,
      wager: wager
    });

    createBetNotification(bet);
  }
});

<|next_version|>
var createBetNotification = function(bet){
  var bet = Bets.findOne({ _id: bet });

  BetNotifications.insert({
    toNotify: bet.bettors[1],
    betBy: bet.bettors[0]
  });
}

Template.createBetForm.events({
  "submit .create-bet" : function(event){
    event.preventDefault();

    var status = "open",
        title = event.target.betTitle.value;
        wager = event.target.betWager.value;
        user = Meteor.user(),
        defender_requested = event.target.defender.value;
        defender = Meteor.users.findOne({ username: defender_requested });

    var bet = Bets.insert({
      bettors: [ user.username, defender.username ],
      status: status,
      title: title,
      wager: wager
    });

    event.target.betTitle.value = '';
    event.target.betWager.value = '';
    event.target.defender.value = '';

    createBetNotification(bet);
  }
});


import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return <div style={{color: 'orange'}}>
    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <FacetPanel title='My awesome facets'/>
  </div>;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;

import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'
import ResultPanel from '../../components/results';

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return <div style={{color: 'orange'}}>
    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <ResultPanel />
    <FacetPanel title='My awesome facets'/>
  </div>;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;

Update the example to use results.

[example] Update the example to use results.

--- src/example/views/home.js
+++ src/example/views/home.js
@@ -6,6 +6,7 @@
 import SearchComponent from './searchComponent'
 import OtherSearchComponent from './otherSearchComponent'
 import SearchWithComponent from './searchWithComponent'
+import ResultPanel from '../../components/results';

 import FacetPanel from '../../components/facet';

@@ -14,6 +15,7 @@
     {/*<SearchComponent/>*/}
     {/*<OtherSearchComponent/>*/}
     {/*<SearchWithComponent/>*/}
+    <ResultPanel />
     <FacetPanel title='My awesome facets'/>
   </div>;
 }

import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'
import ResultPanel from '../../components/results';

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return <div style={{color: 'orange'}}>
    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <FacetPanel title='My awesome facets'/>
  </div>;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;

<|original_code|>
import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return

    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <FacetPanel title='My awesome facets'/>

;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;

<|edits_diff|>
--- src/example/views/home.js
+++ src/example/views/home.js
@@ -6,6 +6,7 @@
 import SearchComponent from './searchComponent'
 import OtherSearchComponent from './otherSearchComponent'
 import SearchWithComponent from './searchWithComponent'
+import ResultPanel from '../../components/results';

 import FacetPanel from '../../components/facet';

<|current_version|>
import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'
import ResultPanel from '../../components/results';

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return

    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <FacetPanel title='My awesome facets'/>

;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;

<|next_version|>
import {connect as connectToState} from 'react-redux';
import compose from 'lodash/flowRight';
import Button from './components/button';
import React, {Component, PropTypes} from 'react';
import map from 'lodash/map';
import SearchComponent from './searchComponent'
import OtherSearchComponent from './otherSearchComponent'
import SearchWithComponent from './searchWithComponent'
import ResultPanel from '../../components/results';

import FacetPanel from '../../components/facet';

const Home = () =>  {
  return

    {/*<SearchComponent/>*/}
    {/*<OtherSearchComponent/>*/}
    {/*<SearchWithComponent/>*/}
    <ResultPanel />
    <FacetPanel title='My awesome facets'/>

;
}

const ConnectedComponentHome = compose(
  connectToState(s => ({reduxState: s}))
)(Home)
export default ConnectedComponentHome;


Make localStream visible on step-01

Make localStream visible on step-01

--- step-01/js/main.js
+++ step-01/js/main.js
@@ -8,8 +8,12 @@
 // Video element where stream will be placed.
 const localVideo = document.querySelector('video');

+// Local stream that will be reproduced on the video.
+let localStream;
+
 // Handles success by adding the MediaStream to the video element.
 function gotLocalMediaStream(mediaStream) {
+  localStream = mediaStream;
   localVideo.srcObject = mediaStream;
 }

<|original_code|>
'use strict';

// On this codelab, you will be streaming only video (video: true).
const mediaStreamConstraints = {
  video: true,
};

// Video element where stream will be placed.
const localVideo = document.querySelector('video');

// Handles success by adding the MediaStream to the video element.
function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

// Handles error by logging a message to the console with the error message.
function handleLocalMediaStreamError(error) {
  console.log('navigator.getUserMedia error: ', error);
}

// Initializes media stream.
navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);

<|edits_diff|>
--- step-01/js/main.js
+++ step-01/js/main.js
@@ -7,6 +7,9 @@

 // Video element where stream will be placed.
 const localVideo = document.querySelector('video');
+
+// Local stream that will be reproduced on the video.
+let localStream;

 // Handles success by adding the MediaStream to the video element.
 function gotLocalMediaStream(mediaStream) {
<|current_version|>
'use strict';

// On this codelab, you will be streaming only video (video: true).
const mediaStreamConstraints = {
  video: true,
};

// Video element where stream will be placed.
const localVideo = document.querySelector('video');

// Local stream that will be reproduced on the video.
let localStream;

// Handles success by adding the MediaStream to the video element.
function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

// Handles error by logging a message to the console with the error message.
function handleLocalMediaStreamError(error) {
  console.log('navigator.getUserMedia error: ', error);
}

// Initializes media stream.
navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);

<|next_version|>
'use strict';

// On this codelab, you will be streaming only video (video: true).
const mediaStreamConstraints = {
  video: true,
};

// Video element where stream will be placed.
const localVideo = document.querySelector('video');

// Local stream that will be reproduced on the video.
let localStream;

// Handles success by adding the MediaStream to the video element.
function gotLocalMediaStream(mediaStream) {
  localStream = mediaStream;
  localVideo.srcObject = mediaStream;
}

// Handles error by logging a message to the console with the error message.
function handleLocalMediaStreamError(error) {
  console.log('navigator.getUserMedia error: ', error);
}

// Initializes media stream.
navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);


Fix req stream race condition due to middleware

--- lib/cb.middleware/main.js
+++ lib/cb.middleware/main.js
@@ -17,6 +17,9 @@
     }));
     // Get User and set it to res object
     app.use(function getUser(req, res, next) {
+        // Pause request stream
+        req.pause();
+
         var uid = req.session.userId;
         if(uid) {
             return workspace.getUser(uid)
@@ -36,6 +39,10 @@
     // Block queries for unAuthenticated users
     var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
     app.use(function filterAuth(req, res, next) {
+        // Resume request now
+        // So our handlers can use it as a stream
+        req.resume();
+
         if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
             return next();
         }

<|original_code|>
// Requires
var _ = require('underscore');

var express = require('express');

function setup(options, imports, register) {
    // Import
    var app = imports.server.app;
    var workspace = imports.workspace;

    // Apply middlewares
    app.use(express.cookieParser());
    app.use(express.cookieSession({
        key: ['sess', workspace.id].join('.'),
        secret: workspace.secret,
    }));
    // Get User and set it to res object
    app.use(function getUser(req, res, next) {
        var uid = req.session.userId;
        if(uid) {
            return workspace.getUser(uid)
            .then(function(user) {
                // Set user
                res.user = user;
                next();
            })
            .fail(function(err) {
                res.user = null;
                next();
            });
        }
        return next();

    });
    // Block queries for unAuthenticated users
    var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
    app.use(function filterAuth(req, res, next) {
        if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
            return next();
        }
        // Unauthorized
        return res.send(403, {
            ok: false,
            data: {},
            error: "Could not run RPC request because user has not authenticated",
            method: req.path,
        });
    });

    // Register
    register(null, {});
}

// Exports
module.exports = setup;

<|edits_diff|>
--- lib/cb.middleware/main.js
+++ lib/cb.middleware/main.js
@@ -17,6 +17,9 @@
     }));
     // Get User and set it to res object
     app.use(function getUser(req, res, next) {
+        // Pause request stream
+        req.pause();
+
         var uid = req.session.userId;
         if(uid) {
             return workspace.getUser(uid)
<|current_version|>
// Requires
var _ = require('underscore');

var express = require('express');

function setup(options, imports, register) {
    // Import
    var app = imports.server.app;
    var workspace = imports.workspace;

    // Apply middlewares
    app.use(express.cookieParser());
    app.use(express.cookieSession({
        key: ['sess', workspace.id].join('.'),
        secret: workspace.secret,
    }));
    // Get User and set it to res object
    app.use(function getUser(req, res, next) {
        // Pause request stream
        req.pause();

        var uid = req.session.userId;
        if(uid) {
            return workspace.getUser(uid)
            .then(function(user) {
                // Set user
                res.user = user;
                next();
            })
            .fail(function(err) {
                res.user = null;
                next();
            });
        }
        return next();

    });
    // Block queries for unAuthenticated users
    var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
    app.use(function filterAuth(req, res, next) {
        if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
            return next();
        }
        // Unauthorized
        return res.send(403, {
            ok: false,
            data: {},
            error: "Could not run RPC request because user has not authenticated",
            method: req.path,
        });
    });

    // Register
    register(null, {});
}

// Exports
module.exports = setup;

<|next_version|>
// Requires
var _ = require('underscore');

var express = require('express');

function setup(options, imports, register) {
    // Import
    var app = imports.server.app;
    var workspace = imports.workspace;

    // Apply middlewares
    app.use(express.cookieParser());
    app.use(express.cookieSession({
        key: ['sess', workspace.id].join('.'),
        secret: workspace.secret,
    }));
    // Get User and set it to res object
    app.use(function getUser(req, res, next) {
        // Pause request stream
        req.pause();

        var uid = req.session.userId;
        if(uid) {
            return workspace.getUser(uid)
            .then(function(user) {
                // Set user
                res.user = user;
                next();
            })
            .fail(function(err) {
                res.user = null;
                next();
            });
        }
        return next();

    });
    // Block queries for unAuthenticated users
    var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
    app.use(function filterAuth(req, res, next) {
        // Resume request now
        // So our handlers can use it as a stream
        req.resume();

        if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
            return next();
        }
        // Unauthorized
        return res.send(403, {
            ok: false,
            data: {},
            error: "Could not run RPC request because user has not authenticated",
            method: req.path,
        });
    });

    // Register
    register(null, {});
}

// Exports
module.exports = setup;


Configure VuewJS to use Material Design.

--- web/src/main.js
+++ web/src/main.js
@@ -1,10 +1,17 @@
 // The Vue build version to load with the `import` command
 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
+
+import VueMaterial from 'vue-material';
+import 'vue-material/dist/vue-material.min.css';
+import 'vue-material/dist/theme/default-dark.css';
+
 import Vue from 'vue';
 import App from './App';
 import router from './router';

 Vue.config.productionTip = false;
+
+Vue.use(VueMaterial);

 /* eslint-disable no-new */
 new Vue({

<|original_code|>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
});

<|edits_diff|>
--- web/src/main.js
+++ web/src/main.js
@@ -1,5 +1,10 @@
 // The Vue build version to load with the `import` command
 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
+
+import VueMaterial from 'vue-material';
+import 'vue-material/dist/vue-material.min.css';
+import 'vue-material/dist/theme/default-dark.css';
+
 import Vue from 'vue';
 import App from './App';
 import router from './router';
<|current_version|>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import VueMaterial from 'vue-material';
import 'vue-material/dist/vue-material.min.css';
import 'vue-material/dist/theme/default-dark.css';

import Vue from 'vue';
import App from './App';
import router from './router';

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
});

<|next_version|>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import VueMaterial from 'vue-material';
import 'vue-material/dist/vue-material.min.css';
import 'vue-material/dist/theme/default-dark.css';

import Vue from 'vue';
import App from './App';
import router from './router';

Vue.config.productionTip = false;

Vue.use(VueMaterial);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
});


Fix jshint to also check the files in bin/.

--- Gruntfile.js
+++ Gruntfile.js
@@ -10,6 +10,9 @@
 			gruntfile: {
 				src: 'Gruntfile.js'
 			},
+			bin: {
+				src: ['bin/*.js']
+			},
 			lib: {
 				src: ['lib/**/*.js']
 			},
@@ -19,6 +22,10 @@
 			gruntfile: {
 				files: '<%= jshint.gruntfile.src %>',
 				tasks: ['jshint:gruntfile']
+			},
+			bin: {
+				files: '<%= jshint.bin.src %>',
+				tasks: ['jshint:bin']
 			},
 			lib: {
 				files: '<%= jshint.lib.src %>',

<|original_code|>
'use strict';

module.exports = function(grunt) {

	grunt.initConfig({
		jshint: {
			options: {
				jshintrc: '.jshintrc'
			},
			gruntfile: {
				src: 'Gruntfile.js'
			},
			lib: {
				src: ['lib/**/*.js']
			},
		},

		watch: {
			gruntfile: {
				files: '<%= jshint.gruntfile.src %>',
				tasks: ['jshint:gruntfile']
			},
			lib: {
				files: '<%= jshint.lib.src %>',
				tasks: ['jshint:lib']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');

};

<|edits_diff|>
--- Gruntfile.js
+++ Gruntfile.js
@@ -9,6 +9,9 @@
 			},
 			gruntfile: {
 				src: 'Gruntfile.js'
+			},
+			bin: {
+				src: ['bin/*.js']
 			},
 			lib: {
 				src: ['lib/**/*.js']
<|current_version|>
'use strict';

module.exports = function(grunt) {

	grunt.initConfig({
		jshint: {
			options: {
				jshintrc: '.jshintrc'
			},
			gruntfile: {
				src: 'Gruntfile.js'
			},
			bin: {
				src: ['bin/*.js']
			},
			lib: {
				src: ['lib/**/*.js']
			},
		},

		watch: {
			gruntfile: {
				files: '<%= jshint.gruntfile.src %>',
				tasks: ['jshint:gruntfile']
			},
			lib: {
				files: '<%= jshint.lib.src %>',
				tasks: ['jshint:lib']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');

};

<|next_version|>
'use strict';

module.exports = function(grunt) {

	grunt.initConfig({
		jshint: {
			options: {
				jshintrc: '.jshintrc'
			},
			gruntfile: {
				src: 'Gruntfile.js'
			},
			bin: {
				src: ['bin/*.js']
			},
			lib: {
				src: ['lib/**/*.js']
			},
		},

		watch: {
			gruntfile: {
				files: '<%= jshint.gruntfile.src %>',
				tasks: ['jshint:gruntfile']
			},
			bin: {
				files: '<%= jshint.bin.src %>',
				tasks: ['jshint:bin']
			},
			lib: {
				files: '<%= jshint.lib.src %>',
				tasks: ['jshint:lib']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');

};


Clear out form field on submit.

Clear out form field on submit.

--- client/templates/query.js
+++ client/templates/query.js
@@ -8,14 +8,20 @@
 Template.addResponse.events({
     'click #submitResponse' : function (event) {
         event.preventDefault();
+
+        // Get the values for the response
         var response = $('#yourResponse').val();
         var authorId = Meteor.userId();
         var queryId = Session.get('queryId');

+        // Insert the response into the database
         Responses.insert({
             authorId: authorId,
             response: response,
             queryId: queryId
         });
+
+        // Reset the form field value to blank
+        $('#yourResponse').val('');
     }
 });

<|original_code|>
Template.showResponses.helpers({
    'responses' : function () {
        Session.set('queryId', this._id);
        return Responses.find({queryId: this._id});
    }
});

Template.addResponse.events({
    'click #submitResponse' : function (event) {
        event.preventDefault();
        var response = $('#yourResponse').val();
        var authorId = Meteor.userId();
        var queryId = Session.get('queryId');

        Responses.insert({
            authorId: authorId,
            response: response,
            queryId: queryId
        });
    }
});

<|edits_diff|>
--- client/templates/query.js
+++ client/templates/query.js
@@ -8,10 +8,13 @@
 Template.addResponse.events({
     'click #submitResponse' : function (event) {
         event.preventDefault();
+
+        // Get the values for the response
         var response = $('#yourResponse').val();
         var authorId = Meteor.userId();
         var queryId = Session.get('queryId');

+        // Insert the response into the database
         Responses.insert({
             authorId: authorId,
             response: response,
<|current_version|>
Template.showResponses.helpers({
    'responses' : function () {
        Session.set('queryId', this._id);
        return Responses.find({queryId: this._id});
    }
});

Template.addResponse.events({
    'click #submitResponse' : function (event) {
        event.preventDefault();

        // Get the values for the response
        var response = $('#yourResponse').val();
        var authorId = Meteor.userId();
        var queryId = Session.get('queryId');

        // Insert the response into the database
        Responses.insert({
            authorId: authorId,
            response: response,
            queryId: queryId
        });
    }
});

<|next_version|>
Template.showResponses.helpers({
    'responses' : function () {
        Session.set('queryId', this._id);
        return Responses.find({queryId: this._id});
    }
});

Template.addResponse.events({
    'click #submitResponse' : function (event) {
        event.preventDefault();

        // Get the values for the response
        var response = $('#yourResponse').val();
        var authorId = Meteor.userId();
        var queryId = Session.get('queryId');

        // Insert the response into the database
        Responses.insert({
            authorId: authorId,
            response: response,
            queryId: queryId
        });

        // Reset the form field value to blank
        $('#yourResponse').val('');
    }
});