<commit_before>import React from 'react';
import { render, mount } from 'enzyme';
import Table from '..';
import Select from '../../select';

describe('Table.pagination', () => {
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
    },
  ];

  const data = [
    { key: 0, name: 'Jack' },
    { key: 1, name: 'Lucy' },
    { key: 2, name: 'Tom' },
    { key: 3, name: 'Jerry' },
  ];

  const pagination = { className: 'my-page', pageSize: 2 };

  function createTable(props) {
    return
;
  }

  function renderedNames(wrapper) {
    return wrapper.find('TableRow').map(row => row.props().record.name);
  }

  it('renders pagination correctly', () => {
    const wrapper = render(createTable());
    expect(wrapper).toMatchSnapshot();
  });

  it('should not show pager if pagination.hideOnSinglePage is true and only 1 page', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 3, hideOnSinglePage: true } }));
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 3, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 4, hideOnSinglePage: true } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: { pageSize: 4, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 5, hideOnSinglePage: true } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: { pageSize: 5, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
  });

  it('should use pageSize when defaultPageSize and pageSize are both specified', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 3, defaultPageSize: 4 } }));
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
  });

  it('paginate data', () => {
    const wrapper = mount(createTable());

    expect(renderedNames(wrapper)).toEqual(['Jack', 'Lucy']);
    wrapper
      .find('Pager')
      .last()
      .simulate('click');
    expect(renderedNames(wrapper)).toEqual(['Tom', 'Jerry']);
  });

  it('repaginates when pageSize change', () => {
    const wrapper = mount(createTable());

    wrapper.setProps({ pagination: { pageSize: 1 } });
    expect(renderedNames(wrapper)).toEqual(['Jack']);
  });

  it('fires change event', () => {
    const handleChange = jest.fn();
    const handlePaginationChange = jest.fn();
    const noop = () => {};
    const wrapper = mount(
      createTable({
        pagination: { ...pagination, onChange: handlePaginationChange, onShowSizeChange: noop },
        onChange: handleChange,
      }),
    );

    wrapper
      .find('Pager')
      .last()
      .simulate('click');

    expect(handleChange).toHaveBeenCalledWith(
      {
        className: 'my-page',
        current: 2,
        pageSize: 2,
      },
      {},
      {},
      {
        currentDataSource: [
          { key: 0, name: 'Jack' },
          { key: 1, name: 'Lucy' },
          { key: 2, name: 'Tom' },
          { key: 3, name: 'Jerry' },
        ],
      },
    );

    expect(handlePaginationChange).toHaveBeenCalledWith(2, 2);
  });

  // https://github.com/ant-design/ant-design/issues/4532
  // https://codepen.io/afc163/pen/dVeNoP?editors=001
  it('should have pager when change pagination from false to undefined', () => {
    const wrapper = mount(createTable({ pagination: false }));
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: undefined });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item-active')).toHaveLength(1);
  });

  // https://github.com/ant-design/ant-design/issues/4532
  // https://codepen.io/afc163/pen/pWVRJV?editors=001
  it('should display pagination as prop pagination change between true and false', () => {
    const wrapper = mount(createTable());
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
    wrapper.setProps({ pagination: false });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination });
    wrapper.update();
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
    wrapper.find('.ant-pagination-item-2').simulate('click');
    expect(renderedNames(wrapper)).toEqual(['Tom', 'Jerry']);
    wrapper.setProps({ pagination: false });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: true });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(1); // pageSize will be 10
    expect(renderedNames(wrapper)).toEqual(['Jack', 'Lucy', 'Tom', 'Jerry']);
  });

  // https://github.com/ant-design/ant-design/issues/5259
  it('change to correct page when data source changes', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 1 } }));
    wrapper.find('.ant-pagination-item-3').simulate('click');
    wrapper.setProps({ dataSource: [data[0]] });
    expect(wrapper.find('.ant-pagination-item-1').hasClass('ant-pagination-item-active')).toBe(
      true,
    );
  });

  it('specify the position of pagination', () => {
    const wrapper = mount(createTable({ pagination: { position: 'top' } }));
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(2);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(0)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    wrapper.setProps({ pagination: { position: 'bottom' } });
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(2);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(1)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    wrapper.setProps({ pagination: { position: 'both' } });
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(3);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(0)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(2)
        .find('.ant-pagination'),
    ).toHaveLength(1);
  });

  /**
   * `pagination` is not designed to accept `true` value,
   * but in practice, many people assign `true` to `pagination`,
   * since they misunderstand that `pagination` can accept a boolean value.
   */
  it('Accepts pagination as true', () => {
    const wrapper = render(createTable({ pagination: true }));
    expect(wrapper).toMatchSnapshot();
  });

  it('ajax render should keep display by the dataSource', () => {
    const onChange = jest.fn();

    const wrapper = mount(
      createTable({
        onChange,
        pagination: {
          total: 200,
        },
      }),
    );

    expect(wrapper.find('.ant-table-tbody tr.ant-table-row')).toHaveLength(data.length);

    wrapper.find('.ant-pagination .ant-pagination-item-2').simulate('click');
    expect(onChange.mock.calls[0][0].current).toBe(2);

    expect(wrapper.find('.ant-table-tbody tr.ant-table-row')).toHaveLength(data.length);
  });

  it('select by checkbox to trigger stopPropagation', () => {
    const onShowSizeChange = jest.fn();
    const wrapper = mount(
      createTable({
        pagination: {
          total: 200,
          showSizeChanger: true,
          onShowSizeChange,
        },
      }),
    );
    wrapper.find(Select).simulate('click');
    expect(wrapper.find('MenuItem').length).toBe(4);
    wrapper.find('MenuItem').at(3).simulate('click');
    expect(onShowSizeChange).toHaveBeenCalled();
  });
});
<commit_msg>:white_check_mark: fix ci in React 15<commit_after>import React from 'react';
import { render, mount } from 'enzyme';
import Table from '..';

describe('Table.pagination', () => {
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
    },
  ];

  const data = [
    { key: 0, name: 'Jack' },
    { key: 1, name: 'Lucy' },
    { key: 2, name: 'Tom' },
    { key: 3, name: 'Jerry' },
  ];

  const pagination = { className: 'my-page', pageSize: 2 };

  function createTable(props) {
    return
;
  }

  function renderedNames(wrapper) {
    return wrapper.find('TableRow').map(row => row.props().record.name);
  }

  it('renders pagination correctly', () => {
    const wrapper = render(createTable());
    expect(wrapper).toMatchSnapshot();
  });

  it('should not show pager if pagination.hideOnSinglePage is true and only 1 page', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 3, hideOnSinglePage: true } }));
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 3, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 4, hideOnSinglePage: true } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: { pageSize: 4, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    wrapper.setProps({ pagination: { pageSize: 5, hideOnSinglePage: true } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: { pageSize: 5, hideOnSinglePage: false } });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
  });

  it('should use pageSize when defaultPageSize and pageSize are both specified', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 3, defaultPageSize: 4 } }));
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
  });

  it('paginate data', () => {
    const wrapper = mount(createTable());

    expect(renderedNames(wrapper)).toEqual(['Jack', 'Lucy']);
    wrapper
      .find('Pager')
      .last()
      .simulate('click');
    expect(renderedNames(wrapper)).toEqual(['Tom', 'Jerry']);
  });

  it('repaginates when pageSize change', () => {
    const wrapper = mount(createTable());

    wrapper.setProps({ pagination: { pageSize: 1 } });
    expect(renderedNames(wrapper)).toEqual(['Jack']);
  });

  it('fires change event', () => {
    const handleChange = jest.fn();
    const handlePaginationChange = jest.fn();
    const noop = () => {};
    const wrapper = mount(
      createTable({
        pagination: { ...pagination, onChange: handlePaginationChange, onShowSizeChange: noop },
        onChange: handleChange,
      }),
    );

    wrapper
      .find('Pager')
      .last()
      .simulate('click');

    expect(handleChange).toHaveBeenCalledWith(
      {
        className: 'my-page',
        current: 2,
        pageSize: 2,
      },
      {},
      {},
      {
        currentDataSource: [
          { key: 0, name: 'Jack' },
          { key: 1, name: 'Lucy' },
          { key: 2, name: 'Tom' },
          { key: 3, name: 'Jerry' },
        ],
      },
    );

    expect(handlePaginationChange).toHaveBeenCalledWith(2, 2);
  });

  // https://github.com/ant-design/ant-design/issues/4532
  // https://codepen.io/afc163/pen/dVeNoP?editors=001
  it('should have pager when change pagination from false to undefined', () => {
    const wrapper = mount(createTable({ pagination: false }));
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: undefined });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item-active')).toHaveLength(1);
  });

  // https://github.com/ant-design/ant-design/issues/4532
  // https://codepen.io/afc163/pen/pWVRJV?editors=001
  it('should display pagination as prop pagination change between true and false', () => {
    const wrapper = mount(createTable());
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
    wrapper.setProps({ pagination: false });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination });
    wrapper.update();
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(2);
    wrapper.find('.ant-pagination-item-2').simulate('click');
    expect(renderedNames(wrapper)).toEqual(['Tom', 'Jerry']);
    wrapper.setProps({ pagination: false });
    expect(wrapper.find('.ant-pagination')).toHaveLength(0);
    wrapper.setProps({ pagination: true });
    expect(wrapper.find('.ant-pagination')).toHaveLength(1);
    expect(wrapper.find('.ant-pagination-item')).toHaveLength(1); // pageSize will be 10
    expect(renderedNames(wrapper)).toEqual(['Jack', 'Lucy', 'Tom', 'Jerry']);
  });

  // https://github.com/ant-design/ant-design/issues/5259
  it('change to correct page when data source changes', () => {
    const wrapper = mount(createTable({ pagination: { pageSize: 1 } }));
    wrapper.find('.ant-pagination-item-3').simulate('click');
    wrapper.setProps({ dataSource: [data[0]] });
    expect(wrapper.find('.ant-pagination-item-1').hasClass('ant-pagination-item-active')).toBe(
      true,
    );
  });

  it('specify the position of pagination', () => {
    const wrapper = mount(createTable({ pagination: { position: 'top' } }));
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(2);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(0)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    wrapper.setProps({ pagination: { position: 'bottom' } });
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(2);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(1)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    wrapper.setProps({ pagination: { position: 'both' } });
    expect(wrapper.find('.ant-spin-container').children()).toHaveLength(3);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(0)
        .find('.ant-pagination'),
    ).toHaveLength(1);
    expect(
      wrapper
        .find('.ant-spin-container')
        .childAt(2)
        .find('.ant-pagination'),
    ).toHaveLength(1);
  });

  /**
   * `pagination` is not designed to accept `true` value,
   * but in practice, many people assign `true` to `pagination`,
   * since they misunderstand that `pagination` can accept a boolean value.
   */
  it('Accepts pagination as true', () => {
    const wrapper = render(createTable({ pagination: true }));
    expect(wrapper).toMatchSnapshot();
  });

  it('ajax render should keep display by the dataSource', () => {
    const onChange = jest.fn();

    const wrapper = mount(
      createTable({
        onChange,
        pagination: {
          total: 200,
        },
      }),
    );

    expect(wrapper.find('.ant-table-tbody tr.ant-table-row')).toHaveLength(data.length);

    wrapper.find('.ant-pagination .ant-pagination-item-2').simulate('click');
    expect(onChange.mock.calls[0][0].current).toBe(2);

    expect(wrapper.find('.ant-table-tbody tr.ant-table-row')).toHaveLength(data.length);
  });

  it('select by checkbox to trigger stopPropagation', () => {
    jest.useFakeTimers();
    const onShowSizeChange = jest.fn();
    const wrapper = mount(
      createTable({
        pagination: {
          total: 200,
          showSizeChanger: true,
          onShowSizeChange,
        },
      }),
    );
    wrapper.find('.ant-select').simulate('click');
    jest.runAllTimers();
    const dropdownWrapper = mount(
      wrapper
        .find('Trigger')
        .instance()
        .getComponent(),
    );
    expect(dropdownWrapper.find('MenuItem').length).toBe(4);
    dropdownWrapper.find('MenuItem').at(3).simulate('click');
    expect(onShowSizeChange).toHaveBeenCalled();
    jest.useRealTimers();
  });
});
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (C) 2009-2010 GGA Software Services LLC
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU Affero General Public License version 3 as published by the Free
 * Software Foundation and appearing in the file LICENSE.GPL included in
 * the packaging of this file.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 ***************************************************************************/

