text:
<?php
namespace phpdotnet\phd;

abstract class Package_Generic_PDF extends Format_Abstract_PDF {
    private $elementmap = array( /* {{{ */
        'abstract'              => 'format_suppressed_tags',
        'abbrev'                => 'format_suppressed_tags',
        'acronym'               => 'format_suppressed_tags',
        'alt'                   => 'format_suppressed_tags',
        'application'           => 'format_suppressed_tags',
        'author'                => array(
            /* DEFAULT */          'format_newline',
            'authorgroup'       => 'format_authorgroup_author',
        ),
        'authorgroup'           => 'format_shifted_para',
        'blockquote'            => 'format_framed_block',
        'book'                  => 'format_suppressed_tags',
        'callout'               => 'format_callout',
        'calloutlist'           => 'format_calloutlist',
        'caution'               => 'format_admonition',
        'citerefentry'          => 'format_suppressed_tags',
        'classname'             => array(
            /* DEFAULT */          'format_suppressed_tags',
            'ooclass'           => array(
                /* DEFAULT */      'format_bold',
                'classsynopsisinfo' => 'format_suppressed_tags',
            ),
        ),
        'co'                    => 'format_co',
        'command'               => 'format_italic',
        'computeroutput'        => 'format_suppressed_tags',
        'constant'              => 'format_bold',
        'code'                  => 'format_verbatim_inline',
        'copyright'             => 'format_copyright',
        'editor'                => 'format_editor',
        'example'               => 'format_example',
        'emphasis'              => 'format_italic',
        'envar'                 => 'format_suppressed_tags',
        'errortype'             => 'format_suppressed_tags',
        'figure'                => 'format_suppressed_tags',
        'filename'              => 'format_italic',
        'firstname'             => 'format_suppressed_tags',
        'formalpara'            => 'format_para',
        'footnote'              => 'format_footnote',
        'footnoteref'           => 'format_footnoteref',
        'funcdef'               => 'format_bold',
        'function'              => 'format_suppressed_tags',
        'glossterm'             => 'format_suppressed_tags',
        'holder'                => 'format_suppressed_tags',
        'imagedata'             => 'format_imagedata',
        'imageobject'           => 'format_shifted_para',
        'index'                 => 'format_para',
        'indexdiv'              => 'format_para',
        'indexentry'            => 'format_shifted_line',
        'info'                  => 'format_suppressed_tags',
        'informalexample'       => 'format_para',
        'itemizedlist'          => 'format_shifted_para',
        'legalnotice'           => 'format_suppressed_tags',
        'link'                  => 'format_link',
        'listitem'              => array(
            /* DEFAULT */          'format_listitem',
            'varlistentry'      => 'format_shifted_para',
        ),
        'literal'               => 'format_italic',
        'literallayout'         => 'format_verbatim_inline',
        'manvolnum'             => 'format_manvolnum',
        'mediaobject'           => 'format_suppressed_tags',
        'member'                => 'format_member',
        'note'                  => 'format_admonition',
        'option'                => 'format_italic',
        'optional'              => 'format_suppressed_tags',
        'orderedlist'           => 'format_shifted_para',
        'othercredit'           => 'format_newline',
        'othername'             => 'format_suppressed_tags',
        'para'                  => array(
            /* DEFAULT */          'format_para',
            'callout'           => 'format_suppressed_tags',
            'listitem'          => 'format_suppressed_tags',
            'step'              => 'format_suppressed_tags',
        ),
        'partintro'             => 'format_para',
        'personname'            => 'format_suppressed_tags',
        'preface'               => 'format_suppressed_tags',
        'primaryie'             => 'format_suppressed_tags',
        'procedure'             => 'format_procedure',
        'productname'           => 'format_suppressed_tags',
        'programlisting'        => 'format_verbatim_block',
        'property'              => array(
            /* DEFAULT */          'format_suppressed_tags',
            'classsynopsisinfo' => 'format_italic',
        ),
        'pubdate'               => 'format_para',
        'quote'                 => 'format_suppressed_tags',
        'refentrytitle'         => 'format_bold',
        'refname'               => 'format_title',
        'refnamediv'            => 'format_suppressed_tags',
        'refpurpose'            => 'format_refpurpose',
        'refsect1'              => 'format_suppressed_tags',
        'refsection'            => 'format_refsection', // DUMMY REFSECTION DELETION
        'refsynopsisdiv'        => 'format_para',
        'replaceable'           => 'format_italic',
        'screen'                => 'format_verbatim_block',
        'section'               => 'format_suppressed_tags',
        'sect1'                 => 'format_suppressed_tags',
        'sect2'                 => 'format_suppressed_tags',
        'sect3'                 => 'format_suppressed_tags',
        'sect4'                 => 'format_suppressed_tags',
        'sect5'                 => 'format_suppressed_tags',
        'seg'                   => 'format_seg',
        'segmentedlist'         => 'format_segmentedlist',
        'seglistitem'           => 'format_seglistitem',
        'segtitle'              => 'format_suppressed_tags',
        'set'                   => 'format_suppressed_tags',
        'simpara'               => array(
            /* DEFAULT */          'format_para',
            'callout'           => 'format_suppressed_tags',
            'listitem'          => 'format_suppressed_tags',
            'step'              => 'format_suppressed_tags',
        ),
        'simplelist'            => 'format_shifted_para',
        'simplesect'            => 'format_suppressed_tags',
        'step'                  => 'format_suppressed_tags',
        'subscript'             => 'format_indice',
        'superscript'           => 'format_indice',
        'surname'               => 'format_suppressed_tags',
        'synopsis'              => 'format_verbatim_block',
        'systemitem'            => 'format_verbatim_inline',
        'tag'                   => 'format_verbatim_inline',
        'term'                  => 'format_suppressed_tags',
        'title'                 => array(
            /* DEFAULT */          'format_title',
            'example'           => 'format_example_title',
            'formalpara'        => 'format_title3',
            'info'              => array(
                /* DEFAULT */      'format_title',
                'example'       => 'format_example_title',
                'note'          => 'format_title3',
                'table'         => 'format_title3',
                'informaltable' => 'format_title3',
                'warning'           => 'format_title3',
            ),
            'informaltable'     => 'format_title3',
            'legalnotice'       => 'format_title2',
            'note'              => 'format_title3',
            'preface'           => 'format_title',
            'procedure'         => 'format_bold',
            'refsect1'          => 'format_title2',
            'refsect2'          => 'format_title3',
            'refsect3'          => 'format_title3',
            'section'           => 'format_title2',
            'sect1'             => 'format_title2',
            'sect2'             => 'format_title3',
            'sect3'             => 'format_title3',
            'sect4'             => 'format_title3',
            'segmentedlist'     => 'format_bold',
            'table'             => 'format_title3',
            'variablelist'      => 'format_bold',
            'warning'           => 'format_title3',
        ),
        'tip'                   => 'format_admonition',
        'titleabbrev'           => 'format_suppressed_tags',
        'type'                  => 'format_suppressed_tags',
        'userinput'             => 'format_bold',
        'variablelist'          => 'format_suppressed_tags',
        /* hack for phpdoc:varentry */
        'phpdoc:varentry'       => 'format_suppressed_tags',
        'varlistentry'          => 'format_newline',
        'varname'               => 'format_italic',
        'warning'               => 'format_admonition',
        'xref'                  => 'format_link',
        'year'                  => 'format_suppressed_tags',
        // TABLES
        'informaltable'         => 'format_table',
        'table'                 => 'format_table',
        'tgroup'                => 'format_tgroup',
        'colspec'               => 'format_colspec',
        'spanspec'              => 'format_suppressed_tags',
        'thead'                 => 'format_thead',
        'tbody'                 => 'format_suppressed_tags',
        'row'                   => 'format_row',
        'entry'                 => array (
            /* DEFAULT */          'format_entry',
            'row'               => array(
                /* DEFAULT */      'format_entry',
                'thead'         => 'format_th_entry',
                'tfoot'         => 'format_th_entry',
                'tbody'         => 'format_entry',
            ),
        ),
        // SYNOPSISES & OO STUFF
        'void'                  => 'format_void',
        'methodname'            => 'format_bold',
        'methodparam'           => 'format_methodparam',
        'methodsynopsis'        => 'format_methodsynopsis',
        'parameter'             => array(
            /* DEFAULT */          'format_parameter',
            'methodparam'       => 'format_methodparam_parameter',
        ),
        'interfacename'         => 'format_suppressed_tags',
        'ooclass'               => array(
            /* DEFAULT */          'format_suppressed_tags',
            'classsynopsis'     => 'format_framed_para',
        ),
        'oointerface'           => array(
            /* DEFAULT */          'format_suppressed_tags',
            'classsynopsisinfo'    => 'format_classsynopsisinfo_oointerface',
        ),
        'classsynopsis'         => 'format_classsynopsis',
        'classsynopsisinfo'     => 'format_classsynopsisinfo',
        'fieldsynopsis'         => array(
            /* DEFAULT */          'format_fieldsynopsis',
            'entry'             => 'format_para',
        ),
        'modifier'              => 'format_suppressed_tags',
        'constructorsynopsis'   => 'format_methodsynopsis',
        'destructorsynopsis'    => 'format_methodsynopsis',
        'initializer'           => 'format_initializer',
        // FAQ
        'qandaset'              => 'format_para',
        'qandaentry'            => 'format_para',
        'question'              => 'format_bold',
        'answer'                => 'format_shifted_para',

    ); /* }}} */

    private $textmap = array(
        'function'              => 'format_function_text',
        'link'                  => 'format_link_text',
        'quote'                 => 'format_quote_text',
        'refname'               => 'format_refname_text',
        'titleabbrev'           => 'format_suppressed_text',
        'segtitle'              => 'format_segtitle_text',
        'modifier'             => array(
            /* DEFAULT */         false,
            'fieldsynopsis'    => 'format_fieldsynopsis_modifier_text',
        ),
        'methodname'           => array(
            /* DEFAULT */         false,
            'constructorsynopsis' => array(
                /* DEFAULT */     false,
                'classsynopsis' => 'format_classsynopsis_methodsynopsis_methodname_text',
            ),
            'methodsynopsis'    => array(
                /* DEFAULT */     false,
                'classsynopsis' => 'format_classsynopsis_methodsynopsis_methodname_text',
            ),
            'destructorsynopsis' => array(
                /* DEFAULT */     false,
                'classsynopsis' => 'format_classsynopsis_methodsynopsis_methodname_text',
            ),
        ),
    );

    protected $lang = "";

