<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {Paper} from '../../../../components/Paper'
import {Button} from '../../../../components/Button'
import * as Constants from '../../../../constants/ComponentTypes'
import ExerciseForm from '../ExerciseForm'
import StatusForm from './StatusForm'

const styles = {
  PaperContent: {
    padding: '20px'
  }
}

class Index extends Component {
  onUpdate(data) {
    this.props.updateExercise(data)
  }

  render() {
    console.log('EXERCISE', this.props.exercise)
    let image = this.props.exercise ? this.props.exercise.get('exercise_image') : ''

    return (

        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Information

            <ExerciseForm
              ref="exerciseForm"
              onSubmit={this.onUpdate.bind(this)}
              initialValues={this.props.exercise ? this.props.exercise.toJS() : {}}
            />

            <Button type="submit" label="Update"/>

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

State

            <StatusForm
              ref="statusForm"
              onSubmit={this.onUpdate.bind(this)}
              initialValues={this.props.exercise ? this.props.exercise.get('exercise_status').toJS() : {}}
            />
            <Button type="submit" label="Update"/>

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Image

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Delete

Deleting an exercise will result in deleting all the content of the exercise, including objectives, events, incidents, injects and audience groups. We do not recommend
            you do this.

            <Button type="submit" label="Delete"/>

        </Paper>

    );
  }
}

Index.propTypes = {
  id: PropTypes.string,
  exercise: PropTypes.object,
  params: PropTypes.object,
}

const select = (state, ownProps) => {
  let exerciseId = ownProps.params.exerciseId
  return {
    loading: state.application.getIn(['ui', 'loading']),
    id: exerciseId,
    exercise: state.application.getIn(['entities', 'exercises', exerciseId])
  }
}

export default connect(select, null)(Index)
<commit_msg>Use undefined instead of empty object. Redux form need it<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import {Paper} from '../../../../components/Paper'
import {Button} from '../../../../components/Button'
import * as Constants from '../../../../constants/ComponentTypes'
import ExerciseForm from '../ExerciseForm'
import StatusForm from './StatusForm'

const styles = {
  PaperContent: {
    padding: '20px'
  }
}

class Index extends Component {
  onUpdate(data) {
    this.props.updateExercise(data)
  }

  render() {
    console.log('EXERCISE', this.props.exercise)
    let image = this.props.exercise ? this.props.exercise.get('exercise_image') : ''

    return (

        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Information

            <ExerciseForm
              ref="exerciseForm"
              onSubmit={this.onUpdate.bind(this)}
              initialValues={this.props.exercise ? this.props.exercise.toJS() : undefined}
            />

            <Button type="submit" label="Update"/>

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

State

            <StatusForm
              ref="statusForm"
              onSubmit={this.onUpdate.bind(this)}
              initialValues={this.props.exercise ? this.props.exercise.get('exercise_status').toJS() : undefined}
            />
            <Button type="submit" label="Update"/>

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Image

        </Paper>
        <Paper type={Constants.PAPER_TYPE_SETTINGS} zDepth={2}>

Delete

Deleting an exercise will result in deleting all the content of the exercise, including objectives, events, incidents, injects and audience groups. We do not recommend
            you do this.

            <Button type="submit" label="Delete"/>

        </Paper>

    );
  }
}

Index.propTypes = {
  id: PropTypes.string,
  exercise: PropTypes.object,
  params: PropTypes.object,
}

const select = (state, ownProps) => {
  let exerciseId = ownProps.params.exerciseId
  return {
    loading: state.application.getIn(['ui', 'loading']),
    id: exerciseId,
    exercise: state.application.getIn(['entities', 'exercises', exerciseId])
  }
}

export default connect(select, null)(Index)
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();
    if (playerMove === "rock" && computerMove === "paper") {
        winner = "computer";
    } else if (playerMove === "rock" && computerMove === "scissors") {
        winner = "player";
    } else if (playerMove === "paper" && computerMove === "rock") {
        winner = "player";
    } else if (playerMove === "paper" && computerMove === "scissors") {
        winner = "computer";
    } else if (playerMove === "scissors" && computerMove === "paper") {
        winner = "player";
    } else if (playerMove === "scissors" && computerMove === "rock") {
        winner = "computer";
    } else if (playerMove === computerMove){
        winner = "tie";
    } return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    while (playerWins < 5 && computerWins < 5) {
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();
    var winner = getWinner(playerMove, computerMove);
    if (winner === "player"){
        playerWins +=1;
    } else if (winner === "computer"){
        computerWins +=1;
    } else if (winner === "tie"){
        console.log("It was a tie!");
    }
    console.log('You chose ' + playerMove + ' and the computer chose ' + computerMove + ".");
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + "." + '\n');
}
    console.log("Final Score: " + playerWins + " for the player and "+ computerWins + " for the computer.");
    return [playerWins, computerWins];
}
playToFive();
<commit_msg>finally fixed the problem by removing two lines from getWinner<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    if (playerMove === "rock" && computerMove === "paper") {
        winner = "computer";
    } else if (playerMove === "rock" && computerMove === "scissors") {
        winner = "player";
    } else if (playerMove === "paper" && computerMove === "rock") {
        winner = "player";
    } else if (playerMove === "paper" && computerMove === "scissors") {
        winner = "computer";
    } else if (playerMove === "scissors" && computerMove === "paper") {
        winner = "player";
    } else if (playerMove === "scissors" && computerMove === "rock") {
        winner = "computer";
    } else if (playerMove === computerMove){
        winner = "tie";
    } return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    while (playerWins < 5 && computerWins < 5) {
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();
    var winner = getWinner(playerMove, computerMove);
    if (winner === "player"){
        playerWins +=1;
    } else if (winner === "computer"){
        computerWins +=1;
    } else if (winner === "tie"){
        console.log("It was a tie!");
    }
    console.log('You chose ' + playerMove + ' and the computer chose ' + computerMove + ".");
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + "." + '\n');
}
    console.log("The final score is " + playerWins + " points for the player and "+ computerWins + " points for the computer. Congrats to the winner!");
    return [playerWins, computerWins];
}
playToFive();
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    var uniqueIdJs = grunt.config.get('uniqueIdJs'),
        uniqueIdCss = grunt.config.get('uniqueIdCss');

    return {
        options: {
            scriptTemplate: '<script src="{{path}}"></script>',
            linkTemplate: '<link rel="stylesheet" href="{{path}}">'
        },
        js: {
            options: {
                openTag: '<!-- SCRIPTS_START -->',
                closeTag: '<!-- SCRIPTS_END -->'
            },
            src: [`build/atlas.${uniqueIdJs}.libs.js`, `build/atlas.${uniqueIdJs}.js`],
            dest: 'build/index.html'
        },
        css: {
            options: {
                openTag: '<!-- STYLESHEETS_START -->', closeTag: '<!-- STYLESHEETS_END -->'
            },
            src: ['build/atlas.' + uniqueIdCss + '.css'],
            dest: 'build/index.html'
        }
    };
};
<commit_msg>format fix<commit_after>module.exports = function (grunt) {
    var uniqueIdJs = grunt.config.get('uniqueIdJs'),
        uniqueIdCss = grunt.config.get('uniqueIdCss');

    return {
        options: {
            scriptTemplate: '<script src="{{path}}"></script>',
            linkTemplate: '<link rel="stylesheet" href="{{path}}">'
        },
        js: {
            options: {
                openTag: '<!-- SCRIPTS_START -->',
                closeTag: '<!-- SCRIPTS_END -->'
            },
            src: [`build/atlas.${uniqueIdJs}.libs.js`, `build/atlas.${uniqueIdJs}.js`],
            dest: 'build/index.html'
        },
        css: {
            options: {
                openTag: '<!-- STYLESHEETS_START -->',
                closeTag: '<!-- STYLESHEETS_END -->'
            },
            src: ['build/atlas.' + uniqueIdCss + '.css'],
            dest: 'build/index.html'
        }
    };
};
<|endoftext|>


<commit_before>'use strict';

var FFmpeg = require('fluent-ffmpeg');
var validator = require('validator');
var url = require('url');
var colors = require('colors');
var request = require('request');
var exec = require('child_process').exec;
var fs = require('fs');
var config = require('../config/config');
var path = require('path');
var mime = require('mime');

/**
 * Removes the temporary uploaded file from the server
 * @param  {string}   filePath The path of the file
 * @param  {function} callback The callback function to send back
 * @return {function} callback ^
 */
function _removeFile(filePath, callback) {
  fs.unlink(filePath, function(err) {
    if(err) {
      return callback(err);
    }
    return callback();
  });
}

