Example #1
0
Security.prototype.registerMiddlewares = function(objects) {

    var self = this;
    _.forIn(objects, function(object, key) {

        if (object.extends != undefined) {

            // try to search on default providers with name
            if (self.validationsForMethod[object.extends] != undefined) {

                object.validation = self.validationsForMethod[object.extends];

                var defaultConfig = _.cloneDeep(self.optionsForMethod[object.extends])
                object.config = _.merge(defaultConfig, object.config);

            } else {
                throw new Error("unknow validation method for key " + key)
            }
        }

        // object must have a validation function
        if (object.validation == undefined) {
            // try to search on default providers with name
            if (self.validationsForMethod[key] != undefined) {
                object.validation = self.validationsForMethod[key];
            } else {
                throw new Error("unknow validation method for key " + key)
            }
        }
 
        self.validationsForMethod[key] = object.validation;

        if(self.optionsForMethod[key] != undefined) {
            var defaultConfig = _.cloneDeep(self.optionsForMethod[key])
            object.config = _.merge(defaultConfig, object.config);
        }

        self.optionsForMethod[key] = object.config;
    })
}
Example #2
0
/**
 * @param {mapboxgl.Map.Batch} batch
 * @param {Object.<String, Point[]>} classes
 */
function addCircleClasses(batch, classes) {
    _.forIn(classes, function (points, classStr) {
        var classAr = classStr.split(CLASS_SEPARATOR);
        var venueIds = points.map(function (p) {
            return p.properties.venueId;
        });
        var radius = Number(classAr[1]);
        var id = ['venue-circle'].concat(classAr).join('-');
        var filter = ['in', 'venueId'].concat(venueIds);
        var layer = {
            source: 'venues',
            type: 'circle',
            minzoom: Number(classAr[2]),
            paint: {
                'circle-radius': {
                    stops: [[14, 3],  [16, radius], [20, radius]]
                }
            }
        };
        //visible layer
        batch.addLayer(_.defaultsDeep({}, layer, {
            id: id,
            filter: filter,
            interactive: true,
            paint: {
                'circle-color': {
                    stops: [[15.9, classAr[0]],  [16, classAr[3]]]
                }
            }
        }), 'rail-label');
        //selection layer
        batch.addLayer(_.defaultsDeep({}, layer, {
            id: 'select-' + id,
            filter: ['in', 'venueId', 'none'],
            paint: {
                'circle-color': chroma(classAr[0]).darken(1).css()
            }
        }), 'rail-label');
    });
}
Example #3
0
  async.parallel(validators, function (err, results) {
    var failed = false;
    var values = {};
    var failures = {};
    var failReason = {};
    // values should be cached to reuse
    var cacheList = ['username', 'firstName', 'lastName', 'primaryEmail'];

    if (err) {
      return next(err);
    }

    // store the values
    _.forIn(results, function (value, key) {
      if (!value) {// valid
        if (-1 !== _.indexOf(cacheList, key)) {
          values[key] = req.body[key];
        }
        return;
      }
      failed = true;
      failures[key] = value;
      if (_.isString(value)) {
        failReason[key] = value;
      }
    });

    if (!failed) { // if all valid, pass the requests to next handler
      log.debug('successed for validation');
      return next();
    }

    req.session.validation = {
      values: values,
      fail: failures,
      failReason: failReason,
    };
    req.flash('error','Please review all the items and try again');
    return res.redirect(req.url);
  });
  describe('with a string', function() {
    function buildTest(state, identifier) {
      it('should support the ' + identifier + ' state', function() {
        var mac1      = defineMachine(dockDef);
        var expected  = {
          topology: {
            containers: {
            }
          }
        };
        var result    = containerStatus(mac1, identifier);

        expected.topology.containers[mac1.id] = state;
        expected.topology.containers[mac1.id].id = mac1.id;

        if (state.added !== false) {
          state.containedBy = mac1.containedBy;
        }

        expect(result).to.eql(expected);
      });
    }

    _.forIn({
      detached: {
        added: false,
        started: false,
        running: false
      },
      added: {
        added: true
      },
      started: {
        started: true
      },
      running: {
        running: true
      }
    }, buildTest);
  });