    /* Current Chunk variables */
    private $cchunk      = array();
    /* Default Chunk variables */
    private $dchunk      = array(
        "xml-base"              => "",
        "refsection"            => false,
        "examplenumber"         => 0,
        "href"                  => "",
        "is-xref"               => false,
        "linkend"               => "",
        "links-to-resolve"      => array(
            /* $id => array( $target ), */
        ),
        "refname"               => "",
        "table"                 => false,
        "verbatim-block"        => false,
        "segmentedlist"         => array(
            "seglistitem"       => 0,
            "segtitle"          => array(
            ),
        ),
        "classsynopsis"         => array(
            "close"             => false,
            "classname"         => false,
        ),
        "classsynopsisinfo"     => array(
            "implements"        => false,
            "ooclass"           => false,
        ),
        "fieldsynopsis"         => array(
            "modifier"          => "public",
        ),
        "footnote"              => array(
        ),
        "tablefootnotes"        => array(
        ),
        "footrefs"              => array(),
        "co"                    => 0,
        "corefs"                => array(),
        "callouts"              => 0,
    );

    public function __construct() {
        parent::__construct();
        $this->setExt(Config::ext() === null ? ".pdf" : Config::ext());
        $this->pdfDoc = new PdfWriter();
    }

    public function __destruct() {
        unset($this->pdfDoc);
    }

    public function getChunkInfo($info) {
        if (isset($this->cchunk[$info]))
            return $this->cchunk[$info];
        else return null;
    }

    public function setChunkInfo($info, $value) {
        $this->cchunk[$info] = $value;
    }

    public function getDefaultChunkInfo() {
        return $this->dchunk;
    }

    public function getDefaultElementmap() {
        return $this->elementmap;
    }

    public function getDefaultTextmap() {
        return $this->textmap;
    }

    public function TEXT($str) {
        if (isset($this->cchunk["refsection"]) && $this->cchunk["refsection"]) // DUMMY REFSECTION DELETION
            return "";

        if (isset($this->cchunk["verbatim-block"]) && $this->cchunk["verbatim-block"]) {
            $this->pdfDoc->appendText(utf8_decode($str));
            return "";
        }

        $ret = utf8_decode(trim(preg_replace('/[ \n\t]+/', ' ', $str)));
        // No whitespace if current text value begins with ',', ';', ':', '.'
        if (strncmp($ret, ",", 1) && strncmp($ret, ";", 1) && strncmp($ret, ":", 1) && strncmp($ret, ".", 1))
            $this->pdfDoc->appendText(" " . $ret);
        else $this->pdfDoc->appendText($ret);
        return "";
    }

    public function format_suppressed_tags($open, $name) {
        /* Ignore it */
        return "";
    }

    public function format_suppressed_text($value, $tag) {
        /* Suppress any content */
        return "";
    }

    public function newChunk() {
        $this->cchunk = $this->dchunk;
    }

    // DUMMY REFSECTION DELETION
    public function format_refsection($open, $name, $attrs, $props) {
        if ($open) {
            $this->cchunk["refsection"] = true;
        } else {
            $this->cchunk["refsection"] = false;
        }
        return "";
    }