function _convertVideo(filePath, uploadDir, fileNoExt) {
  var mkvextract = 'mkvextract tracks ' + filePath + ' 2:' + uploadDir + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
  var subtitleLine;
  var child = exec(mkvextract, function (err, stdout, stderr) {
    if (err) {
      console.log('Mkvextract error: ', err.red);
    } else {
      console.log('Mkvextract completed.'.green);
      var command;
      if ('development' === config.env) {
        subtitleLine = '-vf ass=' + uploadDir + '/' + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
        // FFMPEG time!
        command = new FFmpeg({source: filePath})
          .withVideoCodec('libx264')
          .withVideoBitrate('512k')
          .withAudioCodec('libfdk_aac')
          .withAudioBitrate('128k')
          .setDuration('2:00')
          .withSize('1280x720')
          .withFps(30)
          .withAudioFrequency(48000)
          .toFormat('mp4')
          .addOptions(['-profile:v main', '-movflags faststart', subtitleLine])
          .on('start', function(commandLine) {
              console.log('Spawned FFmpeg with command: ' + commandLine.blue);
          })
          .on('codecData', function(data) {
              // The 'codecData' event is emitted when FFmpeg first
              // reports input codec information. 'data' contains
              // the following information:
              // - 'format': input format
              // - 'duration': input duration
              // - 'audio': audio codec
              // - 'audio_details': audio encoding details
              // - 'video': video codec
              // - 'video_details': video encoding details
              console.log('Input is ' + data.audio + ' audio with ' + data.video + ' video'.blue);
          })
          .on('progress', function(progress) {
              // The 'progress' event is emitted every time FFmpeg
              // reports progress information. 'progress' contains
              // the following information:
              // - 'frames': the total processed frame count
              // - 'currentFps': the framerate at which FFmpeg is
              //   currently processing
              // - 'currentKbps': the throughput at which FFmpeg is
              //   currently processing
              // - 'targetSize': the current size of the target file
              //   in kilobytes
              // - 'timemark': the timestamp of the current frame
              //   in seconds
              // - 'percent': an estimation of the progress
              console.log('Processing: ' + progress.percent + '% done');
          })
          .on('error', function(err, stdout, stderr) {
              console.log("ffmpeg stdout:\n" + stdout);
              console.log("ffmpeg stderr:\n" + stderr);
              // The 'error' event is emitted when an error occurs,
              // either when preparing the FFmpeg process or while
              // it is running
              console.log('Cannot process video: ' + err.message.red);
              console.log(err);
          })
          .on('end', function() {
              // The 'end' event is emitted when FFmpeg finishes
              // processing.
              console.log('Processing finished successfully'.green);
          })
          .saveToFile(path.resolve(uploadDir + '/' + fileNoExt + '.mp4'));
      } else{
        subtitleLine = '-vf ass=' + uploadDir + '/' + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
        // FFMPEG time!
        command = new FFmpeg({source: filePath})
          .withVideoCodec('libx264')
          .withVideoBitrate('512k')
          .withAudioCodec('libfdk_aac')
          .withAudioBitrate('128k')
          .withSize('1280x720')
          .withFps(30)
          .withAudioFrequency(48000)
          .toFormat('mp4')
          .addOptions(['-profile:v main', '-movflags faststart', subtitleLine])
          .on('start', function(commandLine) {
              console.log('Spawned FFmpeg with command: ' + commandLine.blue);
          })
          .on('codecData', function(data) {
              // The 'codecData' event is emitted when FFmpeg first
              // reports input codec information. 'data' contains
              // the following information:
              // - 'format': input format
              // - 'duration': input duration
              // - 'audio': audio codec
              // - 'audio_details': audio encoding details
              // - 'video': video codec
              // - 'video_details': video encoding details
              console.log('Input is ' + data.audio + ' audio with ' + data.video + ' video'.blue);
          })
          .on('progress', function(progress) {
              // The 'progress' event is emitted every time FFmpeg
              // reports progress information. 'progress' contains
              // the following information:
              // - 'frames': the total processed frame count
              // - 'currentFps': the framerate at which FFmpeg is
              //   currently processing
              // - 'currentKbps': the throughput at which FFmpeg is
              //   currently processing
              // - 'targetSize': the current size of the target file
              //   in kilobytes
              // - 'timemark': the timestamp of the current frame
              //   in seconds
              // - 'percent': an estimation of the progress
              console.log('Processing: ' + progress.percent + '% done');
          })
          .on('error', function(err, stdout, stderr) {
              console.log("ffmpeg stdout:\n" + stdout);
              console.log("ffmpeg stderr:\n" + stderr);
              // The 'error' event is emitted when an error occurs,
              // either when preparing the FFmpeg process or while
              // it is running
              console.log('Cannot process video: ' + err.message.red);
          })
          .on('end', function() {
              // The 'end' event is emitted when FFmpeg finishes
              // processing.
              console.log('Processing finished successfully'.green);
          })
          .saveToFile(path.resolve(uploadDir + '/' + fileNoExt + '.mp4'));
        }
    }
  });
  child.stdout.on('data', function(data) { console.log(data.toString()); });
  child.stderr.on('data', function(data) { console.log(data.toString()); });
  child.on('exit', function() {  console.error('Child process exited'.blue); });
}

function _uploadURL(videoURL, uploadDir, uploadRelative, res) {
  // Get the name of the video including the extension
  var filenameArr = url.parse(videoURL).pathname.split('/');
  var filename = filenameArr[filenameArr.length - 1];
  // Create file and relative paths based on type of video
  var filePath = null;
  var relativePath = null;
  var fileNoExt = filename.slice(0, -4).replace(/ /g, "_");
  filePath = path.resolve(config.root + '/' + uploadDir + filename);
  relativePath = uploadRelative + filename;
  // Download the video
  var videoReq = request(videoURL);
  // Pipe the video to the chosen path
  videoReq.pipe(fs.createWriteStream(filePath.replace(/ /g, '_')));
  videoReq.on('response', function(resp) {
    if(resp.statusCode !== 200 && resp.statusCode !== 304) {
      return res.json(400, {message: 'Video could not be downloaded.'});
    }
    // If file is not an video, failed.
    if(!validator.isVideo(filePath)) {
      _removeFile(filePath, function (err) {
        return res.json(400, {message: 'Only video is allowed.'});
      });
    }
    // Get video size
    var videoSize = fs.statSync(filePath).size;
    _convertVideo(filePath.replace(/ /g, "_"), uploadDir, fileNoExt);
    return res.json({message: 'Video uploaded, conversion has started.'});
  });
}

function _uploadFile(video, uploadDir, uploadRelative, res) {
  // Check to see if video is an video based on MIME-type
  var videoPath = video.path;
  var fileNoExt = video.originalFilename.slice(0, -4).replace(/ /g, "_");
  if(!validator.isVideo(videoPath)) {
    _removeFile(videoPath, function (err) {
      return res.json(400, {message: 'Only video is allowed.'});
    });
  }
  var targetPath = path.resolve(uploadDir + '/' + video.originalFilename).replace(/ /g, "_");
  // Move from temp path to new path
  fs.rename(videoPath, targetPath, function(err) {
    if(err) {
      console.log('File Rename');
      console.log(err);
      return res.json(500, {message: 'Problem moving video.'});
    }
    _convertVideo(targetPath, uploadDir, fileNoExt);
    return res.json({message: 'Video uploaded, conversion has started.'});
  });
}

exports.uploadVideo = function(req, res) {
  var video = req.files.file[0];
  var videoURL = req.body.url;
  // If the video is a string and its not a url
  if(!validator.isNull(videoURL) && !validator.isURL(videoURL)) {
    return res.json(400, {message: 'Invalid URL.'});
  }
  if(validator.isURL(videoURL)) {
    return _uploadURL(videoURL, req.uploadDir, req.uploadRelative, res);
  } else {
    return _uploadFile(video, req.uploadDir, req.uploadRelative, res);
  }
};

validator.extend('isVideo', function(str) {
  var videoTypes = ['application/annodex','application/mp4','application/ogg','application/vnd.rn-realmedia','application/x-matroska','video/3gpp','video/3gpp2','video/annodex','video/divx','video/flv','video/h264','video/mp4','video/mp4v-es','video/mpeg','video/mpeg-2','video/mpeg4','video/ogg','video/ogm','video/quicktime','video/ty','video/vdo','video/vivo','video/vnd.rn-realvideo','video/vnd.vivo','video/webm','video/x-bin','video/x-cdg','video/x-divx','video/x-dv','video/x-flv','video/x-la-asf','video/x-m4v','video/x-matroska','video/x-motion-jpeg','video/x-ms-asf','video/x-ms-dvr','video/x-ms-wm','video/x-ms-wmv','video/x-msvideo','video/x-sgi-movie','video/x-tivo','video/avi','video/x-ms-asx','video/x-ms-wvx','video/x-ms-wmx'];
    var videotype = mime.lookup(str);
    for(var typeCtr = 0; typeCtr < videoTypes.length; typeCtr++) {
      if(videoTypes[typeCtr] === videotype) {
        return true;
      }
    }
    return false;
});<commit_msg>Fixed subtitle path when converting video.<commit_after>'use strict';

var FFmpeg = require('fluent-ffmpeg');
var validator = require('validator');
var url = require('url');
var colors = require('colors');
var request = require('request');
var exec = require('child_process').exec;
var fs = require('fs');
var config = require('../config/config');
var path = require('path');
var mime = require('mime');

/**
 * Removes the temporary uploaded file from the server
 * @param  {string}   filePath The path of the file
 * @param  {function} callback The callback function to send back
 * @return {function} callback ^
 */
function _removeFile(filePath, callback) {
  fs.unlink(filePath, function(err) {
    if(err) {
      return callback(err);
    }
    return callback();
  });
}