Example #5
0
  _.each( data.tools, function( tool ) {
    _.forIn( tool, function( value, key ) {
      tool.stars = data.tools.stars || {};

      if (
        key !== 'description' &&
        key !== 'name' &&
        key !== 'type' &&
        key !== 'tags' &&
        key !== 'fuzzy' &&
        /github/.test( value )
      ) {
        queue.push( function( done ) {
          var project = value.replace( 'https://github.com/', '' ).split( '#' )[ 0 ];

          helpers.github.getStars(
            project,
            function( error, stars ) {
              if ( error ) {
                console.warn( 'ERROR -> fetchGithubStars' );
                console.warn( 'ERROR -> ' + project );
                console.warn( error );
                return done( null );
              }

              tool.stars[ key ] = stars;

              pages.tools = renderPage( 'tools' );

              // give it a bit of time
              // to rest and not reach the API limits
              setTimeout( function() {
                done( null );
              }, config.timings.requestDelay );
            }
          );
        } );
      }
    } );
  } );
Example #6
0
module.exports = function(formlyConfig, formlyValidationMessages) {

    //////////////////////////////////////////////////////////////////
    // INPUT TEXT    
    // http://docs.angular-formly.com/docs/formlyconfig#settype
    //////////////////////////////////////////////////////////////////

    var modules = requireAll(require.context("../fields", false, /^\.\/.*\.js$/));

    _.forIn(modules, function (module) {
        formlyConfig.setType(module.getFormlyField());
    });


    //////////////////////////////////////////////////////////////////////////
    // WRAPPER
    // http://docs.angular-formly.com/docs/formlyconfig#setwrapper
    //////////////////////////////////////////////////////////////////////////
    formlyConfig.setWrapper({
        // name: 'inputWrapper', // optional. Defaults to name || types.join(' ') || 'default'
        template: require('../templates/defaultWrapper.html') // must have this OR templateUrl
        //templateUrl: 'path/to/template.html', // the resulting template MUST have <formly-transclude></formly-transclude> in it and must have templateUrl OR template (not both)
        // types: 'input' // this can be a string or an array of strings that map to types specified by setTe


    });

    //////////////////////////////////////////////////////////////////////////
    // Carrega Mensagens Padrão de erro
    //////////////////////////////////////////////////////////////////////////
    // formlyValidationMessages.addStringMessage('required', 'This field is required');

    // TODO: Colocar nos fields, não deve ficar aqui
    formlyConfig.extras.ngModelAttrsManipulatorPreferBound = true;
    formlyValidationMessages.addStringMessage('required', 'Campo Obrigatório');
    formlyValidationMessages.addStringMessage('maxlength', 'Tamanho máximo excedido');
    formlyValidationMessages.addStringMessage('email', 'E-mail Inválido');


};
  function getIndexesFromModels() {
    var indexes = [];

    _.forIn(sails.models, function (model,modelKey) {
      if(sails.config.connections[model.connection].adapter !== 'sails-mongo'){
        sails.log.verbose('sails-hook-mongo-auto-index: ' + 'skipping model ' + modelKey + ', not a sails-mongo model');
        return;
      }

      _.forIn(model.attributes, function (attribute, attributeKey) {
        if (attribute.primaryKey) {
          return; // Sails autocreates primary key indexes
        }

        if (attribute.unique) {
          indexes.push(
            {
              model: model,
              attributeKey: attributeKey,
              unique: true
            }
          );
        }

        if (attribute.index === true) {
          indexes.push(
            {
              model: model,
              attributeKey: attributeKey,
              unique: false
            }
          );
        }

      });
    });

    return indexes;
  }
      var buildPages = function() {
        scope.paginationKeys = [];
        var ellipsis;
        var urlPrefix;
        var queryParams = angular.copy($location.search());
        delete queryParams.page; // Page is handled separately

        // Build url prefix, include existing query params
        urlPrefix = $location.path() + '?';
        _.forIn(queryParams, function(value, key) { urlPrefix += key + '=' + value + '&'; });
        urlPrefix += 'page=';

        var truncate = scope.pageCount > 15;

        // Case 1: No Truncation up to 15 pages
        // [1] 2 3 4 5 6 7 8 9 10 11 13 14 15
        if (!truncate) { generatePageKeys(undefined, urlPrefix); }
        // Case 2: Truncate Tail
        // 1 2 3 4 5 [6] 7 8 ... 14 15 16
        else if (truncate && scope.page <= 6) {
          ellipsis = [{ index: 9, nextIndex: scope.pageCount - 2 }];
          generatePageKeys(ellipsis, urlPrefix);
        }
        // Case 3: Truncate Head
        // 1 2 3 ... 9 10 [11] 12 13 14 15 16
        else if (truncate && scope.page >= scope.pageCount - 5) {
          ellipsis = [{ index: 4, nextIndex: scope.pageCount - 8 }];
          generatePageKeys(ellipsis, urlPrefix);
        }
        // Case 4: Truncate Head and Tail
        // 1 2 3 ... 7 8 [9] 10 11 ... 14 15 16
        else if (truncate && scope.page > 6 && scope.page < scope.pageCount - 5) {
          ellipsis = [
            { index: 4, nextIndex: scope.page - 2 },
            { index: scope.page + 3, nextIndex: scope.pageCount - 2 }
          ];
          generatePageKeys(ellipsis, urlPrefix);
        }
      };
