<commit_before>require.ensure(['script!3Dmol/build/3Dmol.js'], function(require) {

    require('script!3Dmol/build/3Dmol.js');

    // Define our own parser for chemical JSON files, using cjson extension.
    $3Dmol.Parsers.cjson = function(jsonMol) {

        var elementSymbols = [
            "Xx", "H", "He", "Li", "Be", "B", "C", "N", "O", "F",
            "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K",
            "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu",
            "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y",
            "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
            "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr",
            "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm",
            "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
            "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac",
            "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es",
            "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt",
            "Ds", "Rg", "Cn", "Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo" ];

        var atoms = [[]];
        var coords = jsonMol.atoms.coords['3d'];
        var elements = jsonMol.atoms.elements.number;
        var bonds = jsonMol.bonds.connections.index;
        var order = jsonMol.bonds.order;
        for (var i = 0; i < elements.length; ++i) {
            var atom = {};
            atom.index = i;
            atom.serial = i;
            atom.elem = elementSymbols[elements[i]];
            atom.x = coords[3 * i + 0];
            atom.y = coords[3 * i + 1];
            atom.z = coords[3 * i + 2];

            atom.bonds = [];
            atom.bondOrder = [];

            atoms[0].push(atom);
        }
        for (var j = 0; j < order.length; ++j) {
            var atom1 = atoms[0][bonds[2 * j + 0]];
            var atom2 = atoms[0][bonds[2 * j + 1]];
            if (typeof(atom1) != 'undefined' && typeof(atom2) != 'undefined') {
                atom1.bonds.push(atom2.serial);
                atom1.bondOrder.push(order[j]);
                atom2.bonds.push(atom1.serial);
                atom2.bondOrder.push(order[j]);
            }

        }
        return atoms;
    };

    angular.module('mongochemApp')
        .filter('mongochemUnderscores', function() {
            return function(text) {

                if (!text) {
                    return text;
                }

                var str = text.replace(/_/g, ' ');
                return str.charAt(0).toUpperCase() + str.substr(1);
            };
        })
        .controller('mongochemMoleculeHome', ['mongochem.Molecule', 'mongochem.Calculations',
                                              'mongochem.VibrationalModes', 'mongochem.Calculations.SDF',
                                              '$scope', '$state',
                                              function(Molecule, Calculations,
                                                       VibrationalModes,
                                                       SDF, $scope, $state) {

            var fetchMolecule = function(inichikey) {
                $scope.mol = Molecule.getByInchiKey({moleculeId: inichikey}, function(mol) {
                    $scope.viewer.clear();
                    $scope.displayMolecule(mol, {stick:{}});

                    // Fetch the calculations associated with this molecule
                    $scope.calcs = Calculations.query({moleculeId: mol._id}, function(calcs) {
                        if (calcs.length > 0) {
                            // Show the first vibrational modes for the first calculation
                            $scope.vibrationalModes = calcs[0].vibrationalModes;
                        }
                        else {
                            $scope.vibrationalModes = null;
                        }
                    });
                });
            };

            $scope.displayMolecule = function(mol, style) {
                // If we have it use SDF as it has bond information
                if ('cjson' in mol) {
                    $scope.viewer.addModel(mol.cjson, 'cjson');
                }
                else if ('sdf' in mol) {
                    $scope.viewer.addModel(mol.sdf, 'sdf');
                }
                else {
                    $scope.viewer.addModel(mol.xyz, 'xyz');
                }
                $scope.viewer.setStyle({}, style);
                $scope.viewer.zoomTo();
                $scope.viewer.render();
            };

            // Set the default style
            $scope.style = {stick:{}};

            $scope.setViewStyle = function(style) {
                if (style == 'ball') {
                    $scope.style = {sphere:{}};
                }
                else if (style == 'stick') {
                    $scope.style = {stick:{}};
                }
                else {
                    $scope.style = {stick:{hidden: false}, sphere: {scale: 0.3}};
                }

                // It seems that the model is not retained, add it back.
                if (!$scope.viewer.isAnimated()) {
                    $scope.displayMolecule($scope.mol, $scope.style);
                }

            };

            $scope.setInchiKey = function(inchikey) {
                $scope.animModel = null;
                $scope.modeFrames = null;
                $scope.sdf = null;
                $scope.viewer.stopAnimate();

                fetchMolecule(inchikey);
            };

            $scope.showMolecule = function() {
                $state.go('molecule', {moleculeId: $scope.selectedMolecule.inchikey });
            };

            $scope.hasAnimation = function() {
                return $scope.modeFrames && $scope.sdf;
            };

            $scope.hasSpectra = function() {
                return $scope.vibrationalModes;
            };

            $scope.animateMolecule = function() {

                if ($scope.viewer.isAnimated()) {
                    $scope.viewer.stopAnimate();
                }
                else {
                    if (!$scope.animModel) {
                        let atoms = [];
                        atoms = $3Dmol.Parsers.sdf($scope.sdf, {})[0];

                        $scope.viewer.removeAllModels();
                        $scope.animModel = $scope.viewer.createModelFrom({serial: -1}, false);

                        angular.forEach($scope.modeFrames, function(frame) {
                            var frameAtoms = angular.copy(atoms);
                            // Now update the atoms positions
                            let frameAtomIndex = 0;
                            for (var i = 0; i < frameAtoms.length; ++i) {
                                frameAtoms[i].model = $scope.animModel.getID();
                                frameAtoms[i].color = $3Dmol.elementColors.rasmol[frameAtoms[i].elem];
                                frameAtoms[i].x = frame[frameAtomIndex++];
                                frameAtoms[i].y = frame[frameAtomIndex++];
                                frameAtoms[i].z = frame[frameAtomIndex++];
                                frameAtoms[i].index = i;
                            }

                            $scope.animModel.addFrame(frameAtoms);
                        });

                        //$scope.viewer.zoomTo();
                        $scope.animModel.setStyle({}, $scope.style);
                        $scope.viewer.render();
                        $scope.viewer.animate({interval: 75, loop: "forward", reps: 0});
                    }
                }
            };

            var dereg = $scope.$watch('selectedMolecule', function(selectedMolecule) {
                if (selectedMolecule) {
                    $scope.setInchiKey(selectedMolecule.inchikey);
                    // ng-change will takeover now
                    dereg();
                }
            });

            $scope.showFrequenciesHistogram = true;

            $scope.toggleFrequencies = function() {
                $scope.showFrequenciesHistogram = !$scope.showFrequenciesHistogram;
            };

            $scope.$on('mongochem-frequency-histogram-clickbar', function(evt, data) {
                // Cancel any existing animation loop
                $scope.viewer.stopAnimate();
                // Get the frames for this mode
                $scope.mode = data.mode;

                VibrationalModes.get({
                    id: $scope.calcs[0]._id,
                    mode: $scope.mode
                }, function(data) {
                    $scope.viewer.stopAnimate();
                    $scope.animModel = null;
                    $scope.modeFrames = data.frames;
                });

                SDF.get({
                    id: $scope.calcs[0]._id
                },function(data) {
                    $scope.sdf = data.sdf;
                });
            });
        }])
        .controller('mongochemMoleculeDetail', ['mongochem.Molecule', '$scope', '$stateParams', function(Molecule, $scope, $stateParams) {
            $scope.mol = Molecule.getByInchiKey({moleculeId: $stateParams.moleculeId}, function(mol) {
                $scope.displayMolecule(mol , {stick:{}});
            });
        }])
        .controller('mongochemMolecules', ['Molecules', '$scope', function(Molecules, $scope) {
            $scope.molecules = Molecules.query({}, function(molecules) {
                molecules.sort(function(a, b) {
                    return a.name.toLowerCase() > b.name.toLowerCase();
                });
                $scope.selectedMolecule = molecules[0];
            });
        }])
        .directive('mongochem3dmol', ['$timeout', function($timeout) {
            return {
                link: function postLink($scope, $element) {
                    // Run in next digest so we get the right element size
                    $timeout(function() {
                        // Viewer config - properties 'defaultcolors' and 'callback'
                        var config = {defaultcolors: $3Dmol.rasmolElementColors };

                        // Create GLViewer within $element
                        $scope.viewer = $3Dmol.createViewer($($element), config);

                        // Remove postion:absolute from canvas
                        // We should look at patching 3DMol
                        let canvas = $element.find('canvas');
                        let style = canvas.attr('style');
                        style = style.replace(/position:\s*absolute/g, '');
                        canvas.attr('style', style);

                        $scope.viewer.setBackgroundColor(0xefefef);
                        $scope.viewer.resize();
                    });
                }
            };
        }]);
});
<commit_msg>Guard against calling stopAnimate(...) on undefined<commit_after>require.ensure(['script!3Dmol/build/3Dmol.js'], function(require) {

    require('script!3Dmol/build/3Dmol.js');

    // Define our own parser for chemical JSON files, using cjson extension.
    $3Dmol.Parsers.cjson = function(jsonMol) {

        var elementSymbols = [
            "Xx", "H", "He", "Li", "Be", "B", "C", "N", "O", "F",
            "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K",
            "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu",
            "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y",
            "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
            "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr",
            "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm",
            "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
            "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac",
            "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es",
            "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt",
            "Ds", "Rg", "Cn", "Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo" ];

        var atoms = [[]];
        var coords = jsonMol.atoms.coords['3d'];
        var elements = jsonMol.atoms.elements.number;
        var bonds = jsonMol.bonds.connections.index;
        var order = jsonMol.bonds.order;
        for (var i = 0; i < elements.length; ++i) {
            var atom = {};
            atom.index = i;
            atom.serial = i;
            atom.elem = elementSymbols[elements[i]];
            atom.x = coords[3 * i + 0];
            atom.y = coords[3 * i + 1];
            atom.z = coords[3 * i + 2];

            atom.bonds = [];
            atom.bondOrder = [];

            atoms[0].push(atom);
        }
        for (var j = 0; j < order.length; ++j) {
            var atom1 = atoms[0][bonds[2 * j + 0]];
            var atom2 = atoms[0][bonds[2 * j + 1]];
            if (typeof(atom1) != 'undefined' && typeof(atom2) != 'undefined') {
                atom1.bonds.push(atom2.serial);
                atom1.bondOrder.push(order[j]);
                atom2.bonds.push(atom1.serial);
                atom2.bondOrder.push(order[j]);
            }

        }
        return atoms;
    };

    angular.module('mongochemApp')
        .filter('mongochemUnderscores', function() {
            return function(text) {

                if (!text) {
                    return text;
                }

                var str = text.replace(/_/g, ' ');
                return str.charAt(0).toUpperCase() + str.substr(1);
            };
        })
        .controller('mongochemMoleculeHome', ['mongochem.Molecule', 'mongochem.Calculations',
                                              'mongochem.VibrationalModes', 'mongochem.Calculations.SDF',
                                              '$scope', '$state',
                                              function(Molecule, Calculations,
                                                       VibrationalModes,
                                                       SDF, $scope, $state) {

            var fetchMolecule = function(inichikey) {
                $scope.mol = Molecule.getByInchiKey({moleculeId: inichikey}, function(mol) {
                    $scope.viewer.clear();
                    $scope.displayMolecule(mol, {stick:{}});

                    // Fetch the calculations associated with this molecule
                    $scope.calcs = Calculations.query({moleculeId: mol._id}, function(calcs) {
                        if (calcs.length > 0) {
                            // Show the first vibrational modes for the first calculation
                            $scope.vibrationalModes = calcs[0].vibrationalModes;
                        }
                        else {
                            $scope.vibrationalModes = null;
                        }
                    });
                });
            };

            $scope.displayMolecule = function(mol, style) {
                // If we have it use SDF as it has bond information
                if ('cjson' in mol) {
                    $scope.viewer.addModel(mol.cjson, 'cjson');
                }
                else if ('sdf' in mol) {
                    $scope.viewer.addModel(mol.sdf, 'sdf');
                }
                else {
                    $scope.viewer.addModel(mol.xyz, 'xyz');
                }
                $scope.viewer.setStyle({}, style);
                $scope.viewer.zoomTo();
                $scope.viewer.render();
            };

            // Set the default style
            $scope.style = {stick:{}};

            $scope.setViewStyle = function(style) {
                if (style == 'ball') {
                    $scope.style = {sphere:{}};
                }
                else if (style == 'stick') {
                    $scope.style = {stick:{}};
                }
                else {
                    $scope.style = {stick:{hidden: false}, sphere: {scale: 0.3}};
                }

                // It seems that the model is not retained, add it back.
                if (!$scope.viewer.isAnimated()) {
                    $scope.displayMolecule($scope.mol, $scope.style);
                }

            };

            $scope.setInchiKey = function(inchikey) {
                $scope.animModel = null;
                $scope.modeFrames = null;
                $scope.sdf = null;

                if ($scope.viewer) {
                    $scope.viewer.stopAnimate();
                }

                fetchMolecule(inchikey);
            };

            $scope.showMolecule = function() {
                $state.go('molecule', {moleculeId: $scope.selectedMolecule.inchikey });
            };

            $scope.hasAnimation = function() {
                return $scope.modeFrames && $scope.sdf;
            };

            $scope.hasSpectra = function() {
                return $scope.vibrationalModes;
            };

            $scope.animateMolecule = function() {

                if ($scope.viewer.isAnimated()) {
                    $scope.viewer.stopAnimate();
                }
                else {
                    if (!$scope.animModel) {
                        let atoms = [];
                        atoms = $3Dmol.Parsers.sdf($scope.sdf, {})[0];

                        $scope.viewer.removeAllModels();
                        $scope.animModel = $scope.viewer.createModelFrom({serial: -1}, false);

                        angular.forEach($scope.modeFrames, function(frame) {
                            var frameAtoms = angular.copy(atoms);
                            // Now update the atoms positions
                            let frameAtomIndex = 0;
                            for (var i = 0; i < frameAtoms.length; ++i) {
                                frameAtoms[i].model = $scope.animModel.getID();
                                frameAtoms[i].color = $3Dmol.elementColors.rasmol[frameAtoms[i].elem];
                                frameAtoms[i].x = frame[frameAtomIndex++];
                                frameAtoms[i].y = frame[frameAtomIndex++];
                                frameAtoms[i].z = frame[frameAtomIndex++];
                                frameAtoms[i].index = i;
                            }

                            $scope.animModel.addFrame(frameAtoms);
                        });

                        //$scope.viewer.zoomTo();
                        $scope.animModel.setStyle({}, $scope.style);
                        $scope.viewer.render();
                        $scope.viewer.animate({interval: 75, loop: "forward", reps: 0});
                    }
                }
            };

            var dereg = $scope.$watch('selectedMolecule', function(selectedMolecule) {
                if (selectedMolecule) {
                    $scope.setInchiKey(selectedMolecule.inchikey);
                    // ng-change will takeover now
                    dereg();
                }
            });

            $scope.showFrequenciesHistogram = true;

            $scope.toggleFrequencies = function() {
                $scope.showFrequenciesHistogram = !$scope.showFrequenciesHistogram;
            };

            $scope.$on('mongochem-frequency-histogram-clickbar', function(evt, data) {
                // Cancel any existing animation loop
                $scope.viewer.stopAnimate();
                // Get the frames for this mode
                $scope.mode = data.mode;

                VibrationalModes.get({
                    id: $scope.calcs[0]._id,
                    mode: $scope.mode
                }, function(data) {
                    $scope.viewer.stopAnimate();
                    $scope.animModel = null;
                    $scope.modeFrames = data.frames;
                });

                SDF.get({
                    id: $scope.calcs[0]._id
                },function(data) {
                    $scope.sdf = data.sdf;
                });
            });
        }])
        .controller('mongochemMoleculeDetail', ['mongochem.Molecule', '$scope', '$stateParams', function(Molecule, $scope, $stateParams) {
            $scope.mol = Molecule.getByInchiKey({moleculeId: $stateParams.moleculeId}, function(mol) {
                $scope.displayMolecule(mol , {stick:{}});
            });
        }])
        .controller('mongochemMolecules', ['Molecules', '$scope', function(Molecules, $scope) {
            $scope.molecules = Molecules.query({}, function(molecules) {
                molecules.sort(function(a, b) {
                    return a.name.toLowerCase() > b.name.toLowerCase();
                });
                $scope.selectedMolecule = molecules[0];
            });
        }])
        .directive('mongochem3dmol', ['$timeout', function($timeout) {
            return {
                link: function postLink($scope, $element) {
                    // Run in next digest so we get the right element size
                    $timeout(function() {
                        // Viewer config - properties 'defaultcolors' and 'callback'
                        var config = {defaultcolors: $3Dmol.rasmolElementColors };

                        // Create GLViewer within $element
                        $scope.viewer = $3Dmol.createViewer($($element), config);

                        // Remove postion:absolute from canvas
                        // We should look at patching 3DMol
                        let canvas = $element.find('canvas');
                        let style = canvas.attr('style');
                        style = style.replace(/position:\s*absolute/g, '');
                        canvas.attr('style', style);

                        $scope.viewer.setBackgroundColor(0xefefef);
                        $scope.viewer.resize();
                    });
                }
            };
        }]);
});
<|endoftext|>