if (!window.chem || !chem.Struct)
    throw new Error("chem.Molecule should be defined first");

chem.InChiSaver = function() {
};

chem.InChiSaver.prototype.saveMolecule = function(molecule) {
    var ret = '', err = null;
    if (ui.standalone) {
        throw { message : 'InChI is not supported in the standalone mode' };
    } else if (molecule.atoms.count() > 0) {
        molecule = molecule.clone();
        molecule.sgroups.each(function(sgid, sg) {
            if (sg.type != 'MUL') {
                throw { message : "InChi data format doesn't support s-groups" };
            }
        }, this);
        var moldata = new chem.MolfileSaver().saveMolecule(molecule);
        new Ajax.Request(ui.path + 'getinchi', {
            method: 'post',
            asynchronous : false,
            parameters: { moldata: moldata },
            onComplete: function (res) {
                if (res.responseText.startsWith('Ok.')) {
                    ret = res.responseText.split('\n')[1];
                } else if (res.responseText.startsWith('Error.')) {
                    err = { message : res.responseText.split('\n')[1] };
                } else {
                    err = { message : 'Unexpected server message (' + res.responseText + ')' };
                }
            }
        });
    }
    if (err) throw err; else return ret;
};<commit_msg>check for empty scaffold when saving to InChi (KETCHER-637)<commit_after>/****************************************************************************
 * Copyright (C) 2009-2010 GGA Software Services LLC
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU Affero General Public License version 3 as published by the Free
 * Software Foundation and appearing in the file LICENSE.GPL included in
 * the packaging of this file.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 ***************************************************************************/

if (!window.chem || !chem.Struct)
    throw new Error("chem.Molecule should be defined first");

chem.InChiSaver = function() {
};

chem.InChiSaver.prototype.saveMolecule = function(molecule) {
    var ret = '', err = null;
    if (ui.standalone)
        throw {message: 'InChI is not supported in the standalone mode'};
    if (molecule.rgroups.count() !== 0)
        alert("R-group fragments are not supported and will be discarded");
    molecule = molecule.getScaffold();
    if (molecule.atoms.count() === 0)
        return ret;
    molecule = molecule.clone();
    molecule.sgroups.each(function(sgid, sg) {
        if (sg.type !== 'MUL') {
            throw {message: "InChi data format doesn't support s-groups"};
        }
    }, this);
    var moldata = new chem.MolfileSaver().saveMolecule(molecule);
    new Ajax.Request(ui.path + 'getinchi', {
        method: 'post',
        asynchronous: false,
        parameters: {moldata: moldata},
        onComplete: function(res) {
            if (res.responseText.startsWith('Ok.')) {
                ret = res.responseText.split('\n')[1];
            } else if (res.responseText.startsWith('Error.')) {
                err = {message: res.responseText.split('\n')[1]};
            } else {
                err = {message: 'Unexpected server message (' + res.responseText + ')'};
            }
        }
    });
    if (err)
        throw err;
    return ret;
};<|endoftext|>


<commit_before>function ChoreWheel(){
  this.chores = ['Dishes', 'Garbage', 'Recycling', 'Stuff'];
  this.people = ['Mike', 'Will', 'Tanzi', 'Sarah', 'Nick',
                 'Steev', 'Chase Original', 'Nu-Chase', 'Todd'];
  this.pairs = [];
  this.begin = new Date(2014,2,25,13,15,00);
  this.setPairs();
  this.setup();
};

ChoreWheel.prototype.setPairs = function(){
  this.pairs = [];
  for(var i = 0;i < this.people.length;i++){
    if(i >= this.chores.length){
     this.pairs.push(['Free', this.people[i]]);
    }
    else{
      this.pairs.push([this.chores[i], this.people[i]]);
    }
  }
};

ChoreWheel.prototype.getPairs = function(){
  return this.pairs;
};

ChoreWheel.prototype.addPerson = function(name){
  this.people.push(name);
};

ChoreWheel.prototype.addChore = function(name){
  this.chores.push(name);
};

ChoreWheel.prototype.rotateWheel = function(){
  this.people.push(this.people.shift());
  this.setPairs();
  console.log(this.begin);
};

ChoreWheel.prototype.setup = function(){
  var today = new Date();
  var spins = new Date(today-this.begin);
  spins = spins%(this.people.length);

  for(var i = 0;i < spins;i++){
    this.rotateWheel();
  }
};

var wheel = new ChoreWheel();

var choreWheelApp = angular.module('choreWheelApp', []);

choreWheelApp.controller('choreWheelCtrl', function($scope)
                                           {$scope.wheel = wheel});

<commit_msg>Let's count by minutes instead of seconds<commit_after>function ChoreWheel(){
  this.chores = ['Dishes', 'Garbage', 'Recycling', 'Stuff'];
  this.people = ['Mike', 'Will', 'Tanzi', 'Sarah', 'Nick',
                 'Steev', 'Chase Original', 'Nu-Chase', 'Todd'];
  this.pairs = [];
  this.begin = new Date(2014,2,25,13,15,00);
  this.setPairs();
  this.setup();
};

ChoreWheel.prototype.setPairs = function(){
  this.pairs = [];
  for(var i = 0;i < this.people.length;i++){
    if(i >= this.chores.length){
     this.pairs.push(['Free', this.people[i]]);
    }
    else{
      this.pairs.push([this.chores[i], this.people[i]]);
    }
  }
};

ChoreWheel.prototype.getPairs = function(){
  return this.pairs;
};

ChoreWheel.prototype.addPerson = function(name){
  this.people.push(name);
};

ChoreWheel.prototype.addChore = function(name){
  this.chores.push(name);
};

ChoreWheel.prototype.rotateWheel = function(){
  this.people.push(this.people.shift());
  this.setPairs();
  console.log(this.begin);
};

ChoreWheel.prototype.setup = function(){
  var today = new Date();
  var spins = new Date(today-this.begin);
  spins = spins.getMinutes()%(this.people.length);

  for(var i = 0;i < spins;i++){
    this.rotateWheel();
  }
};

var wheel = new ChoreWheel();

var choreWheelApp = angular.module('choreWheelApp', []);

choreWheelApp.controller('choreWheelCtrl', function($scope)
                                           {$scope.wheel = wheel});

<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var peerConnectionsListElem = null;
var ssrcInfoManager = null;
var peerConnectionUpdateTable = null;
var statsTable = null;
var dumpCreator = null;
/** A map from peer connection id to the PeerConnectionRecord. */
var peerConnectionDataStore = {};

/** A simple class to store the updates and stats data for a peer connection. */
var PeerConnectionRecord = (function() {
  /** @constructor */
  function PeerConnectionRecord() {
    /** @private */
    this.record_ = {
      constraints: {},
      servers: [],
      stats: {},
      updateLog: [],
      url: '',
    };
  };

  PeerConnectionRecord.prototype = {
    /** @override */
    toJSON: function() {
      return this.record_;
    },

    /**
     * Adds the initilization info of the peer connection.
     * @param {string} url The URL of the web page owning the peer connection.
     * @param {Array} servers STUN servers used by the peer connection.
     * @param {!Object} constraints Media constraints.
     */
    initialize: function(url, servers, constraints) {
      this.record_.url = url;
      this.record_.servers = servers;
      this.record_.constraints = constraints;
    },

    /**
     * @param {string} dataSeriesId The TimelineDataSeries identifier.
     * @return {!TimelineDataSeries}
     */
    getDataSeries: function(dataSeriesId) {
      return this.record_.stats[dataSeriesId];
    },

    /**
     * @param {string} dataSeriesId The TimelineDataSeries identifier.
     * @param {!TimelineDataSeries} dataSeries The TimelineDataSeries to set to.
     */
    setDataSeries: function(dataSeriesId, dataSeries) {
      this.record_.stats[dataSeriesId] = dataSeries;
    },

    /**
     * @param {string} type The type of the update.
     * @param {string} value The value of the update.
     */
    addUpdate: function(type, value) {
      this.record_.updateLog.push({
        time: (new Date()).toLocaleString(),
        type: type,
        value: value,
      });
    },
  };

  return PeerConnectionRecord;
})();