/**
 * Determines which related objects are new (need to be inserted) and which
 * are existing ones (need to be updated)
 * @param  {Model} model	the model with which the related objects are associated
 * @param  {String} fkName	the name of the column on which all related models
 *                         	have their foreign key
 * @param  {Object} related	an object mapping related models to array of related
 *                          model attribute objects
 * @return {Object}			mapping of new objects, updated objects, and ids of
 *                          updated objects
 */
function _extractRelatedObjects(model, fkName, related) {
  const result = {};

  _.forIn(related, (instances, relatedName) => {
    result[relatedName] = {
      new: [],
      updated: [],
      updatedIds: []
    };

    _.forEach(instances, (attributes) => {
      let MESSAGE, SOURCE;
      if (!_.has(attributes, 'id')) {
        result[relatedName].new.push(attributes);
      } else if (_.isUndefined(model.related(relatedName)
          .get(attributes.id))) {
        MESSAGE = 'A related ' + relatedName + ' object with the given ID does not exist';
        SOURCE = relatedName + '.id';
        throw new errors.NotFoundError(MESSAGE, SOURCE);
      } else if (model.related(relatedName)
        .get(attributes.id)
        .get(fkName) !== model.get('id')) {
        MESSAGE = 'A ' + relatedName + ' object that does not belong to this resource cannot be updated here';
        throw new errors.UnauthorizedError(MESSAGE);
      } else {
        // TODO remove this once Request validator can marshal recursively
        // (prevents unauthorized reassignment of related object to another model)
        attributes[fkName] = model.get('id');

        result[relatedName].updated.push(model.related(relatedName)
          .get(attributes.id)
          .set(attributes));
        result[relatedName].updatedIds.push(attributes.id);
      }
    });
  });

  return _Promise.resolve(result);
}
Example #10
0
function _resolveAttributesToparams1($scope, attribs, craft) {
  let params = {}
  _.forIn(attribs, (value, key) => {

      let parameterElement = craft.params[key]

      if (parameterElement) {

        let {type, name} = parameterElement.attribs

        let resolved =  $scope.resolve(value, type)
        params[name] = resolved

        // set alias, if specified
        let alias = parameterElement.attribs['alias']
        if (alias){
            params[alias] = resolved
        }
      }
  })
  return params
}
Example #11
0
    render(page, options)
    {
        // We _must_ set autoescape to false, otherwise markdown breaks
        const config = _.merge({}, configMan.config.nunjucks, { autoescape: false });

        // Tell nunjucks about whatever templates directory the user setup, and our internal template directory
        const templates = [].concat(path.join(paths.sourceDir, configMan.config.directories.templates), path.join(paths.rootPath, 'templates'));

        // Store the configured nunjucks object
        this.nunjucks = nunjucks.configure(templates, config);

        // Install our custom filters
        _.forIn(momentFilters, (filter, name) =>
        {
            this.nunjucks.addFilter(name, filter);
        });

        // Allow user customization through `site.js`
        if(fs.existsSync(path.join(paths.sourceDir, 'site.js')))
        {
            const site = require(path.join(paths.sourceDir, 'site.js'));
            if(site && site.nunjucks)
            {
                site.nunjucks(nunjucks, this.nunjucks, require('marked'));
            } // end if
        } // end if

        // Render the markdown
        return marked(page.body)
            .then((rendered) =>
            {
                // Allow Nunjucks templating in the content
                rendered = this.nunjucks.renderString(rendered, page.attributes);

                // Now Render the markdown into the page
                const context = _.assign({}, page.attributes, { content: rendered });
                return this.nunjucks.render(page.attributes.template || 'default.html', context);
            });
    } // end render