function _convertVideo(filePath, uploadDir, fileNoExt) {
  var mkvextract = 'mkvextract tracks ' + filePath + ' 2:' + uploadDir + '/' + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
  var subtitleLine;
  var child = exec(mkvextract, function (err, stdout, stderr) {
    if (err) {
      console.log('Mkvextract error: ', err.red);
    } else {
      console.log('Mkvextract completed.'.green);
      var command;
      if ('development' === config.env) {
        subtitleLine = '-vf ass=' + uploadDir + '/' + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
        // FFMPEG time!
        command = new FFmpeg({source: filePath})
          .withVideoCodec('libx264')
          .withVideoBitrate('512k')
          .withAudioCodec('libfdk_aac')
          .withAudioBitrate('128k')
          .setDuration('2:00')
          .withSize('1280x720')
          .withFps(30)
          .withAudioFrequency(48000)
          .toFormat('mp4')
          .addOptions(['-profile:v main', '-movflags faststart', subtitleLine])
          .on('start', function(commandLine) {
              console.log('Spawned FFmpeg with command: ' + commandLine.blue);
          })
          .on('codecData', function(data) {
              // The 'codecData' event is emitted when FFmpeg first
              // reports input codec information. 'data' contains
              // the following information:
              // - 'format': input format
              // - 'duration': input duration
              // - 'audio': audio codec
              // - 'audio_details': audio encoding details
              // - 'video': video codec
              // - 'video_details': video encoding details
              console.log('Input is ' + data.audio + ' audio with ' + data.video + ' video'.blue);
          })
          .on('progress', function(progress) {
              // The 'progress' event is emitted every time FFmpeg
              // reports progress information. 'progress' contains
              // the following information:
              // - 'frames': the total processed frame count
              // - 'currentFps': the framerate at which FFmpeg is
              //   currently processing
              // - 'currentKbps': the throughput at which FFmpeg is
              //   currently processing
              // - 'targetSize': the current size of the target file
              //   in kilobytes
              // - 'timemark': the timestamp of the current frame
              //   in seconds
              // - 'percent': an estimation of the progress
              console.log('Processing: ' + progress.percent + '% done');
          })
          .on('error', function(err, stdout, stderr) {
              console.log("ffmpeg stdout:\n" + stdout);
              console.log("ffmpeg stderr:\n" + stderr);
              // The 'error' event is emitted when an error occurs,
              // either when preparing the FFmpeg process or while
              // it is running
              console.log('Cannot process video: ' + err.message.red);
              console.log(err);
          })
          .on('end', function() {
              // The 'end' event is emitted when FFmpeg finishes
              // processing.
              console.log('Processing finished successfully'.green);
          })
          .saveToFile(path.resolve(uploadDir + '/' + fileNoExt + '.mp4'));
      } else{
        subtitleLine = '-vf ass=' + uploadDir + '/' + fileNoExt.replace(/\[/g, '\\[').replace(/\]/g, '\\]') + '.ass';
        // FFMPEG time!
        command = new FFmpeg({source: filePath})
          .withVideoCodec('libx264')
          .withVideoBitrate('512k')
          .withAudioCodec('libfdk_aac')
          .withAudioBitrate('128k')
          .withSize('1280x720')
          .withFps(30)
          .withAudioFrequency(48000)
          .toFormat('mp4')
          .addOptions(['-profile:v main', '-movflags faststart', subtitleLine])
          .on('start', function(commandLine) {
              console.log('Spawned FFmpeg with command: ' + commandLine.blue);
          })
          .on('codecData', function(data) {
              // The 'codecData' event is emitted when FFmpeg first
              // reports input codec information. 'data' contains
              // the following information:
              // - 'format': input format
              // - 'duration': input duration
              // - 'audio': audio codec
              // - 'audio_details': audio encoding details
              // - 'video': video codec
              // - 'video_details': video encoding details
              console.log('Input is ' + data.audio + ' audio with ' + data.video + ' video'.blue);
          })
          .on('progress', function(progress) {
              // The 'progress' event is emitted every time FFmpeg
              // reports progress information. 'progress' contains
              // the following information:
              // - 'frames': the total processed frame count
              // - 'currentFps': the framerate at which FFmpeg is
              //   currently processing
              // - 'currentKbps': the throughput at which FFmpeg is
              //   currently processing
              // - 'targetSize': the current size of the target file
              //   in kilobytes
              // - 'timemark': the timestamp of the current frame
              //   in seconds
              // - 'percent': an estimation of the progress
              console.log('Processing: ' + progress.percent + '% done');
          })
          .on('error', function(err, stdout, stderr) {
              console.log("ffmpeg stdout:\n" + stdout);
              console.log("ffmpeg stderr:\n" + stderr);
              // The 'error' event is emitted when an error occurs,
              // either when preparing the FFmpeg process or while
              // it is running
              console.log('Cannot process video: ' + err.message.red);
          })
          .on('end', function() {
              // The 'end' event is emitted when FFmpeg finishes
              // processing.
              console.log('Processing finished successfully'.green);
          })
          .saveToFile(path.resolve(uploadDir + '/' + fileNoExt + '.mp4'));
        }
    }
  });
  child.stdout.on('data', function(data) { console.log(data.toString()); });
  child.stderr.on('data', function(data) { console.log(data.toString()); });
  child.on('exit', function() {  console.error('Child process exited'.blue); });
}

function _uploadURL(videoURL, uploadDir, uploadRelative, res) {
  // Get the name of the video including the extension
  var filenameArr = url.parse(videoURL).pathname.split('/');
  var filename = filenameArr[filenameArr.length - 1];
  // Create file and relative paths based on type of video
  var filePath = null;
  var relativePath = null;
  var fileNoExt = filename.slice(0, -4).replace(/ /g, "_");
  filePath = path.resolve(config.root + '/' + uploadDir + filename);
  relativePath = uploadRelative + filename;
  // Download the video
  var videoReq = request(videoURL);
  // Pipe the video to the chosen path
  videoReq.pipe(fs.createWriteStream(filePath.replace(/ /g, '_')));
  videoReq.on('response', function(resp) {
    if(resp.statusCode !== 200 && resp.statusCode !== 304) {
      return res.json(400, {message: 'Video could not be downloaded.'});
    }
    // If file is not an video, failed.
    if(!validator.isVideo(filePath)) {
      _removeFile(filePath, function (err) {
        return res.json(400, {message: 'Only video is allowed.'});
      });
    }
    // Get video size
    var videoSize = fs.statSync(filePath).size;
    _convertVideo(filePath.replace(/ /g, "_"), uploadDir, fileNoExt);
    return res.json({message: 'Video uploaded, conversion has started.'});
  });
}

function _uploadFile(video, uploadDir, uploadRelative, res) {
  // Check to see if video is an video based on MIME-type
  var videoPath = video.path;
  var fileNoExt = video.originalFilename.slice(0, -4).replace(/ /g, "_");
  if(!validator.isVideo(videoPath)) {
    _removeFile(videoPath, function (err) {
      return res.json(400, {message: 'Only video is allowed.'});
    });
  }
  var targetPath = path.resolve(uploadDir + '/' + video.originalFilename).replace(/ /g, "_");
  // Move from temp path to new path
  fs.rename(videoPath, targetPath, function(err) {
    if(err) {
      console.log('File Rename');
      console.log(err);
      return res.json(500, {message: 'Problem moving video.'});
    }
    _convertVideo(targetPath, uploadDir, fileNoExt);
    return res.json({message: 'Video uploaded, conversion has started.'});
  });
}

exports.uploadVideo = function(req, res) {
  var video = req.files.file[0];
  var videoURL = req.body.url;
  // If the video is a string and its not a url
  if(!validator.isNull(videoURL) && !validator.isURL(videoURL)) {
    return res.json(400, {message: 'Invalid URL.'});
  }
  if(validator.isURL(videoURL)) {
    return _uploadURL(videoURL, req.uploadDir, req.uploadRelative, res);
  } else {
    return _uploadFile(video, req.uploadDir, req.uploadRelative, res);
  }
};

validator.extend('isVideo', function(str) {
  var videoTypes = ['application/annodex','application/mp4','application/ogg','application/vnd.rn-realmedia','application/x-matroska','video/3gpp','video/3gpp2','video/annodex','video/divx','video/flv','video/h264','video/mp4','video/mp4v-es','video/mpeg','video/mpeg-2','video/mpeg4','video/ogg','video/ogm','video/quicktime','video/ty','video/vdo','video/vivo','video/vnd.rn-realvideo','video/vnd.vivo','video/webm','video/x-bin','video/x-cdg','video/x-divx','video/x-dv','video/x-flv','video/x-la-asf','video/x-m4v','video/x-matroska','video/x-motion-jpeg','video/x-ms-asf','video/x-ms-dvr','video/x-ms-wm','video/x-ms-wmv','video/x-msvideo','video/x-sgi-movie','video/x-tivo','video/avi','video/x-ms-asx','video/x-ms-wvx','video/x-ms-wmx'];
    var videotype = mime.lookup(str);
    for(var typeCtr = 0; typeCtr < videoTypes.length; typeCtr++) {
      if(videoTypes[typeCtr] === videotype) {
        return true;
      }
    }
    return false;
});<|endoftext|>