// The maximum number of data points bufferred for each stats. Old data points
// will be shifted out when the buffer is full.
var MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000;

<include src="data_series.js"/>
<include src="ssrc_info_manager.js"/>
<include src="stats_graph_helper.js"/>
<include src="stats_table.js"/>
<include src="peer_connection_update_table.js"/>
<include src="dump_creator.js"/>

function initialize() {
  peerConnectionsListElem = $('peer-connections-list');
  dumpCreator = new DumpCreator(peerConnectionsListElem);
  ssrcInfoManager = new SsrcInfoManager();
  peerConnectionUpdateTable = new PeerConnectionUpdateTable();
  statsTable = new StatsTable(ssrcInfoManager);

  chrome.send('getAllUpdates');

  // Requests stats from all peer connections every second.
  window.setInterval(function() {
    if (peerConnectionsListElem.getElementsByTagName('li').length > 0)
      chrome.send('getAllStats');
  }, 1000);
}
document.addEventListener('DOMContentLoaded', initialize);

/**
 * A helper function for getting a peer connection element id.
 *
 * @param {!Object.<string, number>} data The object containing the pid and lid
 *     of the peer connection.
 * @return {string} The peer connection element id.
 */
function getPeerConnectionId(data) {
  return data.pid + '-' + data.lid;
}

/**
 * Extracts ssrc info from a setLocal/setRemoteDescription update.
 *
 * @param {!PeerConnectionUpdateEntry} data The peer connection update data.
 */
function extractSsrcInfo(data) {
  if (data.type == 'setLocalDescription' ||
      data.type == 'setRemoteDescription') {
    ssrcInfoManager.addSsrcStreamInfo(data.value);
  }
}

/**
 * Helper for adding a peer connection update.
 *
 * @param {Element} peerConnectionElement
 * @param {!PeerConnectionUpdateEntry} update The peer connection update data.
 */
function addPeerConnectionUpdate(peerConnectionElement, update) {
  peerConnectionUpdateTable.addPeerConnectionUpdate(peerConnectionElement,
                                                    update);
  extractSsrcInfo(update);
  peerConnectionDataStore[peerConnectionElement.id].addUpdate(
      update.type, update.value);
}

/** Browser message handlers. */

/**
 * Removes all information about a peer connection.
 *
 * @param {!Object.<string, number>} data The object containing the pid and lid
 *     of a peer connection.
 */
function removePeerConnection(data) {
  var element = $(getPeerConnectionId(data));
  if (element) {
    delete peerConnectionDataStore[element.id];
    peerConnectionsListElem.removeChild(element);
  }
}

/**
 * Adds a peer connection.
 *
 * @param {!Object} data The object containing the pid, lid, url, servers, and
 *     constraints of a peer connection.
 */
function addPeerConnection(data) {
  var id = getPeerConnectionId(data);

  if (!peerConnectionDataStore[id]) {
    peerConnectionDataStore[id] = new PeerConnectionRecord();
  }
  peerConnectionDataStore[id].initialize(
      data.url, data.servers, data.constraints);

  var peerConnectionElement = $(id);
  if (!peerConnectionElement) {
    peerConnectionElement = document.createElement('li');
    peerConnectionsListElem.appendChild(peerConnectionElement);
    peerConnectionElement.id = id;
  }
  peerConnectionElement.innerHTML =
      '
PeerConnection ' + peerConnectionElement.id + '
' +
      '
' + data.url + ' ' + data.servers + ' ' + data.constraints +
      '
';

  // Clicking the heading can expand or collapse the peer connection item.
  peerConnectionElement.firstChild.title = 'Click to collapse or expand';
  peerConnectionElement.firstChild.addEventListener('click', function(e) {
    if (e.target.parentElement.className == '')
      e.target.parentElement.className = 'peer-connection-hidden';
    else
      e.target.parentElement.className = '';
  });

  return peerConnectionElement;
}

/**
 * Adds a peer connection update.
 *
 * @param {!PeerConnectionUpdateEntry} data The peer connection update data.
 */
function updatePeerConnection(data) {
  var peerConnectionElement = $(getPeerConnectionId(data));
  addPeerConnectionUpdate(peerConnectionElement, data);
}

/**
 * Adds the information of all peer connections created so far.
 *
 * @param {Array.<!Object>} data An array of the information of all peer
 *     connections. Each array item contains pid, lid, url, servers,
 *     constraints, and an array of updates as the log.
 */
function updateAllPeerConnections(data) {
  for (var i = 0; i < data.length; ++i) {
    var peerConnection = addPeerConnection(data[i]);

    var log = data[i].log;
    for (var j = 0; j < log.length; ++j) {
      addPeerConnectionUpdate(peerConnection, log[j]);
    }
  }
}

/**
 * Handles the report of stats.
 *
 * @param {!Object} data The object containing pid, lid, and reports, where
 *     reports is an array of stats reports. Each report contains id, type,
 *     and stats, where stats is the object containing timestamp and values,
 *     which is an array of strings, whose even index entry is the name of the
 *     stat, and the odd index entry is the value.
 */
function addStats(data) {
  var peerConnectionElement = $(getPeerConnectionId(data));
  if (!peerConnectionElement)
    return;

  for (var i = 0; i < data.reports.length; ++i) {
    var report = data.reports[i];
    statsTable.addStatsReport(peerConnectionElement, report);
    drawSingleReport(peerConnectionElement, report);
  }
}

/**
 * Delegates to dumpCreator to update the recording status.
 * @param {!Object.<string>} update Key-value pairs describing the status of the
 *     RTP recording.
 */
function updateDumpStatus(update) {
  dumpCreator.onUpdate(update);
}
<commit_msg>Fixes a JS exception from webrtc_internals.js when the peerconnection udpate has no event log.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var peerConnectionsListElem = null;
var ssrcInfoManager = null;
var peerConnectionUpdateTable = null;
var statsTable = null;
var dumpCreator = null;
/** A map from peer connection id to the PeerConnectionRecord. */
var peerConnectionDataStore = {};

/** A simple class to store the updates and stats data for a peer connection. */
var PeerConnectionRecord = (function() {
  /** @constructor */
  function PeerConnectionRecord() {
    /** @private */
    this.record_ = {
      constraints: {},
      servers: [],
      stats: {},
      updateLog: [],
      url: '',
    };
  };

  PeerConnectionRecord.prototype = {
    /** @override */
    toJSON: function() {
      return this.record_;
    },

    /**
     * Adds the initilization info of the peer connection.
     * @param {string} url The URL of the web page owning the peer connection.
     * @param {Array} servers STUN servers used by the peer connection.
     * @param {!Object} constraints Media constraints.
     */
    initialize: function(url, servers, constraints) {
      this.record_.url = url;
      this.record_.servers = servers;
      this.record_.constraints = constraints;
    },

    /**
     * @param {string} dataSeriesId The TimelineDataSeries identifier.
     * @return {!TimelineDataSeries}
     */
    getDataSeries: function(dataSeriesId) {
      return this.record_.stats[dataSeriesId];
    },

    /**
     * @param {string} dataSeriesId The TimelineDataSeries identifier.
     * @param {!TimelineDataSeries} dataSeries The TimelineDataSeries to set to.
     */
    setDataSeries: function(dataSeriesId, dataSeries) {
      this.record_.stats[dataSeriesId] = dataSeries;
    },

    /**
     * @param {string} type The type of the update.
     * @param {string} value The value of the update.
     */
    addUpdate: function(type, value) {
      this.record_.updateLog.push({
        time: (new Date()).toLocaleString(),
        type: type,
        value: value,
      });
    },
  };

  return PeerConnectionRecord;
})();

// The maximum number of data points bufferred for each stats. Old data points
// will be shifted out when the buffer is full.
var MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000;

<include src="data_series.js"/>
<include src="ssrc_info_manager.js"/>
<include src="stats_graph_helper.js"/>
<include src="stats_table.js"/>
<include src="peer_connection_update_table.js"/>
<include src="dump_creator.js"/>

function initialize() {
  peerConnectionsListElem = $('peer-connections-list');
  dumpCreator = new DumpCreator(peerConnectionsListElem);
  ssrcInfoManager = new SsrcInfoManager();
  peerConnectionUpdateTable = new PeerConnectionUpdateTable();
  statsTable = new StatsTable(ssrcInfoManager);

  chrome.send('getAllUpdates');

  // Requests stats from all peer connections every second.
  window.setInterval(function() {
    if (peerConnectionsListElem.getElementsByTagName('li').length > 0)
      chrome.send('getAllStats');
  }, 1000);
}
document.addEventListener('DOMContentLoaded', initialize);

/**
 * A helper function for getting a peer connection element id.
 *
 * @param {!Object.<string, number>} data The object containing the pid and lid
 *     of the peer connection.
 * @return {string} The peer connection element id.
 */
function getPeerConnectionId(data) {
  return data.pid + '-' + data.lid;
}

/**
 * Extracts ssrc info from a setLocal/setRemoteDescription update.
 *
 * @param {!PeerConnectionUpdateEntry} data The peer connection update data.
 */
function extractSsrcInfo(data) {
  if (data.type == 'setLocalDescription' ||
      data.type == 'setRemoteDescription') {
    ssrcInfoManager.addSsrcStreamInfo(data.value);
  }
}

/**
 * Helper for adding a peer connection update.
 *
 * @param {Element} peerConnectionElement
 * @param {!PeerConnectionUpdateEntry} update The peer connection update data.
 */
