<commit_before>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

(function () {

  ko.HUE_CHARTS = {
    TYPES: {
      LINECHART: 'lines',
      BARCHART: 'bars',
      TIMELINECHART: 'timeline',
      POINTCHART: 'points',
      PIECHART: 'pie',
      MAP: 'map',
      GRADIENTMAP: 'gradientmap',
      SCATTERCHART: 'scatter'
    }
  };

  var PLOTLY_COMMON_LAYOUT = {
    height: 400
  };

  var PLOTLY_COMMON_OPTIONS = {
    displaylogo: false,
    modeBarButtonsToRemove: ['sendDataToCloud', 'hoverCompareCartesian']
  }

  function resizeHandlers(element) {
    var resizeSubscription = huePubSub.subscribe('resize.plotly.chart', function () {
      Plotly.Plots.resize(element);
    });
    var resizeEvent = function () {
      Plotly.Plots.resize(element);
    };

    $(window).on('resize', resizeEvent);
    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
      resizeSubscription.remove();
      $(window).off('resize', resizeEvent);
    });
  }

  ko.bindingHandlers.pieChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.data);
        var chartData = {
          values: [],
          labels: [],
          type: 'pie'
        }
        data.forEach(function (el) {
          chartData.values.push(el.value);
          chartData.labels.push(el.label);
        });
        Plotly.newPlot(element, [chartData], PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.barChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.datum);
        var chartData = [];
        data.forEach(function (el) {
          var chartSerie = {
            x: [],
            y: [],
            name: el.key,
            type: 'bar'
          }
          el.values.forEach(function (serie) {
            chartSerie.x.push(serie.x);
            chartSerie.y.push(serie.y);
          });
          chartData.push(chartSerie)
        });
        Plotly.newPlot(element, chartData, PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.timelineChart = {
    init: function (element, valueAccessor) {
      $(element).html('To-do.');
    },
    update: function (element, valueAccessor) {
      $(element).html('To-do.');
    }
  };

  ko.bindingHandlers.lineChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.datum);
        var chartData = [];
        data.forEach(function (el) {
          var chartSerie = {
            x: [],
            y: [],
            name: el.key,
            type: 'scatter'
          }
          el.values.forEach(function (serie) {
            chartSerie.x.push(serie.x);
            chartSerie.y.push(serie.y);
          });
          chartData.push(chartSerie)
        });
        Plotly.newPlot(element, chartData, PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.mapChart = {
    init: function (element, valueAccessor) {
      $(element).html('To-do.');
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
      $(element).html('To-do.');
    }
  };

  ko.bindingHandlers.scatterChart = {
    update: function (element, valueAccessor) {
      $(element).html('To-do.');
    }
  };

  ko.bindingHandlers.partitionChart = {
    init: function (element, valueAccessor) {
      $(element).html('To-do.');
    },
    update: function (element, valueAccessor) {
      $(element).html('To-do.');
    }
  };

  window.chartsUpdatingState = function(){};
  window.chartsNormalState = function(){};

})();<commit_msg>HUE-7453 [frontend] Create basic timeline chart port<commit_after>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

(function () {

  ko.HUE_CHARTS = {
    TYPES: {
      LINECHART: 'lines',
      BARCHART: 'bars',
      TIMELINECHART: 'timeline',
      POINTCHART: 'points',
      PIECHART: 'pie',
      MAP: 'map',
      GRADIENTMAP: 'gradientmap',
      SCATTERCHART: 'scatter'
    }
  };

  var PLOTLY_COMMON_LAYOUT = {
    height: 400
  };

  var PLOTLY_COMMON_OPTIONS = {
    displaylogo: false,
    modeBarButtonsToRemove: ['sendDataToCloud', 'hoverCompareCartesian']
  }

  function resizeHandlers(element) {
    var resizeSubscription = huePubSub.subscribe('resize.plotly.chart', function () {
      Plotly.Plots.resize(element);
    });
    var resizeEvent = function () {
      Plotly.Plots.resize(element);
    };

    $(window).on('resize', resizeEvent);
    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
      resizeSubscription.remove();
      $(window).off('resize', resizeEvent);
    });
  }

  ko.bindingHandlers.pieChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.data);
        var chartData = {
          values: [],
          labels: [],
          type: 'pie'
        }
        data.forEach(function (el) {
          chartData.values.push(el.value);
          chartData.labels.push(el.label);
        });
        Plotly.newPlot(element, [chartData], PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.barChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.datum);
        var chartData = [];
        data.forEach(function (el) {
          var chartSerie = {
            x: [],
            y: [],
            name: el.key,
            type: 'bar'
          }
          el.values.forEach(function (serie) {
            chartSerie.x.push(serie.x);
            chartSerie.y.push(serie.y);
          });
          chartData.push(chartSerie)
        });
        Plotly.newPlot(element, chartData, PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.timelineChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.datum);
        var chartData = [];
        data.forEach(function (el) {
          var chartSerie = {
            x: [],
            y: [],
            name: el.key,
            type: 'scatter'
          }
          el.values.forEach(function (serie) {
            chartSerie.x.push(serie.x);
            chartSerie.y.push(serie.y);
          });
          chartData.push(chartSerie)
        });
        Plotly.newPlot(element, chartData, PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.lineChart = {
    init: function (element, valueAccessor) {
      resizeHandlers(element);
    },
    update: function (element, valueAccessor) {
      var options = valueAccessor();
      window.clearTimeout(element.plotterTimeout);
      element.plotterTimeout = window.setTimeout(function () {
        var data = options.transformer(options.datum);
        var chartData = [];
        data.forEach(function (el) {
          var chartSerie = {
            x: [],
            y: [],
            name: el.key,
            type: 'scatter'
          }
          el.values.forEach(function (serie) {
            chartSerie.x.push(serie.x);
            chartSerie.y.push(serie.y);
          });
          chartData.push(chartSerie)
        });
        Plotly.newPlot(element, chartData, PLOTLY_COMMON_LAYOUT, PLOTLY_COMMON_OPTIONS);
      }, 200);
    }
  };

  ko.bindingHandlers.mapChart = {
    init: function (element, valueAccessor) {
      $(element).html('To-do.');
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
      $(element).html('To-do.');
    }
  };

  ko.bindingHandlers.scatterChart = {
    update: function (element, valueAccessor) {
      $(element).html('To-do.');
    }
  };

  ko.bindingHandlers.partitionChart = {
    init: function (element, valueAccessor) {
      $(element).html('To-do.');
    },
    update: function (element, valueAccessor) {
      $(element).html('To-do.');
    }
  };

  window.chartsUpdatingState = function(){};
  window.chartsNormalState = function(){};

})();<|endoftext|>


<commit_before>describe('Charts', function () {

  describe('Chart(), Flow(), Basic()', function () {

    it('throws a "Missing constructor parameters" if the data parameter is missing',() => {
      assert.throws(() => {
        new Chart()
      }, Error);

      assert.throws(() => {
        new Basic()
      }, Error);

      assert.throws(() => {
        new Flow()
      }, Error);

      assert.throws(() => {
        new Chart()
      }, Error);
    });

  });
});<commit_msg>Remove old file test<commit_after><|endoftext|>


<commit_before>import Spawn from 'cross-spawn';

/**
 * Select the key of the value to be replaced from "process.env".
 *
 * @return {Array.<String>} Keys.
 */
export function FilterKeys() {
  return Object
  .keys( process.env )
  .filter( ( key ) => {
    return (
      key && typeof key === 'string' &&
      ( key.indexOf( 'npm_package_' ) !== -1 || key.indexOf( 'npm_config_' ) !== -1 )
    );
  } )
  .sort( ( a, b ) => {
    // Processing the variables with the same prefix in the correct order.
    // "npm_package_config_NAME_NAME2" contained in "npm_package_config_NAME"
    // is in descending order by the length to prevent from being replace earlier.
    //
    return ( b.length - a.length );
  } );
}

/**
 * Replace the arguments in the value of "process.env".
 *
 * @param {Array.<Object>} argv Arguments of the command line.
 * @param {Array.<Object>} argv The filtered key ( "npm_package_" or "npm_config_" ) of "process.env".
 *
 * @return {Array.<String>} Augments.
 */
export function ReplaceArgv( argv, keys ) {
  if( keys.length === 0 ) { return argv; }

  return argv.map( ( arg ) => {
    let newArg = arg;
    keys.forEach( ( key ) => {
      const pettern = '%' + key + '%|\\$' + key + '|' + key;
      const regexp  = new RegExp( pettern );
      if( regexp.test( newArg ) ) {
        newArg = newArg.replace( regexp, String( process.env[ key ] ) );
      }
    } );

    return newArg;
  } );
}

/**
 * Replace the value of the command line arguments in process.env,
 * and run the process with a replaced arguments.
 *
 * @param {Array.<Object>} argv Arguments of the command line.
 *
 * @return {Object} Process.
 */
export default function CrossConfEnv( argv ) {
  const newArgv = ReplaceArgv( argv, FilterKeys() );
  if( !( newArgv && 0 < newArgv.length ) ) { return process.exit(); }

  const command = newArgv.shift();
  const proc    = Spawn( command, newArgv, { stdio: 'inherit' } );

  proc.on( 'exit', process.exit );

  return proc;
}
<commit_msg>Fix a ESDoc<commit_after>import Spawn from 'cross-spawn';

/**
 * Select the key of the value to be replaced from "process.env".
 *
 * @return {Array.<String>} Keys.
 */
export function FilterKeys() {
  return Object
  .keys( process.env )
  .filter( ( key ) => {
    return (
      key && typeof key === 'string' &&
      ( key.indexOf( 'npm_package_' ) !== -1 || key.indexOf( 'npm_config_' ) !== -1 )
    );
  } )
  .sort( ( a, b ) => {
    // Processing the variables with the same prefix in the correct order.
    // "npm_package_config_NAME_NAME2" contained in "npm_package_config_NAME"
    // is in descending order by the length to prevent from being replace earlier.
    //
    return ( b.length - a.length );
  } );
}

