Create an abstract class definition.

@param {Object}      params        An object containing methods and properties
@param {Constructor} [constructor] Assume the passed constructor

@return {Function} The constructor
339852
function createAbstractClass(params, constructor) {
        var def,
            savedMembers,
            key,
            value;

        // Handle abstract methods
        if (hasOwn(params, '$abstracts')) {
            savedMembers = params.$abstracts;
            delete params.$abstracts;
        }

        // Create the class definition
        def = Class.$create(params, constructor);
        def[$abstract] = true;

        // Grab binds
        if (savedMembers) {
            for (key in savedMembers) {
                value = savedMembers[key];

                if (value[$bound]) {
                    insert(def[$class].binds, key);
                }
            }
        }

        return def;
    }
332051
function(param) {
    if (!this.collection) {
      throw new Error('collection property not found');
    }

    param = _.extend({}, param);
        
    return find(this.collection, param);
  }
108416
function (params) {
            if (! this.active) {
                return;
            }

            var paramsArr = Array.prototype.slice.call(arguments),
                n = this._bindings.length,
                bindings;

            if (this.memorize) {
                this._prevParams = paramsArr;
            }

            if (! n) {
                //should come after memorize
                return;
            }

            bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
            this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.

            //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
            //reverse loop since listeners with higher priority will be added at the end of the list
            do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
        }
991899
function(params) {

                            // Create '_createService' function for this purpose for parameters applying to clazz constructor.
                            var service = this._createService(params.class, params.init);

                            _.each(params.call, function(params, method) {
                                service[method].apply(service, params);
                            });

                            return service;
                        }
1310145
public static Class<?>[] toClassesFromObjects(final Object[] params) {
		final Class<?>[] classes = new Class<?>[params.length];
		int i = 0;
		for (final Object object : params) {
			if (object != null) {
				classes[i++] = object.getClass();
			} else {
				classes[i++] = Object.class;
			}
		}
		return classes;
	}
970100
function newInstance(extend) {
  return (initialValues = {}) => {
    const model = {};
    const publicAPI = {};
    extend(publicAPI, model, initialValues);
    return Object.freeze(publicAPI);
  };
}
1146501
function parseClass(params, constructor) {
        var opts = {},
            key,
            value,
            saved = {},
            unallowed,
            ambiguous;

        // Check and save constants to parse later
        if (hasOwn(params, '$constants')) {
            // Check argument
            if (!isObject(params.$constants)) {
                throw new Error('$constants of class "' + constructor.prototype.$name + '" must be an object.');
            }

            // Check reserved keywords
            checkKeywords(params.$constants, 'statics');

            // Check unallowed keywords
            unallowed = testKeywords(params.$constants);
            if (unallowed) {
                throw new Error('$constants of class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".');
            }

            // Check ambiguity
            if (isObject(params.$statics)) {
                ambiguous = intersection(keys(params.$constants), keys(params.$statics));
                if (ambiguous.length) {
                    throw new Error('There are members defined in class "' + constructor.prototype.$name + '" with the same name but with different modifiers: "' + ambiguous.join('", ') + '".');
                }
            }

            saved.$constants = params.$constants;
            delete params.$constants;
        }

        // Check and save finals to parse later
        if (hasOwn(params, '$finals')) {
            // Check argument
            if (!isObject(params.$finals)) {
                throw new Error('$finals of class "' + constructor.prototype.$name + '" must be an object.');
            }

            // Check reserved keywords
            checkKeywords(params.$finals);

            // Check unallowed keywords
            unallowed = testKeywords(params.$finals, ['$statics']);
            if (unallowed) {
                throw new Error('$finals of class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".');
            }

            // Check ambiguity
            if (isObject(params.$finals.$statics)) {
                if (isObject(params.$statics)) {
                    ambiguous = intersection(keys(params.$finals.$statics), keys(params.$statics));
                    if (ambiguous.length) {
                        throw new Error('There are members defined in class "' + constructor.prototype.$name + '" with the same name but with different modifiers: "' + ambiguous.join('", ') + '".');
                    }
                }
                if (saved.$constants) {
                    ambiguous = intersection(keys(params.$finals.$statics), keys(saved.$constants));
                    if (ambiguous.length) {
                        throw new Error('There are members defined in class "' + constructor.prototype.$name + '" with the same name but with different modifiers: "' + ambiguous.join('", ') + '".');
                    }
                }
            }
            ambiguous = intersection(keys(params), keys(params.$finals));
            if (ambiguous.length) {
                remove(ambiguous, '$statics');
                if (ambiguous.length) {
                    throw new Error('There are members defined in class "' + constructor.prototype.$name + '" with the same name but with different modifiers: "' + ambiguous.join('", ') + '".');
                }
            }

            saved.$finals = params.$finals;
            delete params.$finals;
        }

        // Check and save locked to parse later
        if (hasOwn(params, '$locked')) {
            if (!isBoolean(params.$locked)) {
                throw new Error('$locked of class "' + constructor.prototype.name + '" must be a boolean.');
            }

            saved.$locked = params.$locked;
            delete params.$locked;
        }

        // Parse members
        parseMembers(params, constructor);

        // Parse constants
        if (saved.$constants) {
            opts.isConst = true;

            for (key in saved.$constants) {
                value = saved.$constants[key];

                addProperty(key, value, constructor, opts);
            }

            delete opts.isConst;
        }

        // Parse finals
        if (saved.$finals) {
            parseMembers(saved.$finals, constructor, true);
        }

        // Parse locked
        if (hasOwn(saved, '$locked')) {
            if (constructor[$class].forceUnlocked && saved.$locked) {
                throw new Error('Class "' + constructor.prototype.$name + '" cannot be locked because it borrows or extends from a vanilla class.');
            }
            if (constructor[$class].locked === false && saved.$locked) {
                throw new Error('Class "' + constructor.prototype.$name + '" inherits from an unlocked class, therefore its subclasses cannot be locked.');
            }
            constructor[$class].locked = !!saved.$locked;
            delete constructor.prototype.$locked;
        } else if (!hasOwn(constructor[$class], 'locked')) {
            constructor[$class].locked = !!options.locked;
        }
    }
