helper function to create a factory with a flag recreateOnConfigChange idea: allow passing optional properties to be attached to the factory function as 4th argument?
323166
function recreateFactory (name, dependencies, create) {
  const f = factory(name, dependencies, create)
  f.recreateOnConfigChange = true
  return f
}
516478
@SuppressWarnings("unchecked")
	@Override
	public <T> T create(String aName, Object[] params)
	{
		if(aName == null || aName.length() == 0)
			return null;
		
		String factoryName = new StringBuilder(PROP_PREFIX).append(aName).toString();
		
		Object serviceObj = null;
		
		if(singletonCreation)
		    serviceObj = factoryMap.get(factoryName.toString());
		
		if(serviceObj == null)
		{
			//create
			String className = settings.getProperty(factoryName,aName);
			serviceObj = ClassPath.newInstance(className,params);
			
			if(setNestedProperties)
				setProperties(factoryName, serviceObj);
			
			if(singletonCreation)
			   factoryMap.put(factoryName, serviceObj);		
		}
		
		return (T)serviceObj;
	}
189433
function factory(fn){
    if (typeof fn != 'function')
      fn = getter(fn);

    var result = function(value){
      return fn(value);
    };
    /** @cut */ result = devInfoResolver.patchFactory(result);
    result.factory = FACTORY;

    return result;
  }
1062643
def bind(self, key, factory):
        
        if key in self.factories:
            raise AlreadyBoundError(key)
        else:
            self.factories[key] = factory
1131330
function factory(options) {
  options = _.extend({}, options, defaultOptions);

  if (!_.isString(options.warpAndWeftSeparator)) {
    options.warpAndWeftSeparator = '';
  }
  if (options.warpAndWeftSeparator == '') {
    options.warpAndWeftSeparator = index.warpAndWeftSeparator;
  }

  options.transformSyntaxTree = tartan.transform([
    options.transformSyntaxTree,
    tartan.transform.fold({
      allowRootReorder: false,
      allowNestedBlocks: false,
      maxFoldLevels: 2,
      minBlockSize: 3,
      greedy: false,
      allowSplitStripe: false,
      processExistingBlocks: false
    })
  ]);

  options.join = function(components) {
    var parts = [];
    if (components.colors.length > 0) {
      parts.push(components.colors.join(' '));
    }
    if (components.warp != components.weft) {
      parts.push(components.warp + ' ' + options.warpAndWeftSeparator +
        ' ' + components.weft);
    } else {
      parts.push(components.warp);
    }
    return parts.join('\n');
  };

  return tartan.render.format(options);
}
790147
function createEntryFacade(entry) {
    if (entry instanceof Entry !== true) {
        throw new Error("Failed creating entry facade: Provided item is not an Entry");
    }
    const facadeType = getEntryFacadeType(entry);
    const createFields = facadeFieldFactories[facadeType];
    if (!createFields) {
        throw new Error(`Failed creating entry facade: No factory found for type "${facadeType}"`);
    }
    const fields = createFields(entry);
    return {
        type: facadeType,
        fields: addExtraFieldsNonDestructive(entry, fields)
    };
}
755675
function Definition (factoryName, factory) {
  var configDefaults = {}
  var deps = []

  return {
    /**
     * Calls the factory for each arguments and returns
     * the list of tasks that just got created.
     *
     * @params {Object}
     * @returns {Array}
     */
    add: function add () {
      var configs = _(arguments).toArray().flatten(true).value()

      if (configs.length === 0) {
        // by adding an empty object
        // we'll create a task that has no alias
        // that's useful for Definition that are not
        // really tasks creators (e.g the help task)
        configs = [{}]
      }

      var addedTasks = _(configs)
        .map(function (config) {
          return _.assign({}, configDefaults, config)
        })
        .map(function (config) {
          var taskName = name(factoryName, config.alias)
          var deps = _(factory(config, options())).flatten(true).filter(_.identity).value()
          var fn = _.isFunction(_.last(deps)) ? deps.pop() : _.noop

          gulp.task(taskName, deps, fn)
          return taskName
        })
        .run()

      if (gulp.tasks[factoryName] == null || gulp.tasks[factoryName].$root) {
        gulp.task(factoryName, deps.concat(tasks(factoryName + ':')))
        gulp.tasks[factoryName].$root = true
      }

      return addedTasks
    },

    /**
     * Sets the factory's default config.
     *
     * @param {Object} config
     * @returns {{add: add, defaults: defaults, before: before}}
     */
    defaults: function defaults (config) {
      configDefaults = config
      return this
    },

    /**
     * Getter/setter that add tasks to run before any factory's task.
     *
     * @returns {*}
     */
    before: function before () {
      if (arguments.length) {
        deps = arguments[0]
        return this
      }

      return deps
    }
  }
}
655203
def params_factory(schema: dict, add_message: bool) -> list:
    

    # Immediately create message as an argument
    params = []
    if add_message:
        params.append(click.Argument(["message"], required=False))

    for property, prpty_schema in schema.items():
        multiple = False
        choices = None

        if any(char in property for char in ["@"]):
            continue
        if prpty_schema.get("type") in COMPLEX_TYPES:
            continue
        if prpty_schema.get("duplicate"):
            continue
        if property == "message":
            continue

        elif not prpty_schema.get("oneOf"):
            click_type, description, choices = json_schema_to_click_type(prpty_schema)
        else:
            click_type, multiple, description = handle_oneof(prpty_schema["oneOf"])
            # Not all oneOf schema can be handled by click
            if not click_type:
                continue

        # Convert bool values into flags
        if click_type == click.BOOL:
            param_decls = [get_flag_param_decals_from_bool(property)]
            click_type = None
        else:
            param_decls = [get_param_decals_from_name(property)]

        if description:
            description = description.capitalize()

            if multiple:
                if not description.endswith("."):
                    description += "."
                description += " Multiple usages of this option are allowed"
        # Construct the base command options
        option = partial(
            click.Option, param_decls=param_decls, help=description, multiple=multiple
        )

        if choices:
            option = option(type=choices)
        elif click_type:
            option = option(type=click_type)
        else:
            option = option()
        params.append(option)
    return params