Example #12
0
Query.prototype.match = function (field, op, value) {
  var self = this;
  this.data.join.matches = this.data.join.matches || []; 
  if ('string' === typeof(field)) {
    this.data.join.matches.push({
      field: field,
      op: op || '=',
      value: value
    });
  } else if ('object' === typeof(field)) {
    _.forIn(field, function (value, key) {
      var match = { field: key, value: value, };
      if (_.isArray(value)) {
        match.op = 'IN';
      } else {
        match.op = '=';
      }
      self.data.join.matches.push(match);
    });
  }
  return this;
};
Example #13
0
FrontEnd.prototype.init$ = function() {
  var self = this;
  _.forIn(this, function(v, k) {
    // skip private functions
    if (!_.startsWith(k, "api_")) {
      return;
    }
    var f = self[k];
    if (!_.isFunction(f)) {
      return;
    }
    f = f.bind(self);
    if (k[k.length - 1] === "$") {    // remove ending $
      k = k.slice(0, -1);
    }
    k = k.slice(4);   // remove app_
    k = k.replace("__", ".");   // __ to .
    self.api_handler.define_api(k, f);
  });

  return Promise.resolve();
};
Example #14
0
  this.options.filterBy.forEach(function(item) {
    var filter;

    if (item.indexOf('.') !== -1) {
      debugJoin('building (', item, ')');
      joinCandidates = item.split('.');

      if (joinCandidates.length > 2) {
        throw new Error('Paginator does not support nested relations like ' + item);
      }

      relation = joinCandidates.shift();

      if (typeof this.modelInstance[relation] !== 'function') {
        throw new Error('Does not exists the relation "' + relation + '" in ' + this.model);
      }

      join = this.buildJoin(this.modelInstance[relation]());
      this.realTableNames[item] = [join.tableName, joinCandidates.shift()].join('.');
      this.joins[join.tableName] = join.joinData;
    } else {
      this.realTableNames[item] = [this.modelInstance.tableName, item].join('.')
    }

    filter = _this.isRawFilter(item) ? item : _this.realTableNames[item];

    if (_.isObject(this.options.comp)) {
      _.forIn(this.options.comp, function(value, key) {
        if (_.include(value, item)) {
          _this.comps[filter] = key;
        }
      });
    }

    if (!this.comps[filter]) {
      this.comps[filter] = _.isObject(this.options.comp) ? '=' : this.options.comp;
    }

  }.bind(this));
Example #15
0
/**
 * @private
 * @returns {(tinto.Assertion | function(Array.<tinto.Assertion>))}
 */
