<commit_before>/**
 * MatrixModel, a square matrix representation.
 *
 * We don't inherit from ListModel or VectorModel since they're compact
 * representations, but this class is supposed to handle extremely sparse
 * matrices. So, we're defining and maintaining our own arrays.
 *
 * @return MatrixModel
 * @author Erik E. Lorenz <erik.e.lorenz@gmail.com>
 * @license MIT License
 * @see LICENSE
 */
define(['lib/extend', './model'], function(extend, Model) {
  /**
   * Constructor
   *
   * @param size
   *          size of the matrix. defaults to 0
   */
  function MatrixModel(size) {
    MatrixModel.superconstructor.call(this);

    this.data = [];
    this.length = Math.max(0, size || 0);

    return this;
  }
  extend(MatrixModel, Model);

  MatrixModel.prototype.EVENTS = {
    'resize': true
  };

  /**
   * removes the rows and cols associated with the index from the matrix
   *
   * @param index
   *          {Integer} index
   * @return {MatrixModel} this
   */
  MatrixModel.prototype.remove = function(index) {
    if (index >= this.length || index < 0) {
      return this;
    }

    this.data.splice(index, 1);
    this.data.forEach(function(b) {
      b.splice(index, 1);
    });

    this.length -= 1;

    this.emit('resize');

    return this;
  };

  /**
   * resizes the matrix while taking care of
   *
   * @param size
   *          the new size
   * @return this on success, undefined otherwise
   */
  MatrixModel.prototype.resize = function(size) {
    if (size === undefined) {
      return undefined;
    }
    if (size < 0) {
      size = 0;
    }

    if (this.length > size) {
      this.data.splice(size);

      this.data.forEach(function(row) {
        row.splice(size);
      });
    }

    this.length = size;

    this.emit('resize');

    return this;
  };

  /**
   * retrieves the value from the given indices.
   *
   * @param row
   *          vertical position
   * @param col
   *          horizontal position
   * @return value at (row, col). Defaults to 0
   */
  MatrixModel.prototype.get = function(row, col) {
    if (Math.min(row, col) < 0 || Math.max(row, col) >= this.length) {
      console.warn('MatrixModel.get(): out of bounds');
      return undefined;
    }
    if (!this.data[row]) {
      return 0;
    }

    return this.data[row][col] || 0;
  };

  /**
   * sets the value at the given indices and allocates/frees the cell/row if
   * possible
   *
   * @param row
   *          vertical position
   * @param col
   *          horizontal position
   * @param value
   *          integer value to store in position (row, col)
   * @return {MatrixModel} this
   */
  MatrixModel.prototype.set = function(row, col, value) {
    var rowref;

    if (Math.min(row, col) < 0 || Math.max(row, col) >= this.length) {
      console.warn('MatrixModel.set(): out of bounds');
      return undefined;
    }

    rowref = this.data[row];

    if (value) {
      if (!rowref) {
        rowref = this.data[row] = [];
      }
      rowref[col] = value;
    } else if (rowref) {
      delete rowref[col];
    }

    return this;
  };

  /**
   * write the main diagonal elements to a vector
   *
   * @param vector
   *          a VectorModel instance to write the results to
   * @return vector on success, undefined otherwise
   */
  MatrixModel.prototype.diagonal = function(vector) {
    var index;

    vector.resize(this.length);

    for (index = 0; index < vector.length; index += 1) {
      vector.set(index, this.get(index, index));
    }

    return vector;
  };

  /**
   * perform a Matrix*Vector multiplication and store the results in the
   * provided output vector
   *
   * @param outVec
   *          the output vector
   * @param vec
   *          the input vector
   * @return outVec on success, containing this*vec. undefined otherwise.
   */
  MatrixModel.prototype.multVector = function(outVec, vec) {
    var row, col, sum;

    if (vec.length !== this.length) {
      console.warn('MatrixModel.multVector: different input lengths: '
          + this.length + '<>' + vec.length);
      return undefined;
    }

    outVec.resize(vec.length);

    for (row = 0; row < outVec.length; row += 1) {
      sum = 0;

      for (col = 0; col < outVec.length; col += 1) {
        sum += this.get(row, col) * vec.get(col);
      }

      outVec.set(row, sum);
    }

    return outVec;
  };

  /**
   * perform a Vector*Matrix multiplication and store the results in the
   * provided output vector
   *
   * @param outVec
   *          the output vector
   * @param vec
   *          the input vector
   * @return outVec on success, containing this*vec. undefined otherwise.
   */
  MatrixModel.prototype.vectorMult = function(outVec, vec) {
    var row, col, sum;

    if (vec.length !== this.length) {
      console.warn('MatrixModel.multVector: different input lengths: '
          + this.length + '<>' + vec.length);
      return undefined;
    }

    outVec.resize(vec.length);

    for (col = 0; col < outVec.length; col += 1) {
      sum = 0;

      for (row = 0; row < outVec.length; row += 1) {
        sum += this.get(row, col) * vec.get(row);
      }

      outVec.set(col, sum);
    }

    return outVec;
  };

  /**
   * set all elements in the matrix to the same value.
   *
   * In AntisymmetricMatrixModel, the superdiagonal elements will be inverted,
   * while the diagonal elements will equal the value.
   *
   * @param value
   *          Optional. The value. Defaults to 0.
   */
  MatrixModel.prototype.fill = function(value) {
    var row, col;
    value = value || 0;

    if (value === 0) {
      // discard all data, since get() defaults to 0.
      this.data.splice(0);
    } else {
      /*
       * Since we don't know about the data mapping, we cannot simply copy data
       * across this.data. Instead, we just iterate over this.set().
       */
      for (row = 0; row < this.length; row += 1) {
        for (col = 0; col < this.length; col += 1) {
          this.set(row, col, value);
        }
      }
    }
  };

  /**
   * prepare a readonly, nonreferencing, serializable data object, representing
   * the matrix
   *
   * @return a serializable data object
   */
  MatrixModel.prototype.save = function() {
    var data = MatrixModel.superclass.save.call(this);

    data.mat = this.data.map(function(row) {
      return row.map(function(cell) {
        return cell || 0;
      });
    }, this);
    data.l = this.length;

    return data;
  };

  MatrixModel.prototype.restore = function(data) {
    if (MatrixModel.superclass.restore.call(this, data)) {
      return false;
    }

    this.resize(0);
    this.mat.splice(0);

    this.resize(data.l);
    data.mat.forEach(function(row, rowindex) {
      this.data[rowindex] = row.slice();
    }, this);

    return true;
  };

  MatrixModel.prototype.SAVEFORMAT = Object
      .create(MatrixModel.superclass.SAVEFORMAT);
  MatrixModel.prototype.SAVEFORMAT.mat = [[Number]];
  MatrixModel.prototype.SAVEFORMAT.l = Number;

  return MatrixModel;
});
<commit_msg>MatrixModel: using run length encoding (RLE)<commit_after>/**
 * MatrixModel, a square matrix representation.
 *
 * We don't inherit from ListModel or VectorModel since they're compact
 * representations, but this class is supposed to handle extremely sparse
 * matrices. So, we're defining and maintaining our own arrays.
 *
 * @return MatrixModel
 * @author Erik E. Lorenz <erik.e.lorenz@gmail.com>
 * @license MIT License
 * @see LICENSE
 */
define(['lib/extend', './model', './rle'], function(extend, Model, RLE) {
  /**
   * Constructor
   *
   * @param size
   *          size of the matrix. defaults to 0
   */
  function MatrixModel(size) {
    MatrixModel.superconstructor.call(this);

    this.data = [];
    this.length = Math.max(0, size || 0);

    return this;
  }
  extend(MatrixModel, Model);

  MatrixModel.prototype.EVENTS = {
    'resize': true
  };

  /**
   * removes the rows and cols associated with the index from the matrix
   *
   * @param index
   *          {Integer} index
   * @return {MatrixModel} this
   */
  MatrixModel.prototype.remove = function(index) {
    if (index >= this.length || index < 0) {
      return this;
    }

    this.data.splice(index, 1);
    this.data.forEach(function(b) {
      b.splice(index, 1);
    });

    this.length -= 1;

    this.emit('resize');

    return this;
  };

  /**
   * resizes the matrix while taking care of
   *
   * @param size
   *          the new size
   * @return this on success, undefined otherwise
   */
  MatrixModel.prototype.resize = function(size) {
    if (size === undefined) {
      return undefined;
    }
    if (size < 0) {
      size = 0;
    }

    if (this.length > size) {
      this.data.splice(size);

      this.data.forEach(function(row) {
        row.splice(size);
      });
    }

    this.length = size;

    this.emit('resize');

    return this;
  };

  /**
   * retrieves the value from the given indices.
   *
   * @param row
   *          vertical position
   * @param col
   *          horizontal position
   * @return value at (row, col). Defaults to 0
   */
  MatrixModel.prototype.get = function(row, col) {
    if (Math.min(row, col) < 0 || Math.max(row, col) >= this.length) {
      console.warn('MatrixModel.get(): out of bounds');
      return undefined;
    }
    if (!this.data[row]) {
      return 0;
    }

    return this.data[row][col] || 0;
  };

  /**
   * sets the value at the given indices and allocates/frees the cell/row if
   * possible
   *
   * @param row
   *          vertical position
   * @param col
   *          horizontal position
   * @param value
   *          integer value to store in position (row, col)
   * @return {MatrixModel} this
   */
  MatrixModel.prototype.set = function(row, col, value) {
    var rowref;

    if (Math.min(row, col) < 0 || Math.max(row, col) >= this.length) {
      console.warn('MatrixModel.set(): out of bounds');
      return undefined;
    }

    rowref = this.data[row];

    if (value) {
      if (!rowref) {
        rowref = this.data[row] = [];
      }
      rowref[col] = value;
    } else if (rowref) {
      delete rowref[col];
    }

    return this;
  };

  /**
   * write the main diagonal elements to a vector
   *
   * @param vector
   *          a VectorModel instance to write the results to
   * @return vector on success, undefined otherwise
   */
  MatrixModel.prototype.diagonal = function(vector) {
    var index;

    vector.resize(this.length);

    for (index = 0; index < vector.length; index += 1) {
      vector.set(index, this.get(index, index));
    }

    return vector;
  };

  /**
   * perform a Matrix*Vector multiplication and store the results in the
   * provided output vector
   *
   * @param outVec
   *          the output vector
   * @param vec
   *          the input vector
   * @return outVec on success, containing this*vec. undefined otherwise.
   */
  MatrixModel.prototype.multVector = function(outVec, vec) {
    var row, col, sum;

    if (vec.length !== this.length) {
      console.warn('MatrixModel.multVector: different input lengths: '
          + this.length + '<>' + vec.length);
      return undefined;
    }

    outVec.resize(vec.length);

    for (row = 0; row < outVec.length; row += 1) {
      sum = 0;

      for (col = 0; col < outVec.length; col += 1) {
        sum += this.get(row, col) * vec.get(col);
      }

      outVec.set(row, sum);
    }

    return outVec;
  };

  /**
   * perform a Vector*Matrix multiplication and store the results in the
   * provided output vector
   *
   * @param outVec
   *          the output vector
   * @param vec
   *          the input vector
   * @return outVec on success, containing this*vec. undefined otherwise.
   */
  MatrixModel.prototype.vectorMult = function(outVec, vec) {
    var row, col, sum;

    if (vec.length !== this.length) {
      console.warn('MatrixModel.multVector: different input lengths: '
          + this.length + '<>' + vec.length);
      return undefined;
    }

    outVec.resize(vec.length);

    for (col = 0; col < outVec.length; col += 1) {
      sum = 0;

      for (row = 0; row < outVec.length; row += 1) {
        sum += this.get(row, col) * vec.get(row);
      }

      outVec.set(col, sum);
    }

    return outVec;
  };

  /**
   * set all elements in the matrix to the same value.
   *
   * In AntisymmetricMatrixModel, the superdiagonal elements will be inverted,
   * while the diagonal elements will equal the value.
   *
   * @param value
   *          Optional. The value. Defaults to 0.
   */
  MatrixModel.prototype.fill = function(value) {
    var row, col;
    value = value || 0;

    if (value === 0) {
      // discard all data, since get() defaults to 0.
      this.data.splice(0);
    } else {
      /*
       * Since we don't know about the data mapping, we cannot simply copy data
       * across this.data. Instead, we just iterate over this.set().
       */
      for (row = 0; row < this.length; row += 1) {
        for (col = 0; col < this.length; col += 1) {
          this.set(row, col, value);
        }
      }
    }
  };

  /**
   * prepare a readonly, nonreferencing, serializable data object, representing
   * the matrix
   *
   * @return a serializable data object
   */
  MatrixModel.prototype.save = function() {
    var data, mat;

    data = MatrixModel.superclass.save.call(this);

    mat = this.data.map(function(row) {
      return row.map(function(cell) {
        return cell || 0;
      });
    }, this);

    data.mat = RLE.encode(mat);
    console.log(data.mat);

    return data;
  };

  MatrixModel.prototype.restore = function(data) {
    var mat;
    if (MatrixModel.superclass.restore.call(this, data)) {
      return false;
    }

    this.resize(0);

    mat = RLE.decode(data.mat);

    mat.forEach(function(row, rowindex) {
      this.data[rowindex] = row.slice();
    }, this);
    this.resize(this.data.length);

    return true;
  };

  MatrixModel.prototype.SAVEFORMAT = Object
      .create(MatrixModel.superclass.SAVEFORMAT);
  MatrixModel.prototype.SAVEFORMAT.mat = [[Number]];
  MatrixModel.prototype.SAVEFORMAT.l = Number;

  return MatrixModel;
});
<|endoftext|>