<commit_before>WistiaDoc = {
  url: "http://wistia.com",
  path: "/newdoc",
  port: "4000",
  search_path: "/search",
  search_port: "9393",
  search_app_url: function() {
    return WistiaDoc.url + ":" + WistiaDoc.search_port + WistiaDoc.path + WistiaDoc.search_path;
  },
  web_app_url: function() {
    return WistiaDoc.url + ":" + WistiaDoc.port + WistiaDoc.path;
  }
};
<commit_msg>js config update with colon in port integer<commit_after>WistiaDoc = {
  url: "http://wistia.com",
  path: "/newdoc",
  port: ":4000",
  search_path: "/search",
  search_port: ":9393",
  search_app_url: function() {
    return WistiaDoc.url + WistiaDoc.search_port + WistiaDoc.path + WistiaDoc.search_path;
  },
  web_app_url: function() {
    return WistiaDoc.url + WistiaDoc.port + WistiaDoc.path;
  }
};
<|endoftext|>


<commit_before>"use strict";

// Dependencies
var url = require("url");
var async = require("async");
var fs = require("fs");
var https = require("https");

// App variables
var BASE_URL = "https://en.wikipedia.org/wiki/";
var file_url = [
  "Adria_Airways_destinations",
  "AeroSur_destinations",
  "Aegean_Airlines_destinations",
  "Air_Austral_destinations",
  "Air_Nippon_destinations",
  "Air_Arabia_Maroc_destinations",
  "Air_Chathams_destinations",
  "VietJet_Air_destinations",
  "Aeroper%C3%BA_destinations",
  "Category:Lists_of_airline_destinations"
];
var DOWNLOAD_DIR = "./test/spec/models/";

var download_file_httpsGet = function (file_url, callback) {
  if (file_url.indexOf("https") === -1) {
    file_url = BASE_URL + file_url;
  }

  var file_name = url.parse(file_url).pathname.split("/").pop() + ".html";

  file_name = file_name.split(":").pop();
  console.log("filename: " + file_name);//eslint-disable-line no-console
  var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

  https.get(file_url, function (res) {
    res.on("data", function (chunk) {
      file.write(chunk);
    }).on("error", function (err) {
      throw err;
    }).on("end", function () {
      file.end();
      console.log(file_name + " downloaded to " + DOWNLOAD_DIR);//eslint-disable-line no-console
      callback();
    });
  });

};

async.map(file_url, download_file_httpsGet, function (err) {
  if (err) {throw err;}
  console.log("\nModels updated."); //eslint-disable-line no-console
});

<commit_msg>updated so it gets the urls from fixtures JSON<commit_after>"use strict";

// Dependencies
var url = require("url");
var async = require("async");
var fs = require("fs");
var https = require("https");

// App variables
var BASE_URL = "https://en.wikipedia.org/wiki/";
var file_url = [
  "Adria_Airways_destinations",
  "AeroSur_destinations",
  "Aegean_Airlines_destinations",
  "Air_Austral_destinations",
  "Air_Nippon_destinations",
  "Air_Arabia_Maroc_destinations",
  "Air_Chathams_destinations",
  "VietJet_Air_destinations",
  "Aeroper%C3%BA_destinations",
  "Category:Lists_of_airline_destinations"
];
var DOWNLOAD_DIR = "./test/spec/models/";
var fixtures = require("../fixtures/airline_routes.options.json");
var exampleFile = [
  "Category:Lists_of_airline_destinations"
];

for (var i = 0; i < fixtures.length; i+=1) {
  exampleFile.push(fixtures[i].name);
}

var download_file_httpsGet = function (file_url, callback) {
  if (file_url.indexOf("https") === -1) {
    file_url = BASE_URL + file_url;
  }

  var file_name = url.parse(file_url).pathname.split("/").pop() + ".html";

  file_name = file_name.split(":").pop();
  console.log("filename: " + file_name);//eslint-disable-line no-console
  var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

  https.get(file_url, function (res) {
    res.on("data", function (chunk) {
      file.write(chunk);
    }).on("error", function (err) {
      throw err;
    }).on("end", function () {
      file.end();
      console.log(file_name + " downloaded to " + DOWNLOAD_DIR);//eslint-disable-line no-console
      callback();
    });
  });

};

async.map(file_url, download_file_httpsGet, function (err) {
  if (err) {throw err;}
  console.log("\nModels updated."); //eslint-disable-line no-console
});

<|endoftext|>


<commit_before>angular.module('os.administrative.container')
  .directive('osContainerCreator', function(Site, Container, ContainerType, Alerts) {
    function linker(scope, element, attrs) {
      scope.container  = new Container(scope.container || {});

      scope.types = [];
      ContainerType.query().then(
        function(types) {
          scope.types = types;
        }
      );

      scope.sites = [];
      Site.listForContainers('Create').then(
        function(sites) {
          scope.sites = sites;
        }
      );

      scope.createContainer = function() {
        scope.container.$saveOrUpdate().then(
          function(savedContainer) {
            //
            // ID is purposely removed so that same widget can be used for
            // creation of multiple containers
            //
            delete savedContainer.id;
            angular.extend(scope.container, savedContainer);
            Alerts.success('container.creation_success', savedContainer);
          }
        );
      }
    }

    return {
      restrict: 'E',

      templateUrl: 'modules/administrative/container/creator.html',

      scope: {
        container: '='
      },

      compile: function(element, attrs) {
        if (attrs.mdInput == 'true') {
          element.find('input[type="text"], os-select, os-storage-position')
            .attr('os-md-input', 'os-md-input');
        }

        if (attrs.showLabels == 'false') {
          element.find('label').hide();
        }

        return linker;
      }
    }
  });
<commit_msg>PLUGINS-103: Enhanced container create widget to show container type dropdown values based on those configured in metadata. If allowed types is not configured, all provisioned/created types are shown.<commit_after>angular.module('os.administrative.container')
  .directive('osContainerCreator', function(Site, Container, ContainerType, Alerts) {
    function selectType(container, types) {
      if (types.length != 1) {
        return;
      }

      container.typeName = types[0].name;
    }

    function linker(scope, element, attrs) {
      scope.container  = new Container(scope.container || {});

      var data = {};
      if (!!attrs.data) {
        data = JSON.parse(attrs.data);
      }

      var allowedTypes = data.allowedTypes || [];
      if (allowedTypes.length == 0) {
        scope.types = [];
        ContainerType.query().then(
          function(types) {
            scope.types = types;
            selectType(scope.container, scope.types);
          }
        );
      } else {
        scope.types = allowedTypes.map(function(type) { return {name: type}; });
        selectType(scope.container, scope.types);
      }

      scope.sites = [];
      Site.listForContainers('Create').then(
        function(sites) {
          scope.sites = sites;
        }
      );

      scope.createContainer = function() {
        scope.container.$saveOrUpdate().then(
          function(savedContainer) {
            //
            // ID is purposely removed so that same widget can be used for
            // creation of multiple containers
            //
            delete savedContainer.id;
            angular.extend(scope.container, savedContainer);
            Alerts.success('container.creation_success', savedContainer);
          }
        );
      }
    }

    return {
      restrict: 'E',

      templateUrl: 'modules/administrative/container/creator.html',

      scope: {
        container: '='
      },

      compile: function(element, attrs) {
        if (attrs.mdInput == 'true') {
          element.find('input[type="text"], os-select, os-storage-position')
            .attr('os-md-input', 'os-md-input');
        }

        if (attrs.showLabels == 'false') {
          element.find('label').hide();
        }

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


<commit_before>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

    console.log('1');

    req.app.db.models.Wine.findAll({
        where: { createdBy: req.user.id },
        attributes: ['id', 'grape', 'estate', 'name', 'year', 'rating', 'pairing', 'createdBy']
     })
    .error(function(err) {
      // error callback
      console.log('Couldnt find items: ' + err);
      return next(err);
    })
    .success(function(items) {
        console.log('Items returned.');
        console.dir(items);

        outcome.results = items;

    });

    console.log('3');

    if (err) {

    }

    if (req.xhr) {

      res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
      outcome.results.filters = req.query;
      console.log('sending xhr: ');
      console.dir(outcome.results);
      res.send(outcome.results);
    }
    else {
      //?
    }

};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }

    workflow.emit('createAccount');
  });

  workflow.on('createAccount', function() {
    var nameParts = req.body['name.full'].trim().split(/\s/);
    var fieldsToSet = {
      name: {
        first: nameParts.shift(),
        middle: (nameParts.length > 1 ? nameParts.shift() : ''),
        last: (nameParts.length === 0 ? '' : nameParts.join(' ')),
      },
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };
    fieldsToSet.name.full = fieldsToSet.name.first + (fieldsToSet.name.last ? ' '+ fieldsToSet.name.last : '');
    fieldsToSet.search = [
      fieldsToSet.name.first,
      fieldsToSet.name.middle,
      fieldsToSet.name.last
    ];

    req.app.db.models.Account.create(fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.record = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<commit_msg>because of async, moved returncal into query's success fn<commit_after>'use strict';

exports.find = function(req, res, next){
  var outcome = {};

    console.log('1');

    req.app.db.models.Wine.findAll({
        where: { createdBy: req.user.id },
        attributes: ['id', 'grape', 'estate', 'name', 'year', 'rating', 'pairing', 'createdBy']
     })
    .error(function(err) {
      // error callback
      console.log('Couldnt find items: ' + err);
      return next(err);
    })
    .success(function(items) {
        console.log('Items returned.');
        console.dir(items);

        outcome.results = items;
        console.log('3');

        if (req.xhr) {

          res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
          outcome.results.filters = req.query;
          console.log('sending xhr: ');
          console.dir(outcome.results);
          res.send(outcome.results);
        }
        else {
          //?
        }

    });

};

exports.read = function(req, res, next){
  var outcome = {};

  var getStatusOptions = function(callback) {
    req.app.db.models.Status.find({ pivot: 'Account' }, 'name').sort('name').exec(function(err, statuses) {
      if (err) {
        return callback(err, null);
      }

      outcome.statuses = statuses;
      return callback(null, 'done');
    });
  };

  var getRecord = function(callback) {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, record) {
      if (err) {
        return callback(err, null);
      }

      outcome.record = record;
      return callback(null, 'done');
    });
  };

  var asyncFinally = function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.send(outcome.record);
    }
    else {
      res.render('admin/accounts/details', {
        data: {
          record: escape(JSON.stringify(outcome.record)),
          statuses: outcome.statuses
        }
      });
    }
  };

  require('async').parallel([getStatusOptions, getRecord], asyncFinally);
};