/**
 * Replace the arguments in the value of "process.env".
 *
 * @param {Array.<Object>} argv Arguments of the command line.
 * @param {Array.<Object>} keys The filtered key ( "npm_package_" or "npm_config_" ) of "process.env".
 *
 * @return {Array.<String>} Augments.
 */
export function ReplaceArgv( argv, keys ) {
  if( keys.length === 0 ) { return argv; }

  return argv.map( ( arg ) => {
    let newArg = arg;
    keys.forEach( ( key ) => {
      const pettern = '%' + key + '%|\\$' + key + '|' + key;
      const regexp  = new RegExp( pettern );
      if( regexp.test( newArg ) ) {
        newArg = newArg.replace( regexp, String( process.env[ key ] ) );
      }
    } );

    return newArg;
  } );
}

/**
 * Replace the value of the command line arguments in process.env,
 * and run the process with a replaced arguments.
 *
 * @param {Array.<Object>} argv Arguments of the command line.
 *
 * @return {Object} Process.
 */
export default function CrossConfEnv( argv ) {
  const newArgv = ReplaceArgv( argv, FilterKeys() );
  if( !( newArgv && 0 < newArgv.length ) ) { return process.exit(); }

  const command = newArgv.shift();
  const proc    = Spawn( command, newArgv, { stdio: 'inherit' } );

  proc.on( 'exit', process.exit );

  return proc;
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';

export default Ember.Component.extend({
    layout,
    store: Ember.inject.service(),
    licensesAvailable: Ember.A(),
    showBorder: true,
    showYear: true,
    showText: false,
    toggleText: true,
    showCopyrightHolders: true,
    showCategories: true,
    allowDismiss: false,
    showOtherFields: Ember.observer('nodeLicense', 'nodeLicense.text', function() {
        let text = this.get('nodeLicense.text');
        if (!text) {
            return;
        }
        this.set('showYear', text.indexOf('{{year}}') !== -1);
        this.set('showCopyrightHolders', text.indexOf('{{copyrightHolders}}') !== -1);
    }),
    yearRequired: Ember.computed('nodeLicense', function() {
        return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('year') !== -1;
    }),
    copyrightHoldersRequired: Ember.computed('nodeLicense', function() {
        return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('copyrightHolders') !== -1;
    }),
    didReceiveAttrs() {
        if (!this.get('licenses')) {
            this.get('store').query('license', { 'page[size]': 20 }).then(ret => {
                this.set('licensesAvailable', ret);
            });
        } else {
            this.set('licensesAvailable', this.get('licenses'));
        }
        if (!this.get('currentValues.year')) {
            let date = new Date();
            this.set('year', String(date.getUTCFullYear()));
        } else {
            this.set('year', this.get('currentValues.year'));
        }
        if (this.get('currentValues.copyrightHolders')) {
            this.set('copyrightHolders', this.get('currentValues.copyrightHolders'));
        }
    },
    _setNodeLicense: Ember.observer('licensesAvailable', 'currentValues.licenseType', function() {
        if (!this.get('currentValues.licenseType.id')) { //if not resolved properly
            this.set('nodeLicense', this.get('licensesAvailable.firstObject'));
        } else {
            this.set('nodeLicense', this.get('currentValues.licenseType'));
        }
    }),
    nodeLicenseText: Ember.computed('nodeLicense', 'nodeLicense.text', 'year', 'copyrightHolders', function() {
        let text = this.get('nodeLicense.text');
        if (text) {
            text = text.replace(/({{year}})/g, this.get('year') || '');
            text = text.replace(/({{copyrightHolders}})/g, this.get('copyrightHolders') || '');
        }
        return text;
    }),
    licenseEdited: Ember.observer('copyrightHolders', 'nodeLicense', 'year', function() {
        Ember.run.debounce(this, function() {
            if (this.get('autosave')) {
                this.get('actions.save').bind(this)();
            }
        }, 250);
    }),
    year: null,
    copyrightHolders: null,
    actions: {
        selectLicense(license) {
            this.set('nodeLicense', license);
        },
        toggleFullText() {
            this.set('showText', !this.get('showText'));
        },
        save() {
            let values = {
                licenseType: this.get('nodeLicense'),
                year: this.get('year'),
                copyrightHolders: this.get('copyrightHolders') ? this.get('copyrightHolders') : ''
            };
            this.attrs.editLicense(
                values,
                !((this.get('yearRequired') && !values.year) || (this.get('copyrightHoldersRequired') && values.copyrightHolders.length === 0))
            );
        },
        sendSubmit() {
            this.sendAction('pressSubmit');
        },
        dismiss() {
            this.attrs.dismiss();
        }
    }
});
<commit_msg>Use lodash's debounce instead of tying it to Ember's runloop<commit_after>import Ember from 'ember';
import _ from 'lodash/lodash';
import layout from './template';

export default Ember.Component.extend({
    layout,
    store: Ember.inject.service(),
    licensesAvailable: Ember.A(),
    showBorder: true,
    showYear: true,
    showText: false,
    toggleText: true,
    showCopyrightHolders: true,
    showCategories: true,
    allowDismiss: false,
    init() {
        this._super(...arguments);
        // Debouncing autosave prevents a request per keystroke, only sending it
        // when the user is done typing (trailing=true), debounce timer can be tweaked.
        this.set('debouncedAutosave', _.debounce(() => {
            if (this.get('autosave')) {
                this.get('actions.save').bind(this)();
            }
        }, 500, {trailing: true}));
    },
    showOtherFields: Ember.observer('nodeLicense', 'nodeLicense.text', function() {
        let text = this.get('nodeLicense.text');
        if (!text) {
            return;
        }
        this.set('showYear', text.indexOf('{{year}}') !== -1);
        this.set('showCopyrightHolders', text.indexOf('{{copyrightHolders}}') !== -1);
    }),
    yearRequired: Ember.computed('nodeLicense', function() {
        return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('year') !== -1;
    }),
    copyrightHoldersRequired: Ember.computed('nodeLicense', function() {
        return this.get('nodeLicense.requiredFields') && this.get('nodeLicense.requiredFields').indexOf('copyrightHolders') !== -1;
    }),
    didReceiveAttrs() {
        if (!this.get('licenses')) {
            this.get('store').query('license', { 'page[size]': 20 }).then(ret => {
                this.set('licensesAvailable', ret);
            });
        } else {
            this.set('licensesAvailable', this.get('licenses'));
        }
        if (!this.get('currentValues.year')) {
            let date = new Date();
            this.set('year', String(date.getUTCFullYear()));
        } else {
            this.set('year', this.get('currentValues.year'));
        }
        if (this.get('currentValues.copyrightHolders')) {
            this.set('copyrightHolders', this.get('currentValues.copyrightHolders'));
        }
    },
    _setNodeLicense: Ember.observer('licensesAvailable', 'currentValues.licenseType', function() {
        if (!this.get('currentValues.licenseType.id')) { //if not resolved properly
            this.set('nodeLicense', this.get('licensesAvailable.firstObject'));
        } else {
            this.set('nodeLicense', this.get('currentValues.licenseType'));
        }
    }),
    nodeLicenseText: Ember.computed('nodeLicense', 'nodeLicense.text', 'year', 'copyrightHolders', function() {
        let text = this.get('nodeLicense.text');
        if (text) {
            text = text.replace(/({{year}})/g, this.get('year') || '');
            text = text.replace(/({{copyrightHolders}})/g, this.get('copyrightHolders') || '');
        }
        return text;
    }),
    licenseEdited: Ember.observer('copyrightHolders', 'nodeLicense', 'year', function() {
        this.get('debouncedAutosave')();
    }),
    year: null,
    copyrightHolders: null,
    actions: {
        selectLicense(license) {
            this.set('nodeLicense', license);
        },
        toggleFullText() {
            this.set('showText', !this.get('showText'));
        },
        save() {
            let values = {
                licenseType: this.get('nodeLicense'),
                year: this.get('year'),
                copyrightHolders: this.get('copyrightHolders') ? this.get('copyrightHolders') : ''
            };
            this.attrs.editLicense(
                values,
                !((this.get('yearRequired') && !values.year) || (this.get('copyrightHoldersRequired') && values.copyrightHolders.length === 0))
            );
        },
        sendSubmit() {
            this.sendAction('pressSubmit');
        },
        dismiss() {
            this.attrs.dismiss();
        }
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/place-autocomplete-field';

const { Component, isEmpty, isPresent, typeOf, isEqual, run } = Ember;

export default Component.extend({
  layout: layout,
  disabled: false,
  inputClass: 'place-autocomplete--input',
  types: 'geocode',
  restrictions: {},
  tabindex: -1,
  withGeoLocate: false,

  // @see https://developers.google.com/maps/documentation/javascript/places-autocomplete#set_search_area
  geolocate() {
    let navigator = this.get('navigator') || window.navigator;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        let google = this.get('google') || window.google;
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        this.get('autocomplete').setBounds(circle.getBounds());
      });
    }
  },

  didInsertElement() {
    this._super(...arguments);
    run.scheduleOnce('afterRender', this, 'setupComponent');
  },

  setupComponent() {
    this.getAutocomplete();
    this.get('autocomplete').addListener('place_changed', this.placeChanged.bind(this));
    if (this.get("withGeoLocate")) {
      this.geolocate();
    }
  },

  willDestroy() {
    if (isPresent(this.get('autocomplete'))) {
      let google = this.get('google') || window.google;
      google.maps.event.clearInstanceListeners(this.get('autocomplete'));
    }
  },

  getAutocomplete() {
    if(isEmpty(this.get('autocomplete'))){
      let inputElement = document.getElementById(this.elementId).getElementsByTagName('input')[0],
          google = this.get('google') || window.google, //TODO: check how to use the inyected google object
          autocomplete = new google.maps.places.Autocomplete(inputElement, { types: this._typesToArray(), componentRestrictions: this.get('restrictions') });
      this.set('autocomplete', autocomplete);
    }
  },

  placeChanged() {
    let place =  this.get('autocomplete').getPlace();
    this._callCallback('placeChangedCallback', place);
    this.set('value', place.formatted_address);
  },

  _callCallback(callback, place) {
    let callbackFn = this.attrs[callback];
    if (isEqual(typeOf(callbackFn), 'function')) {
      callbackFn(place);
    } else {
      let actionName = this.get(callback);
      if (isPresent(this.get('handlerController')) && isPresent(actionName)) {
        this.get('handlerController').send(actionName, place);
      }
    }
  },

  _typesToArray() {
    if (this.get('types') !== "") {
      return this.get('types').split(',');
    } else {
      return [];
    }
  },

  actions: {
    focusOut() {
      this._callCallback('focusOutCallback');
    }
  }
});
<commit_msg>Fixes #35<commit_after>import Ember from 'ember';
import layout from '../templates/components/place-autocomplete-field';

const { Component, isEmpty, isPresent, typeOf, isEqual, run } = Ember;

export default Component.extend({
  layout: layout,
  disabled: false,
  inputClass: 'place-autocomplete--input',
  types: 'geocode',
  restrictions: {},
  tabindex: -1,
  withGeoLocate: false,

  // @see https://developers.google.com/maps/documentation/javascript/places-autocomplete#set_search_area
  geolocate() {
    let navigator = this.get('navigator') || ((window) ? window.navigator : null);
    if (navigator && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        let google = this.get('google') || window.google;
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        this.get('autocomplete').setBounds(circle.getBounds());
      });
    }
  },

  didInsertElement() {
    this._super(...arguments);
    run.scheduleOnce('afterRender', this, 'setupComponent');
  },

  setupComponent() {
    this.getAutocomplete();
    this.get('autocomplete').addListener('place_changed', this.placeChanged.bind(this));
    if (this.get("withGeoLocate")) {
      this.geolocate();
    }
  },

  willDestroy() {
    if (isPresent(this.get('autocomplete'))) {
      let google = this.get('google') || ((window) ? window.google : null);
      if(google){
        google.maps.event.clearInstanceListeners(this.get('autocomplete'));
      }
    }
  },

  getAutocomplete() {
    if(isEmpty(this.get('autocomplete'))){
      if(document && window){
        let inputElement = document.getElementById(this.elementId).getElementsByTagName('input')[0],
            google = this.get('google') || window.google, //TODO: check how to use the inyected google object
            autocomplete = new google.maps.places.Autocomplete(inputElement, { types: this._typesToArray(), componentRestrictions: this.get('restrictions') });
        this.set('autocomplete', autocomplete);
      }
    }
  },

  placeChanged() {
    let place =  this.get('autocomplete').getPlace();
    this._callCallback('placeChangedCallback', place);
    this.set('value', place.formatted_address);
  },

  _callCallback(callback, place) {
    let callbackFn = this.attrs[callback];
    if (isEqual(typeOf(callbackFn), 'function')) {
      callbackFn(place);
    } else {
      let actionName = this.get(callback);
      if (isPresent(this.get('handlerController')) && isPresent(actionName)) {
        this.get('handlerController').send(actionName, place);
      }
    }
  },

  _typesToArray() {
    if (this.get('types') !== "") {
      return this.get('types').split(',');
    } else {
      return [];
    }
  },

  actions: {
    focusOut() {
      this._callCallback('focusOutCallback');
    }
  }
});
<|endoftext|>