<commit_before>import {Platform} from 'react-native';
import {TabNavigator, StackNavigator, TabBarBottom} from 'react-navigation';

import HomeViewContainer from '../home/HomeViewContainer';
import PlayViewContainer from '../play/PlayViewContainer';
import GuideViewContainer from '../guide/GuideViewContainer';
import AboutViewContainer from '../about/AboutViewContainer';
import PlayDetailViewContainer from '../play/PlayDetailViewContainer';
import GuideDetailContainer from '../guide/GuideDetailContainer';
import ToolsViewContainer from '../tools/ToolsViewContainer';
import PDFView from '../../wdui/PDFView';
import BleView from '../ble/BleViewContainer';

const headerColor = '#384452';
const activeColor = '#fff';

// TabNavigator is nested inside StackNavigator
export const MainScreenNavigator = TabNavigator(
  {
    Home: {screen: HomeViewContainer},
    Play: {screen: PlayViewContainer},
    Guide: {screen: GuideViewContainer},
    Tools: {screen: ToolsViewContainer},
    About: {screen: AboutViewContainer}
  },
  {
    tabBarComponent: TabBarBottom,
    tabBarPosition: 'bottom',
    tabBarOptions: {
      ...Platform.select({
        android: {
          activeTintColor: activeColor,
          indicatorStyle: {backgroundColor: activeColor},
          style: {backgroundColor: headerColor}
        }
      })
    }
  });

MainScreenNavigator.navigationOptions = {
  headerTitleStyle: {color: activeColor},
  headerStyle: {
    backgroundColor: headerColor,
    elevation: 0 // disable header elevation when TabNavigator visible
  }
};

// Root navigator is a StackNavigator
const AppNavigator = StackNavigator({
  Home: {
    path: '/',
    screen: MainScreenNavigator
  },
  Play: {
    screen: PlayViewContainer,
    path: 'play/'
  },
  Guide: {
    path: 'play/',
    screen: GuideViewContainer
  },
  About: {
    path: 'about/',
    screen: AboutViewContainer
  },
  PlayDetailView: {
    path: 'play/:slug',
    screen: PlayDetailViewContainer
  },
  GuideDetailView: {
    path: 'play/category/:category',
    screen: GuideDetailContainer
  },
  ToolsView: {
    path: 'tools/',
    screen: ToolsViewContainer
  },
  PDFView: {
    path: 'tools/:source',
    screen: PDFView
  },
  BleView: {
    path: 'ble/',
    screen: BleView
  }
}, {
  navigationOptions: {
    headerTintColor: '#51c4fe',
    headerBackTitle: '后退',
    headerStyle: {backgroundColor: 'white'},
    headerTitleStyle: {alignSelf: 'center'}
  }
});

export default AppNavigator;
<commit_msg>[T] hidden guide view tabbar<commit_after>import {Platform} from 'react-native';
import {TabNavigator, StackNavigator, TabBarBottom} from 'react-navigation';

import HomeViewContainer from '../home/HomeViewContainer';
import PlayViewContainer from '../play/PlayViewContainer';
import GuideViewContainer from '../guide/GuideViewContainer';
import AboutViewContainer from '../about/AboutViewContainer';
import PlayDetailViewContainer from '../play/PlayDetailViewContainer';
import GuideDetailContainer from '../guide/GuideDetailContainer';
import ToolsViewContainer from '../tools/ToolsViewContainer';
import PDFView from '../../wdui/PDFView';
import BleView from '../ble/BleViewContainer';

const headerColor = '#384452';
const activeColor = '#fff';

// TabNavigator is nested inside StackNavigator
export const MainScreenNavigator = TabNavigator(
  {
    Home: {screen: HomeViewContainer},
    Play: {screen: PlayViewContainer},
    Tools: {screen: ToolsViewContainer},
    About: {screen: AboutViewContainer}
  },
  {
    tabBarComponent: TabBarBottom,
    tabBarPosition: 'bottom',
    tabBarOptions: {
      ...Platform.select({
        android: {
          activeTintColor: activeColor,
          indicatorStyle: {backgroundColor: activeColor},
          style: {backgroundColor: headerColor}
        }
      })
    }
  });

MainScreenNavigator.navigationOptions = {
  headerTitleStyle: {color: activeColor},
  headerStyle: {
    backgroundColor: headerColor,
    elevation: 0 // disable header elevation when TabNavigator visible
  }
};

// Root navigator is a StackNavigator
const AppNavigator = StackNavigator({
  Home: {
    path: '/',
    screen: MainScreenNavigator
  },
  Play: {
    screen: PlayViewContainer,
    path: 'play/'
  },
  Guide: {
    path: 'play/',
    screen: GuideViewContainer
  },
  About: {
    path: 'about/',
    screen: AboutViewContainer
  },
  PlayDetailView: {
    path: 'play/:slug',
    screen: PlayDetailViewContainer
  },
  GuideDetailView: {
    path: 'play/category/:category',
    screen: GuideDetailContainer
  },
  ToolsView: {
    path: 'tools/',
    screen: ToolsViewContainer
  },
  PDFView: {
    path: 'tools/:source',
    screen: PDFView
  },
  BleView: {
    path: 'ble/',
    screen: BleView
  }
}, {
  navigationOptions: {
    headerTintColor: '#51c4fe',
    headerBackTitle: '后退',
    headerStyle: {backgroundColor: 'white'},
    headerTitleStyle: {alignSelf: 'center'}
  }
});

export default AppNavigator;
<|endoftext|>


<commit_before>'use strict';

module.exports =

  /*
   * This directive expects proofreaderActivity, proofreaderActivity.concepts,
   * and processProofreaderActivityForm to be set in scope. The use cases here
   * are the create grammar activity and edit grammar activity controller
   * modules.
   */

/*@ngInject*/
function ProofreaderActivityFormCtrl (
  $scope, _, TopicCategoryService
) {
  $scope.concepts = {};

  TopicCategoryService.get().then(function (topicCategories) {
    $scope.topicCategories = topicCategories;
  });

  $scope.removeQuestionFromSet = function (qs) {
    if ($scope.proofreaderActivity.concepts) {
      $scope.proofreaderActivity.concepts = _.without(
        $scope.proofreaderActivity.concepts, qs
      );
    }
  };
  $scope.addAnotherQuestionToSet = function () {
    $scope.proofreaderActivity.concepts.push({});
  };
};
<commit_msg>rm unused code<commit_after>'use strict';

module.exports =

  /*
   * This directive expects proofreaderActivity, proofreaderActivity.concepts,
   * and processProofreaderActivityForm to be set in scope. The use cases here
   * are the create grammar activity and edit grammar activity controller
   * modules.
   */

/*@ngInject*/
function ProofreaderActivityFormCtrl (
) {
};
<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set, getPath = Ember.getPath, guidFor = Ember.guidFor;

var stateProperty = Ember.computed(function(key) {
  var parent = get(this, 'parentState');
  if (parent) {
    return get(parent, key);
  }
}).property();

var isEmptyObject = function(object) {
  for (var name in obj) {
    if (obj.hasOwnProperty(name)) { return false; }
  }

  return true;
};

DS.State = Ember.State.extend({
  isLoaded: stateProperty,
  isDirty: stateProperty,
  isSaving: stateProperty,
  isDeleted: stateProperty,
  isError: stateProperty,
  isNew: stateProperty,
  isValid: stateProperty,
  isPending: stateProperty,

  stateName: stateProperty
});

var cantLoadData = function() {
  // TODO: get the current state name
  throw "You cannot load data into the store when its associated model is in its current state";
};

var cantWaitOn = function(state) {
  return function() {
    throw "You cannot insert an object into an association while it is " + state;
  };
};

var isEmptyObject = function(obj) {
  for (var prop in obj) {
    if (!obj.hasOwnProperty(prop)) { continue; }
    return false;
  }

  return true;
};

var setProperty = function(manager, context) {
  var key = context.key, value = context.value;

  var model = get(manager, 'model'), type = model.constructor;
  var store = get(model, 'store');
  var data = get(model, 'data');

  data[key] = value;

  if (store) { store.hashWasUpdated(type, get(model, 'clientId')); }
};