function createAccessor() {
  var self = this;
  var assertion = new chai.Assertion(self);
  var accessor = function(assertions) {
    assertions = Array.prototype.slice.call(arguments);
    assertions.forEach(function(assert) {
      assert.call(assertion, self);
    });
  };

  mixin(accessor, chai.Assertion.prototype);

  Object.keys(assertion).forEach(function(prop) {
    accessor[prop] = assertion[prop];
  });

  _.forIn(descriptors(self), function(descriptor, prop) {
    descriptor.get && CountAssertion.register(prop);
  });

  return accessor;
}
Example #16
0
Deployer.prototype.updateEnv = function(callback) {
  var nodeApp = this.app.replace('hylo', 'hylo-node'),
    version = this.version;

  this.log.subhead(util.format('updating ENV on %s and %s', this.app, nodeApp));

  newVars = {
    JS_BUNDLE_URL: this.awsContentUrlPrefix + this.bundlePaths.js,
    CSS_BUNDLE_URL: this.awsContentUrlPrefix + this.bundlePaths.css,
    BUNDLE_VERSION: this.version
  };

  _.forIn(newVars, function(val, key) {
    this.log.writeln(key + ': ' + val);
  }.bind(this));

  heroku.config(this.app).update(newVars, function(err) {
    if (err) throw err;
    var nodeConfig = heroku.config(nodeApp);
    nodeConfig.update({BUNDLE_VERSION: version}, callback);
  });
};
  MoussakaClient.prototype.applyUpdates = function (updates) {
    if (!updates) {
      logger.warn('Updates is null.');
      return;
    }

    _.forIn(updates, function (update, key) {
      var values = update.values;
      var variable = this.registeredVars[key];
      var type = variable.schema.type;
      var ref = variable.ref;

      switch (variable.schema.type) {
        // Primitives
      case 'float':
      case 'double':
      case 'decimal':
        ref.value = values.n;
        break;
      case 'string':
        ref.value = values.s;
        break;
      case 'boolean':
        ref.value = values.b;
        break;
      default:
        // Complex Type
        if (ref.value.setValues) {
          ref.value.setValues(values);
        } else {
          logger.warn('Unsupported variable type: ' + type);
        }
        break;
      }

    }, this);

  };
Example #18
0
Document.prototype.set = function (path, value, type, options) {
  var self = this;
  var schema = this.constructor.schema;
  var schemaType = this.constructor.getType(path);

  if (type && type.constructor.name == 'Object') {
    options = type;
    type = undefined;
  }

  if ('string' !== typeof(path)) {
    _.forIn(path, function (value, key) {
      self.set(key, value);
    });
    return;
  }

  if (schema.options.primaryKey && path === schema.options.primaryKey) {
    return;
  }

  if (!this.constructor.validatePath(path)) {
    throw new Error('Field '+path+' is not in the schema');
  }


  // Not sure if we need to support models or not.
  if (type === String || type === Number || type === Boolean) {
    value = type(value);
  } else if (schemaType && schemaType.type !== 'join') {
    value = typeCasting(value, schemaType, this.db);
  } else if (schemaType && schemaType === 'join') {
    return;
  }
  mpath.set(path, value, this); 

  return value;
};
Example #19
0
        filesParsed.promise.then(function () {
            _.forIn(browserResults, function (browserResult) {
                var browser = karma.results().add(new Test.Browser(browserResult.browser.name));

                browserResult.results.forEach(function (result) {
                    var suite = browser.startSuite(result.suite);
                    var testResult = suite.add(new Test.TestResult(result.description));
                    testResult.id = result.id;
                    testResult.time = result.time;
                    testResult.outcome = getOutcome(result);

                    result.log.forEach(function (logItem) {
                        testResult.log.push(formatError(logItem).replace(/\s+$/, ''));
                    });
                });
            });

            try  {
                Util.writeFile(outputFile, karma.toXml());
            } catch (e) {
                log.error(e);
            }
        });
