Class decorator for creating a class with a metaclass.

    Adapted from the six project:

    https://pythonhosted.org/six/
339554
def add_metaclass(metaclass):
    
    vars_to_skip = ('__dict__', '__weakref__')

    def wrapper(cls):
        copied_dict = {
            key: value
            for key, value in cls.__dict__.items()
            if key not in vars_to_skip
        }
        return metaclass(cls.__name__, cls.__bases__, copied_dict)
    return wrapper
1073928
def new_instance(settings):
    
    settings = set_default({}, settings)
    if not settings["class"]:
        Log.error("Expecting 'class' attribute with fully qualified class name")

    # IMPORT MODULE FOR HANDLER
    path = settings["class"].split(".")
    class_name = path[-1]
    path = ".".join(path[:-1])
    constructor = None
    try:
        temp = __import__(path, globals(), locals(), [class_name], 0)
        constructor = object.__getattribute__(temp, class_name)
    except Exception as e:
        Log.error("Can not find class {{class}}", {"class": path}, cause=e)

    settings['class'] = None
    try:
        return constructor(kwargs=settings)  # MAYBE IT TAKES A KWARGS OBJECT
    except Exception as e:
        pass

    try:
        return constructor(**settings)
    except Exception as e:
        Log.error("Can not create instance of {{name}}", name=".".join(path), cause=e)
405073
def decorate_class(self, klass, *decorator_args, **decorator_kwargs):
        
        class ChildClass(klass):
            def __init__(slf, *args, **kwargs):
                super(ChildClass, slf).__init__(*args, **kwargs)
                self.decorate(
                    slf, *decorator_args, **decorator_kwargs
                )

        decorate_klass = ChildClass
        decorate_klass.__name__ = klass.__name__
        decorate_klass.__module__ = klass.__module__
        # for some reason you can't update a __doc__ on a class
        # http://bugs.python.org/issue12773

        return decorate_klass
652070
def with_meta(class_to_decorate=None, add_init_kwargs=True):
    

    if class_to_decorate is None:
        return functools.partial(with_meta, add_init_kwargs=add_init_kwargs)

    if add_init_kwargs:
        def get_extra_args_function(self):
            return {k: v for k, v in self.get_meta().items() if not k.startswith('_')}

        add_args_to_init_call(class_to_decorate, get_extra_args_function)

    setattr(class_to_decorate, 'get_meta', classmethod(get_meta))

    return class_to_decorate
1113376
private void installMetaClassCreationHandle() {
           try {
               final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle");
               final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor();
                 this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance();
           } catch (final ClassNotFoundException e) {
               this.metaClassCreationHandle = new MetaClassCreationHandle();
           } catch (final Exception e) {
               throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e);
           }
    }
362797
def middleware_class(api=None):
    """"""
    def decorator(middleware_class):
        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_class)
        apply_to_api.http.add_middleware(middleware_class())
        return middleware_class
    return decorator
1135046
function createPythonClass (className, baseClass, body, methods, async = false) {

    const pythonStandardLibraries = {
        'base64': 'base64',
        'hashlib': 'hashlib',
        'math': 'math',
        'json.loads': 'json',
    }

    async = async ? 'async_support.' : ''

    const importFrom = (baseClass == 'Exchange') ?
        ('ccxt.' + async + 'base.exchange') :
        ('ccxt.' + async + baseClass)

    let bodyAsString = body.join ("\n")

    let header = [
        "# -*- coding: utf-8 -*-\n",
        "# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
        "# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code\n",
        'from ' + importFrom + ' import ' + baseClass,
        ... (bodyAsString.match (/basestring/) ? [
            "\n# -----------------------------------------------------------------------------\n",
            "try:",
            "    basestring  # Python 3",
            "except NameError:",
            "    basestring = str  # Python 2",
        ] : [])
    ]

    const libraries = []

    for (let library in pythonStandardLibraries) {
        const regex = new RegExp ("[^\\']" + library + "[^\\'a-zA-Z]")
        if (bodyAsString.match (regex))
            libraries.push ('import ' + pythonStandardLibraries[library])
    }

    const errorImports = []

    for (let error in errors) {
        const regex = new RegExp ("[^\\'\"]" + error + "[^\\'\"]")
        if (bodyAsString.match (regex))
            errorImports.push ('from ccxt.base.errors import ' + error)
    }

    const precisionImports = []

    for (let constant in precisionConstants) {
        if (bodyAsString.indexOf (constant) >= 0) {
            precisionImports.push ('from ccxt.base.decimal_to_precision import ' + constant)
        }
    }

    header = header.concat (libraries, errorImports, precisionImports)

    for (let method of methods) {
        const regex = new RegExp ('self\\.(' + method + ')\\s*\\(', 'g')
        bodyAsString = bodyAsString.replace (regex,
            (match, p1) => ('self.' + unCamelCase (p1) + '('))
    }

    header.push ("\n\nclass " + className + ' (' + baseClass + '):')

    const footer = [
        '', // footer (last empty line)
    ]

    const result = header.join ("\n") + "\n" + bodyAsString + "\n" + footer.join ('\n')
    return result
}
829820
def mock_decorator(*a, **k):
    
    # This is a decorator without parameters, e.g.
    #
    # @login_required
    # def some_view(request):
    #     ...
    #
    if a:
        # This could fail in the instance where a callable argument is passed
        # as a parameter to the decorator!
        if callable(a[0]):
            def wrapper(*args, **kwargs):
                return a[0](*args, **kwargs)
            return wrapper

    # This is a decorator with parameters, e.g.
    #
    # @render_template("index.html")
    # def some_view(request):
    #     ...
    #
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            return function(*args, **kwargs)
        return wrapper
    return real_decorator