function addPeerConnectionUpdate(peerConnectionElement, update) {
  peerConnectionUpdateTable.addPeerConnectionUpdate(peerConnectionElement,
                                                    update);
  extractSsrcInfo(update);
  peerConnectionDataStore[peerConnectionElement.id].addUpdate(
      update.type, update.value);
}

/** Browser message handlers. */

/**
 * Removes all information about a peer connection.
 *
 * @param {!Object.<string, number>} data The object containing the pid and lid
 *     of a peer connection.
 */
function removePeerConnection(data) {
  var element = $(getPeerConnectionId(data));
  if (element) {
    delete peerConnectionDataStore[element.id];
    peerConnectionsListElem.removeChild(element);
  }
}

/**
 * Adds a peer connection.
 *
 * @param {!Object} data The object containing the pid, lid, url, servers, and
 *     constraints of a peer connection.
 */
function addPeerConnection(data) {
  var id = getPeerConnectionId(data);

  if (!peerConnectionDataStore[id]) {
    peerConnectionDataStore[id] = new PeerConnectionRecord();
  }
  peerConnectionDataStore[id].initialize(
      data.url, data.servers, data.constraints);

  var peerConnectionElement = $(id);
  if (!peerConnectionElement) {
    peerConnectionElement = document.createElement('li');
    peerConnectionsListElem.appendChild(peerConnectionElement);
    peerConnectionElement.id = id;
  }
  peerConnectionElement.innerHTML =
      '
PeerConnection ' + peerConnectionElement.id + '
' +
      '
' + data.url + ' ' + data.servers + ' ' + data.constraints +
      '
';

  // Clicking the heading can expand or collapse the peer connection item.
  peerConnectionElement.firstChild.title = 'Click to collapse or expand';
  peerConnectionElement.firstChild.addEventListener('click', function(e) {
    if (e.target.parentElement.className == '')
      e.target.parentElement.className = 'peer-connection-hidden';
    else
      e.target.parentElement.className = '';
  });

  return peerConnectionElement;
}

/**
 * Adds a peer connection update.
 *
 * @param {!PeerConnectionUpdateEntry} data The peer connection update data.
 */
function updatePeerConnection(data) {
  var peerConnectionElement = $(getPeerConnectionId(data));
  addPeerConnectionUpdate(peerConnectionElement, data);
}

/**
 * Adds the information of all peer connections created so far.
 *
 * @param {Array.<!Object>} data An array of the information of all peer
 *     connections. Each array item contains pid, lid, url, servers,
 *     constraints, and an array of updates as the log.
 */
function updateAllPeerConnections(data) {
  for (var i = 0; i < data.length; ++i) {
    var peerConnection = addPeerConnection(data[i]);

    var log = data[i].log;
    if (!log)
      continue;
    for (var j = 0; j < log.length; ++j) {
      addPeerConnectionUpdate(peerConnection, log[j]);
    }
  }
}

/**
 * Handles the report of stats.
 *
 * @param {!Object} data The object containing pid, lid, and reports, where
 *     reports is an array of stats reports. Each report contains id, type,
 *     and stats, where stats is the object containing timestamp and values,
 *     which is an array of strings, whose even index entry is the name of the
 *     stat, and the odd index entry is the value.
 */
function addStats(data) {
  var peerConnectionElement = $(getPeerConnectionId(data));
  if (!peerConnectionElement)
    return;

  for (var i = 0; i < data.reports.length; ++i) {
    var report = data.reports[i];
    statsTable.addStatsReport(peerConnectionElement, report);
    drawSingleReport(peerConnectionElement, report);
  }
}

/**
 * Delegates to dumpCreator to update the recording status.
 * @param {!Object.<string>} update Key-value pairs describing the status of the
 *     RTP recording.
 */
function updateDumpStatus(update) {
  dumpCreator.onUpdate(update);
}
<|endoftext|>


<commit_before>// @flow
import React from "react"
import { connect } from "react-redux"
import { makeStyles } from "@material-ui/styles"
import Grid from "@material-ui/core/Grid"
import List from "@material-ui/core/List"
import ListItem from "@material-ui/core/ListItem"
import Checkbox from "@material-ui/core/Checkbox"
import Hidden from "@material-ui/core/Hidden"
import AddToCartButton from "components/Stocks/CatalogTableItems/AddToCartButton"
import { addToCart } from "actions/cart"

const useStyles = makeStyles({
  listHeaders: {
    borderBottom: "1px solid #888",
    backgroundColor: "#f6f9fc",
    color: "#525f7f",
    fontWeight: 600,
  },
  list: {
    padding: 0,
  },
})

type Props = {
  checkedItems: Array<{
    id: string,
    label: string,
  }>,
  setCheckedItems: Function,
  addToCart: Function,
  handleCheckAllChange: Function,
}

/**
 * StrainCatalogListHeader contains the list of headers (i.e.
 * descriptor, summary, etc) at the top of the catalog page.
 */

const StrainCatalogListHeader = ({
  checkedItems,
  setCheckedItems,
  addToCart,
  handleCheckAllChange,
  dialogOpen,
  setDialogOpen,
}: Props) => {
  const classes = useStyles()
  const checkedItemsLength = checkedItems.length

  return (
    <List className={classes.list}>
      <ListItem className={classes.listHeaders}>
        <Grid container spacing={0} alignItems="center">
          <Hidden smDown>
            <Grid item md={1}>
              {checkedItemsLength > 0 && (
                <Checkbox
                  indeterminate={checkedItemsLength > 0 ? true : false}
                  color="default"
                  value="selectAll"
                  onChange={handleCheckAllChange}
                  inputProps={{
                    "aria-label": "checkbox select all",
                  }}
                />
              )}
            </Grid>
          </Hidden>
          {checkedItemsLength > 0 ? (
            <AddToCartButton
              data={checkedItems}
              setCheckedItems={setCheckedItems}
            />
          ) : (
            <>
              <Grid item xs={12} md={3}>
                Strain Descriptor
              </Grid>
              <Hidden smDown>
                <Grid item md={6}>
                  Strain Summary
                </Grid>
              </Hidden>
              <Hidden lgDown>
                <Grid item xl={1}>
                  Strain ID
                </Grid>
              </Hidden>
              <Hidden smDown>
                <Grid item xs={4} md={1}></Grid>
              </Hidden>
            </>
          )}
        </Grid>
      </ListItem>
    </List>
  )
}

export default connect<*, *, *, *, *, *>(
  null,
  { addToCart },
)(StrainCatalogListHeader)
<commit_msg>feat: add download icon to header when checkboxes are active #227<commit_after>// @flow
import React from "react"
import { connect } from "react-redux"
import { makeStyles } from "@material-ui/styles"
import Grid from "@material-ui/core/Grid"
import List from "@material-ui/core/List"
import ListItem from "@material-ui/core/ListItem"
import Checkbox from "@material-ui/core/Checkbox"
import Hidden from "@material-ui/core/Hidden"
import IconButton from "@material-ui/core/IconButton"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import AddToCartButton from "components/Stocks/CatalogTableItems/AddToCartButton"
import { addToCart } from "actions/cart"

const useStyles = makeStyles({
  listHeaders: {
    borderBottom: "1px solid #888",
    backgroundColor: "#f6f9fc",
    color: "#525f7f",
    fontWeight: 600,
  },
  list: {
    padding: 0,
  },
  button: {
    color: "#004080",
  },
})

type Props = {
  checkedItems: Array<{
    id: string,
    label: string,
  }>,
  setCheckedItems: Function,
  addToCart: Function,
  handleCheckAllChange: Function,
}

/**
 * StrainCatalogListHeader contains the list of headers (i.e.
 * descriptor, summary, etc) at the top of the catalog page.
 */

const StrainCatalogListHeader = ({
  checkedItems,
  setCheckedItems,
  addToCart,
  handleCheckAllChange,
  dialogOpen,
  setDialogOpen,
}: Props) => {
  const classes = useStyles()
  const checkedItemsLength = checkedItems.length

  return (
    <List className={classes.list}>
      <ListItem className={classes.listHeaders}>
        <Grid container spacing={0} alignItems="center">
          <Hidden smDown>
            <Grid item md={1}>
              {checkedItemsLength > 0 && (
                <Checkbox
                  indeterminate={checkedItemsLength > 0 ? true : false}
                  color="default"
                  value="selectAll"
                  onChange={handleCheckAllChange}
                  inputProps={{
                    "aria-label": "checkbox select all",
                  }}
                />
              )}
            </Grid>
          </Hidden>
          {checkedItemsLength > 0 ? (
            <>
              <AddToCartButton
                data={checkedItems}
                setCheckedItems={setCheckedItems}
              />
              <IconButton
                size="medium"
                className={classes.button}
                onClick={() => {}}
                title="Download PDF"
                aria-label="Download PDF">
                <FontAwesomeIcon icon="download" />
              </IconButton>
            </>
          ) : (
            <>
              <Grid item xs={12} md={3}>
                Strain Descriptor
              </Grid>
              <Hidden smDown>
                <Grid item md={6}>
                  Strain Summary
                </Grid>
              </Hidden>
              <Hidden lgDown>
                <Grid item xl={1}>
                  Strain ID
                </Grid>
              </Hidden>
              <Hidden smDown>
                <Grid item xs={4} md={1}></Grid>
              </Hidden>
            </>
          )}
        </Grid>
      </ListItem>
    </List>
  )
}

export default connect<*, *, *, *, *, *>(
  null,
  { addToCart },
)(StrainCatalogListHeader)
<|endoftext|>


<commit_before>import moment from 'moment';

import { ADD_ACTIVITY, EDIT_ACTIVITY, ADD_TAGS } from './types';
import { executeSql } from 'yasav/src/Database';
import { ActivityTypeEnum } from 'yasav/src/const';