// The waitingOn event shares common functionality
// between the different dirty states, but each is
// treated slightly differently. This method is exposed
// so that each implementation can invoke the common
// behavior, and then implement the behavior specific
// to the state.
var waitingOn = function(manager, object) {
  var model = get(manager, 'model'),
      pendingQueue = get(model, 'pendingQueue'),
      objectGuid = guidFor(object);

  pendingQueue[objectGuid] = true;

  var observer = function() {
    if (get(object, 'isLoaded')) {
      manager.send('doneWaitingOn', object);
      Ember.removeObserver(object, 'isLoaded', observer);
    }
  };

  Ember.addObserver(object, 'isLoaded', observer);
};

// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
//   record is loaded via `store.find`, `isLoaded` is false
//   until the adapter sets it. When a record is created locally,
//   its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
//   saved by the adapter. This includes records that have been
//   created (but not yet saved) or deleted.
// * isSaving: The record's transaction has been committed, but
//   the adapter has not yet acknowledged that the changes have
//   been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
//   is true and `isDirty` is true, the record is deleted locally
//   but the deletion was not yet persisted. When `isSaving` is
//   true, the change is in-flight. When both `isDirty` and
//   `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
//   local changes to the backend. This may also result in the
//   record having its `isValid` property become false if the
//   adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
//   did not yet report that it was successfully saved.
// * isValid: No client-side validations have failed and the
//   adapter did not report any server-side validation failures.
// * isPending: A record `isPending` when it belongs to an
//   association on another record and that record has not been
//   saved. A record in this state cannot be saved because it
//   lacks a "foreign key" that will be supplied by its parent
//   association when the parent record has been created. When
//   the adapter reports that the parent has saved, the
//   `isPending` property on all children will become `false`
//   and the transaction will try to commit the records.

// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
var DirtyState = DS.State.extend({
  stateName: null,
  initialState: 'unsaved',

  // FLAGS
  isDirty: true,

  // EVENTS
  willLoadData: cantLoadData,

  setProperty: setProperty,

  // SUBSTATES

  // When a record first becomes dirty, it is `unsaved`.
  // This means that there are local pending changes,
  // but they have not yet begun to be saved.
  unsaved: DS.State.extend({
    // TRANSITIONS
    enter: function(manager) {
      var stateName = get(this, 'stateName'),
          model = get(manager, 'model');

      model.withTransaction(function (t) {
        t.modelBecameDirty(stateName, model);
      });
    },

    exit: function(manager) {
      var model = get(manager, 'model');
      manager.send('notifyModel', model);
    },

    // EVENTS
    waitingOn: function(manager, object) {
      waitingOn(manager, object);
      manager.goToState('pending');
    },

    willCommit: function(manager) {
      manager.goToState('inFlight');
    }
  }),

  // Once a record has been handed off to the adapter to be
  // saved, it is in the 'in flight' state. Changes to the
  // record cannot be made during this window.
  inFlight: DS.State.extend({
    // FLAGS
    isSaving: true,

    // TRANSITIONS
    enter: function(manager) {
      var stateName = get(this, 'stateName'),
          model = get(manager, 'model');

      model.withTransaction(function (t) {
        t.modelBecameClean(stateName, model);
      });
    },

    // EVENTS
    didCommit: function(manager) {
      manager.goToState('loaded');
    },

    wasInvalid: function(manager, errors) {
      var model = get(manager, 'model');

      set(model, 'errors', errors);
      manager.goToState('invalid');
    }
  }),

  // If a record becomes associated with a newly created
  // parent record, it will be `pending` until the parent
  // record has successfully persisted. Once this happens,
  // this record can use the parent's primary key as its
  // foreign key.
  //
  // If the record's transaction had already started to
  // commit, the record will transition to the `inFlight`
  // state. If it had not, the record will transition to
  // the `unsaved` state.
  pending: DS.State.extend({
    // FLAGS
    isPending: true,

    // SUBSTATES

    // A pending record whose transaction has not yet
    // started to commit is in this state.
    start: DS.State.create({
      // EVENTS
      willCommit: function(manager) {
        manager.goToState('saving');
      },

      doneWaitingOn: function(manager, object) {
        var model = get(manager, 'model'),
            pendingQueue = get(model, 'pendingQueue'),
            objectGuid = guidFor(object);

        delete pendingQueue[objectGuid];

        if (isEmptyObject(pendingQueue)) {
          manager.goToState('unsaved');
        }
      }
    }),

    // A pending record whose transaction has started
    // to commit is in this state.
    saving: DS.State.create({
      // FLAGS
      isSaving: true,

      // EVENTS
      doneWaitingOn: function(manager, object) {
        var model = get(manager, 'model'),
            pendingQueue = get(model, 'pendingQueue'),
            objectGuid = guidFor(object);

        delete pendingQueue[objectGuid];

        if (isEmptyObject(pendingQueue)) {
          manager.goToState('inFlight');
        }
      }
    })
  }),

  // A record is in the `invalid` state when its client-side
  // invalidations have failed, or if the adapter has indicated
  // the the record failed server-side invalidations.
  invalid: DS.State.extend({
    // FLAGS
    isValid: false,

    // EVENTS
    setProperty: function(manager, context) {
      setProperty(manager, context);

      var model = get(manager, 'model'),
          errors = get(model, 'errors'),
          key = context.key;

      delete errors[key];

      if (isEmptyObject(errors)) {
        manager.send('becameValid');
      }
    },

    becameValid: function(manager) {
      manager.goToState('unsaved');
    }
  })
});

var states = {
  rootState: Ember.State.create({
    // FLAGS
    isLoaded: false,
    isDirty: false,
    isSaving: false,
    isDeleted: false,
    isError: false,
    isNew: false,
    isValid: true,
    isPending: false,

    // EVENTS
    willLoadData: cantLoadData,

    // SUBSTATES

    // A record begins its lifecycle in the `empty` state.
    // If its data will come from the adapter, it will
    // transition into the `loading` state. Otherwise, if
    // the record is being created on the client, it will
    // transition into the `created` state.
    empty: DS.State.create({
      // EVENTS
      loadingData: function(manager) {
        manager.goToState('loading');
      },

      didCreate: function(manager) {
        manager.goToState('loaded.created');
      }
    }),

    // A record enters this state when the store askes
    // the adapter for its data. It remains in this state
    // until the adapter provides the requested data.
    //
    // Usually, this process is asynchronous, using an
    // XHR to retrieve the data.
    loading: DS.State.create({
      // TRANSITIONS
      exit: function(manager) {
        var model = get(manager, 'model');
        model.didLoad();
      },

      // EVENTS
      willLoadData: Ember.K,
      waitingOn: cantWaitOn("loading"),

      setData: function(manager, data) {
        var model = get(manager, 'model');

        model.beginPropertyChanges();
        model.set('data', data);

        if (data !== null) {
          manager.send('loadedData');
        }

        model.endPropertyChanges();
      },

      loadedData: function(manager) {
        manager.goToState('loaded');
      }
    }),

    // A record enters this state when its data is populated.
    // Most of a record's lifecycle is spent inside substates
    // of the `loaded` state.
    loaded: DS.State.create({
      initialState: 'saved',

      // FLAGS
      isLoaded: true,

      // EVENTS
      willLoadData: Ember.K,

      setProperty: function(manager, context) {
        setProperty(manager, context);
        manager.goToState('updated');
      },

      deleteRecord: function(manager) {
        manager.goToState('deleted');
      },

      // SUBSTATES

      // If there are no local changes to a record, it remains
      // in the `saved` state.
      saved: DS.State.create({
        waitingOn: function(manager, object) {
          waitingOn(manager, object);
          manager.goToState('updated.pending');
        }
      }),

      // A record is in this state after it has been locally
      // created but before the adapter has indicated that
      // it has been saved.
      created: DirtyState.create({
        stateName: 'created',

        // FLAGS
        isNew: true,

        // EVENTS
        notifyModel: function(manager, model) {
          model.didCreate();
        }
      }),

      // A record is in this state if it has already been
      // saved to the server, but there are new local changes
      // that have not yet been saved.
      updated: DirtyState.create({
        stateName: 'updated',

        // EVENTS
        notifyModel: function(manager, model) {
          model.didUpdate();
        }
      })
    }),

    // A record is in this state if it was deleted from the store.
    deleted: DS.State.create({
      // FLAGS
      isDeleted: true,
      isLoaded: true,
      isDirty: true,

      // TRANSITIONS
      enter: function(manager) {
        var model = get(manager, 'model');
        var store = get(model, 'store');

        if (store) {
          store.removeFromModelArrays(model);
        }

        model.withTransaction(function(t) {
          t.modelBecameDirty('deleted', model);
        });
      },

      // EVENTS
      willLoadData: cantLoadData,

      // SUBSTATES

      // When a record is deleted, it enters the `start`
      // state. It will exit this state when the record's
      // transaction starts to commit.
      start: DS.State.create({
        willCommit: function(manager) {
          manager.goToState('saving');
        }
      }),

      // After a record's transaction is committing, but
      // before the adapter indicates that the deletion
      // has saved to the server, a record is in the
      // `saving` substate of `deleted`.
      saving: DS.State.create({
        // FLAGS
        isSaving: true,

        // TRANSITIONS
        exit: function(stateManager) {
          var model = get(stateManager, 'model');

          model.withTransaction(function(t) {
            t.modelBecameClean('deleted', model);
          });
        },

        // EVENTS
        didCommit: function(manager) {
          manager.goToState('saved');
        }
      }),

      // Once the adapter indicates that the deletion has
      // been saved, the record enters the `saved` substate
      // of `deleted`.
      saved: DS.State.create({
        isDirty: false
      })
    }),

    // If the adapter indicates that there was an unknown
    // error saving a record, the record enters the `error`
    // state.
    error: DS.State.create({
      isError: true
    })
  })
};

DS.StateManager = Ember.StateManager.extend({
  model: null,
  initialState: 'rootState',
  states: states
});
<commit_msg>Rename vague "notifyModel" event<commit_after>var get = Ember.get, set = Ember.set, getPath = Ember.getPath, guidFor = Ember.guidFor;

var stateProperty = Ember.computed(function(key) {
  var parent = get(this, 'parentState');
  if (parent) {
    return get(parent, key);
  }
}).property();

var isEmptyObject = function(object) {
  for (var name in obj) {
    if (obj.hasOwnProperty(name)) { return false; }
  }

  return true;
};

DS.State = Ember.State.extend({
  isLoaded: stateProperty,
  isDirty: stateProperty,
  isSaving: stateProperty,
  isDeleted: stateProperty,
  isError: stateProperty,
  isNew: stateProperty,
  isValid: stateProperty,
  isPending: stateProperty,

  stateName: stateProperty
});

var cantLoadData = function() {
  // TODO: get the current state name
  throw "You cannot load data into the store when its associated model is in its current state";
};

var cantWaitOn = function(state) {
  return function() {
    throw "You cannot insert an object into an association while it is " + state;
  };
};

