Copies the no focus libs into the given profile directory.
@param {string} profileDir Path to the profile directory to install into.
@return {!promise.Promise.<string>} The LD_LIBRARY_PATH prefix string to use
for the installed libs.
174248
function installNoFocusLibs(profileDir) {
  var x86 = path.join(profileDir, 'x86');
  var amd64 = path.join(profileDir, 'amd64');

  return mkdir(x86)
      .then(copyLib.bind(null, NO_FOCUS_LIB_X86, x86))
      .then(mkdir.bind(null, amd64))
      .then(copyLib.bind(null, NO_FOCUS_LIB_AMD64, amd64))
      .then(function() {
        return x86 + ':' + amd64;
      });

  function mkdir(dir) {
    return io.exists(dir).then(function(exists) {
      if (!exists) {
        return promise.checkedNodeCall(fs.mkdir, dir);
      }
    });
  }

  function copyLib(src, dir) {
    return io.copy(src, path.join(dir, X_IGNORE_NO_FOCUS_LIB));
  }
}
1004692
function(dirname) {
  var result;

  if (!fs.test('-d', dirname))  { return result; }

  result = {};
  _.each(sg.fs.ls(dirname), (name_) => {
    const name      = path.basename(name_, '.js');
    const filename  = path.join(dirname, name);
    if (!fs.test('-f', `${filename}.js`)) { return; }   // skip
    if (name.startsWith('helper'))        { return; }   // skip helper(s).js

    result[name] = result[name] || {};
    _.extend(result[name], libRa.middlewareify(safeRequire(filename)));
  });

  return result;
}
471763
function createDirectory(options) {
  return new Promise(function(resolve, reject) {
    mkdirp( options.directory, function (err) {
      if(err && err.code !== 'EEXIST') {
        reject(err);
      } else {
        resolve(options);
      }
    });
  });
}
896460
function mkdirs(dir) {
  return new Promise((resolve, reject) => {
    FS.ensureDir(dir, err => {
      err ? reject(err) : resolve(dir);
    })
  });
}
802499
function mkdirp(con, p, callback) {
  p = path.normalize(p);
  var dirs = p.split('/').slice(1); // remove empty string at the start.

  // console.log('dirs', dirs);

  var tasks = [];
  dirs.forEach(function(dir, i) {
    var subpath = '/' + dirs.slice(0, i).join('/') + '/' + dir;
    subpath = path.normalize(subpath); // remove extra `/` in first iteration
    tasks.push(async.apply(create, con, subpath));
  });
  async.waterfall(tasks, function(err, results) {
    if(err) return callback(err);
    // succeeded!
    return callback(null, true);
  });
}
618442
function buildFromDirectory(dirPath){
	var dbsetPath = path.join(dirPath,"dbsets");
	if(fileutil.isExist(dbsetPath)){
		defaultConfig['dbsets'] = dbsetPath;
	}

	var stubsPath = path.join(dirPath,"stubs");
	if(fileutil.isExist(stubsPath)){
		defaultConfig['stubs'] = stubsPath;
	}

	var dumpsPath = path.join(dirPath,"dumps");
	if(fileutil.isExist(dumpsPath)){
		defaultConfig['dumps'] = dumpsPath;
	}

	var mappingsPath = path.join(dirPath,"mappings");
	var files = fileutil.ls(mappingsPath);
	if(files.length > 0){
		defaultConfig['mappings']['requests'] = [];
		files.forEach(function(filename){
			defaultConfig['mappings']['requests'].push(path.join(mappingsPath , filename));
		});
	}

	var trustStorePath = path.join(dirPath,"truststore");
	if(fileutil.isExist(trustStorePath)){
		defaultConfig.server.key = path.join(trustStorePath , "server.key");
		defaultConfig.server.cert = path.join(trustStorePath , "server.crt");

		var cacertPath = path.join(trustStorePath,"ca");
		var cacerts = fileutil.ls(cacertPath);

		if(cacerts.length > 0){
			defaultConfig.server.ca = [];
			cacerts.forEach(function(filename){
				defaultConfig.server.ca.push(path.join(cacertPath , filename));
			});
		}
	}
}
301755
function(channel, action, suffix) {

    var prefix = this.options.cdnBasePath + (suffix ? ('/' + suffix) : '');
    return this._createChannelDir(prefix, channel, action);
  }
