/*
Finds any partial specifications and creates a generated specification
344643
void createTotalSpecifications(final File dir, final String packageDirectory) throws MojoExecutionException {

        if (dir.equals(null)) {
            throw new MojoExecutionException("Could not read from directory " + dir.getPath());
        }
        final File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        final File[] providedContextFiles = dir.listFiles((java.io.FileFilter) FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(), FileFilterUtils.nameFileFilter("providedcontext.json")));
        if (providedContextFiles.length == 1) {
            final File parent = providedContextFiles[0].getParentFile();
            final File outputDir = new File(getSpecificationOutput() + File.separator + packageDirectory.substring(0,packageDirectory.lastIndexOf(File.separator)));
            outputDir.mkdirs();
            try {
                generateTotalSpecification(parent, outputDir);
            } catch (final CodeGenException e) {
                throw new MojoExecutionException("Couldn't create total specification",e);
            }
        }
        for (File entry : dir.listFiles()) {
            if (entry.isDirectory()) {
                createTotalSpecifications(entry, (packageDirectory == null) ? entry.getName() : packageDirectory + File.separator + entry.getName());
            }
        }
    }
1000069
function getParamsDetails(spec_c) {
  var paras = getChildren(spec_c, 'para');
  var details = _.find(_.map(paras, function(para) {
    return getChild(para, 'parameterlist');
  }), function(obj) { return (obj != undefined); });
  return (details ? details.children : undefined);
}
639125
function findOneOrCreatePlugin(schema) {
    schema.statics.findOneOrCreate = function findOneOrCreate(condition, doc, callback) {
        var self = this;

        self.findOne(condition, function(err, result ) {
            if (result) {
                callback(err, result);
            } else {
                self.create(doc, function(err, result) {
                    callback(err, result);
                });
            }
        });
    };
}
1041924
function GENERATE_PARAMS(spec) {
  return _.map(spec, function(paramSpec, paramName) {
    return paramName + ': ' + paramSpec.type;
  }).join(', ');
}
218909
function generateTables() {

        function buildLiteral( literal ) {

            return `"${ util.stringEscape( literal ) }"`;

        }

        function buildRegexp( cls ) {

            return "/^["
                + ( cls.inverted ? "^" : "" )
                + cls.value
                    .map( part => (

                        Array.isArray( part )
                            ? util.regexpEscape( part[ 0 ] )
                                + "-"
                                + util.regexpEscape( part[ 1 ] )
                            : util.regexpEscape( part )

                    ) )
                    .join( "" )
                + "]/"
                + ( cls.ignoreCase ? "i" : "" );

        }

        function buildExpectation( e ) {

            switch ( e.type ) {

                case "rule":
                    return `peg$otherExpectation("${ util.stringEscape( e.value ) }")`;

                case "literal":
                    return "peg$literalExpectation(\""
                           + util.stringEscape( e.value )
                           + "\", "
                           + e.ignoreCase
                           + ")";

                case "class": {

                    const parts = e.value.map( part =>
                        ( Array.isArray( part )
                            ? `["${ util.stringEscape( part[ 0 ] ) }", "${ util.stringEscape( part[ 1 ] ) }"]`
                            : `"${ util.stringEscape( part ) }"` )
                    );

                    return "peg$classExpectation(["
                           + parts.join( ", " ) + "], "
                           + e.inverted + ", "
                           + e.ignoreCase
                           + ")";

                }

                case "any":
                    return "peg$anyExpectation()";

                // istanbul ignore next
                default:
                    session.fatal( `Unknown expectation type (${ JSON.stringify( e ) })` );

            }

        }

        function buildFunc( f ) {

            return `function(${ f.params.join( ", " ) }) {${ f.body }}`;

        }

        if ( options.optimize === "size" ) {

            return [
                "var peg$literals = [",
                indent2( ast.literals.map( buildLiteral ).join( ",\n" ) ),
                "];",
                "var peg$regexps = [",
                indent2( ast.classes.map( buildRegexp ).join( ",\n" ) ),
                "];",
                "var peg$expectations = [",
                indent2( ast.expectations.map( buildExpectation ).join( ",\n" ) ),
                "];",
                "var peg$functions = [",
                indent2( ast.functions.map( buildFunc ).join( ",\n" ) ),
                "];",
                "",
                "var peg$bytecode = [",
                indent2( ast.rules
                    .map( rule =>
                        `peg$decode("${
                            util.stringEscape( rule.bytecode
                                .map( b => String.fromCharCode( b + 32 ) )
                                .join( "" )
                            )
                        }")`
                    )
                    .join( ",\n" )
                ),
                "];"
            ].join( "\n" );

        }

        return ast.literals
            .map( ( c, i ) => "var " + l( i ) + " = " + buildLiteral( c ) + ";" )
            .concat( "", ast.classes.map(
                ( c, i ) => "var " + r( i ) + " = " + buildRegexp( c ) + ";"
            ) )
            .concat( "", ast.expectations.map(
                ( c, i ) => "var " + e( i ) + " = " + buildExpectation( c ) + ";"
            ) )
            .concat( "", ast.functions.map(
                ( c, i ) => "var " + f( i ) + " = " + buildFunc( c ) + ";"
            ) )
            .join( "\n" );

    }
422255
function(template, context, partials) {
        if(!this.includes("#", template) && !this.includes("^", template)) {
          return template;
        }

        var that = this;
        // CSW - Added "+?" so it finds the tighest bound, not the widest
        var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
                "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
                "\\s*", "mg");

        // for each {{#foo}}{{/foo}} section do...
        return template.replace(regex, function(match, type, name, content) {
          var value = that.find(name, context);
          if(type == "^") { // inverted section
            if(!value || that.is_array(value) && value.length === 0) {
              // false or empty list, render it
              return that.render(content, context, partials, true);
            } else {
              return "";
            }
          } else if(type == "#") { // normal section
            if(that.is_array(value)) { // Enumerable, Let's loop!
              return that.map(value, function(row) {
                return that.render(content, that.create_context(row),
                  partials, true);
              }).join("");
            } else if(that.is_object(value)) { // Object, Use it as subcontext!
              return that.render(content, that.create_context(value),
                partials, true);
            } else if(typeof value === "function") {
              // higher order section
              return value.call(context, content, function(text) {
                return that.render(text, context, partials, true);
              });
            } else if(value) { // boolean section
              return that.render(content, context, partials, true);
            } else {
              return "";
            }
          }
        });
      }
338849
function generateFunctionsFiles ({ suffix, factories, entryFolder }) {
  const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars

  const sortedFactories = sortFactories(values(factories))

  // sort the factories, and split them in three groups:
  // - transform: the transform functions
  // - impure: the functions that depend on `math` or `mathWithTransform` (directly or indirectly),
  // - pure: the rest
  const pureFactories = []
  const impureFactories = []
  const transformFactories = []
  sortedFactories
    .filter(factory => !DEPRECATED_FACTORIES[factory.fn])
    .forEach(factory => {
      if (isTransform(factory)) {
        transformFactories.push(factory)
      } else if (
        contains(factory.dependencies, 'math') ||
        contains(factory.dependencies, 'mathWithTransform') ||
        contains(factory.dependencies, 'classes') ||
        isTransform(factory) ||
        factory.dependencies.some(dependency => {
          return impureFactories.find(f => f.fn === stripOptionalNotation(dependency))
        })
      ) {
        impureFactories.push(factory)
      } else {
        pureFactories.push(factory)
      }
    })

  // a map containing:
  // {
  //   'sqrt': true,
  //   'subset': true,
  //   ...
  // }
  const pureExists = {
    config: true
  }
  pureFactories.forEach(factory => {
    pureExists[factory.fn] = true
  })

  const impureExists = {
    ...pureExists
  }
  impureFactories.forEach(factory => {
    impureExists[factory.fn] = true
  })

  const math = sortedFactories
    .filter(factory => !isClass(factory))
    .filter(factory => !isTransform(factory))
    .map(factory => {
      return {
        name: factory.fn,
        renamed: DEPRECATED_FACTORIES[factory.fn],
        mappedName: FACTORY_NAMES_ES6_MAPPING[factory.fn]
      }
    })

  const classes = sortedFactories
    .filter(factory => isClass(factory))
    .map(factory => ({ name: factory.fn }))

  const data = {
    suffix,
    pureFactories: pureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            // TODO: this code is duplicated. extract it in a separate function
            if (!pureExists[dependency]) {
              if (factory.dependencies.indexOf(dependency) !== -1) {
                throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    impureFactories: impureFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    transformFactories: transformFactories.map(factory => {
      const name = FACTORY_NAMES_ES6_MAPPING[factory.fn] || factory.fn

      return {
        braceOpen,
        factoryName: findKey(factories, factory), // TODO: find a better way to match the factory names
        eslintComment: name === 'SQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,
        name,
        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES_ES6[dependency])
          .filter(dependency => {
            if (dependency === 'math' || dependency === 'mathWithTransform' || dependency === 'classes') {
              return true
            }

            // TODO: this code is duplicated. extract it in a separate function
            if (!impureExists[dependency]) {
              // if (factory.dependencies.indexOf(dependency) !== -1) {
              //   throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              // }

              return false
            }

            return true
          })
          .map(dependency => ({ name: dependency }))
      }
    }),

    math,
    classes
  }

  // create file with all functions: functionsAny.generated.js, functionsNumber.generated.js
  fs.writeFileSync(path.join(entryFolder, 'pureFunctions' + suffix + '.generated.js'), pureFunctionsTemplate(data))

  // create file with all functions: impureFunctions.generated.js, impureFunctions.generated.js
  fs.writeFileSync(path.join(entryFolder, 'impureFunctions' + suffix + '.generated.js'), impureFunctionsTemplate(data))
}
654370
function findPartials(source, source_path, options, deps) {
  var reg = /({>\s?")([^"{}]+)("[\s\S]*?\/})/g, // matches dust partial syntax
    result = null, partial,
    dep, name, replace;

  // search source & add a dependency for each match
  while ((result = reg.exec(source)) !== null) {
    partial = {
      prefix: result[1],
      name: result[2],
      suffix: result[3]
    };

    // add to dependencies
    name = addDustDependency(partial.name, source_path, options, deps);

    // retrieve newest dependency
    dep = deps[deps.length - 1];

    // log
    log(options, 'found partial dependency "' + partial.name + '"');

    // if the partial has been renamed, update the name in the template
    if (name != partial.name) {
      log(options, 'renaming partial "' + partial.name + '" to "' + name + '"')

      // build replacement for partial tag
      replace = partial.prefix + name + partial.suffix;

      // replace the original partial path with the new "absolute" path (relative to root)
      source = source.substring(0, result.index) + replace + source.substring(result.index + result[0].length);

      // update regex index
      reg.lastIndex += (replace.length - result[0].length);
    }
  }

  return source;
}
415567
function spec(node, body, objId, initProps, file) {
  // add a simple assignment for all Symbol member expressions due to symbol polyfill limitations
  // otherwise use Object.defineProperty

  var _arr2 = node.properties;
  for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
    var prop = _arr2[_i2];
    // this wont work with Object.defineProperty
    if (t.isLiteral(t.toComputedKey(prop), { value: "__proto__" })) {
      initProps.push(prop);
      continue;
    }

    var key = prop.key;
    if (t.isIdentifier(key) && !prop.computed) {
      key = t.literal(key.name);
    }

    var bodyNode = t.callExpression(file.addHelper("define-property"), [objId, key, prop.value]);

    body.push(t.expressionStatement(bodyNode));
  }

  // only one node and it's a Object.defineProperty that returns the object

  if (body.length === 1) {
    var first = body[0].expression;

    if (t.isCallExpression(first)) {
      first.arguments[0] = t.objectExpression(initProps);
      return first;
    }
  }
}
90472
private WyalFile.VariableDeclaration[] generatePostconditionTypePattern(WyilFile.Decl.FunctionOrMethod declaration,
			LocalEnvironment environment) {
		Tuple<Decl.Variable> params = declaration.getParameters();
		Tuple<Decl.Variable> returns = declaration.getReturns();
		WyalFile.VariableDeclaration[] vars = new WyalFile.VariableDeclaration[params.size() + returns.size()];
		// second, set initial environment
		for (int i = 0; i != params.size(); ++i) {
			WyilFile.Decl.Variable var = params.get(i);
			vars[i] = environment.read(var);
		}
		for (int i = 0; i != returns.size(); ++i) {
			WyilFile.Decl.Variable var = returns.get(i);
			vars[i + params.size()] = environment.read(var);
		}
		//
		return vars;
	}
790925
def generate_specifications(self, count=1):
        

        out = {}

        # mapping of UID index to AR objects {1: <AR1>, 2: <AR2> ...}
        copy_from = self.get_copy_from()

        for arnum in range(count):
            # get the source object
            source = copy_from.get(arnum)

            if source is None:
                out[arnum] = {}
                continue

            # get the results range from the source object
            results_range = source.getResultsRange()

            # mapping of keyword -> rr specification
            specification = {}
            for rr in results_range:
                specification[rr.get("keyword")] = rr
            out[arnum] = specification

        return out
989123
function generateModelDefinition () {
    var definition = {};
    var schema = controller.model().schema;

    definition.id = capitalize(controller.model().singular());
    definition.properties = {};

    Object.keys(schema.paths).forEach(function (name) {
      var path = schema.paths[name];
      var property = generatePropertyDefinition(name, path);
      definition.properties[name] = property;
    });

    Object.keys(schema.virtuals).forEach(function (name) {
      var path = schema.virtuals[name];
      var property = generatePropertyDefinition(name, path);
      definition.properties[name] = property;
    });

    return definition;
  }
937004
function findCustomPropertyDefinitions(cssAssets) {
  const definitionsByProp = {};
  const incomingReferencesByProp = {};
  for (const cssAsset of cssAssets) {
    cssAsset.eachRuleInParseTree(cssRule => {
      if (
        cssRule.parent.type === 'rule' &&
        cssRule.type === 'decl' &&
        /^--/.test(cssRule.prop)
      ) {
        (definitionsByProp[cssRule.prop] =
          definitionsByProp[cssRule.prop] || new Set()).add(cssRule);
        for (const customPropertyName of extractReferencedCustomPropertyNames(
          cssRule.value
        )) {
          (incomingReferencesByProp[cssRule.prop] =
            incomingReferencesByProp[cssRule.prop] || new Set()).add(
            customPropertyName
          );
        }
      }
    });
  }
  const expandedDefinitionsByProp = {};
  for (const prop of Object.keys(definitionsByProp)) {
    expandedDefinitionsByProp[prop] = new Set();
    const seenProps = new Set();
    const queue = [prop];
    while (queue.length > 0) {
      const referencedProp = queue.shift();
      if (!seenProps.has(referencedProp)) {
        seenProps.add(referencedProp);
        if (definitionsByProp[referencedProp]) {
          for (const cssRule of definitionsByProp[referencedProp]) {
            expandedDefinitionsByProp[prop].add(cssRule);
          }
        }
        const incomingReferences = incomingReferencesByProp[referencedProp];
        if (incomingReferences) {
          for (const incomingReference of incomingReferences) {
            queue.push(incomingReference);
          }
        }
      }
    }
  }

  return expandedDefinitionsByProp;
}
1181727
function generateModel(path, modelName, modelFields, generateMethod, ts, cb) {
    var fields = formatTools.getFieldsForModelTemplate(modelFields);
    var schemaName = modelName + 'Schema';

    var extension = (ts) ? 'ts' : 'js';
    var model = ft.loadTemplateSync('model.' + extension);
    model = model.replace(/{modelName}/, modelName);
    model = model.replace(/{schemaName}/g, schemaName);
    model = model.replace(/{fields}/, fields);

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'models', function () {
            ft.writeFile(path + '/models/' + modelName + 'Model.' + extension, model, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Model.' + extension, model, null, cb);
        });
    }
}
1007706
private String[] getClosureCompilerArgs(GlobalPostProcessingContext ctx, List<JoinableResourceBundle> tmpBundles,
			Map<String, String> resultBundlePathMapping) {

		List<String> args = new ArrayList<>();
		JawrConfig config = ctx.getJawrConfig();
		List<JoinableResourceBundle> bundles = new ArrayList<>(tmpBundles);

		// Handle All closure parameters defined in Jawr config
		initCompilerClosureArgumentsFromConfig(args, config);

		String excludedBundlesProp = config.getProperty(JAWR_JS_CLOSURE_BUNDLES_EXCLUDED, "");
		List<String> excludedBundles = Arrays
				.asList(excludedBundlesProp.replaceAll(" ", "").split(MODULE_DEPENDENCIES_SEPARATOR));

		// handle user specified modules
		Map<String, JoinableResourceBundle> bundleMap = new HashMap<>();
		for (JoinableResourceBundle bundle : bundles) {
			if (!excludedBundles.contains(bundle.getName())) {
				bundleMap.put(bundle.getName(), bundle);
			}
		}

		String modules = config.getProperty(JAWR_JS_CLOSURE_MODULES);
		List<String> depModulesArgs = new ArrayList<>();

		List<String> globalBundleDependencies = getGlobalBundleDependencies(ctx, excludedBundles);

		// Initialize the modules arguments
		initModulesArgs(resultBundlePathMapping, args, bundles, bundleMap, modules, depModulesArgs,
				globalBundleDependencies);

		// handle the other bundles
		for (JoinableResourceBundle bundle : bundles) {
			if (!excludedBundles.contains(bundle.getName())) {
				generateBundleModuleArgs(args, bundleMap, resultBundlePathMapping, bundle, globalBundleDependencies);
			}
		}

		// Add dependency modules args after to conform to dependency definition
		// of closure args
		args.addAll(depModulesArgs);

		if (LOGGER.isDebugEnabled()) {
			StringBuilder strArg = new StringBuilder();
			for (String arg : args) {
				strArg.append(arg).append(" ");
			}

			LOGGER.debug("Closure Compiler Args : " + strArg.toString());
		}
		return args.toArray(new String[] {});
	}
834677
function (spec_str) {

	// Specification string
	this.specStr = spec_str;

	// Variable type
	this.VARIABLE_TYPES = ['BOOLEAN', 'FLOAT', 'INTEGER', 'NUMBER', 'STRING', 'TEXT'];
	this.type = null;

	// Range of value
	this.min = null;
	this.max = null;

	// Additonal options
	this.OPTION_KEYS = ['DEFAULT', 'REGEXP'];

	// Additonal options - Default value
	this.default = null;

	// Additonal options - Regular Expression for STRING or TEXT
	this.regExp = null;

	// ---

	// Parse the specification string
	this._parseSpec(this.specStr);

}
137335
function addPartial(filename, done) {
      // Create a copy of the file and delete it from the database.
      const file = clone(files[filename])
      delete files[filename]

      // Compile the partial.
      const info = path.parse(filename)
      const transform = info.ext ? info.ext.substring(1) : null
      const transformer = getTransformer(transform)
      if (transformer) {
        // Construct the options.
        const options = extend({}, metalsmith.metadata(), file, {
          filename: path.join(metalsmith.source(), filename)
        })

        // Compile the partial.
        transformer.compileAsync(file.contents.toString(), options).then(template => {
          /**
           * Define the partial as a function.
           */
          metalsmith.metadata().partials[info.name] = locals => {
            const opt = extend({}, options, locals)
            return template.fn.apply(file, [opt])
          }
          metalsmith.metadata().partials[info.name].file = file
          done()
        }, done)
      } else {
        // Do not error out when the Transformer is not found.
        done()
      }
    }