export function addTags(tags) {
  return (dispatch, getState) => {
    // SELECT * WHERE tag_slug = tag
    if(tags.length > 0){
      newTags = tags
      request = 'SELECT * FROM tag  WHERE '
      searchParams = []
      newTags.forEach((tag) => {
        request += 'slug = ? OR '
        searchParams = searchParams.concat(tag.slug)
      })

      request = request.substr(0,request.length-3)
      return executeSql(request, searchParams)
      .then((res) => {
        ids = []
        res.rows._array.forEach(t => {
          newTags = newTags.filter( tagToFilter => { console.log(tagToFilter.slug + " - " + t.slug); return tagToFilter.slug !== t.slug} )
          ids = ids.concat(t.id)
        })
        let promises = []
        request = "INSERT INTO tag (name, slug) VALUES (?, ?)"
        newTags.forEach(tag => {
          promises = promises.concat(executeSql(request, [tag.value, tag.slug]))
        })

        return Promise.all(promises)
          .then (results => {
            ids = ids.concat(results.map(i => i.insertId))
            //console.log(ids)
            return ids
          });
      });
    } else {
      return []
    }
  }
}

export function addActivity(activity, tagsId, interlocutorId) {
  return (dispatch, getState) => {
    let request;
    let params;
    switch (activity.type) {
      case ActivityTypeEnum.CONTENT:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible, content_source)
        VALUES (?, ?, ${ActivityTypeEnum.CONTENT}, ?, 1, ?);`;
        params = [activity.title, activity.description, activity.date, activity.contentSource];
        break;

      case ActivityTypeEnum.MEETING:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible, interlocutor_id)
        VALUES (?, ?, ${ActivityTypeEnum.MEETING}, ?, 1, ?);`;
        params = [activity.title, activity.description, activity.date, interlocutorId];
        break;

      case ActivityTypeEnum.EVENT:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible)
        VALUES (?, ?, ${ActivityTypeEnum.EVENT}, ?, 1);`;
        params = [activity.title, activity.description, activity.date];
        break;
      default:
        request = '';
        params = null;
    }
    executeSql(request, params)
      .then(({ activityId }) => {
        promises = []
        tagsId.forEach(tagId => promises = promises.concat(executeSql('INSERT INTO activity_tag(activity_id, tag_id) VALUES (?, ?'), [activityId, tagId]))
        Promises.all(promises)
        .then(result => {
          const activityWithId = { ...activity, id: activityId };
          dispatch({ type: ADD_ACTIVITY, activity: activityWithId });
        })
      });
  };
}

export function editActivity(activity, interlocutorId) {
  return (dispatch) => {
    let request;
    let params;
    request = 'UPDATE activity ';
    switch (activity.type) {
      case ActivityTypeEnum.CONTENT:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.CONTENT},
        activity_date = ?, visible = 1, content_source = ?, interlocutor_id = ?`;
        params = [activity.title, activity.description, activity.date, activity.contentSource, interlocutorId, activity.id];
        break;

      case ActivityTypeEnum.MEETING:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.MEETING},
        activity_date = ?, visible = 1`;
        params = [activity.title, activity.description, activity.date, activity.id];
        break;

      case ActivityTypeEnum.EVENT:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.EVENT},
        activity_date = ?, visible =1`;
        params = [activity.title, activity.description, activity.date, activity.id];
        break;
      default:
        request = '';
        params = null;
    }
    request += ' WHERE id = ?;';
    executeSql(request, params)
      .then(() => {
        dispatch({ type: EDIT_ACTIVITY, activity });
      });
  };
}
<commit_msg>Remove console.log<commit_after>import moment from 'moment';

import { ADD_ACTIVITY, EDIT_ACTIVITY, ADD_TAGS } from './types';
import { executeSql } from 'yasav/src/Database';
import { ActivityTypeEnum } from 'yasav/src/const';

export function addTags(tags) {
  return (dispatch, getState) => {
    // SELECT * WHERE tag_slug = tag
    if(tags.length > 0){
      newTags = tags
      request = 'SELECT * FROM tag  WHERE '
      searchParams = []
      newTags.forEach((tag) => {
        request += 'slug = ? OR '
        searchParams = searchParams.concat(tag.slug)
      })

      request = request.substr(0,request.length-3)
      return executeSql(request, searchParams)
      .then((res) => {
        ids = []
        res.rows._array.forEach(t => {
          newTags = newTags.filter( tagToFilter => tagToFilter.slug !== t.slug )
          ids = ids.concat(t.id)
        })
        let promises = []
        request = "INSERT INTO tag (name, slug) VALUES (?, ?)"
        newTags.forEach(tag => {
          promises = promises.concat(executeSql(request, [tag.value, tag.slug]))
        })

        return Promise.all(promises)
          .then (results => {
            ids = ids.concat(results.map(i => i.insertId))
            return ids
          });
      });
    } else {
      return []
    }
  }
}

export function addActivity(activity, tagsId, interlocutorId) {
  return (dispatch, getState) => {
    let request;
    let params;
    switch (activity.type) {
      case ActivityTypeEnum.CONTENT:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible, content_source)
        VALUES (?, ?, ${ActivityTypeEnum.CONTENT}, ?, 1, ?);`;
        params = [activity.title, activity.description, activity.date, activity.contentSource];
        break;

      case ActivityTypeEnum.MEETING:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible, interlocutor_id)
        VALUES (?, ?, ${ActivityTypeEnum.MEETING}, ?, 1, ?);`;
        params = [activity.title, activity.description, activity.date, interlocutorId];
        break;

      case ActivityTypeEnum.EVENT:
        request =
        `INSERT INTO
        activity(title, description, type, activity_date, visible)
        VALUES (?, ?, ${ActivityTypeEnum.EVENT}, ?, 1);`;
        params = [activity.title, activity.description, activity.date];
        break;
      default:
        request = '';
        params = null;
    }
    executeSql(request, params)
      .then(({ activityId }) => {
        promises = []
        tagsId.forEach(tagId => promises = promises.concat(executeSql('INSERT INTO activity_tag(activity_id, tag_id) VALUES (?, ?'), [activityId, tagId]))
        Promises.all(promises)
        .then(result => {
          const activityWithId = { ...activity, id: activityId };
          dispatch({ type: ADD_ACTIVITY, activity: activityWithId });
        })
      });
  };
}

export function editActivity(activity, interlocutorId) {
  return (dispatch) => {
    let request;
    let params;
    request = 'UPDATE activity ';
    switch (activity.type) {
      case ActivityTypeEnum.CONTENT:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.CONTENT},
        activity_date = ?, visible = 1, content_source = ?, interlocutor_id = ?`;
        params = [activity.title, activity.description, activity.date, activity.contentSource, interlocutorId, activity.id];
        break;

      case ActivityTypeEnum.MEETING:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.MEETING},
        activity_date = ?, visible = 1`;
        params = [activity.title, activity.description, activity.date, activity.id];
        break;

      case ActivityTypeEnum.EVENT:
        request +=
        `SET title = ?, description = ?, type = ${ActivityTypeEnum.EVENT},
        activity_date = ?, visible =1`;
        params = [activity.title, activity.description, activity.date, activity.id];
        break;
      default:
        request = '';
        params = null;
    }
    request += ' WHERE id = ?;';
    executeSql(request, params)
      .then(() => {
        dispatch({ type: EDIT_ACTIVITY, activity });
      });
  };
}
<|endoftext|>


<commit_before>WYMeditor.STRINGS['pt-BR'] = {
	Bold: 'Negrito',
	Strong: 'Resaltar',
	Emphasis: 'Itálico',
	Superscript: 'Sobre escrito',
	Subscript: 'Sub escrito ',
	Ordered_List: 'Lista ordenada',
	Unordered_List: 'Lista desordenada',
	Indent: 'Indentado',
	Outdent: 'Desidentar',
	Undo: 'Desfazer',
	Redo: 'Refazer',
	Link: 'Link',
	Unlink: 'Remover Link',
	Image: 'Imagem',
	Table: 'Tabela',
	HTML: 'HTML',
	Paragraph: 'Parágrafo',
	Heading_1: 'Título 1',
	Heading_2: 'Título 2',
	Heading_3: 'Título 3',
	Heading_4: 'Título 4',
	Heading_5: 'Título 5',
	Heading_6: 'Título 6',
	Preformatted: 'Pré-formatado',
	Blockquote: 'Citação',
	Table_Header: 'Título de tabela',
	URL: 'URL',
	Title: 'Título',
	Alternative_Text: 'Texto alternativo',
	Caption: 'Legenda',
	Summary: 'Sumário',
	Number_Of_Rows: 'Número de linhas',
	Number_Of_Cols: 'Número de colunas',
	Insert: 'Inserir',
	Submit: 'Enviar',
	Cancel: 'Cancelar',
	Choose: 'Selecionar',
	Preview: 'Previsualizar',
	Paste_From_Word: 'Copiar do Word',
	Tools: 'Ferramentas',
	Containers: 'Containers',
	Classes: 'Classes',
	Status: 'Estado',
	Source_Code: 'Código fonte',
	Css_Class: 'Aplicar classe CSS'
};<commit_msg>Added some pt-BR i18n to wymeditor<commit_after>WYMeditor.STRINGS['pt-BR'] = {
	Bold:             'Negrito',
	Strong:           'Resaltar',
	Emphasis:         'Itálico',
	Superscript:      'Sobre escrito',
	Subscript:        'Sub escrito ',
	Ordered_List:     'Lista ordenada',
	Unordered_List:   'Lista desordenada',
	Indent:           'Indentado',
	Outdent:          'Desidentar',
	Undo:             'Desfazer',
	Redo:             'Refazer',
	Link:             'Link',
	Unlink:           'Remover Link',
	Image:            'Imagem',
	Table:            'Tabela',
	HTML:             'HTML',
	Paragraph:        'Parágrafo',
	Heading_1:        'Título 1',
	Heading_2:        'Título 2',
	Heading_3:        'Título 3',
	Heading_4:        'Título 4',
	Heading_5:        'Título 5',
	Heading_6:        'Título 6',
	Preformatted:     'Pré-formatado',
	Blockquote:       'Citação',
	Table_Header:     'Título de tabela',
	URL:              'URL',
	Title:            'Título',
	Alternative_Text: 'Texto alternativo',
	Caption:          'Legenda',
	Summary:          'Sumário',
	Number_Of_Rows:   'Número de linhas',
	Number_Of_Cols:   'Número de colunas',
	Insert:           'Inserir',
	Submit:           'Enviar',
	Cancel:           'Cancelar',
	Choose:           'Selecionar',
	Preview:          'Previsualizar',
	Paste_From_Word:  'Copiar do Word',
	Tools:            'Ferramentas',
	Containers:       'Containers',
	Classes:          'Classes',
	Status:           'Estado',
	Source_Code:      'Código fonte',
	Css_Class:        'Aplicar classe CSS'
  Text_Align:       'Alinhamento de texto',
  Image_Align:      'Alinhamento de imagem',
  Font_Size:        'Tamanho da fonte',
  Left:             'Esquerda',
  Right:            'Direita',
  Center:           'Centro',
  Justify:          'Justificado',
  Small:            'Pequena',
  Normal:           'Normal',
  Large:            'Grande',
  Apply_Style:      'Estilo'
};
<|endoftext|>