exports.create = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body['name.full']) {
      workflow.outcome.errors.push('Please enter a name.');
      return workflow.emit('response');
    }

    workflow.emit('createAccount');
  });

  workflow.on('createAccount', function() {
    var nameParts = req.body['name.full'].trim().split(/\s/);
    var fieldsToSet = {
      name: {
        first: nameParts.shift(),
        middle: (nameParts.length > 1 ? nameParts.shift() : ''),
        last: (nameParts.length === 0 ? '' : nameParts.join(' ')),
      },
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };
    fieldsToSet.name.full = fieldsToSet.name.first + (fieldsToSet.name.last ? ' '+ fieldsToSet.name.last : '');
    fieldsToSet.search = [
      fieldsToSet.name.first,
      fieldsToSet.name.middle,
      fieldsToSet.name.last
    ];

    req.app.db.models.Account.create(fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.record = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.update = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.first) {
      workflow.outcome.errfor.first = 'required';
    }

    if (!req.body.last) {
      workflow.outcome.errfor.last = 'required';
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    var fieldsToSet = {
      name: {
        first: req.body.first,
        middle: req.body.middle,
        last: req.body.last,
        full: req.body.first +' '+ req.body.last
      },
      company: req.body.company,
      phone: req.body.phone,
      zip: req.body.zip,
      search: [
        req.body.first,
        req.body.middle,
        req.body.last,
        req.body.company,
        req.body.phone,
        req.body.zip
      ]
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.linkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not link accounts to users.');
      return workflow.emit('response');
    }

    if (!req.body.newUsername) {
      workflow.outcome.errfor.newUsername = 'required';
      return workflow.emit('response');
    }

    workflow.emit('verifyUser');
  });

  workflow.on('verifyUser', function(callback) {
    req.app.db.models.User.findOne({ username: req.body.newUsername }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User not found.');
        return workflow.emit('response');
      }
      else if (user.roles && user.roles.account && user.roles.account !== req.params.id) {
        workflow.outcome.errors.push('User is already linked to a different account.');
        return workflow.emit('response');
      }

      workflow.user = user;
      workflow.emit('duplicateLinkCheck');
    });
  });

  workflow.on('duplicateLinkCheck', function(callback) {
    req.app.db.models.Account.findOne({ 'user.id': workflow.user._id, _id: {$ne: req.params.id} }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (account) {
        workflow.outcome.errors.push('Another account is already linked to that user.');
        return workflow.emit('response');
      }

      workflow.emit('patchUser');
    });
  });

  workflow.on('patchUser', function() {
    req.app.db.models.User.findByIdAndUpdate(workflow.user._id, { 'roles.account': req.params.id }).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAccount');
    });
  });

  workflow.on('patchAccount', function(callback) {
    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { user: { id: workflow.user._id, name: workflow.user.username } }).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.unlinkUser = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not unlink users from accounts.');
      return workflow.emit('response');
    }

    workflow.emit('patchAccount');
  });

  workflow.on('patchAccount', function() {
    req.app.db.models.Account.findById(req.params.id).exec(function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!account) {
        workflow.outcome.errors.push('Account was not found.');
        return workflow.emit('response');
      }

      var userId = account.user.id;
      account.user = { id: undefined, name: '' };
      account.save(function(err, account) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.outcome.account = account;
        workflow.emit('patchUser', userId);
      });
    });
  });

  workflow.on('patchUser', function(id) {
    req.app.db.models.User.findById(id).exec(function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      if (!user) {
        workflow.outcome.errors.push('User was not found.');
        return workflow.emit('response');
      }

      user.roles.account = undefined;
      user.save(function(err, user) {
        if (err) {
          return workflow.emit('exception', err);
        }

        workflow.emit('response');
      });
    });
  });

  workflow.emit('validate');
};

