text:
# -*- python -*-
#                           Package   : hpp-corbaserver
# main.py                   Created on: 2019
#                           Author    : Joseph Mirabel
#
#    Copyright (C) 2019 LAAS-CNRS
#

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# Description:
#
#   Produce interface implementations for HPP

"""Produce interface implementations for HPP"""

from __future__ import print_function

from omniidl import idlast, idlvisitor
from omniidl_be.cxx import ast, util, id, types, output, config
from cxx_impl import template

def if_cpp11(then, _else):
    if config.state["C++11"]:
        return then
    else:
        return _else

def __init__(
    hpp_stream,
    hxx_stream,
    cc_stream,
    idl_filename,
    prefix,
    hh_filename,
    hpp_filename,
    hxx_filename,
):
    self.hpp_stream = hpp_stream
    self.hxx_stream = hxx_stream
    self.cc_stream = cc_stream

    self.idl_filename = idl_filename

    self.prefix = prefix
    self.hh_filename = hh_filename
    self.hpp_filename = hpp_filename
    self.hxx_filename = hxx_filename

def makeError(msg, file, line, errtype=Exception):
    import os

    path = os.path.dirname(__file__)
    path = os.path.dirname(path)
    help = "omniidl -p{} -bcxx_impl -u".format(path)
    return errtype(
        "\n{}:{}: {}\nThe help may help:\n{}\n".format(file, line, msg, help)
    )

# Given an IDL name convert it into the template name of the
# implementation class
def impl_tplname(name):
    return name.suffix("Servant").simple(cxx=1)

# Given an IDL name convert it into the corresponding hpp class name
def hpp_scope(name, suffix=""):
    scope = [n.replace("_idl", "") for n in name.scope()] + [
        name.simple(cxx=0),
    ]
    return id.Name(scope)

# Given an IDL name convert it into the corresponding hpp class name
def hpp_name(name, suffix=""):
    scope = [n.replace("_idl", "") for n in name.scope()] + [
        name.simple(cxx=0),
    ]
    return "::".join(scope)

# Given an IDL name convert it into the corresponding hpp servant class id.Name
def hpp_servant_scope(name):
    scope = [n.replace("_idl", "_impl") for n in name.scope()] + [
        name.simple(cxx=0),
    ]
    return id.Name(scope)

# Given an IDL name convert it into the corresponding hpp servant class name
def hpp_servant_name(name, environment=None):
    scope = hpp_servant_scope(name)
    # scope = [ n.replace('_idl', '') for n in name.scope() ] + [ name.simple(cxx=0), ]
    # scope.insert(1, "corbaServer")
    if environment:
        i = 0
        sc = scope.scope()
        esc = environment.scope()
        while i < len(sc) and i < len(esc) and sc[i] == esc[i]:
            i += 1
        scope._scopedName = scope._scopedName[i:]
    return scope.fullyQualify(cxx=1)

def namespaces(name, environment=None):
    scope = hpp_servant_scope(name)
    if environment:
        env = environment.scope()
        assert scope.scope()[: len(env)] == env
        scope = scope.scope()[len(env) :]
    else:
        scope = scope.scope()
    open_ns = "\n\n".join(["namespace {name} {{".format(name=n) for n in scope])
    closens = "\n\n".join(
        ["}} // namespace {name}".format(name=n) for n in reversed(scope)]
    )
    return open_ns, closens

# Main code entrypoint
def run(tree):
    # first thing is to build the interface implementations
    decl = output.StringStream()
    impl = output.StringStream()
    bii = BuildInterfaceImplementations(decl, impl)
    tree.accept(bii)

    object_downcasts_methods = output.StringStream()
    add_object_downcasts = output.StringStream()
    biod = BuildInterfaceObjectDowncasts(object_downcasts_methods, add_object_downcasts)
    tree.accept(biod)

    openns, closens = "", ""
    guard = id.Name([config.state["Basename"]]).guard()

    # Create header file.
    hpp_stream.out(
        template.hpp_file,
        guard_prefix=config.state["GuardPrefix"],
        guard=guard,
        includes=bii.includes,
        idl_hh=prefix + hh_filename,
        file=idl_filename,
        interface_declarations=str(decl),
        open_namespaces=openns,
        close_namespaces=closens,
    )

    # Create definition of templated functions.
    hxx_stream.out(
        template.hxx_file,
        guard_prefix=config.state["GuardPrefix"],
        guard=guard,
        idl_hpp=prefix + hpp_filename,
        file=idl_filename,
        interface_implementations=str(impl),
        open_namespaces=openns,
        close_namespaces=closens,
    )

    # Create other definition files.
    cc_stream.out(
        template.cc_file,
        idl_hxx=prefix + hxx_filename,
        file=idl_filename,
        object_downcasts_methods=object_downcasts_methods,
        add_object_downcasts=add_object_downcasts,
        open_namespaces=openns,
        close_namespaces=closens,
    )

def get_base_class(node, retDepth=False):
    base = node
    depth = 0
    while base.inherits():
        depth += 1
        base = base.inherits()[0]
    if retDepth:
        return base, depth
    else:
        return base

class Builder(idlvisitor.AstVisitor):
    def __init__(self):
        self._modules = {}

    def registerModule(self, m):
        mname = m.identifier()
        if mname.endswith("_idl"):
            mname = mname[:-4]
        self._modules[m.identifier()] = mname
        for comment in m.comments():
            if comment.text().startswith("// ") or comment.text().startswith("///"):
                pass
            elif comment.text().startswith("//->"):
                self._modules[m.identifier()] = comment.text()[4:].strip()

    def toCppNamespace(self, name):
        def module(n):
            if n in self._modules:
                return self._modules[n]
            if n.endswith("_idl"):
                return n[:-4]
            return n

        scope = [module(n) for n in name.scope()] + [
            name.simple(cxx=0),
        ]
        return id.Name(scope)

    # type conversions
    def argConversion(self, name, _type, _in, _out, param):
        assert _in or _out
        tmp = "_" + name
        in_conv_str = None
        out_conv_str = None

        if _type.string():
            if _in:
                in_conv_str = "std::string {} ({});".format(tmp, name)
            else:
                in_conv_str = "std::string {};".format(tmp)
            if _out:
                out_conv_str = "{} = hpp::corbaServer::c_str ({});".format(name, tmp)
            return tmp, in_conv_str, out_conv_str
        elif _type.typedef():
            if _type.type().name() in ("size_t", "size_type", "value_type"):
                return name, "", out_conv_str
            elif _type.type().name() == "floatSeq":
                if _in:
                    in_conv_str = "hpp::core::vector_t {} = hpp::corbaServer::floatSeqToVector ({});".format(
                        tmp, name
                    )
                    if _out:
                        out_conv_str = (
                            "hpp::corbaServer::vectorToFloatSeq ({}, {});".format(
                                tmp, name
                            )
                        )
                else:  # !_in => _out
                    assert _out
                    in_conv_str = "hpp::core::vector_t {};".format(tmp, name)
                    out_conv_str = (
                        "{} = hpp::corbaServer::vectorToFloatSeq ({});".format(
                            name, tmp
                        )
                    )
                return tmp, in_conv_str, out_conv_str
            elif _type.type().name() == "floatSeqSeq":
                if _in:
                    in_conv_str = "hpp::core::matrix_t {} = hpp::corbaServer::floatSeqSeqToMatrix ({});".format(
                        tmp, name
                    )
                    if _out:
                        out_conv_str = "/* not implemented. See vectorToFloatSeq */ hpp::corbaServer::matrixToFloatSeqSeq ({}, {});".format(
                            tmp, name
                        )
                else:  # !_in => _out
                    in_conv_str = "hpp::core::matrix_t {};".format(tmp, name)
                    assert _out
                    out_conv_str = (
                        "{} = hpp::corbaServer::matrixToFloatSeqSeq ({});".format(
                            name, tmp
                        )
                    )
                return tmp, in_conv_str, out_conv_str
            elif _type.type().name() == "Transform_":
                if _out:
                    raise makeError(
                        "out Transform_ is currently not supported",
                        param.file(),
                        param.line(),
                    )
                return (
                    tmp,
                    "hpp::core::Transform3f {} = hpp::corbaServer::toTransform3f ({});".format(
                        tmp, name
                    ),
                    out_conv_str,
                )
            elif _type.type().name() == "TransformSeq":
                if _out:
                    raise makeError(
                        "out TransformSeq is currently not supported",
                        param.file(),
                        param.line(),
                    )
                return (
                    tmp,
                    "std::vector<hpp::core::Transform3f> {} = hpp::corbaServer::toTransform3f ({});".format(
                        tmp, name
                    ),
                    out_conv_str,
                )
            elif _type.type().name() == "Names_t":
                in_conv_str = "typedef std::vector<std::string> strings_t;"
                if _in:
                    in_conv_str += "strings_t {} = hpp::corbaServer::toStrings<strings_t> ({});".format(
                        tmp, name
                    )
                else:
                    in_conv_str += "strings_t {};".format(tmp, name)
                if _out:
                    out_conv_str = "hpp::corbaServer::toNames_t ({var}.begin(), {var}.end());".format(
                        var=tmp
                    )
                return tmp, in_conv_str, out_conv_str
            elif _type.type().name() == "ComparisonTypes_t":
                if _in:
                    in_conv_str = "hpp::constraints::ComparisonTypes_t {} = hpp::corbaServer::convertComparison ({});".format(
                        tmp, name
                    )
                    if _out:
                        raise ValueError(
                            "inout ComparisonTypes_t is not implemented. See floatSeq convertion for an example."
                        )
                else:  # !_in => _out
                    assert _out
                    raise ValueError(
                        "inout ComparisonTypes_t is not implemented. See floatSeq convertion for an example."
                    )
                return tmp, in_conv_str, out_conv_str
            elif _type.type().name() == "RelativeMotionMatrix":
                if _in:
                    in_conv_str = "hpp::core::RelativeMotion::matrix_type {} = hpp::corbaServer::intSeqSeqToMatrix ({}).cast<hpp::core::RelativeMotion::RelativeMotionType>();".format(
                        tmp, name
                    )
                    if _out:
                        out_conv_str = "/* not implemented. See vectorToFloatSeq */ hpp::corbaServer::matrixToIntSeqSeq ({}.cast<int>(), {});".format(
                            tmp, name
                        )
                else:  # !_in => _out
                    in_conv_str = "hpp::core::RelativeMotion::matrix_type {}".format(
                        tmp
                    )
                    assert _out
                    out_conv_str = "{} = hpp::corbaServer::matrixToIntSeqSeq ({}.cast<int>());".format(
                        name, tmp
                    )
                return tmp, in_conv_str, out_conv_str
            print("typedef", _type.type().name())
            return name, "", out_conv_str
        elif _type.is_basic_data_types():
            return name, "", out_conv_str
        elif _type.objref():
            if _out:
                raise makeError(
                    "out objects is currently not supported", param.file(), param.line()
                )
            conv = "{typeptr} {tmp} = ::hpp::corbaServer::reference_to_object<{type}>(server_, {name});".format(
                type=self.toCppNamespace(
                    id.Name(_type.type().scopedName())
                ).fullyQualify(cxx=1),
                typeptr=self.toCppNamespace(
                    id.Name(_type.type().scopedName()).suffix("Ptr_t")
                ).fullyQualify(cxx=1),
                servanttype=hpp_servant_name(id.Name(_type.type().scopedName())),
                tmp=tmp,
                name=name,
            )
            return tmp, conv, out_conv_str
        print(_type.type(), _type.kind())
        return name, "", out_conv_str

    def retConversion(self, _type):
        """
        Returns two values:
        - storing: will be used as "${storing} (${hpp_method_call})."
        - converting: will be copied as such after the line above.
        """
        if _type.void():
            return "", ""
        if _type.is_basic_data_types():
            return "{} __return__".format(_type.op(types.RET)), "return __return__;"
        if _type.string():
            return "char* __return__ = ::hpp::corbaServer::c_str", "return __return__;"
        if _type.typedef():
            if _type.type().name() in ("size_t", "size_type", "value_type"):
                return "{} __return__".format(_type.op(types.RET)), "return __return__;"
            elif _type.type().name() == "floatSeq":
                return (
                    "{} __return__ = hpp::corbaServer::vectorToFloatSeq".format(
                        _type.op(types.RET)
                    ),
                    "return __return__;",
                )
            elif _type.type().name() == "floatSeqSeq":
                return (
                    "{} __return__ = hpp::corbaServer::matrixToFloatSeqSeq".format(
                        _type.op(types.RET)
                    ),
                    "return __return__;",
                )
            elif _type.type().name() == "Transform_":
                return (
                    "hpp::core::Transform3f __return__",
                    "return hpp::corbaServer::toHppTransform (__return__);",
                )
            elif _type.type().name() == "Names_t":
                return (
                    "{} __return__".format(
                        if_cpp11("auto", "std::vector<std::string>")
                    ),
                    "return hpp::corbaServer::toNames_t (__return__);",
                )
            elif _type.type().name() == "ComparisonTypes_t":
                return (
                    "hpp::constraints::ComparisonTypes_t __return__",
                    "return hpp::corbaServer::convertComparison (__return__);",
                )
            else:
                unaliased = _type.deref()
                if unaliased.sequence():
                    innerType = types.Type(unaliased.type().seqType())
                    if innerType.objref():
                        if isinstance(innerType.type().decl(), idlast.Forward):
                            base = get_base_class(innerType.type().decl().fullDecl())
                        else:
                            base = get_base_class(innerType.type().decl())
                        return (
                            "{outType}* __return__ = hpp::corbaServer::vectorToSeqServant<{outType},{innerBaseType},{innerType}>(server_)".format(
                                innerBaseType=hpp_servant_name(
                                    id.Name(base.scopedName())
                                ),
                                innerType=hpp_servant_name(
                                    id.Name(innerType.type().scopedName())
                                ),
                                outType=id.Name(_type.type().scopedName()).fullyQualify(
                                    cxx=1
                                ),
                            ),
                            "return __return__;",
                        )
                    else:
                        print("Unhandled sequence of", innerType.type())
                else:
                    print("Unhandled type", _type.type().name())
            return "ThisTypeCouldNotBeDeduced __return__", "return __return__;"
        if _type.objref():
            if isinstance(_type.type().decl(), idlast.Forward):
                base = get_base_class(_type.type().decl().fullDecl())
            else:
                base = get_base_class(_type.type().decl())
            store = "{type} __return__".format(
                type=self.toCppNamespace(
                    id.Name(_type.type().scopedName()).suffix("Ptr_t")
                ).fullyQualify(cxx=1)
            )
            conv = "return ::hpp::corbaServer::makeServantDownCast<{basetype},{type}>(server_, __return__)._retn();".format(
                type=hpp_servant_name(id.Name(_type.type().scopedName())),
                basetype=hpp_servant_name(id.Name(base.scopedName())),
            )
            return store, conv
        print(_type.type(), _type.kind())
        return "", ""

    # modules can contain interfaces
    def visitModule(self, node):
        self.registerModule(node)
        for n in node.definitions():
            n.accept(self)