300325
def initializeProfile(self):
        

        LOGGER.debug("> Building '{0}' profile.".format(self.__file))

        sections_file_parser = SectionsFileParser(self.__file)
        sections_file_parser.parse()

        if sections_file_parser.sections:
            fileStructureParsingError = lambda attribute: foundations.exceptions.FileStructureParsingError(
                "{0} | No '{1}' attribute found, '{2}' file structure seems invalid!".format(
                    self.__class__.__name__, attribute, self.__file))

            self.__directory = os.path.dirname(self.__file)
            self.__name = sections_file_parser.get_value("Name", "Component", default=None)
            if self.__name is None:
                raise fileStructureParsingError("Name")

            self.__title = sections_file_parser.get_value("Title", "Component", default=None)
            if self.__title is None:
                self.__title = self.__name

            self.__package = sections_file_parser.get_value("Module", "Component", default=None)
            if self.__package is None:
                raise fileStructureParsingError("Module")

            self.__attribute = sections_file_parser.get_value("Object", "Component", default=None)
            if self.__attribute is None:
                raise fileStructureParsingError("Object")

            self.__require = sections_file_parser.get_value("Require", "Component", default=None)
            self.__require = list() if self.__require is None else self.__require.split("|")

            self.__version = sections_file_parser.get_value("Version", "Component", default=None)
            if self.__version is None:
                raise fileStructureParsingError("Version")

            self.__author = sections_file_parser.get_value("Author", "Informations", default=None)

            self.__email = sections_file_parser.get_value("Email", "Informations", default=None)

            self.__url = sections_file_parser.get_value("Url", "Informations", default=None)

            self.__description = sections_file_parser.get_value("Description", "Informations", default=None)

            return True
        else:
            raise foundations.exceptions.FileStructureParsingError(
                "{0} | No sections found, '{1}' file structure seems invalid!".format(self.__class__.__name__,
                                                                                      self.__file))
130360
function mkdirSync(dirPath) {
    // Get relative path to output
    const relativePath = dirPath.replace(`${CWD}${pathSep}`, '');
  	const dirs = relativePath.split(pathSep);
  	let currentDir = CWD;

    // Check if each dir exists, and if not, create it
    dirs.forEach(dir => {
      currentDir = path.resolve(currentDir, dir);
      if(!fs.existsSync(currentDir)) {
        fs.mkdirSync(currentDir);
      }
    });
  }