<commit_before>var BookmarksBar = Class.create(ResizeableBar, {

	initialize: function($super){
		this.oElement = $('bmbar_content');
		$super("bmbar_content", "bookmarks_bar", "bm", "bmbar_title", "bmbar_extension");
		this.load();
		this.currentCount = 0;
	},

	parseXml: function(transport){
		this.clearElement();
		var oXmlDoc = transport.responseXML;
		if(oXmlDoc == null || oXmlDoc.documentElement == null) return;
		var root = oXmlDoc.documentElement;
		for (var i=0; i < root.childNodes.length;i++)
		{
			if(root.childNodes[i].tagName != 'bookmark') continue;
			this.displayBookmark(root.childNodes[i].getAttribute('path'), root.childNodes[i].getAttribute('title'));
		}
		this.updateUI();
		if(this.contextMenu) this.contextMenu.addElements('div.bm');
		if(modal.pageLoading) modal.updateLoadingProgress('Bookmarks Loaded');
	},

	displayBookmark: function(path, title){
		this.oElement.innerHTML += '
 '+title+'
';
		this.currentCount++;
	},

	clearElement: function(){
		this.oElement.update();
		this.currentCount = 0;
		if(this.contextMenu) this.contextMenu.removeElements('div.bm');
	},

	setContextualMenu:function(oMenu){
		this.contextMenu = oMenu;
	},

	findBookmarkEventSource:function(srcElement){

		for(var i=0; i<this.currentCount; i++)
		{
			var bookmark = $('bookmark_'+i);
			if(!bookmark) continue;
			if(srcElement == bookmark) return bookmark;
			if(srcElement.descendantOf(bookmark)) return bookmark;
		}
	},

	getContextActions: function(bmElement){

		var removeAction = {
				name:MessageHash[146],
				alt:MessageHash[146],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/delete_bookmark.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					this.removeBookmark(bmElement.getAttribute('bm_path'));
				}.bind(this)
			};

		var goToAction = {
				name:MessageHash[224],
				alt:MessageHash[104],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/forward.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					ajaxplorer.goTo(bmElement.getAttribute('bm_path'));
				}
			};

		var renameAction = {
				name:MessageHash[6],
				alt:MessageHash[6],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/applix.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					this.toggleRenameForm(bmElement);
				}.bind(this)
			};

		return new Array(goToAction, renameAction, removeAction);
	},

	toggleRenameForm:function(bmElement){

		modal.prepareHeader(MessageHash[225], ajxpResourcesFolder+'/images/crystal/actions/16/bookmark.png');
	 	var onLoad = function(newForm){
	 		$(newForm).bm_path.value = bmElement.getAttribute('bm_path');
	 		$(newForm).bm_title.value = bmElement.select('a.bookmark_button')[0].innerHTML;
	 	}
	 	var onComplete = function(){
	 		this.renameBookmark(modal.getForm().bm_path.value, modal.getForm().bm_title.value);
	 		hideLightBox(true);
	 	}.bind(this);
		modal.showDialogForm('Rename', 'rename_bookmark', onLoad, onComplete);
	},

	load: function(actionsParameters){
		var connexion = new Connexion();
		if(!actionsParameters) actionsParameters = new Hash();
		actionsParameters.set('get_action', 'get_bookmarks');
		connexion.setParameters(actionsParameters);
		connexion.onComplete = function(transport){
			this.parseXml(transport);
		}.bind(this);
		connexion.sendAsync();
	},

	addBookmark: function(path,title){
		var parameters = new Hash();
		parameters.set('bm_action', 'add_bookmark');
		parameters.set('bm_path', path);
		if(title){
			parameters.set('bm_title', title);
		}
		this.load(parameters);
	},

	removeBookmark: function(path){
		var parameters = new Hash();
		parameters.set('bm_action', 'delete_bookmark');
		parameters.set('bm_path', path);
		this.load(parameters);
	},

	renameBookmark: function(path, title){
		var parameters = new Hash();
		parameters.set('bm_action', 'rename_bookmark');
		parameters.set('bm_path', path);
		parameters.set('bm_title', title);
		this.load(parameters);
	}

});
<commit_msg>Safari pb : artificially trigger a window.resize() event to redraw the resizeable bar...<commit_after>var BookmarksBar = Class.create(ResizeableBar, {

	initialize: function($super){
		this.oElement = $('bmbar_content');
		$super("bmbar_content", "bookmarks_bar", "bm", "bmbar_title", "bmbar_extension");
		this.load();
		this.currentCount = 0;
	},

	parseXml: function(transport){
		this.clearElement();
		var oXmlDoc = transport.responseXML;
		if(oXmlDoc == null || oXmlDoc.documentElement == null) return;
		var root = oXmlDoc.documentElement;
		for (var i=0; i < root.childNodes.length;i++)
		{
			if(root.childNodes[i].tagName != 'bookmark') continue;
			this.displayBookmark(root.childNodes[i].getAttribute('path'), root.childNodes[i].getAttribute('title'));
		}
		if(this.contextMenu) this.contextMenu.addElements('div.bm');
		if(modal.pageLoading) modal.updateLoadingProgress('Bookmarks Loaded');
		window.setTimeout(function(){
			this.updateUI();
			if(Prototype.Browser.WebKit){ // hack for display problem!
				window.resizeBy(1,0);
				window.resizeBy(-1,0);
			}
		}.bind(this), 0);
	},

	displayBookmark: function(path, title){
		this.oElement.innerHTML += '
 '+title+'
';
		this.currentCount++;
	},

	clearElement: function(){
		this.oElement.update();
		this.currentCount = 0;
		if(this.contextMenu) this.contextMenu.removeElements('div.bm');
	},

	setContextualMenu:function(oMenu){
		this.contextMenu = oMenu;
	},

	findBookmarkEventSource:function(srcElement){

		for(var i=0; i<this.currentCount; i++)
		{
			var bookmark = $('bookmark_'+i);
			if(!bookmark) continue;
			if(srcElement == bookmark) return bookmark;
			if(srcElement.descendantOf(bookmark)) return bookmark;
		}
	},

	getContextActions: function(bmElement){

		var removeAction = {
				name:MessageHash[146],
				alt:MessageHash[146],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/delete_bookmark.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					this.removeBookmark(bmElement.getAttribute('bm_path'));
				}.bind(this)
			};

		var goToAction = {
				name:MessageHash[224],
				alt:MessageHash[104],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/forward.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					ajaxplorer.goTo(bmElement.getAttribute('bm_path'));
				}
			};

		var renameAction = {
				name:MessageHash[6],
				alt:MessageHash[6],
				image:ajxpResourcesFolder+'/images/crystal/actions/16/applix.png',
				disabled:false,
				className:"edit",
				callback:function(e){
					this.toggleRenameForm(bmElement);
				}.bind(this)
			};

		return new Array(goToAction, renameAction, removeAction);
	},

	toggleRenameForm:function(bmElement){

		modal.prepareHeader(MessageHash[225], ajxpResourcesFolder+'/images/crystal/actions/16/bookmark.png');
	 	var onLoad = function(newForm){
	 		$(newForm).bm_path.value = bmElement.getAttribute('bm_path');
	 		$(newForm).bm_title.value = bmElement.select('a.bookmark_button')[0].innerHTML;
	 	}
	 	var onComplete = function(){
	 		this.renameBookmark(modal.getForm().bm_path.value, modal.getForm().bm_title.value);
	 		hideLightBox(true);
	 	}.bind(this);
		modal.showDialogForm('Rename', 'rename_bookmark', onLoad, onComplete);
	},

	load: function(actionsParameters){
		var connexion = new Connexion();
		if(!actionsParameters) actionsParameters = new Hash();
		actionsParameters.set('get_action', 'get_bookmarks');
		connexion.setParameters(actionsParameters);
		connexion.onComplete = function(transport){
			this.parseXml(transport);
		}.bind(this);
		connexion.sendAsync();
	},

	addBookmark: function(path,title){
		var parameters = new Hash();
		parameters.set('bm_action', 'add_bookmark');
		parameters.set('bm_path', path);
		if(title){
			parameters.set('bm_title', title);
		}
		this.load(parameters);
	},

	removeBookmark: function(path){
		var parameters = new Hash();
		parameters.set('bm_action', 'delete_bookmark');
		parameters.set('bm_path', path);
		this.load(parameters);
	},

	renameBookmark: function(path, title){
		var parameters = new Hash();
		parameters.set('bm_action', 'rename_bookmark');
		parameters.set('bm_path', path);
		parameters.set('bm_title', title);
		this.load(parameters);
	}

});
<|endoftext|>


<commit_before>/**
 * todo add docstring
 */