<commit_before>/**
 * Main module for analyze view
 * @param {type} $ jQuery module
 * @param {type} facebook Facebook Graph API module
 * @param {type} LastFMProxy LastFM API Wrapper module
 * @param {type} Aggregate Custom aggregation methods module
 * @returns {void}
 */
define (['jquery', 'facebook', 'LastFMProxy', 'StatsAnalyzer'], function ($, facebook, LastFMProxy, StatsAnalyzer) {

    // Stats object for every artist (associative array)
    var artistStats = [];

    // Number of artists liked by the user
    var artistCount = 0;

    // Number of artist already analyzed
    var analyzedArtistCount = 0;

    /**
     * Try to login and get an array of musicians
     * @param {type} callback
     * @returns {undefined}
     */
    function getArtists(callback) {
        FB.init({
            appId      : '1468034890110746',
            xfbml      : true,
            status     : true,
            cookie     : true,
            version    : 'v2.1'
        });

        // Try to login after init is complete
        FB.getLoginStatus(function(response){
            FB.login(function () {
                FB.api(
                    "/me/music?fields=likes,id,name, category",
                    function (response) {
                          var likes = response.data || [];
                          var artists = [];

                          // Filter by  category
                          likes.forEach(function (like) {
                              if(like.category === "Musician/band") {
                                  artists.push(like);
                              }
                          });

                          callback(artists);

                });
            }, {scope: 'user_likes'});
        });

    }

    /**
     * Show the modal window with a given text
     * @param {type} title Window title to show
     * @param {type} text Text to show
     * @param {function} callback
     * @returns {undefined}
     */
    function showModal (title, text, callback) {
        $('#modalTitle').text(title);
        $('#modalText').text(text);
        $('#myModal').modal('show');
        if (callback) {
            $('#modalOk').click(callback);
            $('#modalClose').click(callback);
        }
    }

    /**
     * Update progress bar as analyzedArtistCound increases
     * @returns {undefined}
     */
    function updateProgress () {
        analyzedArtistCount++;
        var percent = analyzedArtistCount / artistCount;
        var progress = percent*100;
        $('#appProgress').css('width', progress + '%');
    }

    /**
     *
     * @param {type} artist
     * @returns {undefined}
     */
    function artistCallback (artist) {
        var initialStatus = $('#initial-status').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function albumCallback (artist) {
         var initialStatus = $('#initial-status-album').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function fanCallback (artist) {
        var initialStatus = $('#initial-status-fan').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function tagCallback (artist) {
        var initialStatus = $('#initial-status-tag').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function similarCallback (artist) {
        var initialStatus = $('#initial-status-similar').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    // Get stats one by one recursively and call a callback when finished
    function getStats (artists, callback) {

        // Race end: empty array
        if (artists.length === 0) {
            callback();
            return;
        }

        // Pop an artist from array
        var artist = artists.pop();

        // Get stats for the popped artist and then continue
        console.log("id del artista:" + artist.id);
        LastFMProxy.getStats(artist.id, artist.name, artistCallback, albumCallback, fanCallback, tagCallback, similarCallback, function (stats) {
            updateProgress();
            artistStats[artist.name] = JSON.parse(stats);
            getStats(artists, callback);

        });
    }

    function showResults() {

        // Analyze the stats
        StatsAnalyzer.build(artistStats);

        // Get the results text
        var ageText = StatsAnalyzer.getAgeText();
        var epochText = StatsAnalyzer.getEpochText();
        var styleText = StatsAnalyzer.getStyleText();
        var similarText = StatsAnalyzer.getSimilarText();

        // Print the resutls
        $('#age_result').text(ageText);
        $('#epoch_result').text(epochText);
        $('#style_result').text(styleText);
        $('#similar_result').text(similarText);

        // Add sharing event handlers shareResult('prueba');
        $('#share_age').click(function () { shareResult(ageText); });
        $('#share_epoch').click(function () { shareResult(epochText); });
        $('#share_style').click(function () { shareResult(styleText); });
        $('#share_similar').click(function () { shareResult(similarText); });

        $('#process').hide();
        $('#results').removeClass('hidden');
        $('#results').animate({
            maxHeight: '1000px',
            opacity:1
        },{
            duration: 1000
        });

    }

    function selectTopRated (artists, n) {
        // Sort from more to less likes
        artists.sort(function (a, b) {
            return b.likes - a.likes;
        });
        return artists.splice(0,n);
    }

    function shareResult (message) {
        var wallPost = {
            method: 'feed',
            picture: $('#share-image').val(),
            link: 'https://apps.facebook.com/music-analyzer',
            name: message,
            caption: "music-analyzer.herokuapp.com",
            description: $('#description').val()
        };

        FB.ui(wallPost);
        /*
        FB.login(function(loginResponse) {
            if (!loginResponse || loginResponse.error) {
                // No permission
                console.log('Login error');
            } else {
                FB.api('/me/feed', 'post', wallPost , function(response) {
                    if (!response || response.error) {
                        console.log('Hubo un error');
                        console.log(response);
                    } else {
                        console.log('Posteado correctamente');
                    }
                });
            }
        }, {scope: 'publish_actions'});
        */
    }

    // DOM callbacks
    $(document).ready(function () {

        // Get user artists
        getArtists(function (artists) {

            var MAX_ARTISTS = 10;

            // If no artist likes show message
            if (artists.length === 0) {
                showModal($('#error-title').val(), $('#error-status').val(), function () {
                    document.location = '/';
                });
            }
            // If too much musicians
            if (artists.length > MAX_ARTISTS) {
                artists = selectTopRated(artists, MAX_ARTISTS);
            }

            artistCount = artists.length || 0;

            // Else get stats one by one
            getStats(artists, function () {
                showResults();
            });

        }); // Get user artists
    }); // End document ready
}); // End module<commit_msg>Debug artist insert 3<commit_after>/**
 * Main module for analyze view
 * @param {type} $ jQuery module
 * @param {type} facebook Facebook Graph API module
 * @param {type} LastFMProxy LastFM API Wrapper module
 * @param {type} Aggregate Custom aggregation methods module
 * @returns {void}
 */
define (['jquery', 'facebook', 'LastFMProxy', 'StatsAnalyzer'], function ($, facebook, LastFMProxy, StatsAnalyzer) {

    // Stats object for every artist (associative array)
    var artistStats = [];

    // Number of artists liked by the user
    var artistCount = 0;

    // Number of artist already analyzed
    var analyzedArtistCount = 0;

    /**
     * Try to login and get an array of musicians
     * @param {type} callback
     * @returns {undefined}
     */
    function getArtists(callback) {
        FB.init({
            appId      : '1468034890110746',
            xfbml      : true,
            status     : true,
            cookie     : true,
            version    : 'v2.1'
        });

        // Try to login after init is complete
        FB.getLoginStatus(function(response){
            FB.login(function () {
                FB.api(
                    "/me/music?fields=likes,id,name, category",
                    function (response) {
                          var likes = response.data || [];
                          var artists = [];

                          // Filter by  category
                          likes.forEach(function (like) {
                              if(like.category === "Musician/band") {
                                  artists.push(like);
                              }
                          });

                          callback(artists);

                });
            }, {scope: 'user_likes'});
        });

    }

    /**
     * Show the modal window with a given text
     * @param {type} title Window title to show
     * @param {type} text Text to show
     * @param {function} callback
     * @returns {undefined}
     */
    function showModal (title, text, callback) {
        $('#modalTitle').text(title);
        $('#modalText').text(text);
        $('#myModal').modal('show');
        if (callback) {
            $('#modalOk').click(callback);
            $('#modalClose').click(callback);
        }
    }

    /**
     * Update progress bar as analyzedArtistCound increases
     * @returns {undefined}
     */
    function updateProgress () {
        analyzedArtistCount++;
        var percent = analyzedArtistCount / artistCount;
        var progress = percent*100;
        $('#appProgress').css('width', progress + '%');
    }

    /**
     *
     * @param {type} artist
     * @returns {undefined}
     */
    function artistCallback (artist) {
        var initialStatus = $('#initial-status').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function albumCallback (artist) {
         var initialStatus = $('#initial-status-album').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function fanCallback (artist) {
        var initialStatus = $('#initial-status-fan').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function tagCallback (artist) {
        var initialStatus = $('#initial-status-tag').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    function similarCallback (artist) {
        var initialStatus = $('#initial-status-similar').val();
        $('#status').text(initialStatus + ' ' + artist + '...');
    }

    // Get stats one by one recursively and call a callback when finished
    function getStats (artists, callback) {

        // Race end: empty array
        if (artists.length === 0) {
            callback();
            return;
        }

        // Pop an artist from array
        var artist = artists.pop();

        // Get stats for the popped artist and then continue
        console.log("id del artista:" + artist.id);
        LastFMProxy.getStats(artist.id, artist.name, artistCallback, albumCallback, fanCallback, tagCallback, similarCallback, function (stats) {
            updateProgress();
            artistStats[artist.name] = JSON.parse(stats);
            getStats(artists, callback);

        });
    }

    function showResults() {

        // Analyze the stats
        StatsAnalyzer.build(artistStats);

        // Get the results text
        var ageText = StatsAnalyzer.getAgeText();
        var epochText = StatsAnalyzer.getEpochText();
        var styleText = StatsAnalyzer.getStyleText();
        var similarText = StatsAnalyzer.getSimilarText();

        // Print the resutls
        $('#age_result').text(ageText);
        $('#epoch_result').text(epochText);
        $('#style_result').text(styleText);
        $('#similar_result').text(similarText);

        // Add sharing event handlers shareResult('prueba');
        $('#share_age').click(function () { shareResult(ageText); });
        $('#share_epoch').click(function () { shareResult(epochText); });
        $('#share_style').click(function () { shareResult(styleText); });
        $('#share_similar').click(function () { shareResult(similarText); });

        $('#process').hide();
        $('#results').removeClass('hidden');
        $('#results').animate({
            maxHeight: '1000px',
            opacity:1
        },{
            duration: 1000
        });

    }

    function selectTopRated (artists, n) {
        // Sort from more to less likes
        artists.sort(function (a, b) {
            return b.likes - a.likes;
        });
        return artists.splice(0,n);
    }

    function shareResult (message) {
        var wallPost = {
            method: 'feed',
            picture: $('#share-image').val(),
            link: 'https://apps.facebook.com/music-analyzer',
            name: message,
            caption: "music-analyzer.herokuapp.com",
            description: $('#description').val()
        };
        FB.ui(wallPost);
    }

    // DOM callbacks
    $(document).ready(function () {

        // Get user artists
        getArtists(function (artists) {

            var MAX_ARTISTS = 10;

            // If no artist likes show message
            if (artists.length === 0) {
                showModal($('#error-title').val(), $('#error-status').val(), function () {
                    document.location = '/';
                });
            }
            // If too much musicians  select the top 10 sorting by likes count
            if (artists.length > MAX_ARTISTS) {
                artists = selectTopRated(artists, MAX_ARTISTS);
            }

            artistCount = artists.length || 0;

            // Else get stats one by one
            getStats(artists, function () {
                showResults();
            });

        }); // Get user artists
    }); // End document ready
}); // End module<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['exports', 'angular'], factory);
    } else if (typeof exports === 'object') {
        factory(exports, require('angular'));
    } else {
        factory((root.commonJsStrict = {}), root.angular);
    }

}(this, function (intersect, angular) {
  var root = this,
      extendInjection = function (module, attribute) {
      var original = module[attribute];
      return (function (name, dependencies, fn) {
        if (typeof fn === 'function' && angular.isArray(dependencies)) {
          dependencies = angular.copy(dependencies);
          dependencies.push(fn);
        }
        return original.call(module, name, dependencies);
      });
    },

    getWrappedComponent = function (module) {
      return angular.extend({}, module, {
        provider: extendInjection(module, 'provider'),
        factory: extendInjection(module, 'factory'),
        service: extendInjection(module, 'service'),
        value: extendInjection(module, 'value'),
        constant: extendInjection(module, 'constant'),
        directive: extendInjection(module, 'directive'),
      });
    };

  angular.extend(intersect, angular);
  angular.extend(intersect, {
    module: function () {
      var module = angular.extend({}, angular.module.apply(angular, arguments));
      return getWrappedComponent(module);
    },
    conflict: function (providedRoot) {
      if (typeof providedRoot === 'undefined') {
        providedRoot = root;
      }
      root.angular = intersect;
    }
  });

  return intersect;
}));
<commit_msg>Remove unnecessary call to angular.extend.<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['exports', 'angular'], factory);
    } else if (typeof exports === 'object') {
        factory(exports, require('angular'));
    } else {
        factory((root.commonJsStrict = {}), root.angular);
    }

}(this, function (intersect, angular) {
  var root = this,
      extendInjection = function (module, attribute) {
      var original = module[attribute];
      return (function (name, dependencies, fn) {
        if (typeof fn === 'function' && angular.isArray(dependencies)) {
          dependencies = angular.copy(dependencies);
          dependencies.push(fn);
        }
        return original.call(module, name, dependencies);
      });
    },

    getWrappedComponent = function (module) {
      return angular.extend({}, module, {
        provider: extendInjection(module, 'provider'),
        factory: extendInjection(module, 'factory'),
        service: extendInjection(module, 'service'),
        value: extendInjection(module, 'value'),
        constant: extendInjection(module, 'constant'),
        directive: extendInjection(module, 'directive'),
      });
    };

  angular.extend(intersect, angular, {
    module: function () {
      var module = angular.extend({}, angular.module.apply(angular, arguments));
      return getWrappedComponent(module);
    },
    conflict: function (providedRoot) {
      if (typeof providedRoot === 'undefined') {
        providedRoot = root;
      }
      root.angular = intersect;
    }
  });

  return intersect;
}));
<|endoftext|>


<commit_before>var fs = require('fs');

function sortObject(obj, strict)
{
  if(obj instanceof Array) {
    var ary;
    if(strict) ary =  obj.sort();
    else ary = obj
    return ary
  }
  if(typeof obj === 'object') {
    var tObj = {};
    Object.keys(obj).sort().forEach( function(key) {
      tObj[key] = sortObject(obj[key])
    } )
    return tObj;
  }
  return obj;
}

function process(path){
  fs.readdir('../'+path, function(err, files){
    if(err){
      console.log("Directory ../"+path+" caused an Error", err);
      return
    }
    for(var i=0; i<files.length; i++) {
      if( files[i].match(/\.json$/) ) {
        try {
          console.log('starting '+path+'/'+files[i]);
          var item = JSON.parse(fs.readFileSync('../'+path+'/'+files[i]));
          fs.writeFileSync(path+'/'+files[i], JSON.stringify(sortObject(item, true),undefined, 2));
        } catch(e) {
          console.error("SOMETHING IS WRONG with ",path+files[i],e)
        }
      }
    }
  })
}

['points', 'topics', 'services', 'index'].forEach(process);
<commit_msg>fixed arays that turned into objects, commented after use, shouldn't be neccesary to do that again<commit_after>var fs = require('fs');

function sortObject(obj, strict)
{
  console.log(obj);
  if(obj instanceof Array) {
    var ary;
    if(strict) ary =  obj.sort();
    else ary = obj
    return ary
  }
  if(typeof obj === 'object') {
    //var fixed;
    //if(fixed = fixArrays(obj))
    //  return fixed;
    var tObj = {};
    Object.keys(obj).sort().forEach( function(key) {
      tObj[key] = sortObject(obj[key])
    } )
    return tObj;
  }
  return obj;
}

function fixArrays(obj){
  var l = Object.keys(obj);
  var ret = [];
  if( l.length == l.filter(function(e){return e.match(/^\d+$/)}).length && l.length > 0){
    l.forEach(function(k){
      ret.push(obj[k])
    })
    console.log(ret);
    return ret;
  } else
    return false;
}

function process(path){
  fs.readdir('../'+path, function(err, files){
    if(err){
      console.log("Directory ../"+path+" caused an Error", err);
      return
    }
    for(var i=0; i<files.length; i++) {
      if( files[i].match(/\.json$/) ) {
        try {
          console.log('starting '+path+'/'+files[i]);
          var item = JSON.parse(fs.readFileSync('../'+path+'/'+files[i]));
          fs.writeFileSync(path+'/'+files[i], JSON.stringify(sortObject(item, true),undefined, 2));
        } catch(e) {
          console.error("SOMETHING IS WRONG with ",path+'/'+files[i],e)
        }
      }
    }
  })
}

['points', 'topics', 'services', 'index'].forEach(process);
<|endoftext|>


<commit_before>//this is my new blog... isn't it great?
function pager() {
    var items = $('.blogpost');
    var numItems = items.length;
    var perPage = 2;
    items.slice(perPage).hide();

    $('#blogcontent').pagination( {
        $('.page-link').hide();
        $('.current').hide();
        $('.page-link.next').show();
        $('.current.prev').show();
        items:numItems,
        itemsOnPage:perPage,
        cssStyle:"dark-theme",
        onPageClick: function(pageNum) {
            var start = perPage * (pageNum - 1);
            var end = start + perPage;
            items.hide()
                 .slice(start, end).show();
        }
   });
}

function getBlog() {
    $.get('entriesorig.json', function(data) {
        $.each(data.entries, function(key, val) {

            console.log("Selecting Blog number " + key + " for next generation.");
            var newBlogPost = $("

")
            var small = $("")
            var para = $("
" + val.date + "
")

            small.append(para)
            var heading = $("
" + val.title + "
");
            var content = $("
" + val.text + "
");

            newBlogPost
                .append(small)
                .append(heading)
                .append(content)
                .append("
")

            $('#blog').append(newBlogPost);

            console.log("Blog number " + key + " generating...");
        });
        $(document).trigger('entries-loaded')
    });
}

$(document).ready(function(){
    getBlog();
    $(document).on('entries-loaded', pager);
});

<commit_msg>Debugging pagination...<commit_after>//this is my new blog... isn't it great?
function pager() {
    var items = $('.blogpost');
    var numItems = items.length;
    var perPage = 2;
    items.slice(perPage).hide();

    $('#blogcontent').pagination( {
        items:numItems,
        itemsOnPage:perPage,
        cssStyle:"dark-theme",
        onPageClick: function(pageNum) {
            var start = perPage * (pageNum - 1);
            var end = start + perPage;
            items.hide()
                 .slice(start, end).show();
        }
        $('.page-link').hide();
        $('.current').hide();
        $('.page-link.next').show();
        $('.current.prev').show();
   });
}

function getBlog() {
    $.get('entriesorig.json', function(data) {
        $.each(data.entries, function(key, val) {

            console.log("Selecting Blog number " + key + " for next generation.");
            var newBlogPost = $("

")
            var small = $("")
            var para = $("
" + val.date + "
")

            small.append(para)
            var heading = $("
" + val.title + "
");
            var content = $("
" + val.text + "
");

            newBlogPost
                .append(small)
                .append(heading)
                .append(content)
                .append("
")

            $('#blog').append(newBlogPost);

            console.log("Blog number " + key + " generating...");
        });
        $(document).trigger('entries-loaded')
    });
}

$(document).ready(function(){
    getBlog();
    $(document).on('entries-loaded', pager);
});

<|endoftext|>


<commit_before>import React from 'react';
import Avatar from 'material-ui/Avatar';
import Chip from 'material-ui/Chip';
import FontIcon from 'material-ui/FontIcon';
import SvgIconFace from 'material-ui/svg-icons/action/face';
import {blue300, indigo900} from 'material-ui/styles/colors';

const styles = {
  chip: {
    margin: 4,
  },
  wrapper: {
    display: 'flex',
    flexWrap: 'wrap',
  },
};

function handleRequestDelete() {
  alert('You clicked the delete button.');
}

function handleTouchTap() {
  alert('You clicked the Chip.');
}

/**
 * Examples of Chips, using an image [Avatar](/#/components/font-icon), [Font Icon](/#/components/font-icon) Avatar,
 * [SVG Icon](/#/components/svg-icon) Avatar, "Letter" (string) Avatar, and with custom colors.
 *
 * Chips with the `onRequestDelete` property defined will display a delete icon.
 */
export default class ChipExampleSimple extends React.Component {

  render() {
    return (

        <Chip
          style={styles.chip}
        >
          Text Chip
        </Chip>

        <Chip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          Deletable Text Chip
        </Chip>

        <Chip
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar src="images/uxceo-128.jpg" />
          Image Avatar Chip
        </Chip>

        <ContactChip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar src="images/ok-128.jpg" />
          Deletable Avatar Chip
        </ContactChip>

        <Chip
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
          FontIcon Avatar Chip
        </Chip>

        <Chip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar color="#444" icon={<SvgIconFace />} />
          SvgIcon Avatar Chip
        </Chip>

        <Chip onTouchTap={handleTouchTap} style={styles.chip}>
          <Avatar size={32}>A</Avatar>
          Text Avatar Chip
        </Chip>

        <Chip
          backgroundColor={blue300}
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar size={32} color={blue300} backgroundColor={indigo900}>
            MB
          </Avatar>
          Colored Chip
        </Chip>

    );
  }
}
<commit_msg>ExampleSimple.js - ln 4 - Import ContactChip<commit_after>import React from 'react';
import Avatar from 'material-ui/Avatar';
import Chip from 'material-ui/Chip';
import ContactChip from 'material-ui/ContactChip';
import FontIcon from 'material-ui/FontIcon';
import SvgIconFace from 'material-ui/svg-icons/action/face';
import {blue300, indigo900} from 'material-ui/styles/colors';

const styles = {
  chip: {
    margin: 4,
  },
  wrapper: {
    display: 'flex',
    flexWrap: 'wrap',
  },
};

function handleRequestDelete() {
  alert('You clicked the delete button.');
}

function handleTouchTap() {
  alert('You clicked the Chip.');
}

/**
 * Examples of Chips, using an image [Avatar](/#/components/font-icon), [Font Icon](/#/components/font-icon) Avatar,
 * [SVG Icon](/#/components/svg-icon) Avatar, "Letter" (string) Avatar, and with custom colors.
 *
 * Chips with the `onRequestDelete` property defined will display a delete icon.
 */
export default class ChipExampleSimple extends React.Component {

  render() {
    return (

        <Chip
          style={styles.chip}
        >
          Text Chip
        </Chip>

        <Chip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          Deletable Text Chip
        </Chip>

        <Chip
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar src="images/uxceo-128.jpg" />
          Image Avatar Chip
        </Chip>

        <ContactChip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar src="images/ok-128.jpg" />
          Deletable Avatar Chip
        </ContactChip>

        <Chip
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
          FontIcon Avatar Chip
        </Chip>

        <Chip
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar color="#444" icon={<SvgIconFace />} />
          SvgIcon Avatar Chip
        </Chip>

        <Chip onTouchTap={handleTouchTap} style={styles.chip}>
          <Avatar size={32}>A</Avatar>
          Text Avatar Chip
        </Chip>

        <Chip
          backgroundColor={blue300}
          onRequestDelete={handleRequestDelete}
          onTouchTap={handleTouchTap}
          style={styles.chip}
        >
          <Avatar size={32} color={blue300} backgroundColor={indigo900}>
            MB
          </Avatar>
          Colored Chip
        </Chip>

    );
  }
}
<|endoftext|>


<commit_before>function getposts(){
	$.getJSON('entries.json', function(data){
		$.each(data.entries, function(key, val) {
			$("#blog").append("

"+data.entries[key].date+"

"+data.entries[key].title+"

"+data.entries[key].text+"

");

			if (data.entries.length-1==key){
				found = [];
				for (i=0;i<=key;i++){
					found.push(i);
				};
				pager(0);
			};
		});
	 });
	 return false;
}

function pager(change){
	console.log("running pager");
	var page = Number($("#pg").html());
	page+=change;
	$("#pg").html(page);
	var count = found.length;
 	for (c=0;c<=$('div.blogpost').length;c++){
		$("#"+c+"").hide();
	}
	console.log("found has "+found.length+"items which include "+found)
	for (i=-5;i<=-1;i++){
		$("#"+[found[page*5+i]]+"").show();
	}
	if (page ==1){
		$("#left").hide();
	}else{
		$("#left").show();
	}
	if (page ==Math.ceil(count/5)) {
		$("#right").hide();
	}else{
		$("#right").show();
	}
	return false;
}

function getselection(){

	console.log("running 'get selection'");
	found = [];
	$("#pg").html(1);
	if ($("#search2").val()){
		$('.hideOnSearch').hide();
		var s2 = new RegExp($("#search2").val(),"i")
		console.log('looking for "'+s2+'"');
		var count = $('div.blogpost').length;
		for (c=0;c<=count;c++){
			$("#"+c+"").hide();
			if($("#"+c+"").text().search(s2)>0){
				found.push(c);
				console.log(found);
			};
		};
		$("#hits").html("Search found "+found.length+" matches.");
		console.log(found);
		pager(0);
	} else {
		console.log("it's empty");
		$('.hideOnSearch').show();
		for (i=0;i<=$('div.blogpost').length;i++){
			found.push(i);
		};
		pager(0);
	};
}

<commit_msg>hide hits<commit_after>function getposts(){
	$.getJSON('entries.json', function(data){
		$.each(data.entries, function(key, val) {
			$("#blog").append("

"+data.entries[key].date+"

"+data.entries[key].title+"

"+data.entries[key].text+"

");

			if (data.entries.length-1==key){
				found = [];
				for (i=0;i<=key;i++){
					found.push(i);
				};
				pager(0);
			};
		});
	 });
	 return false;
}

function pager(change){
	console.log("running pager");
	var page = Number($("#pg").html());
	page+=change;
	$("#pg").html(page);
	var count = found.length;
 	for (c=0;c<=$('div.blogpost').length;c++){
		$("#"+c+"").hide();
	}
	console.log("found has "+found.length+"items which include "+found)
	for (i=-5;i<=-1;i++){
		$("#"+[found[page*5+i]]+"").show();
	}
	if (page ==1){
		$("#left").hide();
	}else{
		$("#left").show();
	}
	if (page ==Math.ceil(count/5)) {
		$("#right").hide();
	}else{
		$("#right").show();
	}
	return false;
}

function getselection(){

	console.log("running 'get selection'");
	found = [];
	$("#pg").html(1);
	if ($("#search2").val()){
		$('.hideOnSearch').hide();
		var s2 = new RegExp($("#search2").val(),"i")
		console.log('looking for "'+s2+'"');
		var count = $('div.blogpost').length;
		for (c=0;c<=count;c++){
			$("#"+c+"").hide();
			if($("#"+c+"").text().search(s2)>0){
				found.push(c);
				console.log(found);
			};
		};
		$("#hits").html("Search found "+found.length+" matches.");
		console.log(found);
		$("#hits").show();
		pager(0);
	} else {
		console.log("it's empty");
		$('.hideOnSearch').show();
		for (i=0;i<=$('div.blogpost').length;i++){
			found.push(i);
		};
		$("#hits").hide();
		pager(0);
	};
}

<|endoftext|>


<commit_before>var assert = require('assert');
var path = require('path');
var levelup = require('levelup');
var memdown = require('memdown');
var PeerRegistry = require('../lib/peer_registry');

var dbPath = path.join(__dirname, './.peers');

describe('Peer Registry', function() {
  var db;

  beforeEach(function(done) {
    db = levelup(dbPath, { db: memdown });
    done();
  });

  afterEach(function(done) {
    if (db) {
      db.close(done);
    }
  });

  it('should save a peer', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0 }, function(err) {
      assert.ifError(err);
      done();
    });
  });

  it('should remove error property on peer save when status is not failed', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0, error: new Error() }, function() {
      reg.get(0, function(err, result) {
        assert.equal(result.error, undefined);
        done();
      });
    });
  })

  it('should find multiple peers', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0 }, function() {
      reg.save({ id: 1 }, function() {
        var query = { match: function() { return true; } };
        reg.find(query, function(err, results) {
          assert.equal(results.length, 2);
          done();
        });
      });
    });
  });

  it('should get peers by id', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 012345 }, function() {
      reg.get(012345, function(err, peer) {
        assert(peer);
        done();
      });
    });
  });

  it('should delete peers', function(done) {
    var reg = new PeerRegistry(db);
    var peer = { id: 0123456 };
    reg.save(peer, function() {
      reg.remove(peer, function(err, peer) {
        assert.ifError(err);
        done();
      });
    });
  });

  it('should close', function(done) {
    var reg = new PeerRegistry(db);
    reg.close(function(err) {
      assert.ifError(err);
      done();
    });
  });

  describe('#add', function() {
    it('should save new peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {};

      reg.add(peer, function(err, result) {
        assert.ok(result);
        done();
      });
    });

    it('should generate an ID for new peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {};

      reg.add(peer, function(err, result) {
        assert.ok(result.id);
        done();
      });
    });

    it('should update existing peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = { id: 012345 };

      reg.save(peer, function() {
        reg.add(peer, function(err, result) {
          assert.equal(result.id, peer.id);
          done();
        });
      });
    });

    it('propagates errors from #find', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {};

      reg.find = function(key, cb) {
        cb(new Error());
      };

      reg.add(peer, function(err, result) {
        assert.ok(err);
        done();
      });
    });

    it('propagates errors from #save', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {};

      reg.save = function(key, cb) {
        cb(new Error());
      };

      reg.add(peer, function(err, result) {
        assert.ok(err);
        done();
      });
    });

    it('it should not match entries when both .url are undefined or null', function(done) {
      var reg = new PeerRegistry(db);
      var peer1 = { name: 'some-peer-1'};
      var peer2 = { name: 'some-peer-2'};

      reg.add(peer1, function(err, result1) {
        assert.ok(result1.id);
        reg.add(peer2, function(err, result2) {
          assert.ok(result2.id);
          assert.ok(result1.id !== result2.id, 'should create two unique peers')
          done();
        });
      });
    });

  });
});
<commit_msg>Updated peer_registry test<commit_after>var assert = require('assert');
var path = require('path');
var levelup = require('levelup');
var memdown = require('memdown');
var PeerRegistry = require('../lib/peer_registry');