Example #20
0
module.exports = function (grunt) {

    grunt.initConfig(gruntConfig);

    grunt.loadNpmTasks('grunt-env');
    grunt.loadNpmTasks('grunt-concurrent');

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-mocha-istanbul');

    grunt.registerTask('cover', ['mocha_istanbul']);
    grunt.registerTask('lint', ['jshint']);
    grunt.registerTask('test', ['mochaTest:test']);
    grunt.registerTask('test:browser', ['concurrent:test-browser']);

    grunt.registerTask('default', ['jshint', 'cover']);

    _.forIn(desireds, function (desired, key) {
        grunt.registerTask('test:browser:' + key, ['env:' + key, 'mochaTest:browser']);
    });
};
Example #21
0
Integrant.generate = function (schema) {
    if (!schema || typeof schema !== "object" || schema instanceof Array) throw new Error("Schema must be an object");

    var output = '';

    _.forIn(schema, function (value, key) {
        // if the value uses the shorthand notation, convert it to a full object
        if (typeof value !== 'object') {
            value = {label: key, type: value};
        }

        // if an unknown type is requested, complain about it
        if (!types[value.type]) throw new Error('Cannot generate HTML for unknown type ' + value.type);

        // add an ID parameter to each object
        value = _.assign({id: 'field-' + Math.random().toString(36).substr(2, 5)}, value);

        // otherwise, compile the appropriate template
        output += '<div class="intgrnt-field">' + types[value.type].template(value) + '</div>';
    });

    return output;
};
Example #22
0
var oneToMany = function (doc, def, options, callback) {
  var model = this.db.model(def.schema.type);
  var query = model.find().where(def.schema.foreign_key).equals(doc.id);
  var match = options.match || def.schema.match;
  if (options.select) {
    query.select(options.select);
  }
  if (match) {
    _.forIn(match, function (value, key) {
      query.where(key);
      if(_.isArray(value)) {
        query.in(value);
      } else {
        query.equals(value);
      }
    });
  }
  query.exec(function (err, docs) {
    if (err) return callback(err);
    doc.set(options.path, docs);
    callback(null, doc);
  });
};
Example #23
0
 _.forIn(options.schedule, (jobOpts, when) => {
     if (typeof jobOpts === 'string') {
         agenda.schedule(when, jobOpts);
     } else {
         _.forIn(jobOpts, (value, key) => {
             if (typeof value === 'string') {
                 agenda.schedule(when, value);
             } else {
                 if (value.data != undefined) {
                     agenda.schedule(when, key, value.data);
                 } else {
                     _.forIn(value, (v, k) => {
                         if (v.data == undefined) {
                             agenda.schedule(when, k);
                         } else {
                             agenda.schedule(when, k, v.data);
                         }
                     });
                 }
             }
         });
     }
 });
