<commit_before>var DbCriteria    = require('./db_criteria');
var DbExpression  = require('./db_expression');
var AppModule     = require('app_module');

module.exports = CommandBuilder.inherits( AppModule );

function CommandBuilder( params ) {
  this._init( params );
}

CommandBuilder.prototype.PARAM_PREFIX = ':ap';

CommandBuilder.prototype._init = function( params ) {
  this.super_._init( params );

  var DbSchema = require( './db_schema' );
  if ( !DbSchema.is_instantiate( params.db_schema ) )
    throw new Error( '`db_schema` is not instance of DbSchema in CommandBuilder.init' );

  this._.db_schema      = params.db_schema;
  this._.db_connection  = this.db_schema.db_connection;
};

CommandBuilder.prototype.create_find_command = function( table, criteria, alias ) {
  var select = Array.isArray( criteria.select ) ? criteria.select.join(',') : criteria.select;

  alias = criteria.alias ? criteria.alias : alias || 't';
  alias = this.db_schema.quote_table_name( alias );

  var sql = ( criteria.distinct ? 'SELECT DISTINCT ' : 'SELECT ' ) +
            select + " FROM " + table.raw_name + " AS "  + alias;
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_group(     sql, criteria.group     );
  sql = this.apply_having(    sql, criteria.having    );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_count_command = function( table, criteria, alias ) {

  alias = criteria.alias != '' ? criteria.alias : alias || 't';
  alias = this.db_schema.quote_table_name( alias );

  var sql = ( criteria.distinct ? 'SELECT DISTINCT' : 'SELECT' ) +
            " COUNT(*) FROM " + table.raw_name + " AS " + alias;
  sql = this.apply_join( sql, criteria.join );
  sql = this.apply_condition( sql, criteria.condition );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_delete_command = function( table, criteria ) {

  var sql = "DELETE FROM " +table.raw_name;
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_group(     sql, criteria.group     );
  sql = this.apply_having(    sql, criteria.having    );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_insert_command = function( table, data ) {

  var fields        = [];
  var values        = {};
  var placeholders  = [];

  var i = 0;

  for ( var column_name in data ) {
    var value   = data[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_insert_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    if ( value == null && !column.allow_null ) {
      this.log(
        'CommandBuilder.create_insert_command has aborted try of setting NULL to column `%s` in table `%s`, which is not allow NULL'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    fields.push( column.raw_name );

    if ( value instanceof DbExpression ) {
      placeholders.push( value.expression );

      for ( var n in value.params ) {
        values[ n ] = value.params[ n ];
      }
    }
    else {
      placeholders.push( this.PARAM_PREFIX + i );
      values[ this.PARAM_PREFIX + i ] = column.typecast( value );
      i++;
    }
  }

  if ( !fields.length ) {

    table.each_primary_key( function( pk ) {
      fields.push( table.get_column( pk ).raw_name );
      placeholders.push( 'NULL' );
    } );
  }

  var sql = "INSERT INTO table (fields) VALUES (placeholders)".format({
    table         : table.raw_name,
    fields        : fields.join(', '),
    placeholders  : placeholders.join(', ')
  });

  return this.create_sql_command( sql, values );
}

CommandBuilder.prototype.create_update_command = function( table, data, criteria ) {

  var fields = [];
  var values = {};
  var i      = 0;

  for ( var column_name in data ) {
    var value   = data[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_update_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    if ( value instanceof DbExpression ) {
      fields.push( column.raw_name + '=' + value.expression );

      for ( var n in value.params ) {
        values[ n ] = value.params[ n ];
      }
    }
    else {
      fields.push( column.raw_name + '=' + this.PARAM_PREFIX + i );
      values[ this.PARAM_PREFIX + i ] = column.typecast( value );
      i++;
    }
  }

  if ( !fields.length )
    throw new Error( 'CommandBuilder.create_update_command: No columns are being updated for table ' + table.name );

  var sql = "UPDATE " + table.raw_name + " SET " + fields.join( ', ' );
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, Object.merge( values, criteria.params ) );
}

CommandBuilder.prototype.create_update_counter_command = function( table, counters, criteria ) {

  var fields = [];

  for ( var column_name in counters ) {
    var value   = counters[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_update_counter_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    fields.push( column.raw_name + '=' + column.raw_name + ( value < 0 ? '' : '+' ) + value );
  }

  if ( !fields.length )
    throw new Error( 'No counter columns are being updated for table ' + table.name );

  var sql = "UPDATE " + table.raw_name + " SET " + fields.join(', ');
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );

}

CommandBuilder.prototype.create_sql_command = function( sql, params ) {
  return this.db_connection.create_command( sql ).bind_values( params || {} );
}

CommandBuilder.prototype.apply_join = function( sql, join ) {
  return join != '' ? sql + ' ' + join : sql;
};

CommandBuilder.prototype.apply_condition = function( sql, condition ) {
  return condition != '' ? sql + ' WHERE ' + condition : sql;
};

CommandBuilder.prototype.apply_order = function( sql, order_by ) {
  return order_by != '' ? sql + ' ORDER BY ' + order_by : sql;
};

CommandBuilder.prototype.apply_limit = function( sql, limit, offset ) {
  if ( limit >= 0 ) sql += ' LIMIT ' + Math.round( limit );
  if ( offset > 0 ) sql += ' OFFSET ' + Math.round( offset );

  return sql;
}

CommandBuilder.prototype.apply_group = function( sql, group ) {
  return group != '' ? sql + ' GROUP BY ' + group : sql;
}

CommandBuilder.prototype.apply_having = function( sql, having ) {
  return having != '' ? sql + ' HAVING ' + having : sql;
};

CommandBuilder.prototype.create_criteria = function( condition, params ) {
  condition = condition || '';
  params    = params    || {};

  var criteria;
  if ( condition instanceof DbCriteria ) criteria = condition.clone();
  else if ( condition instanceof Object ) criteria = new DbCriteria( condition );
  else criteria = new DbCriteria({
    condition : condition,
    params    : params
  });

  return criteria;
}

CommandBuilder.prototype.create_pk_criteria = function( table, pk, condition, params, prefix ) {

  var criteria = this.create_criteria( condition, params );
  if ( criteria.alias != '' ) prefix = this.db_schema.quote_table_name( criteria.alias ) + '.';

  if ( !Object.isObject( pk ) && !Array.isArray( pk ) ) pk = [ pk ];
  if ( table.primary_key instanceof Array && Object.isObject( pk ) && !Object.isEmpty( pk ) ) // single composite key
    pk = [ pk ];

  condition = this.create_in_condition( table, table.primary_key, pk, prefix );

  if ( criteria.condition != '' ) criteria.condition = condition + ' AND (' + criteria.condition + ')';
  else criteria.condition = condition;

  return criteria;
}

CommandBuilder.prototype.create_pk_condition = function( table, values, prefix ) {
  return this.create_in_condition( table, table.primary_key, values, prefix );
}

CommandBuilder.prototype.create_column_criteria = function( table, columns, condition, params, prefix ) {

  var criteria = this.create_criteria( condition, params );
  if ( criteria.alias != '' ) prefix = this.db_schema.quote_table_name( criteria.alias ) + '.';

  var conditions  = [];
  var values      = {};
  var i = 0;

  if ( prefix == null ) prefix = table.raw_name + '.';
  for ( var name in columns ) {
    var value   = columns[ name ];
    var column  = table.get_column( name );

    if ( column == null ) throw new Error( 'Table ' + table.name + ' does not have a column named ' + name );

    if ( value instanceof Array )
      conditions.push( this.create_in_condition( table, name, value, prefix ) );
    else if ( value != null ) {
      conditions.push( prefix + column.raw_name + '=' + this.PARAM_PREFIX + i );
      values[ this.PARAM_PREFIX + i ] = value;
      i++;
    }
    else
      conditions.push( prefix + column.raw_name + ' IS NULL' );
  }

  criteria.params = Object.merge( values, criteria.params );
  if ( conditions[0] != undefined ) {
    if ( criteria.condition != '' )
      criteria.condition = conditions.join( ' AND ' ) + ' AND (' + criteria.condition + ')';
    else
      criteria.condition = conditions.join( ' AND ' )
  }
  return criteria;
}

CommandBuilder.prototype.__get_exist_column = function ( table, column_name ) {
  var column = table.get_column( column_name );
  if ( !column )
      throw new Error( 'Table "%s" does not have a column named "%s"'.format( table.name, column_name ) );
  return column;
};

CommandBuilder.prototype.create_in_condition = function( table, column_name, values, prefix ) {
  if ( Object.isEmpty( values ) ) return '0=1';

  if ( !prefix ) prefix = table.raw_name + '.';

  var column;
  var value;

  if ( typeof column_name == "string" ) {      // single key

    column = this.__get_exist_column( table, column_name );

    values = values.map( function( value ) {
      return this.db_connection.quote_value( column.typecast( value ) );
    }, this );

    if ( values.length == 1 )
      return prefix + column.raw_name + ( values[0] == 'NULL' ? ' IS NULL' : '=' + values[0] );
    else
      return prefix + column.raw_name + ' IN (' + values.join(', ') + ')';
  }

  else if ( column_name instanceof Array ) {// composite key: values=array(array('pk1'=>'v1','pk2'=>'v2'),array(...))

    column_name.forEach( function( name ) {
      column = this.__get_exist_column( table, name );

      values.forEach( function( value ) {

        if ( typeof value[ name ] == 'undefined' )
          throw new Error( 'The value for the column `%s` is not supplied when querying the table `%s`'.format( name, table.name ) );

        value[ name ] = this.db_connection.quote_value( column.typecast( value[ name ] ) );

    }, this ); }, this );

    if ( values.length == 1 ) {
      var entries = [];
      for ( var name in values[0] ) {
        value = values[0][ name ];
        entries.push( prefix + table.get_column( name ).raw_name + ( value == 'NULL' ? ' IS NULL' : '=' + value ) );
      }

      return entries.join( ' AND ' );
    }

    return this._create_composite_in_condition( table, values, prefix );
  }

  else
    throw new Error( 'Column name must be either a string or an array ( now: %s ).'.format( column_name ) );
}

CommandBuilder.prototype._create_composite_in_condition = function( table, values, prefix ) {
  var key_names = [];
  for ( var name in values[0] ) key_names.push( prefix + table.get_column(name).raw_name );

  values = values.map( function( value ) {
    return '(' + Object.values( value ).join( ', ' ) + ')';
  } ).join(', ');

  return '(' + key_names.join( ', ' ) + ') IN (' + values + ')';
}

<commit_msg>множественный insert формат: либо прежний (data = { col_name1 : value1, col_name2 : value2,...}) либо ( data = {col_name1 : [value1.1,value1.2,...], col_name2 : [value2.1,value2.2,...] } )<commit_after>var DbCriteria    = require('./db_criteria');
var DbExpression  = require('./db_expression');
var AppModule     = require('app_module');

module.exports = CommandBuilder.inherits( AppModule );

function CommandBuilder( params ) {
  this._init( params );
}

CommandBuilder.prototype.PARAM_PREFIX = ':ap';

CommandBuilder.prototype._init = function( params ) {
  this.super_._init( params );

  var DbSchema = require( './db_schema' );
  if ( !DbSchema.is_instantiate( params.db_schema ) )
    throw new Error( '`db_schema` is not instance of DbSchema in CommandBuilder.init' );

  this._.db_schema      = params.db_schema;
  this._.db_connection  = this.db_schema.db_connection;
};

CommandBuilder.prototype.create_find_command = function( table, criteria, alias ) {
  var select = Array.isArray( criteria.select ) ? criteria.select.join(',') : criteria.select;

  alias = criteria.alias ? criteria.alias : alias || 't';
  alias = this.db_schema.quote_table_name( alias );

  var sql = ( criteria.distinct ? 'SELECT DISTINCT ' : 'SELECT ' ) +
            select + " FROM " + table.raw_name + " AS "  + alias;
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_group(     sql, criteria.group     );
  sql = this.apply_having(    sql, criteria.having    );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_count_command = function( table, criteria, alias ) {

  alias = criteria.alias != '' ? criteria.alias : alias || 't';
  alias = this.db_schema.quote_table_name( alias );

  var sql = ( criteria.distinct ? 'SELECT DISTINCT' : 'SELECT' ) +
            " COUNT(*) FROM " + table.raw_name + " AS " + alias;
  sql = this.apply_join( sql, criteria.join );
  sql = this.apply_condition( sql, criteria.condition );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_delete_command = function( table, criteria ) {

  var sql = "DELETE FROM " +table.raw_name;
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_group(     sql, criteria.group     );
  sql = this.apply_having(    sql, criteria.having    );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );
}

CommandBuilder.prototype.create_insert_command = function( table, data ){

  var fields        = [];
  var values        = {};
  var placeholders  = [];

  var i = 0;
  var subplaceholders = [];
  for ( var column_name in data ) {
    var value   = data[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_insert_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    if ( value == null && !column.allow_null ) {
      this.log(
        'CommandBuilder.create_insert_command has aborted try of setting NULL to column `%s` in table `%s`, which is not allow NULL'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    fields.push( column.raw_name );

    if ( value instanceof DbExpression ) {
      placeholders.push( value.expression );

      for ( var n in value.params ) {
        values[ n ] = value.params[ n ];
      }
    }
    else {
      if( !Array.isArray( value ) ) value = [ value ];
      for( var v = 0, ln = value.length; v < ln; v++ ){
        if( !subplaceholders[ v ] ) subplaceholders[ v ] = [];
        subplaceholders[ v ].push( this.PARAM_PREFIX + i );
        values[ this.PARAM_PREFIX + i ] = column.typecast( value[ v ] );
        i++;
      }
    }
  }

  for( var v = 0, ln = subplaceholders.length; v < ln; v++ ){
    placeholders.push( '(subplaceholder)'.format( {
      subplaceholder : subplaceholders[ v ].join( ', ' )
      })
    );
  }

  if ( !fields.length ) {

    table.each_primary_key( function( pk ) {
      fields.push( table.get_column( pk ).raw_name );
      placeholders.push( 'NULL' );
    } );
  }

  var sql = "INSERT INTO table (fields) VALUES placeholders".format({
    table         : table.raw_name,
    fields        : fields.join(', '),
    placeholders  : placeholders.join(', ')
  });

  return this.create_sql_command( sql, values );
}

CommandBuilder.prototype.create_update_command = function( table, data, criteria ) {

  var fields = [];
  var values = {};
  var i      = 0;

  for ( var column_name in data ) {
    var value   = data[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_update_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    if ( value instanceof DbExpression ) {
      fields.push( column.raw_name + '=' + value.expression );

      for ( var n in value.params ) {
        values[ n ] = value.params[ n ];
      }
    }
    else {
      fields.push( column.raw_name + '=' + this.PARAM_PREFIX + i );
      values[ this.PARAM_PREFIX + i ] = column.typecast( value );
      i++;
    }
  }

  if ( !fields.length )
    throw new Error( 'CommandBuilder.create_update_command: No columns are being updated for table ' + table.name );

  var sql = "UPDATE " + table.raw_name + " SET " + fields.join( ', ' );
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, Object.merge( values, criteria.params ) );
}

CommandBuilder.prototype.create_update_counter_command = function( table, counters, criteria ) {

  var fields = [];

  for ( var column_name in counters ) {
    var value   = counters[ column_name ];
    var column  = table.get_column( column_name );

    if ( !column ) {
      this.log(
        'CommandBuilder.create_update_counter_command can\'t find column `%s` in table `%s`'.format( column_name, table.name ),
        'warning'
      );
      continue;
    }

    fields.push( column.raw_name + '=' + column.raw_name + ( value < 0 ? '' : '+' ) + value );
  }

  if ( !fields.length )
    throw new Error( 'No counter columns are being updated for table ' + table.name );

  var sql = "UPDATE " + table.raw_name + " SET " + fields.join(', ');
  sql = this.apply_join(      sql, criteria.join      );
  sql = this.apply_condition( sql, criteria.condition );
  sql = this.apply_order(     sql, criteria.order     );
  sql = this.apply_limit(     sql, criteria.limit, criteria.offset );

  return this.create_sql_command( sql, criteria.params );

}

CommandBuilder.prototype.create_sql_command = function( sql, params ) {
  return this.db_connection.create_command( sql ).bind_values( params || {} );
}

CommandBuilder.prototype.apply_join = function( sql, join ) {
  return join != '' ? sql + ' ' + join : sql;
};

CommandBuilder.prototype.apply_condition = function( sql, condition ) {
  return condition != '' ? sql + ' WHERE ' + condition : sql;
};

CommandBuilder.prototype.apply_order = function( sql, order_by ) {
  return order_by != '' ? sql + ' ORDER BY ' + order_by : sql;
};

CommandBuilder.prototype.apply_limit = function( sql, limit, offset ) {
  if ( limit >= 0 ) sql += ' LIMIT ' + Math.round( limit );
  if ( offset > 0 ) sql += ' OFFSET ' + Math.round( offset );

  return sql;
}

CommandBuilder.prototype.apply_group = function( sql, group ) {
  return group != '' ? sql + ' GROUP BY ' + group : sql;
}

CommandBuilder.prototype.apply_having = function( sql, having ) {
  return having != '' ? sql + ' HAVING ' + having : sql;
};

CommandBuilder.prototype.create_criteria = function( condition, params ) {
  condition = condition || '';
  params    = params    || {};

  var criteria;
  if ( condition instanceof DbCriteria ) criteria = condition.clone();
  else if ( condition instanceof Object ) criteria = new DbCriteria( condition );
  else criteria = new DbCriteria({
    condition : condition,
    params    : params
  });

  return criteria;
}

CommandBuilder.prototype.create_pk_criteria = function( table, pk, condition, params, prefix ) {

  var criteria = this.create_criteria( condition, params );
  if ( criteria.alias != '' ) prefix = this.db_schema.quote_table_name( criteria.alias ) + '.';

  if ( !Object.isObject( pk ) && !Array.isArray( pk ) ) pk = [ pk ];
  if ( table.primary_key instanceof Array && Object.isObject( pk ) && !Object.isEmpty( pk ) ) // single composite key
    pk = [ pk ];

  condition = this.create_in_condition( table, table.primary_key, pk, prefix );

  if ( criteria.condition != '' ) criteria.condition = condition + ' AND (' + criteria.condition + ')';
  else criteria.condition = condition;

  return criteria;
}

CommandBuilder.prototype.create_pk_condition = function( table, values, prefix ) {
  return this.create_in_condition( table, table.primary_key, values, prefix );
}

CommandBuilder.prototype.create_column_criteria = function( table, columns, condition, params, prefix ) {

  var criteria = this.create_criteria( condition, params );
  if ( criteria.alias != '' ) prefix = this.db_schema.quote_table_name( criteria.alias ) + '.';

  var conditions  = [];
  var values      = {};
  var i = 0;

  if ( prefix == null ) prefix = table.raw_name + '.';
  for ( var name in columns ) {
    var value   = columns[ name ];
    var column  = table.get_column( name );

    if ( column == null ) throw new Error( 'Table ' + table.name + ' does not have a column named ' + name );

    if ( value instanceof Array )
      conditions.push( this.create_in_condition( table, name, value, prefix ) );
    else if ( value != null ) {
      conditions.push( prefix + column.raw_name + '=' + this.PARAM_PREFIX + i );
      values[ this.PARAM_PREFIX + i ] = value;
      i++;
    }
    else
      conditions.push( prefix + column.raw_name + ' IS NULL' );
  }

  criteria.params = Object.merge( values, criteria.params );
  if ( conditions[0] != undefined ) {
    if ( criteria.condition != '' )
      criteria.condition = conditions.join( ' AND ' ) + ' AND (' + criteria.condition + ')';
    else
      criteria.condition = conditions.join( ' AND ' )
  }
  return criteria;
}

CommandBuilder.prototype.__get_exist_column = function ( table, column_name ) {
  var column = table.get_column( column_name );
  if ( !column )
      throw new Error( 'Table "%s" does not have a column named "%s"'.format( table.name, column_name ) );
  return column;
};

CommandBuilder.prototype.create_in_condition = function( table, column_name, values, prefix ) {
  if ( Object.isEmpty( values ) ) return '0=1';

  if ( !prefix ) prefix = table.raw_name + '.';

  var column;
  var value;

  if ( typeof column_name == "string" ) {      // single key

    column = this.__get_exist_column( table, column_name );

    values = values.map( function( value ) {
      return this.db_connection.quote_value( column.typecast( value ) );
    }, this );

    if ( values.length == 1 )
      return prefix + column.raw_name + ( values[0] == 'NULL' ? ' IS NULL' : '=' + values[0] );
    else
      return prefix + column.raw_name + ' IN (' + values.join(', ') + ')';
  }

  else if ( column_name instanceof Array ) {// composite key: values=array(array('pk1'=>'v1','pk2'=>'v2'),array(...))

    column_name.forEach( function( name ) {
      column = this.__get_exist_column( table, name );

      values.forEach( function( value ) {

        if ( typeof value[ name ] == 'undefined' )
          throw new Error( 'The value for the column `%s` is not supplied when querying the table `%s`'.format( name, table.name ) );

        value[ name ] = this.db_connection.quote_value( column.typecast( value[ name ] ) );

    }, this ); }, this );

    if ( values.length == 1 ) {
      var entries = [];
      for ( var name in values[0] ) {
        value = values[0][ name ];
        entries.push( prefix + table.get_column( name ).raw_name + ( value == 'NULL' ? ' IS NULL' : '=' + value ) );
      }

      return entries.join( ' AND ' );
    }

    return this._create_composite_in_condition( table, values, prefix );
  }

  else
    throw new Error( 'Column name must be either a string or an array ( now: %s ).'.format( column_name ) );
}

CommandBuilder.prototype._create_composite_in_condition = function( table, values, prefix ) {
  var key_names = [];
  for ( var name in values[0] ) key_names.push( prefix + table.get_column(name).raw_name );

  values = values.map( function( value ) {
    return '(' + Object.values( value ).join( ', ' ) + ')';
  } ).join(', ');

  return '(' + key_names.join( ', ' ) + ') IN (' + values + ')';
}

<|endoftext|>


<commit_before>'use strict';

var fs = require("fs"),
	vm = require('vm'),
	GitHubApi = require("github"),
	expect = require('expect.js');

// Load adaptive library into the node context
vm.runInThisContext(fs.readFileSync('adaptive-arp-js/adaptive.js'));

describe('adaptive-arp-javascript', function () {

  /**
   * Test to try the current API version of the platform
   */
  it('Check API version', function (done) {

	if (JSON.parse(process.env.TRAVIS_PULL_REQUEST)) {
		done();
	} else {
		var api_version = Adaptive.AppRegistryBridge.getInstance().getAPIVersion();

		var github = new GitHubApi({
			version: "3.0.0"
		});

		github.authenticate({
			type: "token",
			token: process.env.GH_TOKEN_NODE
		});

		github.repos.getTags({
			user: 'AdaptiveMe',
			repo: 'adaptive-arp-api',
			page: 0,
			per_page: 1
		}, function(error, result){
			if (error) {
				console.log("ERROR: " + error);
			} else {
				expect(result[0].name).to.equal(api_version);
				done();
			}
		});
	}
  });

});
<commit_msg>Solve Mocha Error<commit_after>'use strict';

var fs = require("fs"),
	vm = require('vm'),
	GitHubApi = require("github"),
	expect = require('expect.js');

vm.runInThisContext('var window = JSON.parse(\'{}\')'); // To avoid Mocha Explote: ReferenceError: window is not defined

// Load adaptive library into the node context
vm.runInThisContext(fs.readFileSync('adaptive-arp-js/adaptive.js'));

describe('adaptive-arp-javascript', function () {

  /**
   * Test to try the current API version of the platform
   */
  it('Check API version', function (done) {

	if (JSON.parse(process.env.TRAVIS_PULL_REQUEST)) {
		done();
	} else {
		var apiVersion = Adaptive.AppRegistryBridge.getInstance().getAPIVersion();

		var github = new GitHubApi({
			version: "3.0.0"
		});

		github.authenticate({
			type: "token",
			token: process.env.GH_TOKEN_NODE
		});

		github.repos.getTags({
			user: 'AdaptiveMe',
			repo: 'adaptive-arp-api',
			page: 0,
			per_page: 1
		}, function(error, result){
			if (error) {
				console.log("ERROR: " + error);
			} else {
				expect(result[0].name).to.equal(apiVersion);
				done();
			}
		});
	}
  });

});
<|endoftext|>


<commit_before>var _ = require('underscore')._,
    path = require('path'),
    Tile = require('tilelive.js').Tile;

var mapnik = require('mapnik');
mapnik.register_datasources('/usr/local/lib/mapnik2/input');
mapnik.register_fonts('/usr/local/lib/mapnik2/fonts/');

module.exports = function(app, settings) {
    /**
     * format:
     * - Tile: (png|jpg)
     * - Data Tile: (geojson)
     * - Grid Tile: (*.grid.json)
     */
    app.get('/1.0.0/:mapfile_64/:z/:x/:y.*', function(req, res, next) {
        try {
            var options = {
                scheme: 'tms',
                mapfile: req.param('mapfile_64'),
                xyz: [req.param('x'), req.param('y'), req.param('z')],
                format: req.params[0],
                mapfile_dir: path.join(settings.mapfile_dir)
            };
            var tile = new Tile(options);
        } catch (err) {
            res.send('Tile invalid: ' + err.message);
        }

        tile.render(function(err, data) {
            if (!err) {
                // Using apply here allows the tile rendering
                // function to send custom heades without access
                // to the request object.
                data[1] = _.extend(settings.header_defaults, data[1]);
                res.send.apply(res, data);
            } else {
                res.send('Error rendering image', 500);
                // res.send('', { 'Content-Type': 'image/png' }, 500);
            }
        });
    });
};
<commit_msg>remove registration of mapnik fonts/plugins, since this is already done automatically in node-mapnpik bindings<commit_after>var _ = require('underscore')._,
    path = require('path'),
    Tile = require('tilelive.js').Tile;

module.exports = function(app, settings) {
    /**
     * format:
     * - Tile: (png|jpg)
     * - Data Tile: (geojson)
     * - Grid Tile: (*.grid.json)
     */
    app.get('/1.0.0/:mapfile_64/:z/:x/:y.*', function(req, res, next) {
        try {
            var options = {
                scheme: 'tms',
                mapfile: req.param('mapfile_64'),
                xyz: [req.param('x'), req.param('y'), req.param('z')],
                format: req.params[0],
                mapfile_dir: path.join(settings.mapfile_dir)
            };
            var tile = new Tile(options);
        } catch (err) {
            res.send('Tile invalid: ' + err.message);
        }

        tile.render(function(err, data) {
            if (!err) {
                // Using apply here allows the tile rendering
                // function to send custom heades without access
                // to the request object.
                data[1] = _.extend(settings.header_defaults, data[1]);
                res.send.apply(res, data);
            } else {
                res.send('Error rendering image: ' + err, 500);
                // res.send('', { 'Content-Type': 'image/png' }, 500);
            }
        });
    });
};
<|endoftext|>


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

    var module = angular.module('certification');

    module.controller('CourseClassesController', ['$scope', '$window', 'Evaluation', 'CourseClassesService',
        function($scope, $window, Evaluation, CourseClassesService) {
            // Handle Certification:
            // If class has certification, show the evaluation link
            $scope.errors = {};
            $scope.course_klasses = CourseClassesService.getClasses();
            console.log($scope.course_klasses);
        }
    ]);

    module.controller('CertificateCtrl', ['$scope', 'ClassIdGetter', 'Course', 'CourseCertification', 'CertificateTemplate',
        function($scope, ClassIdGetter, Course, CourseCertification, CertificateTemplate){
            console.log(ClassIdGetter.certificateData());
            $scope.certificate = CourseCertification.get({'link_hash' : ClassIdGetter.certificateData()}, function(certificate) {
//                $scope.certificate = data;

                $scope.course = Course.get({'id' : certificate.course});

                $scope.cert_template = CertificateTemplate.get({'course' : certificate.course });
                return certificate;
            });
        }
    ]);

    module.controller('CertificateTemplateCtrl', ['$sce', '$scope', 'FormUpload', 'ClassIdGetter', 'Course', 'CertificateData',
        function($sce, $scope, FormUpload, ClassIdGetter, Course, CertificateData){

            $scope.certificate_id = ClassIdGetter.certificateDataId();
            $scope.page_title = 'Configurações de template';
            $scope.document_title = '';
            $scope.preview = false;

            $scope.reset = function(event, id){
                $scope.images[id + '_clear'] = true;
                event.currentTarget.src = '';
                var img = document.getElementById(id.replace('_', '-') + "-preview");
                console.log(id);
                img.src = '';
            }

            CertificateData.get({'id' : $scope.certificate_id, }, function(data) {
                $scope.ct = data;
                $scope.page_title += data.type == 'receipt' ? ' de Recibo' :
                    ' de Certificado';
                $scope.message = $sce.trustAsHtml(data.type == 'receipt' ?
                    'Edite as opções do atestado que será emitido ' +
                    'automaticamente após a conclusão do curso.
 Este ' +
                    'atestado não possui a mesma validade ' +
                    'do certificado.' :
                    'Edite os elementos numerados de 1 a 7 ' +
                    'com as informações que serão exibidas no certificado ' +
                    'final do curso.');
                $scope.document_title = data.type == 'receipt' ? "Declaração" :
                    "Certificado";
            }, function(error){
                $scope.alert.error(error.data)
            });

            $scope.saveTemplate = function () {
                $scope.ct.$update({'id' : $scope.certificate_id}, function(updated){
                    var pr = saveImageData();
                    pr.then(function(data){
                        $scope.alert.success('Opções salvas com sucesso!');
                        $scope.images = {};
                    }, function(error){
                        success = false;
                        for (key in error.data) {
                            msg += " : " + error.data[key][0];
                        }
                        $scope.alert.error(msg);
                    });
                }, function(error) {
                    $scope.alert.error('Erro ao salvar dados!');
                });
            }

            $scope.images = {};

            var saveImageData = function(){
                var fu = new FormUpload();
                for (var key in $scope.images) {
                    fu.addField(key, $scope.images[key]);
                }

                return fu.sendTo('/paralapraca/api/certificate_template_images/' + $scope.certificate_id);
            }

        }
    ]);

    module.controller('CertificateDataAdminController', [
        '$scope', '$uibModal', '$window', 'CertificateData', 'Course',
        function ($scope, $uibModal, $window, CertificateData, Course) {
            $scope.certificateList = [];
            $scope.ordering = 'certificate_template.course';
            $scope.reverse = false;
            $scope.filters = {
                type: 'all',
                course: false,
                contract : false,
                textsearch: '',
                check : function(c_data){
                    var f = $scope.filters;
                    var search = f.textsearch.toLowerCase();
                    var target = c_data.certificate_template.course_name.toLowerCase();
                    f.is_clear = f.type == 'all' && !f.course && !f.contract && f.textsearch == ''
                    return (
                        f.type == 'all' || c_data.type == f.type
                    ) && (
                        !search || target.match(search)
                    ) && (
                        !f.contract || c_data.contract.id == f.contract
                    ) && (
                        !f.course || c_data.certificate_template.course == f.course
                    );
                },
                is_clear: true,
                clear: function(){
                    var f = $scope.filters;
                    f.type = 'all';
                    f.course = f.contract = false;
                    f.textsearch = '';
                    f.is_clear = true;
                }
            };

            $scope.generate_templates_modal = function () {
                var modalInstance = $uibModal.open({
                    templateUrl: 'generate_templates_modal.html',
                    controller: ['$scope', '$uibModalInstance', 'CertificateData', 'Contract', 'certificateFormList', 'courses', CertificateModalInstanceCtrl],
                    resolve: {
                        certificateFormList: () => { return $scope.certificateList; },
                        courses: () => { return $scope.courses; }
                    }
                });
                modalInstance.result.then(function (response) {
                    loadData();
                });
            };

            var CertificateModalInstanceCtrl = function ($scope, $uibModalInstance, CertificateData, Contract, certificateFormList, courses) {
                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.certificateFormList = certificateFormList;
                Contract.query({}, function(data){
                    $scope.contracts = data;
                });
                $scope.courses = courses;

                $scope.form_filters = {
                    type: 'all',
                    course: false,
                    contract : false,
                    check : function(c_data){
                        var f = $scope.form_filters;
                        var target = c_data.certificate_template.course_name.toLowerCase();
                        f.has_data = f.course && f.contract
                        if (!f.has_data){
                            return false;
                        }
                        return (
                            f.type == 'all' || c_data.type == f.type
                        ) && (
                            !f.contract || c_data.contract.id == f.contract
                        ) && (
                            !f.course || c_data.certificate_template.course == f.course
                        );
                    },
                    has_data: false,
                };

                $scope.generate_templates = function () {
                    var c_data = new CertificateData({
                        contract: $scope.form_filters.contract,
                        course: $scope.form_filters.course,
                        generate: true
                    });
                    c_data.$save((data) => {
                        $uibModalInstance.close(data);
                    }, (error) => {
                        $uibModalInstance.close(error);
                    });
                };
            };

            var loadData = () => {
                CertificateData.query({}, function(list){
                    $scope.certificateList = list;
                    $scope.certificateFormList = list;
                    var contracts = list.map(function(item){
                        return item.contract;
                    }).reduce(function(prev, curr, i, arr){
                        var index = prev.findIndex(function(item){
                            return item.id == curr.id
                        });
                        index < 0 ? prev.push(curr) : prev;
                        return prev;
                    }, []);

                    $scope.contracts = contracts;
                });
            }
            loadData();

            Course.query({}, function(courses) {
                $scope.courses = courses;
            })

        }
    ]);

    module.controller('ClassEvaluationsController',
    ['$scope', '$uibModal', '$window', '$routeParams', 'CertificationProcess', 'Evaluation', 'Class', 'ClassIdGetter',
    function($scope, $uibModal, $window, $routeParams, CertificationProcess, Evaluation, Class, ClassIdGetter) {
            $scope.errors = {};
            $scope.evaluations = [];

            $scope.stats = {
                has_certificate : 0,
                user_can_certificate : 0,
                user_can_attend : 0,
                upcoming : 0
            };

            $scope.switches = {
                can_certificate : false,
            }

            // FIXME this controller is being used in more than one view with different parameters
            if($routeParams['klassId']) {
                $scope.klass_id = $routeParams['klassId'];
            } else {
                $scope.klass_id = ClassIdGetter.classEditView();
            }

            Class.get({'id' : $scope.klass_id}, function(klass){
                $scope.klass = klass;
                $scope.class_students = klass.students;
                $scope.switches.can_certificate = klass.user_can_certificate;
                $scope.class_evaluations = klass.evaluations;

                if($scope.class_evaluations.length > 0) {
                    var now = new Date().getTime();
                    var next_week = now + 7*24*60*60*1000;

                    for(var i = 0; i < $scope.class_evaluations.length; i++) {
                        evaluation = $scope.class_evaluations[i];
                        var e_date = new Date(evaluation.date).getTime();
                        if ((e_date > now) && (e_date <= next_week)) {
                            $scope.stats.upcoming++;
                        }
                    }
                    $scope.evaluation = $scope.class_evaluations[0];
                }

                $scope.certification_processes = klass.processes;
                for(var i = 0; i < $scope.certification_processes.length; i++){
                    var proc = $scope.certification_processes[i];
                    if(proc.course_certification){
                        $scope.stats.user_can_certificate++;
                        if(!proc.evaluation){
                            $scope.stats.user_can_attend++;
                        }
                    }
                    if(proc.approved){
                        $scope.stats.has_certificate++;
                    }
                }
            });

            $scope.toggleClassCertifiable = function (){
                $scope.switches.can_certificate = false;
                $scope.klass.$update(function(klass){
                    $scope.switches.can_certificate = klass.user_can_certificate;
                })
            }

            $scope.addStudentEvaluation = function () {
                var modalInstance = $uibModal.open(
                    {
                        animation: true,
                        templateUrl: 'addStudentModal.html',
                        controller: ['$scope', '$uibModalInstance', 'processes', 'evaluation', 'students', AddStudentModalCtrl],
                        resolve: {
                            processes: function () {
                                return $scope.certification_processes;
                            },
                            evaluation: function() {
                                return $scope.evaluation;
                            },
                            students: function() {
                                return $scope.class_students;
                            }
                        }
                    }
                );

                modalInstance.result.then(function (class_students) {
                    $scope.user_can_attend = class_students;

                    for(var i = 0; i < $scope.user_can_attend.length; i++){
                        var proc = $scope.user_can_attend[i];
                        if(proc.selected){
                            proc.selected = false;
                            proc.evaluation = $scope.evaluation.id;
                            if(proc.student.id){
                                proc.student = proc.student.id;
                            }
                            proc = new CertificationProcess(proc);

                            proc.$update({}, function(process, data){
                                $scope.evaluation.processes.push(process.id);
                                $scope.certification_processes.filter(function(s){return s.id == process.id;})[0] = process;
                                $scope.stats.user_can_attend--;
                            });
                        }
                    }
                });

            };

            var AddStudentModalCtrl = function ($scope, $uibModalInstance, processes, evaluation, students) {
                $scope.certification_processes = processes;
                $scope.class_students = students;
                $scope.evaluation = evaluation;

                $scope.selectAll = function (select){
                    for(var i = 0; i < $scope.certification_processes.length; i++){
                        if(!$scope.certification_processes[i].evaluation
                                && $scope.certification_processes[i].course_certification)
                            $scope.certification_processes[i].selected = select;
                    }
                }

                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.save = function(){
                    $uibModalInstance.close($scope.certification_processes);
                }
            }

            $scope.createEvaluation = function (isEdit) {
                var modalInstance = $uibModal.open(
                    {
                        animation: true,
                        templateUrl: 'createEvaluationModal.html',
                        controller: ['$scope', '$uibModalInstance', 'klass_id', 'evaluation', CreateUpdateEvaluationModalCtrl],
                        resolve: {
                            klass_id: function () {
                                return $scope.klass_id;
                            },
                            evaluation: function() {
                                if(isEdit){
                                    return $scope.evaluation;
                                } else {
                                    return undefined;
                                }
                            }
                        }
                    }
                );

                modalInstance.result.then(function (evaluation) {
                    if(evaluation.id){
                        evaluation.$update({}, function(updated_eval){
                            // console.log(updated_eval);
                        });
                    } else {
                        evaluation.$save({}, function (new_eval) {
                            $scope.class_evaluations.push(new_eval);
                        });
                    }
                });
            };

            $scope.changeEvaluation = function ($event, $index) {
                $event.preventDefault();
                $scope.evaluation = $scope.class_evaluations[$index];
            };

            var CreateUpdateEvaluationModalCtrl = function ($scope, $uibModalInstance, klass_id, evaluation) {
                if(!evaluation){
                    $scope.evaluation = new Evaluation();
                } else {
                    $scope.evaluation = evaluation;
                }

                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.openCalendar = function(e, b){
                    e.preventDefault();
                    e.stopPropagation();
                    $scope.calendar[b] = true;
                }

                $scope.calendar = {
                    'eval_date' : false,
                    'eval_results_date' : false
                }

                $scope.save = function(){
                    // Write validation
                    $scope.evaluation.klass = klass_id;
                    $uibModalInstance.close($scope.evaluation);
                }
            }

            $scope.isCurrent = function(evaluation_id){
                return evaluation_id == $scope.evaluation.id;
            }

            var evaluation = function($index){
                return $index >= 0 ? $scope.class_evaluations[$index] : false;
            }

            var class_students = function(){
                return $scope.class_students;
            }

        }
    ]);

})(angular);
<commit_msg>certificate settings: add help scope variable<commit_after>(function(angular){
    'use strict';

    var module = angular.module('certification');

    module.controller('CourseClassesController', ['$scope', '$window', 'Evaluation', 'CourseClassesService',
        function($scope, $window, Evaluation, CourseClassesService) {
            // Handle Certification:
            // If class has certification, show the evaluation link
            $scope.errors = {};
            $scope.course_klasses = CourseClassesService.getClasses();
            console.log($scope.course_klasses);
        }
    ]);

    module.controller('CertificateCtrl', ['$scope', 'ClassIdGetter', 'Course', 'CourseCertification', 'CertificateTemplate',
        function($scope, ClassIdGetter, Course, CourseCertification, CertificateTemplate){
            console.log(ClassIdGetter.certificateData());
            $scope.certificate = CourseCertification.get({'link_hash' : ClassIdGetter.certificateData()}, function(certificate) {
//                $scope.certificate = data;

                $scope.course = Course.get({'id' : certificate.course});

                $scope.cert_template = CertificateTemplate.get({'course' : certificate.course });
                return certificate;
            });
        }
    ]);

    module.controller('CertificateTemplateCtrl', ['$sce', '$scope', 'FormUpload', 'ClassIdGetter', 'Course', 'CertificateData',
        function($sce, $scope, FormUpload, ClassIdGetter, Course, CertificateData){

            $scope.certificate_id = ClassIdGetter.certificateDataId();
            $scope.page_title = 'Configurações de template';
            $scope.document_title = '';
            $scope.preview = false;
            $scope.help = false;

            $scope.reset = function(event, id){
                $scope.images[id + '_clear'] = true;
                event.currentTarget.src = '';
                var img = document.getElementById(id.replace('_', '-') + "-preview");
                console.log(id);
                img.src = '';
            }

            CertificateData.get({'id' : $scope.certificate_id, }, function(data) {
                $scope.ct = data;
                $scope.page_title += data.type == 'receipt' ? ' de Recibo' :
                    ' de Certificado';
                $scope.message = $sce.trustAsHtml(data.type == 'receipt' ?
                    'Edite as opções do atestado que será emitido ' +
                    'automaticamente após a conclusão do curso.
 Este ' +
                    'atestado não possui a mesma validade ' +
                    'do certificado.' :
                    'Edite os elementos numerados de 1 a 7 ' +
                    'com as informações que serão exibidas no certificado ' +
                    'final do curso.');
                $scope.document_title = data.type == 'receipt' ? "Declaração" :
                    "Certificado";
            }, function(error){
                $scope.alert.error(error.data)
            });

            $scope.saveTemplate = function () {
                $scope.ct.$update({'id' : $scope.certificate_id}, function(updated){
                    var pr = saveImageData();
                    pr.then(function(data){
                        $scope.alert.success('Opções salvas com sucesso!');
                        $scope.images = {};
                    }, function(error){
                        success = false;
                        for (key in error.data) {
                            msg += " : " + error.data[key][0];
                        }
                        $scope.alert.error(msg);
                    });
                }, function(error) {
                    $scope.alert.error('Erro ao salvar dados!');
                });
            }

            $scope.images = {};

            var saveImageData = function(){
                var fu = new FormUpload();
                for (var key in $scope.images) {
                    fu.addField(key, $scope.images[key]);
                }

                return fu.sendTo('/paralapraca/api/certificate_template_images/' + $scope.certificate_id);
            }

        }
    ]);

    module.controller('CertificateDataAdminController', [
        '$scope', '$uibModal', '$window', 'CertificateData', 'Course',
        function ($scope, $uibModal, $window, CertificateData, Course) {
            $scope.certificateList = [];
            $scope.ordering = 'certificate_template.course';
            $scope.reverse = false;
            $scope.filters = {
                type: 'all',
                course: false,
                contract : false,
                textsearch: '',
                check : function(c_data){
                    var f = $scope.filters;
                    var search = f.textsearch.toLowerCase();
                    var target = c_data.certificate_template.course_name.toLowerCase();
                    f.is_clear = f.type == 'all' && !f.course && !f.contract && f.textsearch == ''
                    return (
                        f.type == 'all' || c_data.type == f.type
                    ) && (
                        !search || target.match(search)
                    ) && (
                        !f.contract || c_data.contract.id == f.contract
                    ) && (
                        !f.course || c_data.certificate_template.course == f.course
                    );
                },
                is_clear: true,
                clear: function(){
                    var f = $scope.filters;
                    f.type = 'all';
                    f.course = f.contract = false;
                    f.textsearch = '';
                    f.is_clear = true;
                }
            };

            $scope.generate_templates_modal = function () {
                var modalInstance = $uibModal.open({
                    templateUrl: 'generate_templates_modal.html',
                    controller: ['$scope', '$uibModalInstance', 'CertificateData', 'Contract', 'certificateFormList', 'courses', CertificateModalInstanceCtrl],
                    resolve: {
                        certificateFormList: () => { return $scope.certificateList; },
                        courses: () => { return $scope.courses; }
                    }
                });
                modalInstance.result.then(function (response) {
                    loadData();
                });
            };

            var CertificateModalInstanceCtrl = function ($scope, $uibModalInstance, CertificateData, Contract, certificateFormList, courses) {
                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.certificateFormList = certificateFormList;
                Contract.query({}, function(data){
                    $scope.contracts = data;
                });
                $scope.courses = courses;

                $scope.form_filters = {
                    type: 'all',
                    course: false,
                    contract : false,
                    check : function(c_data){
                        var f = $scope.form_filters;
                        var target = c_data.certificate_template.course_name.toLowerCase();
                        f.has_data = f.course && f.contract
                        if (!f.has_data){
                            return false;
                        }
                        return (
                            f.type == 'all' || c_data.type == f.type
                        ) && (
                            !f.contract || c_data.contract.id == f.contract
                        ) && (
                            !f.course || c_data.certificate_template.course == f.course
                        );
                    },
                    has_data: false,
                };

                $scope.generate_templates = function () {
                    var c_data = new CertificateData({
                        contract: $scope.form_filters.contract,
                        course: $scope.form_filters.course,
                        generate: true
                    });
                    c_data.$save((data) => {
                        $uibModalInstance.close(data);
                    }, (error) => {
                        $uibModalInstance.close(error);
                    });
                };
            };

            var loadData = () => {
                CertificateData.query({}, function(list){
                    $scope.certificateList = list;
                    $scope.certificateFormList = list;
                    var contracts = list.map(function(item){
                        return item.contract;
                    }).reduce(function(prev, curr, i, arr){
                        var index = prev.findIndex(function(item){
                            return item.id == curr.id
                        });
                        index < 0 ? prev.push(curr) : prev;
                        return prev;
                    }, []);

                    $scope.contracts = contracts;
                });
            }
            loadData();

            Course.query({}, function(courses) {
                $scope.courses = courses;
            })

        }
    ]);

    module.controller('ClassEvaluationsController',
    ['$scope', '$uibModal', '$window', '$routeParams', 'CertificationProcess', 'Evaluation', 'Class', 'ClassIdGetter',
    function($scope, $uibModal, $window, $routeParams, CertificationProcess, Evaluation, Class, ClassIdGetter) {
            $scope.errors = {};
            $scope.evaluations = [];

            $scope.stats = {
                has_certificate : 0,
                user_can_certificate : 0,
                user_can_attend : 0,
                upcoming : 0
            };

            $scope.switches = {
                can_certificate : false,
            }

            // FIXME this controller is being used in more than one view with different parameters
            if($routeParams['klassId']) {
                $scope.klass_id = $routeParams['klassId'];
            } else {
                $scope.klass_id = ClassIdGetter.classEditView();
            }

            Class.get({'id' : $scope.klass_id}, function(klass){
                $scope.klass = klass;
                $scope.class_students = klass.students;
                $scope.switches.can_certificate = klass.user_can_certificate;
                $scope.class_evaluations = klass.evaluations;

                if($scope.class_evaluations.length > 0) {
                    var now = new Date().getTime();
                    var next_week = now + 7*24*60*60*1000;

                    for(var i = 0; i < $scope.class_evaluations.length; i++) {
                        evaluation = $scope.class_evaluations[i];
                        var e_date = new Date(evaluation.date).getTime();
                        if ((e_date > now) && (e_date <= next_week)) {
                            $scope.stats.upcoming++;
                        }
                    }
                    $scope.evaluation = $scope.class_evaluations[0];
                }

                $scope.certification_processes = klass.processes;
                for(var i = 0; i < $scope.certification_processes.length; i++){
                    var proc = $scope.certification_processes[i];
                    if(proc.course_certification){
                        $scope.stats.user_can_certificate++;
                        if(!proc.evaluation){
                            $scope.stats.user_can_attend++;
                        }
                    }
                    if(proc.approved){
                        $scope.stats.has_certificate++;
                    }
                }
            });

            $scope.toggleClassCertifiable = function (){
                $scope.switches.can_certificate = false;
                $scope.klass.$update(function(klass){
                    $scope.switches.can_certificate = klass.user_can_certificate;
                })
            }

            $scope.addStudentEvaluation = function () {
                var modalInstance = $uibModal.open(
                    {
                        animation: true,
                        templateUrl: 'addStudentModal.html',
                        controller: ['$scope', '$uibModalInstance', 'processes', 'evaluation', 'students', AddStudentModalCtrl],
                        resolve: {
                            processes: function () {
                                return $scope.certification_processes;
                            },
                            evaluation: function() {
                                return $scope.evaluation;
                            },
                            students: function() {
                                return $scope.class_students;
                            }
                        }
                    }
                );

                modalInstance.result.then(function (class_students) {
                    $scope.user_can_attend = class_students;

                    for(var i = 0; i < $scope.user_can_attend.length; i++){
                        var proc = $scope.user_can_attend[i];
                        if(proc.selected){
                            proc.selected = false;
                            proc.evaluation = $scope.evaluation.id;
                            if(proc.student.id){
                                proc.student = proc.student.id;
                            }
                            proc = new CertificationProcess(proc);

                            proc.$update({}, function(process, data){
                                $scope.evaluation.processes.push(process.id);
                                $scope.certification_processes.filter(function(s){return s.id == process.id;})[0] = process;
                                $scope.stats.user_can_attend--;
                            });
                        }
                    }
                });

            };

            var AddStudentModalCtrl = function ($scope, $uibModalInstance, processes, evaluation, students) {
                $scope.certification_processes = processes;
                $scope.class_students = students;
                $scope.evaluation = evaluation;

                $scope.selectAll = function (select){
                    for(var i = 0; i < $scope.certification_processes.length; i++){
                        if(!$scope.certification_processes[i].evaluation
                                && $scope.certification_processes[i].course_certification)
                            $scope.certification_processes[i].selected = select;
                    }
                }

                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.save = function(){
                    $uibModalInstance.close($scope.certification_processes);
                }
            }

            $scope.createEvaluation = function (isEdit) {
                var modalInstance = $uibModal.open(
                    {
                        animation: true,
                        templateUrl: 'createEvaluationModal.html',
                        controller: ['$scope', '$uibModalInstance', 'klass_id', 'evaluation', CreateUpdateEvaluationModalCtrl],
                        resolve: {
                            klass_id: function () {
                                return $scope.klass_id;
                            },
                            evaluation: function() {
                                if(isEdit){
                                    return $scope.evaluation;
                                } else {
                                    return undefined;
                                }
                            }
                        }
                    }
                );

                modalInstance.result.then(function (evaluation) {
                    if(evaluation.id){
                        evaluation.$update({}, function(updated_eval){
                            // console.log(updated_eval);
                        });
                    } else {
                        evaluation.$save({}, function (new_eval) {
                            $scope.class_evaluations.push(new_eval);
                        });
                    }
                });
            };

            $scope.changeEvaluation = function ($event, $index) {
                $event.preventDefault();
                $scope.evaluation = $scope.class_evaluations[$index];
            };

            var CreateUpdateEvaluationModalCtrl = function ($scope, $uibModalInstance, klass_id, evaluation) {
                if(!evaluation){
                    $scope.evaluation = new Evaluation();
                } else {
                    $scope.evaluation = evaluation;
                }

                $scope.cancel = function () {
                    $uibModalInstance.dismiss();
                };

                $scope.openCalendar = function(e, b){
                    e.preventDefault();
                    e.stopPropagation();
                    $scope.calendar[b] = true;
                }

                $scope.calendar = {
                    'eval_date' : false,
                    'eval_results_date' : false
                }

                $scope.save = function(){
                    // Write validation
                    $scope.evaluation.klass = klass_id;
                    $uibModalInstance.close($scope.evaluation);
                }
            }

            $scope.isCurrent = function(evaluation_id){
                return evaluation_id == $scope.evaluation.id;
            }

            var evaluation = function($index){
                return $index >= 0 ? $scope.class_evaluations[$index] : false;
            }

            var class_students = function(){
                return $scope.class_students;
            }

        }
    ]);

})(angular);
<|endoftext|>


<commit_before>var auth = require('../auth');
var consts = require('../../../shared/constants');
var service = require('./service');

var players = {};

var init = function(io) {
    io.of(consts.socket.playerSync.NAMESPACE).use(auth);

    io.of(consts.socket.playerSync.NAMESPACE).on('connection', function(socket) {
        // jscs:disable requireCamelCaseOrUpperCaseIdentifiers

        var identity = socket.decoded_token;

        // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
        socket.on(consts.socket.playerSync.REGISTER, function(data) {
            var broadcastConnect = function(player) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_CONNECT, player);
            };

            var emitConnect = function(player) {
                socket.emit(consts.socket.playerSync.OTHER_CONNECT, player);
            };

            var controllerInterface = {
                broadcastConnect: broadcastConnect,
                emitConnect: emitConnect,
                identity: identity,
                playerId: socket.id
            };

            service.register(controllerInterface, data);
        });

        socket.on(consts.socket.playerSync.CHANGE, function(data) {
            var broadcastChange = function(player) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_CHANGE, player);
            };

            var controllerInterface = {
                broadcastChange: broadcastChange,
                playerId: socket.id
            };

            service.update(controllerInterface, data);
        });

        socket.on('disconnect', function() {
            var broadcastDisconnect = function(playerId) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_DISCONNECT, playerId);
            };

            var controllerInterface = {
                broadcastDisconnect: broadcastDisconnect,
                playerId: socket.id
            };

            service.disconnect(controllerInterface);
        });
    });
};

module.exports = {
    init: init,
    players: players
};
<commit_msg>removing players dict from player-sync controller<commit_after>var auth = require('../auth');
var consts = require('../../../shared/constants');
var service = require('./service');

var init = function(io) {
    io.of(consts.socket.playerSync.NAMESPACE).use(auth);

    io.of(consts.socket.playerSync.NAMESPACE).on('connection', function(socket) {
        // jscs:disable requireCamelCaseOrUpperCaseIdentifiers

        var identity = socket.decoded_token;

        // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
        socket.on(consts.socket.playerSync.REGISTER, function(data) {
            var broadcastConnect = function(player) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_CONNECT, player);
            };

            var emitConnect = function(player) {
                socket.emit(consts.socket.playerSync.OTHER_CONNECT, player);
            };

            var controllerInterface = {
                broadcastConnect: broadcastConnect,
                emitConnect: emitConnect,
                identity: identity,
                playerId: socket.id
            };

            service.register(controllerInterface, data);
        });

        socket.on(consts.socket.playerSync.CHANGE, function(data) {
            var broadcastChange = function(player) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_CHANGE, player);
            };

            var controllerInterface = {
                broadcastChange: broadcastChange,
                playerId: socket.id
            };

            service.update(controllerInterface, data);
        });

        socket.on('disconnect', function() {
            var broadcastDisconnect = function(playerId) {
                socket.broadcast.emit(consts.socket.playerSync.OTHER_DISCONNECT, playerId);
            };

            var controllerInterface = {
                broadcastDisconnect: broadcastDisconnect,
                playerId: socket.id
            };

            service.disconnect(controllerInterface);
        });
    });
};

