Processes a module's kwargs. All modules should use this for kwarg processing.

        @obj    - An instance of the module (e.g., self)
        @kwargs - The kwargs passed to the module

        Returns None.
547351
def kwargs(self, obj, kwargs):
        '''
        
        '''
        if hasattr(obj, "KWARGS"):
            for module_argument in obj.KWARGS:
                if has_key(kwargs, module_argument.name):
                    arg_value = kwargs[module_argument.name]
                else:
                    arg_value = copy(module_argument.default)

                setattr(obj, module_argument.name, arg_value)

            for (k, v) in iterator(kwargs):
                if not hasattr(obj, k):
                    setattr(obj, k, v)
        else:
            raise Exception("binwalk.core.module.Modules.process_kwargs: %s has no attribute 'KWARGS'" % str(obj))
1202433
def _from_class(cls, class_name, module_name=None, *args, **kwargs):
        
        def _get_module(module_name):
            names = module_name.split(".")
            module = __import__(names[0])
            for i in xrange(1, len(names)):
                module = getattr(module, names[i])
            return module

        if module_name:
            # module = globals()[module_name]
            # module = __import__(module_name)
            module = _get_module(module_name)
            class_ = getattr(module, class_name)
        else:
            class_ = globals()[class_name]

        if not issubclass(class_, PersistentObject):
            t = class_.__name__, PersistentObject.__name__
            raise TypeError, 'Requested object type %s must be subtype of %s ' % t

        # workaround to mimic FactoryType to work well with FactoryObject.
        name = str(args[0]) if args else cls.__name__
        name = kwargs['name'] if 'name' in kwargs else name
        if hasattr(cls, 'get'):
            instance = cls.get(name)
            if instance:
                return instance

        instance = class_.__new__(class_, *args, **kwargs)
        instance.__init__(*args, **kwargs)
        return instance
410441
def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict:
    
    return {ARGS_LABEL: args,
            KWARGS_LABEL: kwargs}
1282313
def get_object(
        self, object_t, object_id=None, relation=None, parent=None, **kwargs
    ):
        
        url = self.object_url(object_t, object_id, relation, **kwargs)
        response = self.session.get(url)
        return self._process_json(response.json(), parent)
763754
def process(self):
        
        try:
            result = self._func(*self._args, **self._kwds)
        except:
            self._result._set_exception()
        else:
            self._result._set_value(result)
610543
def add_args_kwargs(func):
    

    @wraps(func)
    def wrapper(*args, **kwargs):

        props = argspec(func)

        # if 'args' not in props:
        if isinstance(props[1], type(None)):

            args = args[:len(props[0])]

        if ((not isinstance(props[2], type(None))) or
                (not isinstance(props[3], type(None)))):

            return func(*args, **kwargs)

        else:

            return func(*args)

    return wrapper
764475
def props(obj, required_args=None, **kwargs):
    
    pr = get_obj_attrs(obj)
    pr.update(kwargs)

    if required_args is None:
        required_args = []

    # check that required args are given
    missing = set(required_args) - set(pr.keys())
    if any(missing):
        raise ValueError("Please provide {}".format(', '.join(missing)))

    # Get the parameters to generate the waveform
    # Note that keyword arguments override values in the template object
    input_params = default_args.copy()
    input_params.update(pr)

    return input_params
432496
def load_object(self, kwargs):
        """"""
        self.object = None
        self.config = None
        self.model = self.get_model_class()
        kwargs.pop('app', None)
        kwargs.pop('model', None)

        if self.model and kwargs.get('pk', False):
            try:
                self.object = self.model.objects.get(pk=kwargs.pop('pk'))
            except Exception:
                raise Exception("Could not load {}".format(self.model.__name__.lower()))
            setattr(self, self.model.__name__.lower(), self.object)

        return kwargs