<commit_before>import {
  INCREMENT_ROUND,
  LOAD_ROUNDS_DATA,
  RESET_ROUND,
  RESET_SESSION,
  RESET_TIMER,
  SET_BREAK_PHASE,
  SET_FOCUS_LENGTH,
  SET_FOCUS_PHASE,
  SET_LONG_BREAK_LENGTH,
  SET_LONG_BREAK_INTERVAL,
  SET_LONG_BREAK_PHASE,
  SET_MINUTES,
  SET_SECONDS,
  SET_SHORT_BREAK_LENGTH,
  SET_TOTAL_ROUNDS
} from './types';

const initialState = {
  currentRound: 1,
  currentPhase: 0,
  focusLength: 25,
  longBreakInterval: 4,
  longBreakLength: 25,
  shortBreakLength: 5,
  totalRounds: 12,
  minutes: null,
  seconds: null
};

export default (state = initialState, action) => {
  switch (action.type) {

    case INCREMENT_ROUND: {
      const { currentRound, totalRounds } = state;
      if (currentRound < totalRounds) {
        return {
          ...state,
          currentRound: currentRound + 1
        };
      }
      return state;
    }

    case LOAD_ROUNDS_DATA: {
      const { data } = action;
      return {
        ...state,
        ...data,
        minutes: data.focusLength || 25,
        seconds: 0
      };
    }

    case RESET_ROUND: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        minutes: focusLength,
        seconds: 0
      };
    }

    case RESET_SESSION: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        currentRound: 1,
        minutes: focusLength,
        seconds: 0
      };
    }

    case RESET_TIMER: {
      const { currentPhase, focusLength, shortBreakLength } = state;
      if (currentPhase === 0) return { ...state, minutes: focusLength, seconds: 0 };
      return { ...state, minutes: shortBreakLength, seconds: 0 };
    }

    case SET_BREAK_PHASE: {
      const { shortBreakLength } = state;
      return {
        ...state,
        currentPhase: 1,
        minutes: shortBreakLength,
        seconds: 0
      };
    }

    case SET_FOCUS_LENGTH: {
      const { length: focusLength } = action;
      return { ...state, focusLength };
    }

    case SET_FOCUS_PHASE: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        minutes: focusLength,
        seconds: 0
      };
    }

    case SET_LONG_BREAK_LENGTH: {
      const { length: longBreakLength } = action;
      return { ...state, longBreakLength };
    }

    case SET_LONG_BREAK_INTERVAL: {
      const { interval: longBreakInterval } = action;
      return { ...state, longBreakInterval };
    }

    case SET_LONG_BREAK_PHASE: {
      const { longBreakLength } = state;
      return {
        ...state,
        currentPhase: 2,
        minutes: longBreakLength,
        seconds: 0
      };
    }

    case SET_MINUTES: {
      const { minutes } = action;
      return { ...state, minutes };
    }

    case SET_SECONDS: {
      const { seconds } = action;
      return { ...state, seconds };
    }

    case SET_SHORT_BREAK_LENGTH: {
      const { length: shortBreakLength } = action;
      return { ...state, shortBreakLength };
    }

    case SET_TOTAL_ROUNDS: {
      const { rounds: totalRounds } = action;
      return { ...state, totalRounds };
    }

    default: {
      return state;
    }
  }
};
<commit_msg>fix: Resetting long break phase sets to short time<commit_after>import {
  Phases
} from '../../../containers/enums';