var isEmptyObject = function(obj) {
  for (var prop in obj) {
    if (!obj.hasOwnProperty(prop)) { continue; }
    return false;
  }

  return true;
};

var setProperty = function(manager, context) {
  var key = context.key, value = context.value;

  var model = get(manager, 'model'), type = model.constructor;
  var store = get(model, 'store');
  var data = get(model, 'data');

  data[key] = value;

  if (store) { store.hashWasUpdated(type, get(model, 'clientId')); }
};

// The waitingOn event shares common functionality
// between the different dirty states, but each is
// treated slightly differently. This method is exposed
// so that each implementation can invoke the common
// behavior, and then implement the behavior specific
// to the state.
var waitingOn = function(manager, object) {
  var model = get(manager, 'model'),
      pendingQueue = get(model, 'pendingQueue'),
      objectGuid = guidFor(object);

  pendingQueue[objectGuid] = true;

  var observer = function() {
    if (get(object, 'isLoaded')) {
      manager.send('doneWaitingOn', object);
      Ember.removeObserver(object, 'isLoaded', observer);
    }
  };

  Ember.addObserver(object, 'isLoaded', observer);
};

// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
//   record is loaded via `store.find`, `isLoaded` is false
//   until the adapter sets it. When a record is created locally,
//   its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
//   saved by the adapter. This includes records that have been
//   created (but not yet saved) or deleted.
// * isSaving: The record's transaction has been committed, but
//   the adapter has not yet acknowledged that the changes have
//   been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
//   is true and `isDirty` is true, the record is deleted locally
//   but the deletion was not yet persisted. When `isSaving` is
//   true, the change is in-flight. When both `isDirty` and
//   `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
//   local changes to the backend. This may also result in the
//   record having its `isValid` property become false if the
//   adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
//   did not yet report that it was successfully saved.
// * isValid: No client-side validations have failed and the
//   adapter did not report any server-side validation failures.
// * isPending: A record `isPending` when it belongs to an
//   association on another record and that record has not been
//   saved. A record in this state cannot be saved because it
//   lacks a "foreign key" that will be supplied by its parent
//   association when the parent record has been created. When
//   the adapter reports that the parent has saved, the
//   `isPending` property on all children will become `false`
//   and the transaction will try to commit the records.

// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
var DirtyState = DS.State.extend({
  stateName: null,
  initialState: 'unsaved',

  // FLAGS
  isDirty: true,

  // EVENTS
  willLoadData: cantLoadData,

  setProperty: setProperty,

  // SUBSTATES

  // When a record first becomes dirty, it is `unsaved`.
  // This means that there are local pending changes,
  // but they have not yet begun to be saved.
  unsaved: DS.State.extend({
    // TRANSITIONS
    enter: function(manager) {
      var stateName = get(this, 'stateName'),
          model = get(manager, 'model');

      model.withTransaction(function (t) {
        t.modelBecameDirty(stateName, model);
      });
    },

    exit: function(manager) {
      var model = get(manager, 'model');
      manager.send('invokeLifecycleCallbacks', model);
    },

    // EVENTS
    waitingOn: function(manager, object) {
      waitingOn(manager, object);
      manager.goToState('pending');
    },

    willCommit: function(manager) {
      manager.goToState('inFlight');
    }
  }),

  // Once a record has been handed off to the adapter to be
  // saved, it is in the 'in flight' state. Changes to the
  // record cannot be made during this window.
  inFlight: DS.State.extend({
    // FLAGS
    isSaving: true,

    // TRANSITIONS
    enter: function(manager) {
      var stateName = get(this, 'stateName'),
          model = get(manager, 'model');

      model.withTransaction(function (t) {
        t.modelBecameClean(stateName, model);
      });
    },

    // EVENTS
    didCommit: function(manager) {
      manager.goToState('loaded');
    },

    wasInvalid: function(manager, errors) {
      var model = get(manager, 'model');

      set(model, 'errors', errors);
      manager.goToState('invalid');
    }
  }),

  // If a record becomes associated with a newly created
  // parent record, it will be `pending` until the parent
  // record has successfully persisted. Once this happens,
  // this record can use the parent's primary key as its
  // foreign key.
  //
  // If the record's transaction had already started to
  // commit, the record will transition to the `inFlight`
  // state. If it had not, the record will transition to
  // the `unsaved` state.
  pending: DS.State.extend({
    // FLAGS
    isPending: true,

    // SUBSTATES

    // A pending record whose transaction has not yet
    // started to commit is in this state.
    start: DS.State.create({
      // EVENTS
      willCommit: function(manager) {
        manager.goToState('saving');
      },

      doneWaitingOn: function(manager, object) {
        var model = get(manager, 'model'),
            pendingQueue = get(model, 'pendingQueue'),
            objectGuid = guidFor(object);

        delete pendingQueue[objectGuid];

        if (isEmptyObject(pendingQueue)) {
          manager.goToState('unsaved');
        }
      }
    }),

    // A pending record whose transaction has started
    // to commit is in this state.
    saving: DS.State.create({
      // FLAGS
      isSaving: true,

      // EVENTS
      doneWaitingOn: function(manager, object) {
        var model = get(manager, 'model'),
            pendingQueue = get(model, 'pendingQueue'),
            objectGuid = guidFor(object);

        delete pendingQueue[objectGuid];

        if (isEmptyObject(pendingQueue)) {
          manager.goToState('inFlight');
        }
      }
    })
  }),

  // A record is in the `invalid` state when its client-side
  // invalidations have failed, or if the adapter has indicated
  // the the record failed server-side invalidations.
  invalid: DS.State.extend({
    // FLAGS
    isValid: false,

    // EVENTS
    setProperty: function(manager, context) {
      setProperty(manager, context);

      var model = get(manager, 'model'),
          errors = get(model, 'errors'),
          key = context.key;

      delete errors[key];

      if (isEmptyObject(errors)) {
        manager.send('becameValid');
      }
    },

    becameValid: function(manager) {
      manager.goToState('unsaved');
    }
  })
});

var states = {
  rootState: Ember.State.create({
    // FLAGS
    isLoaded: false,
    isDirty: false,
    isSaving: false,
    isDeleted: false,
    isError: false,
    isNew: false,
    isValid: true,
    isPending: false,

    // EVENTS
    willLoadData: cantLoadData,

    // SUBSTATES

    // A record begins its lifecycle in the `empty` state.
    // If its data will come from the adapter, it will
    // transition into the `loading` state. Otherwise, if
    // the record is being created on the client, it will
    // transition into the `created` state.
    empty: DS.State.create({
      // EVENTS
      loadingData: function(manager) {
        manager.goToState('loading');
      },

      didCreate: function(manager) {
        manager.goToState('loaded.created');
      }
    }),

    // A record enters this state when the store askes
    // the adapter for its data. It remains in this state
    // until the adapter provides the requested data.
    //
    // Usually, this process is asynchronous, using an
    // XHR to retrieve the data.
    loading: DS.State.create({
      // TRANSITIONS
      exit: function(manager) {
        var model = get(manager, 'model');
        model.didLoad();
      },

      // EVENTS
      willLoadData: Ember.K,
      waitingOn: cantWaitOn("loading"),

      setData: function(manager, data) {
        var model = get(manager, 'model');

        model.beginPropertyChanges();
        model.set('data', data);

        if (data !== null) {
          manager.send('loadedData');
        }

        model.endPropertyChanges();
      },

      loadedData: function(manager) {
        manager.goToState('loaded');
      }
    }),

    // A record enters this state when its data is populated.
    // Most of a record's lifecycle is spent inside substates
    // of the `loaded` state.
    loaded: DS.State.create({
      initialState: 'saved',

      // FLAGS
      isLoaded: true,

      // EVENTS
      willLoadData: Ember.K,

      setProperty: function(manager, context) {
        setProperty(manager, context);
        manager.goToState('updated');
      },

      deleteRecord: function(manager) {
        manager.goToState('deleted');
      },

      // SUBSTATES

      // If there are no local changes to a record, it remains
      // in the `saved` state.
      saved: DS.State.create({
        waitingOn: function(manager, object) {
          waitingOn(manager, object);
          manager.goToState('updated.pending');
        }
      }),

      // A record is in this state after it has been locally
      // created but before the adapter has indicated that
      // it has been saved.
      created: DirtyState.create({
        stateName: 'created',

        // FLAGS
        isNew: true,

        // EVENTS
        invokeLifecycleCallbacks: function(manager, model) {
          model.didCreate();
        }
      }),

      // A record is in this state if it has already been
      // saved to the server, but there are new local changes
      // that have not yet been saved.
      updated: DirtyState.create({
        stateName: 'updated',

        // EVENTS
        invokeLifecycleCallbacks: function(manager, model) {
          model.didUpdate();
        }
      })
    }),

    // A record is in this state if it was deleted from the store.
    deleted: DS.State.create({
      // FLAGS
      isDeleted: true,
      isLoaded: true,
      isDirty: true,

      // TRANSITIONS
      enter: function(manager) {
        var model = get(manager, 'model');
        var store = get(model, 'store');

        if (store) {
          store.removeFromModelArrays(model);
        }

        model.withTransaction(function(t) {
          t.modelBecameDirty('deleted', model);
        });
      },

      // EVENTS
      willLoadData: cantLoadData,

      // SUBSTATES

      // When a record is deleted, it enters the `start`
      // state. It will exit this state when the record's
      // transaction starts to commit.
      start: DS.State.create({
        willCommit: function(manager) {
          manager.goToState('saving');
        }
      }),

      // After a record's transaction is committing, but
      // before the adapter indicates that the deletion
      // has saved to the server, a record is in the
      // `saving` substate of `deleted`.
      saving: DS.State.create({
        // FLAGS
        isSaving: true,

        // TRANSITIONS
        exit: function(stateManager) {
          var model = get(stateManager, 'model');

          model.withTransaction(function(t) {
            t.modelBecameClean('deleted', model);
          });
        },

        // EVENTS
        didCommit: function(manager) {
          manager.goToState('saved');
        }
      }),

      // Once the adapter indicates that the deletion has
      // been saved, the record enters the `saved` substate
      // of `deleted`.
      saved: DS.State.create({
        isDirty: false
      })
    }),

    // If the adapter indicates that there was an unknown
    // error saving a record, the record enters the `error`
    // state.
    error: DS.State.create({
      isError: true
    })
  })
};

DS.StateManager = Ember.StateManager.extend({
  model: null,
  initialState: 'rootState',
  states: states
});
<|endoftext|>