Example #24
0
        return utils.executeWhen(newSitemapLinks.length !== 0, function() {

            var xml = builder.create('urlset', { version: '1.0', encoding: 'UTF-8' })
                .commentAfter('XML Sitemap generated by devopsgroup.io/Siteshooter')
                .att('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
                .att('xmlns:image', 'http://www.google.com/schemas/sitemap-image/1.1')
                .att('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd')
                .att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');


            sitemapData = sitemapData.concat(newSitemapLinks);

            ___.forIn(sitemapData, function(url) {
                xml.ele('url')
                    .ele({
                        loc: url,
                        changefreq: 'weekly'
                    });
            });

            return utils.writeFile(path.join(config.process.get('working_directory'), 'sitemap.xml'), xml.end({ pretty: true, indent: '  ', newline: '\n' }));

        }).then(function(){
 processFiles: function(req, fields, cb) {
     var fileFieldKeys = [];
     _.forIn(fields, function(field, key) {
         if (field.config && field.config.file) {
             fileFieldKeys.push(key);
         }
     });
     if (fileFieldKeys.length == 0) {
         return cb();
     }
     var files = {};
     async.eachLimit(fileFieldKeys, 10, function(key, done) {
         req.file(key).upload(function(err, file) {
             if (err) {
                 return done(err);
             }
             files[key] = file;
             done();
         });
     }, function(err, result) {
         cb(err, files);
     });
 },
Example #26
0
Classifier.prototype.train = function (script, genre) {
  var wordOccurences = countWordOccurrences(this.ignore, script);

  // Count scripts trained for genre
  if (!this.training.genres[genre]) this.training.genres[genre] = 0;
  this.training.genres[genre] += 1;

  // Maintain reference to this
  var self = this;

  _.forIn(wordOccurences, function (value, word) {
    // Count occurences in each genre for individual words
    if (!self.training.words[word]) self.training.words[word] = {};
    if (!self.training.words[word][genre]) self.training.words[word][genre] = 0;;
    self.training.words[word][genre] += value;

    // Count totals
    if (!self.training.totals[genre]) self.training.totals[genre] = 0;
    self.training.totals[genre] += 1;
  });

  console.log('Trained (1) script.')
};
 addImport: function(options) {
   if (!opts.hasInit) initOpts(options);
   if (opts.bundleMode === opts.oneBundle) return;
   if (!opts.useImport) return;
   if (!Util.checkSource(opts.source)) { return; }
   if (!opts.info) { opts.info = updateLayer(opts); }
   var content = getStyles();
   var spriteIndex = path.join(opts.cssPath, opts.spriteName + opts.connector + opts.indexName + '.' + opts.processor);
   try {
     stats = fs.lstatSync(spriteIndex);
   }
   catch (e) {
     fs.writeFileSync(spriteIndex);
   }
   fs.truncateSync(spriteIndex);
   _.forIn(content, function(v, i) {
     var importPath = path.relative(opts.cssPath, v.cssPath);
     fs.appendFileSync(
       spriteIndex,
       '@import "./' + path.join(importPath, v.name) + '";\n'
     );
   });
 }
          describe( "case ".concat( repres_key ), function(){
            _.forIn( repres_value, function( cond_value,
                                             cond_key ){
              var conditionText = "in condition ".concat( cond_key );
              conditionText = conditionText.concat( " the correct answer should be given" );
              it( conditionText, function(){
                var subset = subsetNcomp.subsetCloseTo( cond_value.Repr, fx.subsetNComp_closeTo.CP );
                var whatComesOut = _.map( subset, '_id' );
                if( !cond_value.answer ){
                  expect( typeof whatComesOut ).not.equal( 'undefined' );
                  expect( whatComesOut.length ).to.be.equal( 0 );
                } else {
                  _.each( whatComesOut, function( someResponse,
                                                  index ){
                    expect( someResponse ).to.equal( cond_value.answer[ index ] );
                  } );

                }
                ;
              } );

            } );
          } );
Example #29
0
SocketMaster.prototype._socketItems = function(nsp, items, callback) {
  _.forIn(items, function(item, name) {
    var nspAndName;

    nspAndName = nsp + name;

    if (!this.nsp[nspAndName]) {
      console.log('Creating new socket for: ' + nspAndName);

      this.nsp[nspAndName] = this.io.of(nspAndName);

      this.nsp[nspAndName].on('connection', function(socket) {
        console.log('User connected to socket: ', nspAndName);

        socket.on('disconnect', function() {
          console.log('User disconnected from socket: ', nspAndName);
        });

        callback(socket, nspAndName, item);
      });
    }
  }, this);
};
    describe('log levels', function () {

      _.forIn(JasmineMigrate.logLevels, function (level, constant) {
        context('when log level is set to `' + constant + '`', function () {
          before(function () {
            sinon.stub(console, level);

            installPlugin({ log: true, logLevel: level });
          });

          after(function () {
            console[level].restore();
          });

          it('logs with correct method', function () {
            plugin.log('the thing');

            console[level].should.have.been.calledWith('JasmineMigrate:', 'the thing');
          });
        });
      });

    });