143193
function profile(excludeRegex) {
  var categories = [];
  return {
    forCategory: forCategory,
    toArray    : toArray,
    toString   : toString
  };

  function toArray() {
    return categories;
  }

  function toString() {
    return categories
      .map(String)
      .filter(Boolean)
      .join('\n');
  }

  /**
   * Create a category for analysis.
   * @param {string} [label] Optional category label
   * @param {{forCategory:function, start:function, stop:function, report:function, toString:function}} A new instance
   */
  function forCategory(label) {
    var eventsByFilename = {},
        isUsed           = false,
        self             = {
          forCategory: forCategory,
          start      : start,
          stop       : stop,
          report     : report,
          toString   : toString
        };

    label = label || ('category-' + String.fromCharCode(65 + categories.length));
    categories.push(self);
    return self;

    /**
     * Start a segment delineated by the given key.
     * @param {string} key A key to delineate a segment
     * @returns {function} A transform that causes a start event when the file is completed streaming
     */
    function start(key) {
      return createEventTransform(key);
    }

    /**
     * Stop the currently delineated segment.
     * @returns {function} A transform that causes a stop event when the file is completed streaming
     */
    function stop() {
      return createEventTransform(null);
    }

    /**
     * Create a transform that pushes time-stamped events data to the current filename.
     * @param {*} data The event data
     * @returns {function} A browserify transform that captures events on file contents complete
     */
    function createEventTransform(data) {
      return inspect(onComplete);

      function onComplete(filename) {
        isUsed = true;
        var now = Date.now();
        var events = eventsByFilename[filename] = eventsByFilename[filename] || [];
        events.push(now, data);
      }
    }

    /**
     * Create a json report of time verses key verses filename.
     */
    function report() {
      return Object.keys(eventsByFilename)
        .filter(testIncluded)
        .reduce(reduceFilenames, {});

      function testIncluded(filename) {
        return !excludeRegex || !excludeRegex.test(filename);
      }

      function reduceFilenames(reduced, filename) {
        var totalsByKey = {},
            list        = eventsByFilename[filename],
            lastKey     = null,
            lastTime    = NaN;

        // events consist of time,key pairs
        for (var i = 0; i < list.length; i += 2) {
          var time = list[i],
              key  = list[i + 1];
          if (lastKey) {
            var initial = totalsByKey[key] || 0,
                delta   = ((time - lastTime) / 1000) || 0;
            totalsByKey[lastKey] = initial + delta;
          }
          lastKey = key;
          lastTime = time;
        }

        // total at the end to guarantee consistency
        var total = 0;
        for (var key in totalsByKey) {
          total += totalsByKey[key];
        }
        totalsByKey.total = total;

        // store by the short filename
        var short = path.relative(process.cwd(), filename);
        reduced[short] = totalsByKey;
        return reduced;
      }
    }

    /**
     * A string representation of the report, sorted by longest time.
     */
    function toString() {
      var json            = report(),
          filenames       = Object.keys(json),
          longestFilename = filenames.reduce(reduceFilenamesToLength, 0),
          columnOrder     = orderColumns(),
          headerRow       = [label].concat(columnOrder).map(leftJustify).join(' '),
          delimiter       = (new Array(headerRow.length + 1)).join('-');

      if (isUsed) {
        return [delimiter, headerRow, delimiter]
          .concat(rows())
          .concat(delimiter)
          .filter(Boolean)
          .join('\n');
      } else {
        return '';
      }

      /**
       * Establish the column names, in order, left justified (for the maximum length).
       */
      function orderColumns() {
        var keyTotals = filenames.reduce(reduceFilenamesToKeyTotal, {});
        return sort(keyTotals);

        function reduceFilenamesToKeyTotal(reduced, filename) {
          var item = json[filename];
          return Object.keys(item)
            .reduce(reducePropToLength.bind(item), reduced);
        }
      }

      /**
       * Map each filename to a data row, in decreasing time order.
       */
      function rows() {
        var fileTotals = filenames.reduce(reducePropToLength.bind(json), {}),
            fileOrder  = sort(fileTotals);
        return fileOrder.map(rowForFile);

        function rowForFile(filename) {
          var data = json[filename];
//          console.log(JSON.stringify(data, null, 2));
          return [filename]
            .concat(columnOrder
              .map(dataForColumn)
              .map(formatFloat))
            .map(leftJustify)
            .join(' ');

          function dataForColumn(column) {
            return data[column];
          }

          function formatFloat(number) {
            var padding  = '000',
                warning  = ((number > 99) ? '>' : ' '),
                integer  = (padding + Math.min(99, Math.floor(number))).slice(-2),
                fraction = (padding + Math.round(1000 * number)).slice(-3);
            return warning + integer + '.' + fraction;
          }
        }
      }

      function reduceFilenamesToLength(reduced, filename) {
        return Math.max(filename.length, reduced);
      }

      function leftJustify(name, i) {
        var length = i ? Math.max(7, columnOrder[i - 1].length) : longestFilename;
        var padding = (new Array(length + 1)).join(' ');
        return (name + padding).slice(0, length);
      }

      function reducePropToLength(reduced, key) {
        var value = (typeof this[key] === 'object') ? this[key].total : this[key];
        reduced[key] = (reduced[key] || 0) + value;
        return reduced;
      }

      function sort(object) {
        return Object.keys(object)
          .reduce(createObjects.bind(object), [])
          .sort(sortTimeDescending)
          .map(getColumnName);

        function createObjects(reduced, field) {
          reduced.push({
            name: field,
            time: Math.round(this[field] * 1000) / 1000  // millisecond precision
          });
          return reduced;
        }

        function sortTimeDescending(a, b) {
          return b.time - a.time;
        }

        function getColumnName(object) {
          return object.name;
        }
      }
    }
  }
}
276331
function _stampReferencePath(distFolder) {
  const fileName = path.join(distFolder, 'src/component/viewer.component.d.ts');

  return new Promise((resolve) => {
    console.log('Correcting reference paths...');

    // Read file
    let contents = fs.readFileSync(fileName).toString();

    // Remove first line
    contents = contents.substring(contents.indexOf('\n') + 1);
    // Replace with correct reference paths
    contents = '/// <reference types="three" />\n'
      + '/// <reference types="forge-viewer" />\n'
      + contents;

    // Write file
    fs.writeFileSync(fileName, contents);

    resolve();
  });

}
806989
function createGrunter (Lib) {
  'use strict';
  var Q = Lib.q,
    Node = require('allex_nodehelpersserverruntimelib')(Lib),
    Path = Node.Path,
    gruntLocation = findGruntLocation();

  function checkForGrunt (dir) {
    return Node.Fs.dirExists(Node.Path.join(dir, 'node_modules', 'grunt'));
  }

  function findGruntLocation () {
    var dir = __dirname;
    while (!checkForGrunt(dir)) {
      dir = Path.resolve(dir, '..');
    }
    return dir;
  }

  function finalizeGrunt(config) {
    var current = process.cwd();
    process.chdir(gruntLocation);
    config.GruntTasks.forEach(grunt.task.loadNpmTasks.bind(grunt.task));
    grunt.task.run(config.tasklist);
    process.chdir(current);
    if (Lib.isFunction(config.done)) {
      grunt.task.options({
        done: config.done
      });
    }
    grunt.task.start();

  }

  function goforGrunt (config, params, grunt_config) {
    if (grunt_config && grunt_config.verbose) {
      grunt.option('verbose', true);
    }
    if (config.async) {
      var d = Q.defer();
      d.promise.done(finalizeGrunt.bind(null, config));
      config.grunt(grunt, params, d);
    }else{
      var res = config.grunt(grunt, params);
      if (Q.isThenable(res)) {
        res.then(finalizeGrunt.bind(null, config));
        return;
      }
      finalizeGrunt(config);
    }
  }
  return {
    appendifKeys: appendifKeys,
    appendKeyMap: appendKeyMap,
    goforGrunt : goforGrunt
  };
}
537075
function (dirname) {
        return new Promise((resolve, reject) => {
            fs.mkdir(dirname, (err) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(dirname);
                }
            });
        });
    }