    public function format_para($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::PARA);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return "";
    }

    public function format_shifted_para($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->shift();
            $this->pdfDoc->add(PdfWriter::PARA);
        } else {
            $this->pdfDoc->unshift();
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return "";
    }

    public function format_shifted_line($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->shift();
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        } else {
            $this->pdfDoc->unshift();
        }
        return "";
    }

    public function format_title($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            $this->pdfDoc->add(PdfWriter::TITLE);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_title2($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            $this->pdfDoc->add(PdfWriter::TITLE2);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_title3($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            $this->pdfDoc->add(PdfWriter::TITLE3);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_bold($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
        } else {
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_italic($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            $this->pdfDoc->setFont(PdfWriter::FONT_ITALIC);
        } else {
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_admonition($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::ADMONITION);
            $this->pdfDoc->appendText($this->autogen($name, $props["lang"]));
            $this->pdfDoc->add(PdfWriter::ADMONITION_CONTENT);
        } else {
            $this->pdfDoc->add(PdfWriter::END_ADMONITION);
        }
        return "";
    }

    public function format_example($open, $name, $attrs, $props) {
        if ($open) {
            $this->lang = $props["lang"];
            $this->cchunk["examplenumber"]++;
            $this->pdfDoc->add(PdfWriter::ADMONITION);

        } else {
            $this->pdfDoc->add(PdfWriter::END_ADMONITION);
        }
        return "";
    }

    public function format_example_title($open, $name, $attrs, $props) {
        if ($props["empty"]) {
            $this->pdfDoc->appendText($this->autogen("example", $this->lang) .
                $this->cchunk["examplenumber"]);
            $this->pdfDoc->add(PdfWriter::ADMONITION_CONTENT);
        } elseif ($open) {
            $this->pdfDoc->appendText($this->autogen("example", $this->lang) .
                $this->cchunk["examplenumber"] . " -");
        } else {
            $this->pdfDoc->add(PdfWriter::ADMONITION_CONTENT);
        }
        return "";
    }

    public function format_newpage($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::PAGE);
        }
        return "";
    }

    public function format_verbatim_block($open, $name, $attrs, $props) {
        if ($open) {
            $this->cchunk["verbatim-block"] = true;
            $this->pdfDoc->add(PdfWriter::VERBATIM_BLOCK);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->revertFont();
            $this->cchunk["verbatim-block"] = false;
        }
        return "";
    }

    public function format_verbatim_inline($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->setFont(PdfWriter::FONT_VERBATIM, 10);
        } else {
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_framed_block($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::FRAMED_BLOCK);
        } else {
            $this->pdfDoc->add(PdfWriter::END_FRAMED_BLOCK);
        }
        return "";
    }

    public function format_framed_para($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::FRAMED_BLOCK);
            $this->format_para($open, $name, $attrs, $props);
        } else {
            $this->format_para($open, $name, $attrs, $props);
            $this->pdfDoc->add(PdfWriter::END_FRAMED_BLOCK);
        }
        return "";
    }

    public function format_newline($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
    }

    public function format_link($open, $name, $attrs, $props) {
        if ($open && ! $props["empty"]) {
            $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0, 0, 1)); // blue
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["linkend"])) {
                $this->cchunk["linkend"] = $attrs[Reader::XMLNS_DOCBOOK]["linkend"];
            } elseif(isset($attrs[Reader::XMLNS_XLINK]["href"])) {
                $this->cchunk["href"] = $attrs[Reader::XMLNS_XLINK]["href"];
            }
        } elseif ($open && $name == "xref" && isset($attrs[Reader::XMLNS_DOCBOOK]["linkend"])
            && $linkend = $attrs[Reader::XMLNS_DOCBOOK]["linkend"]) {
            $this->cchunk["linkend"] = $linkend;
            $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0, 0, 1)); // blue
            $this->format_link_text(Format::getShortDescription($linkend), $name);
            $this->pdfDoc->revertFont();
            $this->cchunk["linkend"] = "";
        } elseif (!$open) {
            $this->cchunk["href"] = "";
            $this->cchunk["linkend"] = "";
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_link_text($value, $tag) {
        $value = trim(preg_replace('/[ \n\t]+/', ' ', $value));
        if (isset($this->cchunk["href"]) && $this->cchunk["href"]) {
            $this->pdfDoc->add(PdfWriter::URL_ANNOTATION, array(chr(187) . chr(160) . $value, $this->cchunk["href"])); // links with >> symbol
        } elseif (isset($this->cchunk["linkend"]) && $linkend = $this->cchunk["linkend"]) {
            $linkAreas = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, $value);
            if (!isset($this->cchunk["links-to-resolve"][$linkend]))
                $this->cchunk["links-to-resolve"][$linkend] = array();
            foreach ($linkAreas as $area)
                $this->cchunk["links-to-resolve"][$linkend][] = $area;
        }
        return "";
    }

    public function format_function_text($value, $tag, $display_value = null) {
        $value = trim(preg_replace('/[ \n\t]+/', ' ', $value));
        if ($display_value === null) {
            $display_value = $value;
        }

        $ref = strtolower(str_replace(array("_", "::", "->"), array("-", "-", "-"), $value));
        if (($linkend = $this->getRefnameLink($ref)) !== null) {
            $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0, 0, 1)); // blue
            $linkAreas = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, $display_value.($tag == "function" ? "()" : ""));
            if (!isset($this->cchunk["links-to-resolve"][$linkend]))
                $this->cchunk["links-to-resolve"][$linkend] = array();
            foreach ($linkAreas as $area)
                $this->cchunk["links-to-resolve"][$linkend][] = $area;
        } else {
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
            $this->pdfDoc->appendText(" " . $display_value.($tag == "function" ? "()" : ""));
        }
        $this->pdfDoc->revertFont();
        return "";
    }

    public function format_authorgroup_author($open, $name, $attrs, $props) {
        if ($open) {
            if ($props["sibling"] !== $name) {
                $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
                $this->pdfDoc->appendText($this->autogen("by", $props["lang"]));
                $this->pdfDoc->revertFont();
            }
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return "";
    }

    public function format_editor($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
            $this->pdfDoc->appendText($this->autogen("editedby", $props["lang"]));
            $this->pdfDoc->revertFont();
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return "";
    }

    public function format_copyright($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::PARA);
            $this->pdfDoc->appendText(utf8_decode("©"));
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return "";
    }

    // Lists {{{
    public function format_listitem($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->add(PdfWriter::ADD_BULLET);
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP, 0.5);
        }
        return "";
    }

    public function format_procedure($open, $name, $attrs, $props) {
        $this->cchunk["step"] = 0;
        return $this->format_shifted_para($open, $name, $attrs, $props);
    }

    public function format_step($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->add(PdfWriter::ADD_NUMBER_ITEM, (++$this->cchunk["step"]).".");
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP, 0.5);
        }
        return "";
    }

    public function format_member($open, $name, $attrs, $props) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->add(PdfWriter::ADD_BULLET);
        }
        return "";
    }

    public function format_segmentedlist($open, $name, $attrs, $props) {
        $this->cchunk["segmentedlist"] = $this->dchunk["segmentedlist"];
        return $this->format_para($open, $name, $attrs, $props);
    }

    public function format_segtitle_text($value, $tag) {
        $this->cchunk["segmentedlist"]["segtitle"][count($this->cchunk["segmentedlist"]["segtitle"])] = $value;
        return '';
    }
    public function format_seglistitem($open, $name, $attrs) {
        if ($open) {
            $this->cchunk["segmentedlist"]["seglistitem"] = 0;
        }
        return '';
    }
    public function format_seg($open, $name, $attrs) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
            $this->pdfDoc->appendText($this->cchunk["segmentedlist"]["segtitle"][$this->cchunk["segmentedlist"]["seglistitem"]++].":");
            $this->pdfDoc->revertFont();
        }
        return '';
    }
    // }}} Lists

    // Tables {{{
    public function format_table($open, $name, $attrs, $props) {
        if ($open) {
            $this->cchunk["table"] = true;
            $this->pdfDoc->add(PdfWriter::PARA);
        } else {
            $this->cchunk["table"] = false;
            $this->pdfDoc->add(PdfWriter::END_TABLE);

            if ($this->cchunk["tablefootnotes"]) {
                $this->pdfDoc->add(PdfWriter::FRAMED_BLOCK);
                $this->pdfDoc->add(PdfWriter::LINE_JUMP);
                $this->pdfDoc->appendBufferNow();
                foreach ($this->cchunk["footrefs"] as $ref)
                    foreach ($ref as $area)
                        $this->pdfDoc->resolveInternalLink($area[0], array($area[1], $area[2], $area[3], $area[4]), $this->pdfDoc->getCurrentPage());
                $this->pdfDoc->add(PdfWriter::END_FRAMED_BLOCK, array(2)); // With Dash line
                $this->cchunk["tablefootnotes"] = $this->dchunk["tablefootnotes"];
            }
        }
        return "";
    }

    public function format_colspec($open, $name, $attrs) {
        if ($open) {
            Format::colspec($attrs[Reader::XMLNS_DOCBOOK]);
        }
        return "";
    }
    public function format_thead($open, $name, $attrs) {
        if ($open) {
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD);
        } else {
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_row($open, $name, $attrs) {
        if ($open) {
            Format::initRow();
            $valign = isset($attrs[Reader::XMLNS_DOCBOOK]['valign'])
                      ? $attrs[Reader::XMLNS_DOCBOOK]['valign'] : 'middle';
            $colCount = Format::getColCount();
            $this->pdfDoc->add(PdfWriter::TABLE_ROW, array($colCount, $valign));
        } else {
            $this->pdfDoc->add(PdfWriter::TABLE_END_ROW);
        }
        return "";
    }
    public function format_th_entry($open, $name, $attrs, $props) {
        $align = (isset($attrs["align"]) ? $attrs["align"] : "center");
        if ($props["empty"]) {
            $this->pdfDoc->add(PdfWriter::TABLE_ENTRY, array(1, 1, $align));
            $this->pdfDoc->add(PdfWriter::TABLE_END_ENTRY);
        }
        if ($open) {
            $dbattrs = Format::getColspec($attrs[Reader::XMLNS_DOCBOOK]);
            $align = (isset($dbattrs["align"]) ? $dbattrs["align"] : $align);
            $colspan = Format::colspan($attrs[Reader::XMLNS_DOCBOOK]);
            $this->pdfDoc->add(PdfWriter::TABLE_ENTRY, array($colspan, 1, $align));
        } else {
            $this->pdfDoc->add(PdfWriter::TABLE_END_ENTRY);
        }
        return "";
    }
    public function format_entry($open, $name, $attrs, $props) {
        $align = (isset($attrs["align"]) ? $attrs["align"] : "left");
        if ($props["empty"]) {
            $this->pdfDoc->add(PdfWriter::TABLE_ENTRY, array(1, 1, $align));
            $this->pdfDoc->add(PdfWriter::TABLE_END_ENTRY);
            return;
        }
        if ($open) {
            $dbattrs = Format::getColspec($attrs[Reader::XMLNS_DOCBOOK]);
            $align = (isset($dbattrs["align"]) ? $dbattrs["align"] : $align);
            $retval = "";
            if (isset($dbattrs["colname"])) {
                for($i=Format::getEntryOffset($dbattrs); $i>0; --$i) {
                    $this->pdfDoc->add(PdfWriter::TABLE_ENTRY, array(1, 1, $align));
                    $this->pdfDoc->add(PdfWriter::TABLE_END_ENTRY);
                }
            }

            /*
             * "colspan" is *not* an standard prop, only used to overwrite the
             * colspan for <footnote>s in tables
             */
            if (isset($props["colspan"])) {
                $colspan = $props["colspan"];
            } else {
                $colspan = Format::colspan($dbattrs);
            }

            $rowspan = Format::rowspan($dbattrs);
            $this->pdfDoc->add(PdfWriter::TABLE_ENTRY, array($colspan, $rowspan, $align));
        } else {
            $this->pdfDoc->add(PdfWriter::TABLE_END_ENTRY);
        }
        return "";
    }

    public function format_tgroup($open, $name, $attrs, $props) {
        if ($open) {
            Format::tgroup($attrs[Reader::XMLNS_DOCBOOK]);
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["cols"]))
                $this->pdfDoc->add(PdfWriter::TABLE, $attrs[Reader::XMLNS_DOCBOOK]["cols"]);
        } else {
        }
        return "";
    }
    // }}} Tables

    // Synopsises {{{
    public function format_methodsynopsis($open, $name, $attrs, $props) {
        if ($open) {
            $this->params = array("count" => 0, "opt" => 0, "content" => "");
            return $this->format_para($open, $name, $attrs, $props);
        }
        $content = "";
        if ($this->params["opt"]) {
            $content = str_repeat(" ]", $this->params["opt"]);
        }
        $content .= " )";

        $this->pdfDoc->appendText($content);
        return $this->format_para($open, $name, $attrs, $props);
    }

    public function format_classsynopsis_methodsynopsis_methodname_text($value, $tag) {
        $value = $this->TEXT($value);
        if ($this->cchunk["classsynopsis"]["classname"] === false) {
            $this->pdfDoc->appendText($value);
            return '';
        }
        if (strpos($value, '::')) {
            $explode = '::';
        } elseif (strpos($value, '->')) {
            $explode = '->';
        } else {
            $this->pdfDoc->appendText($value);
            return '';
        }

        list($class, $method) = explode($explode, $value);
        if ($class !== $this->cchunk["classsynopsis"]["classname"]) {
            $this->pdfDoc->appendText($value);
            return '';
        }
        $this->pdfDoc->appendText($method);
        return '';
    }

    public function format_methodparam_parameter($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["role"])) {
                $this->pdfDoc->setFont(PdfWriter::FONT_VERBATIM, 10);
                $this->pdfDoc->appendText(" &$");
                return '';
            }
            $this->pdfDoc->setFont(PdfWriter::FONT_VERBATIM, 10);
            $this->pdfDoc->appendText(" $");
            return '';
        }
        $this->pdfDoc->revertFont();
        return '';
    }

    public function format_parameter($open, $name, $attrs, $props) {
        if ($props["empty"]) return '';
        if ($open) {
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["role"])) {
                $this->pdfDoc->setFont(PdfWriter::FONT_VERBATIM_ITALIC, 10);
                $this->pdfDoc->appendText(" &");
                return '';
            }
            $this->pdfDoc->setFont(PdfWriter::FONT_VERBATIM_ITALIC, 10);
            return '';
        }
        $this->pdfDoc->revertFont();
        return '';
    }

    public function format_methodparam($open, $name, $attrs) {
        if ($open) {
            $content = '';
                if ($this->params["count"] == 0) {
                    $content .= " (";
                }
                if (isset($attrs[Reader::XMLNS_DOCBOOK]["choice"]) && $attrs[Reader::XMLNS_DOCBOOK]["choice"] == "opt") {
                    $this->params["opt"]++;
                    $content .= " [";
                } else if($this->params["opt"]) {
                    $content .= str_repeat(" ]", $this->params["opt"]);
                    $this->params["opt"] = 0;
                }
                if ($this->params["count"]) {
                    $content .= ",";
                }
                $content .= '';
                ++$this->params["count"];
                $this->pdfDoc->appendText($content);
                return '';
        }
        return '';
    }

    public function format_void($open, $name, $attrs) {
        $this->pdfDoc->appendText(" ( void");
        return '';
    }

    public function format_classsynopsisinfo($open, $name, $attrs, $props) {
        $this->cchunk["classsynopsisinfo"] = $this->dchunk["classsynopsisinfo"];
        if ($open) {
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["role"]) && $attrs[Reader::XMLNS_DOCBOOK]["role"] == "comment") {
                $this->format_para($open, $name, $attrs, $props);
                $this->pdfDoc->appendText("/* ");
                return '';
            }
            return $this->format_para($open, $name, $attrs, $props);
        }

        if (isset($attrs[Reader::XMLNS_DOCBOOK]["role"]) && $attrs[Reader::XMLNS_DOCBOOK]["role"] == "comment") {
            $this->pdfDoc->appendText(" */");
            return $this->format_para($open, $name, $attrs, $props);
        }
        $this->cchunk["classsynopsis"]["close"] = true;
        $this->pdfDoc->appendText(" {");
        $this->pdfDoc->shift();
        return $this->format_para($open, $name, $attrs, $props);
    }

    public function format_classsynopsisinfo_oointerface($open, $name, $attrs) {
        if ($open) {
            if ($this->cchunk["classsynopsisinfo"]["implements"] === false) {
                $this->cchunk["classsynopsisinfo"]["implements"] = true;
                $this->pdfDoc->appendText(" implements");
                return '';
            }
            $this->pdfDoc->appendText(",");
            return '';
        }
        return '';
    }

    public function format_classsynopsis($open, $name, $attrs, $props) {
        if ($open) {
            return $this->format_para($open, $name, $attrs, $props);
        }

        if ($this->cchunk["classsynopsis"]["close"] === true) {
            $this->cchunk["classsynopsis"]["close"] = false;
            $this->pdfDoc->unshift();
            $this->pdfDoc->appendText("}");
        }
        return $this->format_para($open, $name, $attrs, $props);
    }

    public function format_fieldsynopsis_modifier_text($value, $tag) {
        $this->cchunk["fieldsynopsis"]["modifier"] = trim($value);
        $this->pdfDoc->appendText($this->TEXT($value));
        return '';
    }

    public function format_fieldsynopsis($open, $name, $attrs, $props) {
        $this->cchunk["fieldsynopsis"] = $this->dchunk["fieldsynopsis"];
        if ($open) {
            return $this->format_para($open, $name, $attrs, $props);
        }
        $this->pdfDoc->appendText(";");
        return $this->format_para($open, $name, $attrs, $props);
    }

    public function format_initializer($open, $name, $attrs) {
        if ($open) {
            $this->pdfDoc->appendText(" = ");
        }
        return '';
    }
    // }}} Synopsises

    // Footnotes & Callouts {{{
    public function format_footnoteref($open, $name, $attrs, $props) {
        if ($open) {
            $linkend = $attrs[Reader::XMLNS_DOCBOOK]["linkend"];
            $found = false;
            foreach($this->cchunk["footnote"] as $k => $note) {
                if ($note["id"] === $linkend) {
                    $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0,0,1));
                    $this->cchunk["footrefs"][] = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, "[".($k + 1)."]");
                    $this->pdfDoc->revertFont();
                }
            }
            return '';
        }
    }

    public function format_footnote($open, $name, $attrs, $props) {
        if ($open) {
            $count = count($this->cchunk["footnote"]);
            $noteid = isset($attrs[Reader::XMLNS_XML]["id"]) ? $attrs[Reader::XMLNS_XML]["id"] : $count + 1;
            $note = array("id" => $noteid, "str" => "");
            $this->cchunk["footnote"][$count] = $note;
            if ($this->cchunk["table"]) {
                $this->cchunk["tablefootnotes"][$count] = $noteid;
            }
            $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0,0,1));
            $this->cchunk["footrefs"][] = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, "[".($count + 1)."]");
            $this->pdfDoc->revertFont();
            $this->pdfDoc->setAppendToBuffer(true);
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD, 12, array(0,0,1));
            $this->pdfDoc->appendText("[".($count + 1)."]");
            $this->pdfDoc->revertFont();
            return "";
        }
        $this->pdfDoc->appendText("\n");
        $this->pdfDoc->setAppendToBuffer(false);
        return "";
    }

    public function format_co($open, $name, $attrs, $props) {
        if (($open || $props["empty"]) && isset($attrs[Reader::XMLNS_XML]["id"]) && $id = $attrs[Reader::XMLNS_XML]["id"]) {
            $co = ++$this->cchunk["co"];
            $this->pdfDoc->setFont(PdfWriter::FONT_NORMAL, 12, array(0,0,1));
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["linkends"]) && $linkends = $attrs[Reader::XMLNS_DOCBOOK]["linkends"]) {
                $linkAreas = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, "[{$co}]");
                if (!isset($this->cchunk["links-to-resolve"][$linkends]))
                    $this->cchunk["links-to-resolve"][$linkends] = array();
                foreach ($linkAreas as $area)
                    $this->cchunk["links-to-resolve"][$linkends][] = $area;
            }
            $this->pdfDoc->revertFont();
        }
        return "";
    }

    public function format_calloutlist($open, $name, $attrs) {
        if ($open) {
            $this->pdfDoc->add(PdfWriter::FRAMED_BLOCK);
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->cchunk["co"] = 0;
        } else {
            $this->pdfDoc->add(PdfWriter::END_FRAMED_BLOCK, array(2)); // With Dash line
            $this->cchunk["co"] = 0;
        }
        return '';
    }

    public function format_callout($open, $name, $attrs) {
        if ($open) {
            $co = ++$this->cchunk["co"];
            $this->pdfDoc->setFont(PdfWriter::FONT_BOLD, 12, array(0,0,1));
            if (isset($attrs[Reader::XMLNS_DOCBOOK]["arearefs"]) && $ref = $attrs[Reader::XMLNS_DOCBOOK]["arearefs"]) {
                $linkAreas = $this->pdfDoc->add(PdfWriter::LINK_ANNOTATION, "[{$co}]");
                if (!isset($this->cchunk["links-to-resolve"][$ref]))
                    $this->cchunk["links-to-resolve"][$ref] = array();
                foreach ($linkAreas as $area)
                    $this->cchunk["links-to-resolve"][$ref][] = $area;
            }
            $this->pdfDoc->revertFont();
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
        }
        return '';
    }
    // }}} Footnotes & Callouts

    public function format_quote_text($value, $tag) {
        $value = trim(preg_replace('/[ \n\t]+/', ' ', $value));
        $this->pdfDoc->appendText(' "'.$value.'"');
        return "";
    }

    public function format_refname_text($value, $tag) {
        $this->cchunk["refname"][] = $value;
        $this->pdfDoc->appendText(trim(preg_replace('/[ \n\t]+/', ' ', $value)));
        return "";
    }

    public function format_refpurpose($open, $tag, $attrs, $props) {
        if ($props["empty"]) {
            $this->pdfDoc->add(PdfWriter::PARA);
            foreach($this->cchunk["refname"] as $refname) {
                $this->pdfDoc->appendText(" " . $refname . " --");
            }
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->cchunk["refname"] = array();
        } elseif ($open) {
            $this->pdfDoc->add(PdfWriter::PARA);
            foreach($this->cchunk["refname"] as $refname) {
                $this->pdfDoc->appendText(" " . $refname . " --");
            }
        } else {
            $this->pdfDoc->add(PdfWriter::LINE_JUMP);
            $this->cchunk["refname"] = array();
        }
        return "";
    }

    public function format_manvolnum($open, $name, $attrs) {
        if ($open) {
            $this->pdfDoc->appendText(")");
            return '';
        }
        $this->pdfDoc->appendText(")");
        return '';
        return ")</span>";
    }

    public function format_indice($open, $name, $attrs) {
        if (($open && $name == "subscript") || (!$open && $name == "superscript")) {
            $this->pdfDoc->vOffset("-4");
            return '';
        }
        $this->pdfDoc->vOffset("4");
        return '';
    }

    public function format_imagedata($open, $name, $attrs, $props) {
        if ($props["empty"] && isset($this->cchunk["xml-base"]) && ($base = $this->cchunk["xml-base"]) &&
            isset($attrs[Reader::XMLNS_DOCBOOK]["fileref"]) && ($fileref = $attrs[Reader::XMLNS_DOCBOOK]["fileref"])) {
            $imagePath = Config::xml_root() . DIRECTORY_SEPARATOR . $base . $fileref;
            if (file_exists($imagePath))
                $this->pdfDoc->add(PdfWriter::IMAGE, $imagePath);

        }
        return '';
    }

}