hqDefine('reports/v2/js/context', [
    'jquery',
    'knockout',
    'underscore',
    'hqwebapp/js/assert_properties',
    'hqwebapp/js/initial_page_data',
], function (
    $,
    ko,
    _,
    assertProperties,
    initialPageData
) {
    'use strict';

    var endpoint = function (data) {
        assertProperties.assert(data, ['slug', 'urlname']);

        var self = {};

        self.slug = data.slug;
        self.urlname = data.urlname;

        self.getUrl = function () {
            return initialPageData.reverse(self.urlname, self.slug);
        };

        return self;
    };

    var reportConfig = function () {
        var self = {};

        self.endpoint = {};

        self.init = function () {

            _.each(initialPageData.get('report.endpoints'), function (data) {
                self.endpoint[data.slug] = endpoint(data);
            });

        };

        return self;
    };

    return {
        getReportConfig: function () {
            return reportConfig();
        },
    };
});
<commit_msg>initialize endpoints in report config immediately<commit_after>/**
 * todo add docstring
 */

hqDefine('reports/v2/js/context', [
    'jquery',
    'knockout',
    'underscore',
    'hqwebapp/js/assert_properties',
    'hqwebapp/js/initial_page_data',
], function (
    $,
    ko,
    _,
    assertProperties,
    initialPageData
) {
    'use strict';

    var endpoint = function (data) {
        assertProperties.assert(data, ['slug', 'urlname']);

        var self = {};

        self.slug = data.slug;
        self.urlname = data.urlname;

        self.getUrl = function () {
            return initialPageData.reverse(self.urlname, self.slug);
        };

        return self;
    };

    var reportConfig = function () {
        var self = {};

        self.endpoint = {};

        _.each(initialPageData.get('report.endpoints'), function (data) {
            self.endpoint[data.slug] = endpoint(data);
        });

        return self;
    };

    return {
        getReportConfig: function () {
            return reportConfig();
        },
    };
});
<|endoftext|>


<commit_before>hqDefine("m4change/javascripts/main", function () {
    var initialPageData = hqImport("hqwebapp/js/initial_page_data");
    $(function ()
        var OPTIONS = {
            users: initialPageData.get("users"),
            groups: initialPageData.get("groups"),
            receiverUrl: initialPageData.reverse('receiver_secure_post'),
            enddate: initialPageData.get("end_date"),
            webUserID: initialPageData.get("user_id"),
            domain: initialPageData.get("domain"),
        };

        var managementModel = new McctProjectReviewPageManagement(OPTIONS);
        function applyBindings() {
            var $mcctProjectReviewPageManagement = $('#mcct_project_review_page_management');
            var element = $mcctProjectReviewPageManagement[0];
            element.koApplyBindings(managementModel);

            $mcctProjectReviewPageManagement.find('a.select-all').click(function () {
                $mcctProjectReviewPageManagement.find('input.selected-element').prop('checked', true).change();
                return false;
            });

            $mcctProjectReviewPageManagement.find('a.select-none').click(function() {selectNone(); return false;});
            $mcctProjectReviewPageManagement.find('.dataTables_paginate a').mouseup(selectNone);
            $mcctProjectReviewPageManagement.find('.dataTables_length select').change(selectNone);

            function selectNone() {
                $mcctProjectReviewPageManagement.find('input.selected-element:checked').prop('checked', false).change();
            }
        }

        function applyCheckboxListeners() {
             $('input.selected-element', '#mcct_project_review_page_management').on('change', function(event) {
                 managementModel.updateSelection({}, event);
             });
        }

        // Initialize page once it's ready
        var keepTrying = setInterval(function () {
            if (window.reportTables !== undefined) {
                clearInterval(keepTrying);
                applyBindings();
                applyCheckboxListeners();
                window.reportTables.fnDrawCallback = applyCheckboxListeners;
            }
        }, 1000);

        // Initialize help templates
        $('.hq-help-template').each(function () {
            hqImport("hqwebapp/js/main").transformHelpTemplate($(this), true);
        });

        // Initialize date range
        var $datespan = $('#filter_range');
        if ($datespan.length) {
            var separator = $datespan.data('separator');
            var report_labels = $datespan.data("report-labels");
            var standardHQReport = hqImport("reports/js/standard_hq_report").getStandardHQReport();

            $('#filter_range').createDateRangePicker(report_labels, separator);
            $('#filter_range').on('apply', function(ev, picker) {
                var dates = $(this).val().split(separator);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
            });
        }
    });
});
<commit_msg>Fixed syntax error<commit_after>hqDefine("m4change/javascripts/main", function () {
    var initialPageData = hqImport("hqwebapp/js/initial_page_data");
    $(function () {
        var OPTIONS = {
            users: initialPageData.get("users"),
            groups: initialPageData.get("groups"),
            receiverUrl: initialPageData.reverse('receiver_secure_post'),
            enddate: initialPageData.get("end_date"),
            webUserID: initialPageData.get("user_id"),
            domain: initialPageData.get("domain"),
        };

        var managementModel = new McctProjectReviewPageManagement(OPTIONS);
        function applyBindings() {
            var $mcctProjectReviewPageManagement = $('#mcct_project_review_page_management');
            var element = $mcctProjectReviewPageManagement[0];
            element.koApplyBindings(managementModel);

            $mcctProjectReviewPageManagement.find('a.select-all').click(function () {
                $mcctProjectReviewPageManagement.find('input.selected-element').prop('checked', true).change();
                return false;
            });

            $mcctProjectReviewPageManagement.find('a.select-none').click(function() {selectNone(); return false;});
            $mcctProjectReviewPageManagement.find('.dataTables_paginate a').mouseup(selectNone);
            $mcctProjectReviewPageManagement.find('.dataTables_length select').change(selectNone);

            function selectNone() {
                $mcctProjectReviewPageManagement.find('input.selected-element:checked').prop('checked', false).change();
            }
        }

        function applyCheckboxListeners() {
             $('input.selected-element', '#mcct_project_review_page_management').on('change', function(event) {
                 managementModel.updateSelection({}, event);
             });
        }

        // Initialize page once it's ready
        var keepTrying = setInterval(function () {
            if (window.reportTables !== undefined) {
                clearInterval(keepTrying);
                applyBindings();
                applyCheckboxListeners();
                window.reportTables.fnDrawCallback = applyCheckboxListeners;
            }
        }, 1000);

        // Initialize help templates
        $('.hq-help-template').each(function () {
            hqImport("hqwebapp/js/main").transformHelpTemplate($(this), true);
        });

        // Initialize date range
        var $datespan = $('#filter_range');
        if ($datespan.length) {
            var separator = $datespan.data('separator');
            var report_labels = $datespan.data("report-labels");
            var standardHQReport = hqImport("reports/js/standard_hq_report").getStandardHQReport();

            $('#filter_range').createDateRangePicker(report_labels, separator);
            $('#filter_range').on('apply', function(ev, picker) {
                var dates = $(this).val().split(separator);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
            });
        }
    });
});
<|endoftext|>