module.exports = {
    init: init,
    players: players
};
<|endoftext|>


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

import * as echarts from '../../../echarts';
import * as zrUtil from 'zrender/src/core/util';
import lang from '../../../lang';
import * as featureManager from '../featureManager';

var magicTypeLang = lang.toolbox.magicType;

function MagicType(model) {
    this.model = model;
}

MagicType.defaultOption = {
    show: true,
    type: [],
    // Icon group
    icon: {
        /* eslint-disable */
        line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
        bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
        stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
        tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
        /* eslint-enable */
    },
    // `line`, `bar`, `stack`, `tiled`
    title: zrUtil.clone(magicTypeLang.title),
    option: {},
    seriesIndex: {}
};

var proto = MagicType.prototype;

proto.getIcons = function () {
    var model = this.model;
    var availableIcons = model.get('icon');
    var icons = {};
    zrUtil.each(model.get('type'), function (type) {
        if (availableIcons[type]) {
            icons[type] = availableIcons[type];
        }
    });
    return icons;
};

var seriesOptGenreator = {
    'line': function (seriesType, seriesId, seriesModel, model) {
        if (seriesType === 'bar') {
            return zrUtil.merge({
                id: seriesId,
                type: 'line',
                // Preserve data related option
                data: seriesModel.get('data'),
                stack: seriesModel.get('stack'),
                markPoint: seriesModel.get('markPoint'),
                markLine: seriesModel.get('markLine')
            }, model.get('option.line') || {}, true);
        }
    },
    'bar': function (seriesType, seriesId, seriesModel, model) {
        if (seriesType === 'line') {
            return zrUtil.merge({
                id: seriesId,
                type: 'bar',
                // Preserve data related option
                data: seriesModel.get('data'),
                stack: seriesModel.get('stack'),
                markPoint: seriesModel.get('markPoint'),
                markLine: seriesModel.get('markLine')
            }, model.get('option.bar') || {}, true);
        }
    },
    'stack': function (seriesType, seriesId, seriesModel, model) {
        var isStack = seriesModel.get('stack') === '__ec_magicType_stack__';
        if (seriesType === 'line' || seriesType === 'bar') {
            model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
            return zrUtil.merge({
                id: seriesId,
                stack: isStack ? '' : '__ec_magicType_stack__',
                // FIXME: also need to change tooltip for stack/unstack state.
                title: isStack ? zrUtil.clone(magicTypeLang.title) : zrUtil.merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
            }, model.get('option.stack') || {}, true);
        }
    },
    'tiled': function (seriesType, seriesId, seriesModel, model) {
        if (seriesType === 'line' || seriesType === 'bar') {
            return zrUtil.merge({
                id: seriesId,
                stack: ''
            }, model.get('option.tiled') || {}, true);
        }
    }
};