var dbPath = path.join(__dirname, './.peers');

describe('Peer Registry', function() {
  var db;

  beforeEach(function(done) {
    db = levelup(dbPath, { db: memdown });
    done();
  });

  afterEach(function(done) {
    if (db) {
      db.close(done);
    }
  });

  it('should save a peer', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0 }, function(err) {
      assert.ifError(err);
      done();
    });
  });

  it('should remove error property on peer save when status is not failed', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0, error: new Error() }, function() {
      reg.get(0, function(err, result) {
        assert.equal(result.error, undefined);
        done();
      });
    });
  })

  it('should find multiple peers', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 0 }, function() {
      reg.save({ id: 1 }, function() {
        var query = { match: function() { return true; } };
        reg.find(query, function(err, results) {
          assert.equal(results.length, 2);
          done();
        });
      });
    });
  });

  it('should get peers by id', function(done) {
    var reg = new PeerRegistry(db);
    reg.save({ id: 012345 }, function() {
      reg.get(012345, function(err, peer) {
        assert(peer);
        done();
      });
    });
  });

  it('should delete peers', function(done) {
    var reg = new PeerRegistry(db);
    var peer = { id: 0123456 };
    reg.save(peer, function() {
      reg.remove(peer, function(err, peer) {
        assert.ifError(err);
        done();
      });
    });
  });

  it('should close', function(done) {
    var reg = new PeerRegistry(db);
    reg.close(function(err) {
      assert.ifError(err);
      done();
    });
  });

  describe('#add', function() {
    it('should save new peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {id: 'someid'};

      reg.add(peer, function(err, result) {
        assert.ok(result);
        done();
      });
    });

    it('should generate an ID for new peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {id: 'someid'};

      reg.add(peer, function(err, result) {
        assert.ok(result.id);
        done();
      });
    });

    it('should update existing peers', function(done) {
      var reg = new PeerRegistry(db);
      var peer = { id: 012345 };

      reg.save(peer, function() {
        reg.add(peer, function(err, result) {
          assert.equal(result.id, peer.id);
          done();
        });
      });
    });

    it('propagates errors from #find', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {id: 'someid'};

      reg.find = function(key, cb) {
        cb(new Error());
      };

      reg.add(peer, function(err, result) {
        assert.ok(err);
        done();
      });
    });

    it('propagates errors from #save', function(done) {
      var reg = new PeerRegistry(db);
      var peer = {};

      reg.save = function(key, cb) {
        cb(new Error());
      };

      reg.add(peer, function(err, result) {
        assert.ok(err);
        done();
      });
    });

    it('it should not match entries when both .url are undefined or null', function(done) {
      var reg = new PeerRegistry(db);
      var peer1 = { id: 'some-peer-1'};
      var peer2 = { id: 'some-peer-2'};

      reg.add(peer1, function(err, result1) {
        assert.ok(result1.id);
        reg.add(peer2, function(err, result2) {
          assert.ok(result2.id);
          assert.ok(result1.id !== result2.id, 'should create two unique peers')
          done();
        });
      });
    });

  });
});
<|endoftext|>


