text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 24249 -->
<!-- Reviewed: 22743 -->
<appendix id="doc-standard">
    <title>Zend Framework Dokumentations Standard</title>

    <sect1 id="doc-standard.overview">
        <title>Übersicht</title>

        <sect2 id="doc-standard.overview.scope">
            <title>Ziele</title>

            <para>
                Dieses Dokument bietet Richtlinien für die Erstellung der End-Benutzer
                Dokumentation, die im Zend Framework gefunden werden kann. Es ist als Richtlinie
                für die Mitglieder des Zend Framework gedacht, welche Dokumentationen als Teil
                ihrer übermittelten Komponenten Dokumentation schreiben müssen, sowie für die
                Übersetzer von Dokumentation. Der hier enthaltene Standard ist gedacht für einfache
                Übersetzung von Dokumentationen, minimalisieren von Visualisierung und
                stylistischen Unterschieden zwischen den unterschiedlichen Dokumentationsdateien,
                und macht das Finden von Änderungen in der Dokumentation einfacher mit
                <command>diff</command> Tools.
            </para>

            <para>
                Man kann diese Standards zusammen mit den Regeln unserer
                <ulink url="http://framework.zend.com/license">Lizenz</ulink> adoptieren und oder
                modifizieren.
            </para>

            <para>
                Themen, die im Zend Framework Dokumentations Standard beschrieben sind, enthalten die
                Formatierung von Dokumentationsdateien sowie Empfehlungen für die Qualität der
                Dokumentation.
            </para>
        </sect2>
    </sect1>

    <sect1 id="doc-standard.file-formatting">
        <title>Formatierung von Dokumentationsdateien</title>

        <sect2 id="doc-standard.file-formatting.xml-tags">
            <title>XML Tags</title>

            <para>
                Jede Datei des Manuals muss die folgenden <acronym>XML</acronym> Deklarationen am
                Beginn der Datei enthalten:
            </para>

            <programlisting language="xml"><![CDATA[
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
]]></programlisting>

            <para>
                <acronym>XML</acronym> Dateien von übersetzten Sprachen müssen auch ein Revisions
                Tag enthalten, das mit der Revision der englischen Sprachdatei korrespondiert, auf
                der die Übersetzung basiert.
            </para>

            <programlisting language="xml"><![CDATA[
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 14978 -->
<!-- Reviewed: no -->
]]></programlisting>
        </sect2>

        <sect2 id="doc-standard.file-formatting.max-line-length">
            <title>Maximale Zeilenlänge</title>

            <para>
                Die maximale Zeilenlänge, inklusive Tags, Attribute und Einrückungen, darf 100
                Zeichen nicht überschreiten. Es gibt nur eine einzige Ausnahme zu dieser Regel:
                Attributen und Werte Paaren ist es erlaubt die 100 Zeichen zu überschreiten wenn
                diese nicht getrennt werden dürfen.
            </para>
        </sect2>

        <sect2 id="doc-standard.file-formatting.indentation">
            <title>Einrückung</title>

            <para>
                Eine Einrückung sollte aus 4 Leerzeichen bestehen. Tabulatoren sind nicht erlaubt.
            </para>

            <para>
                Tags, welche auf dem gleichen Level sind, müssen auch die gleiche Einrückung haben.
            </para>

            <programlisting language="xml"><![CDATA[
<sect1>
</sect1>

<sect1>
</sect1>
]]></programlisting>

            <para>
                Tags, welche ein Level unter dem vorhergehenden Tag sind, müssen mit 4 zusätzlichen
                Leerzeichen eingerückt werden.
            </para>

            <programlisting language="xml"><![CDATA[
<sect1>
    <sect2>
    </sect2>
</sect1>
]]></programlisting>

            <para>
                Mehrere Block Tags in der gleichen Zeile sind nicht erlaubt; mehrere Inline Tags
                sind trotzdem erlaubt.
            </para>

            <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<sect1><sect2>
</sect2></sect1>

<!-- ERLAUBT -->
<para>
    <classname>Zend_Magic</classname> existiert nicht. <classname>Zend_Acl</classname> existiert.
</para>
]]></programlisting>
        </sect2>

        <sect2 id="doc-standard.file-formatting.line-termination">
            <title>Zeilenendekennzeichen</title>

            <para>
                Die Zeilenendekennzeichen folgt der Unix Textdatei Konvention. Zeilen müssen mit einem
                einzelnen Linefeed (LF) Zeichen enden. Linefeed Zeichen werden als ordinale 10,
                oder Hexadezimale 0x0A repräsentiert.
            </para>

            <para>
                Beachte: Es sind keine Carriage Returns (<acronym>CR</acronym>) zu verwenden, welche
                die Konvention in Apple OS's (0x0D) sind, oder die Carriage Return - Linefeed
                Kombination (<acronym>CRLF</acronym>), welche der Standard für Windows OS (0x0D,
                0x0A) sind.
            </para>
        </sect2>

        <sect2 id="doc-standard.file-formatting.empty-tags">
            <title>Leere Tags</title>

            <para>
                Leere Tags sind nicht erlaubt; alle Tags müssen Text oder Untertags enthalten.
            </para>

            <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<para>
    Irgendein Text. <link></link>
</para>

<para>
</para>
]]></programlisting>
        </sect2>

        <sect2 id="doc-standard.file-formatting.whitespace">
            <title>Verwendung von Leerzeichen in Dokumenten</title>

            <sect3 id="doc-standard.file-formatting.whitespace.trailing">
                <title>Leerzeichen in Tags</title>

                <para>
                    Öffnende Block Tags sollten direkt anschliessend keine Leerzeichen haben, sondern
                    nur einen Zeilenumbruch (und Einrückungen in der folgenden Zeile).
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<sect1>LEERZEICHEN
</sect1>
]]></programlisting>

                <para>
                    Öffnende Inline Tags sollten keine Leerzeichen haben, die direkt folgen.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
Das ist die Klasse <classname> Zend_Class</classname>.

<!-- OK -->
Das ist die Klasse <classname>Zend_Class</classname>.
]]></programlisting>

                <para>
                    Schließenden Block Tags können Leerzeichen vorangestellt sein, die dem aktuellen
                    Einrückungslevel entsprechen, aber nicht mehr als diese Anzahl.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
    <sect1>
     </sect1>

<!-- OK -->
    <sect1>
    </sect1>
]]></programlisting>

                <para>
                    Schließenden Inline Tags dürfen keine Leerzeichen vorangestellt sein.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
Das ist die Klasse <classname>Zend_Class </classname>

<!-- OK -->
Das ist die Klasse <classname>Zend_Class</classname>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.whitespace.multiple-line-breaks">
                <title>Mehrere Zeilenumbrüche</title>

                <para>
                    Mehrere Zeilenumbrüche innerhalb oder auch zwischen Tags sind nicht erlaubt.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<para>
    Etwas Text...

    ... und mehr Text.
</para>

<para>
    Anderer Paragraph.
</para>

<!-- OK -->
<para>
    Etwas Text...
    ... und mehr Text
</para>

<para>
    Anderer Paragraph.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.whitespace.tag-separation">
                <title>Trennung zwischen Tags</title>

                <para>
                    Tags auf dem gleichen Level müssen durch eine leere Zeile getrennt sein, um die
                    Lesbarkeit zu erhöhen.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<para>
    Etwas Text...
</para>
<para>
    Mehr Text...
</para>

<!-- OK -->
<para>
    Etwas Text...
</para>

<para>
    Mehr Text...
</para>
]]></programlisting>

                <para>
                    Das erste Untertag sollte direkt unterhalb seiner Eltern geöffnet werden, ohne
                    dass eine leere Zeile zwischen ihnen ist; das letzte Untertag sollte direkt vor
                    dem schließenden Tag seiner Eltern geschlossen werden.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<sect1>

    <sect2>
    </sect2>

    <sect2>
    </sect2>

    <sect2>
    </sect2>

</sect1>

<!-- OK -->
<sect1>
    <sect2>
    </sect2>

    <sect2>
    </sect2>

    <sect2>
    </sect2>
