text:
<!DOCTYPE html>

  <!DOCTYPE html>

  <link href="../css/lightbox.css" rel="stylesheet">

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta property="og:url" content="http://alienmouth.com/july2015/16.html" />
  <meta property="og:description" content="Alien Mouth publishes writing and audio/visual art" />
  <meta property="og:type" content="article" />
  <meta property="og:title" content="2 Poems" />
  <meta property="og:image" content="http://alienmouth.com/assets/img/og_image.png" />
  <meta property="og:site_name" content="Alien Mouth">

  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:site" content="@alienmouth" />
  <meta name="twitter:title" content="2 Poems" />
  <meta name="twitter:description" content="Alien Mouth publishes writing and audio/visual art" />
  <meta name="twitter:image" content="http://alienmouth.com/assets/img/twitter.png" />

  <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
  <link rel="manifest" href="/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <title>2 Poems</title>
  <meta name="description" content="Has anyone died bywatching things siton water? By skippinga flat rock across water?Or trying to sit on water?We are not birds.Has anyone died beforeseeing be...">

    <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'>

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

  <link rel="canonical" href="/july2015/16.html">

  <link rel="alternate" type="application/rss+xml" title="Alien Mouth" href="/feed.xml" />

		journal
		reviews
		books
		about
		connect
		submit

2 Poems

by Beyza Ozer on June 30, 2015

Has anyone died by

watching things sit

on water? By skipping

a flat rock across water?

Or trying to sit on water?

We are not birds.

Has anyone died before

seeing beautiful things

on the surface of a lake?

You. Did you at least get

a chance to look at the

clouds? Those balloons

won't hold very long.

You don't need oxygen

after passing the first

atmosphere. The balloon

will pop and you'll be

Up There, waiting.

You'll watch a bright dead

gas fall and take your place.

You will feel something

electric and soon your

bones will change from

white to blue. What used

to be your body will inflate

and glow. Nothing will be

able to touch you again.

Has anyone ever lived

through turning into concrete?

No, but it's intense. I will

look up at you and rent a

light machine to send you

a message: I know you are

lonely right now

but I have ideas.

I Am Moving Into A New House & Flipping All Of The Lightswitches On To Prove That I Am Capable Of Being Alive by Beyza Ozer

but i do not feel alive & it's taken me a few years to get here. the walkway is slippery with old tears & the front porch hasn't stopped dripping blood for approximately eight days. who do i talk to about this? the government?

i did not ask to die this way. i'm wondering what kind of clothing my parents would bury me in. they would pick a dress even though i had asked multiple times to be cremated. mom PLEASE shoot my ashes into space. beyza, what kind of a daughter are you?

i don't want worms in my veins. paper cuts on eyes are something i will never stop crying over. feeling sand in between my toes reminds me of fucked up summers. i do not feel alive & i don't want to be dead.

no one wants to live here. no one wants to make a home in the back of my throat. i want ghosts for neighbors, in theory.

    2 Poems - June 30, 2015 -

	<gcse:search></gcse:search>


text:
<?php
namespace DOMArch\Assembler;

use DOMArch\Assembler;
use PHPDOM\HTML\Document;

class HTML
    extends Assembler
{
    public function __construct(
        Document $body
    )
    {
        parent::__construct($body, 'html');
    }
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
LABELS_CMAP = mcolors.ListedColormap(['white', 'red', 'dodgerblue', 'gold',
                                      'greenyellow', 'blueviolet'])
from ...viewer.canvastools.base import CanvasToolBase

__all__ = ['PaintTool']

class PaintTool(CanvasToolBase):
    """Widget for painting on top of a plot.

    Parameters
    ----------
    manager : Viewer or PlotPlugin.
        Skimage viewer or plot plugin object.
    overlay_shape : shape tuple
        2D shape tuple used to initialize overlay image.
    alpha : float (between [0, 1])
        Opacity of overlay
    on_move : function
        Function called whenever a control handle is moved.
        This function must accept the end points of line as the only argument.
    on_release : function
        Function called whenever the control handle is released.
    on_enter : function
        Function called whenever the "enter" key is pressed.
    rect_props : dict
        Properties for :class:`matplotlib.patches.Rectangle`. This class
        redefines defaults in :class:`matplotlib.widgets.RectangleSelector`.

    Attributes
    ----------
    overlay : array
        Overlay of painted labels displayed on top of image.
    label : int
        Current paint color.

    Examples
    ----------
    >>> from skimage.data import camera
    >>> import matplotlib.pyplot as plt
    >>> from skimage.viewer.canvastools import PaintTool
    >>> import numpy as np

    >>> img = camera() #doctest: +SKIP

    >>> ax = plt.subplot(111) #doctest: +SKIP
    >>> plt.imshow(img, cmap=plt.cm.gray) #doctest: +SKIP
    >>> p = PaintTool(ax,np.shape(img[:-1]),10,0.2) #doctest: +SKIP
    >>> plt.show() #doctest: +SKIP

    >>> mask = p.overlay #doctest: +SKIP
    >>> plt.imshow(mask,cmap=plt.cm.gray) #doctest: +SKIP
    >>> plt.show() #doctest: +SKIP
    """
    def __init__(self, manager, overlay_shape, radius=5, alpha=0.3,
                 on_move=None, on_release=None, on_enter=None,
                 rect_props=None):
        super(PaintTool, self).__init__(manager, on_move=on_move,
                                        on_enter=on_enter,
                                        on_release=on_release)

        props = dict(edgecolor='r', facecolor='0.7', alpha=0.5, animated=True)
        props.update(rect_props if rect_props is not None else {})

        self.alpha = alpha
        self.cmap = LABELS_CMAP
        self._overlay_plot = None
        self.shape = overlay_shape

        self._cursor = plt.Rectangle((0, 0), 0, 0, **props)
        self._cursor.set_visible(False)
        self.ax.add_patch(self._cursor)

        # `label` and `radius` can only be set after initializing `_cursor`
        self.label = 1
        self.radius = radius

        # Note that the order is important: Redraw cursor *after* overlay
        self.artists = [self._overlay_plot, self._cursor]
        self.manager.add_tool(self)

    @property
    def label(self):
        return self._label

    @label.setter
    def label(self, value):
        if value >= self.cmap.N:
            raise ValueError('Maximum label value = %s' % len(self.cmap - 1))
        self._label = value
        self._cursor.set_edgecolor(self.cmap(value))

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, r):
        self._radius = r
        self._width = 2 * r + 1
        self._cursor.set_width(self._width)
        self._cursor.set_height(self._width)
        self.window = CenteredWindow(r, self._shape)

    @property
    def overlay(self):
        return self._overlay

    @overlay.setter
    def overlay(self, image):
        self._overlay = image
        if image is None:
            self.ax.images.remove(self._overlay_plot)
            self._overlay_plot = None
        elif self._overlay_plot is None:
            props = dict(cmap=self.cmap, alpha=self.alpha,
                         norm=mcolors.NoNorm(), animated=True)
            self._overlay_plot = self.ax.imshow(image, **props)
        else:
            self._overlay_plot.set_data(image)
        self.redraw()

    @property
    def shape(self):
        return self._shape

    @shape.setter
    def shape(self, shape):
        self._shape = shape
        if not self._overlay_plot is None:
            self._overlay_plot.set_extent((-0.5, shape[1] + 0.5,
                                           shape[0] + 0.5, -0.5))
            self.radius = self._radius
        self.overlay = np.zeros(shape, dtype='uint8')

    def on_key_press(self, event):
        if event.key == 'enter':
            self.callback_on_enter(self.geometry)
            self.redraw()

    def on_mouse_press(self, event):
        if event.button != 1 or not self.ax.in_axes(event):
            return
        self.update_cursor(event.xdata, event.ydata)
        self.update_overlay(event.xdata, event.ydata)

    def on_mouse_release(self, event):
        if event.button != 1:
            return
        self.callback_on_release(self.geometry)

    def on_move(self, event):
        if not self.ax.in_axes(event):
            self._cursor.set_visible(False)
            self.redraw() # make sure cursor is not visible
            return
        self._cursor.set_visible(True)

        self.update_cursor(event.xdata, event.ydata)
        if event.button != 1:
            self.redraw() # update cursor position
            return
        self.update_overlay(event.xdata, event.ydata)
        self.callback_on_move(self.geometry)

    def update_overlay(self, x, y):
        overlay = self.overlay
        overlay[self.window.at(y, x)] = self.label
        # Note that overlay calls `redraw`
        self.overlay = overlay

    def update_cursor(self, x, y):
        x = x - self.radius - 1
        y = y - self.radius - 1
        self._cursor.set_xy((x, y))

    @property
    def geometry(self):
        return self.overlay

class CenteredWindow(object):
    """Window that create slices numpy arrays over 2D windows.

    Examples
    --------
    >>> a = np.arange(16).reshape(4, 4)
    >>> w = CenteredWindow(1, a.shape)
    >>> a[w.at(1, 1)]
    array([[ 0,  1,  2],
           [ 4,  5,  6],
           [ 8,  9, 10]])
    >>> a[w.at(0, 0)]
    array([[0, 1],
           [4, 5]])
    >>> a[w.at(4, 3)]
    array([[14, 15]])
    """
    def __init__(self, radius, array_shape):
        self.radius = radius
        self.array_shape = array_shape

    def at(self, row, col):
        h, w = self.array_shape
        r = self.radius
        xmin = max(0, col - r)
        xmax = min(w, col + r + 1)
        ymin = max(0, row - r)
        ymax = min(h, row + r + 1)
        return [slice(ymin, ymax), slice(xmin, xmax)]

if __name__ == '__main__':  # pragma: no cover
    np.testing.rundocs()
    from ... import data
    from ...viewer import ImageViewer

    image = data.camera()

    viewer = ImageViewer(image)
    paint_tool = PaintTool(viewer, image.shape)
    viewer.show()


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Annuaire Conserv. Jard. Bot. Genève 11-12:8. 1907