var radioTypes = [
    ['line', 'bar'],
    ['stack', 'tiled']
];

proto.onclick = function (ecModel, api, type) {
    var model = this.model;
    var seriesIndex = model.get('seriesIndex.' + type);
    // Not supported magicType
    if (!seriesOptGenreator[type]) {
        return;
    }
    var newOption = {
        series: []
    };
    var generateNewSeriesTypes = function (seriesModel) {
        var seriesType = seriesModel.subType;
        var seriesId = seriesModel.id;
        var newSeriesOpt = seriesOptGenreator[type](
            seriesType, seriesId, seriesModel, model
        );
        if (newSeriesOpt) {
            // PENDING If merge original option?
            zrUtil.defaults(newSeriesOpt, seriesModel.option);
            newOption.series.push(newSeriesOpt);
        }
        // Modify boundaryGap
        var coordSys = seriesModel.coordinateSystem;
        if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
            var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
            if (categoryAxis) {
                var axisDim = categoryAxis.dim;
                var axisType = axisDim + 'Axis';
                var axisModel = ecModel.queryComponents({
                    mainType: axisType,
                    index: seriesModel.get(name + 'Index'),
                    id: seriesModel.get(name + 'Id')
                })[0];
                var axisIndex = axisModel.componentIndex;

                newOption[axisType] = newOption[axisType] || [];
                for (var i = 0; i <= axisIndex; i++) {
                    newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
                }
                newOption[axisType][axisIndex].boundaryGap = type === 'bar';
            }
        }
    };

    zrUtil.each(radioTypes, function (radio) {
        if (zrUtil.indexOf(radio, type) >= 0) {
            zrUtil.each(radio, function (item) {
                model.setIconStatus(item, 'normal');
            });
        }
    });

    model.setIconStatus(type, 'emphasis');

    ecModel.eachComponent(
        {
            mainType: 'series',
            query: seriesIndex == null ? null : {
                seriesIndex: seriesIndex
            }
        }, generateNewSeriesTypes
    );
    api.dispatchAction({
        type: 'changeMagicType',
        currentType: type,
        newOption: newOption
    });
};