import {
  INCREMENT_ROUND,
  LOAD_ROUNDS_DATA,
  RESET_ROUND,
  RESET_SESSION,
  RESET_TIMER,
  SET_BREAK_PHASE,
  SET_FOCUS_LENGTH,
  SET_FOCUS_PHASE,
  SET_LONG_BREAK_LENGTH,
  SET_LONG_BREAK_INTERVAL,
  SET_LONG_BREAK_PHASE,
  SET_MINUTES,
  SET_SECONDS,
  SET_SHORT_BREAK_LENGTH,
  SET_TOTAL_ROUNDS
} from './types';

const initialState = {
  currentRound: 1,
  currentPhase: 0,
  focusLength: 25,
  longBreakInterval: 4,
  longBreakLength: 25,
  shortBreakLength: 5,
  totalRounds: 12,
  minutes: null,
  seconds: null
};

export default (state = initialState, action) => {
  switch (action.type) {

    case INCREMENT_ROUND: {
      const { currentRound, totalRounds } = state;
      if (currentRound < totalRounds) {
        return {
          ...state,
          currentRound: currentRound + 1
        };
      }
      return state;
    }

    case LOAD_ROUNDS_DATA: {
      const { data } = action;
      return {
        ...state,
        ...data,
        minutes: data.focusLength || 25,
        seconds: 0
      };
    }

    case RESET_ROUND: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        minutes: focusLength,
        seconds: 0
      };
    }

    case RESET_SESSION: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        currentRound: 1,
        minutes: focusLength,
        seconds: 0
      };
    }

    case RESET_TIMER: {
      const { currentPhase, focusLength, longBreakLength, shortBreakLength } = state;

      if (currentPhase === Phases.FOCUS) {
        return { ...state, minutes: focusLength, seconds: 0 };
      } else if (currentPhase === Phases.SHORT_BREAK) {
        return { ...state, minutes: shortBreakLength, seconds: 0 };
      } else if (currentPhase === Phases.LONG_BREAK) {
        return { ...state, minutes: longBreakLength, seconds: 0 };
      }

      return { ...state };
    }

    case SET_BREAK_PHASE: {
      const { shortBreakLength } = state;
      return {
        ...state,
        currentPhase: 1,
        minutes: shortBreakLength,
        seconds: 0
      };
    }

    case SET_FOCUS_LENGTH: {
      const { length: focusLength } = action;
      return { ...state, focusLength };
    }

    case SET_FOCUS_PHASE: {
      const { focusLength } = state;
      return {
        ...state,
        currentPhase: 0,
        minutes: focusLength,
        seconds: 0
      };
    }

    case SET_LONG_BREAK_LENGTH: {
      const { length: longBreakLength } = action;
      return { ...state, longBreakLength };
    }

    case SET_LONG_BREAK_INTERVAL: {
      const { interval: longBreakInterval } = action;
      return { ...state, longBreakInterval };
    }

    case SET_LONG_BREAK_PHASE: {
      const { longBreakLength } = state;
      return {
        ...state,
        currentPhase: 2,
        minutes: longBreakLength,
        seconds: 0
      };
    }

    case SET_MINUTES: {
      const { minutes } = action;
      return { ...state, minutes };
    }

    case SET_SECONDS: {
      const { seconds } = action;
      return { ...state, seconds };
    }

    case SET_SHORT_BREAK_LENGTH: {
      const { length: shortBreakLength } = action;
      return { ...state, shortBreakLength };
    }

    case SET_TOTAL_ROUNDS: {
      const { rounds: totalRounds } = action;
      return { ...state, totalRounds };
    }

    default: {
      return state;
    }
  }
};
<|endoftext|>


<commit_before>// determine the ASN of the connecting IP

var dns = require('dns');
var net_utils = require('./net_utils');

var test_ip = '208.75.177.99';
var providers = [];
var conf_providers = [ 'origin.asn.cymru.com', 'asn.routeviews.org' ];

exports.register = function () {
    var plugin = this;

    // get settings from the config file
    plugin.cfg = plugin.config.get('connect.asn.ini');
    if (plugin.cfg.main.providers) {
        conf_providers = plugin.cfg.main.providers.split(/[\s,;]+/);
    }
    if (plugin.cfg.main.test_ip) { test_ip = plugin.cfg.main.test_ip; }

    // add working providers to the provider list
    var result_cb = function (zone, res) {
        if (!res) {
            plugin.logerror(plugin, zone + " failed");
            return;
        }

        plugin.loginfo(plugin, zone + " succeeded");
        if (providers.indexOf(zone) === -1) providers.push(zone);
    };

    // test each provider
    for (var i=0; i < conf_providers.length; i++) {
        plugin.get_dns_results(conf_providers[i], test_ip, result_cb);
    }
};

exports.get_dns_results = function (zone, ip, cb) {
    var plugin = this;
    var query = ip.split('.').reverse().join('.') + '.' + zone;
    // plugin.logdebug(plugin, "query: " + query);

    var timer = setTimeout(function () {
        plugin.logerror(plugin, 'timeout: ' + zone);
        return cb(zone, '');
    }, (plugin.cfg.main.timeout || 4) * 1000);

    dns.resolveTxt(query, function (err, addrs) {
        clearTimeout(timer);
        if (err) {
            plugin.logerror(plugin, "error: " + err + ' running: '+query);
            return cb(zone, '');
        }

        plugin.logdebug(plugin, zone + " answers: " + addrs);
        var result = '';

        if (zone === 'origin.asn.cymru.com') {
            result = plugin.parse_cymru(addrs[0]);
        }
        else if (zone === 'asn.routeviews.org') {
            result = plugin.parse_routeviews(addrs);
        }
        else if (zone === 'origin.asn.spameatingmonkey.net') {
            result = plugin.parse_monkey(addrs[0]);
        }
        else {
            plugin.logerror(plugin, "unrecognized ASN provider: " + zone);
        }

        return cb(zone, result);
    });
    return true;
};

exports.hook_lookup_rdns = function (next, connection) {
    var plugin = this;
    var ip = connection.remote_ip;
    if (net_utils.is_rfc1918(ip)) return next();

    var pending = providers.length;
    var result_cb = function (zone, r) {
        pending--;
        if (!r && pending === 0) return next();

        // store asn & net from any source
        if (r.asn) connection.results.add(plugin, {asn: r.asn});
        if (r.net) connection.results.add(plugin, {net: r.net});

        // store provider specific results
        if (zone === 'origin.asn.cymru.com') {
            connection.results.add(plugin, { emit: true, cymru: r});
        }
        else if (zone === 'asn.routeviews.org') {
            connection.results.add(plugin, { emit: true, routeviews: r });
        }
        else if (zone === 'origin.asn.spameatingmonkey.net') {
            connection.results.add(plugin, { emit: true, monkey: r });
        }
        if (pending === 0) return next();
    };

    for (var i=0; i < providers.length; i++) {
        var zone = providers[i];
        connection.logdebug(plugin, "zone: " + zone);
        plugin.get_dns_results(zone, ip, result_cb);
    }

    if (pending === 0) return next();
};

exports.parse_routeviews = function (thing) {
    var plugin = this;
    var bits;

    // this is a correct result (node >= 0.10.26)
    // 99.177.75.208.asn.routeviews.org. IN TXT "40431" "208.75.176.0" "21"
    if (Array.isArray(thing)) {
        bits = thing;
    }
    else {
        // this is what node (< 0.10.26) returns
        // 99.177.75.208.asn.routeviews.org. IN TXT "40431208.75.176.021"
        bits = thing.split(/ /);
    }

    if (bits.length !== 3) {
        plugin.logerror(plugin, "result length not 3: " + bits.length + ' string="' + thing + '"');
        return '';
    }

    return { asn: bits[0], net: bits[1] + '/' + bits[2] };
};

exports.parse_cymru = function (str) {
    var plugin = this;
    var r = str.split(/\s+\|\s*/);
    //  99.177.75.208.origin.asn.cymru.com. 14350 IN TXT "40431 | 208.75.176.0/21 | US | arin | 2007-03-02"
    // handle this: cymru: result 4:              string="10290 | 12.129.48.0/24 | US | arin |"
    if (r.length < 4) {
        plugin.logerror(plugin, "cymru: bad result length " + r.length + ' string="' + str + '"');
        return '';
    }
    return { asn: r[0], net: r[1], country: r[2], assignor: r[3], date: r[4] };
};

exports.parse_monkey = function (str) {
    var plugin = this;
    var r = str.split(/\s+\|\s+/);
    // "74.125.44.0/23 | AS15169 | Google Inc. | 2000-03-30"
    // "74.125.0.0/16 | AS15169 | Google Inc. | 2000-03-30 | US"
    if (r.length < 3) {
        plugin.logerror(plugin, "monkey: bad result length " + r.length + ' string="' + str + '"');
        return '';
    }
    return { asn: r[1].substring(2), net: r[0], org: r[2], date: r[3], country: r[4] };
};

exports.hook_data_post = function (next, connection) {
    var plugin = this;
    var asn = connection.results.get('connect.asn');
    if (!asn) return next();
    var txn = connection.transaction;
    plugin.cfg = plugin.config.get('connect.asn.ini');

    if (asn.asn && plugin.cfg.main.asn_header) {
        if (asn.net) {
            txn.add_header('X-Haraka-ASN', asn.asn + ' ' + asn.net);
        }
        else {
            txn.add_header('X-Haraka-ASN', asn.asn);
        }
    }

    if (plugin.cfg.main.provider_header) {
        for (var p in asn) {
            if (!asn[p].asn) {   // ignore non-object results
                // connection.logdebug(plugin, p + ", " + asn[p]);
                continue;
            }
            var name = 'X-Haraka-ASN-' + p.toUpperCase();
            var values = [];
            for (var k in asn[p]) {
                values.push(k + '=' + asn[p][k]);
            }
            txn.add_header(name, values.join(' '));
        }
    }
    return next();
};
<commit_msg>make ASN compatible with node 0.11<commit_after>// determine the ASN of the connecting IP