<commit_before>import {sendableSteps} from "prosemirror-collab"

/* Sets up communicating with server (retrieving document,
  saving, collaboration, etc.).
 */
export class ModServerCommunications {
    constructor(editor) {
        editor.mod.serverCommunications = this
        this.editor = editor
            /* A list of messages to be sent. Only used when temporarily offline.
            Messages will be sent when returning back online. */
        this.messagesToSend = []

        this.connected = false
            /* Whether the connection is established for the first time. */
        this.firstTimeConnection = true
    }

    init() {
        this.createWSConnection()
    }

    createWSConnection() {
        let websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        // Messages object used to ensure that data is received in right order.
        this.messages = {
            server: 0,
            client: 0,
            lastTen: []
        }
        try {
            this.ws = new window.WebSocket(`${websocketProtocol}//${window.websocketServer}${window.websocketPort}/ws/document/${this.editor.docInfo.id}`)
            this.ws.onopen = () => {
                jQuery('#unobtrusive_messages').html('')
            }
        } catch (err) {
            console.error(err)
        }

        this.ws.onmessage = event => {
            let data = JSON.parse(event.data)
            let expectedServer = this.messages.server + 1
            console.log({data, expectedServer})
            if (data.type === 'request_resend') {
                this.resend_messages(data.from)
            } else if (data.s < expectedServer) {
                // Receive a message already received at least once. Ignore.
                return
            } else if (data.s > expectedServer) {
                // Messages from the server have been lost.
                // Request resend.
                this.ws.send(JSON.stringify({
                    type: 'request_resend',
                    from: this.messages.server
                }))
            } else {
                this.messages.server = expectedServer
                if (data.c === this.messages.client) {
                    this.receive(data)
                } else if (data.c < this.messages.client) {
                    // We have received all server messages, but the server seems
                    // to have missed some of the client's messages. They could
                    // have been sent simultaneously.
                    // The server wins over the client in this case.
                    let clientDifference = this.messages.client - data.c
                    this.messages.client = data.c
                    if (clientDifference > this.messages.lastTen.length) {
                        // We cannot fix the situation
                        this.send(() =>({type: 'get_document'}))
                        return
                    }
                    this.messages['lastTen'].slice(0-clientDifference).forEach(getData => {
                        let data = getData()
                        if (!data) {
                            // message is empty
                            return
                        }
                        this.messages.client += 1
                        data.c = this.messages.client
                        data.s = this.messages.server
                        console.log({type:'resend',data})
                        this.ws.send(JSON.stringify(data))
                    })
                    this.receive(data)
                }
            }
        }

        this.ws.onclose = event => {
            this.connected = false
            window.clearInterval(this.wsPinger)
            window.setTimeout(() => {
                this.createWSConnection()
            }, 2000)
            if(!this.editor.view.state.plugins.length) {
                console.warn('doc not initiated')
                return
            }
            let toSend = sendableSteps(this.editor.view.state)
            if (toSend) {
                jQuery('#unobtrusive_messages').html(''+gettext('Warning! Not all your changes have been saved! You could suffer data loss. Attempting to reconnect...')+'')
            } else {
                jQuery('#unobtrusive_messages').html(gettext('Disconnected. Attempting to reconnect...'))
            }

        }
        this.wsPinger = window.setInterval(() => {
            this.send(() => ({
                'type': 'ping'
            }))
        }, 50000)
    }