echarts.registerAction({
    type: 'changeMagicType',
    event: 'magicTypeChanged',
    update: 'prepareAndUpdate'
}, function (payload, ecModel) {
    ecModel.mergeOption(payload.newOption);
});

featureManager.register('magicType', MagicType);

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

import * as echarts from '../../../echarts';
import * as zrUtil from 'zrender/src/core/util';
import lang from '../../../lang';
import * as featureManager from '../featureManager';

var magicTypeLang = lang.toolbox.magicType;

function MagicType(model) {
    this.model = model;
}

MagicType.defaultOption = {
    show: true,
    type: [],
    // Icon group
    icon: {
        /* eslint-disable */
        line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
        bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
        stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z', // jshint ignore:line
        /* eslint-enable */
    },
    // `line`, `bar`, `stack`, `tiled`
    title: zrUtil.clone(magicTypeLang.title),
    option: {},
    seriesIndex: {}
};

var proto = MagicType.prototype;

proto.getIcons = function () {
    var model = this.model;
    var availableIcons = model.get('icon');
    var icons = {};
    zrUtil.each(model.get('type'), function (type) {
        if (availableIcons[type]) {
            icons[type] = availableIcons[type];
        }
    });
    return icons;
};

var seriesOptGenreator = {
    'line': function (seriesType, seriesId, seriesModel, model) {
        if (seriesType === 'bar') {
            return zrUtil.merge({
                id: seriesId,
                type: 'line',
                // Preserve data related option
                data: seriesModel.get('data'),
                stack: seriesModel.get('stack'),
                markPoint: seriesModel.get('markPoint'),
                markLine: seriesModel.get('markLine')
            }, model.get('option.line') || {}, true);
        }
    },
    'bar': function (seriesType, seriesId, seriesModel, model) {
        if (seriesType === 'line') {
            return zrUtil.merge({
                id: seriesId,
                type: 'bar',
                // Preserve data related option
                data: seriesModel.get('data'),
                stack: seriesModel.get('stack'),
                markPoint: seriesModel.get('markPoint'),
                markLine: seriesModel.get('markLine')
            }, model.get('option.bar') || {}, true);
        }
    },
    'stack': function (seriesType, seriesId, seriesModel, model) {
        var isStack = seriesModel.get('stack') === '__ec_magicType_stack__';
        if (seriesType === 'line' || seriesType === 'bar') {
            model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
            return zrUtil.merge({
                id: seriesId,
                stack: isStack ? '' : '__ec_magicType_stack__',
                // FIXME: also need to change tooltip for stack/unstack state.
                title: isStack ? zrUtil.clone(magicTypeLang.title) : zrUtil.merge({ stack: magicTypeLang.title.tiled }, magicTypeLang.title)
            }, model.get('option.stack') || {}, true);
        }
    }
};