var dns = require('dns');
var net_utils = require('./net_utils');

var test_ip = '208.75.177.99';
var providers = [];
var conf_providers = [ 'origin.asn.cymru.com', 'asn.routeviews.org' ];

exports.register = function () {
    var plugin = this;

    plugin.load_asn_ini();

    // add working providers to the provider list
    var result_cb = function (zone, res) {
        if (!res) {
            plugin.logerror(plugin, zone + " failed");
            return;
        }

        plugin.loginfo(plugin, zone + " succeeded");
        if (providers.indexOf(zone) === -1) providers.push(zone);
    };

    // test each provider
    for (var i=0; i < conf_providers.length; i++) {
        plugin.get_dns_results(conf_providers[i], test_ip, result_cb);
    }
};

exports.load_asn_ini = function () {
    var plugin = this;
    plugin.cfg = plugin.config.get('connect.asn.ini', plugin.load_asn_ini);

    if (plugin.cfg.main.providers) {
        conf_providers = plugin.cfg.main.providers.split(/[\s,;]+/);
    }
    if (plugin.cfg.main.test_ip) {
        test_ip = plugin.cfg.main.test_ip;
    }
};

exports.get_dns_results = function (zone, ip, cb) {
    var plugin = this;
    var query = ip.split('.').reverse().join('.') + '.' + zone;
    // plugin.logdebug(plugin, "query: " + query);

    var timer = setTimeout(function () {
        plugin.logerror(plugin, 'timeout: ' + zone);
        return cb(zone, '');
    }, (plugin.cfg.main.timeout || 4) * 1000);

    dns.resolveTxt(query, function (err, addrs) {
        clearTimeout(timer);
        if (err) {
            plugin.logerror(plugin, "error: " + err + ' running: '+query);
            return cb(zone, '');
        }

        var first = addrs[0];
        if (Array.isArray(first)) {
            // node 0.11 returns TXT records as an array of labels
            first = join('', addrs[0]);  // concatenate the labels
        }

        plugin.logdebug(plugin, zone + " answers: " + addrs);
        var result = '';

        if (zone === 'origin.asn.cymru.com') {
            result = plugin.parse_cymru(first);
        }
        else if (zone === 'asn.routeviews.org') {
            result = plugin.parse_routeviews(addrs);
        }
        else if (zone === 'origin.asn.spameatingmonkey.net') {
            result = plugin.parse_monkey(first);
        }
        else {
            plugin.logerror(plugin, "unrecognized ASN provider: " + zone);
        }

        return cb(zone, result);
    });
    return true;
};

exports.hook_lookup_rdns = function (next, connection) {
    var plugin = this;
    var ip = connection.remote_ip;
    if (net_utils.is_rfc1918(ip)) return next();

    var pending = providers.length;
    var result_cb = function (zone, r) {
        pending--;
        if (!r && pending === 0) return next();

        // store asn & net from any source
        if (r.asn) connection.results.add(plugin, {asn: r.asn});
        if (r.net) connection.results.add(plugin, {net: r.net});

        // store provider specific results
        if (zone === 'origin.asn.cymru.com') {
            connection.results.add(plugin, { emit: true, cymru: r});
        }
        else if (zone === 'asn.routeviews.org') {
            connection.results.add(plugin, { emit: true, routeviews: r });
        }
        else if (zone === 'origin.asn.spameatingmonkey.net') {
            connection.results.add(plugin, { emit: true, monkey: r });
        }
        if (pending === 0) return next();
    };

    for (var i=0; i < providers.length; i++) {
        var zone = providers[i];
        connection.logdebug(plugin, "zone: " + zone);
        plugin.get_dns_results(zone, ip, result_cb);
    }

    if (pending === 0) return next();
};

exports.parse_routeviews = function (thing) {
    var plugin = this;
    var labels;

    // this is a correct result (node >= 0.10.26)
    // 99.177.75.208.asn.routeviews.org. IN TXT "40431" "208.75.176.0" "21"
    if (Array.isArray(thing)) {
        labels = thing;
    }
    else {
        // this is what node (< 0.10.26) returns
        // 99.177.75.208.asn.routeviews.org. IN TXT "40431208.75.176.021"
        labels = thing.split(/ /);
    }

    if (labels.length !== 3) {
        plugin.logerror(plugin, "result length not 3: " + labels.length +
                ' string="' + thing + '"');
        return '';
    }

    return { asn: labels[0], net: labels[1] + '/' + labels[2] };
};

exports.parse_cymru = function (str) {
    var plugin = this;
    var r = str.split(/\s+\|\s*/);
    //  99.177.75.208.origin.asn.cymru.com. 14350 IN TXT \
    //      "40431 | 208.75.176.0/21 | US | arin | 2007-03-02"
    // handle this: cymru: result 4:              string= \
    //      "10290 | 12.129.48.0/24 | US | arin |"
    if (r.length < 4) {
        plugin.logerror(plugin, "cymru: bad result length " + r.length +
                ' string="' + str + '"');
        return '';
    }
    return { asn: r[0], net: r[1], country: r[2], assignor: r[3], date: r[4] };
};

exports.parse_monkey = function (str) {
    var plugin = this;
    var r = str.split(/\s+\|\s+/);
    // "74.125.44.0/23 | AS15169 | Google Inc. | 2000-03-30"
    // "74.125.0.0/16 | AS15169 | Google Inc. | 2000-03-30 | US"
    if (r.length < 3) {
        plugin.logerror(plugin, "monkey: bad result length " + r.length +
                ' string="' + str + '"');
        return '';
    }
    return {
        asn: r[1].substring(2),
        net: r[0],
        org: r[2],
        date: r[3],
        country: r[4]
    };
};

exports.hook_data_post = function (next, connection) {
    var plugin = this;
    var asn = connection.results.get('connect.asn');
    if (!asn) return next();
    var txn = connection.transaction;
    plugin.cfg = plugin.config.get('connect.asn.ini');

    if (asn.asn && plugin.cfg.main.asn_header) {
        if (asn.net) {
            txn.add_header('X-Haraka-ASN', asn.asn + ' ' + asn.net);
        }
        else {
            txn.add_header('X-Haraka-ASN', asn.asn);
        }
    }

    if (plugin.cfg.main.provider_header) {
        for (var p in asn) {
            if (!asn[p].asn) {   // ignore non-object results
                // connection.logdebug(plugin, p + ", " + asn[p]);
                continue;
            }
            var name = 'X-Haraka-ASN-' + p.toUpperCase();
            var values = [];
            for (var k in asn[p]) {
                values.push(k + '=' + asn[p][k]);
            }
            txn.add_header(name, values.join(' '));
        }
    }
    return next();
};
<|endoftext|>


<commit_before>var startDate;

