text:
import sys
import re
import string
import commands
import warnings

errors = 0
def warn(msg, error=None):
    global errors
    errors += 1
    if error is None:
        warnings.warn("-- "+str(errors)+" --\n  "+msg, RuntimeWarning, 2)
    else:
        warnings.warn("-- "+str(errors)+" --\n  "+msg+
                      "\n  error was "+str(error), RuntimeWarning, 2)
#fu

# beware, stupid python interprets backslashes in repl only partially!
def s(string, pattern, repl, count=0):
    return re.sub(pattern, repl, string, count)
def m(string, pattern):
    return re.match(pattern, string)
def sorted_keys(dict):
    keys = dict.keys()
    keys.sort()
    return keys

# we make up a few formatter routines to help in the processing:
def html2docbook(text):
    """ the C comment may contain html markup - simulate with docbook tags """
    return (
        s(s(s(s(s(s(s(s(s(s(s(text,
                              r"
",""),
                            r"(</?)em>",r"\1emphasis>"),
                          r"","<userinput>"),
                        r"","</userinput>"),
                      r"<link>","<function>"),
                    r"</link>","</function>"),
                  r"(?s)\s*</screen>","</screen>"),
#               r"
","</para><itemizedlist>"),
#             r"
","</itemizedlist><para>"),
#           r"
","<listitem><para>"),
#         r"
","</para></listitem>\n"),
                r"
","</para><programlisting>\n"),
              r"
","</programlisting><para>"),
            r"
",""),
          r"
",""))
def paramdef2html(text):
    return s(s(s(s(s(text,
                     r"\s+<paramdef>", r"\n<nobr>"),
                   r"<paramdef>",r"<nobr>"),
                 r"</paramdef>",r"</nobr>"),
               r"<parameters>",r"\n "),
             r"</parameters>",r"\n")
def section2html(text):
    mapping = { "<screen>" : "
", "</screen>" : "
",
                "<para>" : "
", "</para>" : "
" ,
                "<function>" : "<link>", "</function>" : "</link>" }
    for str in mapping:
        text = string.replace(text, str, mapping[str])
    return text
def html(text):
    return section2html(paramdef2html(text))
def cdata1(text):
    return string.replace(text, "&",  "&")
def cdata31(text):
    return string.replace(string.replace(text, "<","<"), ">",">")
def cdata3(text):
    return cdata31(cdata1(text))
def cdata43(text):
    return string.replace(text,"\"", """)
def cdata41(text):
    return cdata43(cdata31(text))
def cdata4(text):
    return cdata43(cdata3(text))
def markup_as_screen41 (text):
    """ used for non-star lines in comment blocks """
    return " <screen> " + s(cdata41(text), r"(?m)^", r" ") +" </screen> "

def file_comment2section(text):
    """ convert a C comment into a series of <para> and <screen> parts """
    return ("<para>\n"+
            s(s(s(s(s(s(s(text,
                          r"(?s){<([\w\.\-]+\@[\w\.\-]+\w\w)>",
                          r"<\1>"),
                        r"(?mx) ^\s?\s?\s? ([^\*\s]+ .*) $",
                        lambda x : markup_as_screen41 (x.group(1))),
                      r"(?mx) ^\s*[*]\s* $", r" \n</para><para>\n"),
                    r"(?mx) ^\s?\s?\s?\* (.*) $", r" \1 "),
                  r"(?sx) </screen>(\s*)<screen> ", r"\1"),
                r"(?sx) <([^<>\;]+\@[^<>\;]+)> ", r"<email>\1</email>"),
              r"(?sx) \&lt\;([^<>\&\;]+\@[^<>\&\;]+)\&gt\; ",
              r"<email>\1</email>") + "\n</para>")
def func_comment2section(text):
    """ convert a C comment into a series of <para> and <screen> parts
        and sanitize a few markups already present in the comment text
    """
    return ("<para>\n"+
            s(s(s(s(s(s(s(s(s(s(s(text,
                                  r"<c>",r""),   r"</c>", r""),
                              r"(?mx) ^\s?\s?\s? ([^\*\s]+.*)",
                              lambda x: markup_as_screen41 (x.group(1))),
                            r"(?mx) ^\s?\s?\s?\* (.*) $", r"
 \1"),
                          r"(?mx) ^\s*
\s* $", r"\n</para><para>\n"),
                        r"<<",r"<"),   r">>",r">"),
                    r"(?sx) (</?para>\s*)
",r"\1"),
                  r"(?sx) (</?para>\s*)
",r"\1"),
                r"(?sx) (
\s*)
",r"\1"),
              r"(?sx) <\/screen>(\s*)<screen>",r"\1") + "\n</para>")
def markup_link_syntax(text):
    """ markup the link-syntax ` => somewhere ` in the text block """
    return (
        s(s(s(s(text,
                r"(?mx) (^|\s)\=\>\"([^\"]*)\"", r"\1<link>\2</link>"),
              r"(?mx) (^|\s)\=\>\'([^\"]*)\'", r"\1<link>\2</link>"),
            r"(?mx) (^|\s)\=\>\s(\w[\w.]*\w)\b", r"\1<link>\2</link>"),
          r"(?mx) (^|\s)\=\>\s([^\s\,\.\!\?\:\;\<\>\&\'\=\-]+)",
          r"\1<link>\2</link>"))
def this_function_link(text, name):
    return s(text, r"(?sx) (T|t)his \s (function|procedure) ", lambda x
             : "<function>"+x.group(1)+"he "+name+" "+x.group(2)+"</function>")

# -----------------------------------------------------------------------
class Options:
    var = {}
    def __getattr__(self, name):
        if not self.var.has_key(name): return None
        return self.var[name]
    def __setattr__(self, name, value):
        self.var[name] = value
#end

o = Options()
o.verbose = 0

o.version = s( commands.getoutput(
    """ grep -i "^version *:" *.spec 2>/dev/null |
        sed -e "s/[Vv]ersion *: *//" """),  r"\s*",r"")
o.package = s(commands.getoutput(
    """ grep -i "^name *:" *.spec 2>/dev/null |
        sed -e "s/[Nn]ame *: *//" """),     r"\s*",r"")

if not len(o.version):
    o.version = commands.getoutput(""" date +%Y.%m.%d """)
if not len(o.package):
    o.package = "_project"

o.suffix = "-doc3"
o.mainheader = o.package+".h"

class File:
    def __init__(self, filename):
        self.name = filename
        self.mainheader = o.mainheader
        self.authors = ""
        self.copyright = ""
    def __getattr__(self, name):
        """ defend against program to break on uninited members """
        if self.__dict__.has_key(name): return self.__dict__[name]
        warn("no such member: "+name); return None
    def set_author(self, text):
        if self.authors:
            self.authors += "\n"
        self.authors += text
        return text
    def set_copyright(self, text):
        self.copyright = text
        return text

class InputFiles:
    """ for each set of input files we can create an object
        it does correspond with a single html-output page and
        a single docbook <reference> master page to be output
    """
    def __init__(self):
        # the id will tell us in which order
        # we did meet each function definition
        self.id = 1000
        self.files = [] # file_list
        self.funcs = [] # func_list: of hidden class FuncDeclaration
        self.file = None # current file
    def new_File(self, name):
        self.file = File(name)
        self.files.append(self.file)
        return self.file
    def next_id(self):
        id = self.id ; self.id += 1
        return id
    def add_function_declaration(self, comment, prototype):
        class FuncDeclaration:    # note that both decl.comment and
            pass                  # decl.prototype are in cdata1 format
        func = FuncDeclaration()
        func.file = self.file
        func.comment = s(comment, # need to take out email-style markups
                         r"<([\w\.\-]+\@[\w\.\-]+\w\w)>", r"<\1>")
        func.prototype = prototype
        func.id = all.next_id()
        self.funcs.append(func)
        # print id
        return prototype

def scan_options (options, list):
    def encode(text):
        return s(s(text, r"¬",  r"&#AC;"), r"\*/",r"¬")
    def decode(text):
        return s(text, r"¬", r"*/")

    for name in options:
        found = m(name, r"^(\w+)=(.*)")
        if found:
            o.var[found.group(1)] = found.group(2)
            continue
        #else
        try:
            input = open(name, "r")
        except IOError, error:
            warn(#...... (scan_options) ...............
                "can not open input file: "+name, error)
            continue
        text = input.read() ; input.close()
        text = encode (cdata1 (text))

        file = list.new_File(name)

        # cut per-function comment block
        text = s(text, r"(?x) [/][*][*](?=\s) ([^¬]+) ¬ ([^\{\}\;\#]+) [\{\;]",
                 lambda x : list.add_function_declaration(
            decode(x.group(1)), decode(x.group(2))))

        # cut per-file comment block
        found = m(text, r"(?sx)  [/][*]+(?=\s) ([^¬]+) ¬ "
                  r"(?:\s*\#define\s*\S+)*"
                  r"(\s*\#include\s*<[^<>]*>(?:\s*//[^\n]*)?)")
        if found:
            file.comment = decode(found.group(1))
            file.include = cdata31(found.group(2))
        else:
            file.comment = None
            file.include = None
            found = m(text, r"(?sx)  ^ [/][*]+(?=\s) ([^¬]+) ¬ ")
            if found:
                file.comment = decode(found.group(1))
        #fi
        # throw away the rest - further processing on memorized strings only

    return None

all = InputFiles()
scan_options (sys.argv[1:], all)

if not o.docbookfile:
    o.docbookfile = o.package+o.suffix+".docbook"
if not o.libhtmlfile:
    o.libhtmlfile = o.package+o.suffix+".html"
if not o.dumpdocfile:
    o.dumpdocfile = o.package+o.suffix+".dxml"

# ...........................................................................
# check out information in the file.comment section

def all_files_comment2section(list):
    for file in list:
        if file.comment is None: continue
        file.section = file_comment2section(file.comment)

        file.section = s(
            file.section, r"(?sx) \b[Aa]uthor\s*:(.*</email>) ", lambda x
            : "<author>" + file.set_author(x.group(1)) + "</author>")
        file.section = s(
            file.section, r"(?sx) \b[Cc]opyright\s*:([^<>]*)</para> ",lambda x
            : "<copyright>" + file.set_copyright(x.group(1)) + "</copyright>")
        # if "file" in file.name: print >> sys.stderr, file.comment # 2.3
    #od
all_files_comment2section(all.files)

# -----------------------------------------------------------------------

class Function:
    " <prespec>void* </><namespec>hello</><namespec> (int) const</callspec> "
    def __init__(self):
        self.prespec  = ""
        self.namespec = ""
        self.callspec = ""
        self.name = ""
#    def set(self, **defines):
#        name = defines.keys()[0]
#        self.__dict__[name] = defines[name]
#        return defines[name]
#    def cut(self, **defines):
#        name = defines.keys()[0]
#        self.__dict__[name] += defines[name]
#        return ""
    def __getattr__(self, name):
        """ defend against program exit on members being not inited """
        if self.__dict__.has_key(name): return self.__dict__[name]
        warn("no such member: "+name); return None
    def dict(self):
        return self.__dict__
    def dict_sorted_keys(self):
        keys = self.__dict__.keys()
        keys.sort()
        return keys
    def parse(self, prototype):
        found = m(prototype, r"(?sx) ^(.*[^.]) \b(\w[\w.]*\w)\b (\s*\(.*) $ ")
        if found:
            self.prespec = found.group(1).lstrip()
            self.namespec = found.group(2)
            self.callspec = found.group(3).lstrip()
            self.name = self.namespec.strip()
            return self.name
        return None

# pass 1 of per-func strings ...............................................
# (a) cut prototype into prespec/namespec/callspec
# (b) cut out first line of comment as headline information
# (c) sanitize rest of comment block into proper docbook formatted .body
#
# do this while copying strings from all.funcs to function_list
# and remember the original order in name_list

def markup_callspec(text):
    return (
        s(s(s(s(s(text,
                  r"(?sx) ^([^\(\)]*)\(", r"\1<parameters>(<paramdef>",1),
                r"(?sx) \)([^\(\)]*)$", r"</paramdef>)</parameters>\1",1),
              r"(?sx) , ", r"</paramdef>,<paramdef>"),
            r"(?sx) <paramdef>(\s+) ", r"\1<paramdef>"),
          r"(?sx) (\s+)</paramdef>", r"</paramdef>\1"))

def parse_all_functions(func_list): # list of FunctionDeclarations
    """ parse all FunctionDeclarations and create a list of Functions """
    list = []
    for func in all.funcs:
        function = Function()
        if not function.parse (func.prototype): continue

        list.append(function)

        function.body = markup_link_syntax(func.comment)
        if "\n" not in function.body: # single-line comment is the head
            function.head = function.body
            function.body = ""
        else: # cut comment in first-line and only keep the rest as descr body
            function.head = s(function.body,  r"(?sx) ^([^\n]*\n).*",r"\1",1)
            function.body = s(function.body,  r"(?sx)  ^[^\n]*\n",   r"",  1)
        #fi
        if m(function.head, r"(?sx) ^\s*$ "): # empty head line, autofill here
            function.head = s("("+func.file.name+")", r"[.][.][/]", r"")

        function.body = func_comment2section(function.body)
        function.src = func # keep a back reference

        # add extra docbook markups to callspec in $fn-hash
        function.callspec = markup_callspec (function.callspec)
    #od
    return list
function_list = parse_all_functions(all.funcs)

def examine_head_anchors(func_list):
    """ .into tells later steps which func-name is the leader of a man
        page and that this func should add its descriptions over there. """
    for function in func_list:
        function.into = None
        function.seealso = None

        found = m(function.head, r"(?sx) ^ \s* <link>(\w[\w.]*\w)<\/link>")
        # if found and found.group(1) in func_list.names:
        if found and found.group(1):
            function.into = found.group(1)

        def set_seealso(f, value):
            f.seealso = value
            return value
        function.head = s(function.head, r"(.*)also:(.*)", lambda x
                          : set_seealso(function, x.group(2)) and x.group(1))
        if function.seealso and None:
            print "function[",function.name,"].seealso=",function.seealso
examine_head_anchors(function_list)

# =============================================================== HTML =====

def find_by_name(func_list, name):
    for func in func_list:
        if func.name == name:
            return func
    #od
    return None
#fu

class HtmlFunction:
    def __init__(self, func):
        self.src = func.src
        self.into = func.into
        self.name = func.name
        self.toc_line = paramdef2html(
            "  "+func.prespec+"	\n"+
            "    	\n"+
            "  \n"+
            "                       "+func.namespec+""+
            "  	\n"+
            "    	\n"+
            "  "+func.callspec+"	\n")
        self.synopsis = paramdef2html(
            "  "+func.prespec+"\n"+
            "
"+func.namespec+"\n"+
            "     "+func.callspec+"\n")
        self.anchor = ""
        self.section = "<para>  "+func.head+"\n"+ \
                       "\n</para>"+section2html(func.body)
#class

class HtmlFunctionFamily(HtmlFunction):
    def __init__(page, func):
        HtmlFunction.__init__(page, func)
        page.toc_line_list = [ page.toc_line ]
        # page.html_txt     = page.synopsis
        page.synopsis_list = [ page.synopsis ]
        page.anchor_list   = [ page.anchor ]
        page.section_list  = [ this_function_link(page.section, func.name) ]

def ensure_name(text, name):
    adds = ""+name+" -"
    match = r"(?sx) .*>[^<>]*\b" + name + r"\b[^<>]*<.*"
    found = m(text, match)
    if found: return text
    found = m(text, r".*
.*")
    if found: return s(text, r"(
)", r"\1"+adds, 1)
    return adds+text

def combined_html_pages(func_list):
    """ and now add descriptions of non-leader entries (html-mode) """
    combined = {}

    for func in func_list: # assemble leader pages
        if func.into is not None: continue
        combined[func.name] =  HtmlFunctionFamily(func)

    for func in func_list:
        if func.into is None: continue
        if func.into not in combined :
            warn(#......... (combine_html_pages) ..............
                "function '"+func.name+"'s into => '"+func.into+
                "\n: no such target function: "+func.into)
            combined[func.name] = HtmlFunctionFamily(func)
            continue
        #fi
        page = HtmlFunction(func)
        into = combined[func.into]
        into.toc_line_list.append( page.toc_line )
        into.anchor_list.append( page.anchor )
        into.synopsis_list.append( page.synopsis )
        into.section_list.append(
            s(ensure_name(this_function_link(section2html( func.body ),
                                             func.name), func.name),
              r"(?sx) (</?para>\s*)
", r"\1"))
    return combined.values()
html_pages = combined_html_pages(function_list)

def html_resolve_links_on_page(text, list):
    """ link ref-names of a page with its endpoint on the same html page"""
    def html_link (name , extra):
        """ make <link>s to <href> of correct target or make it  """
        if find_by_name(list, name) is None:
            return ""+name+extra+""
        else:
            return ""+name+extra+""
    #fu html_link
    return s(s(text, r"(?sx) <link>(\w+)([^<>]*)<\/link> ",
               lambda x : html_link(x.group(1),x.group(2))),
             r"(?sx) \-\> ", r"->") # just sanitize..
#fu html_resolve_links

class HtmlPage:
    def __init__(self):
        self.toc = ""
        self.txt = ""
        self.package = o.package
        self.version = o.version
    def page_text(self):
        """ render .toc and .txt parts into proper  page """
        T = ""
        T += ""
        T += "<title>"+self.package+"autodoc documentation </title>"
        T += "\n\n"
        T += "\n
"+self.package+" - "+self.version
        T += "
"
        T += "\n
"
        T +=  self.toc
        T += "\n
"
        T += "\n
Documentation
\n\n
"
        T += html_resolve_links_on_page(self.txt, function_list)
        T += "\n
\n\n"
        return T
    def add_page_map(self, list):
        """ generate the index-block at the start of the onepage-html file """
        keys = list.keys()
        keys.sort()
        for name in keys:
            self.toc += "
\n"+ \
                        "\n

\n".join(
                list[name].toc_line_list)+"
\n"
            self.txt += "\n
"+" ".join(list[name].anchor_list)
            self.txt += "\n"+"\n
".join(list[name].synopsis_list)+"
"
            self.txt += "\n
\n"+"\n".join(list[name].section_list)
            self.txt += ("\n
"+
                         "("+list[name].src.file.name+")"+
                         "

")
    def add_page_list(self, functions):
        """ generate the index-block at the start of the onepage-html file """
        mapp = {}
        for func in functions:
            mapp[func.name] = func
        #od
        self.add_page_map(mapp)
#end

html = HtmlPage()
# html.add_function_dict(Fn)
# html.add_function_list(Fn.sort.values())
html.add_page_list(html_pages)

# and finally print the html-formatted output
try:
    F = open(o.libhtmlfile, "w")
except IOError, error:
    warn(# ............. open(o.libhtmlfile, "w") ..............
        "can not open html output file: "+o.libhtmlfile, error)
else:
    print >> F, html.page_text()
    F.close()
#fi

# ========================================================== DOCBOOK =====
# let's go for the pure docbook, a reference type master for all man pages

class RefPage:
    def __init__(self, func):
        """ initialize the fields needed for a man page entry - the fields are
           named after the docbook-markup that encloses (!!) the text we store
           the entries like X.refhint = "hello" will be printed therefore as
           <refhint>hello</refhint>. Names with underscores are only used as
           temporaries but they are memorized, perhaps for later usage. """
        self.refhint = "\n\n"
        self.refentry = None
        self.refentry_date = o.version.strip()        # //refentryinfo/date
        self.refentry_productname = o.package.strip() # //refentryinfo/prod*
        self.refentry_title = None                    # //refentryinfo/title
        self.refentryinfo = None                      # override
        self.manvolnum = "3"                         # //refmeta/manvolnum
        self.refentrytitle = None                    # //refmeta/refentrytitle
        self.refmeta = None                          # override
        self.refpurpose = None                       # //refnamediv/refpurpose
        self.refname = None                          # //refnamediv/refname
        self.refname_list = []
        self.refnamediv = None                       # override
        self.mainheader = func.src.file.mainheader
        self.includes = func.src.file.include
        self.funcsynopsisinfo = ""       # //funcsynopsisdiv/funcsynopsisinfo
        self.funcsynopsis = None         # //funcsynopsisdiv/funcsynopsis
        self.funcsynopsis_list = []
        self.description = None
        self.description_list = []
        # optional sections
        self.authors_list = []           # //sect1[authors]/listitem
        self.authors = None              # override
        self.copyright = None
        self.copyright_list = []
        self.seealso = None
        self.seealso_list = []
        if  func.seealso:
            self.seealso_list.append(func.seealso)
        # func.func references
        self.func = func
        self.file_authors = None
        if  func.src.file.authors:
            self.file_authors = func.src.file.authors
        self.file_copyright = None
        if  func.src.file.copyright:
            self.file_copyright = func.src.file.copyright
    #fu
    def refentryinfo_text(page):
        """ the manvol formatter wants to render a footer line and header line
            on each manpage and such info is set in <refentryinfo> """
        if page.refentryinfo:
            return page.refentryinfo
        if page.refentry_date and \
           page.refentry_productname and \
           page.refentry_title: return (
            "\n <date>"+page.refentry_date+"</date>"+
            "\n <productname>"+page.refentry_productname+"</productname>"+
            "\n <title>"+page.refentry_title+"</title>")
        if page.refentry_date and \
           page.refentry_productname: return (
            "\n <date>"+page.refentry_date+"</date>"+
            "\n <productname>"+page.refentry_productname+"</productname>")
        return ""
    def refmeta_text(page):
        """ the manvol formatter needs to know the filename of the manpage to
            be made up and these parts are set in <refmeta> actually """
        if page.refmeta:
            return page.refmeta
        if page.manvolnum and page.refentrytitle:
            return (
                "\n <refentrytitle>"+page.refentrytitle+"</refentrytitle>"+
                "\n <manvolnum>"+page.manvolnum+"</manvolnum>")
        if page.manvolnum and page.func.name:
            return (
                "\n <refentrytitle>"+page.func.name+"</refentrytitle>"+
                "\n <manvolnum>"+page.manvolnum+"</manvolnum>")
        return ""
    def refnamediv_text(page):
        """ the manvol formatter prints a header line with a <refpurpose> line
            and <refname>'d functions that are described later. For each of
            the <refname>s listed here, a mangpage is generated, and for each
            of the <refname>!=<refentrytitle> then a symlink is created """
        if page.refnamediv:
            return page.refnamediv
        if page.refpurpose and page.refname:
            return ("\n <refname>"+page.refname+'</refname>'+
                    "\n <refpurpose>"+page.refpurpose+" </refpurpose>")
        if page.refpurpose and page.refname_list:
            T = ""
            for refname in page.refname_list:
                T += "\n <refname>"+refname+'</refname>'
            T += "\n <refpurpose>"+page.refpurpose+" </refpurpose>"
            return T
        return ""
    def funcsynopsisdiv_text(page):
        """ refsynopsisdiv shall be between the manvol mangemaent information
            and the reference page description blocks """
        T=""
        if page.funcsynopsis:
            T += "\n<funcsynopsis>"
            if page.funcsynopsisinfo:
                T += "\n<funcsynopsisinfo>"+    page.funcsynopsisinfo + \
                     "\n</funcsynopsisinfo>\n"
            T += page.funcsynopsis + \
                 "\n</funcsynopsis>\n"
        if page.funcsynopsis_list:
            T += "\n<funcsynopsis>"
            if page.funcsynopsisinfo:
                T += "\n<funcsynopsisinfo>"+    page.funcsynopsisinfo + \
                     "\n</funcsynopsisinfo>\n"
            for funcsynopsis in page.funcsynopsis_list:
                T += funcsynopsis
            T += "\n</funcsynopsis>\n"
        #fi
        return T
    def description_text(page):
        """ the description section on a manpage is the main part. Here
            it is generated from the per-function comment area. """
        if page.description:
            return page.description
        if page.description_list:
            T = ""
            for description in page.description_list:
                if not description: continue
                T += description
            if T: return T
        return ""
    def authors_text(page):
        """ part of the footer sections on a manpage and a description of
            original authors. We prever an itimizedlist to let the manvol
            show a nice vertical aligment of authors of this ref item """
        if page.authors:
            return page.authors
        if page.authors_list:
            T = "<itemizedlist>"
            previous=""
            for authors in page.authors_list:
                if not authors: continue
                if previous == authors: continue
                T += "\n <listitem><para>"+authors+"</para></listitem>"
                previous = authors
            T += "</itemizedlist>"
            return T
        if page.authors:
            return page.authors
        return ""
    def copyright_text(page):
        """ the copyright section is almost last on a manpage and purely
            optional. We list the part of the per-file copyright info """
        if page.copyright:
            return page.copyright
        """ we only return the first valid instead of merging them """
        if page.copyright_list:
            T = ""
            for copyright in page.copyright_list:
                if not copyright: continue
                return copyright # !!!
        return ""
    def seealso_text(page):
        """ the last section on a manpage is called 'SEE ALSO' usally and
            contains a comma-separated list of references. Some manpage
            viewers can parse these and convert them into hyperlinks """
        if page.seealso:
            return page.seealso
        if page.seealso_list:
            T = ""
            for seealso in page.seealso_list:
                if not seealso: continue
                if T: T += ", "
                T += seealso
            if T: return T
        return ""
    def refentry_text(page, id=None):
        """ combine fields into a proper docbook refentry """
        if id is None:
            id = page.refentry
        if id:
            T = '<refentry id="'+id+'">'
        else:
            T = '<refentry>' # this is an error

        if page.refentryinfo_text():
            T += "\n<refentryinfo>"+       page.refentryinfo_text()+ \
                 "\n</refentryinfo>\n"
        if page.refmeta_text():
            T += "\n<refmeta>"+            page.refmeta_text() + \
                 "\n</refmeta>\n"
        if page.refnamediv_text():
            T += "\n<refnamediv>"+         page.refnamediv_text() + \
                 "\n</refnamediv>\n"
        if page.funcsynopsisdiv_text():
            T += "\n<refsynopsisdiv>\n"+   page.funcsynopsisdiv_text()+ \
                 "\n</refsynopsisdiv>\n"
        if page.description_text():
            T += "\n<refsect1><title>Description</title> " + \
                 page.description_text() + "\n</refsect1>"
        if page.authors_text():
            T += "\n<refsect1><title>Author</title> " + \
                 page.authors_text() + "\n</refsect1>"
        if page.copyright_text():
            T += "\n<refsect1><title>Copyright</title> " + \
                 page.copyright_text() + "\n</refsect1>\n"
        if page.seealso_text():
            T += "\n<refsect1><title>See Also</title><para> " + \
                 page.seealso_text() + "\n</para></refsect1>\n"

        T +=  "\n</refentry>\n"
        return T
    #fu
#end

# -----------------------------------------------------------------------
class FunctionRefPage(RefPage):
    def reinit(page):
        """ here we parse the input function for its values """
        if page.func.into:
            page.refhint = "\n              \n"
        #fi
        page.refentry = page.func.name               # //refentry@id
        page.refentry_title = page.func.name.strip() # //refentryinfo/title
        page.refentrytitle = page.func.name          # //refmeta/refentrytitle
        if page.includes:
            page.funcsynopsisinfo += "\n"+page.includes
        if not page.funcsynopsisinfo:
            page.funcsynopsisinfo="\n"+' #include <'+page.mainheader+'>'
        page.refpurpose = page.func.head
        page.refname = page.func.name

        def funcsynopsis_of(func):
            return (
                "\n <funcprototype>\n <funcdef>"+func.prespec+
                " <function>"+func.name+"</function></funcdef>"+
                "\n"+s(s(s(func.callspec,
                           r"<parameters>\s*\(",r" "),
                         r"\)\s*</parameters>",r" "),
                       r"</paramdef>\s*,\s*",r"</paramdef>\n ")+
                " </funcprototype>")
        page.funcsynopsis = funcsynopsis_of(page.func)

        page.description = (
            html2docbook(this_function_link(page.func.body, page.func.name)))

        if page.file_authors:
            def add_authors(page, ename, email):
                page.authors_list.append( ename+' '+email )
                return ename+email
            s(page.file_authors,
              r"(?sx) \s* ([^<>]*) (<email>[^<>]*</email>) ", lambda x
              : add_authors(page, x.group(1), x.group(2)))
        #fi

        if page.file_copyright:
            page.copyright = "<screen>\n"+page.file_copyright+"</screen>\n"
        #fi
        return page
    def __init__(page,func):
        RefPage.__init__(page, func)
        FunctionRefPage.reinit(page)

def refpage_list_from_function_list(funclist):
    list = []
    mapp = {}
    for func in funclist:
        mapp[func.name] = func
    #od
    for func in funclist:
        page = FunctionRefPage(func)
        if func.into and func.into not in mapp:
            warn (# ............ (refpage_list_from_function_list) .......
                "page '"+page.func.name+"' has no target => "+
                "'"+page.func.into+"'"
                "\n: going to reset .into of Function '"+page.func.name+"'")
            func.into = None
        #fi
        list.append(FunctionRefPage(func))
    return list
#fu

# ordered list of pages
refpage_list = refpage_list_from_function_list(function_list)

class FunctionFamilyRefPage(RefPage):
    def __init__(self, page):
        RefPage.__init__(self, page.func)
        self.seealso_list = [] # reset
        self.refhint_list = []
    def refhint_list_text(page):
        T = ""
        for hint in page.refhint_list:
            T += hint
        return T
    def refentry_text(page):
        return page.refhint_list_text() + "\n" + \
               RefPage.refentry_text(page)
    pass

def docbook_pages_recombine(pagelist):
    """ take a list of RefPages and create a new list where sections are
        recombined in a way that their description is listed on the same
        page and the manvol formatter creates symlinks to the combined
        function description page - use the attribute 'into' to guide the
        processing here as each of these will be removed from the output
        list. If no into-pages are there then the returned list should
        render to the very same output text like the input list would do """

    list = []
    combined = {}
    for orig in pagelist:
        if orig.func.into: continue
        page = FunctionFamilyRefPage(orig)
        combined[orig.func.name] = page ; list.append(page)

        page.refentry = orig.refentry              # //refentry@id
        page.refentry_title = orig.refentrytitle   # //refentryinfo/title
        page.refentrytitle = orig.refentrytitle    # //refmeta/refentrytitle
        page.includes = orig.includes
        page.funcsynopsisinfo = orig.funcsynopsisinfo
        page.refpurpose = orig.refpurpose
        if orig.refhint:
            page.refhint_list.append( orig.refhint )
        if orig.refname:
            page.refname_list.append( orig.refname )
        elif orig.refname_list:
            page.refname_list.extend( orig.refname_list )
        if orig.funcsynopsis:
            page.funcsynopsis_list.append( orig.funcsynopsis )
        elif orig.refname_list:
            page.funcsynopsis_list.extend( orig.funcsynopsis_list )
        if orig.description:
            page.description_list.append( orig.description )
        elif orig.refname_list:
            page.description_list.extend( orig.description_list )
        if orig.seealso:
            page.seealso_list.append( orig.seealso )
        elif orig.seealso_list:
            page.seealso_list.extend( orig.seealso_list )
        if orig.authors:
            page.authors_list.append( orig.authors )
        elif orig.authors_list:
            page.authors_list.extend( orig.authors_list )
        if orig.copyright:
            page.copyright_list.append( orig.copyright )
        elif orig.refname_list:
            page.copyright_list.extend( orig.copyright_list )
    #od
    for orig in pagelist:
        if not orig.func.into: continue
        if orig.func.into not in combined:
            warn("page for '"+orig.func.name+
                 "' has no target => '"+orig.func.into+"'")
            page = FunctionFamilyRefPage(orig)
        else:
            page = combined[orig.func.into]

        if orig.refname:
            page.refname_list.append( orig.refname )
        elif orig.refname_list:
            page.refname_list.extend( orig.refname_list )
        if orig.funcsynopsis:
            page.funcsynopsis_list.append( orig.funcsynopsis )
        elif orig.refname_list:
            page.funcsynopsis_list.extend( orig.funcsynopsis_list )
        if orig.description:
            page.description_list.append( orig.description )
        elif orig.refname_list:
            page.description_list.extend( orig.description_list )
        if orig.seealso:
            page.seealso_list.append( orig.seealso )
        elif orig.seealso_list:
            page.seealso_list.extend( orig.seealso_list )
        if orig.authors:
            page.authors_list.append( orig.authors )
        elif orig.authors_list:
            page.authors_list.extend( orig.authors_list )
        if orig.copyright:
            page.copyright_list.append( orig.copyright )
        elif orig.refname_list:
            page.copyright_list.extend( orig.copyright_list )
    #od
    return list
#fu

combined_pages = docbook_pages_recombine(pagelist = refpage_list)

# -----------------------------------------------------------------------

class HeaderRefPage(RefPage):
    pass

def docbook_refpages_perheader(page_list): # headerlist
    " creating the per-header manpage - a combination of function man pages "
    header = {}
    for page in page_list:
        assert not page.func.into
        file = page.func.src.file.mainheader # short for the mainheader index
        if file not in header:
            header[file] = HeaderRefPage(page.func)
            header[file].id = s(file, r"[^\w\.]","-")
            header[file].refentry = header[file].id
            header[file].refentryinfo = None
            header[file].refentry_date = page.refentry_date
            header[file].refentry_productname = (
                "the library "+page.refentry_productname)
            header[file].manvolnum = page.manvolnum
            header[file].refentrytitle = file
            header[file].funcsynopsis = ""
        if 1: # or += or if not header[file].refnamediv:
            header[file].refpurpose = " library "
            header[file].refname = header[file].id

        if not header[file].funcsynopsisinfo and page.funcsynopsisinfo:
            header[file].funcsynopsisinfo  = page.funcsynopsisinfo
        if page.funcsynopsis:
            header[file].funcsynopsis  += "\n"+page.funcsynopsis
        if not header[file].copyright and page.copyright:
            header[file].copyright = page.copyright
        if not header[file].authors and page.authors:
            header[file].authors = page.authors
        if not header[file].authors and page.authors_list:
            header[file].authors_list = page.authors_list
        if not header[file].description:
            found = m(commands.getoutput("cat "+o.package+".spec"),
                      r"(?s)\%description\b([^\%]*)\%")
            if found:
                header[file].description = found.group(1)
            elif not header[file].description:
                header[file].description = "<para>" + (
                    page.refentry_productname + " library") + "</para>";
            #fi
        #fi
    #od
    return header#list
#fu

def leaders(pagelist):
    list = []
    for page in pagelist:
        if page.func.into : continue
        list.append(page)
    return list
header_refpages = docbook_refpages_perheader(leaders(refpage_list))

# -----------------------------------------------------------------------
# printing the docbook file is a two-phase process - we spit out the
# leader pages first - later we add more pages with _refstart pointing
# to the leader page, so that xmlto will add the functions there. Only the
# leader page contains some extra info needed for troff page processing.

doctype = '<!DOCTYPE reference PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"'
doctype += "\n     "
doctype += '"http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">'+"\n"

try:
    F = open(o.docbookfile,"w")
except IOError, error:
    warn("can not open docbook output file: "+o.docbookfile, error)
else:
    print >> F, doctype, '<reference><title>Manual Pages</title>'

    for page in combined_pages:
        print >> F, page.refentry_text()
    #od

    for page in header_refpages.values():
        if not page.refentry: continue
        print >> F, "\n",
        print >> F, page.refentry_text()
    #od

    print >> F, "\n",'</reference>',"\n"
    F.close()
#fi

# _____________________________________________________________________
try:
    F = open( o.dumpdocfile, "w")
except IOError, error:
    warn ("can not open"+o.dumpdocfile,error)
else:
    for func in function_list:
        name = func.name
        print >> F, "<fn id=\""+name+"\">"+"\n"
        for H in sorted_keys(func.dict()):
            print >> F, "<"+H+" name=\""+name+"\">",
            print >> F, str(func.dict()[H]),
            print >> F, "</"+H+">"
        #od
        print >> F, "</fn>\n\n";
    #od
    F.close();
#fi

if errors: sys.exit(errors)


text:
import Ember from 'ember';
import SlideController from './slide';

import data from '../models/data';

import two_ranges from '../models/multi_group/two_ranges';
import three_ranges from '../models/multi_group/three_ranges';
import five_ranges from '../models/multi_group/five_ranges';
import sector_compare_return from '../models/multi_group/sector_compare_return';

import asset_values from '../models/single_group/asset_values';
import many_values from '../models/single_group/many_values';
import monthly_return_single_period from '../models/time_series/monthly_return_single_period';
import high_net_worth_duration from '../models/single_group/high_net_worth_duration';

import one_value from '../models/single_group/one_value';
import two_values from '../models/single_group/two_values';
import zero from '../models/single_group/zero';
import zeroes from '../models/single_group/zeroes';
import sum_to_zero from '../models/single_group/sum_to_zero';
import bad_range from '../models/single_group/bad_range';

export default SlideController.extend({

  // ---------
  // Default Settings
  // ---------

  betweenGroupPadding: 0,
  withinGroupPadding: 0,
  maxLabelHeight: 40,
  stackBars: false,

  hasXAxisTitle: false,
  hasYAxisTitle: false,
  xValueDisplayName: 'X Axis',
  yValueDisplayName: 'Y Axis',

  // ---------
  // Data Selection
  // ---------

  availableDataSets: Ember.computed('rawDataHash', function() {
    return Ember.A(_.keys(this.get('rawDataHash')) );
  }),

  data: Ember.computed('selectedData', 'rawDataHash', function() {
    return this.get('rawDataHash')[this.get('selectedData')];
  }),

  rawDataHash: Ember.computed(function() {
  	return {
	    two_ranges: two_ranges,
	    three_ranges: three_ranges,
	    five_ranges: five_ranges,
	    sector_compare_return: sector_compare_return,
	    '----': data.null,
	    asset_values: asset_values,
	    many_values: many_values,
	    monthly_return_single_period: monthly_return_single_period,
	    high_net_worth_duration: high_net_worth_duration,

	    empty: data.empty,
	    one_value: one_value,
	    two_values: two_values,
	    zero: zero,
	    zeroes: zeroes,
	    sum_to_zero: sum_to_zero,
	    bad_range: bad_range
    };
  }),

  selectedData: 'five_ranges'

});

redpajama_set_name: RedPajamaGithub


text:
@interface GTCitysTableViewController ()

@end

@implementation GTCitysTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

@end


text:
class SfOpticon::Changes::Diff
  ##
  # Generates a basic changeset between to snapshots of the same environment.
  #
  # @param orig_snap
  # @param new_snap
  # @return Array A list of the changes between snapshots
  def self.snap_diff(orig_snap, new_snap)
    log = SfOpticon::Logger
    changes = SfOpticon::Changes::Queue.new

    # Make a simple sf id search array to check for adds and deletes
    orig_snap_ids, new_snap_ids = Hash.new, Hash.new
    orig_snap.each do |o|
      orig_snap_ids[o[:sfobject_id]] = o
    end
    new_snap.each do |o|
      new_snap_ids[o[:sfobject_id]] = o
    end

    # And perform the deletion check
    (orig_snap_ids.keys - new_snap_ids.keys).each do |key|
      log.info { "Deletion detected: #{orig_snap_ids[key][:full_name]}"}
      changes.deletions << SfOpticon::Changes::Deletion.new(orig_snap_ids[key])
    end

    # Now perform the addition check
    (new_snap_ids.keys - orig_snap_ids.keys).each do |key|
      log.info { "Addition detected: #{new_snap_ids[key][:full_name]}" }
      changes.additions << SfOpticon::Changes::Addition.new(new_snap_ids[key])
    end

    # Now mods
    (orig_snap_ids.keys & new_snap_ids.keys).each do |key|
      # Last mod times
      o_last_m = orig_snap_ids[key][:last_modified_date]
      n_last_m = new_snap_ids[key][:last_modified_date]

      # Full names and file names to catch renames
      o_full_name = orig_snap_ids[key][:full_name]
      n_full_name = new_snap_ids[key][:full_name]
      o_file_name = orig_snap_ids[key][:file_name]
      n_file_name = new_snap_ids[key][:file_name]

      if o_last_m != n_last_m
        log.info { "Modification detected: #{orig_snap_ids[key][:full_name]}" }
        if o_full_name != n_full_name || o_file_name != n_file_name
          log.warn { "WARNING: Object renames are not able to be handled in the Metadata API. This action will create a new object upon deploy." }
          log.info { "#{orig_snap_ids[key]} has been renamed to #{new_snap_ids[key][:full_name]}" }
          changes.deletions << SfOpticon::Changes::Deletion.new(orig_snap_ids[key])
          changes.additions << SfOpticon::Changes::Addition.new(new_snap_ids[key])
        else
          changes.modifications << SfOpticon::Changes::Modification.new(new_snap_ids[key])
        end
      end
    end

    changes
  end
end


text:
    <link rel="stylesheet" href="styles/map.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">

          Return to Search


text:
require 'spec_helper'
module Alf
  describe Keys, "if_empty" do

    context 'with an arg' do
      subject{ keys.if_empty([ [:foo] ]) }

      context 'when empty' do
        let(:keys){ Keys[] }
        let(:expected){ Keys[ [:foo] ] }

        it{ should eq(expected) }
      end

      context 'when not empty' do
        let(:keys){ Keys[ [:a] ] }

        it{ should be(keys) }
      end
    end

    context 'with a block' do
      subject{ keys.if_empty{ [ [:foo] ] } }

      context 'when empty' do
        let(:keys){ Keys[] }
        let(:expected){ Keys[ [:foo] ] }

        it{ should eq(expected) }
      end

      context 'when not empty' do
        let(:keys){ Keys[ [:a] ] }

        it{ should be(keys) }
      end
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>io.prestosql</groupId>
        <artifactId>presto-root</artifactId>
        <version>309-SNAPSHOT</version>
    </parent>

    <artifactId>presto-memory-context</artifactId>
    <description>Presto - Memory Tracking Framework</description>
    <name>presto-memory-context</name>

    <properties>
        <air.main.basedir>${project.parent.basedir}</air.main.basedir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>units</artifactId>
        </dependency>

        <!-- for testing -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>testing</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
class EyeTracking extends BaseDemo {
    private _scale: number = 0.3;
    private readonly _target: PIXI.Point = new PIXI.Point();
    private readonly _animationNames: string[] = [
        "PARAM_ANGLE_X",
        "PARAM_ANGLE_Y",
        "PARAM_ANGLE_Z",
        "PARAM_EYE_BALL_X",
        "PARAM_EYE_BALL_Y",
        "PARAM_BODY_X",
        "PARAM_BODY_Y",
        "PARAM_BODY_Z",
        "PARAM_BODY_ANGLE_X",
        "PARAM_BODY_ANGLE_Y",
        "PARAM_BODY_ANGLE_Z",
        "PARAM_BREATH",
    ];
    private _armatureDisplay: dragonBones.PixiArmatureDisplay;

    public constructor() {
        super();

        this._resources.push(
            "resource/shizuku/shizuku_ske.json",
            "resource/shizuku/shizuku.1024/texture_00.png",
            "resource/shizuku/shizuku.1024/texture_01.png",
            "resource/shizuku/shizuku.1024/texture_02.png",
            "resource/shizuku/shizuku.1024/texture_03.png",
        );
    }

    protected _onStart(): void {
        const factory = dragonBones.PixiFactory.factory;
        factory.parseDragonBonesData(this._pixiResources["resource/shizuku/shizuku_ske.json"].data, "shizuku");
        factory.updateTextureAtlases(
            [
                this._pixiResources["resource/shizuku/shizuku.1024/texture_00.png"].texture,
                this._pixiResources["resource/shizuku/shizuku.1024/texture_01.png"].texture,
                this._pixiResources["resource/shizuku/shizuku.1024/texture_02.png"].texture,
                this._pixiResources["resource/shizuku/shizuku.1024/texture_03.png"].texture,
            ],
            "shizuku"
        );

        this._armatureDisplay = factory.buildArmatureDisplay("shizuku", "shizuku");
        this._armatureDisplay.animation.play("idle_00");

        this._armatureDisplay.x = 0.0;
        this._armatureDisplay.y = 200.0;
        this._armatureDisplay.scale.set(this._scale);
        this.addChild(this._armatureDisplay);

        //
        this.interactive = true;
        this.addListener('touchmove', this._touchHandler, this);
        this.addListener('mousemove', this._touchHandler, this);
        PIXI.ticker.shared.add(this._enterFrameHandler, this);
    }

    private _touchHandler(event: PIXI.interaction.InteractionEvent): void {
        this._setTarget(event.data.global.x, event.data.global.y);
    }

    private _setTarget(x: number, y: number) {
        this._target.x += ((x - this.x - this._armatureDisplay.x) / this._scale - this._target.x) * 0.3;
        this._target.y += ((y - this.y - this._armatureDisplay.y) / this._scale - this._target.y) * 0.3;
    }

    protected _enterFrameHandler(deltaTime: number): void {
        const armature = this._armatureDisplay.armature;
        const animation = this._armatureDisplay.animation;
        const canvas = armature.armatureData.canvas;

        let p = 0.0;
        const pX = Math.max(Math.min((this._target.x - canvas.x) / (canvas.width * 0.5), 1.0), -1.0);
        const pY = -Math.max(Math.min((this._target.y - canvas.y) / (canvas.height * 0.5), 1.0), -1.0);
        for (const animationName of this._animationNames) {
            if (!animation.hasAnimation(animationName)) {
                continue;
            }

            let animationState = animation.getState(animationName, 1);
            if (!animationState) {
                animationState = animation.fadeIn(animationName, 0.1, 1, 1, animationName);
                if (animationState) {
                    animationState.resetToPose = false;
                    animationState.stop();
                }
            }

            if (!animationState) {
                continue;
            }

            switch (animationName) {
                case "PARAM_ANGLE_X":
                case "PARAM_EYE_BALL_X":
                    p = (pX + 1.0) * 0.5;
                    break;

                case "PARAM_ANGLE_Y":
                case "PARAM_EYE_BALL_Y":
                    p = (pY + 1.0) * 0.5;
                    break;

                case "PARAM_ANGLE_Z":
                    p = (-pX * pY + 1.0) * 0.5;
                    break;

                case "PARAM_BODY_X":
                case "PARAM_BODY_ANGLE_X":
                    p = (pX + 1.0) * 0.5;
                    break;

                case "PARAM_BODY_Y":
                case "PARAM_BODY_ANGLE_Y":
                    p = (-pX * pY + 1.0) * 0.5;
                    break;

                case "PARAM_BODY_Z":
                case "PARAM_BODY_ANGLE_Z":
                    p = (-pX * pY + 1.0) * 0.5;
                    break;

                case "PARAM_BREATH":
                    p = (Math.sin(armature.clock.time) + 1.0) * 0.5;
                    break;
            }

            animationState.currentTime = p * animationState.totalTime;
        }
    }
}


text:
using EPiServer.Cms.UI.AspNetIdentity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
using System.Web;

[assembly: OwinStartup(typeof(rdContentArea.Startup))]

namespace rdContentArea
{
    public class Startup
    {

        public void Configuration(IAppBuilder app)
        {

            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity<ApplicationUser>();

            // Remove to block registration of administrators
            app.UseAdministratorRegistrationPage(() => HttpContext.Current.Request.IsLocal);

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString(Global.LoginPath),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });

        }
    }
}


text:
package org.apache.hadoop.hbase.quotas;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot.SpaceQuotaStatus;
import org.apache.hadoop.hbase.quotas.policies.DefaultViolationPolicyEnforcement;
import org.apache.hadoop.hbase.quotas.policies.MissingSnapshotViolationPolicyEnforcement;
import org.apache.hadoop.hbase.quotas.policies.NoWritesViolationPolicyEnforcement;
import org.apache.hadoop.hbase.regionserver.RegionServerServices;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Test class for {@link ActivePolicyEnforcement}.
 */
@Category(SmallTests.class)
public class TestActivePolicyEnforcement {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestActivePolicyEnforcement.class);

  private RegionServerServices rss;

  @Before
  public void setup() {
    rss = mock(RegionServerServices.class);
  }

  @Test
  public void testGetter() {
    final TableName tableName = TableName.valueOf("table");
    Map<TableName, SpaceViolationPolicyEnforcement> map = new HashMap<>();
    map.put(tableName, new NoWritesViolationPolicyEnforcement());
    ActivePolicyEnforcement ape = new ActivePolicyEnforcement(map, Collections.emptyMap(), null);
    assertEquals(map.get(tableName), ape.getPolicyEnforcement(tableName));
  }

  @Test
  public void testNoPolicyReturnsNoopEnforcement() {
    ActivePolicyEnforcement ape = new ActivePolicyEnforcement(new HashMap<>(),
      Collections.emptyMap(), mock(RegionServerServices.class));
    SpaceViolationPolicyEnforcement enforcement =
      ape.getPolicyEnforcement(TableName.valueOf("nonexistent"));
    assertNotNull(enforcement);
    assertTrue("Expected an instance of MissingSnapshotViolationPolicyEnforcement, but got "
      + enforcement.getClass(), enforcement instanceof MissingSnapshotViolationPolicyEnforcement);
  }

  @Test
  public void testNoBulkLoadChecksOnNoSnapshot() {
    ActivePolicyEnforcement ape =
      new ActivePolicyEnforcement(new HashMap<TableName, SpaceViolationPolicyEnforcement>(),
        Collections.<TableName, SpaceQuotaSnapshot> emptyMap(), mock(RegionServerServices.class));
    SpaceViolationPolicyEnforcement enforcement =
      ape.getPolicyEnforcement(TableName.valueOf("nonexistent"));
    assertFalse("Should not check bulkloads", enforcement.shouldCheckBulkLoads());
  }

  @Test
  public void testNoQuotaReturnsSingletonPolicyEnforcement() {
    final ActivePolicyEnforcement ape =
      new ActivePolicyEnforcement(Collections.emptyMap(), Collections.emptyMap(), rss);
    final TableName tableName = TableName.valueOf("my_table");
    SpaceViolationPolicyEnforcement policyEnforcement = ape.getPolicyEnforcement(tableName);
    // This should be the same exact instance, the singleton
    assertTrue(policyEnforcement == MissingSnapshotViolationPolicyEnforcement.getInstance());
    assertEquals(1, ape.getLocallyCachedPolicies().size());
    Entry<TableName, SpaceViolationPolicyEnforcement> entry =
      ape.getLocallyCachedPolicies().entrySet().iterator().next();
    assertTrue(policyEnforcement == entry.getValue());
  }

  @Test
  public void testNonViolatingQuotaCachesPolicyEnforcment() {
    final Map<TableName, SpaceQuotaSnapshot> snapshots = new HashMap<>();
    final TableName tableName = TableName.valueOf("my_table");
    snapshots.put(tableName, new SpaceQuotaSnapshot(SpaceQuotaStatus.notInViolation(), 0, 1024));
    final ActivePolicyEnforcement ape =
      new ActivePolicyEnforcement(Collections.emptyMap(), snapshots, rss);
    SpaceViolationPolicyEnforcement policyEnforcement = ape.getPolicyEnforcement(tableName);
    assertTrue("Found the wrong class: " + policyEnforcement.getClass(),
      policyEnforcement instanceof DefaultViolationPolicyEnforcement);
    SpaceViolationPolicyEnforcement copy = ape.getPolicyEnforcement(tableName);
    assertTrue("Expected the instance to be cached", policyEnforcement == copy);
    Entry<TableName, SpaceViolationPolicyEnforcement> entry =
      ape.getLocallyCachedPolicies().entrySet().iterator().next();
    assertTrue(policyEnforcement == entry.getValue());
  }

  @Test
  public void testViolatingQuotaCachesNothing() {
    final TableName tableName = TableName.valueOf("my_table");
    SpaceViolationPolicyEnforcement policyEnforcement = mock(SpaceViolationPolicyEnforcement.class);
    final Map<TableName, SpaceViolationPolicyEnforcement> activePolicies = new HashMap<>();
    activePolicies.put(tableName, policyEnforcement);
    final ActivePolicyEnforcement ape =
      new ActivePolicyEnforcement(activePolicies, Collections.emptyMap(), rss);
    assertTrue(ape.getPolicyEnforcement(tableName) == policyEnforcement);
    assertEquals(0, ape.getLocallyCachedPolicies().size());
  }
}


text:
package com.github.binarywang.wxpay.bean.payscore;

import com.google.gson.annotations.SerializedName;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 明细.
 *
 * @author doger.wang
 * created on  2020-05-19
 */
@Data
@NoArgsConstructor
public class Detail implements Serializable {
  private static final long serialVersionUID = -3901373259400050385L;
  /**
   * seq : 1
   * amount : 900
   * paid_type : NEWTON
   * paid_time : 20091225091210
   * transaction_id : 15646546545165651651
   */
  @SerializedName("seq")
  private int seq;
  @SerializedName("amount")
  private int amount;
  @SerializedName("paid_type")
  private String paidType;
  @SerializedName("paid_time")
  private String paidTime;
  @SerializedName("transaction_id")
  private String transactionId;
}


text:
'use strict';

var timer = require('./timer.js');

// Default to metrics on once probe has been started
var _enabled = true;

// Default to requests off
var _requestsEnabled = false;

// Not running by default
var _started = false;

function Probe(name) {
  this.name = name;
  this.config = {};
}

/*
 * Function to add instrumentation to the target module
 */
Probe.prototype.attach = function(name, target) {
  return target;
};

/*
 * Set configuration by merging passed in config with current one
 */
Probe.prototype.setConfig = function(newConfig) {
  for (var prop in newConfig) {
    if (typeof newConfig[prop] !== 'undefined') {
      this.config[prop] = newConfig[prop];
    }
  }
  if (this.config.filters) {
    this.config.filters.forEach(function(filter) {
      if (typeof filter.regex === 'undefined') {
        filter.regex = new RegExp(filter.pattern);
      }
    });
  }
};

/*
 * Lightweight metrics probes
 */
Probe.prototype.metricsStart = function(probeData) {
  probeData.timer = timer.start();
};

// Implentors should stop the timer and emit an event.
Probe.prototype.metricsEnd = function(probeData) {
  probeData.timer.stop();
};

/*
 * Heavyweight request probes
 */

Probe.prototype.requestStart = function(req, res, am) {};

Probe.prototype.requestEnd = function(req, res, am) {};

/*
 * Default to metrics off until started
 */
Probe.prototype.metricsProbeStart = function(req, res, am) {};
Probe.prototype.metricsProbeEnd = function(req, res, am) {};

/*
 * Default to requests off
 */
Probe.prototype.requestProbeStart = function(req, res, am) {};
Probe.prototype.requestProbeEnd = function(req, res, am) {};

Probe.prototype.enableRequests = function() {
  _requestsEnabled = true;
  if (_started) {
    this.requestProbeStart = this.requestStart;
    this.requestProbeEnd = this.requestEnd;
  }
};

Probe.prototype.disableRequests = function() {
  _requestsEnabled = false;
  this.requestProbeStart = function() {};
  this.requestProbeEnd = function() {};
};

Probe.prototype.enable = function() {
  _enabled = true;
  if (_started) {
    this.metricsProbeStart = this.metricsStart;
    this.metricsProbeEnd = this.metricsEnd;
  }
};

Probe.prototype.disable = function() {
  this.metricsProbeStart = function() {};
  this.metricsProbeEnd = function() {};
};

Probe.prototype.start = function() {
  _started = true;
  if (_enabled) {
    this.metricsProbeStart = this.metricsStart;
    this.metricsProbeEnd = this.metricsEnd;
  }
  if (_requestsEnabled) {
    this.requestProbeStart = this.requestStart;
    this.requestProbeEnd = this.requestEnd;
  }
};

Probe.prototype.stop = function() {
  _started = false;
  this.metricsProbeStart = function() {};
  this.metricsProbeEnd = function() {};
  this.requestProbeStart = function() {};
  this.requestProbeEnd = function() {};
};

module.exports = Probe;


text:
var win = Titanium.UI.currentWindow;

var webview = Titanium.UI.createWebView({
	url : '../webviews/about.html'
});
win.add(webview);


text:
package games

import (
	"bytes"
	"github.com/canopener/serverlog"
)

// Game/Server messages
type finishedMessage struct {
	mtype   uint8
	p1won   bool
	rounds  uint8
	p1score uint8
	p2score uint8
}

func newFinishedMessage(message []byte) finishedMessage {
	fmessage := finishedMessage{}
	buf := bytes.NewBuffer(message)
	b, err := buf.ReadByte()
	if err != nil {
		serverlog.Fatal("Decoding newFinishedMessage err:", err)
	}
	fmessage.mtype = uint8(b)

	b, err = buf.ReadByte()
	if err != nil {
		serverlog.Fatal("Decoding newFinishedMessage err:", err)
	}
	fmessage.p1won = uint8(b) == 255

	b, err = buf.ReadByte()
	if err != nil {
		serverlog.Fatal("Decoding newFinishedMessage err:", err)
	}
	fmessage.rounds = uint8(b)

	b, err = buf.ReadByte()
	if err != nil {
		serverlog.Fatal("Decoding newFinishedMessage err:", err)
	}
	fmessage.p1score = uint8(b)

	b, err = buf.ReadByte()
	if err != nil {
		serverlog.Fatal("Decoding newFinishedMessage err:", err)
	}
	fmessage.p2score = uint8(b)

	return fmessage
}


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\Yaml\Yaml;

use AppBundle\Entity\Moon;

class LoadMoons implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {

        $filename = __DIR__ . '/../../../../data/moons.yml';
        $yml = Yaml::parse(file_get_contents($filename));
        foreach ($yml as $item) {
            $moon = new Moon();
            $moon->setName($item['name']);
            $moon->setRadius($item['radius']);
            $manager->persist($moon);
        }

        $manager->flush();
    }
}


text:
package com.rackspacecloud.blueflood.types;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class SimpleNumberTest {

    @Test
    public void constructorWithIntegerSetsValue() {

        // given
        Object testValue = new Integer(4);

        // when
        SimpleNumber simpleNumber = new SimpleNumber(testValue);

        // then
        assertEquals(testValue, simpleNumber.getValue());
        assertEquals(SimpleNumber.Type.INTEGER, simpleNumber.getDataType());
        assertTrue(simpleNumber.hasData());
    }

    @Test
    public void constructorWithDoubleSetsValue() {

        // given
        Object testValue = new Double(5.0);

        // when
        SimpleNumber simpleNumber = new SimpleNumber(testValue);

        // then
        assertEquals(testValue, simpleNumber.getValue());
        assertEquals(SimpleNumber.Type.DOUBLE, simpleNumber.getDataType());
        assertTrue(simpleNumber.hasData());
    }

    @Test
    public void constructorWithLongSetsValue() {

        // given
        Object testValue = new Long(5L);

        // when
        SimpleNumber simpleNumber = new SimpleNumber(testValue);

        // then
        assertEquals(testValue, simpleNumber.getValue());
        assertEquals(SimpleNumber.Type.LONG, simpleNumber.getDataType());
        assertTrue(simpleNumber.hasData());
    }

    @Test
    public void constructorWithBoxedIntegerSetsValue() {

        // given
        Object testValue = 4;

        // when
        SimpleNumber simpleNumber = new SimpleNumber(testValue);

        // then
        assertEquals(testValue, simpleNumber.getValue());
        assertEquals(SimpleNumber.Type.INTEGER, simpleNumber.getDataType());
        assertTrue(simpleNumber.hasData());
    }

    @Test(expected = NullPointerException.class)
    public void constructorWithNullThrowsException() {

        // when
        SimpleNumber simpleNumber = new SimpleNumber(null);

        // then
        // the exception is thrown
    }

    @Test
    public void constructorWithSimpleNumberSetsValue() {

        // given
        Object testValue = new SimpleNumber(123L);

        // when
        SimpleNumber simpleNumber = new SimpleNumber(testValue);

        // then
        assertEquals(123L, simpleNumber.getValue());
        assertEquals(SimpleNumber.Type.LONG, simpleNumber.getDataType());
        assertTrue(simpleNumber.hasData());
    }

    @Test(expected = IllegalArgumentException.class)
    public void constructorWithFloatThrowsException() {

        // when
        SimpleNumber simpleNumber = new SimpleNumber(123.45f);

        // then
        // the exception is thrown
    }

    @Test(expected = IllegalArgumentException.class)
    public void constructorWithOtherTypeThrowsException() {

        // when
        SimpleNumber simpleNumber = new SimpleNumber(new Object());

        // then
        // the exception is thrown
    }

    @Test
    public void toStringWithIntegerPrintsIntegerString() {

        // given
        SimpleNumber sn = new SimpleNumber(123);

        // expect
        assertEquals("123 (int)", sn.toString());
    }

    @Test
    public void toStringWithLongPrintsLongString() {

        // given
        SimpleNumber sn = new SimpleNumber(123L);

        // expect
        assertEquals("123 (long)", sn.toString());
    }

    @Test
    public void toStringWithDoublePrintsDoubleString() {

        // given
        SimpleNumber sn = new SimpleNumber(123.45d);

        // expect
        assertEquals("123.45 (double)", sn.toString());
    }

    @Test
    public void rollupTypeIsNotTypical() {

        // given
        SimpleNumber sn = new SimpleNumber(123.45d);

        // expect
        assertEquals(RollupType.NOT_A_ROLLUP, sn.getRollupType());
    }

    @Test
    public void hashCodeIsValuesHashCode() {

        // given
        Double value = 123.45d;
        SimpleNumber sn = new SimpleNumber(value);

        // expect
        assertEquals(value.hashCode(), sn.hashCode());
    }

    @Test
    public void equalsWithNullReturnsFalse() {

        // given
        SimpleNumber sn = new SimpleNumber(123.45d);

        // expect
        assertFalse(sn.equals(null));
    }

    @Test
    public void equalsWithOtherTypeReturnsFalse() {

        // given
        SimpleNumber sn = new SimpleNumber(123.45d);

        // expect
        assertFalse(sn.equals(Double.valueOf(123.45d)));
    }

    @Test
    public void equalsWithSimpleNumberOfOtherTypeReturnsFalse() {

        // given
        SimpleNumber sn = new SimpleNumber(123);
        SimpleNumber other = new SimpleNumber(123L);

        // expect
        assertFalse(sn.equals(other));
    }

    @Test
    public void equalsWithSimpleNumberOfSameTypeReturnsTrue() {

        // given
        SimpleNumber sn = new SimpleNumber(123);
        SimpleNumber other = new SimpleNumber(123);

        // expect
        assertTrue(sn.equals(other));
    }

    @Test
    public void equalsWithSimpleNumberOfSameBoxedValueReturnsTrue() {

        // given
        Integer value = 123;
        SimpleNumber sn = new SimpleNumber(value);
        SimpleNumber other = new SimpleNumber(value);

        // expect
        assertTrue(sn.equals(other));
    }
}


text:
package com.amazonaws.services.appflow.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateConnectorProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the connector profile. The name is unique for each ConnectorProfile in your Amazon Web
     * Services account.
     *

     */
    private String connectorProfileName;
    /**
     *

     * The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     * required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here, Amazon
     * AppFlow uses the Amazon AppFlow-managed KMS key.
     *

     */
    private String kmsArn;
    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     */
    private String connectorType;
    /**
     *

     * The label of the connector. The label is unique for each ConnectorRegistration in your Amazon Web
     * Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     *

     */
    private String connectorLabel;
    /**
     *

     * Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     * Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the public
     * internet.
     *

     */
    private String connectionMode;
    /**
     *

     * Defines the connector-specific configuration and credentials.
     *

     */
    private ConnectorProfileConfig connectorProfileConfig;

    /**
     *

     * The name of the connector profile. The name is unique for each ConnectorProfile in your Amazon Web
     * Services account.
     *

     *
     * @param connectorProfileName
     *        The name of the connector profile. The name is unique for each ConnectorProfile in your
     *        Amazon Web Services account.
     */

    public void setConnectorProfileName(String connectorProfileName) {
        this.connectorProfileName = connectorProfileName;
    }

    /**
     *

     * The name of the connector profile. The name is unique for each ConnectorProfile in your Amazon Web
     * Services account.
     *

     *
     * @return The name of the connector profile. The name is unique for each ConnectorProfile in your
     *         Amazon Web Services account.
     */

    public String getConnectorProfileName() {
        return this.connectorProfileName;
    }

    /**
     *

     * The name of the connector profile. The name is unique for each ConnectorProfile in your Amazon Web
     * Services account.
     *

     *
     * @param connectorProfileName
     *        The name of the connector profile. The name is unique for each ConnectorProfile in your
     *        Amazon Web Services account.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateConnectorProfileRequest withConnectorProfileName(String connectorProfileName) {
        setConnectorProfileName(connectorProfileName);
        return this;
    }

    /**
     *

     * The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     * required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here, Amazon
     * AppFlow uses the Amazon AppFlow-managed KMS key.
     *

     *
     * @param kmsArn
     *        The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     *        required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here,
     *        Amazon AppFlow uses the Amazon AppFlow-managed KMS key.
     */

    public void setKmsArn(String kmsArn) {
        this.kmsArn = kmsArn;
    }

    /**
     *

     * The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     * required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here, Amazon
     * AppFlow uses the Amazon AppFlow-managed KMS key.
     *

     *
     * @return The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This
     *         is required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything
     *         here, Amazon AppFlow uses the Amazon AppFlow-managed KMS key.
     */

    public String getKmsArn() {
        return this.kmsArn;
    }

    /**
     *

     * The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     * required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here, Amazon
     * AppFlow uses the Amazon AppFlow-managed KMS key.
     *

     *
     * @param kmsArn
     *        The ARN (Amazon Resource Name) of the Key Management Service (KMS) key you provide for encryption. This is
     *        required if you do not want to use the Amazon AppFlow-managed KMS key. If you don't provide anything here,
     *        Amazon AppFlow uses the Amazon AppFlow-managed KMS key.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateConnectorProfileRequest withKmsArn(String kmsArn) {
        setKmsArn(kmsArn);
        return this;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorType
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @see ConnectorType
     */

    public void setConnectorType(String connectorType) {
        this.connectorType = connectorType;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @return The type of connector, such as Salesforce, Amplitude, and so on.
     * @see ConnectorType
     */

    public String getConnectorType() {
        return this.connectorType;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorType
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectorType
     */

    public CreateConnectorProfileRequest withConnectorType(String connectorType) {
        setConnectorType(connectorType);
        return this;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorType
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectorType
     */

    public CreateConnectorProfileRequest withConnectorType(ConnectorType connectorType) {
        this.connectorType = connectorType.toString();
        return this;
    }

    /**
     *

     * The label of the connector. The label is unique for each ConnectorRegistration in your Amazon Web
     * Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     *

     *
     * @param connectorLabel
     *        The label of the connector. The label is unique for each ConnectorRegistration in your Amazon
     *        Web Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     */

    public void setConnectorLabel(String connectorLabel) {
        this.connectorLabel = connectorLabel;
    }

    /**
     *

     * The label of the connector. The label is unique for each ConnectorRegistration in your Amazon Web
     * Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     *

     *
     * @return The label of the connector. The label is unique for each ConnectorRegistration in your
     *         Amazon Web Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     */

    public String getConnectorLabel() {
        return this.connectorLabel;
    }

    /**
     *

     * The label of the connector. The label is unique for each ConnectorRegistration in your Amazon Web
     * Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     *

     *
     * @param connectorLabel
     *        The label of the connector. The label is unique for each ConnectorRegistration in your Amazon
     *        Web Services account. Only needed if calling for CUSTOMCONNECTOR connector type/.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateConnectorProfileRequest withConnectorLabel(String connectorLabel) {
        setConnectorLabel(connectorLabel);
        return this;
    }

    /**
     *

     * Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     * Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the public
     * internet.
     *

     *
     * @param connectionMode
     *        Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     *        Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the
     *        public internet.
     * @see ConnectionMode
     */

    public void setConnectionMode(String connectionMode) {
        this.connectionMode = connectionMode;
    }

    /**
     *

     * Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     * Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the public
     * internet.
     *

     *
     * @return Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     *         Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the
     *         public internet.
     * @see ConnectionMode
     */

    public String getConnectionMode() {
        return this.connectionMode;
    }

    /**
     *

     * Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     * Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the public
     * internet.
     *

     *
     * @param connectionMode
     *        Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     *        Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the
     *        public internet.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectionMode
     */

    public CreateConnectorProfileRequest withConnectionMode(String connectionMode) {
        setConnectionMode(connectionMode);
        return this;
    }

    /**
     *

     * Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     * Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the public
     * internet.
     *

     *
     * @param connectionMode
     *        Indicates the connection mode and specifies whether it is public or private. Private flows use Amazon Web
     *        Services PrivateLink to route data over Amazon Web Services infrastructure without exposing it to the
     *        public internet.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectionMode
     */

    public CreateConnectorProfileRequest withConnectionMode(ConnectionMode connectionMode) {
        this.connectionMode = connectionMode.toString();
        return this;
    }

    /**
     *

     * Defines the connector-specific configuration and credentials.
     *

     *
     * @param connectorProfileConfig
     *        Defines the connector-specific configuration and credentials.
     */

    public void setConnectorProfileConfig(ConnectorProfileConfig connectorProfileConfig) {
        this.connectorProfileConfig = connectorProfileConfig;
    }

    /**
     *

     * Defines the connector-specific configuration and credentials.
     *

     *
     * @return Defines the connector-specific configuration and credentials.
     */

    public ConnectorProfileConfig getConnectorProfileConfig() {
        return this.connectorProfileConfig;
    }

    /**
     *

     * Defines the connector-specific configuration and credentials.
     *

     *
     * @param connectorProfileConfig
     *        Defines the connector-specific configuration and credentials.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateConnectorProfileRequest withConnectorProfileConfig(ConnectorProfileConfig connectorProfileConfig) {
        setConnectorProfileConfig(connectorProfileConfig);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getConnectorProfileName() != null)
            sb.append("ConnectorProfileName: ").append(getConnectorProfileName()).append(",");
        if (getKmsArn() != null)
            sb.append("KmsArn: ").append(getKmsArn()).append(",");
        if (getConnectorType() != null)
            sb.append("ConnectorType: ").append(getConnectorType()).append(",");
        if (getConnectorLabel() != null)
            sb.append("ConnectorLabel: ").append(getConnectorLabel()).append(",");
        if (getConnectionMode() != null)
            sb.append("ConnectionMode: ").append(getConnectionMode()).append(",");
        if (getConnectorProfileConfig() != null)
            sb.append("ConnectorProfileConfig: ").append(getConnectorProfileConfig());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateConnectorProfileRequest == false)
            return false;
        CreateConnectorProfileRequest other = (CreateConnectorProfileRequest) obj;
        if (other.getConnectorProfileName() == null ^ this.getConnectorProfileName() == null)
            return false;
        if (other.getConnectorProfileName() != null && other.getConnectorProfileName().equals(this.getConnectorProfileName()) == false)
            return false;
        if (other.getKmsArn() == null ^ this.getKmsArn() == null)
            return false;
        if (other.getKmsArn() != null && other.getKmsArn().equals(this.getKmsArn()) == false)
            return false;
        if (other.getConnectorType() == null ^ this.getConnectorType() == null)
            return false;
        if (other.getConnectorType() != null && other.getConnectorType().equals(this.getConnectorType()) == false)
            return false;
        if (other.getConnectorLabel() == null ^ this.getConnectorLabel() == null)
            return false;
        if (other.getConnectorLabel() != null && other.getConnectorLabel().equals(this.getConnectorLabel()) == false)
            return false;
        if (other.getConnectionMode() == null ^ this.getConnectionMode() == null)
            return false;
        if (other.getConnectionMode() != null && other.getConnectionMode().equals(this.getConnectionMode()) == false)
            return false;
        if (other.getConnectorProfileConfig() == null ^ this.getConnectorProfileConfig() == null)
            return false;
        if (other.getConnectorProfileConfig() != null && other.getConnectorProfileConfig().equals(this.getConnectorProfileConfig()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getConnectorProfileName() == null) ? 0 : getConnectorProfileName().hashCode());
        hashCode = prime * hashCode + ((getKmsArn() == null) ? 0 : getKmsArn().hashCode());
        hashCode = prime * hashCode + ((getConnectorType() == null) ? 0 : getConnectorType().hashCode());
        hashCode = prime * hashCode + ((getConnectorLabel() == null) ? 0 : getConnectorLabel().hashCode());
        hashCode = prime * hashCode + ((getConnectionMode() == null) ? 0 : getConnectionMode().hashCode());
        hashCode = prime * hashCode + ((getConnectorProfileConfig() == null) ? 0 : getConnectorProfileConfig().hashCode());
        return hashCode;
    }

    @Override
    public CreateConnectorProfileRequest clone() {
        return (CreateConnectorProfileRequest) super.clone();
    }

}


text:
import socket
import time

echo_socket = socket.create_connection(('127.0.0.1', 8090))
for i in range(10):
    data = 'print(\'Hello, world!\')'
    echo_socket.send(data)
    print('send: ' + data)
    data = echo_socket.recv(9999)
    print('recv: ' + data)
    time.sleep(1)


text:
'use strict';
var generators = require('yeoman-generator');
var sdsUtils = require('../utils.js');
var lodash = require('lodash');

module.exports =  class SDSAngularGenerator extends generators.Base {
    constructor() {
        super(...arguments);
        this.lodash = lodash;

        sdsUtils.getNameArg(this, arguments[0]);
    }

    askFor(){
        var cb = this.async();

        var prompts = [{
            type: 'confirm',
            name: 'needpartial',
            message: 'Does this component need an external html file (i.e. partial)?',
            default: true
        }];

        sdsUtils.addNamePrompt(this, prompts, 'component');

        this.prompt(prompts).then(props => {
            if (props.name) {
                this.name = props.name;
            }
            this.needpartial = props.needpartial;
            sdsUtils.askForModuleAndDir('directive', this, true, cb);
        });
    }

    files(){
        var styleExt = (this.config.get("cssExt") || 'less').replace('.', '');
        this.htmlPath = sdsUtils.getCleanPath(this.dir, this.name + '.html');

        if (this.needpartial) {
            sdsUtils.copyTpl('directive', 'complex/directive.html',   this.name + '.html', this);
            sdsUtils.copyTpl('directive', 'complex/directive.js',     this.name + '.js', this);
            sdsUtils.copyTpl('directive', 'complex/directive.less',   this.name + '.' + styleExt, this);
            if (this.config.get("hasSpecFiles") !== false) {
                sdsUtils.copyTpl('directive', 'complex/directive-spec.js', this.name + '-spec.js', this);
            }
        }else{
            sdsUtils.copyTpl('directive', 'simple/directive.js',      this.name + '.js', this);
            sdsUtils.copyTpl('directive', 'simple/directive-spec.js', this.name + '-spec.js', this);
        }
    }
};


text:
package jintgen.isdl;

import cck.util.Util;
import jintgen.isdl.parser.Token;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Ben L. Titzer
 */
public class AddrModeUse {

    public final Token ref;
    public List<AddrModeDecl> addrModes;
    public List<AddrModeDecl.Operand> operands;
    public final AddrModeDecl localDecl;

    public AddrModeUse(Token n, AddrModeDecl d) {
        ref = n;
        addrModes = new LinkedList<AddrModeDecl>();

        localDecl = d;
        if ( d != null ) {
            addrModes.add(d);
            operands = d.operands;
        }
    }

    public void addEncoding(FormatDecl e) {
        if ( localDecl != null )
            localDecl.addEncoding(e);
        else
            throw Util.failure("cannot add encoding to addressing mode directly");
    }
}


text:
interface CssExports {
  'options': string;
  'selected': string;
}
export const cssExports: CssExports;
export default cssExports;


text:
class ProtocolParameter < ActiveRecord::Base
  attr_accessible :default_value, :description, :name, :unit
  belongs_to :protocol
  belongs_to :unit_type, class_name: "OntologyTerm", foreign_key: "unit_type_id"
  has_many :protocol_parameter_values
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FamousQuotesConsumer
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new FamousQuotes();
            var quotes = client.Quotes.Get();

            quotes.ToList().ForEach(q => Console.WriteLine(q.Text + " -- " + q.Author));
            Console.ReadLine();
        }
    }
}


text:
var keypair = require('keypair');
var fs = require('fs');

var pair = keypair();
fs.writeFile('./server/public.key', pair.public, function() {
	console.log('Wrote public key to ./server/public.key');
});
fs.writeFile('./server/private.key', pair.private, function() {
	console.log('Wrote private key to ./server/private.key');
});