/*
* vim600: sw=4 ts=4 syntax=php et
* vim<600: sw=4 ts=4
*/


text:
export const standard = `
<CalendarPanelFooter
  dateToString={date => date.toLocaleDateString('he-IL')}
  primaryActionLabel="Apply"
  secondaryActionLabel="Cancel"
  selectedDays={{
    from: new Date('2019-05-27T21:00:00.000Z'),
    to: new Date('2019-05-27T21:00:00.000Z'),
  }}
/>
`;

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function

from builtins import str

from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-RIDHijacking',

            'Author': ['Sebastian Castro @r4wd3r'],

            'Description': ('Runs Invoke-RIDHijacking. Allows setting desired privileges to an existent account '
                            'by modifying the Relative Identifier value copy used to create the access token. '
                            'This module needs administrative privileges.'
                            ),

            'Software': '',

            'Techniques': ['T1003'],

            'Background': False,

            'OutputExtension': None,

            'NeedsAdmin': True,

            'OpsecSafe': True,

            'Language': 'powershell',

            'MinLanguageVersion': '2',

            'Comments': [
                'https://github.com/r4wd3r/RID-Hijacking',
                'https://r4wsecurity.blogspot.com/2017/12/rid-hijacking-maintaining-access-on.html',
                'https://csl.com.co/rid-hijacking/'
            ]
        }

        self.options = {
            'Agent': {
                'Description':   'Agent to run module on.',
                'Required'   :   True,
                'Value'      :   ''
            },
            'RID' : {
                'Description':   'RID to set to the specified account. Default 500.',
                'Required'   :   False,
                'Value'      :   '500'
            },
            'User' : {
                'Description':   'User to set the defined RID.',
                'Required'   :   False,
                'Value'      :   ''
            },
            'UseGuest' : {
                'Description':   'Switch. Set the defined RID to the Guest account.',
                'Required'   :   False,
                'Value'      :   ''
            },
            'Password' : {
                'Description':   'Password to set to the defined account.',
                'Required'   :   False,
                'Value'      :   ''
            },
            'Enable' : {
                'Description':   'Switch. Enable the defined account.',
                'Required'   :   False,
                'Value'      :   ''
            }
        }

        # Save off a copy of the mainMenu object to access external
        #   functionality like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        # During instantiation, any settable option parameters are passed as
        #   an object set to the module and the options dictionary is
        #   automatically set. This is mostly in case options are passed on
        #   the command line.
        if params:
            for param in params:
                # Parameter format is [Name, Value]
                option, value = param
                if option in self.options:
                    self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        moduleSource = self.mainMenu.installPath + "/data/module_source/persistence/Invoke-RIDHijacking.ps1"
        if obfuscate:
            helpers.obfuscate_module(moduleSource=moduleSource, obfuscationCommand=obfuscationCommand)
            moduleSource = moduleSource.replace("module_source", "obfuscated_module_source")
        try:
            f = open(moduleSource, 'r')
        except:
            print(helpers.color("[!] Could not read module source path at: " + str(moduleSource)))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode
        scriptEnd = "Invoke-RIDHijacking"

        for option, values in self.options.items():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        scriptEnd += " -" + str(option)
                    else:
                        scriptEnd += " -" + str(option) + " " + str(values['Value'])

        if obfuscate:
            scriptEnd = helpers.obfuscate(psScript=scriptEnd, installPath=self.mainMenu.installPath, obfuscationCommand=obfuscationCommand)
        script += scriptEnd
        script = helpers.keyword_obfuscation(script)

        return script


text:
@interface RealTimeLocationStatusView ()
@property(nonatomic) BOOL isExpended;
@property(nonatomic, strong) UILabel *statusLabel;
@property(nonatomic, strong) UIImageView *locationIcon;
@property(nonatomic, strong) UIImageView *moreIcon;

@property(nonatomic, strong) UILabel *expendLabel;
@property(nonatomic, strong) UIButton *cancelButton;
@property(nonatomic, strong) UIButton *joinButton;
@end

#define RC_REAL_TIME_LOCATION_STATUS_FRAME                                     \
  CGRectMake(0, 62, self.frame.size.width, 38)
#define RC_REAL_TIME_LOCATION_EXPEND_FRAME                                     \
  CGRectMake(0, 62, self.frame.size.width, 85)

@implementation RealTimeLocationStatusView

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self setup];
  }
  return self;
}

- (void)setup {
  UITapGestureRecognizer *tap =
      [[UITapGestureRecognizer alloc] initWithTarget:self
                                              action:@selector(onTaped:)];
  [self addGestureRecognizer:tap];
}

- (void)onTaped:(id)sender {
  if ([self.delegate getStatus] == RC_REAL_TIME_LOCATION_STATUS_INCOMING) {
    self.isExpended = !self.isExpended;
  } else if ([self.delegate getStatus] == RC_REAL_TIME_LOCATION_STATUS_IDLE) {
    self.hidden = YES;
  } else {
    [self.delegate onShowRealTimeLocationView];
  }
}

- (void)updateText:(NSString *)statusText {
  self.statusLabel.text = statusText;
}