<commit_before>var express = require('express'),
    cons = require('consolidate'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    routes = require('./routes/index'),
    path = require('path'),
    bodyParser = require('body-parser');

var app = express();

app.set('view engine', 'ejs');
app.set('views', __dirname + "/views");
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', routes);

MongoClient.connect('mongodb://localhost:27017/league');

app.listen(8080);
console.log("Express server started on port 8080");
<commit_msg>adding configuration variables<commit_after>var express = require('express'),
    cons = require('consolidate'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    routes = require('./routes/index'),
    path = require('path'),
    bodyParser = require('body-parser');

var app = express();

app.set('view engine', 'ejs');
app.set('views', __dirname + "/views");
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', routes);

app.listen(8080);
console.log("Express server started on port 8080");
<|endoftext|>


<commit_before>// diff 2 collections

var coll1 = {
    dbname: 'ctml_ak81894_sd-dfc9-2176_2017_06_25_2200',
    coll: 'fxpgEvent',
    label: 'ctml1',
    keys: { usi: 1, tradeType: '$eventType' },
    key_mapping : {tradeType: 'eventType'}
};

var coll2 = {
    dbname: 'QControlData_FX_2606',
    coll: 'tradeEvent',
    label: 'ctml2',
    keys: { usi: 1, tradeType: 1 },
};

var target_dbname = coll2.dbname;
var target_coll = buildUniqueCollName(coll2.coll, coll2.label);
var work_dir = 'c:\\temp';
var keys = coll2.keys;

function find_unique(dbname: string, coll: string, side: string, keys) {
    var _db = db.getSiblingDB(dbname);
    var unique_coll = buildUniqueCollName(coll, side);
    var _id = _.mapValues(keys, (value, key, object) => '$' + key);
    _.assign(_id, { side: side })
    var cursor = _db.getCollection(coll).aggregate(
        [
            { $project: keys },
            { $group: { _id: _id } },
            { $out: unique_coll },
        ],
        {
            allowDiskUse: true
        }
    );
    cursor.toArray();
    console.log(_.template('unique record count for ${dbname}.${coll}: ${count}')
        ({
            'dbname': dbname,
            'coll': coll,
            'count': _db.getCollection(unique_coll).count()
        }));
}

function buildUniqueCollName(coll: string, side: string): string {
    return 'unique_' + coll + '_' + side;
}

function do_export() {
    var export_cmd = _.template('"${mongoexport}" --verbose --host ${mongo_server} -d "${dbname}" -c "${unique_coll}" --out "${work_dir}\\${unique_coll}.json"  --type json')
        ({
            mongoexport: 'C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongoexport',
            mongo_server: 'sd-dfc9-2176:27017',
            dbname: coll1.dbname,
            unique_coll: buildUniqueCollName(coll1.coll, coll1.label),
            work_dir: work_dir
        });
    console.log('running export command: ' + export_cmd);
    var export_output = shelljs.exec(export_cmd,
        { async: false, silent: false }
        );
    console.log('after export')
}

function do_import() {
    var import_cmd = _.template('"${mongoimport}" -v --host ${mongo_server} -d "${dbname}" -c "${target_coll}" --file "${work_dir}\\${unique_coll}.json"  --type json')
        ({
            mongoimport: 'C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongoimport',
            mongo_server: 'sd-dfc9-2176:27017',
            dbname: target_dbname,
            target_coll: buildUniqueCollName(coll2.coll, coll2.label),
            unique_coll: buildUniqueCollName(coll1.coll, coll1.label),
            work_dir: work_dir
        });
    console.log('running import command: ' + import_cmd);
    shelljs.exec(import_cmd, { async: false, silent: false });
    console.log('after export')
}

function minus(dbname, left, right, coll, keys) {
    console.log('calculating diff of ' + left.label + " and " + right.label);
    var diff_coll = "diff_" + left.label + "_" + right.label;
    var _db = db.getSiblingDB(dbname);
    var cursor;
    console.log('running diff');
    _db.getCollection(diff_coll).remove({})
    var _project = _.mapValues(keys, (value, key, object) => '$_id.' + key);
    _.assign(_project, { side: '$_id.side' })
    var _group = _.mapValues(keys, (value, key, object) => '$' + key);

    cursor =
        _db.getSiblingDB(dbname)
            .getCollection(coll)
            .aggregate(
            [
                { $project: _project },
                // { $group: { _id: { usi: '$usi', tradeType: '$tradeType' }, sides: { $addToSet: '$side' } } },
                { $group: { _id: _group, sides: { $addToSet: '$side' } } },
                { $project: { sides: '$sides', s: { $size: '$sides' } } },
                { $match: { s: 1, } },
                { $unwind: "$sides" },
                { $group: { _id: '$sides', usis: { $addToSet: '$_id' } } },
                { $out: diff_coll }
            ],
            { allowDiskUse: true }
            );
    cursor.toArray();

    // buildDifferenceCollection(_db, left, right, diff_coll);
    // buildDifferenceCollection(_db, right, left, diff_coll);
    console.log('done');
}

function buildDifferenceCollection(_db, left, right, diff_coll) {
    console.log('building difference collection: ' + left.label + " minus" + right.label);
    var coll_l_minus_r = left.label + "_minus_" + right.label;
    _db.getCollection(coll_l_minus_r).remove({})
    var cursor =
        _db.getCollection(diff_coll).aggregate([
            { $match: { _id: left.label } },
            { $unwind: "$usis" },
            { $group: { _id: { usi: '$usis.usi', tradeType: '$usis.tradeType' } } },
            { $out: coll_l_minus_r }
        ]);
    cursor.toArray();
}

function clean(dbname, left, right, target_coll) {
    var diff_coll = "diff_" + left.label + "_" + right.label;
    var _db = db.getSiblingDB(dbname);
    _db.getCollection(diff_coll).drop();
    _db.getCollection(left.label + "_minus_" + right.label).drop();
    _db.getCollection(right.label + "_minus_" + left.label).drop();
    _db.getCollection(target_coll).drop();
}

console.log('started');
// clean(target_dbname, coll1, coll2, target_coll);
// find_unique(coll1.dbname, coll1.coll, coll1.label, coll1.keys);
// find_unique(coll2.dbname, coll2.coll, coll2.label, coll2.keys);
// db.getSiblingDB(target_dbname).getCollection(target_coll).createIndex({ "_id.usi": 1 })
// do_export();
// do_import();
minus(target_dbname, coll1, coll2, target_coll, keys);
console.log('done');
<commit_msg>stricter types, generic key mapping<commit_after>// diff 2 collections

var coll1 = new MongoCollection('ctml_ak81894_sd-dfc9-2176_2017_06_25_2200', 'fxpgEvent', 'ctml1', {tradeType: 'eventType'});
var coll2 = new MongoCollection('QControlData_FX_2606', 'tradeEvent', 'ctml2', {});

class MongoCollection {
    dbname: string;
    coll: string;
    label: string;
    key_mapping:Object;

    constructor(dbname: string,
        coll: string,
        label: string,
        key_mapping: Object) {
        this.dbname = dbname;
        this.coll = coll;
        this.label = label;
        this.key_mapping = key_mapping;
    }
}
var target_dbname:string = coll2.dbname;
var target_coll = buildUniqueCollName(coll2);
var work_dir = 'c:\\temp';
var keys = { usi: 1, tradeType: 1 };

function find_unique(coll: MongoCollection, keys:Object) {
    var _db = db.getSiblingDB(coll.dbname);
    var unique_coll = buildUniqueCollName(coll);
    var _id = _.mapValues(_.defaults(coll.key_mapping, keys), (value, key, object) => '$' + key);
    _.assign(_id, { side: coll.side })
    var cursor = _db.getCollection(coll.coll).aggregate(
        [
            { $project: keys },
            { $group: { _id: _id } },
            { $out: unique_coll },
        ],
        {
            allowDiskUse: true
        }
    );
    cursor.toArray();
    console.log(_.template('unique record count for ${coll.dbname}.${coll.coll}: ${count}')
        ({
            'dbname': coll.dbname,
            'coll': coll.coll,
            'count': _db.getCollection(unique_coll).count()
        }));
}

function mapKeys(keys:Object, key_mapping:Object) {

}

function buildUniqueCollName(coll: MongoCollection): string {
    return 'unique_' + coll.coll + '_' + coll.side;
}

function do_export() {
    var export_cmd = _.template('"${mongoexport}" --verbose --host ${mongo_server} -d "${dbname}" -c "${unique_coll}" --out "${work_dir}\\${unique_coll}.json"  --type json')
        ({
            mongoexport: 'C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongoexport',
            mongo_server: 'sd-dfc9-2176:27017',
            dbname: coll1.dbname,
            unique_coll: buildUniqueCollName(coll1.coll, coll1.label),
            work_dir: work_dir
        });
    console.log('running export command: ' + export_cmd);
    var export_output = shelljs.exec(export_cmd,
        { async: false, silent: false }
        );
    console.log('after export')
}

function do_import() {
    var import_cmd = _.template('"${mongoimport}" -v --host ${mongo_server} -d "${dbname}" -c "${target_coll}" --file "${work_dir}\\${unique_coll}.json"  --type json')
        ({
            mongoimport: 'C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongoimport',
            mongo_server: 'sd-dfc9-2176:27017',
            dbname: target_dbname,
            target_coll: buildUniqueCollName(coll2.coll, coll2.label),
            unique_coll: buildUniqueCollName(coll1.coll, coll1.label),
            work_dir: work_dir
        });
    console.log('running import command: ' + import_cmd);
    shelljs.exec(import_cmd, { async: false, silent: false });
    console.log('after export')
}

function minus(dbname, left, right, coll, keys) {
    console.log('calculating diff of ' + left.label + " and " + right.label);
    var diff_coll = "diff_" + left.label + "_" + right.label;
    var _db = db.getSiblingDB(dbname);
    var cursor;
    console.log('running diff');
    _db.getCollection(diff_coll).remove({})
    var _project = _.mapValues(keys, (value, key, object) => '$_id.' + key);
    _.assign(_project, { side: '$_id.side' })
    var _group = _.mapValues(keys, (value, key, object) => '$' + key);

    cursor =
        _db.getSiblingDB(dbname)
            .getCollection(coll)
            .aggregate(
            [
                { $project: _project },
                // { $group: { _id: { usi: '$usi', tradeType: '$tradeType' }, sides: { $addToSet: '$side' } } },
                { $group: { _id: _group, sides: { $addToSet: '$side' } } },
                { $project: { sides: '$sides', s: { $size: '$sides' } } },
                { $match: { s: 1, } },
                { $unwind: "$sides" },
                { $group: { _id: '$sides', usis: { $addToSet: '$_id' } } },
                { $out: diff_coll }
            ],
            { allowDiskUse: true }
            );
    cursor.toArray();

    buildDifferenceCollection(_db, left, right, diff_coll);
    buildDifferenceCollection(_db, right, left, diff_coll);
    console.log('buiding diffrence collections done');
}

function buildDifferenceCollection(_db, left, right, diff_coll) {
    console.log('building difference collection: ' + left.label + " minus" + right.label);
    var coll_l_minus_r = left.label + "_minus_" + right.label;
    _db.getCollection(coll_l_minus_r).remove({})
    var cursor =
        _db.getCollection(diff_coll).aggregate([
            { $match: { _id: left.label } },
            { $unwind: "$usis" },
            { $group: { _id: { usi: '$usis.usi', tradeType: '$usis.tradeType' } } },
            { $out: coll_l_minus_r }
        ]);
    cursor.toArray();
}

function clean(dbname, left, right, target_coll) {
    var diff_coll = "diff_" + left.label + "_" + right.label;
    var _db = db.getSiblingDB(dbname);
    _db.getCollection(diff_coll).drop();
    _db.getCollection(left.label + "_minus_" + right.label).drop();
    _db.getCollection(right.label + "_minus_" + left.label).drop();
    _db.getCollection(target_coll).drop();
}

console.log('started');
clean(target_dbname, coll1, coll2, target_coll);
find_unique(coll1, keys);
find_unique(coll2, keys);
db.getSiblingDB(target_dbname).getCollection(target_coll).createIndex({ "_id.usi": 1 })
do_export();
do_import();
minus(target_dbname, coll1, coll2, target_coll, keys);
console.log('comparison done');
<|endoftext|>


<commit_before>var gpio = require("gpio");

var LED_PORT = 17, SWITCH_PORT = 25;

var ledPort = gpio.export(LED_PORT, {direction: 'out'});
var switchPort = gpio.export(SWITCH_PORT, {direction: 'in', interval:400});

switchPort.on('change', function(val){
    console.log("switch value: " + val);
    ledPort.set(val);
});

function ledOn(){
    port_17.set();
    setTimeout(ledOff, 1000);
}

function ledOff(){
    port_17.reset();
    setTimeout(ledOn, 1000);
}<commit_msg>testing gpio<commit_after>var gpio = require("gpio");

var LED_PORT = 17, SWITCH_PORT = 27;

var ledPort = gpio.export(LED_PORT, {direction: 'out'});
var switchPort = gpio.export(SWITCH_PORT, {direction: 'in', interval:400});

switchPort.on('change', function(val){
    console.log("switch value: " + val);
    ledPort.set(val);
});

function ledOn(){
    port_17.set();
    setTimeout(ledOff, 1000);
}

function ledOff(){
    port_17.reset();
    setTimeout(ledOn, 1000);
}<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.InvisibleText.
sap.ui.define(['jquery.sap.global', './Control', './library', 'jquery.sap.strings'],
	function(jQuery, Control, library, strings) {
	"use strict";

	/**
	 * Constructor for a new InvisibleText.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * An InvisibleText is used to bring hidden texts to the UI for screen reader support. The hidden text can e.g. be referenced
	 * in the ariaLabelledBy or ariaDescribedBy associations of other controls.
	 *
	 * The inherited properties busy, busyIndicatorDelay and visible and the aggregation tooltip is not supported by this control.
	 *
	 * @extends sap.ui.core.Control
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.27.0
	 * @name sap.ui.core.InvisibleText
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var InvisibleText = Control.extend("sap.ui.core.InvisibleText", /** @lends sap.ui.core.InvisibleText.prototype */ {
		metadata : {
			library : "sap.ui.core",
			publicMethods: ["toStatic"],
			properties : {

				/**
				 * The text of the InvisibleText.
				 */
				text : {type : "string", defaultValue : ""}
			}
		},

		renderer : function(oRm, oControl) {
			// The text is hidden through "display: none" in the shared CSS class
			// "sapUiInvisibleText", as an alternative in case screen readers have trouble with
			// "display: none", the following class definition could be used:
			//	.sapUiInvisibleText {
			//		display: inline-block !important;
			//		visibility: hidden !important;
			//		width: 0 !important;
			//		height: 0 !important;
			//		overflow: hidden !important;
			//		position: absolute !important;
			//	}

			oRm.write("");
			oRm.writeEscaped(oControl.getText() || "");
			oRm.write("");
		}
	});

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Local BusyIndicator is not supported by control.
	 * @name sap.ui.core.InvisibleText#setBusyIndicatorDelay
	 * @function
	 */
	InvisibleText.prototype.setBusy = function() {
		jQuery.sap.log.warning("Property busy is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Local BusyIndicator is not supported by control.
	 * @name sap.ui.core.InvisibleText#setBusyIndicatorDelay
	 * @function
	 */
	InvisibleText.prototype.setBusyIndicatorDelay = function() {
		jQuery.sap.log.warning("Property busyIndicatorDelay is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Property visible is not supported by control.
	 * @name sap.ui.core.InvisibleText#setVisible
	 * @function
	 */
	InvisibleText.prototype.setVisible = function() {
		jQuery.sap.log.warning("Property visible is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Tooltip is not supported by control.
	 * @name sap.ui.core.InvisibleText#setTooltip
	 * @function
	 */
	InvisibleText.prototype.setTooltip = function() {
		jQuery.sap.log.warning("Aggregation tooltip is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	InvisibleText.prototype.setText = function(sText) {
		this.setProperty("text", sText, true);
		this.$().html(jQuery.sap.encodeHTML(this.getText() || ""));
		return this;
	};

	/**
	 * Adds this control into the static, hidden area UI area container.
	 *
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @see sap.ui.core.Control#placeAt
	 * @name sap.ui.core.InvisibleText#toStatic
	 * @function
	 */
	InvisibleText.prototype.toStatic = function() {
		return this.placeAt("sap-ui-static");
	};

	return InvisibleText;

}, /* bExport= */ true);<commit_msg>[FIX] core.InvisibleText: Should not invalidate static UIArea.<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.InvisibleText.
sap.ui.define(['jquery.sap.global', './Control', './library', 'jquery.sap.strings'],
	function(jQuery, Control, library, strings) {
	"use strict";

	/**
	 * Constructor for a new InvisibleText.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * An InvisibleText is used to bring hidden texts to the UI for screen reader support. The hidden text can e.g. be referenced
	 * in the ariaLabelledBy or ariaDescribedBy associations of other controls.
	 *
	 * The inherited properties busy, busyIndicatorDelay and visible and the aggregation tooltip is not supported by this control.
	 *
	 * @extends sap.ui.core.Control
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.27.0
	 * @name sap.ui.core.InvisibleText
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var InvisibleText = Control.extend("sap.ui.core.InvisibleText", /** @lends sap.ui.core.InvisibleText.prototype */ {
		metadata : {
			library : "sap.ui.core",
			publicMethods: ["toStatic"],
			properties : {

				/**
				 * The text of the InvisibleText.
				 */
				text : {type : "string", defaultValue : ""}
			}
		},

		renderer : function(oRm, oControl) {
			// The text is hidden through "display: none" in the shared CSS class
			// "sapUiInvisibleText", as an alternative in case screen readers have trouble with
			// "display: none", the following class definition could be used:
			//	.sapUiInvisibleText {
			//		display: inline-block !important;
			//		visibility: hidden !important;
			//		width: 0 !important;
			//		height: 0 !important;
			//		overflow: hidden !important;
			//		position: absolute !important;
			//	}

			oRm.write("");
			oRm.writeEscaped(oControl.getText() || "");
			oRm.write("");
		}
	});

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Local BusyIndicator is not supported by control.
	 * @name sap.ui.core.InvisibleText#setBusyIndicatorDelay
	 * @function
	 */
	InvisibleText.prototype.setBusy = function() {
		jQuery.sap.log.warning("Property busy is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Local BusyIndicator is not supported by control.
	 * @name sap.ui.core.InvisibleText#setBusyIndicatorDelay
	 * @function
	 */
	InvisibleText.prototype.setBusyIndicatorDelay = function() {
		jQuery.sap.log.warning("Property busyIndicatorDelay is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Property visible is not supported by control.
	 * @name sap.ui.core.InvisibleText#setVisible
	 * @function
	 */
	InvisibleText.prototype.setVisible = function() {
		jQuery.sap.log.warning("Property visible is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	/**
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @deprecated Tooltip is not supported by control.
	 * @name sap.ui.core.InvisibleText#setTooltip
	 * @function
	 */
	InvisibleText.prototype.setTooltip = function() {
		jQuery.sap.log.warning("Aggregation tooltip is not supported by control sap.ui.core.InvisibleText.");
		return this;
	};

	InvisibleText.prototype.setText = function(sText) {
		this.setProperty("text", sText, true);
		this.$().html(jQuery.sap.encodeHTML(this.getText() || ""));
		return this;
	};

	/**
	 * Adds this control into the static, hidden area UI area container.
	 *
	 * @return {sap.ui.core.Control} Returns this to allow method chaining
	 * @public
	 * @see sap.ui.core.Control#placeAt
	 * @name sap.ui.core.InvisibleText#toStatic
	 * @function
	 */
	InvisibleText.prototype.toStatic = function() {
		var oCore = sap.ui.getCore();

		try {
			var oStatic = oCore.getStaticAreaRef();
			var oRM = oCore.createRenderManager();
			oRM.render(this, oStatic);
			oRM.destroy();
		} catch(e) {
			this.placeAt("sap-ui-static");
		}

		return this;
	};

	return InvisibleText;

}, /* bExport= */ true);<|endoftext|>


<commit_before>// Clear add action form and add action to group
var closeGroupActionForm = function (actionId) {
    $('.add-action-form').toggleClass('visible');
    var groupId = $('.group-title').attr("id");

    Meteor.call('addActionToGroup', groupId, actionId, function (err) {
        if (err) {
            console.log(err);
        } else {
            humane.log("Action added.");
        }
    });
};

Template.editGroup.group = {
    group: this._id
}

Template.editGroup.helpers({
    /**
     *
     * @returns {array of actions} returns the groups actions
     */
    'getActions': function () {
        if (this.actions) {
            return this.actions.map(function (actionId) {
                return Actions.findOne(actionId);
            });
        }
    },
    'group': function () {
        return this._id;
    },
    /**
     *
     * @returns {array of users} who belong to the group
     */
    'getUsers': function () {
        if (this.users) {
            return this.users.map(function (user) {
                user_doc = Meteor.users.findOne(user.userId);
                user_doc.groupPoints = user.points;
                return user_doc;
            });
        }
    },
    /**
     *
     * @returns {arrays of users} who are admins
     */
    'getAdmins': function () {
        if (this.admins) {
            return this.admins.map(function (user) {
                user_doc = Meteor.users.findOne(user);
                return user_doc;
            });
        }
    },
    /**
     *
     * @returns {cursor} competitions which belong to this group
     */
    'getCompetitions': function () {
        return Competitions.find({"parentGroup": this._id});
    },
    /**
     *
     * @returns {user[]} who requested to be a part of the group
     */
    'getUserRequests': function () {
        if (this.usersRequesting) {
            return this.usersRequesting.map(function (userId) {
                return Meteor.users.findOne(userId);
            });
        }
    }
});

Template.editGroup.events({
    'click .add-actions': function (e) {
        $('.add-action-form').toggleClass('visible');
    },
    'click .add-user': function (e) {
        $('.add-user-form').toggleClass('visible');
    },
    'click .add-admin': function (e) {
        $('.add-admin-form').toggleClass('visible');
    },
    'submit .add-user-form': function (e) {
        e.preventDefault();
        var userId = Meteor.users.findOne({username: e.target.username.value})._id;
        Meteor.call("addUser", this._id, userId, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                e.target.username.value = '';
                $('.add-user-form').toggleClass('visible');
            }
        });
    },
    'submit .add-admin-form': function (e) {
        e.preventDefault();
        var userId = Meteor.users.findOne({username: event.target.username.value})._id;
        Meteor.call("addAdmin", this._id, userId, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                e.target.username.value = '';
                $('.add-admin-form').toggleClass('visible');
            }
        });
    },
    'click .remove-user': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('removeUser', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-admin': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('removeAdmin', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-comp': function (e) {
        var compId = e.target.getAttribute('id');
        Meteor.call('removeCompetition', compId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-action': function (e) {
        var actionId = e.target.getAttribute('id');
        Meteor.call('removeActionFromGroup', this._id, actionId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .request-user': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('addUser', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            } else {
                humane.log("Join request submitted.");
            }
        });
    },
    'click .global': function (e) {
        var actionId = e.target.getAttribute('id');
        Meteor.call('submitForApproval', actionId, function (err) {
            if (err) {
                console.log(err);
            } else {
                humane.log("Action submitted for global approval.");
            }
        });
    },
    'click .edit-group-name': function (e) {
        $('.group-name').toggleClass('hidden');
        $('.group-name-field').toggleClass('visible');
        Meteor.call('updateGroupName', this._id, $('.group-name-field').val(), function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .new-competition': function (e) {
        $('.add-competition-form').toggleClass('visible');
    },
    'click .remove-group': function (e) {
        e.preventDefault();
        var really = confirm("Are you sure you want to delete this group? There's no going back!");
        if (really) {
            Meteor.call('removeGroup', this._id, function (err) {
                if (err) {
                    console.log(err);
                }
            });
            Router.go('/user/profile/');
        }
    }
});
Template.editGroup.rendered = function () {
    closeActionForm = closeGroupActionForm;
};
<commit_msg>fixed group bug<commit_after>// Clear add action form and add action to group
var closeGroupActionForm = function (actionId) {
    $('.add-action-form').toggleClass('visible');
    var groupId = $('.group-title').attr("id");

    Meteor.call('addActionToGroup', groupId, actionId, function (err) {
        if (err) {
            console.log(err);
        } else {
            humane.log("Action added.");
        }
    });
};

Template.editGroup.helpers({
    /**
     *
     * @returns {array of actions} returns the groups actions
     */
    'getActions': function () {
        if (this.actions) {
            return this.actions.map(function (actionId) {
                return Actions.findOne(actionId);
            });
        }
    },
    group: function () {
        return this._id;
    },
    /**
     *
     * @returns {array of users} who belong to the group
     */
    'getUsers': function () {
        if (this.users) {
            return this.users.map(function (user) {
                user_doc = Meteor.users.findOne(user.userId);
                user_doc.groupPoints = user.points;
                return user_doc;
            });
        }
    },
    /**
     *
     * @returns {arrays of users} who are admins
     */
    'getAdmins': function () {
        if (this.admins) {
            return this.admins.map(function (user) {
                user_doc = Meteor.users.findOne(user);
                return user_doc;
            });
        }
    },
    /**
     *
     * @returns {cursor} competitions which belong to this group
     */
    'getCompetitions': function () {
        return Competitions.find({"parentGroup": this._id});
    },
    /**
     *
     * @returns {user[]} who requested to be a part of the group
     */
    'getUserRequests': function () {
        if (this.usersRequesting) {
            return this.usersRequesting.map(function (userId) {
                return Meteor.users.findOne(userId);
            });
        }
    },
    /**
     *
     * @param {string} id userId
     * @returns {Boolean} whether this is not the current user's id
     */
    diff: function (id) {
        return id !== Meteor.userId();
    }
});

Template.editGroup.events({
    'click .add-actions': function (e) {
        $('.add-action-form').toggleClass('visible');
    },
    'click .add-user': function (e) {
        $('.add-user-form').toggleClass('visible');
    },
    'click .add-admin': function (e) {
        $('.add-admin-form').toggleClass('visible');
    },
    'submit .add-user-form': function (e) {
        e.preventDefault();
        var userId = Meteor.users.findOne({username: e.target.username.value})._id;
        Meteor.call("addUser", this._id, userId, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                e.target.username.value = '';
                $('.add-user-form').toggleClass('visible');
            }
        });
    },
    'submit .add-admin-form': function (e) {
        e.preventDefault();
        var userId = Meteor.users.findOne({username: event.target.username.value})._id;
        Meteor.call("addAdmin", this._id, userId, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                e.target.username.value = '';
                $('.add-admin-form').toggleClass('visible');
            }
        });
    },
    'click .remove-user': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('removeUser', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-admin': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('removeAdmin', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-comp': function (e) {
        var compId = e.target.getAttribute('id');
        Meteor.call('removeCompetition', compId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .remove-action': function (e) {
        var actionId = e.target.getAttribute('id');
        Meteor.call('removeActionFromGroup', this._id, actionId, function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .request-user': function (e) {
        var userId = e.target.getAttribute('id');
        Meteor.call('addUser', this._id, userId, function (err) {
            if (err) {
                console.log(err);
            } else {
                humane.log("Join request submitted.");
            }
        });
    },
    'click .global': function (e) {
        var actionId = e.target.getAttribute('id');
        Meteor.call('submitForApproval', actionId, function (err) {
            if (err) {
                console.log(err);
            } else {
                humane.log("Action submitted for global approval.");
            }
        });
    },
    'click .edit-group-name': function (e) {
        $('.group-name').toggleClass('hidden');
        $('.group-name-field').toggleClass('visible');
        Meteor.call('updateGroupName', this._id, $('.group-name-field').val(), function (err) {
            if (err) {
                console.log(err);
            }
        });
    },
    'click .new-competition': function (e) {
        $('.add-competition-form').toggleClass('visible');
    },
    'click .remove-group': function (e) {
        e.preventDefault();
        var really = confirm("Are you sure you want to delete this group? There's no going back!");

        if (really) {
            Meteor.call('removeGroup', this._id, function (err) {
                if (err) {
                    console.log(err);
                }
            });
            Router.go('/user/profile/');
        }
    }
});

Template.editGroup.rendered = function () {
    closeActionForm = closeGroupActionForm;
};
<|endoftext|>


<commit_before>import createPrototypeProxy from './createPrototypeProxy';
import bindAutoBindMethods from './bindAutoBindMethods';
import deleteUnknownAutoBindMethods from './deleteUnknownAutoBindMethods';
import supportsProtoAssignment from './supportsProtoAssignment';

const RESERVED_STATICS = [
  'length',
  'name',
  'arguments',
  'caller',
  'prototype',
  'toString'
];

function isEqualDescriptor(a, b) {
  if (!a && !b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  for (let key in a) {
    if (a[key] !== b[key]) {
      return false;
    }
  }
  return true;
}

function proxyClass(InitialComponent) {
  // Prevent double wrapping.
  // Given a proxy class, return the existing proxy managing it.
  if (Object.prototype.hasOwnProperty.call(InitialComponent, '__reactPatchProxy')) {
    return InitialComponent.__reactPatchProxy;
  }

  let CurrentComponent;
  let ProxyComponent;

  let staticDescriptors = {};
  function wasStaticModifiedByUser(key) {
    // Compare the descriptor with the one we previously set ourselves.
    const currentDescriptor = Object.getOwnPropertyDescriptor(ProxyComponent, key);
    return !isEqualDescriptor(staticDescriptors[key], currentDescriptor);
  }

  try {
    // Create a proxy constructor with matching name
    ProxyComponent = new Function('getCurrentComponent',
      `return function ${InitialComponent.name || 'ProxyComponent'}() {
         return getCurrentComponent().apply(this, arguments);
      }`
    )(() => CurrentComponent);
  } catch (err) {
    // Some environments may forbid dynamic evaluation
    ProxyComponent = function () {
      return CurrentComponent.apply(this, arguments);
    };
  }

  // Proxy toString() to the current constructor
  ProxyComponent.toString = function toString() {
    return CurrentComponent.toString();
  };

  let prototypeProxy;
  if (InitialComponent.prototype && InitialComponent.prototype.isReactComponent) {
    // Point proxy constructor to the proxy prototype
    prototypeProxy = createPrototypeProxy();
    ProxyComponent.prototype = prototypeProxy.get();
  }

  function update(NextComponent) {
    if (typeof NextComponent !== 'function') {
      throw new Error('Expected a constructor.');
    }

    // Prevent proxy cycles
    if (Object.prototype.hasOwnProperty.call(NextComponent, '__reactPatchProxy')) {
      return update(NextComponent.__reactPatchProxy.__getCurrent());
    }

    // Save the next constructor so we call it
    CurrentComponent = NextComponent;

    // Try to infer displayName
    ProxyComponent.displayName = NextComponent.displayName || NextComponent.name;

    // Set up the same prototype for inherited statics
    ProxyComponent.__proto__ = NextComponent.__proto__;

    // Copy static methods and properties
    Object.getOwnPropertyNames(NextComponent).forEach(key => {
      if (RESERVED_STATICS.indexOf(key) > -1) {
        return;
      }

      const staticDescriptor = {
        ...Object.getOwnPropertyDescriptor(NextComponent, key),
        configurable: true
      };

      // Copy static unless user has redefined it at runtime
      if (!wasStaticModifiedByUser(key)) {
        Object.defineProperty(ProxyComponent, key, staticDescriptor);
        staticDescriptors[key] = staticDescriptor;
      }
    });

    // Remove old static methods and properties
    Object.getOwnPropertyNames(ProxyComponent).forEach(key => {
      if (RESERVED_STATICS.indexOf(key) > -1) {
        return;
      }

      // Skip statics that exist on the next class
      if (NextComponent.hasOwnProperty(key)) {
        return;
      }

      // Skip non-configurable statics
      const descriptor = Object.getOwnPropertyDescriptor(ProxyComponent, key);
      if (descriptor && !descriptor.configurable) {
        return;
      }

      // Delete static unless user has redefined it at runtime
      if (!wasStaticModifiedByUser(key)) {
        delete ProxyComponent[key];
        delete staticDescriptors[key];
      }
    });

    if (prototypeProxy) {
      // Update the prototype proxy with new methods
      const mountedInstances = prototypeProxy.update(NextComponent.prototype);

      // Set up the constructor property so accessing the statics work
      ProxyComponent.prototype.constructor = ProxyComponent;

      // We might have added new methods that need to be auto-bound
      mountedInstances.forEach(bindAutoBindMethods);
      mountedInstances.forEach(deleteUnknownAutoBindMethods);
    }
  };

  function get() {
    return ProxyComponent;
  }

  function getCurrent() {
    return CurrentComponent;
  }

  update(InitialComponent);

  const proxy = { get, update };

  Object.defineProperty(proxy, '__getCurrent', {
    configurable: false,
    writable: false,
    enumerable: false,
    value: getCurrent
  });

  Object.defineProperty(ProxyComponent, '__reactPatchProxy', {
    configurable: false,
    writable: false,
    enumerable: false,
    value: proxy
  });

  return proxy;
}

function createFallback(Component) {
  let CurrentComponent = Component;

  return {
    get() {
      return CurrentComponent;
    },
    update(NextComponent) {
      CurrentComponent = NextComponent;
    }
  };
}

export default function createClassProxy(Component) {
  return Component.__proto__ && supportsProtoAssignment() ?
    proxyClass(Component) :
    createFallback(Component);
}
<commit_msg>Fallback to object instantiation in order to support ES6 classes.<commit_after>import createPrototypeProxy from './createPrototypeProxy';
import bindAutoBindMethods from './bindAutoBindMethods';
import deleteUnknownAutoBindMethods from './deleteUnknownAutoBindMethods';
import supportsProtoAssignment from './supportsProtoAssignment';

const RESERVED_STATICS = [
  'length',
  'name',
  'arguments',
  'caller',
  'prototype',
  'toString'
];

function isEqualDescriptor(a, b) {
  if (!a && !b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  for (let key in a) {
    if (a[key] !== b[key]) {
      return false;
    }
  }
  return true;
}

function proxyClass(InitialComponent) {
  // Prevent double wrapping.
  // Given a proxy class, return the existing proxy managing it.
  if (Object.prototype.hasOwnProperty.call(InitialComponent, '__reactPatchProxy')) {
    return InitialComponent.__reactPatchProxy;
  }

  let CurrentComponent;
  let ProxyComponent;

  let staticDescriptors = {};
  function wasStaticModifiedByUser(key) {
    // Compare the descriptor with the one we previously set ourselves.
    const currentDescriptor = Object.getOwnPropertyDescriptor(ProxyComponent, key);
    return !isEqualDescriptor(staticDescriptors[key], currentDescriptor);
  }

  function instantiate(factory, context, params) {
    const component = factory()

    try {
      return component.apply(context, params);
    } catch (err) {
      const instance = new component(...params);

      Object.keys(instance).forEach(key => {
        if (RESERVED_STATICS.indexOf(key) > -1) {
          return;
        }
        context[key] = instance[key];
      })
    }
  }

  try {
    // Create a proxy constructor with matching name
    ProxyComponent = new Function('factory', 'instantiate',
      `return function ${InitialComponent.name || 'ProxyComponent'}() {
         return instantiate(factory, this, arguments);
      }`
    )(() => CurrentComponent, instantiate);
  } catch (err) {
    // Some environments may forbid dynamic evaluation
    ProxyComponent = function () {
      return instantiate(() => CurrentComponent, this, arguments);
    };
  }

  // Proxy toString() to the current constructor
  ProxyComponent.toString = function toString() {
    return CurrentComponent.toString();
  };

  let prototypeProxy;
  if (InitialComponent.prototype && InitialComponent.prototype.isReactComponent) {
    // Point proxy constructor to the proxy prototype
    prototypeProxy = createPrototypeProxy();
    ProxyComponent.prototype = prototypeProxy.get();
  }

  function update(NextComponent) {
    if (typeof NextComponent !== 'function') {
      throw new Error('Expected a constructor.');
    }

    // Prevent proxy cycles
    if (Object.prototype.hasOwnProperty.call(NextComponent, '__reactPatchProxy')) {
      return update(NextComponent.__reactPatchProxy.__getCurrent());
    }

    // Save the next constructor so we call it
    CurrentComponent = NextComponent;

    // Try to infer displayName
    ProxyComponent.displayName = NextComponent.displayName || NextComponent.name;

    // Set up the same prototype for inherited statics
    ProxyComponent.__proto__ = NextComponent.__proto__;

    // Copy static methods and properties
    Object.getOwnPropertyNames(NextComponent).forEach(key => {
      if (RESERVED_STATICS.indexOf(key) > -1) {
        return;
      }

      const staticDescriptor = {
        ...Object.getOwnPropertyDescriptor(NextComponent, key),
        configurable: true
      };

      // Copy static unless user has redefined it at runtime
      if (!wasStaticModifiedByUser(key)) {
        Object.defineProperty(ProxyComponent, key, staticDescriptor);
        staticDescriptors[key] = staticDescriptor;
      }
    });

    // Remove old static methods and properties
    Object.getOwnPropertyNames(ProxyComponent).forEach(key => {
      if (RESERVED_STATICS.indexOf(key) > -1) {
        return;
      }

      // Skip statics that exist on the next class
      if (NextComponent.hasOwnProperty(key)) {
        return;
      }

      // Skip non-configurable statics
      const descriptor = Object.getOwnPropertyDescriptor(ProxyComponent, key);
      if (descriptor && !descriptor.configurable) {
        return;
      }

      // Delete static unless user has redefined it at runtime
      if (!wasStaticModifiedByUser(key)) {
        delete ProxyComponent[key];
        delete staticDescriptors[key];
      }
    });

    if (prototypeProxy) {
      // Update the prototype proxy with new methods
      const mountedInstances = prototypeProxy.update(NextComponent.prototype);

      // Set up the constructor property so accessing the statics work
      ProxyComponent.prototype.constructor = ProxyComponent;

      // We might have added new methods that need to be auto-bound
      mountedInstances.forEach(bindAutoBindMethods);
      mountedInstances.forEach(deleteUnknownAutoBindMethods);
    }
  };

  function get() {
    return ProxyComponent;
  }

  function getCurrent() {
    return CurrentComponent;
  }

  update(InitialComponent);

  const proxy = { get, update };

  Object.defineProperty(proxy, '__getCurrent', {
    configurable: false,
    writable: false,
    enumerable: false,
    value: getCurrent
  });

  Object.defineProperty(ProxyComponent, '__reactPatchProxy', {
    configurable: false,
    writable: false,
    enumerable: false,
    value: proxy
  });

  return proxy;
}

function createFallback(Component) {
  let CurrentComponent = Component;

  return {
    get() {
      return CurrentComponent;
    },
    update(NextComponent) {
      CurrentComponent = NextComponent;
    }
  };
}

export default function createClassProxy(Component) {
  return Component.__proto__ && supportsProtoAssignment() ?
    proxyClass(Component) :
    createFallback(Component);
}
<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-handlebars
*/

var get = Ember.get, set = Ember.set;

/**
  `{{yield}}` denotes an area of a template that will be rendered inside
  of another template. It has two main uses:

  ### Use with `layout`
  When used in a Handlebars template that is assigned to an `Ember.View`
  instance's `layout` property Ember will render the layout template first,
  inserting the view's own rendered output at the `{{yield}}` location.

  An empty `<body>` and the following application code:

  ```javascript
  AView = Ember.View.extend({
    classNames: ['a-view-with-layout'],
    layout: Ember.Handlebars.compile('<div class="wrapper">{{yield}}</div>'),
    template: Ember.Handlebars.compile('<span>I am wrapped</span>')
  });

  aView = AView.create();
  aView.appendTo('body');
  ```

  Will result in the following HTML output:

  ```html
  <body>
    <div class='ember-view a-view-with-layout'>
      <div class="wrapper">
        <span>I am wrapped</span>
      </div>
    </div>
  </body>
  ```

  The `yield` helper cannot be used outside of a template assigned to an
  `Ember.View`'s `layout` property and will throw an error if attempted.

  ```javascript
  BView = Ember.View.extend({
    classNames: ['a-view-with-layout'],
    template: Ember.Handlebars.compile('{{yield}}')
  });

  bView = BView.create();
  bView.appendTo('body');

  // throws
  // Uncaught Error: assertion failed:
  // You called yield in a template that was not a layout
  ```

  ### Use with Ember.Component
  When designing components `{{yield}}` is used to denote where, inside the component's
  template, an optional block passed to the component should render:

  ```handlebars
  <!-- application.hbs -->
  {{#labeled-textfield value=someProperty}}
    First name:
  {{/my-component}}
  ```

  ```handlebars
  <!-- components/my-component.hbs -->
  <label>
    {{yield}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    First name: <input type="text" />
  <label>
  ```

  @method yield
  @for Ember.Handlebars.helpers
  @param {Hash} options
  @return {String} HTML string
*/
Ember.Handlebars.registerHelper('yield', function(options) {
  var view = options.data.view;

  while (view && !get(view, 'layout')) {
    if (view._contextView) {
      view = view._contextView;
    } else {
      view = get(view, 'parentView');
    }
  }

  Ember.assert("You called yield in a template that was not a layout", !!view);

  view._yield(this, options);
});
<commit_msg>Fix component name in documentation example<commit_after>/**
@module ember
@submodule ember-handlebars
*/

var get = Ember.get, set = Ember.set;

/**
  `{{yield}}` denotes an area of a template that will be rendered inside
  of another template. It has two main uses:

  ### Use with `layout`
  When used in a Handlebars template that is assigned to an `Ember.View`
  instance's `layout` property Ember will render the layout template first,
  inserting the view's own rendered output at the `{{yield}}` location.

  An empty `<body>` and the following application code:

  ```javascript
  AView = Ember.View.extend({
    classNames: ['a-view-with-layout'],
    layout: Ember.Handlebars.compile('<div class="wrapper">{{yield}}</div>'),
    template: Ember.Handlebars.compile('<span>I am wrapped</span>')
  });

  aView = AView.create();
  aView.appendTo('body');
  ```

  Will result in the following HTML output:

  ```html
  <body>
    <div class='ember-view a-view-with-layout'>
      <div class="wrapper">
        <span>I am wrapped</span>
      </div>
    </div>
  </body>
  ```

  The `yield` helper cannot be used outside of a template assigned to an
  `Ember.View`'s `layout` property and will throw an error if attempted.

  ```javascript
  BView = Ember.View.extend({
    classNames: ['a-view-with-layout'],
    template: Ember.Handlebars.compile('{{yield}}')
  });

  bView = BView.create();
  bView.appendTo('body');

  // throws
  // Uncaught Error: assertion failed:
  // You called yield in a template that was not a layout
  ```

  ### Use with Ember.Component
  When designing components `{{yield}}` is used to denote where, inside the component's
  template, an optional block passed to the component should render:

  ```handlebars
  <!-- application.hbs -->
  {{#labeled-textfield value=someProperty}}
    First name:
  {{/labeled-textfield}}
  ```

  ```handlebars
  <!-- components/labeled-textfield.hbs -->
  <label>
    {{yield}} {{input value=value}}
  </label>
  ```

  Result:

  ```html
  <label>
    First name: <input type="text" />
  <label>
  ```

  @method yield
  @for Ember.Handlebars.helpers
  @param {Hash} options
  @return {String} HTML string
*/
Ember.Handlebars.registerHelper('yield', function(options) {
  var view = options.data.view;

  while (view && !get(view, 'layout')) {
    if (view._contextView) {
      view = view._contextView;
    } else {
      view = get(view, 'parentView');
    }
  }

  Ember.assert("You called yield in a template that was not a layout", !!view);

  view._yield(this, options);
});
<|endoftext|>