# Build the interface implementations (hpp, hxx)
#
class BuildInterfaceImplementations(Builder):
    def __init__(self, decl, impl):
        # super(BuildInterfaceImplementations, self).__init__()
        Builder.__init__(self)
        self.interface_declarations = decl
        self.interface_implementations = impl
        self.includes = ""

        self.storages = {}

    # Tree walking code
    def visitAST(self, node):
        for n in node.declarations():
            if ast.shouldGenerateCodeForDecl(n):
                for c in n.comments():
                    if len(c.text()) > 2 and c.text()[2] == "*":
                        self.includes += c.text()[3:].strip() + "\n"
                n.accept(self)

    def visitStruct(self, node):
        if not node.identifier().endswith("Storage"):
            return
        if not node.members():
            return

        class Storage(object):
            pass

        storage = Storage()

        storage.members = []
        for m in node.members():
            type = self.toCppNamespace(id.Name(m.memberType().scopedName())).suffix(
                "Ptr_t"
            )
            for d in m.declarators():
                storage.members.append((type, d.identifier()))

        storage.sc = hpp_servant_scope(id.Name(node.scopedName()))

        sc = node.scopedName()
        sc[-1] = sc[-1][:-7]
        storage.class_sc = hpp_servant_scope(id.Name(sc))

        st = output.StringStream()
        st.out(
            template.storage_decl,
            storage_class_name=storage.sc.simple(),
            hpp_base_class=storage.class_sc.simple(),
            storage_attributes="\n".join(
                [t.fullyQualify() + " " + n for t, n in storage.members]
            ),
            storage_constr_attr_decl=", ".join(
                [t.fullyQualify() + " _" + n for t, n in storage.members]
            )
            + ", ",
            storage_constr_attr_defs=", "
            + ", ".join([n + " (_" + n + ")" for t, n in storage.members]),
            storage_attr_call=", ".join([n for t, n in storage.members]) + ", ",
        )
        storage.decl = str(st)

        self.storages[storage.class_sc.fullyQualify(cxx=0)] = storage

    # interfaces cannot be further nested
    def visitInterface(self, node):
        scopedName = id.Name(node.scopedName())
        openns, closens = namespaces(scopedName)

        impl_name = scopedName.simple(cxx=1)
        impl_tpl_name = impl_tplname(scopedName)
        cxx_fqname = scopedName.fullyQualify()
        hpp_class = self.toCppNamespace(scopedName).fullyQualify(cxx=1)

        fqname = scopedName.fullyQualify(cxx=0)

        is_base_class = not bool(node.inherits())
        # ptr_t = self.toCppNamespace (scopedName.suffix("Ptr_t")).fullyQualify(cxx=1)
        wkptr_t = "hpp::weak_ptr<{}>".format(
            self.toCppNamespace(scopedName).fullyQualify(cxx=1)
        )
        if is_base_class:
            key = hpp_servant_name(scopedName)
            impl_base_name = "hpp::corbaServer::ServantBase"
            if key in self.storages:
                st = self.storages[key]
                # declare storage
                self.interface_declarations.out(st.decl)
                storage = st.sc.simple() + "< " + wkptr_t + " >"
            else:
                storage = wkptr_t
            hpp_base_class = None
        else:
            baseScopedName = id.Name(node.inherits()[0].scopedName())
            hpp_base_class = self.toCppNamespace(baseScopedName).fullyQualify(cxx=1)
            key = hpp_servant_name(baseScopedName)
            impl_base_name = hpp_servant_name(baseScopedName.suffix("Servant"))
            if key in self.storages:
                st = self.storages[key]
                storage = st.sc.simple() + "< " + wkptr_t + " >"
                self.storages[fqname] = st
            else:
                storage = wkptr_t

        # build methods corresponding to attributes, operations etc.
        # attributes[] and operations[] will contain lists of function
        # signatures eg
        #   [ char *echoString(const char *mesg) ]
        attributes = []
        operations = []

        allCallables = node.callables()

        # declarations contains a list of in-class decl signatures
        # implementations contains a list of out of line impl signatures
        # (typically differ by classname::)
        declarations = output.StringStream()
        implementations = output.StringStream()

        for c in allCallables:
            comments = c.comments()
            hpp_opname = None
            comments_impl = []
            for comment in comments:
                if comment.text().startswith("// ") or comment.text().startswith("///"):
                    # Skip this comment
                    pass
                elif comment.text().startswith("//*"):
                    if not comments_impl:
                        comments_impl.append(
                            " // generated from {}:{}\n".format(
                                node.file(), node.line()
                            )
                        )
                    comments_impl.append(comment.text()[3:])
                elif comment.text().startswith("//->"):
                    if hpp_opname is not None:
                        raise makeError(
                            "Function was already renamed",
                            comment.file(),
                            comment.line(),
                        )
                    hpp_opname = comment.text()[4:].strip()

            if isinstance(c, idlast.Attribute):
                attrType = types.Type(c.attrType())
                d_attrType = attrType.deref()

                for i in c.identifiers():
                    attribname = id.mapID(i)
                    returnType = attrType.op(types.RET)
                    inType = attrType.op(types.IN)
                    attributes.append(returnType + " " + attribname + "()")
                    # need a set method if not a readonly attribute
                    if not c.readonly():
                        declarations.out(
                            template.operation_decl_code,
                            return_type="void",
                            opname=attribname,
                            arg_defs=inType + " _" + attribname,
                        )

                        tmpVar, in_conv, out_conv = self.argConversion(
                            "_" + attribname, attrType, True, False, c
                        )
                        implementations.out(
                            template.operation_impl_code,
                            return_type="void",
                            impl_tpl_name=impl_tpl_name,
                            opname=attribname,
                            hpp_opname=hpp_opname if hpp_opname else attribname,
                            arg_defs=inType + " _" + attribname,
                            in_conversions=in_conv if in_conv else "",
                            out_conversions=out_conv if out_conv else "",
                            store_return="",
                            do_return="",
                            arg_calls=tmpVar,
                        )

                    declarations.out(
                        template.operation_decl_code,
                        return_type=returnType,
                        opname=attribname,
                        arg_defs="",
                    )

                    store_return, do_return = self.retConversion(attrType)
                    implementations.out(
                        template.operation_impl_code,
                        return_type=returnType,
                        impl_tpl_name=impl_tpl_name,
                        opname=attribname,
                        hpp_opname=hpp_opname if hpp_opname else attribname,
                        arg_defs="",
                        in_conversions="",
                        out_conversions="",
                        store_return=store_return,
                        do_return=do_return,
                        arg_calls="",
                    )
            elif isinstance(c, idlast.Operation):
                params = []
                paramNames = []
                in_conversions = []
                out_conversions = []
                for p in c.parameters():
                    paramType = types.Type(p.paramType())
                    cxx_type = paramType.op(types.direction(p), use_out=0)

                    argname = id.mapID(p.identifier())
                    if not comments_impl:
                        tmpVar, in_conv, out_conv = self.argConversion(
                            argname, paramType, p.is_in(), p.is_out(), p
                        )
                        if in_conv:
                            in_conversions.append(in_conv)
                        if out_conv:
                            out_conversions.append(out_conv)
                    else:
                        tmpVar = argname

                    params.append(cxx_type + " " + argname)
                    paramNames.append(tmpVar)

                # deal with possible "context"
                if c.contexts() != []:
                    params.append("CORBA::Context_ptr _ctxt")

                store_return, do_return = self.retConversion(types.Type(c.returnType()))
                return_type = types.Type(c.returnType()).op(types.RET)

                error_type = "::hpp::Error"
                if len(c.raises()) > 0:
                    error_type = "::" + "::".join(c.raises()[0].scopedName())

                opname = id.mapID(c.identifier())
                arguments = ", ".join(params)
                argumentsCall = ", ".join(paramNames)
                args = opname + "(" + arguments + ")"

                declarations.out(
                    template.operation_decl_code,
                    return_type=return_type,
                    opname=opname,
                    arg_defs=arguments,
                )

                if comments_impl:
                    implementations.out(
                        template.provided_operation_impl_code,
                        return_type=return_type,
                        impl_tpl_name=impl_tpl_name,
                        opname=opname,
                        error_type=error_type,
                        implementation="".join(comments_impl),
                        arg_defs=arguments,
                    )
                elif opname in template.predefined_operations_impl_code:
                    # assert not c.parameters(), "Interface operation str should not have arguments"
                    implementations.out(
                        template.predefined_operations_impl_code[opname],
                        return_type=return_type,
                        impl_tpl_name=impl_tpl_name,
                        opname=opname,
                        error_type=error_type,
                        conversions="\n  ".join(in_conversions),
                        arg_defs=arguments,
                        store_return=store_return,
                        do_return=do_return,
                        arg_calls=argumentsCall,
                    )
                else:
                    implementations.out(
                        template.operation_impl_code,
                        return_type=return_type,
                        impl_tpl_name=impl_tpl_name,
                        opname=opname,
                        hpp_opname=hpp_opname if hpp_opname is not None else opname,
                        error_type=error_type,
                        in_conversions="\n  ".join(in_conversions),
                        out_conversions="\n  ".join(out_conversions),
                        arg_defs=arguments,
                        store_return=store_return,
                        do_return=do_return,
                        arg_calls=argumentsCall,
                    )

            else:
                util.fatalError("Internal error generating interface member")
                raise AssertionError("No code for interface member: " + repr(c))

        openns, closens = namespaces(scopedName)

        # Output the _i class definition definition
        self.interface_declarations.out(
            template.base_interface_def
            if is_base_class
            else template.inherited_interface_def,
            fq_name=fqname,
            impl_tpl_name=impl_tpl_name,
            impl_base_name=impl_base_name,
            operations=str(declarations),
            impl_name=impl_name,
            fq_POA_name="POA_" + cxx_fqname,
            hpp_class=hpp_class,
            hpp_base_class=hpp_base_class,
            storage=storage,
            open_namespaces=openns,
            close_namespaces=closens,
        )

        self.interface_implementations.out(
            template.base_interface_code
            if is_base_class
            else template.inherited_interface_code,
            fqname=fqname,
            impl_name=impl_name,
            impl_tpl_name=impl_tpl_name,
            impl_base_name=impl_base_name,
            hpp_class=hpp_class,
            operations=str(implementations),
            open_namespaces=openns,
            close_namespaces=closens,
        )