- (void)updateRealTimeLocationStatus {
  switch ([self.delegate getStatus]) {
  case RC_REAL_TIME_LOCATION_STATUS_IDLE:
    self.hidden = YES;
    self.isExpended = NO;
    break;
  case RC_REAL_TIME_LOCATION_STATUS_INCOMING:
    self.hidden = NO;
    self.isExpended = NO;
    [self setBackgroundColor:[UIColor colorWithRed:((float)0x11) / 255
                                             green:((float)0x40) / 255
                                              blue:((float)0x60) / 255
                                             alpha:0.7]];
    break;
  case RC_REAL_TIME_LOCATION_STATUS_OUTGOING:
  case RC_REAL_TIME_LOCATION_STATUS_CONNECTED:
    self.hidden = NO;
    self.isExpended = NO;
    [self setBackgroundColor:[UIColor colorWithRed:((float)0x69) / 255
                                             green:((float)0xb8) / 255
                                              blue:((float)0xee) / 255
                                             alpha:0.7]];
    break;
  default:
    break;
  }
}

- (void)onCanelPressed:(id)sender {
  self.isExpended = NO;
}

- (void)onJoinPressed:(id)sender {
  self.isExpended = NO;
  [self.delegate onJoin];
}

- (void)setIsExpended:(BOOL)isExpended {
  if (!self.hidden) {
    if (!isExpended) {
      [self showStatus];
      [UIView beginAnimations:nil context:NULL];
      [UIView setAnimationDuration:0.1f];
      self.frame = RC_REAL_TIME_LOCATION_STATUS_FRAME;
      [UIView commitAnimations];
    } else {
      [self showExtendedView];
      [UIView beginAnimations:nil context:NULL];
      [UIView setAnimationDuration:0.1f];
      self.frame = RC_REAL_TIME_LOCATION_EXPEND_FRAME;
      [UIView commitAnimations];
    }
  }
  _isExpended = isExpended;
}

- (void)showStatus {
  for (UIView *subView in self.subviews) {
    [subView removeFromSuperview];
  }
  [self addSubview:self.statusLabel];
  [self addSubview:self.locationIcon];
  [self addSubview:self.moreIcon];
}

- (void)showExtendedView {
  for (UIView *subView in self.subviews) {
    [subView removeFromSuperview];
  }
  [self addSubview:self.expendLabel];
  [self addSubview:self.cancelButton];
  [self addSubview:self.joinButton];
}

- (UILabel *)statusLabel {
  if (!_statusLabel) {
    _statusLabel = [[UILabel alloc]
        initWithFrame:CGRectMake(30, 0, self.frame.size.width - 60, 40)];
    _statusLabel.textAlignment = NSTextAlignmentCenter;
    _statusLabel.textColor = [UIColor whiteColor];
  }
  return _statusLabel;
}
- (UIImageView *)locationIcon {
  if (!_locationIcon) {
    _locationIcon =
        [[UIImageView alloc] initWithFrame:CGRectMake(10, 13, 10, 14)];
    [_locationIcon setImage:[UIImage imageNamed:@"white_location_icon"]];
  }
  return _locationIcon;
}
- (UIImageView *)moreIcon {
  if (!_moreIcon) {
    _moreIcon = [[UIImageView alloc]
        initWithFrame:CGRectMake(self.frame.size.width - 20, 13, 10, 14)];
    [_moreIcon setImage:[UIImage imageNamed:@"location_arrow"]];
  }
  return _moreIcon;
}
- (UILabel *)expendLabel {
  if (!_expendLabel) {
    _expendLabel = [[UILabel alloc]
        initWithFrame:CGRectMake(30, 0, self.frame.size.width - 48, 60)];
    _expendLabel.textAlignment = NSTextAlignmentCenter;
    _expendLabel.textColor = [UIColor whiteColor];
    [_expendLabel setText:@"加"
                          @"入位置共享,聊天中其他人也能看到你的位置,确定加入"
                          @"?"];
    _expendLabel.numberOfLines = 0;
  }
  return _expendLabel;
}
- (UIButton *)cancelButton {
  if (!_cancelButton) {
    _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(79, 52, 50, 25)];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton
        setBackgroundImage:[UIImage imageNamed:@"location_share_button"]
                  forState:UIControlStateNormal];
    [_cancelButton
        setBackgroundImage:[UIImage imageNamed:@"location_share_button_hover"]
                  forState:UIControlStateHighlighted];
    [_cancelButton addTarget:self
                      action:@selector(onCanelPressed:)
            forControlEvents:UIControlEventTouchUpInside];
  }
  return _cancelButton;
}
- (UIButton *)joinButton {
  if (!_joinButton) {
    _joinButton = [[UIButton alloc]
        initWithFrame:CGRectMake(self.frame.size.width - 50 - 79, 52, 50, 25)];
    [_joinButton setTitle:@"加入" forState:UIControlStateNormal];
    [_joinButton
        setBackgroundImage:[UIImage imageNamed:@"location_share_button"]
                  forState:UIControlStateNormal];
    [_joinButton
        setBackgroundImage:[UIImage imageNamed:@"location_share_button_hover"]
                  forState:UIControlStateHighlighted];
    [_joinButton addTarget:self
                    action:@selector(onJoinPressed:)
          forControlEvents:UIControlEventTouchUpInside];
  }
  return _joinButton;
}
@end


text:
package org.oscm.subscriptionservice.bean;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import org.junit.Assert;
import org.junit.Test;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.PlatformUser;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.TechnicalProduct;
import org.oscm.internal.intf.DiscountService;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.vo.VODiscount;
import org.oscm.test.EJBTestBase;
import org.oscm.test.data.Discounts;
import org.oscm.test.data.Marketplaces;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.Products;
import org.oscm.test.data.TechnicalProducts;
import org.oscm.test.ejb.TestContainer;
import org.oscm.test.stubs.ConfigurationServiceStub;

public class DiscountServiceBeanIT extends EJBTestBase {

    protected DataService mgr;
    protected DiscountService discountService;

    private Product product;
    private List<String> customerUserKeys = new ArrayList<>();
    List<Organization> customers;
    private String supplierUserKey;

    @Override
    protected void setup(TestContainer container) throws Exception {
        container.enableInterfaceMocking(true);
        container.addBean(new ConfigurationServiceStub());
        container.addBean(new DataServiceBean());
        container.addBean(new DiscountServiceBean());

        mgr = container.get(DataService.class);
        discountService = container.get(DiscountService.class);

        container.login("setup", ROLE_ORGANIZATION_ADMIN);
        runTX(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                // Create a supplier
                Organization supplier = Organizations.createOrganization(mgr,
                        OrganizationRoleType.SUPPLIER,
                        OrganizationRoleType.TECHNOLOGY_PROVIDER);

                PlatformUser supplierUser = Organizations.createUserForOrg(mgr,
                        supplier, false, "supplierUser");
                supplierUserKey = String.valueOf(supplierUser.getKey());

                // Create a marketplace
                Marketplace marketplace = Marketplaces.ensureMarketplace(
                        supplier, supplier.getOrganizationId(), mgr);

                // Create a technical service
                TechnicalProduct techProd = TechnicalProducts
                        .createTechnicalProduct(mgr, supplier, "techProdId",
                                false, ServiceAccessType.LOGIN);

                // Create a product in the defined marketplace
                product = Products.createProduct(supplier, techProd, true,
                        "productId", "priceModelId", marketplace, mgr);

                // Create two customers for the same supplier
                customers = new ArrayList<>();
                customers.add(Organizations.createCustomer(mgr, supplier));
                customers.add(Organizations.createCustomer(mgr, supplier));
                // Create a customer who has no association to a supplier
                customers.add(Organizations.createOrganization(mgr));

                // Define a discount for the first customer only
                final BigDecimal discountValue = new BigDecimal("2.00");
                Discounts.createDiscount(mgr,
                        customers.get(0).getSources().get(0), discountValue);

                // Create platform users for all the three customers
                PlatformUser firstUser = Organizations.createUserForOrg(mgr,
                        customers.get(0), false, "firstUser");
                customerUserKeys.add(String.valueOf(firstUser.getKey()));

                PlatformUser secondUser = Organizations.createUserForOrg(mgr,
                        customers.get(1), false, "secondUser");
                customerUserKeys.add(String.valueOf(secondUser.getKey()));

                PlatformUser thirdUser = Organizations.createUserForOrg(mgr,
                        customers.get(2), false, "thirdUse");

                customerUserKeys.add(String.valueOf(thirdUser.getKey()));

                mgr.refresh(supplier);
                return null;
            }
        });

        // Log-in as the first customer
        container.login(customerUserKeys.get(0));

    }

    @Test
    public void testGetDiscountForService() throws Exception {
        VODiscount voDiscount = discountService
                .getDiscountForService(product.getKey());
        Assert.assertEquals(voDiscount.getValue(), new BigDecimal("2.00"));
    }

    @Test(expected = ObjectNotFoundException.class)
    public void testGetCustomerDiscountServiceNotFound() throws Exception {
        long invalidProductKey = 0;
        discountService.getDiscountForService(invalidProductKey);
    }

    public void testGetDiscountNotDefined() throws Exception {
        // Log-in as the customer for whom no discount has
        // been specified by the supplier
        container.login(customerUserKeys.get(1));
        Assert.assertNull(
                discountService.getDiscountForService(product.getKey()));
    }

    @Test
    public void testGetDiscountAssociationToSupplierNotFound()
            throws Exception {
        // Log-in as the customer with no association to the supplier.
        container.login(customerUserKeys.get(2));
        Assert.assertNull(
                discountService.getDiscountForService(product.getKey()));
    }

    @Test
    public void testGetDiscountForCustomer() throws Exception {
        // Log-in as a supplier and fetch the discount of a customer.
        container.login(supplierUserKey);
        VODiscount voDiscount = discountService
                .getDiscountForCustomer(customers.get(0).getOrganizationId());
        Assert.assertEquals(voDiscount.getValue(), new BigDecimal("2.00"));
    }

    /**
     * This situation can happen for example if the user accesses the public
     * catalog without first logging-in.
     */
    @Test
    public void testGetDiscountNoLoggedInUser() throws Exception {
        container.logout();
        Assert.assertNull(
                discountService.getDiscountForService(product.getKey()));
    }

}


text:
from model.project import Project
from selenium.webdriver.support.ui import Select
import time
# -*- coding: utf-8 -*-