module.exports = {

    id: 'permissions',
    defaultConfig: {
        allowedUserNames: [],
        message: '⛔ you are not authorized'
    },

    plugin(bot, pluginConfig) {

        bot.mod('message', (data) => {
            const userId = data.message.from.id;
            if (pluginConfig.allowedUserNames.indexOf(data.message.from.username) < 0) {
                data.message = {};
                bot.sendMessage(userId, pluginConfig.message);
            }

            return data;
        });

        bot.on('start', () => {
            startDate = Date.now();
        });

        bot.mod('message', (data) => {
        if (data.message.date*1000 < startDate) {
            data.message = {};
        }

        return data;
    });

    }
};
<commit_msg>delete not related code<commit_after>module.exports = {

    id: 'permissions',
    defaultConfig: {
        allowedUserNames: [],
        message: '⛔ you are not authorized'
    },

    plugin(bot, pluginConfig) {

        bot.mod('message', (data) => {
            const userId = data.message.from.id;
            if (pluginConfig.allowedUserNames.indexOf(data.message.from.username) < 0) {
                data.message = {};
                bot.sendMessage(userId, pluginConfig.message);
            }

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


<commit_before>/**
 * @param {string[]} D
 * @param {number} N
 * @return {number}
 */
let atMostNGivenDigitSet = function(D, N) {
  const lenN = N.toString().length;
  const m = N.toString().length - 1;

  let res = 0;
  for (let i = 1; i <= m; i++) {
    res += Math.pow(D.length, m);
  }

};<commit_msg>remove unused code<commit_after><|endoftext|>


<commit_before>import ENV from 'canvas-web/config/environment';
import Ember from 'ember';
import OAuth from 'canvas-web/mixins/oauth';

export default Ember.Component.extend(OAuth, {
  clientID: ENV.slackClientID,
  endpoint: 'https://slack.com/oauth/authorize',
  redirectURL: ENV.slackAddRedirectURI,
  scope: `bot
    channels:read
    chat:write:bot
    commands
    team:read
    users:read`.w(),
  state: 'add'
});
<commit_msg>Add groups:read scope<commit_after>import ENV from 'canvas-web/config/environment';
import Ember from 'ember';
import OAuth from 'canvas-web/mixins/oauth';

export default Ember.Component.extend(OAuth, {
  clientID: ENV.slackClientID,
  endpoint: 'https://slack.com/oauth/authorize',
  redirectURL: ENV.slackAddRedirectURI,
  scope: `bot
    channels:read
    chat:write:bot
    commands
    groups:read
    team:read
    users:read`.w(),
  state: 'add'
});
<|endoftext|>


<commit_before>var app = require('../../');

app.utils = require('util');
app.utils.async = require('async');
app.utils.glob = require('glob');
app.utils.clone = require('clone');

/**
 * Extend an object with defaults.
 *
 * @param [deep] {Boolean} If true, performs a deep (recursive) merge.
 * @param obj {Object} The object to extend.
 * @param defaults {Object} An object containing the defaults.
 */
app.utils.defaults = function (deep, obj, defaults) {
  var copy;

  // Shallow.
  if (arguments.length === 2) {
    defaults = obj;
    obj = deep;
    deep = false;
  }

  // Support arbitrary number of defaults objects.
  if (arguments.length > 2) {
    var mixins = Array.prototype.slice.call(arguments, (deep === true) ? 2 : 1);
    if (mixins.length > 1) {
      mixins.forEach(function (mixin) {
        if (deep === true) {
          app.utils.defaults(true, obj, mixin);
        }
        else {
          app.utils.defaults(obj, mixin);
        }
      });
      return obj;
    }
  }

  // Clone the defaults so we dont transfer any properties by reference.
  if (deep === true) {
    copy = app.utils.clone(defaults);
  }
  else {
    copy = defaults;
  }

  Object.keys(copy).forEach(function(key) {
    if (deep && (typeof obj[key] === 'object') && (typeof copy[key] === 'object')) {
      app.utils.defaults(deep, obj[key], copy[key]);
    }
    else if (!obj.hasOwnProperty(key)) {
      obj[key] = copy[key];
    }
  });
};
<commit_msg>Fixes app.utils.defaults().<commit_after>var app = require('../../');

app.utils = require('util');
app.utils.async = require('async');
app.utils.glob = require('glob');
app.utils.clone = require('clone');

/**
 * Extend an object with defaults.
 *
 * @param [deep] {Boolean} If true, performs a deep (recursive) merge.
 * @param obj {Object} The object to extend.
 * @param defaults {Object} An object containing the defaults.
 */
app.utils.defaults = function (deep, obj, defaults) {
  var copy;

  // Shallow.
  if (deep !== true) {
    defaults = obj;
    obj = deep;
    deep = false;
  }

  // Support arbitrary number of defaults objects.
  if (arguments.length > 2) {
    var mixins = Array.prototype.slice.call(arguments, (deep === true) ? 2 : 1);
    if (mixins.length > 1) {
      mixins.forEach(function (mixin) {
        if (deep === true) {
          app.utils.defaults(true, obj, mixin);
        }
        else {
          app.utils.defaults(obj, mixin);
        }
      });
      return obj;
    }
  }

  // Clone the defaults so we dont transfer any properties by reference.
  if (deep === true) {
    copy = app.utils.clone(defaults);
  }
  else {
    copy = defaults;
  }

  Object.keys(copy).forEach(function(key) {
    // Only dive into object literals.
    if (deep && app.utils.isObjectLiteral(obj[key]) && app.utils.isObjectLiteral(copy[key])) {
      app.utils.defaults(deep, obj[key], copy[key]);
    }
    else if (!obj.hasOwnProperty(key)) {
      obj[key] = copy[key];
    }
  });

  return obj;
};

/**
 * Check if an object is an object literal.
 */
app.utils.isObjectLiteral = function (obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
};
<|endoftext|>


<commit_before>var mapjson = require('./mapjson.js');
var yogView = require('yog-view');
var yogBigPipe = require('yog-bigpipe');
var _ = require('lodash');

module.exports.views = function(app, conf){
    var middleware = [];

    //初始化map.json API
    var resourceApi = mapjson({
        config_dir: conf.confDir
    });
    middleware.push(resourceApi);

    //初始化bigpipe
    if (conf.bigpipe){
        middleware.push(yogBigPipe());
    }

    _(conf.engine).forEach(function(engine, name){
        //设置view engine
        app.engine(name, yogView.init({
            cache: conf.cache,
            engine: engine
        }, app));
    });

    if (conf.cache){
        app.enable('view cache');
    }

    return function(){
        app.use(middleware);
    };
};

module.exports.views.defaultConf = {
    confDir: yog.ROOT_PATH + '/conf/fis',
    bigpipe: true,
    engine: {
        tpl: require('yog-swig')
    }
};<commit_msg>固定views path，避免express对views路径识别错误<commit_after>var mapjson = require('./mapjson.js');
var yogView = require('yog-view');
var yogBigPipe = require('yog-bigpipe');
var _ = require('lodash');

module.exports.views = function(app, conf){
    var middleware = [];

    //初始化map.json API
    var resourceApi = mapjson({
        config_dir: conf.confDir
    });
    middleware.push(resourceApi);

    //初始化bigpipe
    if (conf.bigpipe){
        middleware.push(yogBigPipe());
    }

    app.set('views', conf.viewsDir);

    _(conf.engine).forEach(function(engine, name){
        //设置view engine
        app.engine(name, yogView.init({
            cache: conf.cache,
            engine: engine
        }, app));
    });

    if (conf.cache){
        app.enable('view cache');
    }

    return function(){
        app.use(middleware);
    };
};

module.exports.views.defaultConf = {
    confDir: yog.ROOT_PATH + '/conf/fis',
    viewsDir: yog.ROOT_PATH + '/views',
    bigpipe: true,
    engine: {
        tpl: require('yog-swig')
    }
};<|endoftext|>


<commit_before>var app = angular.module('twitterapp');

var syncFavourites = function (tweetId, isFavourite) {

  $('#stream .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

  $('#favouriteTweets .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

  $('#userTweets .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

};

app.directive('tweetForm', [function () {

  return {
    restrict: 'E',
    replace: true,
    templateUrl: "components/tweet/views/tweetForm.html",
    link: function (scope, element, attrs) {
      var MAX_CHARS = 140,
        parentElement = element.parent(),
        charCountDiv = parentElement.find('.char-count'),
        tweetButton = parentElement.find('.send-tweet'),
        textarea = parentElement.find('textarea');

      var resetForm = function () {
        scope.newTweet.message = '';
        scope.newTweetForm.$setPristine();
        textarea.attr('rows', '1');
        charCountDiv.text(MAX_CHARS);
      };

      textarea.focus(function () {
        textarea.attr('rows', '4');
      });

      textarea.blur(function () {
        if (!angular.isDefined(scope.newTweet) || !angular.isDefined(scope.newTweet.message) || scope.newTweet.message === '') {
          textarea.attr('rows', '1');
        }
      });

      textarea.keyup(function () {
        var charsRemaining,
          charCount = textarea.val().length;

        charsRemaining = MAX_CHARS - charCount;
        charCountDiv.text(charsRemaining);

        if (charsRemaining < 0) {
          charCountDiv.css('color', 'red');
          tweetButton.attr('disabled', 'true');
        } else {
          charCountDiv.css('color', '#5E6D70');
          tweetButton.removeAttr('disabled');
        }

      });

      scope.$on('tweetSuccess', function (event, args) {
        resetForm();
      })

    }
  };

}]);

app.directive('tweetIconPanel', ['$rootScope', 'tweetFactory', '$compile', function ($rootScope, tweetFactory, $compile) {

  return {
    restrict: 'E',
    replace: false,
    link: function (scope, element, attrs) {
      var panelDiv,
        iconsDiv,
        favouriteIcon,
        replyIcon,
        retweetIcon,
        replyFormDiv,
        retweetFormDiv,
        idDiv,
        newTweet;

      scope.$on('newTweetInStream', function (event, args) {
        newTweet = scope.streamtweets[0];
        favouriteIcon = angular.element('
').addClass('action-icon').addClass('favourite-icon').data('id-str', newTweet.id_str).data('is-favourite', false).append(angular.element(''));
        replyIcon = angular.element('
').addClass('action-icon').addClass('reply-icon').data('id-str', newTweet.id_str).append(angular.element(''));
        retweetIcon = angular.element('
').addClass('action-icon').addClass('retweet-icon').data('id-str', newTweet.id_str).append(angular.element(''));
        replyFormDiv = angular.element('
');
        retweetFormDiv = angular.element('
');
        panelDiv = angular.element(document.getElementById(newTweet.id_str));
        iconsDiv = angular.element('
');
        iconsDiv.append(replyIcon);
        iconsDiv.append(retweetIcon);
        iconsDiv.append(favouriteIcon);
        panelDiv.append(iconsDiv);
        panelDiv.append(angular.element('
'))
        panelDiv.append(replyFormDiv);
        panelDiv.append(retweetFormDiv);

        favouriteIcon.on('click', function () {
          var div = $(this),
            id_str,
            destroy = div.data('is-favourite');

          id_str = div.data('id-str');
          $rootScope.favouriteTweet(id_str, destroy, function (err, data) {
            if (err) {
              $rootScope.addStreamMessage({'type': 'error', 'msg': 'Unable to reach Twitter'});
            }

            if (!destroy) {
              div.css('color', 'yellow');
              div.data('is-favourite', true);
              syncFavourites(id_str, true);
            } else {
              div.css('color', '#5E6D70');
              div.data('is-favourite', false);
              syncFavourites(id_str, false);
            }
          });
        });

        replyIcon.on('click', function () {
          var formDiv,
            textarea,
            charCountDiv,
            charsRemaining,
            MAX_CHARS = 140,
            parentDiv,
            screenName,
            tweetId,
            replyButton,
            replyTweet = {},
            selectedTweet,
            screenNames = [],
            clicked = $(this);

          tweetFactory.getReplyForm().then(function (promise) {
            var originalMessage,
              i;

            parentDiv = clicked.parents('.tweet');
            screenName = parentDiv.find('.screen-name').text();
            tweetId = parentDiv.find('.tweet-id').text();
            originalMessage = parentDiv.find('.text');
            screenNames.push(screenName);

            for (i = 0; i < scope.streamtweets.length; i++) {
              if (scope.streamtweets[i].id_str === tweetId) {
                selectedTweet = scope.streamtweets[i];
              }
            }

            if (selectedTweet && selectedTweet.user_mentions && selectedTweet.user_mentions.length > 0) {
              for (i = 0; i < selectedTweet.user_mentions.length; i++) {
                screenNames.push('@' + selectedTweet.user_mentions[i].screen_name);
              }
            }

            formDiv = parentDiv.find('.reply-form');
            formDiv.html(promise.data);
            textarea = formDiv.find('textarea');
            textarea.text(screenNames.join(' '));
            charCountDiv = formDiv.find('.char-count');
            charsRemaining = MAX_CHARS - textarea.val().length;
            charCountDiv.text(charsRemaining);
            formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
            cancelButton = formDiv.find('.cancel-reply');
            replyButton = formDiv.find('.send-reply');
            formDiv.slideDown();

            // Increment/decrement the char count
            // when new chars are entered into the textarea
            textarea.keyup(function () {

              charsRemaining = MAX_CHARS - textarea.val().length;
              charCountDiv.text(charsRemaining);

              if (charsRemaining < 0) {
                charCountDiv.css('color', 'red');
                replyButton.attr('disabled', 'true');
              } else {
                charCountDiv.css('color', '#5E6D70');
                replyButton.removeAttr('disabled');
              }

            });

            // Cancel button click
            cancelButton.on('click', function () {
              formDiv.find('textarea').text('');
              formDiv.slideUp();
            });

            // Reply button click
            replyButton.on('click', function () {
              replyTweet.message = formDiv.find('textarea').val();
              replyTweet.tweetId = formDiv.find('.tweet-id').attr('value');

              scope.sendStatusUpdate(replyTweet);

              scope.$on('replySuccess', function (event, args) {
                formDiv.find('textarea').text('');
                formDiv.slideUp();
              });

            });

          });

        });

        retweetIcon.on('click', function () {
          var div = $(this),
            i,
            selectedTweet,
            retweet = {},
            destroy = div.data('is-retweeted'),
            tweetId = $(this).data('id-str');

          for (i = 0; i < scope.streamtweets.length; i++) {
            if (scope.streamtweets[i].id_str === tweetId) {
              selectedTweet = scope.streamtweets[i];
              $rootScope.retweetedTweet = selectedTweet;
              break;
            }
          }

          if (destroy) {

            scope.removeStatus(div.data('retweet-id'));

            scope.$on('removeSuccess', function (event, args) {
              div.css('color', '#5E6D70');
              div.data('is-retweeted', false);
              div.data('retweet-id', false);
            });

          } else {

            tweetFactory.getRetweetForm().then(function (promise) {
              parentDiv = div.parents('.tweet');
              tweetId = parentDiv.find('.tweet-id').text();
              formDiv = parentDiv.children('.retweet-form');
              formDiv.html($compile(promise.data)(scope));
              formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
              cancelButton = formDiv.find('.cancel-retweet');
              retweetButton = formDiv.find('.send-retweet');
              formDiv.slideDown();

              // Cancel button click
              cancelButton.on('click', function () {
                formDiv.find('textarea').text('');
                formDiv.slideUp();
              });

              // Retweet button click
              retweetButton.on('click', function () {

                scope.sendStatusRetweet(tweetId);

                scope.$on('retweetSuccess', function (event, args) {
                  div.css('color', 'yellow');
                  div.data('is-retweeted', true);
                  div.data('retweet-id', args.tweetId);
                  formDiv.slideUp();
                });

              });

            });
          }

        });

      });
    }
  };

}]);

app.directive('iconPanel', ['$rootScope', 'tweetFactory', function ($rootScope, tweetFactory) {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: "components/tweet/views/tweetIconPanel.html",
    link: function (scope, element, attrs) {
      var favouriteDiv = element.find('.favourite-icon'),
        retweetDiv = element.find('.retweet'),
        replyDiv = element.find('.reply'),
        tweetList;

      if (attrs.context === 'userTweets') {
        retweetDiv.hide();
        favouriteDiv.data('is-favourite', false);
        tweetList = $rootScope.userTweets;
      } else if (attrs.context == 'favouriteTweets') {
        favouriteDiv.data('is-favourite', true);
        favouriteDiv.css('color', 'yellow');
        tweetList = $rootScope.favouriteTweets;
      }

      favouriteDiv.on('click', function () {
        var div = $(this),
          id_str,
          destroy = div.data('is-favourite');

        id_str = div.parents('.panel').find('.tweet-id').text();

        alert(attrs.context);

        $rootScope.favouriteTweet(id_str, destroy, function (err, data) {
          if (err) {
            $rootScope.addStreamMessage({'type': 'error', 'msg': 'Unable to reach Twitter to favourite tweet'});
          }

          if (!destroy) {
            div.css('color', 'yellow');
            div.data('is-favourite', true);
            syncFavourites(id_str, true);
          } else {
            div.css('color', '#5E6D70');
            div.data('is-favourite', false);
            syncFavourites(id_str, false);
          }
        });
      });

      replyDiv.on('click', function () {
        var formDiv,
          textarea,
          charCountDiv,
          charsRemaining,
          MAX_CHARS = 140,
          parentDiv,
          screenName,
          tweetId,
          replyButton,
          replyTweet = {},
          selectedTweet,
          screenNames = [],
          clicked = $(this);

        tweetFactory.getReplyForm().then(function (promise) {
          var originalMessage,
            i;

          parentDiv = clicked.parents('.tweet');
          screenName = parentDiv.find('.screen-name').text();
          tweetId = parentDiv.find('.tweet-id').text();
          originalMessage = parentDiv.find('.text');
          screenNames.push(screenName);

          for (i = 0; i < tweetList.length; i++) {
            if (tweetList[i].id_str === tweetId) {
              selectedTweet = tweetList[i];
            }
          }

          if (selectedTweet && selectedTweet.user_mentions && selectedTweet.user_mentions.length > 0) {
            for (i = 0; i < selectedTweet.user_mentions.length; i++) {
              screenNames.push('@' + selectedTweet.user_mentions[i].screen_name);
            }
          }

          formDiv = parentDiv.find('.reply-form');
          formDiv.html(promise.data);
          textarea = formDiv.find('textarea');
          textarea.text(screenNames.join(' '));
          charCountDiv = formDiv.find('.char-count');
          charsRemaining = MAX_CHARS - textarea.val().length;
          charCountDiv.text(charsRemaining);
          formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
          cancelButton = formDiv.find('.cancel-reply');
          replyButton = formDiv.find('.send-reply');
          formDiv.slideDown();

          // Increment/decrement the char count
          // when new chars are entered into the textarea
          textarea.keyup(function () {

            charsRemaining = MAX_CHARS - textarea.val().length;
            charCountDiv.text(charsRemaining);

            if (charsRemaining < 0) {
              charCountDiv.css('color', 'red');
              replyButton.attr('disabled', 'true');
            } else {
              charCountDiv.css('color', '#5E6D70');
              replyButton.removeAttr('disabled');
            }

          });

          // Cancel button click
          cancelButton.on('click', function () {
            formDiv.find('textarea').text('');
            formDiv.slideUp();
          });

          // Reply button click
          replyButton.on('click', function () {
            replyTweet.message = formDiv.find('textarea').val();
            replyTweet.tweetId = formDiv.find('.tweet-id').attr('value');

            scope.sendStatusUpdate(replyTweet);

            scope.$on('replySuccess', function (event, args) {
              formDiv.find('textarea').text('');
              formDiv.slideUp();
            });

          });

        });

      });

      retweetDiv.on('click', function () {
        //mikeTest();
      });
    }
  };
}]);<commit_msg>Removed alert<commit_after>var app = angular.module('twitterapp');

var syncFavourites = function (tweetId, isFavourite) {

  $('#stream .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

  $('#favouriteTweets .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

  $('#userTweets .tweet').each(function (index) {
    var tweet = $(this),
      colour = (isFavourite) ? 'yellow' : '#5E6D70',
      favouriteDiv;

    if (tweet.find('.tweet-id').text() === tweetId) {
      favouriteDiv = tweet.find('.favourite-icon');
      favouriteDiv.css('color', colour);
      favouriteDiv.data('is-favourite', isFavourite);
      return false;
    }
  });

};

app.directive('tweetForm', [function () {

  return {
    restrict: 'E',
    replace: true,
    templateUrl: "components/tweet/views/tweetForm.html",
    link: function (scope, element, attrs) {
      var MAX_CHARS = 140,
        parentElement = element.parent(),
        charCountDiv = parentElement.find('.char-count'),
        tweetButton = parentElement.find('.send-tweet'),
        textarea = parentElement.find('textarea');

      var resetForm = function () {
        scope.newTweet.message = '';
        scope.newTweetForm.$setPristine();
        textarea.attr('rows', '1');
        charCountDiv.text(MAX_CHARS);
      };

      textarea.focus(function () {
        textarea.attr('rows', '4');
      });

      textarea.blur(function () {
        if (!angular.isDefined(scope.newTweet) || !angular.isDefined(scope.newTweet.message) || scope.newTweet.message === '') {
          textarea.attr('rows', '1');
        }
      });

      textarea.keyup(function () {
        var charsRemaining,
          charCount = textarea.val().length;

        charsRemaining = MAX_CHARS - charCount;
        charCountDiv.text(charsRemaining);

        if (charsRemaining < 0) {
          charCountDiv.css('color', 'red');
          tweetButton.attr('disabled', 'true');
        } else {
          charCountDiv.css('color', '#5E6D70');
          tweetButton.removeAttr('disabled');
        }

      });

      scope.$on('tweetSuccess', function (event, args) {
        resetForm();
      })

    }
  };

}]);

app.directive('tweetIconPanel', ['$rootScope', 'tweetFactory', '$compile', function ($rootScope, tweetFactory, $compile) {

  return {
    restrict: 'E',
    replace: false,
    link: function (scope, element, attrs) {
      var panelDiv,
        iconsDiv,
        favouriteIcon,
        replyIcon,
        retweetIcon,
        replyFormDiv,
        retweetFormDiv,
        idDiv,
        newTweet;

      scope.$on('newTweetInStream', function (event, args) {
        newTweet = scope.streamtweets[0];
        favouriteIcon = angular.element('
').addClass('action-icon').addClass('favourite-icon').data('id-str', newTweet.id_str).data('is-favourite', false).append(angular.element(''));
        replyIcon = angular.element('
').addClass('action-icon').addClass('reply-icon').data('id-str', newTweet.id_str).append(angular.element(''));
        retweetIcon = angular.element('
').addClass('action-icon').addClass('retweet-icon').data('id-str', newTweet.id_str).append(angular.element(''));
        replyFormDiv = angular.element('
');
        retweetFormDiv = angular.element('
');
        panelDiv = angular.element(document.getElementById(newTweet.id_str));
        iconsDiv = angular.element('
');
        iconsDiv.append(replyIcon);
        iconsDiv.append(retweetIcon);
        iconsDiv.append(favouriteIcon);
        panelDiv.append(iconsDiv);
        panelDiv.append(angular.element('
'))
        panelDiv.append(replyFormDiv);
        panelDiv.append(retweetFormDiv);

        favouriteIcon.on('click', function () {
          var div = $(this),
            id_str,
            destroy = div.data('is-favourite');

          id_str = div.data('id-str');
          $rootScope.favouriteTweet(id_str, destroy, function (err, data) {
            if (err) {
              $rootScope.addStreamMessage({'type': 'error', 'msg': 'Unable to reach Twitter'});
            }

            if (!destroy) {
              div.css('color', 'yellow');
              div.data('is-favourite', true);
              syncFavourites(id_str, true);
            } else {
              div.css('color', '#5E6D70');
              div.data('is-favourite', false);
              syncFavourites(id_str, false);
            }
          });
        });

        replyIcon.on('click', function () {
          var formDiv,
            textarea,
            charCountDiv,
            charsRemaining,
            MAX_CHARS = 140,
            parentDiv,
            screenName,
            tweetId,
            replyButton,
            replyTweet = {},
            selectedTweet,
            screenNames = [],
            clicked = $(this);

          tweetFactory.getReplyForm().then(function (promise) {
            var originalMessage,
              i;

            parentDiv = clicked.parents('.tweet');
            screenName = parentDiv.find('.screen-name').text();
            tweetId = parentDiv.find('.tweet-id').text();
            originalMessage = parentDiv.find('.text');
            screenNames.push(screenName);

            for (i = 0; i < scope.streamtweets.length; i++) {
              if (scope.streamtweets[i].id_str === tweetId) {
                selectedTweet = scope.streamtweets[i];
              }
            }

            if (selectedTweet && selectedTweet.user_mentions && selectedTweet.user_mentions.length > 0) {
              for (i = 0; i < selectedTweet.user_mentions.length; i++) {
                screenNames.push('@' + selectedTweet.user_mentions[i].screen_name);
              }
            }

            formDiv = parentDiv.find('.reply-form');
            formDiv.html(promise.data);
            textarea = formDiv.find('textarea');
            textarea.text(screenNames.join(' '));
            charCountDiv = formDiv.find('.char-count');
            charsRemaining = MAX_CHARS - textarea.val().length;
            charCountDiv.text(charsRemaining);
            formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
            cancelButton = formDiv.find('.cancel-reply');
            replyButton = formDiv.find('.send-reply');
            formDiv.slideDown();

            // Increment/decrement the char count
            // when new chars are entered into the textarea
            textarea.keyup(function () {

              charsRemaining = MAX_CHARS - textarea.val().length;
              charCountDiv.text(charsRemaining);

              if (charsRemaining < 0) {
                charCountDiv.css('color', 'red');
                replyButton.attr('disabled', 'true');
              } else {
                charCountDiv.css('color', '#5E6D70');
                replyButton.removeAttr('disabled');
              }

            });

            // Cancel button click
            cancelButton.on('click', function () {
              formDiv.find('textarea').text('');
              formDiv.slideUp();
            });

            // Reply button click
            replyButton.on('click', function () {
              replyTweet.message = formDiv.find('textarea').val();
              replyTweet.tweetId = formDiv.find('.tweet-id').attr('value');

              scope.sendStatusUpdate(replyTweet);

              scope.$on('replySuccess', function (event, args) {
                formDiv.find('textarea').text('');
                formDiv.slideUp();
              });

            });

          });

        });

        retweetIcon.on('click', function () {
          var div = $(this),
            i,
            selectedTweet,
            retweet = {},
            destroy = div.data('is-retweeted'),
            tweetId = $(this).data('id-str');

          for (i = 0; i < scope.streamtweets.length; i++) {
            if (scope.streamtweets[i].id_str === tweetId) {
              selectedTweet = scope.streamtweets[i];
              $rootScope.retweetedTweet = selectedTweet;
              break;
            }
          }

          if (destroy) {

            scope.removeStatus(div.data('retweet-id'));

            scope.$on('removeSuccess', function (event, args) {
              div.css('color', '#5E6D70');
              div.data('is-retweeted', false);
              div.data('retweet-id', false);
            });

          } else {

            tweetFactory.getRetweetForm().then(function (promise) {
              parentDiv = div.parents('.tweet');
              tweetId = parentDiv.find('.tweet-id').text();
              formDiv = parentDiv.children('.retweet-form');
              formDiv.html($compile(promise.data)(scope));
              formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
              cancelButton = formDiv.find('.cancel-retweet');
              retweetButton = formDiv.find('.send-retweet');
              formDiv.slideDown();

              // Cancel button click
              cancelButton.on('click', function () {
                formDiv.find('textarea').text('');
                formDiv.slideUp();
              });

              // Retweet button click
              retweetButton.on('click', function () {

                scope.sendStatusRetweet(tweetId);

                scope.$on('retweetSuccess', function (event, args) {
                  div.css('color', 'yellow');
                  div.data('is-retweeted', true);
                  div.data('retweet-id', args.tweetId);
                  formDiv.slideUp();
                });

              });

            });
          }

        });

      });
    }
  };

}]);

app.directive('iconPanel', ['$rootScope', 'tweetFactory', function ($rootScope, tweetFactory) {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: "components/tweet/views/tweetIconPanel.html",
    link: function (scope, element, attrs) {
      var favouriteDiv = element.find('.favourite-icon'),
        retweetDiv = element.find('.retweet'),
        replyDiv = element.find('.reply'),
        tweetList;

      if (attrs.context === 'userTweets') {
        retweetDiv.hide();
        favouriteDiv.data('is-favourite', false);
        tweetList = $rootScope.userTweets;
      } else if (attrs.context == 'favouriteTweets') {
        favouriteDiv.data('is-favourite', true);
        favouriteDiv.css('color', 'yellow');
        tweetList = $rootScope.favouriteTweets;
      }

      favouriteDiv.on('click', function () {
        var div = $(this),
          id_str,
          destroy = div.data('is-favourite');

        id_str = div.parents('.panel').find('.tweet-id').text();

        $rootScope.favouriteTweet(id_str, destroy, function (err, data) {
          if (err) {
            $rootScope.addStreamMessage({'type': 'error', 'msg': 'Unable to reach Twitter to favourite tweet'});
          }

          if (!destroy) {
            div.css('color', 'yellow');
            div.data('is-favourite', true);
            syncFavourites(id_str, true);
          } else {
            div.css('color', '#5E6D70');
            div.data('is-favourite', false);
            syncFavourites(id_str, false);
          }
        });
      });

      replyDiv.on('click', function () {
        var formDiv,
          textarea,
          charCountDiv,
          charsRemaining,
          MAX_CHARS = 140,
          parentDiv,
          screenName,
          tweetId,
          replyButton,
          replyTweet = {},
          selectedTweet,
          screenNames = [],
          clicked = $(this);

        tweetFactory.getReplyForm().then(function (promise) {
          var originalMessage,
            i;

          parentDiv = clicked.parents('.tweet');
          screenName = parentDiv.find('.screen-name').text();
          tweetId = parentDiv.find('.tweet-id').text();
          originalMessage = parentDiv.find('.text');
          screenNames.push(screenName);

          for (i = 0; i < tweetList.length; i++) {
            if (tweetList[i].id_str === tweetId) {
              selectedTweet = tweetList[i];
            }
          }

          if (selectedTweet && selectedTweet.user_mentions && selectedTweet.user_mentions.length > 0) {
            for (i = 0; i < selectedTweet.user_mentions.length; i++) {
              screenNames.push('@' + selectedTweet.user_mentions[i].screen_name);
            }
          }

          formDiv = parentDiv.find('.reply-form');
          formDiv.html(promise.data);
          textarea = formDiv.find('textarea');
          textarea.text(screenNames.join(' '));
          charCountDiv = formDiv.find('.char-count');
          charsRemaining = MAX_CHARS - textarea.val().length;
          charCountDiv.text(charsRemaining);
          formDiv.find('.tweet-id').attr('value', selectedTweet.id_str);
          cancelButton = formDiv.find('.cancel-reply');
          replyButton = formDiv.find('.send-reply');
          formDiv.slideDown();

          // Increment/decrement the char count
          // when new chars are entered into the textarea
          textarea.keyup(function () {

            charsRemaining = MAX_CHARS - textarea.val().length;
            charCountDiv.text(charsRemaining);

            if (charsRemaining < 0) {
              charCountDiv.css('color', 'red');
              replyButton.attr('disabled', 'true');
            } else {
              charCountDiv.css('color', '#5E6D70');
              replyButton.removeAttr('disabled');
            }

          });

          // Cancel button click
          cancelButton.on('click', function () {
            formDiv.find('textarea').text('');
            formDiv.slideUp();
          });

          // Reply button click
          replyButton.on('click', function () {
            replyTweet.message = formDiv.find('textarea').val();
            replyTweet.tweetId = formDiv.find('.tweet-id').attr('value');

            scope.sendStatusUpdate(replyTweet);

            scope.$on('replySuccess', function (event, args) {
              formDiv.find('textarea').text('');
              formDiv.slideUp();
            });

          });

        });

      });

      retweetDiv.on('click', function () {
        //mikeTest();
      });
    }
  };
}]);<|endoftext|>


<commit_before>/*
 *
 * CompetitionList
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import selectCompetitionListProp from './selectors';
import styles from './styles.css';
import { createStructuredSelector } from 'reselect';
import { loadCompetitionList } from './actions';

export class CompetitionList extends React.Component { // eslint-disable-line react/prefer-stateless-function

  /**
   * call action to load dancer profile
   */
  componentDidMount() {
    this.props.loadCompetitionList();
  }

  render() {
    const competitionList = this.props.competitionList;

    let listRender;

    if (competitionList) {
      listRender = (
hello, there

      );
    }

    return (

        <Helmet
          title="CompetitionList"
          meta={[
            { name: 'description', content: 'Description of CompetitionList' },
          ]}
        />
        {listRender}

    );
  }
}

CompetitionList.propTypes = {
  competitionList: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.bool,
  ]),
  loadCompetitionList: React.PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  competitionList: selectCompetitionListProp(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    loadCompetitionList: () => dispatch(loadCompetitionList()),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(CompetitionList);
<commit_msg>Список соревнований со ссылками<commit_after>/*
 *
 * CompetitionList
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { selectCompetitionListProp } from './selectors';
import styles from './styles.css';
import { createStructuredSelector } from 'reselect';
import { loadCompetitionList } from './actions';
import { push } from 'react-router-redux';

import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table';

export class CompetitionList extends React.Component { // eslint-disable-line react/prefer-stateless-function

  /**
   * call action to load dancer profile
   */
  componentDidMount() {
    this.props.loadCompetitionList();
  }

  openCompetitionPage = (id) => {
    this.props.changeRoute(`/competitions/${id}`);
  };

  render() {
    const competitionList = this.props.competitionList;

    let listRender;

    if (competitionList) {
      listRender = (

          <TableHeader displaySelectAll={false}>
            <TableRow>
              <TableHeaderColumn>Date</TableHeaderColumn>
              <TableHeaderColumn>Name</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody displayRowCheckbox={false}>
            {competitionList.content.map((item, index) =>
              <TableRow key={index}>
                <TableRowColumn>{item.Date}</TableRowColumn>
                <TableRowColumn>
                   this.openCompetitionPage(item.id)}>{item.title}
                </TableRowColumn>
              </TableRow>
            )}
          </TableBody>

      );
    }

    return (

        <Helmet
          title="CompetitionList"
          meta={[
            { name: 'description', content: 'Description of CompetitionList' },
          ]}
        />
        {listRender}

    );
  }
}

CompetitionList.propTypes = {
  competitionList: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.bool,
  ]),
  loadCompetitionList: React.PropTypes.func,
  changeRoute: React.PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  competitionList: selectCompetitionListProp(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    loadCompetitionList: () => dispatch(loadCompetitionList()),
    changeRoute: (url) => dispatch(push(url)),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(CompetitionList);
<|endoftext|>


<commit_before>import { Widget } from '@phosphor/widgets';
import { ABCWidgetFactory } from 'jupyterlab/lib/docregistry';
import { ActivityMonitor } from 'jupyterlab/lib/common/activitymonitor';

/**
 * The class name added to a DocWidget.
 */
const CLASS_NAME = 'jp-DocWidget{{cookiecutter.mime_short_name}}';

/**
 * The timeout to wait for change activity to have ceased before rendering.
 */
const RENDER_TIMEOUT = 1000;

/**
 * A widget for rendering {{cookiecutter.extension_name}} files.
 */
export class DocWidget extends Widget {
  constructor(context) {
    super();
    this._context = context;
    this.addClass(CLASS_NAME);
    context.model.contentChanged.connect(() => {
      this.update();
    });
    context.pathChanged.connect(() => {
      this.update();
    });
    this._monitor = new ActivityMonitor({
      signal: context.model.contentChanged,
      timeout: RENDER_TIMEOUT
    });
    this._monitor.activityStopped.connect(this.update, this);
  }

  /**
   * Dispose of the resources used by the widget.
   */
  dispose() {
    if (!this.isDisposed) {
      this._context = null;
      this._monitor.dispose();
      super.dispose();
    }
  }

  /**
   * A message handler invoked on an `'update-request'` message.
   */
  onUpdateRequest(msg) {
    this.title.label = this._context.path.split('/').pop();
    if (this.isAttached) {
      const content = this._context.model.toString();
      const json = content ? JSON.parse(content) : {};
      const text = document.createTextNode(JSON.stringify(json));
      this.node.appendChild(text);
    }
  }

  /**
   * A message handler invoked on an `'after-attach'` message.
   */
  onAfterAttach(msg) {
    this.update();
  }
}

/**
 * A widget factory for DocWidget.
 */
export class DocWidgetFactory extends ABCWidgetFactory {
  constructor(options) {
    super(options);
  }

  /**
   * Create a new widget given a context.
   */
  createNewWidget(context, kernel) {
    const widget = new DocWidget(context);
    this.widgetCreated.emit(widget);
    return widget;
  }
}
<commit_msg>Catch errors when rendering document content and display error<commit_after>import { Widget } from '@phosphor/widgets';
import { ABCWidgetFactory } from 'jupyterlab/lib/docregistry';
import { ActivityMonitor } from 'jupyterlab/lib/common/activitymonitor';

/**
 * The class name added to a DocWidget.
 */
const CLASS_NAME = 'jp-DocWidget{{cookiecutter.mime_short_name}}';

/**
 * The timeout to wait for change activity to have ceased before rendering.
 */
const RENDER_TIMEOUT = 1000;

/**
 * A widget for rendering {{cookiecutter.extension_name}} files.
 */
export class DocWidget extends Widget {
  constructor(context) {
    super();
    this._context = context;
    this.addClass(CLASS_NAME);
    context.model.contentChanged.connect(() => {
      this.update();
    });
    context.pathChanged.connect(() => {
      this.update();
    });
    this._monitor = new ActivityMonitor({
      signal: context.model.contentChanged,
      timeout: RENDER_TIMEOUT
    });
    this._monitor.activityStopped.connect(this.update, this);
  }

  /**
   * Dispose of the resources used by the widget.
   */
  dispose() {
    if (!this.isDisposed) {
      this._context = null;
      this._monitor.dispose();
      super.dispose();
    }
  }

  /**
   * A message handler invoked on an `'update-request'` message.
   */
  onUpdateRequest(msg) {
    this.title.label = this._context.path.split('/').pop();
    if (this.isAttached) {
      const content = this._context.model.toString();
      try {
        const json = JSON.parse(content);
        const text = document.createTextNode(JSON.stringify(json, null, 2));
        this.node.appendChild(text);
      } catch (error) {
        let container = document.createElement('div');
        container.setAttribute('class', 'jp-RenderedText jp-mod-error');
        container.style.cssText = `width: 100%; text-align: center; padding: 10px; box-sizing: border-box;`
        let titleContainer = document.createElement('span');
        titleContainer.style.cssText = `font-size: 18px; font-weight: 500; padding-bottom: 10px;`
        const titleText = document.createTextNode('Invalid JSON');
        titleContainer.appendChild(titleText);
        container.appendChild(titleContainer);
        let contentContainer = document.createElement('pre');
        contentContainer.style.cssText = `text-align: left; padding: 10px; overflow: hidden;`
        const contentText = document.createTextNode(content);
        contentContainer.appendChild(contentText);
        container.appendChild(contentContainer);
        this.node.innerHTML = '';
        this.node.appendChild(container);
      }
    }
  }

  /**
   * A message handler invoked on an `'after-attach'` message.
   */
  onAfterAttach(msg) {
    this.update();
  }
}

/**
 * A widget factory for DocWidget.
 */
export class DocWidgetFactory extends ABCWidgetFactory {
  constructor(options) {
    super(options);
  }

  /**
   * Create a new widget given a context.
   */
  createNewWidget(context, kernel) {
    const widget = new DocWidget(context);
    this.widgetCreated.emit(widget);
    return widget;
  }
}
<|endoftext|>


<commit_before>// Heroku defines the environment variable PORT, and requires the binding address to be 0.0.0.0
var host = process.env.PORT ? '0.0.0.0' : '127.0.0.1';
var port = process.env.PORT || 9199;

var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
    //requireHeader: ['origin', 'x-requested-with'],
    removeHeaders: ['cookie', 'cookie2'],
	secure: 'false',
}).listen(port, host, function() {
    console.log('Running CORS Anywhere on ' + host + ':' + port);
});
<commit_msg>Update cors port to bind to default addr<commit_after>// Heroku defines the environment variable PORT, and requires the binding address to be 0.0.0.0
var host = '0.0.0.0'; //'127.0.0.1'; //process.env.PORT ? '0.0.0.0' : '127.0.0.1';
var port = process.env.PORT || 9199;

var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
    //requireHeader: ['origin', 'x-requested-with'],
    removeHeaders: ['cookie', 'cookie2'],
	secure: 'false',
}).listen(port, host, function() {
    console.log('Running CORS Anywhere on ' + host + ':' + port);
});
<|endoftext|>


<commit_before>'use strict';

var Queries = require('../../helpers/queries');
var OverviewParser = require('../../helpers/overview_parser');

exports.showPage = {
    handler: function(request, reply) {
        return reply.view('performance/overview');
    }
};

exports.getData = {
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;
        var region_code = request.query.region_code;
        var role = request.auth.credentials.role;
        var queryString = Queries.overviewPerformance(region_code, role);

        sequelize.query(queryString, {
            type: sequelize.QueryTypes.SELECT
        }).then(function(rows) {

            var final_dict;

            if (role === 'block') {
                final_dict = OverviewParser.block(rows);
            }

            if (role === 'district') {
                final_dict = OverviewParser.district(rows);
            }

            final_dict.config = {
                role: role,
                headers: ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'],
                labels: [
                    'Muster roll closure to muster roll entry',
                    'Muster roll entry to wage list generation',
                    'Wage list generation to wage list signing',
                    'Wage list signing to FTO generation',
                    'FTO generation to first signature',
                    'First signature to second signature',
                    'Second signature to processed by bank',
                ],
            };

            reply(final_dict);
        });
    }
};
<commit_msg>Add stepwise comparison to data api<commit_after>'use strict';

var Queries = require('../../helpers/queries');
var OverviewParser = require('../../helpers/overview_parser');

exports.showPage = {
    handler: function(request, reply) {
        return reply.view('performance/overview');
    }
};

exports.getData = {
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;
        var region_code = request.query.region_code;
        var role = request.auth.credentials.role;
        var queryString = Queries.overviewPerformance(region_code, role);

        sequelize.query(queryString, {
            type: sequelize.QueryTypes.SELECT
        }).then(function(rows) {

            var final_dict;

            if (role === 'block') {
                final_dict = OverviewParser.block(rows);
            }

            if (role === 'district') {
                final_dict = OverviewParser.district(rows);
            }

            final_dict.config = {
                role: role,
                headers: ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'],
                labels: [
                    'Muster roll closure to muster roll entry',
                    'Muster roll entry to wage list generation',
                    'Wage list generation to wage list signing',
                    'Wage list signing to FTO generation',
                    'FTO generation to first signature',
                    'First signature to second signature',
                    'Second signature to processed by bank',
                ],
                comparison_lines: role === 'block' ? ['block', 'district', 'state'] : ['district', state]
            };

            reply(final_dict);
        });
    }
};
<|endoftext|>