    activateConnection() {
        this.connected = true
        if (this.firstTimeConnection) {
            this.editor.waitingForDocument = false
            this.editor.askForDocument()
        } else {
            this.editor.mod.footnotes.fnEditor.renderAllFootnotes()
            this.editor.mod.collab.docChanges.checkVersion()
            this.send(() => ({
                type: 'participant_update'
            }))
            while (this.messagesToSend.length > 0) {
                this.send(this.messagesToSend.shift())
            }
        }
        this.firstTimeConnection = false
    }

    /** Sends data to server or keeps it in a list if currently offline. */
    send(getData) {
        if (this.connected) {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            this.messages.lastTen.push(getData)
            this.messages.lastTen = this.messages['lastTen'].slice(-10)
            console.log({data})
            this.ws.send(JSON.stringify(data))
        } else {
            this.messagesToSend.push(getData)
        }
    }

    resend_messages(from) {
        let toSend = this.messages.client - from
        this.messages.client = from
        if (toSend > this.messages.lastTen.length) {
            // Too many messages requested. Abort.
            this.send(() => ({type: 'get_document'}))
            return
        }
        this.messages.lastTen.slice(0-toSend).forEach(getData => {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            console.log({data})
            this.ws.send(JSON.stringify(data))
        })
    }

    receive(data) {
        switch (data.type) {
            case 'chat':
                this.editor.mod.collab.chat.newMessage(data)
                break
            case 'connections':
                this.editor.mod.collab.updateParticipantList(data.participant_list)
                break
            case 'welcome':
                this.editor.mod.styles.setStyles(data.styles)
                this.activateConnection()
                break
            case 'doc_data':
                this.editor.receiveDocument(data)
                break
            case 'confirm_version':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.enableDiffSending()
                break
            case 'selection_change':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveSelectionChange(data)
                break
            case 'diff':
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveFromCollaborators(data)
                break
            case 'confirm_diff':
                this.editor.mod.collab.docChanges.confirmDiff(data["rid"])
                break
            case 'reject_diff':
                this.editor.mod.collab.docChanges.rejectDiff(data["rid"])
                break
            case 'access_denied':
                window.location.href = '/'
                break
        }
    }

}
<commit_msg>only increase client version if message really sent<commit_after>import {sendableSteps} from "prosemirror-collab"