var radioTypes = [
    ['line', 'bar'],
    ['stack']
];

proto.onclick = function (ecModel, api, type) {
    var model = this.model;
    var seriesIndex = model.get('seriesIndex.' + type);
    // Not supported magicType
    if (!seriesOptGenreator[type]) {
        return;
    }
    var newOption = {
        series: []
    };
    var generateNewSeriesTypes = function (seriesModel) {
        var seriesType = seriesModel.subType;
        var seriesId = seriesModel.id;
        var newSeriesOpt = seriesOptGenreator[type](
            seriesType, seriesId, seriesModel, model
        );
        if (newSeriesOpt) {
            // PENDING If merge original option?
            zrUtil.defaults(newSeriesOpt, seriesModel.option);
            newOption.series.push(newSeriesOpt);
        }
        // Modify boundaryGap
        var coordSys = seriesModel.coordinateSystem;
        if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
            var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
            if (categoryAxis) {
                var axisDim = categoryAxis.dim;
                var axisType = axisDim + 'Axis';
                var axisModel = ecModel.queryComponents({
                    mainType: axisType,
                    index: seriesModel.get(name + 'Index'),
                    id: seriesModel.get(name + 'Id')
                })[0];
                var axisIndex = axisModel.componentIndex;

                newOption[axisType] = newOption[axisType] || [];
                for (var i = 0; i <= axisIndex; i++) {
                    newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
                }
                newOption[axisType][axisIndex].boundaryGap = type === 'bar';
            }
        }
    };

    zrUtil.each(radioTypes, function (radio) {
        if (zrUtil.indexOf(radio, type) >= 0) {
            zrUtil.each(radio, function (item) {
                model.setIconStatus(item, 'normal');
            });
        }
    });

    model.setIconStatus(type, 'emphasis');

    ecModel.eachComponent(
        {
            mainType: 'series',
            query: seriesIndex == null ? null : {
                seriesIndex: seriesIndex
            }
        }, generateNewSeriesTypes
    );
    api.dispatchAction({
        type: 'changeMagicType',
        currentType: type,
        newOption: newOption
    });
};