class ProjectHelper:
    def __init__(self, app):
        self.app = app

    def navigate_manage_projects_page(self):
        wd = self.app.wd
        if not (len(wd.find_elements_by_css_selector("input[value='Create New Project']")) > 0 and
                        wd.current_url.endswith("manage_proj_page.php") > 0):
            wd.get("http://localhost/mantisbt-1.2.19/manage_proj_page.php")

    project_cache = None

    def get_project_list(self):
        if self.project_cache is None:
            wd = self.app.wd
            self.navigate_manage_projects_page()
            self.project_cache = []
            elements = wd.find_elements_by_xpath("/html/body/table[3]/tbody/tr")[2:]
            for element in elements:
                href = element.find_element_by_tag_name("a").get_attribute("href")
                name = element.find_element_by_tag_name("a").text
                id = href[70:len(href)]
                status = element.find_elements_by_tag_name("td")[1].text
                enabled =  element.find_elements_by_tag_name("td")[2].text
                view_state =  element.find_elements_by_tag_name("td")[3].text
                description =  element.find_elements_by_tag_name("td")[4].text
                self.project_cache.append(Project(name=name, id=id, status=status, enabled=enabled,
                                          view_state=view_state, description=description))
                #print("Project 1: ", self.project_cache[0])
        return list(self.project_cache)

    def create(self, project):
            wd = self.app.wd
            self.navigate_manage_projects_page()
            # init group creation
            wd.find_element_by_css_selector("input[value='Create New Project']").click()
            self.fill_project_form(project)
            wd.find_element_by_css_selector("input[value='Add Project']").click()
            self.project_cache = None

    def fill_project_form(self, project):
        wd = self.app.wd
        self.fill_text_field("name", project.name)
        Select(wd.find_element_by_name("status")).select_by_visible_text(project.status)
        Select(wd.find_element_by_name("view_state")).select_by_visible_text(project.view_status)
        self.fill_text_field("description", project.description)

    def fill_text_field(self, field_name, field_data):
        wd = self.app.wd
        if field_data is not None:
            wd.find_element_by_name(field_name).click()
            wd.find_element_by_name(field_name).clear()
            wd.find_element_by_name(field_name).send_keys(field_data)

    def navigate_edit_project_page_by_name(self, projectname):
        wd = self.app.wd
        self.navigate_manage_projects_page()
        elements = wd.find_elements_by_xpath("/html/body/table[3]/tbody/tr")[2:]
        print("222")
        for element in elements:
            a = element.find_element_by_tag_name("a")
            if a.text == projectname:
                b = a
                print("projectname=", projectname)
        b.click()

    def delete_project_by_name(self, name):
        wd = self.app.wd
        self.navigate_edit_project_page_by_name(name)
        wd.find_element_by_css_selector("input[value='Delete Project']").click()
        wd.find_element_by_css_selector("input[value='Delete Project']").click()
        self.project_cache = None


text:
import * as OperationTypes from "./OperationTypes";
import {
  consoleLog,
  consoleError,
  consoleWarn
} from "./helperFunctions/logging";

export class ValueMapV2 {
  parts: any[] = [];
  originalString = "";

  // TODO: clean up mapping, maybe merge with other mapping one used
  // for thml
  // also: originalString is confusing (maybe?)
  constructor(originalString: string) {
    this.originalString = originalString;
  }

  push(
    fromIndexInOriginal,
    toIndexInOriginal,
    operationLog,
    resultString,
    isPartOfSubject = false
  ) {
    this.parts.push({
      fromIndexInOriginal,
      toIndexInOriginal,
      operationLog,
      resultString,
      isPartOfSubject
    });
  }

  getAtResultIndex(
    indexInResult,
    /* hacky arg for encodeuricompoennt */ dontAddBackBasedOnLocationInResultValue = false
  ) {
    let resultString = "";
    let part: any | null = null;
    for (var i = 0; i < this.parts.length; i++) {
      part = this.parts[i];
      resultString += part.resultString;
      if (resultString.length > indexInResult) {
        break;
      }
    }

    const resultIndexBeforePart =
      resultString.length - part.resultString.length;
    let charIndex =
      (part.isPartOfSubject ? part.fromIndexInOriginal : 0) +
      (dontAddBackBasedOnLocationInResultValue
        ? 0
        : indexInResult - resultIndexBeforePart);

    if (charIndex > part.operationLog.result.primitive.length) {
      charIndex = part.operationLog.result.primitive.length - 1;
    }

    let operationLog = part.operationLog;
    if (operationLog.operation === OperationTypes.stringReplacement) {
      operationLog = operationLog.args.value;
    }
    return {
      charIndex,
      operationLog: operationLog
    };
  }

  __debugPrint() {
    let originalString = "";
    let newString = "";
    this.parts.forEach(part => {
      newString += part.resultString;
      originalString += this.originalString.slice(
        part.fromIndexInOriginal,
        part.toIndexInOriginal
      );
    });
    consoleLog({ originalString, newString });
  }
}


text:
package singleton;

public class Singleton {

	private static Singleton instance;
	private Singleton(){}

	public static Singleton getInstance(){
		if(instance == null)
			instance = new Singleton();
		return instance;
	}

	public void operation(){
		System.out.println("Good");
	}
}


text:
import VisaList from './visa-list';
import VisaCard from './visa-card';
import VisaSection from './visa-section';

export default VisaList;

export {
    VisaList as VisaList,
    VisaCard as VisaCard,
    VisaSection as VisaSection
};


text:
namespace SceneEngine { class TerrainManager; class IntersectionTestContext; }
namespace PlatformRig { class IOverlaySystem; }

namespace Sample
{
    std::shared_ptr<PlatformRig::IOverlaySystem> CreateTerrainEditorOverlaySystem(
        std::shared_ptr<SceneEngine::TerrainManager> terrainManager,
        std::shared_ptr<SceneEngine::IntersectionTestContext> intersectionContext);
}


text:
class AddSiteVisit < ActiveRecord::Migration

  def self.up

    create_table "site_visits", :force => true do |t|
      t.column "name", :string, :null => false
      t.column "updated_at", :datetime
      t.column "created_at", :datetime
    end

    add_index :site_visits, :name

  end

  def self.down

    remove_index :site_visits, :name

    drop_table :site_visits
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ascochyta ballotina I.E. Brezhnev

### Remarks
null


text:
#region Licence

#endregion

using System;
using System.Globalization;
using System.Resources;

namespace WmcSoft.ComponentModel
{
    public static class ResourceHelpers
    {
        public static string GetString(Type resourceSource, string name)
        {
            var mgr = new ResourceManager(resourceSource);
            return mgr.GetString(name, CultureInfo.CurrentUICulture);
        }
    }
}


text:
.class public interface abstract Lcn/com/smartdevices/bracelet/chart/StatisticChartView$StatisticChartLoadCallback;
.super Ljava/lang/Object;

# interfaces
.implements Lcn/com/smartdevices/bracelet/chart/data/ChartDataLoader$LoadCallback;

# virtual methods
.method public abstract onOverScrolled()V
.end method


text:
package com.lithium.flow.util;

import java.util.Spliterator;

/**
 * @author Matt Ayres
 */
public abstract class IndefiniteSpliterator<T> implements Spliterator<T> {
	@Override
	public Spliterator<T> trySplit() {
		return null;
	}

	@Override
	public long estimateSize() {
		return Long.MAX_VALUE;
	}

	@Override
	public int characteristics() {
		return IMMUTABLE;
	}
}


text:
namespace CohesionAndCoupling
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class ThreeDimensionalUtils
    {
        public static double CalcDistance3D(double x1, double y1, double z1, double x2, double y2, double z2)
        {
            double distance = Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));
            return distance;
        }

        public static double CalcDiagonalXYZ(double width, double height, double depth)
        {
            double distance = CalcDistance3D(0, 0, 0, width, height, depth);
            return distance;
        }

        public static double CalcVolume(double width, double height, double depth)
        {
            double volume = width * height * depth;
            return volume;
        }
    }
}


text:
<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * OpenID Library
 *
 * @package    CodeIgniter
 * @author     bardelot
 * @see        http://cakebaker.42dh.com/2007/01/11/cakephp-and-openid/
 *             & http://openidenabled.com/php-openid/
 */

class Openid
{
    var $storePath = 'tmp';

    var $sreg_enable = false;
    var $sreg_required = null;
    var $sreg_optional = null;
    var $sreg_policy = null;

    var $ax_enable = false;
    var $ax_required = null;
    var $ax_optional = null;

    var $pape_enable = false;
    var $pape_policy_uris = null;

    var $request_to;
    var $trust_root;
    var $ext_args;

    function Openid()
    {
        $CI = & get_instance();
        $CI->config->load('openid');
        $this->storePath = $CI->config->item('openid_storepath');

        session_start();
        $this->_doIncludes();

        log_message('debug', "OpenID Class Initialized");
    }

    function _doIncludes()
    {
        set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());

        require_once "Auth/OpenID/Consumer.php";
        require_once "Auth/OpenID/FileStore.php";
        require_once "Auth/OpenID/SReg.php";
        require_once "Auth/OpenID/AX.php";
        require_once "Auth/OpenID/PAPE.php";
    }

    function set_sreg($enable, $required = null, $optional = null, $policy = null)
    {
        $this->sreg_enable = $enable;
        $this->sreg_required = $required;
        $this->sreg_optional = $optional;
        $this->sreg_policy = $policy;
    }

    function set_ax($enable, $required = null, $optional = null)
    {
        $this->ax_enable = $enable;
        $this->ax_required = $required;
        $this->ax_optional = $optional;
    }

    function set_pape($enable, $policy_uris = null)
    {
        $this->pape_enable = $enable;
        $this->pape_policy_uris = $policy_uris;
    }

    function set_request_to($uri)
    {
        $this->request_to = $uri;
    }

    function set_trust_root($trust_root)
    {
        $this->trust_root = $trust_root;
    }

    function set_args($args)
    {
        $this->ext_args = $args;
    }

    function _set_message($error, $msg, $val = '', $sub = '%s')
    {
        $CI = & get_instance();
        $CI->lang->load('openid', 'english');
        echo str_replace($sub, $val, $CI->lang->line($msg));

        if ($error)
        {
            exit();
        }
    }

    function authenticate($openId)
    {
        $consumer = $this->_getConsumer();
        $authRequest = $consumer->begin($openId);

        // No auth request means we can't begin OpenID.
        if (!$authRequest)
        {
            $this->_set_message(true, 'openid_auth_error');
        }

        if ($this->sreg_enable)
        {
            $sreg_request = Auth_OpenID_SRegRequest::build($this->sreg_required, $this->sreg_optional, $this->sreg_policy);

            if ($sreg_request)
            {
                $authRequest->addExtension($sreg_request);
            }
            else
            {
                $this->_set_message(true, 'openid_sreg_failed');
            }
        }

        if ($this->ax_enable)
        {
            $ax_request = new Auth_OpenID_AX_FetchRequest;

            if ($this->ax_required)
            {
                foreach ($this->ax_required as $attrib => $alias)
                {
                    $ax_request->add(Auth_OpenID_AX_AttrInfo::make($attrib, 1, true, $alias));
                }
            }

            if ($this->ax_optional)
            {
                foreach ($this->ax_optional as $attrib => $alias)
                {
                    $ax_request->add(Auth_OpenID_AX_AttrInfo::make($attrib, 1, false, $alias));
                }
            }

            $authRequest->addExtension($ax_request);
        }

        if ($this->pape_enable)
        {
            $pape_request = new Auth_OpenID_PAPE_Request($this->pape_policy_uris);

            if ($pape_request)
            {
                $authRequest->addExtension($pape_request);
            }
            else
            {
                $this->_set_message(true, 'openid_pape_failed');
            }
        }

        if ($this->ext_args != null)
        {
            foreach ($this->ext_args as $extensionArgument)
            {
                if (count($extensionArgument) == 3)
                {
                    $authRequest->addExtensionArg($extensionArgument[0], $extensionArgument[1], $extensionArgument[2]);
                }
            }
        }

        // Redirect the user to the OpenID server for authentication.
        // Store the token for this authentication so we can verify the
        // response.

        // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
        // form to send a POST request to the server.
        if ($authRequest->shouldSendRedirect())
        {
            $redirect_url = $authRequest->redirectURL($this->trust_root, $this->request_to);

            // If the redirect URL can't be built, display an error
            // message.
            if (Auth_OpenID::isFailure($redirect_url))
            {
                $this->_set_message(true, 'openid_redirect_failed', $redirect_url->message);
            }
            else
            {
                // Send redirect.
                header("Location: " . $redirect_url);
            }
        }
        else
        {
            // Generate form markup and render it.
            $form_id = 'openid_message';
            $form_html = $authRequest->formMarkup($this->trust_root, $this->request_to, false, array('id' => $form_id));

            // Display an error if the form markup couldn't be generated;
            // otherwise, render the HTML.
            if (Auth_OpenID::isFailure($form_html))
            {
                $this->_set_message(true, 'openid_redirect_failed', $form_html->message);
            }
            else
            {
                $page_contents = array("<title>" , "OpenID transaction in progress" , "</title>" , "" , $form_html , "");

                print implode("\n", $page_contents);
            }
        }

    }

    function getResponse()
    {
        $consumer = $this->_getConsumer();
        $response = $consumer->complete($this->request_to);

        return $response;
    }

    function _getConsumer()
    {
        if (!file_exists($this->storePath) && !mkdir($this->storePath))
        {
            $this->_set_message(true, 'openid_storepath_failed', $this->storePath);
        }

        $store = new Auth_OpenID_FileStore($this->storePath);
        $consumer = new Auth_OpenID_Consumer($store);

        return $consumer;
    }
}