1365442
function Builder(baseURL, cfg) {
  if (typeof baseURL == 'object') {
    cfg = baseURL;
    baseURL = null;
  }

  this.loader = null;
  this.resetConfig = function() {};

  this.reset();

  if (baseURL)
    this.config({ baseURL: baseURL });

  // config passed to constructor will
  // be saved for future .reset() calls
  if (typeof cfg == 'object')
    this.config(cfg, true, !!baseURL);
  else if (typeof cfg == 'string')
    this.loadConfigSync(cfg, true, !!baseURL);
}
1217791
function cordovaCreateLegacyAdapter (dir, id, name, cfg, extEvents) {
    // Unwrap and shallow-clone that nasty nested config object
    const opts = Object.assign({}, ((cfg || {}).lib || {}).www);

    if (id) opts.id = id;
    if (name) opts.name = name;
    if (extEvents) opts.extEvents = extEvents;

    return cordovaCreate(dir, opts);
}
827293
@SuppressWarnings("unchecked")
	public T create(Object[] args)
	{
		for(int i=0, n=args.length; i<n; i++)
		{
			if(arguments[i] instanceof FactoryDefinition.InjectedArgument)
			{
				args[i] = arguments[i].getValue(null);
			}
		}

		try
		{
			return (T) raw.newInstance(args);
		}
		catch(IllegalArgumentException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(InstantiationException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(IllegalAccessException e)
		{
			throw new SerializationException("Unable to create; " + e.getMessage(), e);
		}
		catch(InvocationTargetException e)
		{
			throw new SerializationException("Unable to create; " + e.getCause().getMessage(), e.getCause());
		}
	}
232689
function factory(options) {
  options = _.extend({}, options);

  if (!_.isString(options.warpAndWeftSeparator)) {
    options.warpAndWeftSeparator = '';
  }
  if (options.warpAndWeftSeparator == '') {
    options.warpAndWeftSeparator = index.warpAndWeftSeparator;
  }

  return tartan.parse([
    tartan.parse.pivot(),
    tartan.parse.stripe(),
    tartan.parse.literal('['),
    tartan.parse.literal(']'),
    tartan.parse.literal('('),
    tartan.parse.literal(')'),
    tartan.parse.literal(options.warpAndWeftSeparator),
    tartan.parse.repeat({
      allowAsPrefix: true,
      allowAsSuffix: true
    }),
    tartan.parse.color({
      allowLongNames: true,
      colorPrefix: /[=]?[#]/,
      colorSuffix: null,
      colorFormat: 'both',
      allowComment: true,
      commentSuffix: /;/,
      requireCommentSuffix: false,
      commentFormat: /^\s*(.*)\s*;\s*$/
    })
  ], {
    errorHandler: options.errorHandler,
    processTokens: tartan.filter([
      options.processTokens,
      tartan.filter.removeTokens(tartan.defaults.insignificantTokens)
    ]),
    buildSyntaxTree: syntax({
      errorHandler: options.errorHandler,
      processTokens: tartan.filter.classify({
        isWarpAndWeftSeparator: function(token) {
          return tartan.utils.token.isLiteral(token) &&
            (token.value == options.warpAndWeftSeparator);
        }
      }),
      transformSyntaxTree: options.transformSyntaxTree
    })
  });
}
882150
function initCreate (args) {
    // method name is moduleNameCreate
    var methodName = `${this.name}Create`
    // method signature is moduleName.methodname
    var methodSignature = `${this.moduleName}.${methodName}`
    // capture model to pass to function
    var model = this
    // add create method to module and to object instance
    this.createMeta = immutable.method(methodSignature, function (args) {
        return createMeta(model, args)
    }, {
        // disable freezing args
        freeze: false,
    })
}
1164396
function setting(options) {
  var conf = {};

  if (options === null || typeof options !== 'object') {
    options = {};
  }

  for (var key in defaultSetting) {
    conf[key] = options[key] === undefined ? defaultSetting[key] : options[key];
  }

  conf.format = defaultFormat(['json', 'xml'].indexOf(conf.format.toLowerCase()));

  var prefix = conf.prefix;
  if ((typeof prefix === 'string' || util.isRegExp(prefix)) && !options.prefixPattern) {
    conf.prefixPattern = util.isRegExp(prefix) ? prefix : new RegExp(prefix);
  }

  if (conf.authenticate) {
    conf.deny = options.deny;
    conf.authenticatePattern = options.authenticatePattern || conf.prefixPattern;

    if (conf.authenticate.constructor.name !== 'GeneratorFunction') {
      console.error('authenticate should be a GeneratorFunction');
      conf.authenticate = false;
    }
    if (conf.deny.constructor.name !== 'GeneratorFunction') {
      console.error('deny should be a GeneratorFunction');
    }
  }

  return conf;
}
927917
function factory(key, options) {
  var settings = options || {}

  function one(value) {
    var fn = one.invalid
    var handlers = one.handlers

    if (value && own.call(value, key)) {
      fn = own.call(handlers, value[key]) ? handlers[value[key]] : one.unknown
    }

    return (fn || noop).apply(this, arguments)
  }

  one.handlers = settings.handlers || {}
  one.invalid = settings.invalid
  one.unknown = settings.unknown

  return one
}
643899
def init(self, *args):
        '''
        '''
        cfg = {}
        for k, v in self.options.items():
            if k.lower() in self.cfg.settings and v is not None:
                cfg[k.lower()] = v
        return cfg
732839
function generateTSConfig(options, fileNames) {
        var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
        var configurations = {
            compilerOptions: serializeCompilerOptions(compilerOptions)
        };
        if (fileNames && fileNames.length) {
            // only set the files property if we have at least one file
            configurations.files = fileNames;
        }
        return configurations;
        function getCustomTypeMapOfCommandLineOption(optionDefinition) {
            if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
                // this is of a type CommandLineOptionOfPrimitiveType
                return undefined;
            }
            else if (optionDefinition.type === "list") {
                return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
            }
            else {
                return optionDefinition.type;
            }
        }
        function getNameOfCompilerOptionValue(value, customTypeMap) {
            // There is a typeMap associated with this command-line option so use it to map value back to its name
            for (var key in customTypeMap) {
                if (customTypeMap[key] === value) {
                    return key;
                }
            }
            return undefined;
        }
        function serializeCompilerOptions(options) {
            var result = ts.createMap();
            var optionsNameMap = getOptionNameMap().optionNameMap;
            for (var name_35 in options) {
                if (ts.hasProperty(options, name_35)) {
                    // tsconfig only options cannot be specified via command line,
                    // so we can assume that only types that can appear here string | number | boolean
                    switch (name_35) {
                        case "init":
                        case "watch":
                        case "version":
                        case "help":
                        case "project":
                            break;
                        default:
                            var value = options[name_35];
                            var optionDefinition = optionsNameMap[name_35.toLowerCase()];
                            if (optionDefinition) {
                                var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
                                if (!customTypeMap) {
                                    // There is no map associated with this compiler option then use the value as-is
                                    // This is the case if the value is expect to be string, number, boolean or list of string
                                    result[name_35] = value;
                                }
                                else {
                                    if (optionDefinition.type === "list") {
                                        var convertedValue = [];
                                        for (var _i = 0, _a = value; _i < _a.length; _i++) {
                                            var element = _a[_i];
                                            convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
                                        }
                                        result[name_35] = convertedValue;
                                    }
                                    else {
                                        // There is a typeMap associated with this command-line option so use it to map value back to its name
                                        result[name_35] = getNameOfCompilerOptionValue(value, customTypeMap);
                                    }
                                }
                            }
                            break;
                    }
                }
            }
            return result;
        }
    }