376678
def instantiate(params)
      instance = Instance.new( *interpolate(params), @parent )
      instance.apply_resource_type
      instance
    end
108940
public Object newInstance( String name, Object[] params, String[] types ) throws ClassLoaderException {
        Class<?> clazz;
        try {
            clazz = loadClass(name);
        } catch (ClassNotFoundException e) {
            throw new ClassLoaderException(e);
        }
        
        List<Class> paramTypes = new ArrayList<Class>();
        
        if ( types != null ) {
            for( String type: types ) {
                try {
                    paramTypes.add( loadClass(type) );
                } catch (ClassNotFoundException e) {
                    throw new ClassLoaderException(e);
                }
            }
        } else if ( params != null ) {
            for ( Object param: params ) {
                paramTypes.add( param.getClass() );
            }
        } 
        
        if ( params != null ) {
            Constructor<?> constructor;
            try {
                constructor = clazz.getConstructor( paramTypes.toArray( new Class[paramTypes.size()] ) );
            } catch (SecurityException e) {
                throw new ClassLoaderException("Private constructor for " + clazz.getSimpleName(), e);
            } catch (NoSuchMethodException e) {
                throw new ClassLoaderException("No such constructor for " + clazz.getSimpleName(), e);
            } catch (Exception e) {
                throw new ClassLoaderException("Attempted to access constructor for " + clazz.getSimpleName(), e);
            }
            
            try {
                return constructor.newInstance(params);
            } catch (IllegalArgumentException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (InstantiationException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (IllegalAccessException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (InvocationTargetException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (Exception e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            }

        } else {
            Constructor<?> constructor;
            try {
                constructor = clazz.getConstructor();
            } catch (SecurityException e) {
                throw new ClassLoaderException("Private constructor for " + clazz.getSimpleName(),e);
            } catch (NoSuchMethodException e) {
                throw new ClassLoaderException("No such constructor for " + clazz.getSimpleName(),e);
            } catch (Exception e) {
                throw new ClassLoaderException("Attempted to access constructor for " + clazz.getSimpleName(), e);
            }
            
            try {
                return constructor.newInstance();
            } catch (IllegalArgumentException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (InstantiationException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (IllegalAccessException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (InvocationTargetException e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            } catch (Exception e) {
                throw new ClassLoaderException("Attempted to created new instance of " + clazz.getSimpleName(),e);
            }
        }
    }
209554
function(Constructor, args) {
        var instance,
            Wrapper = function() {
                return Constructor.apply(this, args || []);
            };

        Wrapper.prototype = Constructor.prototype;
        instance = new Wrapper();
        instance.constructor = Constructor;

        return instance;
    }
442160
private static String construct(final String... params) {
        final StringBuilder builder = new StringBuilder();
        for (int idx = 0; idx < params.length; idx += 2) {
            builder.append(encode(params[idx]))
                .append('=')
                .append(encode(params[idx + 1]))
                .append('&');
        }
        return builder.toString();
    }
200185
function (params) {
  assert.ok(params.__fhdb, "__fhdb parameter required for shared database");

  /**
   * Copy the default options that are always required by ditcher
   * @param target The options object to copy them to
   * @returns The options object plus the default properties
   */
  this.copyDefaultOptions = function (target) {
    target.__fhdb = params.__fhdb;
    target.__dbperapp = params.__dbperapp;
    return target;
  };

  /**
   * Create a new collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection
   * @param name collection name
   * @param (optional) options
   * @param (optional) callback results callback
   * @returns Promise if no callback passed
   */
  this.createCollection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    if (typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    if (callback) {
      params.ditcher.doCreate(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doCreate(options, function (err, collection) {
          if (err) {
            return reject(err);
          }

          resolve(collection);
        });
      });
    }
  };

  /**
   * Drop a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#dropCollection
   * @param name
   * @param (optional) callback
   * @returns Promise if no callback passed
   */
  this.dropCollection = function (name, callback) {
    assert.ok(name, "collection name required");

    var options = {
      type: name
    };

    options = this.copyDefaultOptions(options || {});

    if (callback) {
      params.ditcher.doDropCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doDropCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * List all collections
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
   * @param filter Query to filter collections by
   * @param options (optional) Optional settings
   * @returns Cursor
   */
  this.listCollections = function (filter, options) {
    options = this.copyDefaultOptions(options || {});
    return params.ditcher.doGetCollectionsListCursor(filter, options);
  };

  /**
   * Return collections instance
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#collection
   * @param name Query to filter collections by
   * @param options (optional) Optional settings
   * @param callback (optional) result callback
   * @returns Collection instance if no callback passed
   */
  this.collection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    return params.ditcher.doGetCollectionInstance(options, callback);
  };

  /**
   * Create an index on collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createIndex
   * @param name Name of the collection
   * @param fieldOrSpec Field to use for the index
   * @param options (optional) Options
   * @param callback (optional) result callback
   * @returns Promise if no callback passed
   */
  this.createIndex = function (name, fieldOrSpec, options, callback) {
    assert.ok(name, "collection name required");
    assert.ok(fieldOrSpec, "index spec required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;
    options.index = fieldOrSpec;

    if (callback) {
      params.ditcher.doIndex(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doIndex(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Rename a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#renameCollection
   * @param fromCollection Current name
   * @param toCollection New name
   * @param options (optional) Options
   * @param callback (optional) Result callback
   */
  this.renameCollection = function (fromCollection, toCollection, options, callback) {
    assert.ok(fromCollection, "current collection name required");
    assert.ok(toCollection, "new collection name required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = fromCollection;
    options.toCollection = toCollection;

    if (callback) {
      params.ditcher.doRenameCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doRenameCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Close the database connection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#close
   * @param force Force close, emitting no events
   * @param callback (optional) result callback
   */
  this.close = function (force, callback) {
    if (typeof force === "function") {
      callback = force;
      force = false;
    }

    return params.ditcher.database.close(force, callback);
  };
}
231336
function(param) {

			/**
			 * Reference the instance
			 */
			var rInstance = this;

			if (typeof param !== "undefined") {
				rInstance.text = param.text;
				rInstance.scopes = [].concat(param.scope);
			}


			/**
			 * The required regexp computed using delims in settings
			 * @type {RegExp}
			 */
			var re = new RegExp(['{%(.+?)%}|', this.delimStart, '(.+?)', this.delimEnd].join(''), 'g');

			/**
			 * Save the raw text
			 * @type {String}
			 */
			rInstance.raw = rInstance.text;

			/**
			 * Compute and assign to compiledText property of the same object
			 * @param  {String} _  Matched string
			 * @param  {String} $1 Content of first match group
			 * @param  {String} $2 Content of second match group
			 * @return {String}    Interpolated string
			 */

			rInstance.text = rInstance.text.replace(re, function(_, $1, $2) {
				var computed;

				/**
				 * If escaped value is found, interpolation will not happen
				 */
				if ($1) {
					computed = $1;
				}

				/**
				 * Matched content, let's interpolate
				 */
				if ($2) {

					/**
					 * Break out scope variables out of scope's box and evaluate the expr expression
					 */
					var scopeBox = function(expr, localScope) {
						var variables = '';

						/**
						 * If scope is a window object, no need to scopebox it
						 */
						if (typeof window !== "undefined" ? localScope !== window : true) {
							for(var i in localScope) {
								variables += 'var ' + i + ' = localScope.' + i + '; ';
							}
						}
						var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()';
						return eval(unbox);
					};

					if (rInstance.scopes.length) {
						var numScopes = rInstance.scopes.length;
						for (var i=0;i<numScopes;i++) {
							/**
							 * Current Scope
							 * @type {String}
							 */
							var scope = rInstance.scopes[i];

							/**
							 * Get the computation
							 * @type {Any}
							 */
							computed = scopeBox($2, scope);

							/**
							 * If the computed property is a function, execute it in the context of the current scope
							 * @type {Unknown}
							 */
							if (typeof computed === "function") {
								computed = computed.call(scope);
							}

							/**
							 * If the computed property is an object, get the string
							 */
							if (typeof computed === "object") {
								computed = computed.toString();
							}
								
							/**
							 * Found what we were looking for, now break the loop
							 */
							if (computed !== undefined)
								break;
						}
					} else {
						/**
						 * If no scope is passed, let us assume the global scope
						 * @type {Any}
						 */
						computed = scopeBox($2, (typeof window !== "undefined" ? window : {}));
					}

					/**
					 * If no computations were found, we return the raw matched value back
					 * @type {String}
					 */
					computed = computed !== undefined ? computed : _;
				}

				/**
				 * Final computed value returned
				 */
				return computed;
			});
			
			/**
			 * Return self for chaining
			 */
			return rInstance;
		}
312165
function (options) {
        // no splitting is being done here, as string scripts are split right before assignment below anyway
        (_.isString(options) || _.isArray(options)) && (options = { exec: options });

        if (!options) { return; } // in case definition object is missing, there is no point moving forward

        // create the request property
        /**
         * @augments {Script.prototype}
         * @type {string}
         */
        this.type = options.type || 'text/javascript';
        options.hasOwnProperty('src') && (

            /**
             * @augments {Script.prototype}
             * @type {Url}
             */
            this.src = new Url(options.src)
        );

        if (!this.src && options.hasOwnProperty('exec')) { // eslint-disable-line no-prototype-builtins
            /**
             * @augments {Script.prototype}
             * @type {Array<string>}
             */
            this.exec = _.isString(options.exec) ? options.exec.split(SCRIPT_NEWLINE_PATTERN) :
                _.isArray(options.exec) ? options.exec : undefined;
        }
    }
436413
function(params) {
		var me = this;

		if (Object.keys(model.columns).length == 0) {
			logger.error("Attempting to initialize `" + model.ident + "` instance before filling schema!");
			return null;
		} else if (model.primary === undefined) {
			logger.error("No primary key found for `" + model.ident + "`!");
			return null;
		}

		Object.defineProperty(me, 'values', {
			value: {},
			enumerable: false,
			writable: true,
			configurable: true,
		}); // Raw column values, accessed by setter/getter functions.

		params = params || {};

		/* --- Instance Methods --- */

		/**
		 * Saves the object's properties corresponding to table columns into the database.
		 */
		function save() {
			var act = new NobleMachine(function() {
				setStrs = [];

				for (var key in model.columns) {
					if ([model.primary].indexOf(key) == -1 && me[key] !== undefined) {
						setStrs.push('`' + key + '`' + " = " + nrutil.serialize(me[key]));
					}
				}

				if (model.columns['updatedAt'])
					setStrs.push('`updatedAt` = NOW()');

				var sql;
				if (me[model.primary]) {
					sql = "UPDATE " + model.table
							+ " SET " + setStrs.join(',')
							+ " WHERE `" + model.primary + "` = " + me[model.primary];
				} else {
					if (model.columns['createdAt'])
						setStrs.push('`createdAt` = NOW()');

					sql = "INSERT"
							+ " INTO " + model.table
							+ " SET " + setStrs.join(',');
				}


				act.toNext(db_query(sql));
			});

			act.next(function(result) {
				//log.debug("RESULT: " + JSON.stringify(result));

				if (result.insert_id) {
					me[model.primary] = result.insert_id;
				} else if (!me[model.primary]) {
					act.toError("No insert_id, and no extant primary key!");
					return;
				}

				
				logger.log("Successfully saved `" + model.ident + "` record `" + me[model.primary] + "`");

				act.toNext(me);
			});

			act.error(function(err) {
				logger.error("Error saving `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		/**
		 * Reloads the object's properties with the current database values.
		 */
		function reload() {
			var params = {}

			params[model.primary] = me[model.primary]
		
			var act = new NobleMachine(model.find(params));

			act.next(function(newInst) {
				if (newInst) {
					for (var col in model.columns) {
						me[col] = newInst[col];
					}

					act.toNext(me);
				} else {
					for (var key in model.columns) {
						me[key] = undefined
					}

					act.toNext(null);
				}
			});

			return act;
		}

		/**
		 * Removes this object's corresponding database row.
		 */
		function destroy() {
			var act = new NobleMachine(function() {
				if (me.onDestroy) {
					var preact = me.onDestroy();
					if (preact && preact.start instanceof Function) {
						act.toNext(preact)
						return;
					}
				}
			});

			act.next(function() {
				var sql = "DELETE FROM " + model.table
						+ " WHERE `" + model.primary + "` = " + me[model.primary];

				act.toNext(db_query(sql));
			});

			act.next(function() {
				logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");

				for (var param in me) {
					delete me[param];	
				}
			});

			act.error(function(err) {
				logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		// Generic setter for SQL-correspondent values. Forces typecasting for database compatibility.
		function setValue(key, val) {
			//util.log(key + ": " + JSON.stringify(val));

			if (val === null) {
				me.values[key] = null;
			} else if (val === undefined) {
				me.values[key] = undefined;
			} else {
				type = model.columns[key]['DATA_TYPE'];

				switch (type) {
					case 'datetime':
					case 'timestamp':
						me.values[key] = new Date(val);
						break;
					case 'text':
					case 'varchar':
						me.values[key] = val.toString();
						break;
					case 'int':
					case 'tinyint':
						if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
							me.values[key] = !!val // Boolean
						} else {
							me.values[key] = parseInt(val);
						}
						break;
					default:
						me.values[key] = val;
				}
			}
		}

		// Generic getter for SQL-correspondent values.
		function getValue(key) {
			return me.values[key];
		}

		for (var key in model.columns) {
			me.__defineSetter__(key, setValue.bind(me, key));
			me.__defineGetter__(key, getValue.bind(me, key));

			if (params[key] !== undefined) {
				setValue(key, params[key]);
			}
		}

		_.extend(me, {
			save: save,
			reload: reload,
			destroy: destroy,
			setValue: setValue
		});

		if (defFunc !== undefined) {
			defFunc(me);
		}

		return me;
	}
52271
function construct (constructor, args) {
  function Factory () {
    return constructor.apply(this, args);
  }

  Factory.prototype = constructor.prototype;

  return new Factory();
}
956755
function(options) {
    var cls = new Class(null,options);
    cls.inherit(Error);
    return cls.toFunction();
  }