# Build the interface object downcasts (cc)
#
class BuildInterfaceObjectDowncasts(Builder):
    def __init__(self, methods, adders):
        # super(BuildInterfaceObjectDowncasts, self).__init__()
        Builder.__init__(self)
        self.methods = methods
        self.adders = adders

    # Tree walking code
    def visitAST(self, node):
        for n in node.declarations():
            if ast.shouldGenerateCodeForDecl(n):
                n.accept(self)

    # interfaces cannot be further nested
    def visitInterface(self, node):
        idlScopedName = id.Name(node.scopedName())
        servantScope = hpp_servant_scope(idlScopedName)
        scopedName = hpp_servant_name(idlScopedName)

        base, depth = get_base_class(node, retDepth=True)
        baseScopedName = hpp_servant_name(id.Name(base.scopedName()), servantScope)

        if depth == 0:
            self.methods.out(
                template.definition_object_downcast,
                servant_class=servantScope.fullyQualify(),
            )

        openns, closens = namespaces(servantScope)
        self.adders.out(
            template.definition_add_object_downcast,
            # class_name = scopedName,
            # base_class_name = baseScopedName,
            class_name=idlScopedName.simple(),
            base_class_name=baseScopedName,
            open_namespaces=openns,
            close_namespaces=closens,
            depth=depth,
        )


text:
'use strict';

angular.module('myApp.usersView')
.controller('UsersController', ['$scope', 'UserService', function($scope, UserService) {
console.log("uv");
var self = this;

self.user = { id:null, login:"", password: "", repassword: "", version: null};
self.users = [];

self.submit = submit;
self.edit = edit;
self.remove = remove;
self.reset = reset;

    fetchAllUsers();

    function fetchAllUsers(){
        UserService.fetchAllUsers()
            .then(
            function(d) {
                self.users = d;
            },
            function(errResponse){
                console.error('Error while fetching Users');
            }
        );
    }

    function createContact(user){
        UserService.createUser(user)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while creating Contact');
            }
        );
    }

    function updateContact(user){
        UserService.updateUser(user)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while updating Contact');
            }
        );
    }

    function deleteContact(id){
        UserService.deleteContact(id)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while deleting Contact');
            }
        );
    }

    function submit() {
        if(self.user.id===null){
            console.log('Saving New Contact', self.user);
            createContact(self.user);
        }else{
            console.log('Contact updated with id ', self.user.id);
            updateContact(self.user, self.user.id);
        }
        reset();
    }

    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.users.length; i++){
            if(self.users[i].id === id) {
                self.user = angular.copy(self.users[i]);
                break;
            }
        }
    }

    function remove(id){
        console.log('id to be deleted', id);
        if(self.user.id === id) {//clean form if the user to be deleted is shown there.
            reset();
        }
        deleteContact(id);
    }

    function reset(){
        self.user={ id:null, login:"", password:"", repassword:"", version: null };
        $scope.myForm.$setPristine(); //reset Form
    }

}]);

redpajama_set_name: RedPajamaGithub


text:
package proto