text:
<?php
namespace Cheetahmail\Campaigns\ChronoContact;

use Cheetahmail\AuthHeaderInterface;

class ChronoContact extends \SoapClient
{
    const EMS_WS_NAMESPACE = 'http://ws.ems6.net/';

    /**
     * @var array $classmap The defined classes
     */
    private static $classmap = array(
        'SendMail'                     => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMail',
        'SendMailResponse'             => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailResponse',
        'AuthHeader'                   => 'Cheetahmail\\Campaigns\\ChronoContact\\AuthHeader',
        'SendMailByPacket'             => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailByPacket',
        'ArrayOfInt'                   => 'Cheetahmail\\Campaigns\\ChronoContact\\ArrayOfInt',
        'SendMailByPacketResponse'     => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailByPacketResponse',
        'SendMailHTML'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailHTML',
        'SendMailHTMLResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailHTMLResponse',
        'SendMailHTMLByPacket'         => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailHTMLByPacket',
        'SendMailHTMLByPacketResponse' => 'Cheetahmail\\Campaigns\\ChronoContact\\SendMailHTMLByPacketResponse',
        'CreateTemplate'               => 'Cheetahmail\\Campaigns\\ChronoContact\\CreateTemplate',
        'CreateTemplateResponse'       => 'Cheetahmail\\Campaigns\\ChronoContact\\CreateTemplateResponse',
        'GetTemplate'                  => 'Cheetahmail\\Campaigns\\ChronoContact\\GetTemplate',
        'GetTemplateResponse'          => 'Cheetahmail\\Campaigns\\ChronoContact\\GetTemplateResponse',
        'Template'                     => 'Cheetahmail\\Campaigns\\ChronoContact\\Template',
        'DeleteTemplate'               => 'Cheetahmail\\Campaigns\\ChronoContact\\DeleteTemplate',
        'DeleteTemplateResponse'       => 'Cheetahmail\\Campaigns\\ChronoContact\\DeleteTemplateResponse',
        'ModifyTemplate'               => 'Cheetahmail\\Campaigns\\ChronoContact\\ModifyTemplate',
        'ModifyTemplateResponse'       => 'Cheetahmail\\Campaigns\\ChronoContact\\ModifyTemplateResponse',
        'GetTemplates'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\GetTemplates',
        'GetTemplatesResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\GetTemplatesResponse',
        'ArrayOfArrayOfString'         => 'Cheetahmail\\Campaigns\\ChronoContact\\ArrayOfArrayOfString',
        'ArrayOfString'                => 'Cheetahmail\\Campaigns\\ChronoContact\\ArrayOfString',
        'CreateChrono'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\CreateChrono',
        'CreateChronoResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\CreateChronoResponse',
        'ModifyChrono'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\ModifyChrono',
        'ModifyChronoResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\ModifyChronoResponse',
        'getChronos'                   => 'Cheetahmail\\Campaigns\\ChronoContact\\getChronos',
        'getChronosResponse'           => 'Cheetahmail\\Campaigns\\ChronoContact\\getChronosResponse',
        'getChrono'                    => 'Cheetahmail\\Campaigns\\ChronoContact\\getChrono',
        'getChronoResponse'            => 'Cheetahmail\\Campaigns\\ChronoContact\\getChronoResponse',
        'Chrono'                       => 'Cheetahmail\\Campaigns\\ChronoContact\\Chrono',
        'DeleteChrono'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\DeleteChrono',
        'DeleteChronoResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\DeleteChronoResponse',
        'getCampaigns'                 => 'Cheetahmail\\Campaigns\\ChronoContact\\getCampaigns',
        'getCampaignsResponse'         => 'Cheetahmail\\Campaigns\\ChronoContact\\getCampaignsResponse',
    );

    /**
     * ChronoContact constructor.
     * @param AuthHeaderInterface $authHeader
     * @param null $wsdl
     * @param array $options
     */
    public function __construct(AuthHeaderInterface $authHeader, $wsdl = null, $options = [])
    {
        $this->__setSoapHeaders($this->createHeader($authHeader));
        $wsdl = $wsdl ?: __DIR__ . '/../../../data/campaigns/chronocontact.wsdl';
        foreach (self::$classmap as $key => $value) {
            if (!isset($options['classmap'][$key])) {
                $options['classmap'][$key] = $value;
            }
        }
        $options = array_merge([
            'features' => 1,
        ]);
        parent::__construct($wsdl, $options);
    }

    /**
     * @param AuthHeaderInterface $authHeader
     * @return \SoapHeader
     */
    public function createHeader(AuthHeaderInterface $authHeader)
    {
        $data           = new \StdClass();
        $data->UserName = new \SoapVar($authHeader->getUserName(), XSD_STRING, null, null, null, self::EMS_WS_NAMESPACE);
        $data->Password = new \SoapVar($authHeader->getPassword(), XSD_STRING, null, null, null, self::EMS_WS_NAMESPACE);
        $data->IdMlist  = new \SoapVar($authHeader->getIdMlist(), XSD_INTEGER, null, null, null, self::EMS_WS_NAMESPACE);
        $headerValues   = new \SoapVar($data, SOAP_ENC_OBJECT, null, null, null, self::EMS_WS_NAMESPACE);
        $header         = new \SoapHeader(self::EMS_WS_NAMESPACE, "AuthHeader", $headerValues);

        return $header;
    }

    /**
     * Méthode permettant d'ordonner l'envoi d'un mail de type Chrono à un utilisateur
     *
     * @param SendMail $parameters
     * @return SendMailResponse
     */
    public function SendMail(SendMail $parameters)
    {
        return $this->__soapCall('SendMail', array($parameters));
    }

    /**
     * Méthode permettant d'ordonner l'envoi d'un mail de type Chrono à un utilisateur
     *
     * @param SendMailByPacket $parameters
     * @return SendMailByPacketResponse
     */
    public function SendMailByPacket(SendMailByPacket $parameters)
    {
        return $this->__soapCall('SendMailByPacket', array($parameters));
    }

    /**
     * Méthode permettant d'ordonner l'envoi d'un mail de type Chrono à un utilisateur en précisant éventuellement un sujet, un corps de message HTML ou texte
     *
     * @param SendMailHTML $parameters
     * @return SendMailHTMLResponse
     */
    public function SendMailHTML(SendMailHTML $parameters)
    {
        return $this->__soapCall('SendMailHTML', array($parameters));
    }

    /**
     * Méthode permettant d'ordonner l'envoi d'un mail de type Chrono à un utilisateur en précisant éventuellement un sujet, un corps de message HTML ou texte
     *
     * @param SendMailHTMLByPacket $parameters
     * @return SendMailHTMLByPacketResponse
     */
    public function SendMailHTMLByPacket(SendMailHTMLByPacket $parameters)
    {
        return $this->__soapCall('SendMailHTMLByPacket', array($parameters));
    }

    /**
     * Méthode permettant de creer un template mail, la methode renvoi l'identifiant du template créé
     *
     * @param CreateTemplate $parameters
     * @return CreateTemplateResponse
     */
    public function CreateTemplate(CreateTemplate $parameters)
    {
        return $this->__soapCall('CreateTemplate', array($parameters));
    }

    /**
     * Méthode permettant de récupérer un template mail
     *
     * @param GetTemplate $parameters
     * @return GetTemplateResponse
     */
    public function GetTemplate(GetTemplate $parameters)
    {
        return $this->__soapCall('GetTemplate', array($parameters));
    }

    /**
     * Méthode permettant de supprimer un template mail
     *
     * @param DeleteTemplate $parameters
     * @return DeleteTemplateResponse
     */
    public function DeleteTemplate(DeleteTemplate $parameters)
    {
        return $this->__soapCall('DeleteTemplate', array($parameters));
    }

    /**
     * Méthode permettant de modifier un template en fonction de son id, renvoi true si la modification s'est bien effectuée
     *
     * @param ModifyTemplate $parameters
     * @return ModifyTemplateResponse
     */
    public function ModifyTemplate(ModifyTemplate $parameters)
    {
        return $this->__soapCall('ModifyTemplate', array($parameters));
    }

    /**
     * Méthode permettant d'obtenir la liste de ses templates (paires idtempalte/ description)
     *
     * @param GetTemplates $parameters
     * @return GetTemplatesResponse
     */
    public function GetTemplates(GetTemplates $parameters)
    {
        return $this->__soapCall('GetTemplates', array($parameters));
    }

    /**
     * Méthode permettant de creer une campagne chronomail, la methode renvoi l'identifiant du chronomail créé
     *
     * @param CreateChrono $parameters
     * @return CreateChronoResponse
     */
    public function CreateChrono(CreateChrono $parameters)
    {
        return $this->__soapCall('CreateChrono', array($parameters));
    }