/* Sets up communicating with server (retrieving document,
  saving, collaboration, etc.).
 */
export class ModServerCommunications {
    constructor(editor) {
        editor.mod.serverCommunications = this
        this.editor = editor
            /* A list of messages to be sent. Only used when temporarily offline.
            Messages will be sent when returning back online. */
        this.messagesToSend = []

        this.connected = false
            /* Whether the connection is established for the first time. */
        this.firstTimeConnection = true
    }

    init() {
        this.createWSConnection()
    }

    createWSConnection() {
        let websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        // Messages object used to ensure that data is received in right order.
        this.messages = {
            server: 0,
            client: 0,
            lastTen: []
        }
        try {
            this.ws = new window.WebSocket(`${websocketProtocol}//${window.websocketServer}${window.websocketPort}/ws/document/${this.editor.docInfo.id}`)
            this.ws.onopen = () => {
                jQuery('#unobtrusive_messages').html('')
            }
        } catch (err) {
            console.error(err)
        }

        this.ws.onmessage = event => {
            let data = JSON.parse(event.data)
            let expectedServer = this.messages.server + 1
            console.log({data, expectedServer})
            if (data.type === 'request_resend') {
                this.resend_messages(data.from)
            } else if (data.s < expectedServer) {
                // Receive a message already received at least once. Ignore.
                return
            } else if (data.s > expectedServer) {
                // Messages from the server have been lost.
                // Request resend.
                this.ws.send(JSON.stringify({
                    type: 'request_resend',
                    from: this.messages.server
                }))
            } else {
                this.messages.server = expectedServer
                if (data.c === this.messages.client) {
                    this.receive(data)
                } else if (data.c < this.messages.client) {
                    // We have received all server messages, but the server seems
                    // to have missed some of the client's messages. They could
                    // have been sent simultaneously.
                    // The server wins over the client in this case.
                    let clientDifference = this.messages.client - data.c
                    this.messages.client = data.c
                    if (clientDifference > this.messages.lastTen.length) {
                        // We cannot fix the situation
                        this.send(() =>({type: 'get_document'}))
                        return
                    }
                    this.messages['lastTen'].slice(0-clientDifference).forEach(getData => {
                        let data = getData()
                        if (!data) {
                            // message is empty
                            return
                        }
                        this.messages.client += 1
                        data.c = this.messages.client
                        data.s = this.messages.server
                        console.log({type:'resend',data})
                        this.ws.send(JSON.stringify(data))
                    })
                    this.receive(data)
                }
            }
        }

        this.ws.onclose = event => {
            this.connected = false
            window.clearInterval(this.wsPinger)
            window.setTimeout(() => {
                this.createWSConnection()
            }, 2000)
            if(!this.editor.view.state.plugins.length) {
                console.warn('doc not initiated')
                return
            }
            let toSend = sendableSteps(this.editor.view.state)
            if (toSend) {
                jQuery('#unobtrusive_messages').html(''+gettext('Warning! Not all your changes have been saved! You could suffer data loss. Attempting to reconnect...')+'')
            } else {
                jQuery('#unobtrusive_messages').html(gettext('Disconnected. Attempting to reconnect...'))
            }

        }
        this.wsPinger = window.setInterval(() => {
            this.send(() => ({
                'type': 'ping'
            }))
        }, 50000)
    }

    activateConnection() {
        this.connected = true
        if (this.firstTimeConnection) {
            this.editor.waitingForDocument = false
            this.editor.askForDocument()
        } else {
            this.editor.mod.footnotes.fnEditor.renderAllFootnotes()
            this.editor.mod.collab.docChanges.checkVersion()
            this.send(() => ({
                type: 'participant_update'
            }))
            while (this.messagesToSend.length > 0) {
                this.send(this.messagesToSend.shift())
            }
        }
        this.firstTimeConnection = false
    }

    /** Sends data to server or keeps it in a list if currently offline. */
    send(getData) {
        if (this.connected) {
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            this.messages.client += 1
            data.c = this.messages.client
            data.s = this.messages.server
            this.messages.lastTen.push(getData)
            this.messages.lastTen = this.messages['lastTen'].slice(-10)
            console.log({data})
            this.ws.send(JSON.stringify(data))
        } else {
            this.messagesToSend.push(getData)
        }
    }

    resend_messages(from) {
        let toSend = this.messages.client - from
        this.messages.client = from
        if (toSend > this.messages.lastTen.length) {
            // Too many messages requested. Abort.
            this.send(() => ({type: 'get_document'}))
            return
        }
        this.messages.lastTen.slice(0-toSend).forEach(getData => {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            console.log({data})
            this.ws.send(JSON.stringify(data))
        })
    }

    receive(data) {
        switch (data.type) {
            case 'chat':
                this.editor.mod.collab.chat.newMessage(data)
                break
            case 'connections':
                this.editor.mod.collab.updateParticipantList(data.participant_list)
                break
            case 'welcome':
                this.editor.mod.styles.setStyles(data.styles)
                this.activateConnection()
                break
            case 'doc_data':
                this.editor.receiveDocument(data)
                break
            case 'confirm_version':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.enableDiffSending()
                break
            case 'selection_change':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveSelectionChange(data)
                break
            case 'diff':
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveFromCollaborators(data)
                break
            case 'confirm_diff':
                this.editor.mod.collab.docChanges.confirmDiff(data["rid"])
                break
            case 'reject_diff':
                this.editor.mod.collab.docChanges.rejectDiff(data["rid"])
                break
            case 'access_denied':
                window.location.href = '/'
                break
        }
    }

}
<|endoftext|>