exports.newNote = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.data) {
      workflow.outcome.errors.push('Data is required.');
      return workflow.emit('response');
    }

    workflow.emit('addNote');
  });

  workflow.on('addNote', function() {
    var noteToAdd = {
      data: req.body.data,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { $push: { notes: noteToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.newStatus = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.body.id) {
      workflow.outcome.errors.push('Please choose a status.');
    }

    if (workflow.hasErrors()) {
      return workflow.emit('response');
    }

    workflow.emit('addStatus');
  });

  workflow.on('addStatus', function() {
    var statusToAdd = {
      id: req.body.id,
      name: req.body.name,
      userCreated: {
        id: req.user._id,
        name: req.user.username,
        time: new Date().toISOString()
      }
    };

    req.app.db.models.Account.findByIdAndUpdate(req.params.id, { status: statusToAdd, $push: { statusLog: statusToAdd } }, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};

exports.delete = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    if (!req.user.roles.admin.isMemberOf('root')) {
      workflow.outcome.errors.push('You may not delete accounts.');
      return workflow.emit('response');
    }

    workflow.emit('deleteAccount');
  });

  workflow.on('deleteAccount', function(err) {
    req.app.db.models.Account.findByIdAndRemove(req.params.id, function(err, account) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.account = account;
      workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<|endoftext|>


<commit_before>window.addEventListener('dragenter', function (e) {
	com.magadanski.utils.addClass(document.body, 'dropTarget');
});

window.addEventListener('dragleave', function (e) {
	if (!e.pageX) com.magadanski.utils.removeClass(document.body, 'dropTarget');
});

window.addEventListener('dragover', function (e) {
	e.preventDefault();
});

window.addEventListener('drop', function (e) {
	e.preventDefault();
	com.magadanski.utils.removeClass(document.body, 'dropTarget');
}, true);

document.addEventListener('DOMContentLoaded', function (e) {
	player = new com.magadanski.Player(document.getElementById('player'));
	subData = new com.magadanski.SubData();

	loadVideoButton = document.getElementById('load-video');
	loadSubtitlesButton = document.getElementById('load-subtitles');

	playerDropTarget = document.getElementById('player-drop-target');
	subDropTarget = document.getElementById('sub-drop-target');

	setStartButton = document.getElementById('set-start');
	setStopButton = document.getElementById('set-stop');
	setStopStartButton = document.getElementById('set-stop-start');

	saveToYouTubeButton = document.getElementById('save-to-youtube');
	loadVideoFromYouTubeButton = document.getElementById('load-video-from-youtube');

	changeFontButton = document.getElementById('change-font');
	helpButton = document.getElementById('help');

	loadVideoButton.addEventListener('change', function (e) {
		if (typeof(e.currentTarget.files) != 'undefined') {
			player.load(e.currentTarget.files[0]);
		}
	});

	playerDropTarget.addEventListener('drop', function (e) {
		if (typeof(e.dataTransfer.files) != 'undefined') {
			player.load(e.dataTransfer.files[0]);
		}
	});

	loadSubtitlesButton.addEventListener('change', function (e) {
		if (typeof(e.currentTarget.files) != 'undefined') {
			loadFileContent(e.currentTarget.files[0], onSubFileLoaded);
		}
	});

	subDropTarget.addEventListener('drop', function (e) {
		if (typeof(e.dataTransfer.files) != 'undefined') {
			loadFileContent(e.dataTransfer.files[0], onSubFileLoaded);
		}
	});

	function onSubFileLoaded(e, fileContent) {
		subData.loadSubs(fileContent);
	}
});

function loadFileContent(file, callback) {
	if (window.FileReader) {
		// TODO: make sure file can be read as text without browser crash
		// http://stackoverflow.com/questions/9265139/html5-filereader-api-crashes-chrome-17-when-reading-large-file-as-slice
		var reader = new FileReader(file);

		reader.onloadend = function(e) {
			console.log(file, e, this);
			return;
			if (typeof(callback) == 'function') {
				callback(e, this.result);
			}
		}

		reader.readAsText(file);
	} else {
		alert('Your browser does not support HTML5 File System access');
	}
}<commit_msg>loadFileContent works in chunks now -- prevent browser crash<commit_after>window.addEventListener('dragenter', function (e) {
	com.magadanski.utils.addClass(document.body, 'dropTarget');
});

window.addEventListener('dragleave', function (e) {
	if (!e.pageX) com.magadanski.utils.removeClass(document.body, 'dropTarget');
});

window.addEventListener('dragover', function (e) {
	e.preventDefault();
});

window.addEventListener('drop', function (e) {
	e.preventDefault();
	com.magadanski.utils.removeClass(document.body, 'dropTarget');
}, true);

document.addEventListener('DOMContentLoaded', function (e) {
	player = new com.magadanski.Player(document.getElementById('player'));
	subData = new com.magadanski.SubData();

	loadVideoButton = document.getElementById('load-video');
	loadSubtitlesButton = document.getElementById('load-subtitles');

	playerDropTarget = document.getElementById('player-drop-target');
	subDropTarget = document.getElementById('sub-drop-target');

	setStartButton = document.getElementById('set-start');
	setStopButton = document.getElementById('set-stop');
	setStopStartButton = document.getElementById('set-stop-start');

	saveToYouTubeButton = document.getElementById('save-to-youtube');
	loadVideoFromYouTubeButton = document.getElementById('load-video-from-youtube');

	changeFontButton = document.getElementById('change-font');
	helpButton = document.getElementById('help');

	loadVideoButton.addEventListener('change', function (e) {
		if (typeof(e.currentTarget.files) != 'undefined') {
			player.load(e.currentTarget.files[0]);
		}
	});

	playerDropTarget.addEventListener('drop', function (e) {
		if (typeof(e.dataTransfer.files) != 'undefined') {
			player.load(e.dataTransfer.files[0]);
		}
	});

	loadSubtitlesButton.addEventListener('change', function (e) {
		if (typeof(e.currentTarget.files) != 'undefined') {
			loadFileContent(e.currentTarget.files[0], onSubFileLoaded);
		}
	});

	subDropTarget.addEventListener('drop', function (e) {
		if (typeof(e.dataTransfer.files) != 'undefined') {
			loadFileContent(e.dataTransfer.files[0], onSubFileLoaded);
		}
	});

	function onSubFileLoaded(e, fileContent) {
		subData.loadSubs(fileContent);
	}
});

function loadFileContent(file, callback) {
	if (window.FileReader) {
		var chunkSize = 2097152; // 2MB
		var startByte = 0;
		var endByte = 0;
		var reader = new FileReader(file);
		var fileContent = null;
		var fileSlice = file.slice || file.webkitSlice || file.mozSlice;

		function readChunk() {
			endByte = Math.min(startByte + chunkSize, file.size);
			reader.readAsText( fileSlice.call(file, startByte, endByte) );
		}

		reader.onloadend = function(e) {
			if (e.target.readyState == FileReader.DONE) {
				fileContent = new Blob([fileContent, e.target.result], { type: 'text/plain; charset=UTF-8', endings: 'native' });

				if (endByte < file.size) {
					startByte += chunkSize;
					readChunk();
				} else {
					if (typeof(callback) == 'function') {
						callback(e, this.result);
					}
				}
			}
		}

		readChunk();
	} else {
		alert('Your browser does not support HTML5 File System access');
	}
}<|endoftext|>


<commit_before>'use strict'

const Promise = require('bluebird')
const _ = require('lodash')

const getLocations = require('./getLocations')
const getHotelsByPath = require('./getHotelsByPath')
const getHotelItem = require('./getHotelItem')
const errors = require('../errors/classes')
const filterHotels = require('./filterHotels')
const limitHotels = require('./limitHotels')

function getHotels (req, res) {
  if (!req.body.cities || !req.body.cities.length) {
    const err = new errors.BadRequest('Cities missing')
    return res.status(err.statusCode).send(err)
  }

  const filterOptions = {
    max_price: req.query.max_price || 100
  }

  const returnHeaders = {}
  const hotelResult = []
  const runLimit = limitHotels.bind(null, hotelResult)
  const hotelOptions = {
    // Add more stuff to get more detailed queries
    and_filter: '253',
    order: req.query.relevance || 'price',
    currency: req.query.currency || 'EUR',
    max_price: filterOptions.max_price,
    start_date: req.query.start_date,
    end_date: req.query.end_date
  }

  return Promise.map(req.body.cities, getLocations).map((location) => {
    location._embedded.locations = location._embedded.locations.filter(location => {
      return location.type === 'path'
    })
    return Promise.map(location._embedded.locations, (basicHotel) => {
      return getHotelsByPath(_.defaults({
        path: basicHotel.path
      }, hotelOptions)).then(runLimit)
    }, {
      concurrency: 4
    })
  }, {
    concurrency: 3
    // If we found enough entries, just ignore all running commands and return the result
  }).catch(errors.HardHotelSearchBreak, () => {}).then(() => {
    returnHeaders['X-Hotels-available'] = hotelResult.length
    return Promise.map(filterHotels(hotelResult, filterOptions), getHotelItem)
  }).then((results) => {
    // Add specific headers to the result if required
    // Note: currently we have a max of approximately 40 entries but this is not our true maximum
    // There might be more
    _.each(returnHeaders, (value, headerKey) => {
      res.append(headerKey, value)
    })
    return res.status(200).send(results)
  }).catch((err) => {
    console.error(err)
    if (err.statusCode) {
      return res.sendStatus(err.statusCode)
    }
    // Urgs :/
    res.sendStatus(500)
  })
}

module.exports = getHotels
<commit_msg>Switch to distance as a default<commit_after>'use strict'

const Promise = require('bluebird')
const _ = require('lodash')

const getLocations = require('./getLocations')
const getHotelsByPath = require('./getHotelsByPath')
const getHotelItem = require('./getHotelItem')
const errors = require('../errors/classes')
const filterHotels = require('./filterHotels')
const limitHotels = require('./limitHotels')

function getHotels (req, res) {
  if (!req.body.cities || !req.body.cities.length) {
    const err = new errors.BadRequest('Cities missing')
    return res.status(err.statusCode).send(err)
  }

  const filterOptions = {
    max_price: req.query.max_price || 100
  }

  const returnHeaders = {}
  const hotelResult = []
  const runLimit = limitHotels.bind(null, hotelResult)
  const hotelOptions = {
    // Add more stuff to get more detailed queries
    and_filter: '253',
    order: req.query.relevance || 'distance',
    currency: req.query.currency || 'EUR',
    max_price: filterOptions.max_price,
    start_date: req.query.start_date,
    end_date: req.query.end_date
  }

  return Promise.map(req.body.cities, getLocations).map((location) => {
    location._embedded.locations = location._embedded.locations.filter(location => {
      return location.type === 'path'
    })
    return Promise.map(location._embedded.locations, (basicHotel) => {
      return getHotelsByPath(_.defaults({
        path: basicHotel.path
      }, hotelOptions)).then(runLimit)
    }, {
      concurrency: 4
    })
  }, {
    concurrency: 3
    // If we found enough entries, just ignore all running commands and return the result
  }).catch(errors.HardHotelSearchBreak, () => {}).then(() => {
    returnHeaders['X-Hotels-available'] = hotelResult.length
    return Promise.map(filterHotels(hotelResult, filterOptions), getHotelItem)
  }).then((results) => {
    // Add specific headers to the result if required
    // Note: currently we have a max of approximately 40 entries but this is not our true maximum
    // There might be more
    _.each(returnHeaders, (value, headerKey) => {
      res.append(headerKey, value)
    })
    return res.status(200).send(results)
  }).catch((err) => {
    console.error(err)
    if (err.statusCode) {
      return res.sendStatus(err.statusCode)
    }
    // Urgs :/
    res.sendStatus(500)
  })
}

module.exports = getHotels
<|endoftext|>


<commit_before>'use strict';

describe('YaTreeviewCtrl', function () {

    // load the controller's module
    beforeEach(module('ya.treeview'));

    var scope, ctrl;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        scope.model = [
            {
                label: 'parent1',
                children: [
                    {
                        label: 'child'
                    }
                ]
            },
            {
                label: 'parent2',
                children: [
                    {
                        label: 'child',
                        children: [
                            {
                                label: 'innerChild'
                            }
                        ]
                    }
                ]
            },
            {
                label: 'parent3'
            }
        ];
        ctrl = $controller('YaTreeviewCtrl', {$scope: scope});
    }));

    it('should create a separate view', function () {
        expect(scope.view).not.toBe(scope.model);
    });

    it('should create a separate view with $model property on each node', function () {
        expect(scope.view[0].$model).toBe(scope.model[0]);
        expect(scope.view[2].$model).toBe(scope.model[2]);
        expect(scope.view[0].$children[0].$model).toBe(scope.model[0].children[0]);
    });

    it('should create a separate view with $parent property on each node', function () {
        expect(scope.view[0].$parent).toBeNull();
        expect(scope.view[0].$children[0].$parent).toBe(scope.model[0]);
        expect(scope.view[1].$children[0].$children[0].$parent).toBe(scope.model[1].children[0]);
    });

    it('should create a separate view with $root property on each node', function () {
        expect(scope.view[0].$root).toBeNull();
        expect(scope.view[0].$children[0].$root).toBe(scope.model[0]);
        expect(scope.view[1].$children[0].$children[0].$root).toBe(scope.model[1]);
    });

    it('should create a separate view with $children property on each node with children', function () {
        expect(scope.view[0].$children.length).toBe(1);
        expect(scope.view[0].$children[0].$children).toBeUndefined();
    });

    it('should have collapsed property on each node', function () {
        expect(scope.view[0].collapsed).toBeDefined();
        expect(scope.view[0].$children[0].collapsed).toBeDefined();
    });
});
<commit_msg>test fixes<commit_after>'use strict';

describe('YaTreeviewCtrl', function () {

    // load the controller's module
    beforeEach(module('ya.treeview'));

    var scope, ctrl;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        scope.model = [
            {
                label: 'parent1',
                children: [
                    {
                        label: 'child'
                    }
                ]
            },
            {
                label: 'parent2',
                children: [
                    {
                        label: 'child',
                        children: [
                            {
                                label: 'innerChild'
                            }
                        ]
                    }
                ]
            },
            {
                label: 'parent3'
            }
        ];
        ctrl = $controller('YaTreeviewCtrl', {$scope: scope});
    }));

    it('should create a separate view', function () {
        expect(scope.tree).not.toBe(scope.model);
    });

    it('should create a separate view with $model property on each node', function () {
        expect(scope.tree[0].$model).toBe(scope.model[0]);
        expect(scope.tree[2].$model).toBe(scope.model[2]);
        expect(scope.tree[0].$children[0].$model).toBe(scope.model[0].children[0]);
    });

    it('should create a separate view with $parent property on each node', function () {
        expect(scope.tree[0].$parent).toBeNull();
        expect(scope.tree[0].$children[0].$parent).toBe(scope.model[0]);
        expect(scope.tree[1].$children[0].$children[0].$parent).toBe(scope.model[1].children[0]);
    });

    it('should create a separate view with $root property on each node', function () {
        expect(scope.tree[0].$root).toBeNull();
        expect(scope.tree[0].$children[0].$root).toBe(scope.model[0]);
        expect(scope.tree[1].$children[0].$children[0].$root).toBe(scope.model[1]);
    });

    it('should create a separate view with $children property on each node with children', function () {
        expect(scope.tree[0].$children.length).toBe(1);
        expect(scope.tree[0].$children[0].$children).toBeUndefined();
    });

    it('should have collapsed property on each node', function () {
        expect(scope.tree[0].collapsed).toBeDefined();
        expect(scope.tree[0].$children[0].collapsed).toBeDefined();
    });
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var app = angular.module('radar.forms.fields');

  function factory(_, sortCohorts, cohortStore, session, hasPermissionForGroup) {
    return {
      restrict: 'A',
      scope: {
        model: '=',
        required: '&'
      },
      templateUrl: 'app/forms/fields/cohort-field.html',
      link: function(scope) {
        scope.$watch(function() {
          return session.user;
        }, function(user) {
          setCohorts([]);

          cohortStore.findMany({isRecruitmentGroup: true}).then(function(cohorts) {
            cohorts = _.filter(cohorts, function(x) {
              return hasPermissionForGroup(user, x, 'RECRUIT_PATIENT');
            });

            setCohorts(cohorts);
          });
        });

        function setCohorts(cohorts) {
          scope.cohorts = sortCohorts(cohorts);
        }
      }
    };
  }

  factory.$inject = ['_', 'sortCohorts', 'cohortStore', 'session', 'hasPermissionForGroup'];

  app.directive('frmRecruitPatientCohortField', factory);
})();
<commit_msg>Use hasDependencies flag<commit_after>(function() {
  'use strict';

  var app = angular.module('radar.forms.fields');

  function factory(_, sortCohorts, cohortStore, session, hasPermissionForGroup) {
    return {
      restrict: 'A',
      scope: {
        model: '=',
        required: '&'
      },
      templateUrl: 'app/forms/fields/cohort-field.html',
      link: function(scope) {
        scope.$watch(function() {
          return session.user;
        }, function(user) {
          setCohorts([]);

          cohortStore.findMany().then(function(cohorts) {
            cohorts = _.filter(cohorts, function(x) {
              return !x.hasDependencies && hasPermissionForGroup(user, x, 'RECRUIT_PATIENT');
            });

            setCohorts(cohorts);
          });
        });

        function setCohorts(cohorts) {
          scope.cohorts = sortCohorts(cohorts);
        }
      }
    };
  }

  factory.$inject = ['_', 'sortCohorts', 'cohortStore', 'session', 'hasPermissionForGroup'];

  app.directive('frmRecruitPatientCohortField', factory);
})();
<|endoftext|>