    /**
     * Méthode permettant de modifier une campagne chronomail en fonction de son id, renvoi true si la modification s'est bien effectuée
     *
     * @param ModifyChrono $parameters
     * @return ModifyChronoResponse
     */
    public function ModifyChrono(ModifyChrono $parameters)
    {
        return $this->__soapCall('ModifyChrono', array($parameters));
    }

    /**
     * Méthode permettant d'obtenir la liste de ses chronomail (paires idchrono/ description)
     *
     * @param getChronos $parameters
     * @return getChronosResponse
     */
    public function getChronos(getChronos $parameters)
    {
        return $this->__soapCall('getChronos', array($parameters));
    }

    /**
     * Méthode permettant d'obtenir un Chrono
     *
     * @param getChrono $parameters
     * @return getChronoResponse
     */
    public function getChrono(getChrono $parameters)
    {
        return $this->__soapCall('getChrono', array($parameters));
    }

    /**
     * Méthode permettant de supprimer un Chrono
     *
     * @param DeleteChrono $parameters
     * @return DeleteChronoResponse
     */
    public function DeleteChrono(DeleteChrono $parameters)
    {
        return $this->__soapCall('DeleteChrono', array($parameters));
    }

    /**
     * Méthode permettant d'obtenir la liste de ses campagnes chronomail (paires id/ nom)
     *
     * @param getCampaigns $parameters
     * @return getCampaignsResponse
     */
    public function getCampaigns(getCampaigns $parameters)
    {
        return $this->__soapCall('getCampaigns', array($parameters));
    }
}


text:
require 'spec_helper'
require 'awestruct/deploy/github_pages_deploy'

describe Awestruct::Deploy::GitHubPagesDeploy do

  before :each do
    site_config = double
    site_config.stub(:output_dir).and_return '_site'

    @deploy_config = double
    @deploy_config.stub(:[]).with('branch').and_return('the-branch')
    @deploy_config.stub(:[]).with('repository').and_return('the-repo')
    @deploy_config.stub(:[]).with('gzip').and_return('false')
    @deploy_config.stub(:[]).with('gzip_level')
    @deploy_config.stub(:[]).with('scm').and_return('git')
    @deploy_config.stub(:[]).with('source_dir').and_return('.')
    @deploy_config.stub(:[]).with('uncommitted').and_return('false')
    @deployer = Awestruct::Deploy::GitHubPagesDeploy.new( site_config, @deploy_config )

    @git = double
    @git.stub_chain(:status, :changed, :empty?).and_return true
    ::Git.stub(:open).with('.').and_return @git
    Awestruct::ExceptionHelper.class_variable_set :@@failed, false
  end

  it "should be auto-registered" do
    Awestruct::Deployers.instance[ :github_pages ].should == Awestruct::Deploy::GitHubPagesDeploy
  end

  it "should warn and noop if no changes have been committed" do
    git_scm = double()
    git_scm.stub(:uncommitted_changes?).with('.').and_return true
    @deployer.instance_variable_set('@scm', git_scm)
    $LOG.should_receive(:error).with(Awestruct::Deploy::Base::UNCOMMITTED_CHANGES)
    @deployer.run
  end

  it "should save and restore the current branch when publishing" do
    git_scm = double()
    git_scm.stub(:uncommitted_changes?).with('.').and_return false
    @deployer.instance_variable_set('@scm', git_scm)
    @git.should_receive(:current_branch).and_return( 'bacon' )
    @git.stub_chain(:branch, :checkout)
    @git.should_receive(:push).with('the-repo', 'the-branch')
    @git.should_receive(:checkout).with( 'bacon' )

    @deployer.stub(:add_and_commit_site)
    @deployer.run
  end

  it "should save and restore the current detached branch when publishing" do
    git_scm = double()
    git_scm.stub(:uncommitted_changes?).with('.').and_return false
    @deployer.instance_variable_set('@scm', git_scm)
    @git.should_receive(:current_branch).and_return( '(no branch)' )
    @git.stub_chain(:log, :first, :sha).and_return( '0123456789' )
    @git.should_receive(:branch).with('__awestruct_deploy__').and_return @git
    @git.should_receive(:checkout)
    @git.should_receive(:branch).with('the-branch').and_return @git
    @git.should_receive(:checkout)
    @git.should_receive(:push).with('the-repo', 'the-branch')
    @git.should_receive(:checkout).with( '0123456789' )
    @git.should_receive(:branch).with('__awestruct_deploy__').and_return @git
    @git.should_receive(:delete)

    @deployer.stub(:add_and_commit_site)
    @deployer.run
  end
end


text:
from _pydevd_bundle.pydevd_io import IORedirector
from _pydevd_bundle.pydevd_comm import NetCommandFactory
import pytest

def test_io_redirector():

    class MyRedirection1(object):
        encoding = 'foo'

    class MyRedirection2(object):
        pass

    my_redirector = IORedirector(MyRedirection1(), MyRedirection2(), wrap_buffer=True)
    none_redirector = IORedirector(None, None, wrap_buffer=True)

    assert my_redirector.encoding == 'foo'
    with pytest.raises(AttributeError):
        none_redirector.encoding

    # Check that we don't fail creating the IORedirector if the original
    # doesn't have a 'buffer'.
    for redirector in (
            my_redirector,
            none_redirector,
        ):
        redirector.write('test')
        redirector.flush()

    assert not redirector.isatty()

class _DummyWriter(object):

    __slots__ = ['commands', 'command_meanings']

    def __init__(self):
        self.commands = []
        self.command_meanings = []

    def add_command(self, cmd):
        from _pydevd_bundle.pydevd_comm import ID_TO_MEANING
        meaning = ID_TO_MEANING[str(cmd.id)]
        self.command_meanings.append(meaning)
        self.commands.append(cmd)

class _DummyPyDb(object):

    def __init__(self):
        self.cmd_factory = NetCommandFactory()
        self.writer = _DummyWriter()

def test_debug_console():
    from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn

    class OriginalStdin(object):

        def readline(self):
            return 'read'

    original_stdin = OriginalStdin()

    py_db = _DummyPyDb()
    debug_console_std_in = DebugConsoleStdIn(py_db, original_stdin)
    assert debug_console_std_in.readline() == 'read'

    assert py_db.writer.command_meanings == ['CMD_INPUT_REQUESTED', 'CMD_INPUT_REQUESTED']


text:
<?php
/**
 * Created by PhpStorm.
 * User: Nguyen
 * Date: 10/21/2015
 * Time: 11:01 PM
 */
$this->title = 'Trang của bạn';
$this->params['breadcrumbs'][] = $this->title;
$user = \common\models\User::findOne(['id' => Yii::$app->user->getId()]);
?>

                <img class="profile-user-img img-responsive img-circle" src="<?php
                    if ($user['image'] != "") {
                        echo Yii::$app->request->baseUrl ."/images/" .$user['image'];
                    } else {
                        echo Yii::$app->request->baseUrl ."/images/avatar-default.jpg";
                    }
                    ?>" alt="User profile picture">

<?= $model['fullname'] ?>

<?= $model['job'] ?>

                        Posts 100

                        Friends 100

About Me

                  Education

                    <?= $model['education'] ?>

                 Location

<?= $model['location'] ?>

Settings

Thành công!

Bạn đã cập nhật thành công thông tin cá nhân!

                    <form class="form-horizontal" action="<?= \yii\helpers\Url::to(['/user/edit-user-profile']) ?>" method="post" enctype="multipart/form-data">

                            Full Name

                                <input name="ProfileForm[fullname]" value="<?= $model['fullname'] ?>" type="text" class="form-control" id="inputName" placeholder="Name">

                            Avatar

                                <input name="ProfileForm[avatar]" type="file" id="inputFile" accept="image/*">

                            Gender

                                <select class="form-control" name="ProfileForm[gender][]" id="inputGender">
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>

                            Old Password

                                <input name="ProfileForm[oldPassword]" type="password" class="form-control" id="inputName" placeholder="Password">

                            New Password

                                <input name="ProfileForm[newPassword]" type="password" class="form-control" id="inputName" placeholder="Password">

                            Education

                                <input name="ProfileForm[education]" value="<?= $model['education'] ?>" type="text" class="form-control" id="inputEducation" placeholder="Education">

                            Work

                                <input name="ProfileForm[job]" value="<?= $model['job'] ?>" type="text" class="form-control" id="inputJob" placeholder="Job">

                            Location

                                <input name="ProfileForm[location]" value="<?= $model['location'] ?>" type="text" class="form-control" id="inputLocation" placeholder="Location">

                                <button type="submit" class="btn btn-success">Submit</button>

                    </form>


text:
require 'test_helper'

class QuotationTemplateTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Roslyn.Test.EditorUtilities
Imports Roslyn.Test.Utilities

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
    Public Class SyncLockBlockTests
        <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
        Public Sub ApplyAfterSyncLockStatement()
            VerifyStatementEndConstructApplied(
                before:={"Class c1",
                         "Sub foo()",
                         "SyncLock variable",
                         "End Sub",
                         "End Class"},
                beforeCaret:={2, -1},
                after:={"Class c1",
                        "Sub foo()",
                        "SyncLock variable",
                        "",
                        "End SyncLock",
                        "End Sub",
                        "End Class"},
                afterCaret:={3, -1})
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
        Public Sub DontApplyForMatchedUsing()
            VerifyStatementEndConstructNotApplied(
                text:={"Class c1",
                       "Sub foo()",
                       "SyncLock variable",
                       "End SyncLock",
                       "End Sub",
                       "End Class"},
                caret:={2, -1})
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
        Public Sub VerifyNestedSyncBlock()
            VerifyStatementEndConstructApplied(
                before:={"Class C",
                         "    Sub S",
                         "        SyncLock x",
                         "            SyncLock y",
                         "        End SyncLock",
                         "    End Sub",
                         "End Class"},
                beforeCaret:={3, -1},
                 after:={"Class C",
                         "    Sub S",
                         "        SyncLock x",
                         "            SyncLock y",
                         "",
                         "            End SyncLock",
                         "        End SyncLock",
                         "    End Sub",
                         "End Class"},
                afterCaret:={4, -1})
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
        Public Sub VerifyInvalidSyntax()
            VerifyStatementEndConstructNotApplied(
                text:={"Class C",
                       "    Sub S",
                       "        Using (SyncLock 1) ",
                       "    End Sub",
                       "End Class"},
                caret:={2, -1})
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
        Public Sub VerifyInvalidLocation()
            VerifyStatementEndConstructNotApplied(
                text:={"Class EC",
                       "    Synclock 1",
                       "End Class"},
                caret:={1, -1})
        End Sub
    End Class
End Namespace