<commit_before>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var timer = countdown(new Date(2019, 0, 5, 9, 0, 0, 0), function(ts) {
        document.getElementById('clock').innerHTML = ts.toString();
    }, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
});
<commit_msg>Update countdown for bag day<commit_after>$(document).ready(function(){
    $('#studentid').focus();
    var timeout;
    var l;
    var working = false;
    handleresponse = function (msg) {
        console.log(msg);
        l.stop();
        working = false;
        $('#studentid').val('').focus();
        var level='danger';
        var title='Uh-Oh...';
        var description='There may be a problem with your account. Please contact an administrator if this keeps happening.';
        if(msg.code=="checkin"){
            level='success';
            title=msg.name+',';
            description='you are now checked in. Don\'t forget to check out when the meeting is over!';
        }
        if(msg.code=="checkout"){
            level='success';
            title=msg.name+',';
            description='you have checked out. You now have '+msg.hours+' hours.';
        }
        if(msg.code=="exceed"){
            level='warning';
            description='You\'ve been checked in too long! Hours from the last session will not be counted. Input again if you need to be checked in.';
        }
        if(msg.code=="false"){
            description='The entered ID is either too short or too nonexistant.';
        }
        $('#alertbox').html('
'+title+' '+description+'
');
        $('#alertbox').fadeIn(200);
        timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
    }
    $('#checkin').click(function () {
        if(!working){
            l = Ladda.create(this);
            l.start();
            working = true;
            clearTimeout(timeout);
            $('#alertbox').fadeOut(100);
            var studentid=$('#studentid').val();
            $.ajax({
                type: "GET",
                url: '?p=json&r=checkin&d='+studentid
            }).done(handleresponse).fail(function(){console.log('Something has gone very wrong')});
        }
    });
    $("#studentid").keyup(function(event){
        if(event.keyCode == 13){
            $("#checkin").click();
        }
    });
    var timer = countdown(new Date(2019, 1, 19, 22, 59, 0, 0), function(ts) {
        document.getElementById('clock').innerHTML = ts.toString();
    }, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
});
<|endoftext|>


<commit_before>var util = require('util')
var fs = require('fs')
var exec = require('child_process').exec;
var child;

var prevTag = "v0.1.0";
var nextTag = "v0.1.1";

// Executes the git log command
child = exec('git log '+ prevTag +'...'+ nextTag +' --pretty=format:"{ \\"author\\" : \\"%an\\", \\"commit\\" : \\"%h\\", \\"date\\" : \\"%ar\\", \\"title\\" : \\"%s\\" },"', function (error, stdout, stderr) {

  var jsonStr = "{ \"data\" : [ " + stdout.toString();
  jsonStr = jsonStr.substr(0, jsonStr.length - 1) + " ] } ";

  try {
	var json = JSON.parse(jsonStr);
	json = json.data;

	console.log("Parsed JSON" )

	var changes = "";
	for ( var i = 0, l = json.length; i < l; i++ )
		changes += `* ${json[i].title} - see ${json[i].commit} \n`;

	try {
		fs.writeFile( 'changes.md', changes, function(err){
		if (err)
			throw err;
			console.log('It\'s saved!');
		});
	}
	catch(err){
		  console.log('Could not write file:  ' + err);
	  }
  }
  catch(err){
	  console.log('Could not parse JSON:  ' + err);
	  console.log('JSON STRING: ' + jsonStr);
  }

  if (error !== null) {
    console.log('exec error: ' + error);
  }
});<commit_msg>Updated git log versions<commit_after>var util = require('util')
var fs = require('fs')
var exec = require('child_process').exec;
var child;

var prevTag = "v0.1.1";
var nextTag = "v0.2.0";

// Executes the git log command
child = exec('git log '+ prevTag +'...'+ nextTag +' --pretty=format:"{ \\"author\\" : \\"%an\\", \\"commit\\" : \\"%h\\", \\"date\\" : \\"%ar\\", \\"title\\" : \\"%s\\" },"', function (error, stdout, stderr) {

  var jsonStr = "{ \"data\" : [ " + stdout.toString();
  jsonStr = jsonStr.substr(0, jsonStr.length - 1) + " ] } ";

  try {
	var json = JSON.parse(jsonStr);
	json = json.data;

	console.log("Parsed JSON" )

	var changes = "";
	for ( var i = 0, l = json.length; i < l; i++ )
		changes += `* ${json[i].title} - see ${json[i].commit} \n`;

	try {
		fs.writeFile( 'changes.md', changes, function(err){
		if (err)
			throw err;
			console.log('It\'s saved!');
		});
	}
	catch(err){
		  console.log('Could not write file:  ' + err);
	  }
  }
  catch(err){
	  console.log('Could not parse JSON:  ' + err);
	  console.log('JSON STRING: ' + jsonStr);
  }

  if (error !== null) {
    console.log('exec error: ' + error);
  }
});<|endoftext|>


<commit_before><commit_msg>removing lodash slice<commit_after><|endoftext|>


<commit_before>angular.module("deploydApp", ["ngResource", "ui.bootstrap", "checklist-model"])
  .controller("resourceCtrl", function ($scope, $http, $resource, $location) {

    $scope.baseUrl = "http://" + $location.host() + ":" + $location.port() + "/"
    $scope.resourceUrl = $scope.baseUrl + $scope.routeKey + '/';
    $scope.displayMode = "list";
    $scope.currentResource = null;
    $scope.error = null;
    $scope.checkedResources = [];
    $scope.checkedAll = false;
    $scope.checkedSeveral = false;

    $scope.checkAll = function() {
      angular.copy($scope.resources.map(function(item) { return item.id; }), $scope.checkedResources);
     };
     $scope.uncheckAll = function() {
       angular.copy([], $scope.checkedResources);
     };

     $scope.changeCheck = function() {
       if ($scope.checkedAll) {
         $scope.uncheckAll();
         $scope.checkedAll = false;
       } else {
         $scope.checkAll();
         $scope.checkedAll = true;
       };
     };

     $scope.$watch('checkedResources.length', function() {
       if ($scope.checkedResources.length > 1) {
         $scope.checkedSeveral = true;
       } else {
         $scope.checkedSeveral = false;
       };
     });

    $scope.selfResource = $resource($scope.resourceUrl + ":id", { id: "@id" },
      { create: { method: "POST" }, save: { method: "PUT" }, query: { isArray: true } }
    );

    $scope.listResources = function () {
      $scope.resources = $scope.selfResource.query();
    }

    $scope.deleteResource = function (resource) {
      resource.$delete().then(function() {
        $scope.resources.splice($scope.resources.indexOf(resource), 1);
      });
      $scope.displayMode = 'list';
    }

    $scope.createResource = function (resource) {
      new $scope.selfResource(resource).$create().then(
        function (newResource) {
          $scope.resources.push(newResource);
          $scope.clearError();
          $scope.displayMode = 'list';
        },
        function (error) {
          $scope.error = error.data;
        }
      );
    }

    $scope.updateResource = function (resource) {
      resource.$save().then(
        function (modifiedResource) {
          $scope.clearError();
          $scope.displayMode = "list";
        }, function (error) {
          $scope.error = error.data;
        }
      );
    }

    $scope.editOrCreateResource = function (resource) {
      $scope.currentResource = resource ? resource : {};
      $scope.displayMode  = 'edit';
    }

    $scope.saveEdit = function (resource) {
      if (angular.isDefined(resource.id)) {
        $scope.updateResource(resource);
      } else {
        $scope.createResource(resource);
      }
    }

    $scope.cancelEdit = function () {
      if ($scope.currentResource && $scope.currentResource.$get) {
        $scope.currentResource.$get;
      } else {
        $scope.currentResource = {};
      }
      $scope.clearError();
      $scope.displayMode = 'list';
    }

    $scope.clearError = function () {
      $scope.error = null;
    }

    $scope.listResources();

  });
<commit_msg>code align<commit_after>angular.module("deploydApp", ["ngResource", "ui.bootstrap", "checklist-model"])
  .controller("resourceCtrl", function ($scope, $http, $resource, $location) {

    $scope.baseUrl = "http://" + $location.host() + ":" + $location.port() + "/"
    $scope.resourceUrl = $scope.baseUrl + $scope.routeKey + '/';
    $scope.displayMode = "list";
    $scope.currentResource = null;
    $scope.error = null;
    $scope.checkedResources = [];
    $scope.checkedAll = false;
    $scope.checkedSeveral = false;

    $scope.checkAll = function() {
      angular.copy($scope.resources.map(function(item) { return item.id; }), $scope.checkedResources);
    };

    $scope.uncheckAll = function() {
      angular.copy([], $scope.checkedResources);
    };

    $scope.changeCheck = function() {
      if ($scope.checkedAll) {
        $scope.uncheckAll();
        $scope.checkedAll = false;
      } else {
        $scope.checkAll();
        $scope.checkedAll = true;
      };
    };

    $scope.$watch('checkedResources.length', function() {
      if ($scope.checkedResources.length > 1) {
        $scope.checkedSeveral = true;
      } else {
        $scope.checkedSeveral = false;
      };
    };

    $scope.selfResource = $resource($scope.resourceUrl + ":id", { id: "@id" },
      { create: { method: "POST" }, save: { method: "PUT" }, query: { isArray: true } }
    );

    $scope.listResources = function () {
      $scope.resources = $scope.selfResource.query();
    }

    $scope.deleteResource = function (resource) {
      resource.$delete().then(function() {
        $scope.resources.splice($scope.resources.indexOf(resource), 1);
      });
      $scope.displayMode = 'list';
    }

    $scope.createResource = function (resource) {
      new $scope.selfResource(resource).$create().then(
        function (newResource) {
          $scope.resources.push(newResource);
          $scope.clearError();
          $scope.displayMode = 'list';
        },
        function (error) {
          $scope.error = error.data;
        }
      );
    }

    $scope.updateResource = function (resource) {
      resource.$save().then(
        function (modifiedResource) {
          $scope.clearError();
          $scope.displayMode = "list";
        }, function (error) {
          $scope.error = error.data;
        }
      );
    }

    $scope.editOrCreateResource = function (resource) {
      $scope.currentResource = resource ? resource : {};
      $scope.displayMode  = 'edit';
    }

    $scope.saveEdit = function (resource) {
      if (angular.isDefined(resource.id)) {
        $scope.updateResource(resource);
      } else {
        $scope.createResource(resource);
      }
    }

    $scope.cancelEdit = function () {
      if ($scope.currentResource && $scope.currentResource.$get) {
        $scope.currentResource.$get;
      } else {
        $scope.currentResource = {};
      }
      $scope.clearError();
      $scope.displayMode = 'list';
    }

    $scope.clearError = function () {
      $scope.error = null;
    }

    $scope.listResources();

  });
<|endoftext|>