253368
function _libraryFiles(directory) {
	return new Promise((fulfill) => {
		const files = [];
		klaw(directory)
			.on('data', (item) => {
				const relativePath = path.relative(directory, item.path);
				files.push(relativePath);
			})
			.on('end', () => {
				fulfill(files);
			});
	});
}
1240687
function copyAssetsLess() {
  return gulp.src(['./src/assets/stylesheets/*.less'])
    .pipe(replace(/\.\.\/.\.\/.\.\//g, function () {
      return '../../../../';
    }))
    .pipe(replace(/@import '\.\.\/\.\.\/.*\//g, function () {
      return '@import \'';
    }))
    .pipe(rename({dirname: ''}))
    .pipe(gulp.dest(libraryDist + '/dist/less'));
}
35413
function createDir (directoryToCreate) {
  return new Promise((resolve, reject) => {
    mkdirp(directoryToCreate, (err) => {
      if (err) {
        return reject(new Error(err));
      }

      return resolve();
    });
  });
}
72977
function ls_ (req, depth, cb) {
  if (typeof cb !== "function") cb = depth, depth = 1
  mkdir(npm.cache, function (er) {
    if (er) return log.er(cb, "no cache dir")(er)
    function dirFilter (f, type) {
      return type !== "dir" ||
        ( f && f !== npm.cache + "/" + req
         && f !== npm.cache + "/" + req + "/" )
    }
    find(path.join(npm.cache, req), dirFilter, depth, function (er, files) {
      if (er) return cb(er)
      return cb(null, files.map(function (f) {
        f = f.substr(npm.cache.length + 1)
        f = f.substr((f === req ? path.dirname(req) : req).length)
             .replace(/^\//, '')
        return f
      }))
    })
  })
}