<commit_before>(function () {

var adaptive = angular.module('adaptive.scroll', []);

adaptive.factory('$gyroscope', ['$rootScope', function ($rootScope) {

  var alphaStart, betaStart, gammaStart;
  var alpha, beta, gamma;
  var trashold = 20;
  var active;

  window.ondevicemotion = function(event) {
var ax = event.accelerationIncludingGravity.x;
var ay = event.accelerationIncludingGravity.y;
var az = event.accelerationIncludingGravity.z;
var rotation = event.rotationRate;
console.log(ax);
console.log(ay);
console.log(az);
console.log(rotation);
if (rotation != null) {
  var arAlpha = Math.round(rotation.alpha);
  var arBeta = Math.round(rotation.beta);
  var arGamma = Math.round(rotation.gamma);
  console.log(arAlpha);
  console.log(arBeta);
  console.log(arGamma);

}
  };

  window.ondeviceorientation = function(event) {
    alert('ondeviceorientation');
    alpha = Math.round(event.alpha);
    beta = Math.round(event.beta);
    gamma = Math.round(event.gamma);

    if (active && !alphaStart && !betaStart && !gammaStart) {
      alphaStart = alpha;
      betaStart = beta;
      gammaStart = gamma;
    }

    console.log(alpha, beta, gamma);
    console.log(Math.abs(alphaStart - alpha), Math.abs(betaStart - beta), Math.abs(gammaStart - gamma));
    console.log(Math.abs(alphaStart - alpha) > trashold, Math.abs(betaStart - beta) > trashold, Math.abs(gammaStart - gamma) > trashold);

    if (active) {
      if ((Math.abs(alphaStart - alpha) > trashold) || (Math.abs(betaStart - beta) > trashold) || (Math.abs(gammaStart - gamma) > trashold)) {
        sendEvent();
      }
      else {
        sendEvent(0,0,0);
      }
    }
  };

  var sendEvent = function(a,b,c) {
    var alphaDiff = a || (alphaStart - alpha);
    var betaDiff = b || (betaStart - beta);
    var gammaDiff = c || (gammaStart - gamma);
    $rootScope.$broadcast('adaptive.scroll:deviceorientation', {'alphaDiff': alphaDiff, 'betaDiff': betaDiff, 'gammaDiff': gammaDiff});
  };

  var watchPosition = function(degrees) {
    console.log('w', degrees);
    trashold = degrees || trashold;
    active = true;
  };

  var ignorePosition = function() {
    active = false;
    sendEvent(0,0,0);
  };

  return {
    watchPosition: function(degrees) {
      console.log('rw', degrees);
      watchPosition(degrees);
    },
    ignorePosition: function() {
      ignorePosition();
    }
  };

}]);

adaptive.directive('adaptivescroll', ['$rootScope', function ($rootScope) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var getOptions = function () {
        return angular.extend({}, scope.$eval(attrs.adaptivescroll));
      };
      var opts = getOptions();
      console.log(opts);

      window.requestAnimationFrame = (function(){
        return  window.requestAnimationFrame       ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame    ||
                function( callback ){
                  window.setTimeout(callback, 1000 / 60);
                };
      })();

      var alphaDiff = 0;
      var betaDiff = 0;
      var gammaDiff = 0;

      var scroll = function() {
        if (alphaDiff || betaDiff) {
          element[0].scrollTop = element[0].scrollTop + alphaDiff;
          element[0].scrollLeft = element[0].scrollLeft + betaDiff;
        }
        window.requestAnimationFrame(scroll);
      };

      window.requestAnimationFrame(scroll);

      $rootScope.$on('adaptive.scroll:deviceorientation', function(e, data){

        alphaDiff = data.alphaDiff;
        betaDiff = data.betaDiff;
        gammaDiff = data.gammaDiff;

        console.log('received', {'alphaDiff': alphaDiff, 'betaDiff': betaDiff, 'gammaDiff': gammaDiff});

      });

    }
  };
}]);

})();<commit_msg>rotate right axes, requestAnimationFrame start after start clicked, cancel event<commit_after>(function () {

var adaptive = angular.module('adaptive.scroll', []);

adaptive.factory('$gyroscope', ['$rootScope', function ($rootScope) {

  var alphaStart, betaStart, gammaStart;
  var alpha, beta, gamma;
  var trashold = 20;
  var active;

  window.ondeviceorientation = function(event) {
    console.log(event);
    if (!active) {
      return false;
    }

    alpha = Math.round(event.alpha);
    beta = Math.round(event.beta);
    gamma = Math.round(event.gamma);

    if (!alphaStart && !betaStart && !gammaStart) {
      alphaStart = alpha;
      betaStart = beta;
      gammaStart = gamma;
    }

    console.log('starting', alphaStart, betaStart, gammaStart);
    console.log('current', alpha, beta, gamma);
    console.log('diff', Math.abs(alphaStart - alpha), Math.abs(betaStart - beta), Math.abs(gammaStart - gamma));
    console.log('passed trashold: ' + trashold, Math.abs(alphaStart - alpha) > trashold, Math.abs(betaStart - beta) > trashold, Math.abs(gammaStart - gamma) > trashold);

    if ((Math.abs(alphaStart - alpha) > trashold) || (Math.abs(betaStart - beta) > trashold) || (Math.abs(gammaStart - gamma) > trashold)) {
      sendEvent();
    }
  };

  var sendEvent = function(a,b,c) {
    var alphaDiff = a || (alphaStart - alpha);
    var betaDiff = b || (betaStart - beta);
    var gammaDiff = c || (gammaStart - gamma);
    $rootScope.$broadcast('adaptive.scroll:deviceorientation', {'event': 'ondeviceorientation', 'alphaDiff': alphaDiff, 'betaDiff': betaDiff, 'gammaDiff': gammaDiff});
  };

  var startEvent = function() {
        $rootScope.$broadcast('adaptive.scroll:deviceorientation', {'event': 'ondeviceorientationstart'});
  };

  var stopEvent = function() {
        $rootScope.$broadcast('adaptive.scroll:deviceorientation', {'event': 'ondeviceorientationstop'});
  };

  var watchPosition = function(degrees) {
    console.log('trashold', degrees);
    trashold = degrees || trashold;
    active = true;
  };

  var ignorePosition = function() {
    active = false;
    stopEvent();
  };

  return {
    watchPosition: function(degrees) {
      watchPosition(degrees);
    },
    ignorePosition: function() {
      ignorePosition();
    }
  };

}]);

adaptive.directive('adaptivescroll', ['$rootScope', function ($rootScope) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var getOptions = function () {
        return angular.extend({}, scope.$eval(attrs.adaptivescroll));
      };
      var opts = getOptions();
      console.log(opts);

      (function() {
        var lastTime = 0;
        var vendors = ['webkit', 'moz'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame =
              window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
      }());

      var alphaDiff = 0;
      var betaDiff = 0;
      var gammaDiff = 0;
      var requestId;

      var scroll = function() {
        if (alphaDiff || betaDiff) {
          element[0].scrollTop = element[0].scrollTop + betaDiff;
          element[0].scrollLeft = element[0].scrollLeft + gammaDiff;
        }
        requestId = window.requestAnimationFrame(scroll);
      };

      $rootScope.$on('adaptive.scroll:deviceorientation', function(e, data){

        console.log('received', data);

        if (data.event == 'ondeviceorientation') {
          alphaDiff = data.alphaDiff;
          betaDiff = data.betaDiff;
          gammaDiff = data.gammaDiff;
        }

        if (data.event == 'ondeviceorientation' && !requestId) {
          requestId = window.requestAnimationFrame(scroll);
        }

        if (data.event == 'ondeviceorientationstop' && requestId) {
          window.cancelAnimationFrame(requestId);
          requestId = null;
        }

      });

    }
  };
}]);

})();<|endoftext|>


<commit_before>import styles from './Footer.less';

import React from 'react';
import Link from 'Link/Link';

const Footer = () => (

      {'Crafted with love by '}
      <Link
        className={styles.link}
        href="https://twitter.com/moroshko"
        underline={false}
      >
        @moroshko
      </Link>

      {'Page design by '}
      <Link
        className={styles.link}
        href="https://twitter.com/ThatBaldUXGuy"
        underline={false}
      >
        @thatbalduxguy
      </Link>

      {'Licensed under '}
      <Link
        className={styles.link}
        href="http://moroshko.mit-license.org/"
        underline={false}
      >
        MIT license
      </Link>

);

export default Footer;
<commit_msg>Update Vedran's twitter account (#302)<commit_after>import styles from './Footer.less';

import React from 'react';
import Link from 'Link/Link';

const Footer = () => (

      {'Crafted with love by '}
      <Link
        className={styles.link}
        href="https://twitter.com/moroshko"
        underline={false}
      >
        @moroshko
      </Link>

      {'Page design by '}
      <Link
        className={styles.link}
        href="https://twitter.com/vedranio"
        underline={false}
      >
        @thatbalduxguy
      </Link>

      {'Licensed under '}
      <Link
        className={styles.link}
        href="http://moroshko.mit-license.org/"
        underline={false}
      >
        MIT license
      </Link>

);

export default Footer;
<|endoftext|>


<commit_before>angular.module('codeine').filter('nodesFilter', [ '$log', function($log) {
    return function(nodes, query, monitor, tags) {
        $log.debug("nodesFilter: got " + nodes.length + " nodes, query = '" + query  + "' , monitor = '" + monitor + "' , tags = " + angular.toJson(tags));
        var res = [];
        for (var i=0; i < nodes.length ; i++) {
            if (showByName(query, nodes[i].node_alias) && showByMonitor(monitor, nodes[i].failed_monitors) && showByTags(tags,nodes[i].tags))
                res.push(nodes[i]);
        }
        return res;
    };
}]);

var showByName = function(query,node_name) {
    if (!query)
        return true;
    return node_name.indexOf(query) !== -1;
}

var showByMonitor = function(selectedMonitor,monitors) {
    if (selectedMonitor === 'All Nodes')
        return true;

    if (selectedMonitor === 'Any Alert')
        return monitors.length > 0;

    return monitors.indexOf(selectedMonitor) !== -1;
}

var showByTags = function(tags,nodeTags) {
    for (var i=0; i < tags.length ; i++) {
        if (!tags[i].state) {
            continue;
        }
        if (tags[i].state === 1) {
            if (nodeTags.indexOf(tags[i].name) === -1)
                return false;
        } else {
            if (nodeTags.indexOf(tags[i].name) !== -1)
                return false;
        }
    }
    return true;
}<commit_msg>removed log from filter<commit_after>angular.module('codeine').filter('nodesFilter', [ '$log', function($log) {
    return function(nodes, query, monitor, tags) {
        var startTime = new Date();
        var res = [];
        for (var i=0; i < nodes.length ; i++) {
            if (showByName(query, nodes[i].node_alias) && showByMonitor(monitor, nodes[i].failed_monitors) && showByTags(tags,nodes[i].tags))
                res.push(nodes[i]);
        }
        var endtime = new Date();
        $log.debug("nodesFilter: took " + startTime.getTime() - endtime.getTime() + " ms");
        return res;
    };
}]);

var showByName = function(query,node_name) {
    if (!query)
        return true;
    return node_name.indexOf(query) !== -1;
}

var showByMonitor = function(selectedMonitor,monitors) {
    if (selectedMonitor === 'All Nodes')
        return true;

    if (selectedMonitor === 'Any Alert')
        return monitors.length > 0;

    return monitors.indexOf(selectedMonitor) !== -1;
}

var showByTags = function(tags,nodeTags) {
    for (var i=0; i < tags.length ; i++) {
        if (!tags[i].state) {
            continue;
        }
        if (tags[i].state === 1) {
            if (nodeTags.indexOf(tags[i].name) === -1)
                return false;
        } else {
            if (nodeTags.indexOf(tags[i].name) !== -1)
                return false;
        }
    }
    return true;
}<|endoftext|>


<commit_before>const fs = require('fs');
var storage_conn = require('../obj_storage/pkg_cloud_storage_conn.js')
var watson_conn = require('./watson_vr_conn.js')
var variables = require("../config/variables.js").variables

/*
Call to create custom classifier
storage_conn.getContainerFiles(variables.container)
.then((files) => storage_conn.prepareDownloadStreams(files))
.then(()=> watson_conn.prepareTrainingStreams())
.then((params) => watson_conn.createCustomClassifier(params))
*/

var classifier_params = {
  //images_file: fs.createReadStream(variables.test_file),
  images_file: fs.createReadStream(variables.test_zip_file),
  threshold: variables.threshold,
  classifier_ids: variables.classifier_id
};
watson_conn.classifyObjects(classifier_params);

<commit_msg>Refactoring code for easy reuse<commit_after>const fs = require('fs');
var storage_conn = require('../obj_storage/pkg_cloud_storage_conn.js')
var watson_conn = require('./watson_vr_conn.js')
var variables = require("../config/variables.js").variables

/*
Call to create custom classifier
storage_conn.getContainerFiles(variables.container)
.then((files) => storage_conn.prepareDownloadStreams(files))
.then(()=> watson_conn.prepareTrainingStreams())
.then((params) => watson_conn.createCustomClassifier(params))
*/

var classifier_params = {
  //images_file: fs.createReadStream(variables.test_file),
  images_file: fs.createReadStream(variables.test_zip_file),
  threshold: variables.threshold,
  classifier_ids: variables.classifier_id
};
watson_conn.classifyObjects(classifier_params);

<|endoftext|>