import (
	context "context"
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	grpc "google.golang.org/grpc"
	codes "google.golang.org/grpc/codes"
	status "google.golang.org/grpc/status"
	emptypb "google.golang.org/protobuf/types/known/emptypb"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package

// DispatchUserCommandRequest is passed when dispatching
type DispatchUserCommandRequest struct {
	Name                 string   `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	Payload              []byte   `protobuf:"bytes,2,opt,name=payload,proto3" json:"payload,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int64    `json:"-"`
}

func (m *DispatchUserCommandRequest) Reset()         { *m = DispatchUserCommandRequest{} }
func (m *DispatchUserCommandRequest) String() string { return proto.CompactTextString(m) }
func (*DispatchUserCommandRequest) ProtoMessage()    {}
func (*DispatchUserCommandRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_116e343673f7ffaf, []int{0}
}

func (m *DispatchUserCommandRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_DispatchUserCommandRequest.Unmarshal(m, b)
}
func (m *DispatchUserCommandRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_DispatchUserCommandRequest.Marshal(b, m, deterministic)
}
func (m *DispatchUserCommandRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_DispatchUserCommandRequest.Merge(m, src)
}
func (m *DispatchUserCommandRequest) XXX_Size() int {
	return xxx_messageInfo_DispatchUserCommandRequest.Size(m)
}
func (m *DispatchUserCommandRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_DispatchUserCommandRequest.DiscardUnknown(m)
}

var xxx_messageInfo_DispatchUserCommandRequest proto.InternalMessageInfo

func (m *DispatchUserCommandRequest) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

func (m *DispatchUserCommandRequest) GetPayload() []byte {
	if m != nil {
		return m.Payload
	}
	return nil
}

// User object
type User struct {
	Id                   string   `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
	Email                string   `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"`
	FacebookId           string   `protobuf:"bytes,3,opt,name=facebookId,proto3" json:"facebookId,omitempty"`
	GoogleId             string   `protobuf:"bytes,4,opt,name=googleId,proto3" json:"googleId,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int64    `json:"-"`
}

func (m *User) Reset()         { *m = User{} }
func (m *User) String() string { return proto.CompactTextString(m) }
func (*User) ProtoMessage()    {}
func (*User) Descriptor() ([]byte, []int) {
	return fileDescriptor_116e343673f7ffaf, []int{1}
}

func (m *User) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_User.Unmarshal(m, b)
}
func (m *User) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_User.Marshal(b, m, deterministic)
}
func (m *User) XXX_Merge(src proto.Message) {
	xxx_messageInfo_User.Merge(m, src)
}
func (m *User) XXX_Size() int {
	return xxx_messageInfo_User.Size(m)
}
func (m *User) XXX_DiscardUnknown() {
	xxx_messageInfo_User.DiscardUnknown(m)
}

var xxx_messageInfo_User proto.InternalMessageInfo

func (m *User) GetId() string {
	if m != nil {
		return m.Id
	}
	return ""
}

func (m *User) GetEmail() string {
	if m != nil {
		return m.Email
	}
	return ""
}

func (m *User) GetFacebookId() string {
	if m != nil {
		return m.FacebookId
	}
	return ""
}

func (m *User) GetGoogleId() string {
	if m != nil {
		return m.GoogleId
	}
	return ""
}

// GetUserRequest is a request data to read user
type GetUserRequest struct {
	Id                   string   `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int64    `json:"-"`
}

func (m *GetUserRequest) Reset()         { *m = GetUserRequest{} }
func (m *GetUserRequest) String() string { return proto.CompactTextString(m) }
func (*GetUserRequest) ProtoMessage()    {}
func (*GetUserRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_116e343673f7ffaf, []int{2}
}

func (m *GetUserRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_GetUserRequest.Unmarshal(m, b)
}
func (m *GetUserRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_GetUserRequest.Marshal(b, m, deterministic)
}
func (m *GetUserRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_GetUserRequest.Merge(m, src)
}
func (m *GetUserRequest) XXX_Size() int {
	return xxx_messageInfo_GetUserRequest.Size(m)
}
func (m *GetUserRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_GetUserRequest.DiscardUnknown(m)
}

var xxx_messageInfo_GetUserRequest proto.InternalMessageInfo

func (m *GetUserRequest) GetId() string {
	if m != nil {
		return m.Id
	}
	return ""
}

// ListUserRequest is a request data to read all user for a given page
type ListUserRequest struct {
	Page                 int64    `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"`
	Limit                int64    `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int64    `json:"-"`
}

func (m *ListUserRequest) Reset()         { *m = ListUserRequest{} }
func (m *ListUserRequest) String() string { return proto.CompactTextString(m) }
func (*ListUserRequest) ProtoMessage()    {}
func (*ListUserRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_116e343673f7ffaf, []int{3}
}

func (m *ListUserRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ListUserRequest.Unmarshal(m, b)
}
func (m *ListUserRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ListUserRequest.Marshal(b, m, deterministic)
}
func (m *ListUserRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ListUserRequest.Merge(m, src)
}
func (m *ListUserRequest) XXX_Size() int {
	return xxx_messageInfo_ListUserRequest.Size(m)
}
func (m *ListUserRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_ListUserRequest.DiscardUnknown(m)
}

var xxx_messageInfo_ListUserRequest proto.InternalMessageInfo

func (m *ListUserRequest) GetPage() int64 {
	if m != nil {
		return m.Page
	}
	return 0
}

func (m *ListUserRequest) GetLimit() int64 {
	if m != nil {
		return m.Limit
	}
	return 0
}

// ListUserResponse list of all users
type ListUserResponse struct {
	Users                []*User  `protobuf:"bytes,1,rep,name=users,proto3" json:"users,omitempty"`
	Page                 int64    `protobuf:"varint,2,opt,name=page,proto3" json:"page,omitempty"`
	Limit                int64    `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"`
	Total                int64    `protobuf:"varint,4,opt,name=total,proto3" json:"total,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int64    `json:"-"`
}

func (m *ListUserResponse) Reset()         { *m = ListUserResponse{} }
func (m *ListUserResponse) String() string { return proto.CompactTextString(m) }
func (*ListUserResponse) ProtoMessage()    {}
func (*ListUserResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_116e343673f7ffaf, []int{4}
}

func (m *ListUserResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ListUserResponse.Unmarshal(m, b)
}
func (m *ListUserResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ListUserResponse.Marshal(b, m, deterministic)
}
func (m *ListUserResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ListUserResponse.Merge(m, src)
}
func (m *ListUserResponse) XXX_Size() int {
	return xxx_messageInfo_ListUserResponse.Size(m)
}
func (m *ListUserResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_ListUserResponse.DiscardUnknown(m)
}

var xxx_messageInfo_ListUserResponse proto.InternalMessageInfo

func (m *ListUserResponse) GetUsers() []*User {
	if m != nil {
		return m.Users
	}
	return nil
}

func (m *ListUserResponse) GetPage() int64 {
	if m != nil {
		return m.Page
	}
	return 0
}

func (m *ListUserResponse) GetLimit() int64 {
	if m != nil {
		return m.Limit
	}
	return 0
}

func (m *ListUserResponse) GetTotal() int64 {
	if m != nil {
		return m.Total
	}
	return 0
}

func init() {
	proto.RegisterType((*DispatchUserCommandRequest)(nil), "proto.DispatchUserCommandRequest")
	proto.RegisterType((*User)(nil), "proto.User")
	proto.RegisterType((*GetUserRequest)(nil), "proto.GetUserRequest")
	proto.RegisterType((*ListUserRequest)(nil), "proto.ListUserRequest")
	proto.RegisterType((*ListUserResponse)(nil), "proto.ListUserResponse")
}

func init() {
	proto.RegisterFile("user.proto", fileDescriptor_116e343673f7ffaf)
}

var fileDescriptor_116e343673f7ffaf = []byte{
	// 384 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x51, 0x41, 0xcf, 0xd2, 0x40,
	0x10, 0x4d, 0x4b, 0x2b, 0x76, 0x30, 0x68, 0x46, 0xc5, 0xa6, 0x24, 0xa6, 0xf4, 0x44, 0x4c, 0x2c,
	0x09, 0x1e, 0xf5, 0x84, 0x1a, 0x83, 0xf1, 0x40, 0x6a, 0xfc, 0x01, 0xdb, 0x76, 0x29, 0x1b, 0x5b,
	0x76, 0xed, 0x6e, 0x4d, 0xf8, 0x8f, 0xfe, 0x28, 0xb3, 0xbb, 0x2d, 0x02, 0xf2, 0x9d, 0x76, 0xde,
	0xcc, 0xdb, 0x79, 0x33, 0x6f, 0x00, 0x3a, 0x49, 0xdb, 0x54, 0xb4, 0x5c, 0x71, 0xf4, 0xcd, 0x13,
	0xcd, 0x2b, 0xce, 0xab, 0x9a, 0xae, 0x0c, 0xca, 0xbb, 0xfd, 0x8a, 0x36, 0x42, 0x9d, 0x2c, 0x27,
	0xf9, 0x0a, 0xd1, 0x27, 0x26, 0x05, 0x51, 0xc5, 0xe1, 0x87, 0xa4, 0xed, 0x47, 0xde, 0x34, 0xe4,
	0x58, 0x66, 0xf4, 0x57, 0x47, 0xa5, 0x42, 0x04, 0xef, 0x48, 0x1a, 0x1a, 0x3a, 0xb1, 0xb3, 0x0c,
	0x32, 0x13, 0x63, 0x08, 0x63, 0x41, 0x4e, 0x35, 0x27, 0x65, 0xe8, 0xc6, 0xce, 0xf2, 0x49, 0x36,
	0xc0, 0xe4, 0x00, 0x9e, 0xee, 0x81, 0x53, 0x70, 0x59, 0xd9, 0xff, 0x71, 0x59, 0x89, 0x2f, 0xc0,
	0xa7, 0x0d, 0x61, 0xb5, 0xe1, 0x07, 0x99, 0x05, 0xf8, 0x1a, 0x60, 0x4f, 0x0a, 0x9a, 0x73, 0xfe,
	0x73, 0x5b, 0x86, 0x23, 0x53, 0xba, 0xc8, 0x60, 0x04, 0x8f, 0xed, 0xe0, 0xdb, 0x32, 0xf4, 0x4c,
	0xf5, 0x8c, 0x93, 0x18, 0xa6, 0x5f, 0xa8, 0xd2, 0x62, 0xc3, 0xa4, 0x37, 0x9a, 0xc9, 0x7b, 0x78,
	0xfa, 0x8d, 0xc9, 0x2b, 0x0a, 0x82, 0x27, 0x48, 0x65, 0x97, 0xf1, 0x33, 0x13, 0xeb, 0xd1, 0x6a,
	0xd6, 0x30, 0x65, 0x46, 0xf3, 0x33, 0x0b, 0x92, 0x0e, 0x9e, 0xfd, 0xfb, 0x2c, 0x05, 0x3f, 0x4a,
	0x8a, 0x0b, 0xf0, 0xb5, 0xb5, 0x32, 0x74, 0xe2, 0xd1, 0x72, 0xb2, 0x9e, 0x58, 0xff, 0x52, 0xc3,
	0xb1, 0x95, 0xb3, 0x80, 0x7b, 0x4f, 0x60, 0x74, 0x21, 0xa0, 0xb3, 0x8a, 0x2b, 0x52, 0x9b, 0xc5,
	0xfc, 0xcc, 0x82, 0xf5, 0x1f, 0x07, 0x26, 0xba, 0xdf, 0x77, 0xda, 0xfe, 0x66, 0x05, 0xc5, 0x1d,
	0x3c, 0xbf, 0x73, 0x1b, 0x5c, 0xf4, 0xd2, 0x0f, 0xdf, 0x2d, 0x9a, 0xa5, 0xd6, 0xaa, 0x74, 0xb8,
	0x79, 0xfa, 0x59, 0xdf, 0x1c, 0xdf, 0xc2, 0xb8, 0xf7, 0x0d, 0x5f, 0xf6, 0x5d, 0xae, 0x7d, 0x8c,
	0x2e, 0xf7, 0xc2, 0x0f, 0x10, 0x0c, 0x3e, 0x48, 0x9c, 0xf5, 0x95, 0x1b, 0x5b, 0xa3, 0x57, 0xff,
	0xe5, 0xad, 0x63, 0x9b, 0x37, 0x30, 0xaf, 0x38, 0x11, 0x2c, 0xe7, 0xac, 0xa6, 0xad, 0xa8, 0x89,
	0xa2, 0x69, 0xd5, 0x8a, 0xc2, 0xf2, 0x37, 0x81, 0x26, 0xef, 0x74, 0xb8, 0x73, 0xf2, 0x47, 0x26,
	0xf7, 0xee, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1f, 0x3e, 0xc4, 0x2b, 0xbf, 0x02, 0x00, 0x00,
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6

// UserServiceClient is the client API for UserService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type UserServiceClient interface {
	DispatchUserCommand(ctx context.Context, in *DispatchUserCommandRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
	GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*User, error)
	ListUsers(ctx context.Context, in *ListUserRequest, opts ...grpc.CallOption) (*ListUserResponse, error)
}

type userServiceClient struct {
	cc grpc.ClientConnInterface
}

func NewUserServiceClient(cc grpc.ClientConnInterface) UserServiceClient {
	return &userServiceClient{cc}
}

func (c *userServiceClient) DispatchUserCommand(ctx context.Context, in *DispatchUserCommandRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
	out := new(emptypb.Empty)
	err := c.cc.Invoke(ctx, "/proto.UserService/DispatchUserCommand", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *userServiceClient) GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*User, error) {
	out := new(User)
	err := c.cc.Invoke(ctx, "/proto.UserService/GetUser", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *userServiceClient) ListUsers(ctx context.Context, in *ListUserRequest, opts ...grpc.CallOption) (*ListUserResponse, error) {
	out := new(ListUserResponse)
	err := c.cc.Invoke(ctx, "/proto.UserService/ListUsers", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// UserServiceServer is the server API for UserService service.
type UserServiceServer interface {
	DispatchUserCommand(context.Context, *DispatchUserCommandRequest) (*emptypb.Empty, error)
	GetUser(context.Context, *GetUserRequest) (*User, error)
	ListUsers(context.Context, *ListUserRequest) (*ListUserResponse, error)
}

// UnimplementedUserServiceServer can be embedded to have forward compatible implementations.
type UnimplementedUserServiceServer struct {
}

func (*UnimplementedUserServiceServer) DispatchUserCommand(ctx context.Context, req *DispatchUserCommandRequest) (*emptypb.Empty, error) {
	return nil, status.Errorf(codes.Unimplemented, "method DispatchUserCommand not implemented")
}
func (*UnimplementedUserServiceServer) GetUser(ctx context.Context, req *GetUserRequest) (*User, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GetUser not implemented")
}
func (*UnimplementedUserServiceServer) ListUsers(ctx context.Context, req *ListUserRequest) (*ListUserResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method ListUsers not implemented")
}

func RegisterUserServiceServer(s *grpc.Server, srv UserServiceServer) {
	s.RegisterService(&_UserService_serviceDesc, srv)
}

func _UserService_DispatchUserCommand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(DispatchUserCommandRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(UserServiceServer).DispatchUserCommand(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/proto.UserService/DispatchUserCommand",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(UserServiceServer).DispatchUserCommand(ctx, req.(*DispatchUserCommandRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _UserService_GetUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(GetUserRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(UserServiceServer).GetUser(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/proto.UserService/GetUser",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(UserServiceServer).GetUser(ctx, req.(*GetUserRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _UserService_ListUsers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(ListUserRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(UserServiceServer).ListUsers(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/proto.UserService/ListUsers",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(UserServiceServer).ListUsers(ctx, req.(*ListUserRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _UserService_serviceDesc = grpc.ServiceDesc{
	ServiceName: "proto.UserService",
	HandlerType: (*UserServiceServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "DispatchUserCommand",
			Handler:    _UserService_DispatchUserCommand_Handler,
		},
		{
			MethodName: "GetUser",
			Handler:    _UserService_GetUser_Handler,
		},
		{
			MethodName: "ListUsers",
			Handler:    _UserService_ListUsers_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "user.proto",
}


text:
require 'flickr'

FLICKR_API_KEY = 'c3a627d98da4cbb53042955c55702bc7'

class Flickr
  alias :orig_initialize :initialize

  @last_request = nil

  def initialize(api_key = FLICKR_API_KEY, email=nil, password=nil)
    @api_key = api_key
    @host = 'http://flickr.com'
    @api = '/services/rest'
    login(email, password) if email and password
  end

  # Implements flickr.photos.getRecent and flickr.photos.search
  def photos(*criteria)
    photos = (criteria[0]) ? photos_search(criteria[0]) : photos_getRecent
    return [] unless photos && photos['photos']['photo']

    if photos['photos']['photo'].is_a?(Hash)
      return [Photo.new(photos['photos']['photo']['id'])]
    end

    photos['photos']['photo'].collect do |photo|
      Photo.new(photo['id'])
    end
  end

  class Photo
    attr_accessor :date_taken

    def getInfo
      info = @client.photos_getInfo('photo_id'=>@id)['photo']
      @title = info['title']
      @owner = User.new(info['owner']['nsid'])
      @server = info['server']
      @isfavorite = info['isfavorite']
      @license = info['license']
      @rotation = info['rotation']
      @description = info['description']
      @notes = info['notes']['note']#.collect { |note| Note.new(note.id) }

      date = info['dates']['taken']
      if date
        @date_taken = Time.parse(date)
      end

      self
    end

    def photopage_url
      self.owner.url.gsub(/\/people/, "/photos") + "#{@id}"
    end

    def date_taken
      @date_taken.nil? ? getInfo.date_taken : @date_taken
    end

    def sizes
      unless @sizes
        @sizes = @client.photos_getSizes('photo_id'=>@id)['sizes']['size']
      end

      return @sizes
    end

    def size(s)
      sizes.find{ |asize| asize['label'] == s }
    end

    def thumbnail
      size('Thumbnail')['source'] if size('Thumbnail')
    end

    def medium
      size('Medium')['source'] if size('Medium')
    end

    def small
      size('Small')['source'] if size('Small')
    end

    def square
      size('Square')['source'] if size('Square')
    end
  end

end

class PhotoSearch

  PER_PAGE = 200
  MIN_SHOW_PHOTOS = 20
  FLICKR_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

  attr_reader :flickr

  def initialize
    @flickr = Flickr.new
  end

  def flickr_time(time)
    time.strftime(FLICKR_TIME_FORMAT)
  end

  def find_show_photos(band, oldest_show = 3.months.ago)
    # Search for photos we think were taken at past shows of this band
    shows = band.shows.find(:all, :conditions => ["date >= ?", oldest_show])
    for show in shows
      date = show.date
      if date.hour == 0
        date = date + 19.hours
      end

      OFFLINE_LOGGER.info "#{band.name} - #{date}"

      min_date = date - 8.hours
      max_date = date + 12.hours

      name_tag = band.short_name
      tags = "#{name_tag}, concert"

      photos = do_with_retry do
        @flickr.photos(:tags => tags, :per_page => PER_PAGE.to_s, :tag_mode => 'all',
                       :min_taken_date => flickr_time(min_date), :max_taken_date => flickr_time(max_date))
      end

      OFFLINE_LOGGER.info "  found #{photos.size} photos"
      if photos.size < MIN_SHOW_PHOTOS
        tags = "#{name_tag}, livemusic"

        photos += do_with_retry do
          @flickr.photos(:tags => tags, :per_page => PER_PAGE.to_s, :tag_mode => 'all',
                         :min_taken_date => flickr_time(min_date), :max_taken_date => flickr_time(max_date))
        end

        OFFLINE_LOGGER.info "  look for livemusic, now found #{photos.size} photos"
      end

      if photos.size < MIN_SHOW_PHOTOS && name_tag.starts_with?("the")
        name_tag = name_tag[3..-1]
        tags = "#{name_tag}, concert"
        photos += do_with_retry do
          @flickr.photos(:tags => tags, :per_page => PER_PAGE.to_s, :tag_mode => 'all',
                         :min_taken_date => flickr_time(min_date), :max_taken_date => flickr_time(max_date))
        end

        OFFLINE_LOGGER.info "  look without 'the', now found #{photos.size} photos"
      end

      for photo in photos[0..20]
        next if FlickrPhoto.find_by_flickr_id(photo.id)

        next unless photo.thumbnail && photo.medium && photo.square && photo.small
        fp = do_with_retry do
          FlickrPhoto.new(:band_id => band.id, :show_id => show.id, :photopage_url => photo.photopage_url,
                           :thumbnail_source => photo.thumbnail, :medium_source => photo.medium, :square_source => photo.square,
                           :title => photo.title, :owner => photo.owner.id, :flickr_id => photo.id,
                           :date => photo.date_taken, :venue_id => show.venue.id, :small_source => photo.small)
         end

        fp.save!
      end
    end

    if band.flickr_photos.size < 20
      # Look for other photos to fill things out
      OFFLINE_LOGGER.info "   Try to find unattached photos"

      tags = "#{band.short_name}, concert"
      photos = do_with_retry do
        @flickr.photos(:tags => tags, :per_page => "200", :tag_mode => 'all',
                       :min_taken_date => flickr_time(6.months.ago))
      end

      photos = photos.random(40)
      OFFLINE_LOGGER.info "    Add #{photos.size} unattached photos"
      for photo in photos
        next unless photo.thumbnail && photo.medium && photo.square && photo.small
	next if FlickrPhoto.find_by_flickr_id(photo.id)

        fp = do_with_retry do
          FlickrPhoto.new(:band_id => band.id, :photopage_url => photo.photopage_url,
                           :thumbnail_source => photo.thumbnail, :medium_source => photo.medium, :square_source => photo.square,
                           :title => photo.title, :owner => photo.owner.id, :flickr_id => photo.id,
                           :date => photo.date_taken, :small_source => photo.small)
        end

        fp.save!
      end
    end

    return nil
  end

  def do_with_retry(retries = 3)
    ret = nil
    sleep_time = 1
    begin
      sleep(sleep_time)
      ret = yield
    rescue Exception => e
      OFFLINE_LOGGER.error "Error talking to flickr: #{e}, #{e.backtrace}"
      if retries > 0
        OFFLINE_LOGGER.info "Retrying..."
        retries -= 1
        sleep_time *= 2
        retry
      end
    end

    raise "Too many errors" unless ret
    return ret
  end

end


text:
Swift-HelloWorld
================

Basic example of using the Swift language


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Random Adj/Noun Generator</title>

                -
                <button id="again" onclick="generate();">Generate again</button>

                This name was pre-filled from the URL (not randomly generated).

                Adjectives:

                Nouns:

                Possible combinations:


text:
#ifndef __SYSDEP_I386_SKAS_PTRACE_H
#define __SYSDEP_I386_SKAS_PTRACE_H

struct ptrace_faultinfo {
        int is_write;
        unsigned long addr;
};

struct ptrace_ldt {
        int func;
        void *ptr;
        unsigned long bytecount;
};

#define PTRACE_LDT 54

#endif


text:
import type { SubmitHandler } from "react-hook-form";
import { CenteredLoading } from "~/components/centered-loading";
import { FailedToFetch } from "~/components/failed-to-fetch";
import { FormInformation } from "~/components/form/information";
import { FormInput } from "~/components/form/input";
import { FormSubmit } from "~/components/form/submit";
import { usePutForm } from "~/hooks/form";
import { useRequireAdmin } from "~/hooks/require";
import { useTrackGenre, useUpdateTrackGenre } from "~/hooks/track-genres";
import { AdminLayout } from "~/layouts/admin/layout";
import type { PageComponent } from "~/pages/_app";
import type { Schema } from "~/rules/track-genre/update";
import { label, schema } from "~/rules/track-genre/update";
import { setErrors } from "~/utils/form";

const Page: PageComponent = () => {
  useRequireAdmin();

  const genre = useTrackGenre();
  const updateGenre = useUpdateTrackGenre<Schema>();

  const form = usePutForm<Schema>({
    schema,
    focus: "name",
    data: genre.data,
  });

  const onSubmit: SubmitHandler<Schema> = (body) => {
    const variables = { body, id: genre.data?.id };

    updateGenre.mutate(variables, {
      onError: async (response) => {
        await setErrors(response, form.setError);
      },
    });
  };

  if (genre.isLoading) {
    return <CenteredLoading />;
  }

  if (genre.isError) {
    return <FailedToFetch />;
  }

  return (
    <>

Update track genres

      <form onSubmit={form.handleSubmit(onSubmit)}>
        <FormInformation className="mb-10" />
        <FormInput
          label={label.name}
          className="mb-8 w-full md:w-1/2"
          type="text"
          inputClass="border-gray-700 bg-gray-900"
          register={form.register("name")}
          feedback={form.errors.name?.message}
          placeholder="Name"
          required
        />
        <FormSubmit disabled={form.disabled || updateGenre.isLoading}>
          Update
        </FormSubmit>
      </form>
    </>
  );
};

Page.getLayout = (page) => (
  <AdminLayout title="Update track genres">{page}</AdminLayout>
);

export default Page;


text:
package play.server;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.util.CharsetUtil;

public class FlashPolicyHandler extends FrameDecoder {

	private static final String XML = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>";
    private ChannelBuffer policyResponse = ChannelBuffers.copiedBuffer(XML, CharsetUtil.UTF_8);

    /**
     * Creates a handler allowing access from any domain and any port
     */
    public FlashPolicyHandler() {
        super();
    }

    /**
     * Create a handler with a custom XML response. Useful for defining your own domains and ports.
     * @param policyResponse Response XML to be passed back to a connecting client
     */
    public FlashPolicyHandler(ChannelBuffer policyResponse) {
        super();
        this.policyResponse = policyResponse;
    }

    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
        if (buffer.readableBytes() < 2) {
            return null;
        }

        final int magic1 = buffer.getUnsignedByte(buffer.readerIndex());
        final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1);
        boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p');

        if (isFlashPolicyRequest) {
            buffer.skipBytes(buffer.readableBytes()); // Discard everything
            channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE);
            return null;
        }

        // Remove ourselves, important since the byte length check at top can hinder frame decoding
        // down the pipeline
        ctx.getPipeline().remove(this);
        return buffer.readBytes(buffer.readableBytes());
    }

}


text:
package com.webcohesion.enunciate.modules.jaxrs.api.impl;

import com.webcohesion.enunciate.api.Styles;
import com.webcohesion.enunciate.api.resources.Method;
import com.webcohesion.enunciate.api.resources.Resource;
import com.webcohesion.enunciate.api.resources.ResourceGroup;
import com.webcohesion.enunciate.facets.Facet;
import com.webcohesion.enunciate.javac.decorations.element.ElementUtils;
import com.webcohesion.enunciate.javac.javadoc.JavaDoc;
import com.webcohesion.enunciate.modules.jaxrs.model.ResourceMethod;

import javax.lang.model.element.AnnotationMirror;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Ryan Heaton
 */
public class ResourceImpl implements Resource {

  final ResourceMethod resourceMethod;
  private final ResourceGroup group;
  private final List<Method> methods;

  public ResourceImpl(ResourceMethod resourceMethod, ResourceGroup group) {
    this.resourceMethod = resourceMethod;
    this.group = group;
    Set<String> httpMethods = this.resourceMethod.getHttpMethods();
    this.methods = new ArrayList<Method>(httpMethods.size());
    for (String httpMethod : httpMethods) {
      this.methods.add(new MethodImpl(httpMethod, this.resourceMethod, this.group));
    }
  }

  @Override
  public String getPath() {
    return resourceMethod.getFullpath();
  }

  @Override
  public String getRelativePath() {
    String relativePath = getPath();
    while (relativePath.startsWith("/")) {
      relativePath = relativePath.substring(1);
    }
    return relativePath;
  }

  @Override
  public String getSlug() {
    return group.getSlug() + "_" + this.resourceMethod.getSimpleName();
  }

  @Override
  public String getDeprecated() {
    return ElementUtils.findDeprecationMessage(this.resourceMethod);
  }

  @Override
  public String getSince() {
    JavaDoc.JavaDocTagList tags = this.resourceMethod.getJavaDoc().get("since");
    return tags == null ? null : tags.toString();
  }

  @Override
  public String getVersion() {
    JavaDoc.JavaDocTagList tags = this.resourceMethod.getJavaDoc().get("version");
    return tags == null ? null : tags.toString();
  }

  @Override
  public List<? extends Method> getMethods() {
    return methods;
  }

  @Override
  public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
    return this.resourceMethod.getAnnotation(annotationType);
  }

  @Override
  public Map<String, AnnotationMirror> getAnnotations() {
    return this.resourceMethod.getAnnotations();
  }

  @Override
  public Set<Facet> getFacets() {
    return this.resourceMethod.getFacets();
  }

  @Override
  public JavaDoc getJavaDoc() {
    return this.resourceMethod.getJavaDoc();
  }

  @Override
  public Set<String> getStyles() {
    return Styles.gatherStyles(this.resourceMethod, this.resourceMethod.getContext().getContext().getConfiguration().getAnnotationStyles());
  }
}


text:
namespace System.Runtime.Serialization
{
	[AttributeUsage (AttributeTargets.Property | AttributeTargets.Field,
		Inherited = false, AllowMultiple = false)]
	public sealed class DataMemberAttribute : System.Attribute
	{
		bool is_required;
		bool emit_default = true;
		string name;
		int order = -1;

		public DataMemberAttribute ()
		{
		}

		public bool EmitDefaultValue {
			get { return emit_default; }
			set { emit_default = value; }
		}

		public bool IsRequired {
			get { return is_required; }
			set { is_required = value; }
		}

		public string Name {
			get { return name; }
			set { name = value; }
		}

		public int Order {
			get { return order; }
			set { order = value; }
		}
	}
}
#pragma warning restore 436
#endif


text:
<?php

namespace Application\Controller;

use Application\Form\UserForm;
use Zend\Authentication\Result;
use Zend\Mvc\Controller\AbstractActionController;
use DoctrineModule\Authentication\Adapter\ObjectRepository;

class AuthController extends AbstractActionController
{
    public function indexAction()
    {
        $request = $this->getRequest();
        $form = new UserForm();

        if ($request->isPost()) {
            $form->setData($request->getPost());

            if ($form->isValid()) {
                /** ObjectRepository $authService */
                $authService = $this->getService('auth_service');

                /** @var Result $authResult */
                $authResult = $authService
                    ->setIdentity($request->getPost('email'))
                    ->setCredential($request->getPost('password'))
                    ->authenticate();

                if ($authResult->isValid()) {
                    // open the session
                }
            }
        }

        return ['form' => $form];
    }

    /**
     * @param $id
     *
     * @return mixed
     */
    protected function getService($id)
    {
        return $this->getPluginManager()->getServiceLocator()->get($id);
    }
}


text:
//-----------------------------------------------------------------------------------
//
// SAFECASS: Safety Architecture For Engineering Computer-Assisted Surgical Systems
//
// Copyright (C) 2012-2016 Min Yang Jung and Peter Kazanzides
//
//-----------------------------------------------------------------------------------
//
// Created on   : Apr 10, 2016
// Last revision: Apr 20, 2016
// Author       : Min Yang Jung <myj@jhu.edu>
// Github       : https://github.com/safecass/safecass
//
#ifndef _SignalAccessor_h
#define _SignalAccessor_h

#include <vector>
#include <boost/circular_buffer.hpp>

#include "common/common.h"

namespace SC {

//! Base class of signal accessor classes
class SignalAccessorBase
{
protected:
    //! Reference to original object associated with this signal accessor
    const ParamBase & SignalObject;
    //! Name of signal that this signal accessor is associated with
    const std::string SignalName;

public:
    SignalAccessorBase(const ParamBase & object, const std::string & name)
        : SignalObject(object), SignalName(name)
    {}
    virtual ~SignalAccessorBase() {}

    //! Returns name of signal associated with this signal accessor
    inline std::string GetSignalName(void) const { return SignalName; }

    //
    // Pure virtual methods
    //
    virtual void Push(void) = 0;
    virtual void GetValue(ParamBase & arg) const = 0;
    virtual void ToStream(std::ostream & os) const = 0;
};

inline std::ostream & operator<< (std::ostream & os, const SignalAccessorBase & accessor)
{
    accessor.ToStream(os);
    return os;
}

//! Signal accessor class
template<class T>
class SignalAccessor: public SignalAccessorBase
{
public:
    //! Typedef for base class
    typedef SignalAccessorBase BaseType;

    //! Typedefs for container access
    typedef boost::circular_buffer<T>          ContainerType;
    typedef typename ContainerType::size_type  SizeType;
    typedef typename ContainerType::value_type ValueType;
    typedef typename ContainerType::iterator   IteratorType;
    /*!
        'param_type' of boost.call_traits represents the "best" way to pass a parameter
        of type `value_type` to a method
        \sa boost/call_traits
    */
    typedef typename boost::call_traits<ValueType>::param_type ParameterType;

    //! Container maintaining snapshots of signals
    ContainerType * Container;

    //! Constructor
    SignalAccessor(const ParamBase & object, const std::string & name, size_t size)
        : SignalAccessorBase(object, name)
    {
        Container = new ContainerType(size);
    }

    //! Destructor
    ~SignalAccessor(void) {
        delete Container;
    }

    virtual void Push(void) {
        const ValueType * param = dynamic_cast<const ValueType *>(&SignalObject);
        SCASSERT(param);
        Container->push_back(*param);
    }

    void Push(ParameterType item, bool debug = false) {
        if (debug) {
            const ValueType * _obj = dynamic_cast<const ValueType*>(&item);
            SCLOG_DEBUG << "Signal accessor \"" << this->GetSignalName() << "\": push " << *_obj << std::endl;
        }
        Container->push_back(item);
        if (debug) {
            SCLOG_DEBUG << "Signal accessor \"" << this->GetSignalName() << "\": size after push = "
                        << Container->size() << std::endl;
        }
    }

    virtual void GetValue(ParamBase & arg) const {
        if (!Container) {
            arg.SetValid(false);
            return;
        }

        // circular_buffer memory layout:
        //
        // boost::circular_buffer<int> cb(3);
        // cb.push_back(1);
        // cb.push_back(2);
        // cb.push_back(3);
        // cb.push_back(4);
        //
        // assert(cb[0] == 2);
        // assert(cb[1] == 3);
        // assert(cb[2] == 4);
        //
        // assert(*cb.begin() == 2);
        // assert(cb.front() == 2);
        // assert(cb.back() == 4);

        ValueType * pArg = dynamic_cast<ValueType *>(&arg);
        SCASSERT(pArg);
        *pArg = Container->back();
    }

    //
    // Getters
    //
    inline size_t GetContainerSize(void) { return Container->size(); }

    virtual void ToStream(std::ostream & os) const {
        os << "Signal accessor \"" << this->GetSignalName() << "\": " << SignalObject
           << ", container: ";
        if (Container->empty()) {
            os << "empty";
            return;
        }
        IteratorType it = Container->begin();
        for (; it != Container->end(); ++it) {
            os << *it;
            if (it + 1 != Container->end())
                os << ", ";
        }
    }
};

};

#endif // _SignalAccessor_h


text:
#ifndef INFORMATION_SCHEMA_CPP_TIME_ZONE_NAME_H
#define INFORMATION_SCHEMA_CPP_TIME_ZONE_NAME_H

#include<string>

namespace dbcrudgen {
    namespace db {
        namespace mysql {
            class TimeZoneName {

            private:
                std::string name;
                int timeZoneId;

            public:

                static constexpr const char *TABLE_NAME = "time_zone_name";

                struct COLUMNS {
                    struct NAME {
                        static constexpr const char *_NAME = "Name";
                        static const int INDEX = 1;
                    };
                    struct TIME_ZONE_ID {
                        static constexpr const char *NAME = "Time_zone_id";
                        static const int INDEX = 2;
                    };
                };

                TimeZoneName(std::string &name, int timeZoneId) : name{name}, timeZoneId{timeZoneId} {}

                // Get the value of name
                const std::string &getName() const {
                    return name;
                }

                // Get the value of timeZoneId
                int getTimeZoneId() const {
                    return timeZoneId;
                }

                /**
                * Returns the table name 'time_zone_name';
                */
                static const char *getDatabaseTableName() {
                    return TABLE_NAME;
                }
            };
        }
    }

}
#endif //INFORMATION_SCHEMA_CPP_TIME_ZONE_NAME_H


text:
<?php

/**
 * Description of plugin
 * @author Alexey Berezuev <alexey@berezuev.ru>
 * @license http://opensource.org/licenses/MIT
 * @version 0.1
 */

set_include_path(get_include_path().PATH_SEPARATOR.dirname(__file__).'/include');

return array(
    'id' => 'berezuev:osticket-spreader',
    'version' => '0.1',
    'name' => 'osticket-spreader',
    'author' => 'Alexey Berezuev',
    'description' => 'Spread tickets evenly between several managers.',
    'url' => 'https://github.com/berezuev/osticket-spreader',
    'plugin' => 'spreader.php:SpreaderPlugin'
);


text:
layout: post
title: Shortcuts
date: 2008-05-23T09:17:00.004Z
author: Marcus Hammarberg
tags: null
modified_time: 2010-12-14T15:20:33.277Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-8412792532818677787
blogger_orig_url: http://www.marcusoft.net/2008/05/shortcuts.html
---

Anyone
who has worked with me know that I love shortcuts
(that is
keyboard
shortcuts - i wouldn't dream of taking shortcuts in
real life...).

I love
them in
general but specifically in Visual
Studio - they often involve at least three keys and at least two hands to be fully executed.

Here is
a list of some of them - i haven't seen some them before and other ones are loved friends of mine:
<http://www.dev102.com/2008/05/06/11-more-visual-studio-shortcuts-you-should-know/>

**\[UPDATED\]**
That short-cut site contained some other really useful stuff also:

- <http://www.dev102.com/2008/05/09/6-useful-visual-studio-tweaks-you-need-to-know/>
- <http://www.dev102.com/2008/04/17/10-visual-studio-shortcuts-you-must-know/>


text:
(function( $ ) {
    $.fn.loadR = function(options) {
    	var settings = $.extend({
    		showLoadingAnimation : false,
    		loadingHTML : '',
    		contentURL : ''
    	}, $.fn.loadR.defaults, options);

    	return this.each(function() {
    		var elem = $(this);
    		var url = settings.contentURL == '' ? elem.attr('data-loadr') : settings.contentURL;
    		if(settings.showLoadingAnimation) {
    			elem = elem.after(settings.loadingHTML);
    		}

    		$.get(url, function(html) {
    			cleanupLoadingAnimation(elem);
    			elem.replaceWith(html);
    		}).fail(function() {
    			cleanupLoadingAnimation(elem);
    		});
    	});

    	function cleanupLoadingAnimation(elem) {
    		if(settings.showLoadingAnimation) {
				elem.next().remove();
			}
    	}
    };
}( jQuery ));


text:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request

from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.utils.markup import replace_tags

from product_spiders.items import Product, ProductLoader

class PipebootexpressComSpider(BaseSpider):
    name = 'pipebootexpress.com'
    allowed_domains = ['pipebootexpress.com']
    start_urls = (
        'http://pipebootexpress.com/',
        )

    download_delay = 2

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        base_url = get_base_url(response)

        categories = hxs.select("//div[@id='dvWrapControl732']//a/@href").extract()
        for link in categories:
            url = urljoin_rfc(base_url, link)
            yield Request(url, callback=self.parse)

        items = hxs.select("//table[@class='ProductGroup']/tr[@class='ProductGroupItem'] |\
                            //table[@class='ProductGroup']/tr[@class='ProductGroupAlternatingItem']")
        for item in items:
            name = item.select("td[@id='tdProductGroupDisplayDescription']/div/font | \
                                td[@id='tdProductGroupDisplayAltDescription']/div/font").extract()
            if not name:
                print "%s - ERROR! NO NAME!" % response.url
                continue
            name = replace_tags(name[0])
            url = response.url
            price = item.select("td[@id='tdProductGroupDisplayPricing']//text() | \
                                 td[@id='tdProductGroupDisplayAltPricing']//text()").extract()
            if not price:
                print "%s - ERROR! NO PRICE!" % response.url
                continue
            price = price[0].split(',')[0]
            l = ProductLoader(item=Product(), response=response)
            l.add_value('identifier', unicode(name).encode('ascii', 'ignore'))
            l.add_value('name', name)
            l.add_value('url', url)
            l.add_value('price', price)
            yield l.load_item()


text:
use std::{
    future::Future,
    sync::{Arc, Mutex},
};

use file_system::{set_io_type, IOType};
use futures::{channel::oneshot, future::TryFutureExt};
use kvproto::kvrpcpb::CommandPri;
use online_config::{ConfigChange, ConfigManager, ConfigValue, Result as CfgResult};
use prometheus::IntGauge;
use thiserror::Error;
use tikv_util::{
    sys::SysQuota,
    yatp_pool::{self, FuturePool, PoolTicker, YatpPoolBuilder},
};
use yatp::{pool::Remote, queue::Extras, task::future::TaskCell};

use self::metrics::*;
use crate::{
    config::{UnifiedReadPoolConfig, UNIFIED_READPOOL_MIN_CONCURRENCY},
    storage::kv::{destroy_tls_engine, set_tls_engine, Engine, FlowStatsReporter},
};

pub enum ReadPool {
    FuturePools {
        read_pool_high: FuturePool,
        read_pool_normal: FuturePool,
        read_pool_low: FuturePool,
    },
    Yatp {
        pool: yatp::ThreadPool<TaskCell>,
        running_tasks: IntGauge,
        max_tasks: usize,
        pool_size: usize,
    },
}

impl ReadPool {
    pub fn handle(&self) -> ReadPoolHandle {
        match self {
            ReadPool::FuturePools {
                read_pool_high,
                read_pool_normal,
                read_pool_low,
            } => ReadPoolHandle::FuturePools {
                read_pool_high: read_pool_high.clone(),
                read_pool_normal: read_pool_normal.clone(),
                read_pool_low: read_pool_low.clone(),
            },
            ReadPool::Yatp {
                pool,
                running_tasks,
                max_tasks,
                pool_size,
            } => ReadPoolHandle::Yatp {
                remote: pool.remote().clone(),
                running_tasks: running_tasks.clone(),
                max_tasks: *max_tasks,
                pool_size: *pool_size,
            },
        }
    }
}

#[derive(Clone)]
pub enum ReadPoolHandle {
    FuturePools {
        read_pool_high: FuturePool,
        read_pool_normal: FuturePool,
        read_pool_low: FuturePool,
    },
    Yatp {
        remote: Remote<TaskCell>,
        running_tasks: IntGauge,
        max_tasks: usize,
        pool_size: usize,
    },
}

impl ReadPoolHandle {
    pub fn spawn<F>(&self, f: F, priority: CommandPri, task_id: u64) -> Result<(), ReadPoolError>
    where
        F: Future<Output = ()> + Send + 'static,
    {
        match self {
            ReadPoolHandle::FuturePools {
                read_pool_high,
                read_pool_normal,
                read_pool_low,
            } => {
                let pool = match priority {
                    CommandPri::High => read_pool_high,
                    CommandPri::Normal => read_pool_normal,
                    CommandPri::Low => read_pool_low,
                };

                pool.spawn(f)?;
            }
            ReadPoolHandle::Yatp {
                remote,
                running_tasks,
                max_tasks,
                ..
            } => {
                let running_tasks = running_tasks.clone();
                // Note that the running task number limit is not strict.
                // If several tasks are spawned at the same time while the running task number
                // is close to the limit, they may all pass this check and the number of running
                // tasks may exceed the limit.
                if running_tasks.get() as usize >= *max_tasks {
                    return Err(ReadPoolError::UnifiedReadPoolFull);
                }

                running_tasks.inc();
                let fixed_level = match priority {
                    CommandPri::High => Some(0),
                    CommandPri::Normal => None,
                    CommandPri::Low => Some(2),
                };
                let extras = Extras::new_multilevel(task_id, fixed_level);
                let task_cell = TaskCell::new(
                    async move {
                        f.await;
                        running_tasks.dec();
                    },
                    extras,
                );
                remote.spawn(task_cell);
            }
        }
        Ok(())
    }

    pub fn spawn_handle<F, T>(
        &self,
        f: F,
        priority: CommandPri,
        task_id: u64,
    ) -> impl Future<Output = Result<T, ReadPoolError>>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let (tx, rx) = oneshot::channel::<T>();
        let res = self.spawn(
            async move {
                let res = f.await;
                let _ = tx.send(res);
            },
            priority,
            task_id,
        );
        async move {
            res?;
            rx.map_err(ReadPoolError::from).await
        }
    }

    pub fn get_normal_pool_size(&self) -> usize {
        match self {
            ReadPoolHandle::FuturePools {
                read_pool_normal, ..
            } => read_pool_normal.get_pool_size(),
            ReadPoolHandle::Yatp { pool_size, .. } => *pool_size,
        }
    }

    pub fn get_queue_size_per_worker(&self) -> usize {
        match self {
            ReadPoolHandle::FuturePools {
                read_pool_normal, ..
            } => {
                read_pool_normal.get_running_task_count() as usize
                    / read_pool_normal.get_pool_size()
            }
            ReadPoolHandle::Yatp {
                running_tasks,
                pool_size,
                ..
            } => running_tasks.get() as usize / *pool_size,
        }
    }

    pub fn scale_pool_size(&mut self, max_thread_count: usize) {
        match self {
            ReadPoolHandle::FuturePools { .. } => {
                unreachable!()
            }
            ReadPoolHandle::Yatp {
                remote,
                running_tasks: _,
                max_tasks,
                pool_size,
            } => {
                remote.scale_workers(max_thread_count);
                *max_tasks = max_tasks
                    .saturating_div(*pool_size)
                    .saturating_mul(max_thread_count);
                *pool_size = max_thread_count;
            }
        }
    }
}

#[derive(Clone)]
pub struct ReporterTicker<R: FlowStatsReporter> {
    reporter: R,
}

impl<R: FlowStatsReporter> PoolTicker for ReporterTicker<R> {
    fn on_tick(&mut self) {
        self.flush_metrics_on_tick();
    }
}

impl<R: FlowStatsReporter> ReporterTicker<R> {
    fn flush_metrics_on_tick(&mut self) {
        crate::storage::metrics::tls_flush(&self.reporter);
        crate::coprocessor::metrics::tls_flush(&self.reporter);
    }
}

#[cfg(test)]
fn get_unified_read_pool_name() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);
    format!(
        "unified-read-pool-test-{}",
        COUNTER.fetch_add(1, Ordering::Relaxed)
    )
}

#[cfg(not(test))]
fn get_unified_read_pool_name() -> String {
    "unified-read-pool".to_string()
}

pub fn build_yatp_read_pool<E: Engine, R: FlowStatsReporter>(
    config: &UnifiedReadPoolConfig,
    reporter: R,
    engine: E,
) -> ReadPool {
    let unified_read_pool_name = get_unified_read_pool_name();
    let mut builder = YatpPoolBuilder::new(ReporterTicker { reporter });
    let raftkv = Arc::new(Mutex::new(engine));
    let pool = builder
        .name_prefix(&unified_read_pool_name)
        .stack_size(config.stack_size.0 as usize)
        .thread_count(
            config.min_thread_count,
            config.max_thread_count,
            std::cmp::max(
                UNIFIED_READPOOL_MIN_CONCURRENCY,
                SysQuota::cpu_cores_quota() as usize,
            ),
        )
        .after_start(move || {
            let engine = raftkv.lock().unwrap().clone();
            set_tls_engine(engine);
            set_io_type(IOType::ForegroundRead);
        })
        .before_stop(|| unsafe {
            destroy_tls_engine::<E>();
        })
        .build_multi_level_pool();
    ReadPool::Yatp {
        pool,
        running_tasks: UNIFIED_READ_POOL_RUNNING_TASKS
            .with_label_values(&[&unified_read_pool_name]),
        max_tasks: config
            .max_tasks_per_worker
            .saturating_mul(config.max_thread_count),
        pool_size: config.max_thread_count,
    }
}

impl From<Vec<FuturePool>> for ReadPool {
    fn from(mut v: Vec<FuturePool>) -> ReadPool {
        assert_eq!(v.len(), 3);
        let read_pool_high = v.remove(2);
        let read_pool_normal = v.remove(1);
        let read_pool_low = v.remove(0);
        ReadPool::FuturePools {
            read_pool_high,
            read_pool_normal,
            read_pool_low,
        }
    }
}

pub struct ReadPoolConfigManager(pub ReadPoolHandle);

impl ConfigManager for ReadPoolConfigManager {
    fn dispatch(&mut self, change: ConfigChange) -> CfgResult<()> {
        if let Some(ConfigValue::Module(unified)) = change.get("unified") {
            if let Some(ConfigValue::Usize(max_thread_count)) = unified.get("max_thread_count") {
                self.0.scale_pool_size(*max_thread_count);
            }
        }
        info!(
            "readpool config changed";
            "change" => ?change,
        );
        Ok(())
    }
}

#[derive(Debug, Error)]
pub enum ReadPoolError {
    #[error("{0}")]
    FuturePoolFull(#[from] yatp_pool::Full),

    #[error("Unified read pool is full")]
    UnifiedReadPoolFull,

    #[error("{0}")]
    Canceled(#[from] oneshot::Canceled),
}

mod metrics {
    use prometheus::*;

    lazy_static! {
        pub static ref UNIFIED_READ_POOL_RUNNING_TASKS: IntGaugeVec = register_int_gauge_vec!(
            "tikv_unified_read_pool_running_tasks",
            "The number of running tasks in the unified read pool",
            &["name"]
        )
        .unwrap();
    }
}

#[cfg(test)]
mod tests {
    use std::{thread, time::Duration};

    use futures::channel::oneshot;
    use raftstore::store::{ReadStats, WriteStats};

    use super::*;
    use crate::storage::TestEngineBuilder;

    #[derive(Clone)]
    struct DummyReporter;

    impl FlowStatsReporter for DummyReporter {
        fn report_read_stats(&self, _read_stats: ReadStats) {}
        fn report_write_stats(&self, _write_stats: WriteStats) {}
    }

    #[test]
    fn test_yatp_full() {
        let config = UnifiedReadPoolConfig {
            min_thread_count: 1,
            max_thread_count: 2,
            max_tasks_per_worker: 1,
            ..Default::default()
        };
        // max running tasks number should be 2*1 = 2

        let engine = TestEngineBuilder::new().build().unwrap();
        let pool = build_yatp_read_pool(&config, DummyReporter, engine);

        let gen_task = || {
            let (tx, rx) = oneshot::channel::<()>();
            let task = async move {
                let _ = rx.await;
            };
            (task, tx)
        };

        let handle = pool.handle();
        let (task1, tx1) = gen_task();
        let (task2, _tx2) = gen_task();
        let (task3, _tx3) = gen_task();
        let (task4, _tx4) = gen_task();

        assert!(handle.spawn(task1, CommandPri::Normal, 1).is_ok());
        assert!(handle.spawn(task2, CommandPri::Normal, 2).is_ok());

        thread::sleep(Duration::from_millis(300));
        match handle.spawn(task3, CommandPri::Normal, 3) {
            Err(ReadPoolError::UnifiedReadPoolFull) => {}
            _ => panic!("should return full error"),
        }
        tx1.send(()).unwrap();

        thread::sleep(Duration::from_millis(300));
        assert!(handle.spawn(task4, CommandPri::Normal, 4).is_ok());
    }

    #[test]
    fn test_yatp_scale_up() {
        let config = UnifiedReadPoolConfig {
            min_thread_count: 1,
            max_thread_count: 2,
            max_tasks_per_worker: 1,
            ..Default::default()
        };
        // max running tasks number should be 2*1 = 2

        let engine = TestEngineBuilder::new().build().unwrap();
        let pool = build_yatp_read_pool(&config, DummyReporter, engine);

        let gen_task = || {
            let (tx, rx) = oneshot::channel::<()>();
            let task = async move {
                let _ = rx.await;
            };
            (task, tx)
        };

        let mut handle = pool.handle();
        let (task1, _tx1) = gen_task();
        let (task2, _tx2) = gen_task();
        let (task3, _tx3) = gen_task();
        let (task4, _tx4) = gen_task();
        let (task5, _tx5) = gen_task();

        assert!(handle.spawn(task1, CommandPri::Normal, 1).is_ok());
        assert!(handle.spawn(task2, CommandPri::Normal, 2).is_ok());

        thread::sleep(Duration::from_millis(300));
        match handle.spawn(task3, CommandPri::Normal, 3) {
            Err(ReadPoolError::UnifiedReadPoolFull) => {}
            _ => panic!("should return full error"),
        }

        handle.scale_pool_size(3);
        assert_eq!(handle.get_normal_pool_size(), 3);

        assert!(handle.spawn(task4, CommandPri::Normal, 4).is_ok());

        thread::sleep(Duration::from_millis(300));
        match handle.spawn(task5, CommandPri::Normal, 5) {
            Err(ReadPoolError::UnifiedReadPoolFull) => {}
            _ => panic!("should return full error"),
        }
    }

    #[test]
    fn test_yatp_scale_down() {
        let config = UnifiedReadPoolConfig {
            min_thread_count: 1,
            max_thread_count: 2,
            max_tasks_per_worker: 1,
            ..Default::default()
        };
        // max running tasks number should be 2*1 = 2

        let engine = TestEngineBuilder::new().build().unwrap();
        let pool = build_yatp_read_pool(&config, DummyReporter, engine);

        let gen_task = || {
            let (tx, rx) = oneshot::channel::<()>();
            let task = async move {
                let _ = rx.await;
            };
            (task, tx)
        };

        let mut handle = pool.handle();
        let (task1, tx1) = gen_task();
        let (task2, tx2) = gen_task();
        let (task3, _tx3) = gen_task();
        let (task4, _tx4) = gen_task();
        let (task5, _tx5) = gen_task();

        assert!(handle.spawn(task1, CommandPri::Normal, 1).is_ok());
        assert!(handle.spawn(task2, CommandPri::Normal, 2).is_ok());

        thread::sleep(Duration::from_millis(300));
        match handle.spawn(task3, CommandPri::Normal, 3) {
            Err(ReadPoolError::UnifiedReadPoolFull) => {}
            _ => panic!("should return full error"),
        }

        tx1.send(()).unwrap();
        tx2.send(()).unwrap();
        thread::sleep(Duration::from_millis(300));

        handle.scale_pool_size(1);
        assert_eq!(handle.get_normal_pool_size(), 1);

        assert!(handle.spawn(task4, CommandPri::Normal, 4).is_ok());

        thread::sleep(Duration::from_millis(300));
        match handle.spawn(task5, CommandPri::Normal, 5) {
            Err(ReadPoolError::UnifiedReadPoolFull) => {}
            _ => panic!("should return full error"),
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
 ~ Copyright (c) 2010-2011 Sonatype, Inc.
 ~ All rights reserved. This program and the accompanying materials
 ~ are made available under the terms of the Eclipse Public License v1.0
 ~ and Apache License v2.0 which accompanies this distribution.
 ~ The Eclipse Public License is available at
 ~   http://www.eclipse.org/legal/epl-v10.html
 ~ The Apache License v2.0 is available at
 ~   http://www.apache.org/licenses/LICENSE-2.0.html
 ~ You may elect to redistribute this code under either of these licenses.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.sonatype.sisu.inject</groupId>
    <artifactId>guice-plexus</artifactId>
    <version>2.1.1</version>
  </parent>

  <artifactId>guice-plexus-metadata</artifactId>

  <name>Guice - Plexus metadata</name>

  <dependencies>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-component-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>org.sonatype.sisu</groupId>
      <artifactId>sisu-guice</artifactId>
    </dependency>
    <dependency>
      <groupId>org.sonatype.sisu.inject</groupId>
      <artifactId>guice-bean-reflect</artifactId>
    </dependency>
  </dependencies>

</project>


text:
module BigcommerceTool
  class Global < GenericLookup

    def initialize(config_path, file_load_path)
      @file_load_path = file_load_path
      super(config_path)
    end

    def lookup(key)
      unless @translations[key].to_s.match(/From File/)
        super(key)
      else
        load_from_file(key)
      end
    end

    def code
      "GLOBAL_"
    end

    private

    def load_from_file(key)
      File.open(File.join(Dir.pwd, @file_load_path, "#{key}.html") , "rb").read
    end
  end
end


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Deltion Live Streaming</title>
</head>

<body>
    <video width="320" height="240" controls="true" autoplay="true" preload="none">
      <source src="http://192.168.2.6:8090/test1.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
    Your browser does not support the video tag.
    </video>
</body>
</html>