</sect1>
]]></programlisting>
            </sect3>
        </sect2>

        <sect2 id="doc-standard.file-formatting.program-listing">
            <title>Programmcode-Abschnitte</title>

            <para>
                Das öffnende <emphasis><programlisting></emphasis> Tag muss das richtige
                "language" Attribut anzeigen und auf dem gleichen Level eingerückt sein wie die
                vorhergehenden Blöcke.
            </para>

            <programlisting language="xml"><![CDATA[
<para>Vorhergehender Paragraph.</para>

<programlisting language="php">]]><<![CDATA[![CDATA[
]]></programlisting>

            <para>
                <acronym>CDATA</acronym> sollte um alle Programmcode-Abschnitte vorhanden sein.
            </para>

            <para>
                <emphasis><programlisting></emphasis> Abschnitte dürfen keine Zeilenumbrüche
                oder Leerzeichen am Anfang oder Ende des Abschnitts besitzen, da diese auch in der
                endgültigen Ausgabe dargestellt werden.
            </para>

            <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<programlisting language="php">]]><<![CDATA[![CDATA[

$render = "xxx";

]]]]>><![CDATA[</programlisting>

<!-- OK -->
<programlisting language="php">]]><<![CDATA[![CDATA[
$render = "xxx";
]]]]>><![CDATA[</programlisting>
]]></programlisting>

            <para>
                Endende <acronym>CDATA</acronym> und <emphasis><programlisting></emphasis>
                Tags sollten in der gleichen Zeile, aber ohne Einrückung stehen.
            </para>

            <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
    <programlisting language="php">]]><<![CDATA[![CDATA[
$render = "xxx";
]]]]>><![CDATA[
    </programlisting>

<!-- NICHT ERLAUBT -->
    <programlisting language="php">]]><<![CDATA[![CDATA[
$render = "xxx";
    ]]]]>><![CDATA[</programlisting>

<!-- OK -->
    <programlisting language="php">]]><<![CDATA[![CDATA[
$render = "xxx";
]]]]>><![CDATA[</programlisting>
]]></programlisting>

            <para>
                Das <emphasis><programlisting></emphasis> Tag sollte das "language" Attribut
                mit einem Wert enthalten, der dem Inhalt des Programmcode-Abschnitts entspricht.
                Typischerweise enthält es die Werte "css", "html", "ini", "javascript", "php",
                "text", und "xml".
            </para>

            <programlisting language="xml"><![CDATA[
<!-- PHP -->
<programlisting language="php">]]><<![CDATA[![CDATA[

<!-- Javascript -->
<programlisting language="javascript">]]><<![CDATA[![CDATA[

<!-- XML -->
<programlisting language="xml">]]><<![CDATA[![CDATA[
]]></programlisting>

            <para>
                Für Programmcode-Abschnitte, die nur <acronym>PHP</acronym> Code enthalten, werden
                keine <acronym>PHP</acronym>-Tags (wie z.B. "<?php", "?>") benötigt, und
                sollten auch nicht verwendet werden. Sie zeigen nur das Naheliegendste und werden
                durch die Verwendung des <emphasis><programlisting></emphasis> Tags
                impliziert.
            </para>

            <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<programlisting language="php"]]><<![CDATA[![CDATA[<?php
    // ...
?>]]]]>><![CDATA[</programlisting>

<programlisting language="php"]]><<![CDATA[![CDATA[
<?php
    // ...
?>
]]]]>><![CDATA[</programlisting>
]]></programlisting>

            <para>
                Die Zeilenlängen in Programmcode-Abschnitten sollten den <link
                    linkend="coding-standard.php-file-formatting.max-line-length">Coding Standard
                    Empfehlungen</link> folgen.
            </para>

            <para>
                <methodname>require_once()</methodname>, <methodname>require()</methodname>,
                <methodname>include_once()</methodname> und <methodname>include()</methodname>
                sollten innerhalb von <acronym>PHP</acronym>-Listings nicht verwendet werden.
                Sie zeigen nur das Naheliegendste, und sind meistens nicht notwendig, wenn ein
                Autoloader verwendet wird. Sie sollten nur verwendet werden, wenn sie essentiell
                für das Beispiel sind.
            </para>

            <note>
                <title>Niemals Short Tags verwenden</title>

                <para>
                    Short Tags (z.B., "<?", "<?=") sollten niemals innerhalb von
                    <emphasis>programlisting</emphasis> oder eines Dokuments verwendet werden.
                </para>
            </note>
        </sect2>

        <sect2 id="doc-standard.file-formatting.inline-tags">
            <title>Notizen zu speziellen Inline Tags</title>

            <sect3 id="doc-standard.file-formatting.inline-tags.classname">
                <title>classname</title>

                <para>
                    Das Tag <emphasis><classname></emphasis> muß jedesmal verwendet werden,
                    wenn ein Klassenname durch sich selbst repräsentiert wird; er sollte nicht
                    in Kombination mit einem Methodennamen, Variablennamen, oder einer Konstante
                    verwendet werden, und auch anderer Inhalt ist nicht innerhalb des Tags erlaubt.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Die Klasse <classname>Zend_Class</classname>.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.varname">
                <title>varname</title>

                <para>
                    Variablen müssen im <emphasis><varname></emphasis> Tag eingeschlossen sein.
                    Variablen müssen mit Verwendung des "$" Siegels geschrieben werden. Kein
                    anderer Inhalt ist innerhalb des Tags erlaubt, ausser es wird ein Klassenname
                    verwendet, der eine Klassenvariable anzeigt.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Die Variable <varname>$var</varname> und die Klassenvariable
    <varname>Zend_Class::$var</varname>.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.methodname">
                <title>methodname</title>

                <para>
                    Methoden müssen innerhalb des <emphasis><methodname></emphasis> Tags
                    stehen. Methoden müssen entweder die komplette Methoden Signatur enthalten,
                    oder zumindest ein Paar schließender Klammern (z.B., "()"). Kein anderer
                    Inhalt ist innerhalb dieses Tags erlaubt, ausser es wird ein Klassenname
                    verwendet, der eine Klassenmethode anzeigt.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Die Methode <methodname>foo()</methodname> und die Klassenmethode
    <methodname>Zend_Class::foo()</methodname>. Eine Methode mit der kompletten
    Signatur <methodname>foo($bar, $baz)</methodname>
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.constant">
                <title>constant</title>

                <para>
                    Das <emphasis><constant></emphasis> Tag ist zu verwenden wenn Konstanten
                    angezeigt werden sollen. Konstanten müssen <acronym>GROßGESCHRIEBEN</acronym>
                    werden. Kein anderer Inhalt ist innerhalb dieses Tags erlaubt, ausser es wird
                    ein Klassenname verwendet, der eine Klassenkonstante anzeigt.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Die Konstante <constant>FOO</constant> und die Klassenkonstante
    <constant>Zend_Class::FOO</constant>.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.filename">
                <title>filename</title>

                <para>
                    Dateinamen und Pfade müssen im <emphasis><filename></emphasis> Tag
                    enthalten sein. Kein anderer Inhalt ist innerhalb dieses Tags erlaubt.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Die Datei <filename>application/Bootstrap.php</filename>.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.command">
                <title>command</title>

                <para>
                    Commands, Shell Skripte, und Programmaufrufe müssen im
                    <emphasis><command></emphasis> Tag enthalten sein. Wenn das Kommando
                    Argumente enthält sollten diese auch im Tag enthalten sein.
                </para>

                <programlisting language="xml"><![CDATA[
<para>
    Ausführen von <command>zf.sh create project</command>.
</para>
]]></programlisting>
            </sect3>

            <sect3 id="doc-standard.file-formatting.inline-tags.code">
                <title>code</title>

                <para>
                    Die Verwendung des <emphasis><code></emphasis> Tags ist nicht erlaubt.
                    Stattdessen sollten die anderen vorher besprochenen Inline Tags verwendet
                    werden.
                </para>
            </sect3>
        </sect2>

        <sect2 id="doc-standard.file-formatting.block-tags">
            <title>Notizen zu speziellen Block Tags</title>

            <sect3 id="doc-standard.file-formatting.block-tags.title">
                <title>title</title>

                <para>
                    Das <emphasis><title></emphasis> Tag darf keine anderen Tags enthalten.
                </para>

                <programlisting language="xml"><![CDATA[
<!-- NICHT ERLAUBT -->
<title>Verwendung von <classname>Zend_Class</classname></title>

<!-- OK -->
<title>Verwendung von Zend_Class</title>
]]></programlisting>
            </sect3>
        </sect2>
    </sect1>

    <sect1 id="doc-standard.recommendations">
        <title>Empfehlungen</title>

        <sect2 id="doc-standard.recommendations.editors">
            <title>Editoren ohne Autoformatierung verwenden</title>

            <para>
                Für die Bearbeitung der Dokumentation sollten typischerweise keine formalen
                <acronym>XML</acronym>-Editoren verwendet werden. Solche Editoren formatieren
                bestehende Dokumente normalerweise so, dass diese ihren eigenen Standards folgen
                und folgen dem Docbook Standard nicht strikt. Als Beispiel haben wir gesehen
                das sie die <acronym>CDATA</acronym> Tags entfernen, die Trennung von 4 Leerzeichen
                zu Tabs oder 2 Leerzeichen  ändern, usw.
            </para>

            <para>
                Die Styling Richtlinien wurde großteils geschrieben, um Übersetzern zu helfen, damit
                diese durch Verwendung von normalen <command>diff</command>-Tools erkennen, welche
                Zeilen sich geändert haben. Die automatische Formatierung macht diesen Prozess
                viel schwieriger.
            </para>
        </sect2>

        <sect2 id="doc-standard.recommendations.images">
            <title>Verwendung von Bildern</title>

            <para>
                Gute Bilder und Diagramme können die Lesbarkeit und das Verständnis erhöhen. Sie
                sollten immer dann verwendet werden, wenn sie diesen Zielen helfen. Bilder sollten
                im Verzeichnis <filename>documentation/manual/en/figures/</filename> platziert,
                und nach dem Kapitel benannt werden, in dem sie vorkommen.
            </para>
        </sect2>

        <sect2 id="doc-standard.recommendations.examples">
            <title>Gute Fallbeispiele</title>

            <para>
                Man sollte nach guten Fallbeispielen suchen, die von der Community verbreitet werden.
                Speziell jene, die in den Kommentaren der Proposals oder einer der Mailing Listen
                gesendet werden. Beispiel zeigen oft viel besser die Verwendung, als es
                Beschreibungen tun.
            </para>

            <para>
                Wenn man Beispiele für die Aufnahme in das Handbuch schreibt, sollte man
                allen Coding Standards und Dokumentations Standards folgen.
            </para>
        </sect2>

        <sect2 id="doc-standard.recommendations.phpdoc">
            <title>Vermeide die Wiederholung von phpdoc Inhalten</title>

            <para>
                Das Handbuch ist dazu gedacht, ein Referenzhandbuch für die Verwendung durch
                Endbenutzer zu sein. Die Wiederholung von phpdoc Dokumentation für intern
                verwendete Komponenten und Klassen ist nicht erwünscht, und die Beschreibungen
                sollten auf die Verwendung fokussiert sein, und nicht der internen Arbeitsweise.
                In jedem Fall und zu jeder Zeit wollen wir, dass sich die Dokumentations-Teams auf
                die Übersetzung des englischen Handbuchs und nicht auf ide phpdoc Kommentare
                fokussiert.
            </para>
        </sect2>

        <sect2 id="doc-standard.recommendations.links">
            <title>Verwendung von Links</title>

            <para>
                Links sollten zu anderen Abschnitten des Handbuchs oder externen Quellen verweisen,
                statt Dokumentation zu wiederholen.
            </para>

            <para>
                Die Verlinkung zu anderen Abschnitten des Handbuchs kann durchgeführt werden, indem
                das <emphasis><link></emphasis> Tag verwendet wird (für welches man den Link
                Text selbst angeben muß).
            </para>

            <programlisting language="xml"><![CDATA[
<para>
    "Link" verweist zu einer Sektion, und verwendet beschreibenden Text: <link
        linkend="doc-standard.recommendations.links">Dokumentation zum
        Link</link>.
</para>
]]></programlisting>

            <para>
                Um auf eine externe Ressource zu verweisen, muss <emphasis><ulink></emphasis>
                verwendet werden:
            </para>

            <programlisting language="xml"><![CDATA[
<para>
    Die <ulink url="http://framework.zend.com/">Zend Framework Seite</ulink>.
</para>
]]></programlisting>
        </sect2>
    </sect1>
</appendix>


text:
<?php

use Rs\Json\Patch;
use Rs\Json\Patch\InvalidOperationException;
use Rs\Json\Patch\InvalidPatchDocumentJsonException;
use Rs\Json\Patch\InvalidTargetDocumentJsonException;
use function Parvula\app;

/**
 * @api {post} /pages Create a new page
 * @apiDescription Page **must not** exists
 * @apiName Create page
 * @apiGroup Page
 *
 * @apiParam {string} title Page title
 * @apiParam {string} slug Page slug (eg. `/my-slug`)
 * @apiParam {string} [content] Optional Page content
 * @apiParam {mixed} [field] Optional Custom(s) field(s)
 *
 * @apiParamExample {json} Request-Example:
 *     {
 *       "title": "My title",
 *       "slug": "my_new_slug",
 *       "content": "Some content"
 *     }
 *
 * @apiSuccess (201) PageCreated Page was created
 * @apiError (400) BadField This page need at least a slug and a title
 * @apiError (404) PageException If exception
 * @apiError (409) PageAlreadyExists Page already exists
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 400 Bad Request
 *     {
 *       "error": "BadField",
 *       "message": "This page need at least a slug and a title"
 *     }
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 409 Conflict
 *     {
 *       "error": "PageAlreadyExists",
 *       "message": "This page already exists"
 *     }
 */
// TODO 'Location' header with link to /pages/{id} containing new ID.
$this->post('', function ($req, $res) {
	$parsedBody = $req->getParsedBody();

	if (!isset($parsedBody['slug'], $parsedBody['title'])) {
		return $this->api->json($res, [
			'error' => 'BadField',
			'message' => 'This page need at least a slug and a title'
		], 400);
	}

	$pages = app('pages');
	if ($pages->find($parsedBody['slug'])) {
		return $this->api->json($res, [
			'error' => 'PageAlreadyExists',
			'message' => 'Page `' . htmlspecialchars($parsedBody['slug']) . '` already exists'
		], 409);
	}

	$pageArr = (array) $parsedBody;

	try {
		$result = $pages->create($pageArr);
	} catch (Exception $e) {
		return $this->api->json($res, [
			'error' => 'PageException',
			'message' => $e->getMessage()
		], 500);
	}

	if (!$result) {
		return $this->api->json($res, [
			'error' => 'PageCannotBeCreated'
		], 500);
	}

	return $res->withStatus(201);
})->setName('pages.create');

$this->map(['PUT', 'DELETE'], '', function ($req, $res) {
	return $res->withStatus(405); // Method Not Allowed
});

/**
 * @api {put} /pages/:slug Update a page
 * @apiDescription Page **must** exists to be updated
 * @apiName Update page
 * @apiGroup Page
 *
 * @apiParam {string} title Page title
 * @apiParam {string} slug Page slug (eg. `/my-slug`)
 * @apiParam {string} [content] Optional Page content
 * @apiParam {mixed} [field] Optional Custom(s) field(s)
 *
 * @apiParamExample {json} Request-Example:
 *     {
 *       "title": "My updated title",
 *       "slug": "updated_slug",
 *       "content": "Some edited content"
 *     }
 *
 * @apiSuccess (204) PageUpdated
 * @apiError (400) BadField This page need at least a `slug` and a `title`
 * @apiError (404) PageException If page does not exists or exception
 */
$this->put('/{slug:.+}', function ($req, $res, $args) {
	$parsedBody = $req->getParsedBody();

	if (!isset($parsedBody['slug'], $parsedBody['title'])) {
		return $this->api->json($res, [
			'error' => 'BadField',
			'message' => 'This page need at least a `slug` and a `title`'
		], 400);
	}

	try {
		app('pages')->update($args['slug'], (array) $parsedBody);
	} catch (Exception $e) {
		return $this->api->json($res, [
			'error' => 'PageException',
			'message' => $e->getMessage()
		], 500);
	}

	$res->withStatus(204);
})->setName('pages.update');

/**
 * @api {patch} /pages/:slug Update specific field(s) of a page
 * @apiDescription Patch uses [Json patch (rfc6902)](https://tools.ietf.org/html/rfc6902)
 * @apiName Patch page
 * @apiGroup Page
 *
 * @apiSuccess (204) PagePatched
 * @apiError (400) InvalidPatchDocumentJsonException
 * @apiError (400) InvalidTargetDocumentJsonException
 * @apiError (400) InvalidOperationException
 * @apiError (404) PageDoesNotExists If page does not exists
 * @apiError (404) PageException
 * @apiError (500) ServerException
 */
$this->patch('/{slug:.+}', function ($req, $res, $args) {
	$parsedBody = $req->getParsedBody();
	$bodyJson = json_encode($req->getParsedBody());

	$slug = $args['slug'];
	$pages = app('pages');
	if (!isset($req->getQueryParams()['parse'])) {
		$pages->setRenderer(app('pageRendererRAW'));
	}
	$page = $pages->find($slug);

	if (!$page) {
		return $this->api->json($res, [
			'error' => 'PageDoesNotExists',
			'message' => 'Page does not exists'
		], 404);
	}

	try {
		// string concatenation convert page to json
		$patch = new Patch((string) $page, $bodyJson);

		$patchedDocument = $patch->apply();

		$pages->update($slug, json_decode($patchedDocument, true));
	} catch (InvalidPatchDocumentJsonException $e) {
		// Will be thrown when using invalid JSON in a patch document
		return $this->api->json($res, [
			'error' => 'InvalidPatchDocumentJsonException',
			'message' => $e->getMessage()
		], 400);
	} catch (InvalidTargetDocumentJsonException $e) {
		// Will be thrown when using invalid JSON in a target document
		return $this->api->json($res, [
			'error' => 'InvalidTargetDocumentJsonException',
			'message' => $e->getMessage()
		], 400);
	} catch (InvalidOperationException $e) {
		// Will be thrown when using an invalid JSON Pointer operation (i.e. missing property)
		return $this->api->json($res, [
			'error' => 'InvalidOperationException',
			'message' => $e->getMessage()
		], 400);
	} catch (Exception $e) {
		return $this->api->json($res, [
			'error' => 'ServerException',
			'message' => $e->getMessage()
		], 500);
	}
})->setName('pages.patch');

/*
 * @api {delete} /page/:slug Delete a page.
 * @apiName Delete page
 * @apiGroup Page
 *
 * @apiSuccess (204) PageDeleted
 * @apiError (404) PageDoesNotExists If page does not exists and thus cannot be deleted
 * @apiError (404) PageException If not ok or exception
 */
$this->delete('/{slug:.+}', function ($req, $res, $args) {
	$pages = app('pages');
	$page = $pages->find($args['slug']);

	if (!$page) {
		return $this->api->json($res, [
			'error' => 'PageDoesNotExists',
			'message' => 'Page does not exists and thus cannot be deleted'
		], 404);
	}

	try {
		$result = $pages->delete($args['slug']);
	} catch (Exception $e) {
		return $this->api->json($res, [
			'error' => 'PageException',
			'message' => $e->getMessage()
		], 404);
	}

	if (!$result) {
		return $this->api->json($res, [
			'error' => 'PageCannotBeDeleted'
		], 500);
	}

	return $res->withStatus(204);
})->setName('pages.delete');

redpajama_set_name: RedPajamaGithub


text:
package org.deri.vocidex;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

import com.hp.hpl.jena.rdf.model.Resource;

/**
 * A document that can be indexed. Documents consist of:
 *
 * 1. A JSON object (the contents)
 * 2. A URI as a unique ID
 * 3. A document type (string).
 *
 * @author Richard Cyganiak
 */
public class VocidexDocument {
	private final static ObjectMapper mapper = new ObjectMapper();

	private static String toJsonString(ObjectNode description) {
		try {
			return mapper.writeValueAsString(description);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	private static ObjectNode toJsonObject(String json) {
		try {
			return (ObjectNode) mapper.readTree(json);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	private final String type;
	private final Resource uri;
	private final ObjectNode root;

	/**
	 * Creates a new empty indexable document. Properties can be added via
	 * the JSON object returned by {@link #getRoot()}.
	 *
	 * @param type The type of document
	 * @param uri The id that uniquely names the document
	 */
	public VocidexDocument(String type, Resource uri) {
		this(type, uri, mapper.createObjectNode());
	}

	/**
	 * Creates a new indexable document from a JSON string.
	 *
	 * @param type The type of document
	 * @param uri The id that uniquely names the document
	 * @param json JSON contents of the document
	 */
	public VocidexDocument(String type, Resource uri, String json) {
		this(type, uri, toJsonObject(json));
	}

	/**
	 * Creates a new indexable document from a JSON object.
	 *
	 * @param type The type of document
	 * @param uri The id that uniquely names the document
	 * @param description JSON object with the contents of the document
	 */
	public VocidexDocument(String type, Resource uri, ObjectNode description) {
		if (!uri.isURIResource()) {
			throw new IllegalArgumentException("Document ID is not a URI resource: " + uri);
		}
		this.type = type;
		this.uri = uri;
		this.root = description;
	}

	public String getType() {
		return type;
	}

	public Resource getURI() {
		return uri;
	}

	/**
	 * @return String form of {@link #getURI()}
	 */
	public String getId() {
		return uri.getURI();
	}

	public ObjectNode getRoot() {
		return root;
	}

	public String getJSONContents() {
		return toJsonString(root);
	}
}


text:
@interface ListViewController ()

@end

@implementation ListViewController

-(id) init
{
    self=[super init];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    ListView *list=[[ListView alloc]initWithFrame:self.view.frame];
    list.ValueTotalOpen.text=[NSString stringWithFormat:@": %d",(int)self.TotalOpenIssues];
    list.valueTotalOneDayOpen.text=[NSString stringWithFormat:@": %d",(int)self.TotalOneDayIssues];
    list.valueTotalSevenDayOpen.text=[NSString stringWithFormat:@": %d",(int)self.TotalSevenDayIssues];
    list.valueTotalRestDayOpen.text=[NSString stringWithFormat:@": %d",(int)self.TotalOtherDayIssues];
    self.view=list;
    self.title=@"Issues List";

    // Do any additional setup after loading the view, typically from a nib.
}
@end


text:
    #pragma hdrstop
#endif

#include "wx/numformatter.h"
#include "wx/intl.h"

#include <locale.h> // for setlocale and LC_ALL

// ----------------------------------------------------------------------------
// local helpers
// ----------------------------------------------------------------------------

namespace
{

// Contains information about the locale which was used to initialize our
// cached values of the decimal and thousands separators. Notice that it isn't
// enough to store just wxLocale because the user code may call setlocale()
// directly and storing just C locale string is not enough because we can use
// the OS API directly instead of the CRT ones on some platforms. So just store
// both.
class LocaleId
{
public:
    LocaleId()
    {
#if wxUSE_INTL
        m_wxloc = NULL;
#endif // wxUSE_INTL
        m_cloc = NULL;
    }

    ~LocaleId()
    {
        Free();
    }

#if wxUSE_INTL
    // Return true if this is the first time this function is called for this
    // object or if the program locale has changed since the last time it was
    // called. Otherwise just return false indicating that updating locale-
    // dependent information is not necessary.
    bool NotInitializedOrHasChanged()
    {
        wxLocale * const wxloc = wxGetLocale();
        const char * const cloc = setlocale(LC_ALL, NULL);
        if ( m_wxloc || m_cloc )
        {
            if ( m_wxloc == wxloc && strcmp(m_cloc, cloc) == 0 )
                return false;

            Free();
        }
        //else: Not initialized yet.

        m_wxloc = wxloc;
        m_cloc = wxCRT_StrdupA(cloc);

        return true;
    }
#endif // wxUSE_INTL

private:
    void Free()
    {
#if wxUSE_INTL
        free(m_cloc);
#endif // wxUSE_INTL
    }

#if wxUSE_INTL
    // Non-owned pointer to wxLocale which was used.
    wxLocale *m_wxloc;
#endif // wxUSE_INTL

    // Owned pointer to the C locale string.
    char *m_cloc;

    wxDECLARE_NO_COPY_CLASS(LocaleId);
};

} // anonymous namespace

// ============================================================================
// wxNumberFormatter implementation
// ============================================================================

// ----------------------------------------------------------------------------
// Locale information accessors
// ----------------------------------------------------------------------------

wxChar wxNumberFormatter::GetDecimalSeparator()
{
#if wxUSE_INTL
    // Notice that while using static variable here is not MT-safe, the worst
    // that can happen is that we redo the initialization if we're called
    // concurrently from more than one thread so it's not a real problem.
    static wxChar s_decimalSeparator = 0;

    // Remember the locale which was current when we initialized, we must redo
    // the initialization if the locale changed.
    static LocaleId s_localeUsedForInit;

    if ( s_localeUsedForInit.NotInitializedOrHasChanged() )
    {
        const wxString
            s = wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER);
        if ( s.empty() )
        {
            // We really must have something for decimal separator, so fall
            // back to the C locale default.
            s_decimalSeparator = '.';
        }
        else
        {
            // To the best of my knowledge there are no locales like this.
            wxASSERT_MSG( s.length() == 1,
                          "Multi-character decimal separator?" );

            s_decimalSeparator = s[0];
        }
    }

    return s_decimalSeparator;
#else // !wxUSE_INTL
    return wxT('.');
#endif // wxUSE_INTL/!wxUSE_INTL
}

bool wxNumberFormatter::GetThousandsSeparatorIfUsed(wxChar *sep)
{
#if wxUSE_INTL
    static wxChar s_thousandsSeparator = 0;
    static LocaleId s_localeUsedForInit;

    if ( s_localeUsedForInit.NotInitializedOrHasChanged() )
    {
        const wxString
            s = wxLocale::GetInfo(wxLOCALE_THOUSANDS_SEP, wxLOCALE_CAT_NUMBER);
        if ( !s.empty() )
        {
            wxASSERT_MSG( s.length() == 1,
                          "Multi-character thousands separator?" );

            s_thousandsSeparator = s[0];
        }
        //else: Unlike above it's perfectly fine for the thousands separator to
        //      be empty if grouping is not used, so just leave it as 0.
    }

    if ( !s_thousandsSeparator )
        return false;

    if ( sep )
        *sep = s_thousandsSeparator;

    return true;
#else // !wxUSE_INTL
    wxUnusedVar(sep);
    return false;
#endif // wxUSE_INTL/!wxUSE_INTL
}

// ----------------------------------------------------------------------------
// Conversion to string and helpers
// ----------------------------------------------------------------------------

wxString wxNumberFormatter::PostProcessIntString(wxString s, int style)
{
    if ( style & Style_WithThousandsSep )
        AddThousandsSeparators(s);

    wxASSERT_MSG( !(style & Style_NoTrailingZeroes),
                  "Style_NoTrailingZeroes can't be used with integer values" );

    return s;
}

wxString wxNumberFormatter::ToString(long val, int style)
{
    return PostProcessIntString(wxString::Format("%ld", val), style);
}

#ifdef wxHAS_LONG_LONG_T_DIFFERENT_FROM_LONG

wxString wxNumberFormatter::ToString(wxLongLong_t val, int style)
{
    return PostProcessIntString(wxString::Format("%" wxLongLongFmtSpec "d", val),
                                style);
}

#endif // wxHAS_LONG_LONG_T_DIFFERENT_FROM_LONG

wxString wxNumberFormatter::ToString(double val, int precision, int style)
{
    wxString s = wxString::FromDouble(val,precision);

    if ( style & Style_WithThousandsSep )
        AddThousandsSeparators(s);

    if ( style & Style_NoTrailingZeroes )
        RemoveTrailingZeroes(s);

    return s;
}

void wxNumberFormatter::AddThousandsSeparators(wxString& s)
{
    // Thousands separators for numbers in scientific format are not relevant.
    if ( s.find_first_of("eE") != wxString::npos )
        return;

    wxChar thousandsSep;
    if ( !GetThousandsSeparatorIfUsed(&thousandsSep) )
        return;

    size_t pos = s.find(GetDecimalSeparator());
    if ( pos == wxString::npos )
    {
        // Start grouping at the end of an integer number.
        pos = s.length();
    }

    // End grouping at the beginning of the digits -- there could be at a sign
    // before their start.
    const size_t start = s.find_first_of("0123456789");

    // We currently group digits by 3 independently of the locale. This is not
    // the right thing to do and we should use lconv::grouping (under POSIX)
    // and GetLocaleInfo(LOCALE_SGROUPING) (under MSW) to get information about
    // the correct grouping to use. This is something that needs to be done at
    // wxLocale level first and then used here in the future (TODO).
    const size_t GROUP_LEN = 3;

    while ( pos > start + GROUP_LEN )
    {
        pos -= GROUP_LEN;
        s.insert(pos, thousandsSep);
    }
}

void wxNumberFormatter::RemoveTrailingZeroes(wxString& s)
{
    // If number is in scientific format, trailing zeroes belong to the exponent and cannot be removed.
    if ( s.find_first_of("eE") != wxString::npos )
        return;

    const size_t posDecSep = s.find(GetDecimalSeparator());
    // No decimal point => removing trailing zeroes irrelevant for integer number.
    if ( posDecSep == wxString::npos )
        return;
    wxCHECK_RET( posDecSep, "Can't start with decimal separator" );

    // Find the last character to keep.
    size_t posLastNonZero = s.find_last_not_of("0");

    // If it's the decimal separator itself, don't keep it neither.
    if ( posLastNonZero == posDecSep )
        posLastNonZero--;

    s.erase(posLastNonZero + 1);
    // Remove sign from orphaned zero.
    if ( s.compare("-0") == 0 )
        s = "0";
}

// ----------------------------------------------------------------------------
// Conversion from strings
// ----------------------------------------------------------------------------

void wxNumberFormatter::RemoveThousandsSeparators(wxString& s)
{
    wxChar thousandsSep;
    if ( !GetThousandsSeparatorIfUsed(&thousandsSep) )
        return;

    s.Replace(wxString(thousandsSep), wxString());
}

bool wxNumberFormatter::FromString(wxString s, long *val)
{
    RemoveThousandsSeparators(s);
    return s.ToLong(val);
}

#ifdef wxHAS_LONG_LONG_T_DIFFERENT_FROM_LONG

bool wxNumberFormatter::FromString(wxString s, wxLongLong_t *val)
{
    RemoveThousandsSeparators(s);
    return s.ToLongLong(val);
}

#endif // wxHAS_LONG_LONG_T_DIFFERENT_FROM_LONG

bool wxNumberFormatter::FromString(wxString s, double *val)
{
    RemoveThousandsSeparators(s);
    return s.ToDouble(val);
}


text:
package com.heisenberg.test.execution;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.heisenberg.api.DataTypes;
import com.heisenberg.api.activitytypes.ScriptTask;
import com.heisenberg.api.builder.WorkflowBuilder;
import com.heisenberg.api.instance.WorkflowInstance;
import com.heisenberg.test.WorkflowTest;

/**
 * @author Walter White
 */
public class ScriptTest extends WorkflowTest {

  @Test
  public void testScript() {
    WorkflowBuilder process = workflowEngine.newWorkflow();

    process.newVariable()
      .id("n")
      .dataType(DataTypes.TEXT);

    process.newVariable()
      .id("m")
      .dataType(DataTypes.TEXT);

    process.newActivity()
      .activityType(new ScriptTask()
        .variableMapping("name", "n")
        .variableMapping("message", "m")
        .script("message = 'Hello ' + name;")
      )
      .id("a");

    String workflowId = process.deploy();

    WorkflowInstance workflowInstance = workflowEngine.newStart()
      .workflowId(workflowId)
      .variableValue("n", "World")
      .startWorkflowInstance();

    assertEquals("Hello World", workflowInstance.getVariable("m"));
  }
}


text:
module Finitio
  module HashBasedType

    def generate_data(generator, world = nil)
      tuple = {}
      heading.each do |a|
        if a.required or generator.flip_coin
          tuple[a.name.to_sym] = generator.call(a.type, world)
        end
      end
      tuple
    end

  end # class HashBasedType
end # module Finitio


text:
<?php

/**
 * @file
 * Contains \Drupal\aggregator\Form\FeedDeleteForm.
 */

namespace Drupal\aggregator\Form;

use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Url;

/**
 * Provides a form for deleting a feed.
 */
class FeedDeleteForm extends ContentEntityDeleteForm {

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('aggregator.admin_overview');
  }

  /**
   * {@inheritdoc}
   */
  protected function getRedirectUrl() {
    return $this->getCancelUrl();
  }

  /**
   * {@inheritdoc}
   */
  protected function getDeletionMessage() {
    return $this->t('The feed %label has been deleted.', array(
      '%label' => $this->entity->label(),
    ));
  }

}


text:
<?php
namespace Coulondre\JobeetBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Coulondre\JobeetBundle\Entity\Job;

class LoadJobData extends AbstractFixture implements OrderedFixtureInterface
{
  public function load(ObjectManager $em)
  {
    $job_sensio_labs = new Job();
    $job_sensio_labs->setCategory($em->merge($this->getReference('category-programming')));
    $job_sensio_labs->setType('full-time');
    $job_sensio_labs->setCompany('Sensio Labs');
    $job_sensio_labs->setLogo('sensio-labs.gif');
    $job_sensio_labs->setUrl('http://www.sensiolabs.com/');
    $job_sensio_labs->setPosition('Web Developer');
    $job_sensio_labs->setLocation('Paris, France');
    $job_sensio_labs->setDescription('You\'ve already developed websites with symfony and you want to work with Open-Source technologies. You have a minimum of 3 years experience in web development with PHP or Java and you wish to participate to development of Web 2.0 sites using the best frameworks available.');
    $job_sensio_labs->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
    $job_sensio_labs->setIsPublic(true);
    $job_sensio_labs->setIsActivated(true);
    $job_sensio_labs->setToken('job_sensio_labs');
    $job_sensio_labs->setEmail('job@example.com');
    $job_sensio_labs->setExpiresAt(new \DateTime('2012-10-10'));

    $job_extreme_sensio = new Job();
    $job_extreme_sensio->setCategory($em->merge($this->getReference('category-design')));
    $job_extreme_sensio->setType('part-time');
    $job_extreme_sensio->setCompany('Extreme Sensio');
    $job_extreme_sensio->setLogo('extreme-sensio.gif');
    $job_extreme_sensio->setUrl('http://www.extreme-sensio.com/');
    $job_extreme_sensio->setPosition('Web Designer');
    $job_extreme_sensio->setLocation('Paris, France');
    $job_extreme_sensio->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in.');
    $job_extreme_sensio->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
    $job_extreme_sensio->setIsPublic(true);
    $job_extreme_sensio->setIsActivated(true);
    $job_extreme_sensio->setToken('job_extreme_sensio');
    $job_extreme_sensio->setEmail('job@example.com');
    $job_extreme_sensio->setExpiresAt(new \DateTime('2012-10-10'));

    $job_expired = new Job();
    $job_expired->setCategory($em->merge($this->getReference('category-programming')));
    $job_expired->setType('full-time');
    $job_expired->setCompany('Sensio Labs');
    $job_expired->setLogo('sensio-labs.gif');
    $job_expired->setUrl('http://www.sensiolabs.com/');
    $job_expired->setPosition('Web Developer Expired');
    $job_expired->setLocation('Paris, France');
    $job_expired->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit.');
    $job_expired->setHowToApply('Send your resume to lorem.ipsum [at] dolor.sit');
    $job_expired->setIsPublic(true);
    $job_expired->setIsActivated(true);
    $job_expired->setToken('job_expired');
    $job_expired->setEmail('job@example.com');
    $job_expired->setCreatedAt(new \DateTime('2005-12-01'));
    $job_expired->setExpiresAt(new \DateTime('2005-12-01'));

    $em->persist($job_sensio_labs);
    $em->persist($job_extreme_sensio);
    $em->persist($job_expired);

    for($i = 100; $i <= 130; $i++)
    {
    $job = new Job();
    $job->setCategory($em->merge($this->getReference('category-programming')));
    $job->setType('full-time');
    $job->setCompany('Company '.$i);
    $job->setPosition('Web Developer');
    $job->setLocation('Paris, France');
    $job->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit.');
    $job->setHowToApply('Send your resume to lorem.ipsum [at] dolor.sit');
    $job->setIsPublic(true);
    $job->setIsActivated(true);
    $job->setToken('job_'.$i);
    $job->setEmail('job@example.com');
    $job->setExpiresAt(new \DateTime('2012-10-10'));

    $em->persist($job);
  }

    $em->flush();
  }

  public function getOrder()
  {
    return 2; // the order in which fixtures will be loaded
  }
}


text:
package org.apache.nuvem.cloud.xmpp.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.nuvem.cloud.xmpp.api.Error;
import org.apache.nuvem.cloud.xmpp.api.ErrorCode;
import org.apache.nuvem.cloud.xmpp.api.Status;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.SendResponse;

/**
 * Acts as an adapter to transform the status recieved by the the send API to
 * the form compatible with nuvem.
 */
public class GoogleStatusAdapter {

    /**
     * converstion map.
     */
    private static Map<SendResponse.Status, ErrorCode> converstionMap;

    static {
        converstionMap = new HashMap<SendResponse.Status, ErrorCode>();
        converstionMap.put(SendResponse.Status.INVALID_ID, ErrorCode.INVALID_ID);
        converstionMap.put(SendResponse.Status.OTHER_ERROR, ErrorCode.UNKNOWN_ERROR);
    }

    public static Status toStatus(SendResponse responseStatus) {
        Status status = new Status();
        ErrorCode code = null;
        if (responseStatus != null && responseStatus.getStatusMap() != null && !responseStatus.getStatusMap().isEmpty()) {
            Map<JID, SendResponse.Status> statuses = responseStatus.getStatusMap();
            for (JID jid : statuses.keySet()) {
                if (converstionMap.containsKey(statuses.get(jid)))
                    status.addError(new Error(code, "For :" + jid.getId()));
            }
        }
        return status;

    }
}


text:
Examples from the cats documentation at https://typelevel.org/cats/

## Notes

* Versions have recently been bumped to 2.0.0 but the examples have not been updated yet


text:
from flask import Blueprint, render_template, request, Response
from flask import redirect, make_response
from sqlalchemy import or_, and_
from sqlalchemy.orm import aliased

from grano.lib.serialisation import jsonify
from grano.lib.exc import BadRequest
from grano.lib.args import object_or_404, request_data
from grano.model import Entity, Schema, EntityProperty, Project, Permission
from grano.logic import entities, relations
from grano.logic.references import ProjectRef
from grano.logic.graph import GraphExtractor
from grano.lib.pager import Pager
from grano.lib.exc import Gone, BadRequest
from grano.core import app, db, url_for
from grano.views.util import filter_query
from grano.views.cache import validate_cache
from grano import authz

blueprint = Blueprint('entities_api', __name__)

@blueprint.route('/api/1/entities', methods=['GET'])
def index():
    query = filter_query(Entity, Entity.all(), request.args)

    if 'q' in request.args and len(request.args.get('q').strip()):
        q = '%%%s%%' % request.args.get('q').strip()
        query = query.join(EntityProperty)
        query = query.filter(EntityProperty.name=='name')
        query = query.filter(EntityProperty.value_string.ilike(q))

    for schema in request.args.getlist('schema'):
        if not len(schema.strip()):
            continue
        alias = aliased(Schema)
        query = query.join(alias, Entity.schemata)
        query = query.filter(alias.name.in_(schema.split(',')))

    query = query.filter(Entity.same_as==None)
    query = query.distinct()
    pager = Pager(query)
    validate_cache(keys=pager.cache_keys())
    return jsonify(pager, index=True)

@blueprint.route('/api/1/entities', methods=['POST', 'PUT'])
def create():
    data = request_data({'author': request.account})
    project = ProjectRef().get(data.get('project'))
    data['project'] = project
    authz.require(authz.project_edit(project))
    entity = entities.save(data)
    db.session.commit()
    return jsonify(entity)

@blueprint.route('/api/1/entities/<id>', methods=['GET'])
def view(id):
    entity = object_or_404(Entity.by_id(id))
    authz.require(authz.project_read(entity.project))
    return jsonify(entity)

@blueprint.route('/api/1/entities/<id>/graph', methods=['GET'])
def graph(id):
    entity = object_or_404(Entity.by_id(id))
    authz.require(authz.project_read(entity.project))
    extractor = GraphExtractor(root_id=entity.id)
    validate_cache(keys=extractor.to_hash())
    if extractor.format == 'gexf':
        return Response(extractor.to_gexf(),
                mimetype='text/xml')
    return jsonify(extractor)

@blueprint.route('/api/1/entities/_suggest', methods=['GET'])
def suggest():
    if not 'q' in request.args or not len(request.args.get('q').strip()):
        raise BadRequest("Missing the query ('q' parameter).")

    q = db.session.query(EntityProperty)
    q = q.join(Entity)
    q = q.join(Project)
    q = q.outerjoin(Permission)
    q = q.filter(or_(Project.private==False,
        and_(Permission.reader==True, Permission.account==request.account)))

    q = q.filter(EntityProperty.name=='name')
    q = q.filter(EntityProperty.active==True)
    q = q.filter(EntityProperty.entity_id!=None)
    q = q.filter(EntityProperty.value_string.ilike(request.args.get('q') + '%'))
    if 'project' in request.args:
        q = q.filter(Project.slug==request.args.get('project'))

    q = q.distinct()
    pager = Pager(q)

    data = []
    def convert(props):
        for prop in props:
            data.append({
                'name': prop.value,
                'id': prop.entity_id,
                'api_url': url_for('entities_api.view', id=prop.entity_id)
            })
        return data

    validate_cache(keys='#'.join([d['name'] for d in data]))
    return jsonify(pager.to_dict(results_converter=convert))

@blueprint.route('/api/1/entities/<id>', methods=['POST', 'PUT'])
def update(id):
    entity = object_or_404(Entity.by_id(id))
    authz.require(authz.project_edit(entity.project))
    data = request_data({'author': request.account})
    entity = entities.save(data, entity=entity)
    db.session.commit()
    return jsonify(entity)

@blueprint.route('/api/1/entities/_merge', methods=['POST', 'PUT'])
def merge():
    validator = entities.MergeValidator()
    data = validator.deserialize(request_data())
    authz.require(authz.project_edit(data['orig'].project))

    if data['orig'].id == data['dest'].id:
        raise BadRequest('Origin and destination are identical.')

    if data['orig'].project_id != data['dest'].project_id:
        raise BadRequest('Entities belong to different projects.')

    dest = entities.merge(data['orig'], data['dest'])
    db.session.commit()
    return jsonify(dest)

@blueprint.route('/api/1/entities/<id>', methods=['DELETE'])
def delete(id):
    entity = object_or_404(Entity.by_id(id))
    authz.require(authz.project_edit(entity.project))
    entities.delete(entity)
    db.session.commit()
    raise Gone()


text:
'use strict';
var mongoose = require('mongoose');

var db = function () {
    return {
        config: function (conf) {
            var defaultdb = 'mongodb://localhost:27017/MobYourLife';
            mongoose.connect(process.env.MONGOLAB_CONNECTION || defaultdb);
            var db = mongoose.connection;
            db.on('error', console.error.bind(console, 'connection error:'));
            db.once('open', function callback() {
                console.log('db connection open');
            });
        }
    };
};

module.exports = db();


text:
<!DOCTYPE html>

    <title>Example</title>

    <link rel="stylesheet" type="text/css" href="styles.css"/>

Jacqui's Flower Shop

    <form method="post">

                        Astor:
                        <input name="astor" value="0" required>

                        Daffodil:
                        <input name="daffodil" value="0" required >

                        Rose:
                        <input name="rose" value="0" required>

                        Peony:
                        <input name="peony" value="0" required>

                        Primula:
                        <input name="primula" value="0" required>

                        Snowdrop:
                        <input name="snowdrop" value="0" required>

<button type="submit">Place Order</button>

    </form>


text:
"""Provides agency object."""

from __future__ import absolute_import
from ..entity import Entity

class Agency(Entity):
    """docstring for Agency"""
    collection = 'agencies'
    resource = 'agency'
    _relations = {
        'organization', 'billing_contact', 'sales_contact',
        'traffic_contact',
    }
    _pull = {
        'allow_x_adv_optimization': Entity._int_to_bool,
        'allow_x_adv_pixels': Entity._int_to_bool,
        'billing_contact_id': int,
        'created_on': Entity._strpt,
        'id': int,
        'logo': None,
        'name': None,
        'organization_id': int,
        'sales_contact_id': int,
        'status': Entity._int_to_bool,
        'updated_on': Entity._strpt,
        'version': int,
    }
    _push = _pull.copy()
    _push.update({
        'allow_x_adv_optimization': int,
        'allow_x_adv_pixels': int,
        'status': int,
    })

    def __init__(self, session, properties=None, **kwargs):
        super(Agency, self).__init__(session, properties, **kwargs)


text:
module ElbowPatch
  class Railtie < ::Rails::Railtie
    initializer "load cve patches" do
      Dir[File.expand_path('../cve/*.rb', __FILE__)].each do |filename|
        require filename
      end
    end
  end
end


text:
rowSize = 20;				//global
var puzzle;						//global!
var dictionary;
var clientList;
var gameStarted = false;
var gameTime = 120 * 1000;
var startGameTimeOut = gameTime/2;
var captainName;
var saveServer;
fs = require('fs');

function Player(){};
Player.prototype.name = 'player';
Player.prototype.score = 0;

var PlayerList = function(){};
PlayerList.prototype = new Array();
PlayerList.prototype.incScore = function(name,incFactor){
	var i;
	for(i = 0; i < this.length; i++){
		if(this[i].name === name){
			this[i].score += incFactor;
			break;
		}
	}
}
var playerList;

exports.initGame = function(){
	//generatePuzzle(rowSize);			//populate global variable puzzle
	var rndPuzzFile = Math.floor((Math.random()*5)+1);		//total puzzle files are 5; pick random in 1 to 5
	var puzzleFilePath = "public/puzzles/puzz" + rndPuzzFile + ".txt";
	console.log("random file: " + rndPuzzFile);
	readPuzzle(puzzleFilePath);
	fs.readFile('wordList.txt', 'ascii', function (err,data) {
		if (err) {
			return console.log(err);
		}
		dictionary = data.split("\n");
	});
	if(!clientList)
		clientList = new Array();
	if(typeof(playerList) === 'undefined' || playerList === null)
		playerList = new PlayerList();
}

exports.start = function(req,res){
	if(!req.session.name || playerList.length === 0)
		res.redirect("/");
	else if(gameStarted)
		res.render('error', {errorMsg: "Sorry game has started"});
	else{
		var captain = false;
		var temp, i = 0;
		if(!clientList)
			clientList = new Array();
		if(playerList[0].name === req.session.name){
			captainName = req.session.name;
			captain = true;
			saveServer = setTimeout(function(){							//this is to prevent game lock if captain gets lost.
				clientList = null;									 //delete clientList
				playerList = new PlayerList();									//delete playerList
			},startGameTimeOut);
		}
		res.render('game', {player: req.session.name, captain : captain, hostName : req.headers.host});
	}
}

exports.newUser = function(req, res){				// post on /start
	var playerName = req.body.playerName;
	var newPlayer = new Player();
	newPlayer.name = playerName;
	newPlayer.score = 0;
	playerList.push(newPlayer);
	req.session.name = playerName;
	req.session.score = 0;
	res.redirect("/start")
}

exports.sendPuzz = function(req,res){
	res.json({puzz : puzzle});
}

exports.sockOnConnection = function (socket) {
	clientList.push(socket);

	socket.on('chkAns', function(data){
		if(chkAns(data)){
			updateAll(data);
			playerList.incScore(data.playerName, 1);
		}
	})
	socket.on('startGame', function(data){
		gameStarted = true;
		var name = data.playerName;
		if(name == captainName){
			for(var i = 0; i < clientList.length; i++){
				clientList[i].emit('startGame',data);
			}
			clearTimeout(saveServer);
			setTimeout(function(){
				if(gameStarted){
					for(var i = 0; i < clientList.length; i++){
						clientList[i].emit('gameOver',playerList);
					}
					clientList = null;									 //delete clientList
					playerList = new PlayerList();									//delete playerList
					gameStarted = false;
				}
			},gameTime);
		}
	});
	function updateAll(data){
		if(clientList){
			for(var i = 0; i < clientList.length; i++){
				clientList[i].emit('update',data);
			}
		}
	}
}

function chkAns(data){
	var startPt = data.startPt.split('-');
	var endPt = data.endPt.split('-');
	var word = getStringFromPuzzle(startPt,endPt);
	word = word.toLowerCase();
	if(dictionary.indexOf(word) != -1)
		return true;
	else
		return false;
}

function getStringFromPuzzle(startPt,endPt){
	startPt[0] = parseInt(startPt[0]);
	startPt[1] = parseInt(startPt[1]);
	endPt[0] = parseInt(endPt[0]);
	endPt[1] = parseInt(endPt[1]);
	var word = '';
	if(startPt[0] == endPt[0]){			//horizontal
		if(startPt[1] < endPt[1]){				//go right
			for(;startPt[1] <= endPt[1]; startPt[1]++){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
		else {									//go left
			for(;startPt[1] >= endPt[1]; startPt[1]--){
				word += puzzle[startPt[0]][startPt[1]];;
			}
		}
	}
	else if(startPt[1] == endPt[1]){		//vertical
		if(startPt[0] < endPt[0]){
			for(;startPt[0] <= endPt[0]; startPt[0]++){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
		else {
			for(;startPt[0] >= endPt[0]; startPt[0]--){
				word += puzzle[startPt[0]][startPt[1]];;
			}
		}
	}
	else {									//diagonal
		if(startPt[0] < endPt[0] && startPt[1] < endPt[1]){					//go south east
			for(;startPt[0] <= endPt[0] && startPt[1] <= endPt[1]; startPt[0]++, startPt[1]++){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
		else if(startPt[0] > endPt[0] && startPt[1] > endPt[1]){					//go north west
			for(;startPt[0] >= endPt[0] && startPt[1] >= endPt[1]; startPt[0]--, startPt[1]--){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
		else if(startPt[0] < endPt[0] && startPt[1] > endPt[1]){					//go south west
			for(;startPt[0] <= endPt[0] && startPt[1] >= endPt[1]; startPt[0]++, startPt[1]--){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
		else if(startPt[0] > endPt[0] && startPt[1] < endPt[1]){					//go north east
			for(;startPt[0] >= endPt[0] && startPt[1] <= endPt[1]; startPt[0]--, startPt[1]++){
				word += puzzle[startPt[0]][startPt[1]];
			}
		}
	}
	return word;
}

function generatePuzzle(rowSize){		//in multiplayer we need something like gameID
	var i,j;
	puzzle = new Array();
	for(i = 0; i < rowSize; i++){
		puzzle.push(new Array());
		for(j = 0; j < rowSize; j++)
			puzzle[i].push('a');
	}
}

function readPuzzle(puzzleFilePath){
	var lines;
	var i;
	fs.readFile(puzzleFilePath, 'ascii', function (err,data) {
		if (err) {
			return console.log(err);
		}
		lines = data.split("\n");
		puzzle = new Array();
		for(i = 0; i < lines.length; i++){
			puzzle.push(lines[i].split("\t"));
		}
	});
}


text:
class Admin::TrackbackCodesController < ApplicationController
	layout "admin"
	before_filter :login_required
	access_control [ :index, :new, :update, :edit ] => '(admin)'

  # GET /trackback_codes
  # GET /trackback_codes.xml
  def index
    @trackback_codes = TrackbackCode.find(:all, :conditions => ["type IS NULL"]) # Only retrieve non-affiliates

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @trackback_codes }
    end
  end

  # GET /trackback_codes/1
  # GET /trackback_codes/1.xml
  def show
    @trackback_code = TrackbackCode.first( :name => params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @trackback_code }
    end
  end

  # GET /trackback_codes/new
  # GET /trackback_codes/new.xml
  def new
    @trackback_code = TrackbackCode.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @trackback_code }
    end
  end

  # GET /trackback_codes/1/edit
  def edit
    @trackback_code = TrackbackCode.first(:name => params[:id])
  end

  # POST /trackback_codes
  # POST /trackback_codes.xml
  def create
		begin
			params[:trackback_code][:percentage] = params[:trackback_code][:percentage].to_f
			@trackback_code = TrackbackCode.new(params[:trackback_code])
			@trackback_code.save

			flash[:notice] = 'TrackbackCode was successfully created.'
    	respond_to do |format|
				format.html { redirect_back_or_default(@trackback_code) }
				format.xml  { render :xml => @trackback_code, :status => :created, :location => @trackback_code }
			end
		rescue Exception => ex
			logger.error ex
    	respond_to do |format|
        format.html { render :action => "new" }
        format.xml  { render :xml => @trackback_code.errors, :status => :unprocessable_entity }
			end
		end
  end

  # PUT /trackback_codes/1
  # PUT /trackback_codes/1.xml
  def update
    @trackback_code = TrackbackCode.find(params[:id])

    respond_to do |format|
      if @trackback_code.update_attributes(params[:trackback_code])
        flash[:notice] = 'TrackbackCode was successfully updated.'
        format.html { redirect_to(@trackback_code) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @trackback_code.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /trackback_codes/1
  # DELETE /trackback_codes/1.xml
  def destroy
    @trackback_code = TrackbackCode.find(params[:id])
    @trackback_code.destroy

    respond_to do |format|
      format.html { redirect_to(trackback_codes_url) }
      format.xml  { head :ok }
    end
  end
end


text:
require 'logger'
require 'fileutils'

#
# Service object to oversee the execution of a Scenario
#
module SippyCup
  class Runner
    attr_accessor :sipp_pid

    #
    # Create a runner from a scenario
    #
    # @param [Scenario, XMLScenario] scenario The scenario to execute
    # @param [Hash] opts Options to modify the runner
    # @option opts [optional, true, false] :full_sipp_output Whether or not to copy SIPp's stdout/stderr to the parent process. Defaults to true.
    # @option opts [optional, Logger] :logger A logger to use in place of the internal logger to STDOUT.
    # @option opts [optional, String] :command The command to execute. This is mostly available for testing.
    #
    def initialize(scenario, opts = {})
      @scenario = scenario
      @scenario_options = @scenario.scenario_options

      defaults = { full_sipp_output: true }
      @options = defaults.merge(opts)

      @command = @options[:command]
      @logger = @options[:logger] || Logger.new(STDOUT)
    end

    #
    # Runs the loaded scenario using SIPp
    #
    def run
      @input_files = @scenario.to_tmpfiles

      @logger.info "Preparing to run SIPp command: #{command}"

      execute_with_redirected_streams

      wait unless @options[:async]
    ensure
      cleanup_input_files unless @options[:async]
    end

    #
    # Tries to stop SIPp by killing the target PID
    #
    # @raises Errno::ESRCH when the PID does not correspond to a known process
    # @raises Errno::EPERM when the process referenced by the PID cannot be killed
    #
    def stop
      Process.kill "KILL", @sipp_pid if @sipp_pid
    end

    #
    # Waits for the runner to finish execution
    #
    # @raises Errno::ENOENT when the SIPp executable cannot be found
    # @raises SippyCup::ExitOnInternalCommand when SIPp exits on an internal command. Calls may have been processed
    # @raises SippyCup::NoCallsProcessed when SIPp exit normally, but has processed no calls
    # @raises SippyCup::FatalError when SIPp encounters a fatal failure
    # @raises SippyCup::FatalSocketBindingError when SIPp fails to bind to the specified socket
    # @raises SippyCup::SippGenericError when SIPp encounters another type of error
    #
    # @return Boolean true if execution succeeded without any failed calls, false otherwise
    #
    def wait
      exit_status = Process.wait2 @sipp_pid.to_i
      @rd.close if @rd
      final_result = process_exit_status exit_status, @stderr_buffer
      if final_result
        @logger.info "Test completed successfully!"
      else
        @logger.info "Test completed successfully but some calls failed."
      end
      @logger.info "Statistics logged at #{File.expand_path @scenario_options[:stats_file]}" if @scenario_options[:stats_file]

      final_result
    ensure
      cleanup_input_files
    end

  private

    def command
      @command ||= begin
        command = "sudo $(which sipp)"
        command_options.each_pair do |key, value|
          command << (value ? " -#{key} #{value}" : " -#{key}")
        end
        command << " #{@scenario_options[:destination]}"
      end
    end

    def command_options
      options = {
        p: @scenario_options[:source_port] || '8836',
        sf: @input_files[:scenario].path,
        l: @scenario_options[:concurrent_max] || @scenario_options[:max_concurrent] || 5,
        m: @scenario_options[:number_of_calls] || 10,
        r: @scenario_options[:calls_per_second] || 10,
        s: @scenario_options[:to_user] || '1'
      }

      options[:i] = @scenario_options[:source] if @scenario_options[:source]
      options[:mp] = @scenario_options[:media_port] if @scenario_options[:media_port]

      if @scenario_options[:calls_per_second_max]
        options[:no_rate_quit] = nil
        options[:rate_max] = @scenario_options[:calls_per_second_max]
        options[:rate_increase] = @scenario_options[:calls_per_second_incr] || 1
      end

      if @scenario_options[:stats_file]
        options[:trace_stat] = nil
        options[:stf] = @scenario_options[:stats_file]
        options[:fd] = @scenario_options[:stats_interval] || 1
      end

      if @scenario_options[:summary_report_file]
        options[:trace_screen] = nil
        options[:screen_file] = @scenario_options[:summary_report_file]
      end

      if @scenario_options[:errors_report_file]
        options[:trace_err] = nil
        options[:error_file] = @scenario_options[:errors_report_file]
      end

      if @scenario_options[:transport_mode]
        options[:t] = @scenario_options[:transport_mode]
      end

      if @scenario_options[:scenario_variables]
        options[:inf] = @scenario_options[:scenario_variables]
      end

      options.merge! @scenario_options[:options] if @scenario_options[:options]

      options
    end

    def execute_with_redirected_streams
      @rd, wr = IO.pipe
      stdout_target = @options[:full_sipp_output] ? $stdout : '/dev/null'

      @sipp_pid = spawn command, err: wr, out: stdout_target

      @stderr_buffer = String.new

      Thread.new do
        wr.close
        until @rd.eof?
          buffer = @rd.readpartial(1024).strip
          @stderr_buffer += buffer
          $stderr << buffer if @options[:full_sipp_output]
        end
      end
    end

    def process_exit_status(process_status, error_message = nil)
      exit_code = process_status[1].exitstatus
      case exit_code
      when 0
        true
      when 1
        false
      when 97
        raise SippyCup::ExitOnInternalCommand, error_message
      when 99
        raise SippyCup::NoCallsProcessed, error_message
      when 255
        raise SippyCup::FatalError, error_message
      when 254
        raise SippyCup::FatalSocketBindingError, error_message
      else
        raise SippyCup::SippGenericError, error_message
      end
    end

    def cleanup_input_files
      @input_files.values.compact.each do |value|
        value.close
        value.unlink
      end if @input_files
    end
  end

  # The corresponding SIPp error code is listed after the exception
  class Error < StandardError; end
  class ExitOnInternalCommand < Error; end # 97
  class NoCallsProcessed < Error; end # 99
  class FatalError < Error; end # -1
  class FatalSocketBindingError < Error; end # -2
  class SippGenericError < Error; end # 255 and undocumented errors
end


text:
/**
 * @author Vladimir Kozhin <affka@affka.ru>
 * @license MIT
 */

'use strict';

const Jii = require('../../BaseJii');
const Server = require('./Server');
const Component = require('../../base/Component');
const Event = require('../../base/Event');
const ActiveRecord = require('../../data/BaseActiveRecord');
const InvalidConfigException = require('../../exceptions/InvalidConfigException');
const _isFunction = require('lodash/isFunction');
const _isEmpty = require('lodash/isEmpty');
const _extend = require('lodash/extend');
const BaseObject = require('../../base/BaseObject');
const NeatComet = require('neatcomet');

class NeatServer extends BaseObject {

    preInit() {
        /**
         * @type {NeatComet.NeatCometServer}
         */
        this.engine = null;

        /**
         * Note: onOpenProfileCommand() and onCloseProfileCommand must be called from actions explicitly.
         * There's no way to subscribe for them in Jii.
         *
         * @type {NeatComet.api.ICometServerEvents}
         */
        this._events = null;

        /**
         * @type {boolean}
         */
        this.listenModels = true;

        /**
         * @type {object|boolean}
         */
        this.hasDynamicAttributes = false;

        /**
         * Callback function to be called when folder loaded from server.
         * @callback NeatServer~dataLoadHandlerCallback
         * @param {object} params
         * @returns {Promise}
         */
        /**
         * @type {NeatServer~dataLoadHandlerCallback}
         */
        this.dataLoadHandler = null;

        /**
         * @type {Server}
         **/
        this.comet = null;

        /**
         * @type {object}
         */
        this.bindings = null;

        /**
         * @type {string}
         * @deprecated
         */
        this.configFileName = null;

        super.preInit(...arguments);
    }

    init() {
        super.init();

        // Init transport
        this.comet = this.comet === null ? Jii.app.get('comet') : this.comet instanceof Component ? this.comet : Jii.createObject(this.comet);

        this.engine = new NeatComet.NeatCometServer();
        this.engine.setup({
            comet: this,
            ormLoader: this,
            configFileName: this.configFileName || this.bindings,
            externalDataLoader: this.dataLoadHandler
        });

        Jii.app.inlineActions['neat/open'] = this._actionOpenProfile.bind(this);
        Jii.app.inlineActions['neat/close'] = this._actionCloseProfile.bind(this);

        if (this.listenModels && ActiveRecord) {
            Event.on(ActiveRecord, ActiveRecord.EVENT_AFTER_INSERT, this._onModelInsert.bind(this));
            Event.on(ActiveRecord, ActiveRecord.EVENT_AFTER_UPDATE, this._onModelUpdate.bind(this));
            Event.on(ActiveRecord, ActiveRecord.EVENT_AFTER_DELETE, this._onModelDelete.bind(this));
        }
    }

    /**
     * Allowed to expect that it will be called only once per ICometServer instance
     * @param {NeatComet.api.ICometServerEvents} eventsHandler
     */
    bindServerEvents(eventsHandler) {
        this._events = eventsHandler;

        this.comet.on(Server.EVENT_ADD_CONNECTION, event => {
            eventsHandler.onNewConnection(event.connection.id);
        });
        this.comet.on(Server.EVENT_REMOVE_CONNECTION, event => {
            eventsHandler.onLostConnection(event.connection.id);
        });
    }

    /**
     * @return {boolean}
     */
    getSupportsForwardToClient() {
        // TODO: Implement
        return false;
    }

    /**
     * @param {String} channel
     * @param {*} message
     */
    broadcast(channel, message) {
        this.comet.sendToChannel(this.constructor.ROUTE_PREFIX + channel, message);
    }

    /**
     * @param {String} channel
     * @param {Function} callback
     */
    subscribe(channel, callback) {
        /**
         * @param ChannelEvent event
         */
        callback.__jiiCallbackWrapper = event => {
            callback(event.channel.substr(this.constructor.ROUTE_PREFIX.length), JSON.parse(event.message));
        };

        this.comet.on('channel:' + this.constructor.ROUTE_PREFIX + channel, callback.__jiiCallbackWrapper);
    }

    /**
     * @param {String} channel
     * @param {Function} callback
     */
    unsubscribe(channel, callback) {
        if (callback && callback.__jiiCallbackWrapper) {
            callback = callback.__jiiCallbackWrapper;
        }
        this.comet.off('channel:' + this.constructor.ROUTE_PREFIX + channel, callback);
    }

    /**
     *
     * @param connectionId
     * @param channel
     * @param data
     */
    pushToClient(connectionId, channel, data) {
        this.comet.sendToConnection(connectionId, [
            'channel',
            this.constructor.ROUTE_PREFIX + channel,
            JSON.stringify(data)
        ].join(' '));
    }

    /**
     * @param {string|ActiveQuery} modelClassName
     * @param {object|null} match
     * @param {string} whereType
     * @param {string|null} where
     * @param {object} attributes
     * @param {NeatComet.bindings.BindingServer} binding
     * @returns {Promise} Array of records data
     */
    loadRecords(modelClassName, match, whereType, where, attributes, binding) {

        /** @typedef {BaseActiveRecord} modelClass  */
        var modelClass = Jii.namespace(modelClassName);
        if (!_isFunction(modelClass)) {
            throw new InvalidConfigException('Not found model `' + modelClassName + '` for binding');
        }

        /** @typedef {ActiveQuery} query  */
        var query = modelClass.find();

        // Apply match condition
        if (match) {
            query.where(match);
        }

        // Apply custom filter
        switch (whereType) {

            case NeatComet.api.IOrmLoader.WHERE_NONE:
                // Find all
                break;

            case NeatComet.api.IOrmLoader.WHERE_JS:
                where = NeatComet.bindings.BindingServer.convertWhereJsToSql(where);
                break;

            case NeatComet.api.IOrmLoader.WHERE_SQL:
                where = NeatComet.bindings.BindingServer.convertWhereJsToSql(where);
                query.from(modelClass.tableName() + ' ' + NeatComet.api.IOrmLoader.TABLE_ALIAS_IN_SQL).andWhere(where, NeatComet.bindings.BindingServer.filterAttributesBySqlParams(where, attributes));
                break;

            default:
                throw new InvalidConfigException('Where type `' + whereType + '` is not implemented');
        }

        // Query via model implementation
        if (!_isEmpty(this.hasDynamicAttributes)) {
        } else {
            if (binding.attributes !== null) {
                query.select(binding.attributes);
            }
            return query.asArray().all();
        }
    }

    /**
     *
     * @param {AfterSaveEvent} event
     * @param {} event.sender
     * @private
     */
    _onModelInsert(event) {
        /** @typedef {ActiveRecord} model */
        var model = event.sender;

        this.engine.broadcastEvent(model.className(), 'sendAdd', model.getAttributes());
    }

    /**
     *
     * @param {AfterSaveEvent} event
     * @param {ActiveRecord} event.sender
     * @private
     */
    _onModelUpdate(event) {
        /** @typedef {ActiveRecord} model */
        var model = event.sender;

        var oldAttributes = _extend({}, event.changedAttributes, model.getOldAttributes());
        this.engine.broadcastEvent(model.className(), 'sendUpdate', model.getAttributes(), oldAttributes);
    }

    /**
     *
     * @param {Event} event
     * @param {ActiveRecord} event.sender
     * @private
     */
    _onModelDelete(event) {
        /** @typedef {ActiveRecord} model */
        var model = event.sender;

        this.engine.broadcastEvent(model.className(), 'sendRemove', model.getAttributes());
    }

    /**
     * @param {Context} context
     * @param {Connection} context.connection
     * @param {Request} context.request
     * @param {Response} context.response
     */
    _actionOpenProfile(context) {
        this._events.onOpenProfileCommand(context.connection.id, context.request.get('neat')).then(neatResponse => {
            context.response.data = {
                neat: neatResponse
            };
            context.response.send();
        });
    }

    /**
     * @param {Context} context
     * @param {Connection} context.connection
     * @param {Request} context.request
     * @param {Response} context.response
     */
    _actionCloseProfile(context) {
        context.response.send();
        // No wait
        this._events.onCloseProfileCommand(context.connection.id, context.request.get('neat'));
    }

}

NeatServer.ROUTE_PREFIX = 'profiles:';
module.exports = NeatServer;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.hibernate.CallbackException (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.hibernate.CallbackException

Packages that use CallbackException

Package
Description

org.hibernate

org.hibernate.classic

Uses of CallbackException in org.hibernate

Methods in org.hibernate that throw CallbackException

Modifier and Type
Method and Description

Object
Interceptor.getEntity(String entityName,
         Serializable id)

String
Interceptor.getEntityName(Object object)

Object
Interceptor.instantiate(String entityName,
           EntityMode entityMode,
           Serializable id)

void
EmptyInterceptor.onCollectionRecreate(Object collection,
                    Serializable key)

void
Interceptor.onCollectionRecreate(Object collection,
                    Serializable key)

void
EmptyInterceptor.onCollectionRemove(Object collection,
                  Serializable key)

void
Interceptor.onCollectionRemove(Object collection,
                  Serializable key)

void
EmptyInterceptor.onCollectionUpdate(Object collection,
                  Serializable key)

void
Interceptor.onCollectionUpdate(Object collection,
                  Serializable key)

void
Interceptor.onDelete(Object entity,
        Serializable id,
        Object[] state,
        String[] propertyNames,
        Type[] types)

boolean
Interceptor.onFlushDirty(Object entity,
            Serializable id,
            Object[] currentState,
            Object[] previousState,
            String[] propertyNames,
            Type[] types)

boolean
Interceptor.onLoad(Object entity,
      Serializable id,
      Object[] state,
      String[] propertyNames,
      Type[] types)

boolean
Interceptor.onSave(Object entity,
      Serializable id,
      Object[] state,
      String[] propertyNames,
      Type[] types)

void
Interceptor.postFlush(Iterator entities)

void
Interceptor.preFlush(Iterator entities)

Uses of CallbackException in org.hibernate.classic

Methods in org.hibernate.classic that throw CallbackException

Modifier and Type
Method and Description

boolean
Lifecycle.onDelete(Session s)

boolean
Lifecycle.onSave(Session s)

boolean
Lifecycle.onUpdate(Session s)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
//
//  GTLYouTubeActivityContentDetailsRecommendation.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   YouTube Data API (youtube/v3)
// Description:
//   Programmatic access to YouTube features.
// Documentation:
//   https://developers.google.com/youtube/v3
// Classes:
//   GTLYouTubeActivityContentDetailsRecommendation (0 custom class methods, 3 custom properties)

#import "GTLYouTubeActivityContentDetailsRecommendation.h"

#import "GTLYouTubeResourceId.h"

// ----------------------------------------------------------------------------
//
//   GTLYouTubeActivityContentDetailsRecommendation
//

@implementation GTLYouTubeActivityContentDetailsRecommendation
@dynamic reason, resourceId, seedResourceId;
@end


text:
/*
 * ScoringFunctionIteratorTest.java
 * JUnit based test
 *
 * Created on September 14, 2007, 9:04 AM
 */

package org.galagosearch.core.retrieval.extents;

import org.galagosearch.core.retrieval.structured.ScoringFunctionIterator;
import org.galagosearch.core.retrieval.structured.CountIterator;
import junit.framework.*;
import java.io.IOException;

/**
 *
 * @author trevor
 */
public class ScoringFunctionIteratorTest extends TestCase {
    public ScoringFunctionIteratorTest(String testName) {
        super(testName);
    }

    public static class FakeScoreIterator extends ScoringFunctionIterator {
        public FakeScoreIterator( CountIterator iter ) {
            super(iter);
        }

        public double scoreCount(int count, int length){//String kunal,int docCount,int doc) {
            return count + length;
        }
        public double scoreCount1(int count, int length,String kunal,int docCount,int doc) {
            return count + length;
        }
    }

    public void testScore() throws IOException {
        int document = 0;
        int length = 0;

        int[][] data = { { 1, 3 }, { 5, 8, 9 } };
        FakeExtentIterator iterator = new FakeExtentIterator( data );
        FakeScoreIterator instance = new FakeScoreIterator( iterator );

        assertFalse( instance.isDone() );

        assertEquals( instance.nextCandidate(), 1 );
        assertEquals( 4.0, instance.score( 1, 3 ) );
        instance.movePast( 1 );

        assertFalse( instance.isDone() );
        assertEquals( instance.nextCandidate(), 5 );
        assertEquals( 5.0, instance.score( 2, 5 ) );

        assertFalse( instance.isDone() );
        assertEquals( 12.0, instance.score( 5, 10 ) );
        instance.movePast( 5 );

        assertTrue( instance.isDone() );
    }
}


text:
- Know of the existence of the `boolean` type.
- Know about boolean operators and how to build logical expressions with them.
- Know of the boolean operator precedence rules.
- Know where it's documented, or at least how to search for it.

## Out of scope

- Binary operators

## Concepts

- `booleans`: Know of the existence of the `boolean` type.
  Know about boolean operators and how to build logical expressions with them.
  Know of the boolean operator precedence rules.
  Know where it's documented, or at least how to search for it.

## Prerequisites

- `basics`

## Analyzer

This exercise could benefit from the following rules added to the the [analyzer][analyzer]:

- Verify that the `canExecuteFastAttack` function is as simple as possible (single negation `!`).
- Verify that the `canSpy` function is as simple as possible (double OR `||`).
- Verify that the `canSignalPrisoner` function is as simple as possible (single OR `||` and single negation `!`)
- Verify that the `canFreePrisoner` function is not overly complex.
  Helper variables may be used, but those should result in a suggestion about combining them (informational, non-essential).

[analyzer]: https://github.com/exercism/javascript-analyzer


text:
from django.db import models
from quiz.models import Quiz

# Creates a model for the quiz question item.  It essentially
# creates the schema in the database for the quiz question item,
# including all fields and types.  This represents each question in a quiz,
# which encompasses the question text, type, and priority
class QuizQuestion(models.Model):
    # the survey this question corresponds to
    quiz = models.ForeignKey(Quiz)
    questionName = models.CharField(max_length=50)
    questionDescription = models.TextField()
    questionType = models.CharField(max_length=10)
    priority = models.IntegerField(default=0)
    createTime = models.DateTimeField(auto_now_add=True)
    updateTime = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.questionName


text:
class Status < ApplicationRecord
  extend Enumerize

  include Likeable
  include Shareable

  POSITIVE_KINDS = %i[wanna_watch watching watched].freeze

  KIND_MAPPING = {
    wanna_watch: :plan_to_watch,
    watching: :watching,
    watched: :completed,
    on_hold: :on_hold,
    stop_watching: :dropped,
    no_select: :no_status
  }.freeze

  KIND_ICONS = {
    completed: :check,
    dropped: :stop,
    on_hold: :pause,
    plan_to_watch: :circle,
    watching: :play,
    no_status: :bars
  }.freeze

  enumerize :kind, scope: true, in: {
    wanna_watch: 1,
    watching: 2,
    watched: 3,
    on_hold: 5,
    stop_watching: 4
  }

  belongs_to :activity, counter_cache: :resources_count, optional: true
  belongs_to :work
  belongs_to :oauth_application, class_name: "Doorkeeper::Application", optional: true
  belongs_to :user
  has_many :activities,
    dependent: :destroy,
    as: :trackable
  has_many :likes,
    dependent: :destroy,
    as: :recipient

  scope :positive, -> { with_kind(*POSITIVE_KINDS) }
  scope :with_not_deleted_work, -> { joins(:work).merge(Work.only_kept) }

  def self.kind_v2_to_v3(kind_v2)
    return if kind_v2.blank?

    KIND_MAPPING[kind_v2.to_sym]
  end

  def self.kind_v3_to_v2(kind_v3)
    return if kind_v3.blank?

    KIND_MAPPING.invert[kind_v3.to_sym]
  end

  def self.initial
    order(:id).first
  end

  def self.initial?(status)
    count == 1 && initial.id == status.id
  end

  def self.kind_icon(kind_v3)
    KIND_ICONS[kind_v3]
  end

  def self.no_status?(kind)
    kind.to_s.in?(%w[no_select no_status])
  end

  def kind_v3
    self.class.kind_v2_to_v3(kind)
  end

  def share_to_sns
    return if !user.setting.share_status_to_twitter? || !user.authorized_to?(:twitter, shareable: true)

    ShareStatusToTwitterJob.perform_later(user.id, id)
  end

  def share_url
    "#{user.preferred_annict_url}/@#{user.username}/#{kind}"
  end

  def facebook_share_title
    work.local_title
  end

  def twitter_share_body
    work_title = work.local_title
    share_url = share_url_with_query(:twitter)

    base_body = if user.locale == "ja"
      "アニメ「%s」の視聴ステータスを「#{kind_text}」にしました #{share_url}"
    else
      "Changed %s's status to \"#{kind_text}\". Anime list: #{share_url}"
    end

    base_body % work_title
  end

  def facebook_share_body
    work_title = work.local_title

    base_body = if user.locale == "ja"
      "アニメ「%s」の視聴ステータスを「#{kind_text}」にしました。"
    else
      "Changed %s's status to \"#{kind_text}\"."
    end

    base_body % work_title
  end

  def needs_single_activity_group?
    false
  end

  def save_library_entry!
    library_entry = user.library_entries.find_or_initialize_by(work: work)
    library_entry.status = self

    case kind.to_sym
    when :watched, :stop_watching
      library_entry.watched_episode_ids = []
      library_entry.next_episode_id = nil
      library_entry.next_slot_id = nil
    when :watching
      library_entry.set_next_resources!
      library_entry.position = 1
    end

    library_entry.save!
  end
end


text:
/// <reference path="jquery-2.0.3.js" />
/// <reference path="hello-angular.js" />
/// <reference path="angular.js" />

// Create ngTwitter Module (roughly Module = namespace in C#)

var ngTwitter = angular.module("ngTwitter", ['ngResource']);

ngTwitter.config(function ($routeProvider)
{
    $routeProvider.when(
        "/", {
            templateUrl: "timeline",
            controller: "TimelineController"
        }).when(
        "/status/:id", {
            templateUrl: "status",
            controller: "StatusController"
        })
});

// Declaring a Service
ngTwitter.factory("TwitterService", function ($resource, $http, $routeParams)
{
    return {
        timeline: $resource("/Home/Tweet"),
    }
});

ngTwitter.directive("retweetButton", function ($http, $routeParams)
{
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        controller: function ($scope, $element)
        {
            $element.on("click", function (item)
            {
                var resultPromise = $http.post("/Home/Retweet/", $scope.status);
                resultPromise.success(function (data)
                {
                    if (data.success)
                    {
                        alert("Retweeted successfully");
                    }
                    else
                    {
                        alert("ERROR: Retweeted failed! " + data.errorMessage);
                    }
                });
            });
        },
        template: "<button class='btn btn-mini' ng-transclude><i class='icon-retweet'></i></button>"
    };
});

ngTwitter.controller("StatusController", function ($scope, $http, $routeParams,
TwitterService)
{
    var resultPromise = $http.get("/Home/Status/" + $routeParams.id);
    resultPromise.success(function (data)
    {
        $scope.status = data;
    });
});

ngTwitter.controller("TimelineController", function ($scope, $http, $routeParams, TwitterService)
{
    $scope.tweets = TwitterService.timeline.query({});

    $scope.newTweets = {
        0: "No new Tweets",
        other: "{} new Tweets"
    };

    $scope.sendStatus = function ()
    {
        var tweetText = $scope.statusText;
        var newTimeLine = new TwitterService.timeline(
            {
                Tweet: tweetText
            });
        newTimeLine.$save(function (data, headers)
        {
            if (data.success && data.success == true)
            {
                alert("Tweet Sent Successfully!");
                $scope.statusText = "";
            }
            else
            {
                alert("ERROR: " + data.errorMessage);
            }
        });
    };

    //$scope.retweet = function (item)
    //{
    //    var resultPromise = $http.post("/Home/Retweet/", item);
    //    resultPromise.success(function (data)
    //    {
    //        if (data.success)
    //        {
    //            alert("Retweeted successfully");
    //        }
    //        else
    //        {
    //            alert("ERROR: Retweeted failed! " + data.errorMessage);
    //        }
    //    });
    //};
});