echarts.registerAction({
    type: 'changeMagicType',
    event: 'magicTypeChanged',
    update: 'prepareAndUpdate'
}, function (payload, ecModel) {
    ecModel.mergeOption(payload.newOption);
});

featureManager.register('magicType', MagicType);

export default MagicType;<|endoftext|>


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

describe('the environment', function(){

  it('Le logiciel eSpeak est installé', function(done){
    exec('espeak -h', function(error, stdout, stderr){
      expect(stdout).toMatch(/eSpeak/);
      done();
    });
  });

  it('Le logiciel Mbrola est installé', function(done){
    exec('mbrola -h', function(error, stdout, stderr){
      expect(stdout).toMatch(/mbrola/);
      done();
    });
  });

  it('Le logiciel Lame est installé', function(done){
    exec('lame -h', function(error, stdout, stderr){
      // programs that execute successfully return
      // 0 as their exit code, and any other number
      // to indicate some sort of failure.
      // lame -h returns an exit code of 1 for some
      // reason, so node puts the output in the error
      // variable. Grrr. So... what's the word? LAME.
      expect(error).toMatch(/lame/);
      done();
    });
  });

});
<commit_msg>Remove test for mbrola.<commit_after>var exec = require('child_process').exec;

describe('the environment', function(){

  it('Le logiciel eSpeak est installé', function(done){
    exec('espeak -h', function(error, stdout, stderr){
      expect(stdout).toMatch(/eSpeak/);
      done();
    });
  });

  it('Le logiciel Lame est installé', function(done){
    exec('lame -h', function(error, stdout, stderr){
      // programs that execute successfully return
      // 0 as their exit code, and any other number
      // to indicate some sort of failure.
      // lame -h returns an exit code of 1 for some
      // reason, so node puts the output in the error
      // variable. Grrr. So... what's the word? LAME.
      expect(error).toMatch(/lame/);
      done();
    });
  });

});
<|endoftext|>


<commit_before>import './util/ie8'
// import './modules/util.spec'
import './modules/h.spec'
import './modules/createElement.spec'
import './modules/diff.spec'
import './modules/vtypes.spec'
import './modules/render.spec'
import './modules/refs.spec'
import './modules/keys.spec'
import './modules/svg.spec'
import './modules/event.spec'
import './modules/component.spec'
import './modules/context.spec'
import './modules/lifecycle.spec'
import './modules/cloneElement.spec'
import './modules/patch.spec'
import './modules/hook.spec'
<commit_msg>chore: remove ie8 polyfill import from root spec<commit_after>// import './modules/util.spec'
import './modules/h.spec'
import './modules/createElement.spec'
import './modules/diff.spec'
import './modules/vtypes.spec'
import './modules/render.spec'
import './modules/refs.spec'
import './modules/keys.spec'
import './modules/svg.spec'
import './modules/event.spec'
import './modules/component.spec'
import './modules/context.spec'
import './modules/lifecycle.spec'
import './modules/cloneElement.spec'
import './modules/patch.spec'
import './modules/hook.spec'
<|endoftext|>