#### Original name
null

### Remarks
null


text:
Foxii
=====
This is a git repository of the Foxii Project.
Please show our [Wiki](https://github.com/mikan/Foxii/wiki) to get more information.

Copyright© 2014 [tAsktoys](http://www.tasktoys.com) All rights reserved.


text:
package org.elasticsearch.common.lucene.search.function;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Scorer;
import org.elasticsearch.script.ExplainableSearchScript;
import org.elasticsearch.script.SearchScript;

import java.io.IOException;
import java.util.Map;

public class ScriptScoreFunction extends ScoreFunction {

    static final class CannedScorer extends Scorer {
        protected int docid;
        protected float score;

        public CannedScorer() {
            super(null);
        }

        @Override
        public int docID() {
            return docid;
        }

        @Override
        public float score() throws IOException {
            return score;
        }

        @Override
        public int freq() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public int nextDoc() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public int advance(int target) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public long cost() {
            return 1;
        }
    }

    private final String sScript;

    private final Map<String, Object> params;

    private final CannedScorer scorer;

    private final SearchScript script;

    public ScriptScoreFunction(String sScript, Map<String, Object> params, SearchScript script) {
        super(CombineFunction.REPLACE);
        this.sScript = sScript;
        this.params = params;
        this.script = script;
        this.scorer = new CannedScorer();
        script.setScorer(scorer);
    }

    @Override
    public void setNextReader(AtomicReaderContext ctx) {
        script.setNextReader(ctx);
    }

    @Override
    public double score(int docId, float subQueryScore) {
        script.setNextDocId(docId);
        scorer.docid = docId;
        scorer.score = subQueryScore;
        return script.runAsDouble();
    }

    @Override
    public Explanation explainScore(int docId, Explanation subQueryExpl) {
        Explanation exp;
        if (script instanceof ExplainableSearchScript) {
            script.setNextDocId(docId);
            scorer.docid = docId;
            scorer.score = subQueryExpl.getValue();
            exp = ((ExplainableSearchScript) script).explain(subQueryExpl);
        } else {
            double score = score(docId, subQueryExpl.getValue());
            exp = new Explanation(CombineFunction.toFloat(score), "script score function: composed of:");
            exp.addDetail(subQueryExpl);
        }
        return exp;
    }

    @Override
    public String toString() {
        return "script[" + sScript + "], params [" + params + "]";
    }

}


text:
<?php

namespace PhpInk\Nami\CoreBundle\Model;

use Doctrine\Common\Collections\ArrayCollection;
use PhpInk\Nami\CoreBundle\Model\Image\BlockImageInterface;

/**
 * Block interface
 */
interface BlockInterface
{
    /**
     * Fill null collection properties
     * DB onPostLoad HOOK
     */
    public function initialize();

    /**
     * Set the value of active.
     *
     * @param boolean $active
     * @return BlockInterface
     */
    public function setActive($active);

    /**
     * Get the value of active.
     *
     * @return boolean
     */
    public function isActive();

    /**
     * Get the value of title.
     *
     * @return string
     */
    public function getTitle();

    /**
     * Set the value of title.
     *
     * @param string $title
     * @return BlockInterface
     */
    public function setTitle($title);

    /**
     * Get the value of content.
     *
     * @return string
     */
    public function getContent();

    /**
     * Set the value of content.
     *
     * @param string $content
     * @return BlockInterface
     */
    public function setContent($content);

    /**
     * Get the value of type.
     *
     * @return string
     */
    public function getType();

    /**
     * Set the value of type.
     *
     * @param string $type
     * @return BlockInterface
     */
    public function setType($type);

    /**
     * Remove a block image
     *
     * @param BlockImageInterface $image
     * @return BlockInterface
     */
    public function removeImage(BlockImageInterface $image);

    /**
     * Add a block image
     *
     * @param BlockImageInterface $image
     * @return BlockInterface
     */
    public function addImage(BlockImageInterface $image);

    /**
     * Returns the block images
     *
     * @return ArrayCollection
     */
    public function getImages();

    /**
     * Returns bool if the block has images
     *
     * @return ArrayCollection
     */
    public function hasImages();

    /**
     * Returns first image
     *
     * @return BlockImageInterface
     */
    public function getFirstImage();

    /**
     * Returns first image url
     *
     * @return string
     */
    public function getFirstImageUrl();

    /**
     * Returns first image url
     *
     * @return string
     */
    public function getFirstImageName();

    /**
     * Returns the block images ID
     *
     * @return array
     */
    public function getImagesId();

    /**
     * Get the value of template.
     *
     * @return mixed
     */
    public function getTemplate();

    /**
     * Set the value of template.
     *
     * @param mixed $template
     * @return BlockInterface
     */
    public function setTemplate($template);

    /**
     * Get the value of page.
     *
     * @return PageInterface
     */
    public function getPage();

    /**
     * Get the value of page.
     *
     * @return int|string|null
     */
    public function getPageId();

    /**
     * Set the value of page.
     *
     * @param PageInterface $page
     * @return BlockInterface
     */
    public function setPage($page);

    /**
     * Displays a _references param for JMS
     * with related entities data
     *
     * @param UserInterface|null $user
     * @param array $groups
     * @return array
     */
    public function getReferences(UserInterface $user = null, $groups = array());

    public function __toString();

    /**
     * Set the value of plugin
     * @param mixed $plugin
     * @return BlockInterface
     */
    public function setPlugin($plugin);
}


text:
import os
import sys
import yaml
import traceback
import transaction
import json
from elasticsearch import Elasticsearch

if __name__ == "__main__":

    test_name = "Add"
    configpath = os.path.abspath('./edm.yml') if os.path.exists('./edm.yml') else sys.exit(1)

    config = None
    with open(configpath, 'r') as stream:
        try:
            config = yaml.load(stream)
        except yaml.YAMLError as e:
            raise Exception from e

    ret = 0
    # print(config)
    try:
        connection = Elasticsearch(config['elasticsearch_hosts'],
                                   # sniff before doing anything
                                   sniff_on_start=True,
                                   # refresh nodes after a node fails to respond
                                   sniff_on_connection_fail=True,
                                   # and also every 60 seconds
                                   sniffer_timeout=60)

        connection.create(index=config['default_index'],
                          doc_type='group',
                          id='2',
                          body={"gid": 234,
                                "owner": "bemineni",
                                "name": "Sammy",
                                "grp_hash": "456678",
                                "description": "Sammy group"
                                })
        data = connection.get_source(index=config['default_index'],
                                     doc_type="group",
                                     id='2')
        print(json.dumps(data,
                         indent=4, sort_keys=True))

    except Exception as e:
        print("Failed to add item")
        print("Test failed")
        traceback.print_exc()
        ret = 1
    finally:
        print(test_name + " Test complete")

    sys.exit(ret)


text:
/*
 *  Schema / Field Editor integrated into Module Editor
*/

fieldEditor_class = function () {
    this.moduleId = $("#Main > div.editContent").attr("data-id");
};

fieldEditor_class.prototype.initPageEvents = function () {
    var self = this;

    // Load Schema into Field editor on Schema Change
    $("#SchemaSelector").change(function () {
        var schemaId = $("#SchemaSelector option:selected").attr("data-id");

        // Check for No Schema
        if (schemaId == -1) {
            $("#FieldEntry").html("
No Schema assigned.
");
            return;
        }

        // If there is a schema, load it
        self.loadSchemaIntoFields(schemaId, self.moduleId);

        // Update the edit schema link
        $("#EditSchemaLink").attr("href", "/admin/editschema/" + schemaId);
    }).trigger("change");

    // Refresh the schema by simply triggering a change on the drop down
    $("#RefreshSchemaLink").click(function () {
        $("#SchemaSelector").trigger("change");
    });

    $('.js-sync-schema-view').click(self.syncSchemaView);

    this.initListEvents();
};

fieldEditor_class.prototype.loadSchemaIntoFields = function (schemaId, moduleId) {
    var self = this;

    var data = {
        schemaId: schemaId,
        moduleId: moduleId,
        isPage: $("#PageTitle").length > 0
    };

    // Set loading spinner
    var $container = $("#FieldEntry");
    common.showAjaxLoader($container);
    $("#RefreshSchemaLink i.fa-refresh").addClass("fa-spin");

    // Kick off ajax to get the schema and values
    $.ajax({
        url: "/admin/schemas/getschemahtml",
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data, null, 2),
        success: function (data) {
            var obj = jQuery.parseJSON(data.data);

            // Clear the html
            $("#EditorTab").html("

");

            // Build out the fields into html and then place them on the page
            var $content = self.buildSchemaContent(obj.fields);
            $("#FieldEditorContainer").append($content);

            // Move any list items' children up to it's parent
            self.moveChildrenToList(obj.fields);

            // Set the user values into the newly placed fields
            var schemaData = jQuery.parseJSON(data.values);

            if (schemaData != null) {
                self.loadSchemaValues(schemaData);
            }

            self.initSpecialFields();

            // End Loading
            $("#RefreshSchemaLink i.fa-refresh").removeClass("fa-spin");
            common.hideAjaxLoader($container);
        },
        error: function (data) {
            alert("An Error Occurred. Please refresh and try again.");
        }
    });
};

fieldEditor_class.prototype.initSpecialFields = function ($parent) {

    $parent = $parent || $('#FieldEntry');

    // Set up Image Uploaders
    $('a.upload', $parent).fileBrowser({
        directory: "",
        isEditor: false
    }, function (object) {
        var path = object.src || object.href,
            $input = $(object.elem).parent().find("input[type=text]");

        $input.val(path);
        return false;
    });

    // Set up Date Pickers
    $('.date input', $parent).datepicker();

    // Setup CKEditors
    // Timeout needed for CK Bug
    setTimeout(function () {
        $('textarea.editor', $parent).each(function () {
            var id = $(this).attr("id");
            var $el = $("#" + id);

            if (!$el.hasClass("activated")) {
                CKEDITOR.replace(id);
                $el.addClass("activated");
            }
        });
    }, 300);
}

fieldEditor_class.prototype.loadSchemaValues = function (schemaValues) {

    $.each(schemaValues, function (key, value) {

        var label = key;
        var inputName = key.toLowerCase().replace(/ /g, '-');

        //text inputs
        $("#FieldEntry input[name='" + inputName + "']").val(value);

        // Text Area / Paragraphs
        $("#FieldEntry textarea[name='" + inputName + "']").val(value);

        // Select Boxes
        $("#FieldEntry select[name='" + inputName + "']").val(value);

        // Checkboxes
        $("#FieldEntry div.checkContainer[data-label='" + label + "']").each(function () {
            var nValues = value;
            var $this = $(this);

            $.each(nValues, function (key, val) {

                var $input = $this.find("input[data-label='" + val + "']");
                if ($input.length > 0) {
                    $input.prop("checked", true);
                }
                else {
                    // Other / Specify
                    $this.find("input.otherInput").prop("checked", true);
                    $this.find("input.otherSpecifyInput").val(val);
                }
            });
        });

        // Radio Buttons
        $("#FieldEntry div.radioContainer[data-label='" + label + "']").each(function () {
            var $input = $(this).find("input[data-label='" + value + "']");
            if ($input.length > 0) {
                $input.prop("checked", true);
            }
            else {
                // Other / Specify
                $(this).find("input.otherInput").prop("checked", true);
                $(this).find("input.otherSpecifyInput").val(value);
            }
        });

        $("#FieldEntry div.formContainer.list[data-label='" + label + "']").each(function () {

            var $this = $(this);

            var nValues = value[0].values;

            $.each(nValues, function (innerKey, innerValue) {

                var $listContainer = $this.find(" > li > .listContainer")[innerKey];

                // If it doesn't exist add it
                if (typeof $listContainer == "undefined" || $listContainer.length < 1) {
                    var $new = $this.find(" > li > .listContainer").last().clone(),
                        $newRadios = $new.find('.radioContainer, .checkboxContainer');

                    // Radio button/checkbox groups require unique names
                    $newRadios.each(function () {

                        var $input = $(this).find('input[type="radio"], input[type="checkbox"]'),
                            name = $input.attr("name") + Date.now();

                        $input.each($input, function () {
                            var id = $(this).attr("id") + Date.now();

                            $(this).attr("name", name);
                            $(this).attr("id", id);
                        });

                    });

                    $this.find(" > li > .listContainer").last().after($new);

                    $listContainer = $this.find(" > li > .listContainer")[innerKey];
                }

                $($listContainer).find("[data-label='" + innerValue[0] + "']").val(innerValue[1]);

                // Load up the values. This is where recursion should happen for lists within lists
                for (var propt in innerValue) {
                    $($listContainer).find("[data-label='" + propt + "']").val(innerValue[propt]);
                }
            });
        });
    });
};

fieldEditor_class.prototype.buildSchemaContent = function (fields) {
    var self = this;
    var $content = $("<form id='FieldEntry'>");

    // loop through the fields
    $.each(fields, function (index, value) {
        var oItem = value;
        var label = oItem.label;
        var inputName = label.toLowerCase().replace(/ /g, '-'); // lowercase, replace spaces with dashes
        var type = oItem.field_type;
        var bRequired = oItem.required;
        var sRequiredTokend = (bRequired) ? " *" : "";
        var cId = oItem.cid;
        var requiredClass = (bRequired) ? "required" : "";
        var options = oItem.field_options;
        var description = options.description || "";
        var sizeClass = options.size || "";
        var includeOther = options.include_other_option || false;
        var schemaId = options.schema_id || 0;

        // Text Fields
        if (type == "text") {

            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("<input name='" + inputName + "' data-label='" + label + "' type='text' class='form-control " + requiredClass + "' data-id='" + cId + "' autocomplete='off' />");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Paragraph / Text Area Fields
        if (type == "paragraph") {
            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("<textarea name='" + inputName + "' data-label='" + label + "' type='text' class='form-control " + requiredClass + "' data-id='" + cId + "' autocomplete='off' ></textarea>");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Image Uploader Fields
        if (type == "image") {

            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("<input name='" + inputName + "' data-label='" + label + "' type='text' class='form-control " + requiredClass + "' data-id='" + cId + "' autocomplete='off' />");
            $formContainer.append(" Select Image...");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // WYSIWYG Editor
        if (type == "wysiwyg") {
            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("<textarea name='" + inputName + "' id='" + cId + "' data-label='" + label + "' type='text' class='editor " + requiredClass + "' data-id='" + cId + "' autocomplete='off' ></textarea>");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Multiple Choice / Radio Buttons
        if (type == "radio") {

            var $formContainer = $("
");
            $formContainer.append("" + label + "");

            // Add Radio Options
            $.each(options.options, function (key, value) {
                var radioLabel = value.label;
                var radioId = value.label.toLowerCase().replace(/ /g, '-'); // lowercase, replace spaces with dashes
                var checked = value.checked == true ? "checked=checked" : "";
                var radioName = label.toLowerCase().replace(/ /g, '-');

                var $radioContainer = $("
");

                var inputHtml = "<input id='" + radioId + "'  name='" + radioName + "' type='radio' data-label='" + radioLabel + "' class='" + requiredClass + "' data-id='" + cId + "' autocomplete='off' " + checked + " />";
                $radioContainer.append("" + inputHtml + " " + radioLabel + "");

                $formContainer.append($radioContainer);
            });

            // Add Other choice if necessary
            if (includeOther) {
                var checkId = inputName + "OtherRadio";
                var checkName = label.toLowerCase().replace(/ /g, '-');
                var checkLabel = "Other";
                var checked = "";

                var $checkContainer = $("
");

                var inputHtml = "<input id='" + checkId + "'  name='" + checkName + "' type='radio' data-label='" + checkLabel + "' class='otherInput " + requiredClass + "' data-id='" + cId + "' autocomplete='off' " + checked + " />";
                $checkContainer.append("" + inputHtml + " " + checkLabel + "");
                $checkContainer.append('<input type="text" class="otherSpecifyInput" autocomplete="off" />');

                $formContainer.append($checkContainer);
            }

            $content.append($formContainer);
        }

        // CheckBoxes
        if (type == "checkboxes") {

            var $formContainer = $("
");
            $formContainer.append("" + label + "");

            // Add CheckBox Options
            $.each(options.options, function (key, value) {
                var checkLabel = value.label;
                var checkId = value.label.toLowerCase().replace(/ /g, '-'); // lowercase, replace spaces with dashes
                var checked = value.checked == true ? "checked=checked" : "";
                var checkName = label.toLowerCase().replace(/ /g, '-');

                var $checkContainer = $("
");

                var inputHtml = "<input id='" + checkId + "'  name='" + checkName + "' type='checkbox' data-label='" + checkLabel + "' class='" + requiredClass + "' value='test' data-id='" + cId + "' autocomplete='off' " + checked + " />";
                $checkContainer.append("" + inputHtml + " " + checkLabel + "");

                $formContainer.append($checkContainer);
            });

            // Add Other choice if necessary
            if (includeOther) {
                var checkId = inputName + "OtherCheck";
                var checkName = inputName + "Check1";
                var checkLabel = "Other";
                var checked = "";

                var $checkContainer = $("
");

                var inputHtml = "<input id='" + checkId + "'  name='" + checkName + "' type='checkbox' data-label='" + checkLabel + "' class='otherInput " + requiredClass + "' value='test' data-id='" + cId + "' autocomplete='off' " + checked + " />";
                $checkContainer.append("" + inputHtml + " " + checkLabel + "");
                $checkContainer.append('<input type="text" class="otherSpecifyInput"/>');

                $formContainer.append($checkContainer);
            }

            $content.append($formContainer);
        }

        // Select Boxes / Dropdown
        if (type == "dropdown") {
            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            var $select = $("<select class='form-control' name='" + inputName + "' data-label='" + label + "' data-id='" + cId + "'></select>");

            $.each(options.options, function (key, value) {

                var label = value.label;
                var checked = value.checked;
                var selectedText = checked ? "selected=selected" : "";

                $select.append("<option " + selectedText + " >" + label + "</option>");
            });

            $formContainer.append($select);

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Module list
        if (type == "module") {
            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            var $select = $("<select class='form-control' name='" + inputName + "' data-label='" + label + "' data-id='" + cId + "'></select>");

            $.ajax({
                async: false,
                url: "/admin/schemas/getlistofmodulesbyschemaid/" + schemaId,
                type: "GET",
                success: function (data) {
                    $(data.moduleNames).each(function () {
                        $select.append("<option>" + this + "</option>");
                    });
                }
            });

            $formContainer.append($select);

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Datepicker Fields
        if (type == "date") {

            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("<input name='" + inputName + "' data-label='" + label + "' type='text' class='form-control " + requiredClass + "' data-id='" + cId + "' autocomplete='off' />");
            $formContainer.append("");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }

        // Listings
        if (type == "list") {

            var formControls = "

";
            var $formContainer = $("
");

            $formContainer.append("" + label + sRequiredTokend + "");
            $formContainer.append("
 " + formControls + "
");

            if (description.length > 0) {
                $formContainer.append("
" + description + "
");
            }

            $content.append($formContainer);
        }
    });

    // Wrap each form container in list items for better viewing
    $content.find("div.formContainer").wrapAll("

").wrapInner("

");

    return $content;
};

fieldEditor_class.prototype.moveChildrenToList = function (fields) {

    $.each(fields, function (index, value) {
        if (value.field_type == "list") {
            var $listItem = $("[data-id=" + value.cid + "]");

            var nChildren = value.field_options.children;
            for (var x = 0; x < nChildren.length; x++) {

                var $child = $("[data-id=" + nChildren[x] + "]");

                // move it
                if ($child.length > 0) {
                    var $childContainer = $child.closest(".formContainer");

                    $listItem.append($childContainer);
                }
            }

            // Add an "Add" button to the list if it's not already there
            $listItem.after("New " + value.label + " +");
        }
    });

    // Make them sortable
    $(".formContainer.list ").sortable({
        items: ".listContainer",
        handle: ".listControls",
        revert: 100
    });
};

fieldEditor_class.prototype.syncSchemaView = function () {

    var self = this,
        $self = $(self),
        schemaId = $self.attr('data-schema'),
        itemId = $self.attr('data-item'),
        ispage = $self.attr('data-ispage'),
        itemList = [],
        updateContentItem = function (page, syncData, callback) {

            var parsedHtml = Mustache.to_html(syncData.html, JSON.parse(page.schemaValues)),
                data = {
                    itemId: page.id,
                    unparsedHtml: syncData.html,
                    parsedHtml: parsedHtml,
                    template: syncData.template,
                    parent: syncData.parent,
                    ispage: ispage
                };

            $self.siblings('.sync-counter').first().text('Syncing ' + (itemList.indexOf(page) + 1) + ' of ' + itemList.length);

            $.ajax({
                url: "/admin/schemas/syncschemaview/",
                type: "POST",
                dataType: 'json',
                data: JSON.stringify(data, null, 2),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {

                    if (!data.success) {
                        noty({ text: data.error, type: 'error' });
                        return false;
                    }

                    if (itemList.indexOf(page) === itemList.length - 1 && typeof callback === 'function') {
                        callback();
                    } else {
                        updateContentItem(itemList[itemList.indexOf(page) + 1], syncData, callback);
                    }

                }
            });

        };

    $self.addClass('is-syncing');

    $.ajax({
        url: "/admin/schemas/getschemasyncdata/?schemaid=" + schemaId + "&itemid=" + itemId + "&ispage=" + ispage,
        type: "GET",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

            itemList = data.items;
            $self.after('

');

            updateContentItem(itemList[0], data, function () {

                $self.removeClass('is-syncing');
                $self.siblings('.sync-counter').remove();
                noty({ text: "Items successfully synced.", type: 'success' });

            });

        }
    });

    return false;

};

fieldEditor_class.prototype.initListEvents = function () {

    var self = this;

    $("#EditorTab").on("click", ".newListItem", function (e) {
        e.preventDefault();
        var $listContainer = $(this).prev().clone();
        $listContainer.addClass("animated zoomIn");
        $listContainer.attr("data-id", self.generateCId());

        $(this).before($listContainer);

        // No longer need the class
        setTimeout(function () {
            $(".animated.zoomIn").removeClass("animated zoomIn");
        }, 400);

        console.log($(this).closest('.formContainer'));

        self.initSpecialFields($(this).closest('.formContainer'));
    });

    $("#EditorTab").on("click", ".listContainer .remove", function (e) {
        e.preventDefault();

        var $listContainer = $(this).closest(".listContainer");

        if ($listContainer.closest("li").find(".listContainer").length < 2) {
            alert("At least one list item must be present.");
            return false;
        }

        if (confirm("Delete this list item?")) {
            $listContainer.remove();
        }
    });
};

fieldEditor_class.prototype.generateCId = function () {

    // if duplicate, increment till we find a free spot
    var count = 0;
    var id = "c" + count;
    var $frame = $("#FieldEntry");
    while ($frame.find("[data-id=" + id + "]").length > 0) {
        id = "c" + count;
        count++;
    }
    return id;
};

// Keep at the bottom
$(document).ready(function () {
    fieldEditor = new fieldEditor_class();
    fieldEditor.initPageEvents();
});


text:
"""
Sponge Knowledge Base
Remote API security
"""

def configureAccessService():
    # Configure the RoleBasedAccessService.

    # Simple access configuration: role -> knowledge base names regexps.
    remoteApiServer.accessService.addRolesToKb({ "ROLE_ADMIN2":[".*"], "ROLE_ANONYMOUS2":["boot", "python"]})

    # Simple access configuration: role -> event names regexps.
    remoteApiServer.accessService.addRolesToSendEvent({ "ROLE_ADMIN2":[".*"], "ROLE_ANONYMOUS2":[]})
    remoteApiServer.accessService.addRolesToSubscribeEvent({ "ROLE_ADMIN2":[".*"], "ROLE_ANONYMOUS2":[".*"]})

def onStartup():
    # Configure the access service on startup.
    configureAccessService()

def onAfterReload():
    # Reconfigure the access service after each reload.
    configureAccessService()


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

<section xml:id="clip-instruction"
    xmlns="http://docbook.org/ns/docbook" version="5.0" xml:lang="en"
    xmlns:xi="http://www.w3.org/2001/XInclude">
    <title>clip</title>

    <indexterm>
        <primary>clip</primary>
    </indexterm>
    <para>Applies the current path as the clipping path. Future operations will
        only draw within the current path. Note that future clip instructions
        will also be limited by this path. To set a completely new clipping path,
        you must first reset the layer with a reset instruction. If you wish to
        only reset the clipping path, but preserve the current transform matrix,
        push the layer state before setting the clipping path, and pop the layer
        state to reset.</para>
    <variablelist>
        <varlistentry>
            <term><parameter>layer</parameter></term>
            <listitem>
                <para>The layer whose clipping path should be set.</para>
            </listitem>
        </varlistentry>
    </variablelist>

</section>


text:
package org.kie.persistence.jpa;

import org.kie.KieBase;
import org.kie.runtime.Environment;
import org.kie.runtime.KieSession;
import org.kie.runtime.KieSessionConfiguration;

public interface KieStoreServices {

    KieSession newKieSession(KieBase kbase,
                             KieSessionConfiguration configuration,
                             Environment environment);

    KieSession loadKieSession(int id,
                              KieBase kbase,
                              KieSessionConfiguration configuration,
                              Environment environment);

}


text:
/*Estilos Para seccional*/
.solo-seccional{
    display: block !important;
}


text:
using System;
using System.Linq;
using Google.Apis.Dfareporting.v2_2;
using Google.Apis.Dfareporting.v2_2.Data;

namespace DfaReporting.Samples {
  /// <summary>
  /// This example displays the name, ID and advertiser ID for every active ad
  /// your DFA user profile can see.
  /// </summary>
  class GetAds : SampleBase {
    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This example displays the name, ID and advertiser ID for" +
            " every active ad.\n";
      }
    }

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      SampleBase codeExample = new GetAds();
      Console.WriteLine(codeExample.Description);
      codeExample.Run(DfaReportingFactory.getInstance());
    }

    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="service">An initialized Dfa Reporting service object
    /// </param>
    public override void Run(DfareportingService service) {
      long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE"));

      // Limit the fields returned.
      String fields = "nextPageToken,ads(advertiserId,id,name)";

      AdsListResponse result;
      String nextPageToken = null;

      do {
        // Create and execute the ad list request.
        AdsResource.ListRequest request = service.Ads.List(profileId);
        request.Active = true;
        request.Fields = fields;
        request.PageToken = nextPageToken;
        result = request.Execute();

        foreach (Ad ad in result.Ads) {
          Console.WriteLine(
              "Ad with ID {0} and name \"{1}\" is associated with advertiser" +
              " ID {2}.", ad.Id, ad.Name, ad.AdvertiserId);
        }

        // Update the next page token.
        nextPageToken = result.NextPageToken;
      } while (result.Ads.Any() && !String.IsNullOrEmpty(nextPageToken));
    }
  }
}


text:
<?php
/**
 * Device Detector - The Universal Device Detection library for parsing User Agents
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace DeviceDetector;

use DeviceDetector\Cache\CacheInterface;
use DeviceDetector\Cache\CacheStatic;
use DeviceDetector\Parser\Bot;
use DeviceDetector\Parser\OperatingSystem;
use DeviceDetector\Parser\Client\ClientParserAbstract;
use DeviceDetector\Parser\Device\DeviceParserAbstract;
use \Spyc;

class DeviceDetector
{
    /**
     * Holds all registered client types
     * @var array
     */
    public static $clientTypes = array();

    /**
     * Operating system families that are known as desktop only
     *
     * @var array
     */
    protected static $desktopOsArray = array('AmigaOS', 'IBM', 'GNU/Linux', 'Mac', 'Unix', 'Windows', 'BeOS');

    /**
     * Constant used as value for unknown browser / os
     */
    const UNKNOWN = "UNK";

    /**
     * Holds the useragent that should be parsed
     * @var string
     */
    protected $userAgent;

    /**
     * Holds the operating system data after parsing the UA
     * @var array
     */
    protected $os = null;

    /**
     * Holds the client data after parsing the UA
     * @var array
     */
    protected $client = null;

    /**
     * Holds the device type after parsing the UA
     * @var string
     */
    protected $device = null;

    /**
     * Holds the device brand data after parsing the UA
     * @var string
     */
    protected $brand = '';

    /**
     * Holds the device model data after parsing the UA
     * @var string
     */
    protected $model = '';

    /**
     * Holds bot information if parsing the UA results in a bot
     * (All other information attributes will stay empty in that case)
     *
     * If $discardBotInformation is set to true, this property will be set to
     * true if parsed UA is identified as bot, additional information will be not available
     *
     * @var array|boolean
     */
    protected $bot = null;

    protected $discardBotInformation = false;

    /**
     * Holds the cache class used for caching the parsed yml-Files
     * @var CacheInterface
     */
    protected $cache = null;

    /**
     * Constructor
     *
     * @param string $userAgent  UA to parse
     */
    public function __construct($userAgent='')
    {
        if ($userAgent != '') {
            $this->setUserAgent($userAgent);
        }

        $this->addClientParser('FeedReader');
        $this->addClientParser('MobileApp');
        $this->addClientParser('MediaPlayer');
        $this->addClientParser('PIM');
        $this->addClientParser('Browser');

        $this->addDeviceParser('HbbTv');
        $this->addDeviceParser('Console');
        $this->addDeviceParser('CarBrowser');
        $this->addDeviceParser('Camera');
        $this->addDeviceParser('Mobile');
    }

    /**
     * Sets the useragent to be parsed
     *
     * @param string $userAgent
     */
    public function setUserAgent($userAgent)
    {
        if ($this->userAgent != $userAgent) {
            $this->reset();
        }
        $this->userAgent = $userAgent;
    }

    protected function reset()
    {
        $this->bot    = null;
        $this->client = null;
        $this->device = null;
        $this->os     = null;
        $this->brand  = '';
        $this->model  = '';
        $this->parsed = false;
    }

    /**
     * @var ClientParserAbstract[]
     */
    protected $clientParsers = array();

    /**
     * @param ClientParserAbstract|string $parser
     * @throws \Exception
     */
    public function addClientParser($parser)
    {
        if (is_string($parser) && class_exists('DeviceDetector\\Parser\\Client\\'.$parser)) {
            $className = 'DeviceDetector\\Parser\\Client\\'.$parser;
            $parser = new $className();
        }

        if ($parser instanceof ClientParserAbstract) {
            $this->clientParsers[] = $parser;
            self::$clientTypes[] = $parser->getName();
            return;
        }

        throw new \Exception('client parser not found');
    }

    public function getClientParsers()
    {
        return $this->clientParsers;
    }

    /**
     * @var DeviceParserAbstract[]
     */
    protected $deviceParsers = array();

    /**
     * @param DeviceParserAbstract|string $parser
     * @throws \Exception
     */
    public function addDeviceParser($parser)
    {
        if (is_string($parser) && class_exists('DeviceDetector\\Parser\\Device\\'.$parser)) {
            $className = 'DeviceDetector\\Parser\\Device\\'.$parser;
            $parser = new $className();
        }

        if ($parser instanceof DeviceParserAbstract) {
            $this->deviceParsers[] = $parser;
            return;
        }

        throw new \Exception('device parser not found');
    }

    public function getDeviceParsers()
    {
        return $this->deviceParsers;
    }

    /**
     * Sets whether to discard additional bot information
     * If information is discarded it's only possible check whether UA was detected as bot or not.
     * (Discarding information speeds up the detection a bit)
     *
     * @param bool $discard
     */
    public function discardBotInformation($discard=true)
    {
        $this->discardBotInformation = $discard;
    }

    /**
     * Returns if the parsed UA was identified as a Bot
     *
     * @see bots.yml for a list of detected bots
     *
     * @return bool
     */
    public function isBot()
    {
        return !empty($this->bot);
    }

    /**
     * Returns if the parsed UA was identified as a touch enabled device
     *
     * Note: That only applies to windows 8 tablets
     *
     * @return bool
     */
    public function isTouchEnabled()
    {
        $regex = 'Touch';
        return $this->matchUserAgent($regex);
    }

    public function isMobile()
    {
        return !$this->isBot() && !$this->isDesktop();
    }

    /**
     * Returns if the parsed UA was identified as desktop device
     * Desktop devices are all devices with an unknown type that are running a desktop os
     *
     * @see self::$desktopOsArray
     *
     * @return bool
     */
    public function isDesktop()
    {
        $osShort = $this->getOs('short_name');
        if (empty($osShort)) {
            return false;
        }

        $decodedFamily = OperatingSystem::getOsFamily($osShort);

        return in_array($decodedFamily, self::$desktopOsArray);
    }

    /**
     * Returns the operating system data extracted from the parsed UA
     *
     * If $attr is given only that property will be returned
     *
     * @param string $attr  property to return(optional)
     *
     * @return array|string
     */
    public function getOs($attr = '')
    {
        if ($attr == '') {
            return $this->os;
        }

        if (!isset($this->os[$attr])) {
            return self::UNKNOWN;
        }

        return $this->os[$attr];
    }

    /**
     * Returns the client data extracted from the parsed UA
     *
     * If $attr is given only that property will be returned
     *
     * @param string $attr  property to return(optional)
     *
     * @return array|string
     */
    public function getClient($attr = '')
    {
        if ($attr == '') {
            return $this->client;
        }

        if (!isset($this->client[$attr])) {
            return self::UNKNOWN;
        }

        return $this->client[$attr];
    }

    /**
     * Returns the device type extracted from the parsed UA
     *
     * @see DeviceParserAbstract::$deviceTypes for available device types
     *
     * @return int|null
     */
    public function getDevice()
    {
        return $this->device;
    }

    /**
     * Returns the device type extracted from the parsed UA
     *
     * @see DeviceParserAbstract::$deviceTypes for available device types
     *
     * @return string
     */
    public function getDeviceName()
    {
        if ($this->getDevice() !== null) {
            return DeviceParserAbstract::getDeviceName($this->getDevice());
        }

        return '';
    }

    /**
     * Returns the device brand extracted from the parsed UA
     *
     * @see self::$deviceBrand for available device brands
     *
     * @return string
     */
    public function getBrand()
    {
        return $this->brand;
    }

    /**
     * Returns the full device brand name extracted from the parsed UA
     *
     * @see self::$deviceBrand for available device brands
     *
     * @return string
     */
    public function getBrandName()
    {
        return DeviceParserAbstract::getFullName($this->getBrand());
    }

    /**
     * Returns the device model extracted from the parsed UA
     *
     * @return string
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * Returns the user agent that is set to be parsed
     *
     * @return string
     */
    public function getUserAgent()
    {
        return $this->userAgent;
    }

    /**
     * Returns the bot extracted from the parsed UA
     *
     * @return array
     */
    public function getBot()
    {
        return $this->bot;
    }

    protected $parsed = false;

    /**
     * Triggers the parsing of the current user agent
     */
    public function parse()
    {
        if ($this->parsed) {
            return;
        }

        $this->parsed = true;

        // skip parsing for empty useragents or those not containing any letter
        if (empty($this->userAgent) || preg_match('[a-z]', $this->userAgent)) {
            return;
        }

        $this->parseBot();
        if ($this->isBot())
            return;

        $this->parseOs();

        /**
         * Parse Clients
         * Clients might be browsers, Feed Readers, Mobile Apps, Media Players or
         * any other application accessing with an parseable UA
         */
        $this->parseClient();

        $this->parseDevice();
    }

    /**
     * Parses the UA for bot information using the Bot parser
     */
    protected function parseBot()
    {
        $botParser = new Bot();
        $botParser->setUserAgent($this->getUserAgent());
        $botParser->setCache($this->getCache());
        if ($this->discardBotInformation) {
            $botParser->discardDetails();
        }
        $this->bot = $botParser->parse();
    }

    protected function parseClient() {

        $parsers = $this->getClientParsers();

        foreach ($parsers AS $parser) {
            $parser->setCache($this->getCache());
            $parser->setUserAgent($this->getUserAgent());
            $client = $parser->parse();
            if (!empty($client)) {
                $this->client = $client;
                break;
            }
        }
    }

    protected function parseDevice() {

        $parsers = $this->getDeviceParsers();

        foreach ($parsers AS $parser) {
            $parser->setCache($this->getCache());
            $parser->setUserAgent($this->getUserAgent());
            if ($parser->parse()) {
                $this->device = $parser->getDeviceType();
                $this->model  = $parser->getModel();
                $this->brand  = $parser->getBrand();
                break;
            }
        }

        /**
         * Android up to 3.0 was designed for smartphones only. But as 3.0, which was tablet only, was published
         * too late, there were a bunch of tablets running with 2.x
         * With 4.0 the two trees were merged and it is for smartphones and tablets
         *
         * So were are expecting that all devices running Android < 2 are smartphones
         * Devices running Android 3.X are tablets. Device type of Android 2.X and 4.X+ are unknown
         */
        if (is_null($this->device) && $this->getOs('short_name') == 'AND' && $this->getOs('version') != '') {
            if (version_compare($this->getOs('version'), '2.0') == -1) {
                $this->device = DeviceParserAbstract::DEVICE_TYPE_SMARTPHONE;
            } else if (version_compare($this->getOs('version'), '3.0') >= 0 AND version_compare($this->getOs('version'), '4.0') == -1) {
                $this->device = DeviceParserAbstract::DEVICE_TYPE_TABLET;
            }
        }

        /**
         * According to http://msdn.microsoft.com/en-us/library/ie/hh920767(v=vs.85).aspx
         * Internet Explorer 10 introduces the "Touch" UA string token. If this token is present at the end of the
         * UA string, the computer has touch capability, and is running Windows 8 (or later).
         * This UA string will be transmitted on a touch-enabled system running Windows 8 (RT)
         *
         * As most touch enabled devices are tablets and only a smaller part are desktops/notebooks we assume that
         * all Windows 8 touch devices are tablets.
         */
        if (is_null($this->device) && in_array($this->getOs('short_name'), array('WI8', 'WRT')) && $this->isTouchEnabled()) {
            $this->device = DeviceParserAbstract::DEVICE_TYPE_TABLET;
        }

        // set device type to desktop for all devices running a desktop os that were not detected as an other device type
        if (is_null($this->device) && $this->isDesktop()) {
            $this->device = DeviceParserAbstract::DEVICE_TYPE_DESKTOP;
        }
    }

    protected function parseOs()
    {
        $osParser = new OperatingSystem();
        $osParser->setUserAgent($this->getUserAgent());
        $osParser->setCache($this->getCache());
        $this->os = $osParser->parse();
    }

    protected function matchUserAgent($regex)
    {
        $regex = '/(?:^|[^A-Z_-])(?:' . str_replace('/', '\/', $regex) . ')/i';

        if (preg_match($regex, $this->userAgent, $matches)) {
            return $matches;
        }

        return false;
    }

    static public function getInfoFromUserAgent($ua)
    {
        $deviceDetector = new DeviceDetector($ua);
        $deviceDetector->parse();

        if ($deviceDetector->isBot()) {
            return array(
                'user_agent' => $deviceDetector->getUserAgent(),
                'bot'        => $deviceDetector->getBot()
            );
        }

        $osFamily = OperatingSystem::getOsFamily($deviceDetector->getOs('short_name'));
        $browserFamily = \DeviceDetector\Parser\Client\Browser::getBrowserFamily($deviceDetector->getClient('short_name'));

        $processed = array(
            'user_agent'     => $deviceDetector->getUserAgent(),
            'os'             => array(
                'name'       => $deviceDetector->getOs('name'),
                'short_name' => $deviceDetector->getOs('short_name'),
                'version'    => $deviceDetector->getOs('version'),
            ),
            'client'        => array(
                'type'       => $deviceDetector->getClient('type'),
                'name'       => $deviceDetector->getClient('name'),
                'short_name' => $deviceDetector->getClient('short_name'),
                'version'    => $deviceDetector->getClient('version'),
            ),
            'device'         => array(
                'type'       => $deviceDetector->getDeviceName(),
                'brand'      => $deviceDetector->getBrand(),
                'model'      => $deviceDetector->getModel(),
            ),
            'os_family'      => $osFamily !== false ? $osFamily : 'Unknown',
            'browser_family' => $browserFamily !== false ? $browserFamily : 'Unknown',
        );
        return $processed;
    }

    /**
     * Sets the Cache class
     *
     * Note: The given class needs to have a 'get' and 'set' method to be used
     *
     * @param $cache
     */
    public function setCache(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Returns Cache object
     *
     * @return CacheInterface
     */
    public function getCache()
    {
        if (!empty($this->cache)) {
            return $this->cache;
        }

        return new CacheStatic();
    }
}


text:
[![Build](https://img.shields.io/travis/jaredhanson/passport-oauth1.svg)](https://travis-ci.org/jaredhanson/passport-oauth1)
[![Coverage](https://img.shields.io/coveralls/jaredhanson/passport-oauth1.svg)](https://coveralls.io/r/jaredhanson/passport-oauth1)
[![Quality](https://img.shields.io/codeclimate/github/jaredhanson/passport-oauth1.svg?label=quality)](https://codeclimate.com/github/jaredhanson/passport-oauth1)
[![Dependencies](https://img.shields.io/david/jaredhanson/passport-oauth1.svg)](https://david-dm.org/jaredhanson/passport-oauth1)

General-purpose OAuth 1.0 authentication strategy for [Passport](http://passportjs.org/).

This module lets you authenticate using OAuth in your Node.js applications.
By plugging into Passport, OAuth authentication can be easily and unobtrusively
integrated into any application or framework that supports
[Connect](http://www.senchalabs.org/connect/)-style middleware, including
[Express](http://expressjs.com/).

Note that this strategy provides generic OAuth support.  In many cases, a
provider-specific strategy can be used instead, which cuts down on unnecessary
configuration, and accommodates any provider-specific quirks.  See the
[list](https://github.com/jaredhanson/passport/wiki/Strategies) for supported
providers.

Developers who need to implement authentication against an OAuth provider that
is not already supported are encouraged to sub-class this strategy.  If you
choose to open source the new provider-specific strategy, please add it to the
list so other people can find it.

## Install

    $ npm install passport-oauth1

## Usage

#### Configure Strategy

The OAuth authentication strategy authenticates users using a third-party
account and OAuth tokens.  The provider's OAuth endpoints, as well as the
consumer key and secret, are specified as options.  The strategy requires a
`verify` callback, which receives a token and profile, and calls `cb`
providing a user.

    passport.use(new OAuth1Strategy({
        requestTokenURL: 'https://www.example.com/oauth/request_token',
        accessTokenURL: 'https://www.example.com/oauth/access_token',
        userAuthorizationURL: 'https://www.example.com/oauth/authorize',
        consumerKey: EXAMPLE_CONSUMER_KEY,
        consumerSecret: EXAMPLE_CONSUMER_SECRET,
        callbackURL: "http://127.0.0.1:3000/auth/example/callback",
        signatureMethod: "RSA-SHA1"
      },
      function(token, tokenSecret, profile, cb) {
        User.findOrCreate({ exampleId: profile.id }, function (err, user) {
          return cb(err, user);
        });
      }
    ));

#### Authenticate Requests

Use `passport.authenticate()`, specifying the `'oauth'` strategy, to
authenticate requests.

For example, as route middleware in an [Express](http://expressjs.com/)
application:

    app.get('/auth/example',
      passport.authenticate('oauth'));

    app.get('/auth/example/callback',
      passport.authenticate('oauth', { failureRedirect: '/login' }),
      function(req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
      });

## Related Modules

- [passport-oauth2](https://github.com/jaredhanson/passport-oauth2) — OAuth 2.0 authentication strategy
- [passport-http-oauth](https://github.com/jaredhanson/passport-http-oauth) — OAuth authentication strategy for APIs
- [oauthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit

## Contributing

#### Tests

The test suite is located in the `test/` directory.  All new features are
expected to have corresponding test cases.  Ensure that the complete test suite
passes by executing:

```bash
$ make test
```

#### Coverage

All new feature development is expected to have test coverage.  Patches that
increse test coverage are happily accepted.  Coverage reports can be viewed by
executing:

```bash
$ make test-cov
$ make view-cov
```

## Support

#### Funding

This software is provided to you as open source, free of charge.  The time and
effort to develop and maintain this project is dedicated by [@jaredhanson](https://github.com/jaredhanson).
If you (or your employer) benefit from this project, please consider a financial
contribution.  Your contribution helps continue the efforts that produce this
and other open source software.

Funds are accepted via [PayPal](https://paypal.me/jaredhanson), [Venmo](https://venmo.com/jaredhanson),
and [other](http://jaredhanson.net/pay) methods.  Any amount is appreciated.

## License

[The MIT License](http://opensource.org/licenses/MIT)

Copyright (c) 2011-2016 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>


text:
// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "main.h"

#include "test/test_bitcoin.h"

#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup)

static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams)
{
    int maxHalvings = 64;
    CAmount nInitialSubsidy = 50 * COIN;

    CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
    BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
    for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
        int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
        CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);
        BOOST_CHECK(nSubsidy <= nInitialSubsidy);
        BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
        nPreviousSubsidy = nSubsidy;
    }
    BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0);
}

static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
    Consensus::Params consensusParams;
    consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
    TestBlockSubsidyHalvings(consensusParams);
}

BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
    /*const boost::scoped_ptr<CChainParams> testChainParams(CChainParams::Factory(CBaseChainParams::MAIN));
    TestBlockSubsidyHalvings(testChainParams->GetConsensus()); // As in main
    TestBlockSubsidyHalvings(150); // As in regtest
    TestBlockSubsidyHalvings(1000); // Just another interval*/
}

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    std::map<std::string, std::string> mapArgs;
    const boost::scoped_ptr<CChainParams> testChainParams(CChainParams::Factory(CBaseChainParams::MAIN, mapArgs));
    CAmount nSum = GetBlockSubsidy(0, testChainParams->GetConsensus());
    BOOST_CHECK_EQUAL(nSum, 2100000000000000ULL);
    for (int nHeight = 1; nHeight < 14000000; nHeight += 1000) {
        CAmount nSubsidy = GetBlockSubsidy(nHeight, testChainParams->GetConsensus());
        BOOST_CHECK(nSubsidy == 0);
        nSum += nSubsidy * 1000;
        BOOST_CHECK(MoneyRange(nSum));
    }
    BOOST_CHECK_EQUAL(nSum, 2100000000000000ULL);
}

bool ReturnFalse() { return false; }
bool ReturnTrue() { return true; }

BOOST_AUTO_TEST_CASE(test_combiner_all)
{
    boost::signals2::signal<bool (), CombinerAll> Test;
    BOOST_CHECK(Test());
    Test.connect(&ReturnFalse);
    BOOST_CHECK(!Test());
    Test.connect(&ReturnTrue);
    BOOST_CHECK(!Test());
    Test.disconnect(&ReturnFalse);
    BOOST_CHECK(Test());
    Test.disconnect(&ReturnTrue);
    BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Excess.Compiler.Roslyn;
using Excess.Concurrent.Compiler.Model;

namespace Excess.Concurrent.Compiler
{
    using CSharp = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
    using Roslyn = RoslynCompiler;

    internal class ExpressionLinker : CSharpSyntaxRewriter
    {
        Class _class;
        SemanticModel _model;
        public ExpressionLinker(Class @class, SemanticModel model)
        {
            _class = @class;
            _model = model;
        }

        bool _first = true;
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            if (_first)
            {
                //the one we are linking
                _first = false;
                return base.VisitClassDeclaration(node);
            }

            //custom types, may be the generated expression types
            var fields = null as Dictionary<string, TypeSyntax>;
            if (_typeAssignments.TryGetValue(node.Identifier.ToString(), out fields))
                return node.AddMembers(fields
                    .Select(f => Templates
                    .AssignmentField
                    .Get<MemberDeclarationSyntax>(f.Key, f.Value))
                    .ToArray());

            return node; //let it go unmodified
        }

        bool _isStatic;
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            if (_class.IsSignal(node))
            {
                _isStatic = Roslyn.IsStatic(node);
                return base.VisitMethodDeclaration(node);
            }

            return node;
        }

        public override SyntaxNode VisitBlock(BlockSyntax node)
        {
            return node.WithStatements(CSharp.List(
                node
                .Statements
                .SelectMany(st => LinkExpressionStatement(st))
                .ToArray()));
        }

        //the issue at hand, we cannot have "yield return"s inside a try catch (thanks, Obama)
        //So we will split the try catch(es) around the requisition of the (proverbial) cheese.
        int _trysInStack = 0;
        bool _tryConcurrent = false;
        List<string> _tryVariables = new List<string>();
        public override SyntaxNode VisitTryStatement(TryStatementSyntax node)
        {
            _trysInStack++;
            try
            {
                var newNode = (TryStatementSyntax)base.VisitTryStatement(node);

                if (_tryConcurrent)
                {
                    var variableName = "__try" + _trysInStack;
                    _tryVariables.Add(variableName);

                    //we can only split on expressions directly on the try level
                    //i.e. no try { if () { EXPRESSION }}
                    if (_trysInStack > 1 && !(newNode.Parent.Parent is TryStatementSyntax))
                    {
                        Debug.Assert(false); //td: error
                        return newNode;
                    }

                    var statements = new List<StatementSyntax>(newNode.Block.Statements);
                    var newStatements = new List<StatementSyntax>();
                    var currentIndex = 0;

                    while (currentIndex < statements.Count)
                    {
                        var oldIndex = currentIndex;
                        for (int i = oldIndex; i < statements.Count; i++, currentIndex++)
                        {
                            var statement = statements[i];

                            if (statement is YieldStatementSyntax)
                            {
                                newStatements.Add(newNode
                                    .WithBlock(CSharp.Block(
                                        statements
                                        .Skip(oldIndex)
                                        .Take(currentIndex - oldIndex - 1))));

                                //variable and return yield
                                //td: assert
                                newStatements.Add(statements[currentIndex - 1]);
                                newStatements.Add(statements[currentIndex++]);
                                break;
                            }

                            //must make variables available to later code, unless it precedes a yield
                            var yieldNext = statements.Count > i + 1 && statements[i + 1] is YieldStatementSyntax;
                            if (statement is LocalDeclarationStatementSyntax && !yieldNext)
                            {
                                var decl = statement as LocalDeclarationStatementSyntax;

                                var varType = decl.Declaration.Type;
                                if (varType == null || varType.Kind() == SyntaxKind.TypeVarKeyword)
                                    varType = Roslyn.SymbolTypeSyntax(_model, decl
                                        .Declaration
                                        .Variables[0]
                                        .Initializer
                                        .Value);

                                Debug.Assert(varType != null, "Untyped local variable on try fix");

                                var assignmentStatements = new List<StatementSyntax>();
                                newStatements.Add(decl
                                    .WithDeclaration(decl.Declaration
                                    .WithType(varType)
                                    .WithVariables(CSharp.SeparatedList(
                                        decl
                                        .Declaration
                                        .Variables
                                        .Select(v =>
                                        {
                                            assignmentStatements.Add(CSharp.ExpressionStatement(
                                                CSharp.AssignmentExpression(
                                                    SyntaxKind.SimpleAssignmentExpression,
                                                    CSharp.IdentifierName(v.Identifier),
                                                    v.Initializer.Value)));

                                            return v.WithInitializer(v
                                                .Initializer
                                                .WithValue(Templates
                                                    .DefaultValue
                                                    .Get<ExpressionSyntax>(varType)));
                                        })))));

                                //once moved the variables "up" scope
                                //we must keep the assignments
                                Debug.Assert(assignmentStatements.Any());
                                statements.RemoveAt(i);
                                statements.InsertRange(i, assignmentStatements);
                            }
                        }
                    }

                    Debug.Assert(newStatements.Any());
                    return LinkTryStatements(newStatements, variableName);
                }

                return newNode;
            }
            finally
            {
                _trysInStack--;
            }
        }

        private SyntaxNode LinkTryStatements(List<StatementSyntax> statements, string variable)
        {
            var newStatements = new List<StatementSyntax>();
            var firstTry = _trysInStack == 1;
            if (firstTry)
            {
                foreach (var v in _tryVariables)
                    newStatements.Add(Templates
                        .TryVariable
                        .Get<StatementSyntax>(v));

                _tryConcurrent = false;
                _tryVariables.Clear();
            }

            return CSharp.Block(
                newStatements.Union(
                CreateTrySplit(statements, 0, variable)));
        }

        private IEnumerable<StatementSyntax> CreateTrySplit(List<StatementSyntax> statements, int index, string variable)
        {
            bool foundTry = false;
            for (int i = index; i < statements.Count; i++, index++)
            {
                if (foundTry)
                {
                    yield return CSharp.IfStatement(
                        Templates.Negation.Get<ExpressionSyntax>(CSharp.IdentifierName(variable)),
                        CSharp.Block(CreateTrySplit(statements, index, variable)));

                    yield break;
                }

                var statement = statements[i];
                if (statement is TryStatementSyntax)
                {
                    foundTry = true;
                    var @try = statement as TryStatementSyntax;
                    yield return @try
                        .WithCatches(CSharp.List(
                            @try
                            .Catches
                            .Select(c => c.WithBlock(CSharp.Block(new [] {
                                Templates
                                .SetTryVariable
                                .Get<StatementSyntax>(variable)}.Union(
                                c.Block.Statements))))));
                }
                else
                    yield return statement;
            }
        }

        //concurrent expressions, must remember all assignents
        Dictionary<string, Dictionary<string, TypeSyntax>> _typeAssignments = new Dictionary<string, Dictionary<string, TypeSyntax>>();
        private IEnumerable<StatementSyntax> LinkExpressionStatement(StatementSyntax statement)
        {
            var yieldStatement = statement as YieldStatementSyntax;
            if (yieldStatement == null)
                yield return (StatementSyntax)Visit(statement);
            else
            {
                var expression = yieldStatement
                    .Expression
                    as ObjectCreationExpressionSyntax;

                if (expression == null)
                    yield return (StatementSyntax)Visit(statement);
                else
                {
                    //check for try/catch statements
                    if (_trysInStack > 0)
                    {
                        _tryConcurrent = true;
                        Debug.Assert(statement.Parent.Parent is TryStatementSyntax); //td: error
                    }

                    var assignments = new Dictionary<string, TypeSyntax>();
                    var typeName = expression.Type.ToString();

                    expression = expression
                        .ReplaceNodes(expression
                            .DescendantNodes()
                            .OfType<ParenthesizedLambdaExpressionSyntax>(),
                            (on, nn) => LinkExpresion(nn, assignments));

                    if (assignments.Any())
                        _typeAssignments[typeName] = assignments;

                    //create a variable to hold the expression, then yield-return it
                    //after completion, the results of the expression will be extracted from
                    //this variable
                    var varName = typeName + "_var";
                    var exprVariable = Templates
                        .ExpressionVariable
                        .Get<StatementSyntax>(varName, expression);

                    yield return exprVariable;

                    yield return yieldStatement
                        .WithExpression(CSharp.IdentifierName(varName));

                    //we must check whether the expression failed
                    yield return Templates
                        .ExpressionFailedCheck
                        .Get<StatementSyntax>(varName);

                    //and finally, we must generate expression assignments
                    //this way, any operand result will stay in the expression
                    //and only be used "after" the expression is complete.
                    foreach (var assigment in assignments)
                    {
                        yield return Templates
                            .AssigmentAfterExpression
                            .Get<StatementSyntax>(
                                assigment.Key,
                                varName);
                    }
                }
            }
        }

        private ParenthesizedLambdaExpressionSyntax LinkExpresion(ParenthesizedLambdaExpressionSyntax expression, Dictionary<string, TypeSyntax> assignments)
        {
            var body = expression.Body as BlockSyntax;
            if (body == null)
                return expression; //td: error checking

            return expression
                .WithBody(body
                    .WithStatements(CSharp.List(body
                        .Statements
                        .Select(st => LinkConcurrentStatement(st, assignments)))));
        }

        private StatementSyntax LinkConcurrentStatement(StatementSyntax statement, Dictionary<string, TypeSyntax> assignments)
        {
            //we encode the process (in whichever form) as call in the form
            //__marker__(process, success, failure);
            //why? why not?
            var exprStatement = statement as ExpressionStatementSyntax;
            if (exprStatement == null)
                return statement; //td: error checking

            var invocation = exprStatement.Expression as InvocationExpressionSyntax;
            if (    invocation == null
                ||  invocation.Expression.ToString() != "__marker__"
                ||  invocation.ArgumentList.Arguments.Count != 3)
                return statement; //td: error checking

            var operand = invocation.ArgumentList.Arguments[0].Expression;
            var success = invocation.ArgumentList.Arguments[1].Expression as InvocationExpressionSyntax;
            var failure = invocation.ArgumentList.Arguments[2].Expression as InvocationExpressionSyntax;

            return LinkOperand(operand, success, failure, assignments);
        }

        private StatementSyntax LinkOperand(ExpressionSyntax operand, InvocationExpressionSyntax success, InvocationExpressionSyntax failure, Dictionary<string, TypeSyntax> assignments)
        {
            if (operand is InvocationExpressionSyntax)
                return LinkProcessInvocation(operand as InvocationExpressionSyntax, success, failure);

            if (operand is IdentifierNameSyntax)
                return LinkSignal(operand as IdentifierNameSyntax, success, failure);

            if (operand is AssignmentExpressionSyntax)
                return LinkAssignment(operand as AssignmentExpressionSyntax, success, failure, assignments);

            if (operand is ParenthesizedExpressionSyntax)
                return LinkOperand((operand as ParenthesizedExpressionSyntax).Expression, success, failure, assignments);

            if (operand is LiteralExpressionSyntax)
            {
                var literal = operand as LiteralExpressionSyntax;
                switch (literal.Kind())
                {
                    case SyntaxKind.TrueLiteralExpression:
                    case SyntaxKind.FalseLiteralExpression:
                        return CSharp.ExpressionStatement(success
                            .ReplaceNodes(success
                            .DescendantNodes()
                            .OfType<LiteralExpressionSyntax>()
                            .Where(l => l.Kind() == SyntaxKind.TrueLiteralExpression
                                     || l.Kind() == SyntaxKind.FalseLiteralExpression),
                            (on, nn) => literal));
                }
            }

            throw new NotImplementedException(); //td:
        }

        private StatementSyntax LinkAssignment(AssignmentExpressionSyntax assignment, InvocationExpressionSyntax success, InvocationExpressionSyntax failure, Dictionary<string, TypeSyntax> assignments)
        {
            var leftString = assignment.Left.ToString();
            var leftType = Roslyn.SymbolTypeSyntax(_model, assignment.Left);

            Debug.Assert(assignment.Left is IdentifierNameSyntax);
            Debug.Assert(!assignments.ContainsKey(leftString));
            Debug.Assert(leftType != null); //td: error

            assignments[leftString] = leftType;

            var emptyAssignments = new Dictionary<string, TypeSyntax>();
            var right = LinkOperand(assignment.Right, success, failure, emptyAssignments);

            Debug.Assert(right != null);
            Debug.Assert(!emptyAssignments.Any());

            //there are 2 scenarios, first, the right operand was a concurrent expression
            //in which case it would have a success function
            var successFunc = right
                .DescendantNodes()
                .OfType<ParenthesizedLambdaExpressionSyntax>()
                .Where(fn => fn
                    .ParameterList
                    .Parameters
                    .Any(p => p.Identifier.ToString() == "__res"))
                .SingleOrDefault();

            if (successFunc != null)
            {
                var bodyStatement = (successFunc.Body as StatementSyntax)
                    ?? CSharp.ExpressionStatement((ExpressionSyntax)successFunc.Body);

                return right.ReplaceNode(successFunc, successFunc
                    .WithBody(CSharp.Block(new[] {
                        Templates
                            .ExpressionAssigment
                            .Get<StatementSyntax>(assignment.Left, leftType) }
                        .Union(successFunc.Body is BlockSyntax
                            ? (successFunc.Body as BlockSyntax)
                                .Statements
                                .AsEnumerable()
                            : new[] { bodyStatement })
                        .ToArray())));
            }

            //else, we need to substitute the actual Right expr by
            //an assignment.
            var rightString = assignment.Right.ToString();
            return right.ReplaceNodes(right.
                DescendantNodes()
                .OfType<ExpressionSyntax>()
                .Where(node => node.ToString().Equals(rightString)),
                (on, nn) => CSharp.AssignmentExpression(
                    assignment.Kind(),
                    Templates
                        .ExpressionProperty
                        .Get<ExpressionSyntax>(assignment.Left),
                    nn));
        }

        private ParenthesizedLambdaExpressionSyntax WrapInLambda(params ExpressionSyntax[] expressions)
        {
            return WrapInLambda(expressions
                .AsEnumerable());
        }

        private ParenthesizedLambdaExpressionSyntax WrapInLambda(IEnumerable<ExpressionSyntax> expressions)
        {
            return CSharp.ParenthesizedLambdaExpression(
                CSharp.Block(expressions
                    .Select(e => CSharp.ExpressionStatement(e))));
        }

        private StatementSyntax LinkSignal(IdentifierNameSyntax name, InvocationExpressionSyntax success, InvocationExpressionSyntax failure)
        {
            var signalName = name.ToString();
            var signal = _class.GetSignal(signalName);
            Debug.Assert(signal != null);

            return Templates
                .SignalListener
                .Get<StatementSyntax>(
                    Roslyn.Quoted(signalName),
                    WrapInLambda(success));
        }

        private StatementSyntax LinkProcessInvocation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure)
        {
            var call = invocation.Expression;
            if (call is IdentifierNameSyntax)
                return LinkThisInvocation(invocation, success, failure);

            return LinkExternalInvocation(invocation, success, failure);
        }

        private StatementSyntax LinkThisInvocation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure)
        {
            Debug.Assert(invocation.Expression is IdentifierNameSyntax);

            //internal calls
            StatementSyntax result;
            if (syntaxOperation(invocation, success, failure, out result))
                return result;
            else
            {
                var identifier = (invocation.Expression as IdentifierNameSyntax)
                    .ToString();
                var signal = _class.GetSignal(identifier);
                var functional = default(StatementSyntax);
                if (signal != null)
                {
                    var expr = invocation
                        .WithExpression(CSharp.IdentifierName("__concurrent" + identifier))
                        .WithArgumentList(invocation
                            .ArgumentList
                            .AddArguments(
                                CSharp.Argument(
                                    Templates.CancelationArgument),
                                CSharp.Argument(WrapInLambda(success)
                                    .AddParameterListParameters(CSharp.Parameter(CSharp.ParseToken(
                                        "__res")))),
                                CSharp.Argument(WrapInLambda(failure)
                                    .AddParameterListParameters(CSharp.Parameter(CSharp.ParseToken(
                                        "__ex"))))));

                    return CSharp.ExpressionStatement(Templates
                        .Advance
                        .Get<ExpressionSyntax>(expr));
                }
                else if (isFunctionalCall(invocation, out functional))
                    return functional;

                return CSharp.ExpressionStatement(invocation);
            }
        }

        private bool isFunctionalCall(InvocationExpressionSyntax invocation, out StatementSyntax functional)
        {
            functional = null;
            var containingClass = invocation
                .Ancestors()
                .OfType<ClassDeclarationSyntax>()
                .FirstOrDefault();

            if (containingClass == null)
                return false;

            var parentContainer = containingClass.Parent as ClassDeclarationSyntax;
            if (parentContainer == null || parentContainer.Identifier.ToString() != "Functions" )
                return false;

            var concurrentClassName = invocation.Expression.ToString() + "__concurrent";
            var concurrentClass = parentContainer
                .Members
                .OfType<ClassDeclarationSyntax>()
                .SingleOrDefault(@class => @class.Identifier.ToString() == concurrentClassName);

            var newInvocation = default(InvocationExpressionSyntax);
            if (concurrentClass != null)
                newInvocation = Templates.ConcurrentFunctionStatement
                    .Get<InvocationExpressionSyntax>(
                        concurrentClass.Identifier,
                        (invocation.Expression as IdentifierNameSyntax)
                            .Identifier);
            else
                newInvocation = Templates.FunctionStatement
                    .Get<InvocationExpressionSyntax>(invocation.Expression);

            functional = CSharp.ExpressionStatement(newInvocation);
            return true;
        }

        private StatementSyntax LinkExternalInvocation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure)
        {
            var queueStatement = null as StatementSyntax;
            if (_class.isQueueInvocation(invocation, true, success, out queueStatement))
                return queueStatement;

            Debug.Assert(invocation.Expression is MemberAccessExpressionSyntax);
            Debug.Assert(!invocation.Expression
                .DescendantNodes()
                .OfType<InvocationExpressionSyntax>()
                .Any()); //td: errors

            var symbol = _model.GetSymbolInfo(invocation.Expression).Symbol;
            if (symbol != null)
            {
                if (isConcurrent(symbol))
                    return CSharp.ExpressionStatement(
                        invocation
                        .WithArgumentList(invocation
                            .ArgumentList
                            .AddArguments(
                                CSharp.Argument(Templates.CancelationArgument),
                                CSharp.Argument(Templates
                                    .SuccessFunction
                                    .Get<ExpressionSyntax>(success)),
                                CSharp.Argument(Templates
                                    .FailureFunction
                                    .Get<ExpressionSyntax>(failure)))));

                if (isTask(symbol))
                    return Templates.TaskInvocation
                        .Get<StatementSyntax>(invocation, success, failure);
            }

            return Templates
                .NonConcurrentInvocation
                .Get<StatementSyntax>(invocation, success, failure);
        }

        private bool isTask(ISymbol symbol)
        {
            var method = symbol as IMethodSymbol;
            if (method == null)
                return false;

            if (method.ReturnType == null || method.ReturnType.Name != "Task")
                return false;

            return method
                .ReturnType
                .AllInterfaces
                .Any(i => i.Name == "IAsyncResult"); //td: needs to be safer
        }

        private bool isConcurrent(ISymbol symbol)
        {
            var type = symbol.ContainingType;
            return type != null && type.MemberNames.Contains("__concurrent" + symbol.Name);

        }

        private bool syntaxOperation(InvocationExpressionSyntax invocation, InvocationExpressionSyntax success, InvocationExpressionSyntax failure, out StatementSyntax result)
        {
            result = null;
            switch (invocation.Expression.ToString())
            {
                case "seconds":
                    result = Templates
                        .Seconds
                        .Get<StatementSyntax>(
                            invocation.ArgumentList
                                .Arguments[0] //td: validate
                                .Expression,
                            success,
                            failure,
                            Templates.Cheese(_isStatic));
                    break;
                case "timeout":
                    throw new NotImplementedException();
                case "parallel":
                    throw new NotImplementedException();
                default:
                    return false;
            }

            return true;
        }
    }
}


text:
'use strict';

require('./server/index.js');


text:
template union tSlot<Compose>;

Compose::Compose(Slot _first, Slot _second)
  : Tuple(2), first(_first), second(_second)
{
  DEBLOG(cerr << "Compose construction " << *this << '\n');
}

Compose::Compose(const Slot &both)
  : Tuple(2), first(both[0]), second(both[1])
{
  DEBLOG(cerr << "Compose construction " << *this << '\n');
}

Compose::~Compose()
{}

Slot Compose::call(Slot &args)
{
  DEBLOG(cerr << "Compose call: "
	 << *this
	 << " args: " << args
	 << '\n');
  Slot result = new List(second->call(args));
  DEBLOG(cerr << "Compose call: " << *this
	 << " args: " << args
	 << " apply second: " << result << '\n');
  DEBLOG(cerr << "calling first: " << first
	 << " of type " << first->typeId()
	 << " with " << result << '\n');
  result = first->call(result);
  DEBLOG(cerr << "Compose call: " << *this
	 << " apply first: " << result << '\n');
  return result;
}