357860
def container(dec):
    
    # Credits: http://stackoverflow.com/a/1167248/1798683
    @wraps(dec)
    def meta_decorator(f):
        decorator = dec(f)
        decorator.orig_func = f
        return decorator
    return meta_decorator
221249
def good_classmethod_decorator(decorator):
    """""" 
    def new_decorator(cls, f):
        g = decorator(cls, f)
        g.__name__ = f.__name__
        g.__doc__ = f.__doc__
        g.__dict__.update(f.__dict__)
        return g
        
    new_decorator.__name__ = decorator.__name__
    new_decorator.__doc__ = decorator.__doc__
    new_decorator.__dict__.update(decorator.__dict__)

    return new_decorator
313272
def get_name(cls):
        
        if not hasattr(cls.Meta, 'name'):
            class_name = getattr(cls.get_model(), '__name__', None)
            setattr(
                cls.Meta,
                'name',
                inflection.underscore(class_name) if class_name else None
            )

        return cls.Meta.name
352306
def dir_class(cls):
    
    # Class attributes (including methods).
    for name, value in vars_class(cls).items():
        if isinstance(value, ObjectMethod):
            if value.has_classmethod:
                yield name
        elif isinstance(value, Disabled):
            pass  # Hide this; disabled.
        else:
            yield name
    # Metaclass attributes.
    for name, value in vars_class(type(cls)).items():
        if name == "mro":
            pass  # Hide this; not interesting.
        elif isinstance(value, Disabled):
            pass  # Hide this; disabled.
        else:
            yield name
449087
def decorate(decorator_cls, *args, **kwargs):
    """"""
    global _wrappers

    wrapper_cls = _wrappers.get(decorator_cls, None)
    if wrapper_cls is None:

        class PythonWrapper(decorator_cls):
            pass

        wrapper_cls = PythonWrapper
        wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
        _wrappers[decorator_cls] = wrapper_cls

    def decorator(fn):
        wrapped = wrapper_cls(fn, *args, **kwargs)
        _update_wrapper(wrapped, fn)
        return wrapped

    return decorator
26164
def create_class(self, name: str) -> ConstantClass:
        
        self.append((
            7,
            self.create_utf8(name).index
        ))
        return self.get(self.raw_count - 1)
871873
def create_class(request):
    

    if request.method == 'GET':
        return render(request, 'classes_create.html', {}, help_text=create_class.__doc__)

    if request.method == 'POST':
        if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
            return render_json(request, {
                'error': _('User is not logged in.'),
                'error_type': 'user_unauthorized'
            }, template='classes_create.html', status=401)

        data = json_body(request.body.decode("utf-8"))
        if 'code' in data and Class.objects.filter(code=data['code']).exists():
            return render_json(request, {
                'error': _('A class with this code already exists.'),
                'error_type': 'class_with_code_exists'
            }, template='classes_create.html', status=400)

        if 'name' not in data or not data['name']:
            return render_json(request, {'error': _('Class name is missing.'), 'error_type': 'missing_class_name'},
                               template='classes_create.html', status=400)

        cls = Class(name=data['name'], owner=request.user.userprofile)
        if 'code' in data:
            cls.code = data['code']
        cls.save()
        return render_json(request, cls.to_json(), template='classes_create.html', status=201)
    else:
        return HttpResponseBadRequest("method %s is not allowed".format(request.method))
568278
def decorate_all_methods(decorator):
  
  def decorate_class(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
      if name != "__init__":
        setattr(cls, name, decorator(m))
    return cls
  return decorate_class
1365290
def _is_base_matcher_class_definition(meta, classname, dict_):
        
        if classname != 'BaseMatcher':
            return False
        methods = list(filter(inspect.isfunction, dict_.values()))
        return methods and all(m.__module__ == __name__ for m in methods)