516869
def _process_for(self, node, **kwargs):
        

        # since a for loop can introduce new names into the context
        # we need to remember the ones that existed outside the loop
        previous_stored_names = self.stored_names.copy()

        with self._execution():
            self.output.write('__runtime.each(')

            if is_method_call(node.iter, dict.keys.__name__):
                self.output.write('Object.keys(')

            self._process_node(node.iter, **kwargs)

            if is_method_call(node.iter, dict.keys.__name__):
                self.output.write(')')

            self.output.write(',')
            self.output.write('function')
            self.output.write('(')

            # javascript iterations put the value first, then the key
            if isinstance(node.target, nodes.Tuple):
                if len(node.target.items) > 2:
                    raise Exception('De-structuring more than 2 items is not supported.')

                for i, item in enumerate(reversed(node.target.items)):
                    self._process_node(item, **kwargs)
                    if i < len(node.target.items) - 1:
                        self.output.write(',')
            else:
                self._process_node(node.target, **kwargs)

            self.output.write(')')
            self.output.write('{')

            if node.test:
                self.output.write('if (!(')
                self._process_node(node.test, **kwargs)
                self.output.write(')) { return; }')

        assigns = node.target.items if isinstance(node.target, nodes.Tuple) else [node.target]

        with self._scoped_variables(assigns, **kwargs):
            for n in node.body:
                self._process_node(n, **kwargs)

        with self._execution():
            self.output.write('}')
            self.output.write(')')
            self.output.write(';')

        # restore the stored names
        self.stored_names = previous_stored_names
1314607
def as_dict(self):
        
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__}

        try:
            parent_module = self.__class__.__module__.split('.')[0]
            module_version = import_module(parent_module).__version__
            d["@version"] = u"{}".format(module_version)
        except AttributeError:
            d["@version"] = None

        args = getargspec(self.__class__.__init__).args

        def recursive_as_dict(obj):
            if isinstance(obj, (list, tuple)):
                return [recursive_as_dict(it) for it in obj]
            elif isinstance(obj, dict):
                return {kk: recursive_as_dict(vv) for kk, vv in obj.items()}
            elif hasattr(obj, "as_dict"):
                return obj.as_dict()
            return obj

        for c in args:
            if c != "self":
                try:
                    a = self.__getattribute__(c)
                except AttributeError:
                    try:
                        a = self.__getattribute__("_" + c)
                    except AttributeError:
                        raise NotImplementedError(
                            "Unable to automatically determine as_dict "
                            "format from class. MSONAble requires all "
                            "args to be present as either self.argname or "
                            "self._argname, and kwargs to be present under"
                            "a self.kwargs variable to automatically "
                            "determine the dict format. Alternatively, "
                            "you can implement both as_dict and from_dict.")
                d[c] = recursive_as_dict(a)
        if hasattr(self, "kwargs"):
            d.update(**self.kwargs)
        if hasattr(self, "_kwargs"):
            d.update(**self._kwargs)
        return d
1258323
def delete_object(self, obj, view_kwargs):
        
        if obj is None:
            url_field = getattr(self, 'url_field', 'id')
            filter_value = view_kwargs[url_field]
            raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
                                 source={'parameter': url_field})

        self.before_delete_object(obj, view_kwargs)

        self.session.delete(obj)
        try:
            self.session.commit()
        except JsonApiException as e:
            self.session.rollback()
            raise e
        except Exception as e:
            self.session.rollback()
            raise JsonApiException("Delete object error: " + str(e))

        self.after_delete_object(obj, view_kwargs)
230199
def call(self, *args, **kwargs):
        
        args, kwargs = self.__process__(*args, **kwargs)
        return check_call(args, **kwargs)
474442
def j(*args, **kwargs):
    
    if not args:
        raise ValueError("you didn't pass any arguments to print out")

    with Reflect.context(args, **kwargs) as r:
        instance = J_CLASS(r, stream, **kwargs)
        instance()