<commit_before>describe("ActiveRecord", function(){
	var User, records, models, xhr, server;

	beforeEach(function(){
		//User = Class('User','Model').include(PubSub.mixins['pubsub']);
		var pubsub = PubSub.mixins['pubsub'];
		User = Class('User','ActiveRecord').include(pubsub);
		User.configure({attributes:['id','age','name','lastname']});
		models = [
			{id:1,name:'Pepe',lastname:'Rone',age:31},
			{id:2,name:'Goliat',lastname:'One',age:31},
			{id:3,name:'Mortadelo',lastname:'Two',age:51},
			{id:4,name:'Filemon',lastname:'Three',age:21}
		];
		records = [
			{name:'Pepe',lastname:'Rone',age:31},
			{name:'Goliat',lastname:'One',age:31},
			{name:'Mortadelo',lastname:'Two',age:51},
			{name:'Filemon',lastname:'Three',age:21}
		];

		server = sinon.fakeServer.create();
	});

	afterEach(function(){
		if(xhr) xhr.restore();
	});

	it("should register a set of records", function(){
		var user = User.add(records);
		expect(User.count()).toBe(0);
		expect(User.count(true)).toBe(records.length);
	});

	it("should register a set of models", function(){
		var user = User.add(models);
		expect(User.count()).toEqual(User.count(true));
		expect(User.count()).toBe(records.length);
	});

	it("should find users by id",function(){
		User.add(models);
		var user = User.findByPk(1);
		expect(user).toBeTruthy();
		expect(user.id).toBe(1);
		expect(user.name).toBe('Pepe');
	});

	it("should find users by gid",function(){
		User.add(models);
		var res  = User.findByPk(1);
		var user = User.findByGid(res.gid);
		expect(user).toBeTruthy();
		expect(user.gid).toEqual(res.gid);
		expect(user.name).toBe('Pepe');
	});

	it("should find users by attribute",function(){
		User.add(models);
		var user = User.findByAttribute('name', 'Pepe');
		expect(user).toBeTruthy();
		expect(user.id).toEqual(1);
		expect(user.name).toBe('Pepe');
	});

	it("should find all users by attribute",function(){
		User.add(models);
		var users = User.findAllByAttribute('age', 31);
		expect(users).toBeArray();
		expect(users).toHaveLength(2);
		users.every(function(user){
			expect(user.age).toBe(31);
		});
	});

	it("should delete all records",function(){
		User.add(models);
		expect(User.count()).toBe(models.length);
		User.deleteAll();
		expect(User.count()).toBe(0);
	});

	it("Should create models from POJOs",function(){
		User.add(records);
		expect(User.count(true)).toBe(records.length);
		var user = User.findByAttribute('name','Pepe', true);
		expect(user).toBeTruthy();
		expect(user.name).toBe('Pepe');
	});

	it("should select items using a filter method", function(){
		User.add(models);
		var users = User.select(function(item){
			return item.age === 31;
		});

		expect(users).toBeTruthy();
		expect(users).toHaveLength(2);
		expect(users).toEachHave('age', 31);
	});

	it("should create new models from POJOs",function(){
		User.add(models);
		var record = {id:666, name:'Contra',lastname:'Delalora', age:56};
		var model  = User.create(record);
		expect(model).toBeTruthy();
		expect(model.id).toBeTruthy();
		expect(User.count()).toBe(models.length+1);
		expect(User.findByAttribute('name','Contra')).toBeTruthy();
	});

	// it("should create new models from an array of POJOs",function(){
	// 	User.add(models);
	// 	User.add(records);
	// });

	it("should destroy a record",function(){
		User.add(models);

		var record = {id:666, name:'Contra',lastname:'Delalora', age:56};
		var model  = User.create(record);

		var callback = sinon.spy();
		model.subscribe('destroy',callback);
		model.subscribe('beforeDestroy',callback);

		expect(User.count()).toBe(models.length+1);
		expect(User.destroy(666)).toHavePropertieValue('gid',model.gid);
		expect(User.count()).toBe(models.length);
		expect(callback).toHaveBeenCalledTwice();
	});

	it("beforeDestroy should allow us to abort destruction :)",function(){
		User.add(models);
		var model = User.findByPk(1);
		expect(model).toBeTruthy();

		var callback = {};
		callback.beforeDestroy = function beforeDestroy(options){
			options.skipDestroy = true;
		};

		var spy = sinon.spy(callback, 'beforeDestroy');

		model.subscribe('beforeDestroy',callback.beforeDestroy);

		User.destroy(1);

		expect(User.count()).toBe(models.length);
		expect(spy).toHaveBeenCalled();
	});

	it("should check if a model exists",function(){
		User.add(models);
		expect(User.exists(1)).toBeTruthy();
	});

	it("should update new models", function(){

		User.add(models);

		var user = User.findByPk(1);
		expect(user).toBeTruthy();
		expect(user.id).toBe(1);

		var callback = sinon.spy();
		user.subscribe('update.attributes',callback);

		var age = user.age + 10;
		var user2 = User.update(1, {age:age});
		// expect(user.age).not.toBe(age);
		expect(user2.age).toBe(age);
		expect(user.gid).toEqual(user2.gid);
		expect(callback).toHaveBeenCalled();
	});

////////////////////////////////////////////
	it("should sync with server: fetch",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var users = User.fetch();

		// expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('GET');
		expect(requests[0].url).toMatchObject('/api/user/');
	});

	it("should sync with server: create",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.create(records[0]);
		user.save();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('POST');
		expect(requests[0].url).toMatchObject('/api/user/create');
	});

	it("should sync with server: update",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.create(models[0]);
		user.age = 99;
		user.save();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('PUT');
		expect(requests[0].url).toMatchObject('/api/user/update/'+user.id);
	});

	it("should sync with server: delete",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.add(models[0]);
		user.destroy();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('POST');
		expect(requests[0].url).toMatchObject('/api/user/delete/'+user.id);
	});

	it("should sync with server data:fetch all",function(){
		server.respondWith("GET", "/api/user/",
                                [200, { "Content-Type": "application/json" },
                                 '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch();
		server.respond();
		expect(User.count()).toBe(2);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

	it("should sync with server data: fetch by id ",function(){
		server.respondWith("GET", "/api/user/12",
                                [200, { "Content-Type": "application/json" },
                                  '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch(12);
		server.respond();
		expect(User.count()).toBe(2);

		console.log(User.records);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

	it("should sync with server data: create",function(){
		server.respondWith("GET", "/api/user/",
                                [200, { "Content-Type": "application/json" },
                                 '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch();
		server.respond();
		expect(User.count()).toBe(2);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

});<commit_msg>Added test for AR::udpate<commit_after>describe("ActiveRecord", function(){
	var User, records, models, xhr, server;

	beforeEach(function(){
		//User = Class('User','Model').include(PubSub.mixins['pubsub']);
		var pubsub = PubSub.mixins['pubsub'];
		User = Class('User','ActiveRecord').include(pubsub);
		User.configure({attributes:['id','age','name','lastname']});
		models = [
			{id:1,name:'Pepe',lastname:'Rone',age:31},
			{id:2,name:'Goliat',lastname:'One',age:31},
			{id:3,name:'Mortadelo',lastname:'Two',age:51},
			{id:4,name:'Filemon',lastname:'Three',age:21}
		];
		records = [
			{name:'Pepe',lastname:'Rone',age:31},
			{name:'Goliat',lastname:'One',age:31},
			{name:'Mortadelo',lastname:'Two',age:51},
			{name:'Filemon',lastname:'Three',age:21}
		];

		server = sinon.fakeServer.create();
	});

	afterEach(function(){
		if(xhr) xhr.restore();
	});

	it("should register a set of records", function(){
		var user = User.add(records);
		expect(User.count()).toBe(0);
		expect(User.count(true)).toBe(records.length);
	});

	it("should register a set of models", function(){
		var user = User.add(models);
		expect(User.count()).toEqual(User.count(true));
		expect(User.count()).toBe(records.length);
	});

	it("should find users by id",function(){
		User.add(models);
		var user = User.findByPk(1);
		expect(user).toBeTruthy();
		expect(user.id).toBe(1);
		expect(user.name).toBe('Pepe');
	});

	it("should find users by gid",function(){
		User.add(models);
		var res  = User.findByPk(1);
		var user = User.findByGid(res.gid);
		expect(user).toBeTruthy();
		expect(user.gid).toEqual(res.gid);
		expect(user.name).toBe('Pepe');
	});

	it("should find users by attribute",function(){
		User.add(models);
		var user = User.findByAttribute('name', 'Pepe');
		expect(user).toBeTruthy();
		expect(user.id).toEqual(1);
		expect(user.name).toBe('Pepe');
	});

	it("should find all users by attribute",function(){
		User.add(models);
		var users = User.findAllByAttribute('age', 31);
		expect(users).toBeArray();
		expect(users).toHaveLength(2);
		users.every(function(user){
			expect(user.age).toBe(31);
		});
	});

	it("should delete all records",function(){
		User.add(models);
		expect(User.count()).toBe(models.length);
		User.deleteAll();
		expect(User.count()).toBe(0);
	});

	it("Should create models from POJOs",function(){
		User.add(records);
		expect(User.count(true)).toBe(records.length);
		var user = User.findByAttribute('name','Pepe', true);
		expect(user).toBeTruthy();
		expect(user.name).toBe('Pepe');
	});

	it("should select items using a filter method", function(){
		User.add(models);
		var users = User.select(function(item){
			return item.age === 31;
		});

		expect(users).toBeTruthy();
		expect(users).toHaveLength(2);
		expect(users).toEachHave('age', 31);
	});

	it("should create new models from POJOs",function(){
		User.add(models);
		var record = {id:666, name:'Contra',lastname:'Delalora', age:56};
		var model  = User.create(record);
		expect(model).toBeTruthy();
		expect(model.id).toBeTruthy();
		expect(User.count()).toBe(models.length+1);
		expect(User.findByAttribute('name','Contra')).toBeTruthy();
	});

	// it("should create new models from an array of POJOs",function(){
	// 	User.add(models);
	// 	User.add(records);
	// });

	it("should destroy a record",function(){
		User.add(models);

		var record = {id:666, name:'Contra',lastname:'Delalora', age:56};
		var model  = User.create(record);

		var callback = sinon.spy();
		model.subscribe('destroy',callback);
		model.subscribe('beforeDestroy',callback);

		expect(User.count()).toBe(models.length+1);
		expect(User.destroy(666)).toHavePropertieValue('gid',model.gid);
		expect(User.count()).toBe(models.length);
		expect(callback).toHaveBeenCalledTwice();
	});

	it("beforeDestroy should allow us to abort destruction :)",function(){
		User.add(models);
		var model = User.findByPk(1);
		expect(model).toBeTruthy();

		var callback = {};
		callback.beforeDestroy = function beforeDestroy(options){
			options.skipDestroy = true;
		};

		var spy = sinon.spy(callback, 'beforeDestroy');

		model.subscribe('beforeDestroy',callback.beforeDestroy);

		User.destroy(1);

		expect(User.count()).toBe(models.length);
		expect(spy).toHaveBeenCalled();
	});

	it("should check if a model exists",function(){
		User.add(models);
		expect(User.exists(1)).toBeTruthy();
	});

	it("should update new models", function(){

		User.add(models);

		var user = User.findByPk(1);
		expect(user).toBeTruthy();
		expect(user.id).toBe(1);

		var callback = sinon.spy();
		user.subscribe('update.attributes',callback);

		var age = user.age + 10;
		var user2 = User.update(1, {age:age});
		// expect(user.age).not.toBe(age);
		expect(user2.age).toBe(age);
		expect(user.gid).toEqual(user2.gid);
		expect(callback).toHaveBeenCalled();
	});

////////////////////////////////////////////
	it("should sync with server: fetch",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var users = User.fetch();

		// expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('GET');
		expect(requests[0].url).toMatchObject('/api/user/');
	});

	it("should sync with server: create",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.create(records[0]);
		user.save();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('POST');
		expect(requests[0].url).toMatchObject('/api/user/create');
	});

	it("should sync with server: update",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.create(models[0]);
		user.age = 99;
		user.save();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('PUT');
		expect(requests[0].url).toMatchObject('/api/user/update/'+user.id);
	});

	it("should sync with server: delete",function(){
		xhr = sinon.useFakeXMLHttpRequest();
        requests = [];
		xhr.onCreate = function (req) { requests.push(req); };

		var user = User.add(models[0]);
		user.destroy();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('POST');
		expect(requests[0].url).toMatchObject('/api/user/delete/'+user.id);
	});

	it("should sync with server data:fetch all",function(){
		server.respondWith("GET", "/api/user/",
                                [200, { "Content-Type": "application/json" },
                                 '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch();
		server.respond();
		expect(User.count()).toBe(2);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

	it("should sync with server data: fetch by id ",function(){
		server.respondWith("GET", "/api/user/12",
                                [200, { "Content-Type": "application/json" },
                                  '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch(12);
		server.respond();
		expect(User.count()).toBe(2);

		console.log(User.records);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

	it("should sync with server data: create",function(){
		server.respondWith("GET", "/api/user/",
                                [200, { "Content-Type": "application/json" },
                                 '[ { "id": 12, "name": "User","lastname":"Last","age":31 },{ "id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);

		User.fetch();
		server.respond();
		expect(User.count()).toBe(2);

		var user = User.findByPk(12);
		expect(user).toBeTruthy();
		expect(user).toHaveProperties('age','name','lastname');
		expect(user.get('name')).toBe('User');
	});

	it("should sync with server data: update",function(){
		server.respondWith("GET", "/api/user/",
                                [200, { "Content-Type": "application/json" },
                                 '{"id": 1, "name": "User1","lastname":"Last1","age":31 }]'
                                ]);
		var user = User.add(models[0]);
		user.age = 31;
		user.save();
		expect(requests.length).toBe(1);
		expect(requests[0].method).toMatchObject('POST');
		expect(requests[0].url).toMatchObject('/api/user/create');
	});

});<|endoftext|>