831734
def produce(self, obj, val, ctx=None):
        
        val = obj.default if val == None else val
        if val == None:
            return None

        obj = deref(obj)
        ctx = {} if ctx == None else ctx
        if 'name' not in ctx and hasattr(obj, 'name'):
            ctx['name'] = obj.name
        if 'guard' not in ctx:
            ctx['guard'] = CycleGuard()
        if 'addp_schema' not in ctx:
            # Schema Object of additionalProperties
            ctx['addp_schema'] = None
        if 'addp' not in ctx:
            # additionalProperties
            ctx['addp'] = False
        if '2nd_pass' not in ctx:
            # 2nd pass processing function
            ctx['2nd_pass'] = None
        if 'factory' not in ctx:
            # primitive factory
            ctx['factory'] = self
        if 'read' not in ctx:
            # default is in 'read' context
            ctx['read'] = True

        # cycle guard
        ctx['guard'].update(obj)

        ret = None
        if obj.type:
            creater, _2nd = self.get(_type=obj.type, _format=obj.format)
            if not creater:
                raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')')

            ret = creater(obj, val, ctx)
            if _2nd:
                val = _2nd(obj, ret, val, ctx)
                ctx['2nd_pass'] = _2nd
        elif len(obj.properties) or obj.additionalProperties:
            ret = Model()
            val = ret.apply_with(obj, val, ctx)

        if isinstance(ret, (Date, Datetime, Byte, File)):
            # it's meanless to handle allOf for these types.
            return ret

        def _apply(o, r, v, c):
            if hasattr(ret, 'apply_with'):
                v = r.apply_with(o, v, c)
            else:
                _2nd = c['2nd_pass']
                if _2nd == None:
                    _, _2nd = self.get(_type=o.type, _format=o.format)
                if _2nd:
                    _2nd(o, r, v, c)
                    # update it back to context
                    c['2nd_pass'] = _2nd
            return v

        # handle allOf for Schema Object
        allOf = getattr(obj, 'allOf', None)
        if allOf:
            not_applied = []
            for a in allOf:
                a = deref(a)
                if not ret:
                    # try to find right type for this primitive.
                    ret = self.produce(a, val, ctx)
                    is_member = hasattr(ret, 'apply_with')
                else:
                    val = _apply(a, ret, val, ctx)

                if not ret:
                    # if we still can't determine the type,
                    # keep this Schema object for later use.
                    not_applied.append(a)
            if ret:
                for a in not_applied:
                    val = _apply(a, ret, val, ctx)

        if ret != None and hasattr(ret, 'cleanup'):
            val = ret.cleanup(val, ctx)

        return ret
1250932
def execute(self, *args, **kwargs):
        '''
        
        '''
        run_modules = []
        orig_arguments = self.arguments

        if args or kwargs:
            self._set_arguments(list(args), kwargs)

        # Run all modules
        for module in self.list():
            obj = self.run(module)

        # Add all loaded modules that marked themselves as enabled to the
        # run_modules list
        for (module, obj) in iterator(self.executed_modules):
            # Report the results if the module is enabled and if it is a
            # primary module or if it reported any results/errors
            if obj.enabled and (obj.PRIMARY or obj.results or obj.errors):
                run_modules.append(obj)

        self.arguments = orig_arguments

        return run_modules
355267
function process( ctx, obj ) {
    try {
        if ( Array.isArray( obj ) ) return processArray( ctx, obj );
        switch ( typeof obj ) {
        case "string":
            return processString( ctx, obj );
        case "object":
            return processObject( ctx, obj );
        default:
            return obj;
        }
    } catch ( ex ) {
        fatal( ctx, ex );
    }
}
25823
def use_args(
        self,
        argmap: ArgMap,
        req: typing.Optional[Request] = None,
        locations: typing.Iterable = None,
        as_kwargs: bool = False,
        validate: Validate = None,
        error_status_code: typing.Optional[int] = None,
        error_headers: typing.Union[typing.Mapping[str, str], None] = None,
    ) -> typing.Callable[..., typing.Callable]:
        
        locations = locations or self.locations
        request_obj = req
        # Optimization: If argmap is passed as a dictionary, we only need
        # to generate a Schema once
        if isinstance(argmap, Mapping):
            argmap = core.dict2schema(argmap, self.schema_class)()

        def decorator(func: typing.Callable) -> typing.Callable:
            req_ = request_obj

            if inspect.iscoroutinefunction(func):

                @functools.wraps(func)
                async def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = await self.parse(
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args or {})
                        return await func(*args, **kwargs)
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return await func(*new_args, **kwargs)

            else:

                @functools.wraps(func)  # type: ignore
                def wrapper(*args, **kwargs):
                    req_obj = req_

                    if not req_obj:
                        req_obj = self.get_request_from_view_args(func, args, kwargs)
                    # NOTE: At this point, argmap may be a Schema, callable, or dict
                    parsed_args = yield from self.parse(  # type: ignore
                        argmap,
                        req=req_obj,
                        locations=locations,
                        validate=validate,
                        error_status_code=error_status_code,
                        error_headers=error_headers,
                    )
                    if as_kwargs:
                        kwargs.update(parsed_args)
                        return func(*args, **kwargs)  # noqa: B901
                    else:
                        # Add parsed_args after other positional arguments
                        new_args = args + (parsed_args,)
                        return func(*new_args, **kwargs)

            return wrapper

        return decorator