text:
<?php

/**
 * @package toolkit
 */
/**
 * Devkit extends the HTMLPage class to provide an object representation
 * of a Symphony Devkit page. Devkit's are used to aid in debugging by providing
 * raw XML representations of data sources and parameters and to help provide
 * profiling. There are two Symphony Devkit's currently, Debug and Profile. Devkit
 * pages are restricted to Symphony Author's and require them to be authenticated
 * to view them.
 */

class DevKit extends HTMLPage
{
    /**
     * The Devkit's `$_GET` query string
     * @var string
     */
    protected $_query_string = '';

    /**
     * An instance of the XSLTPage, usually FrontendPage
     * @var XSLTPage
     */
    protected $_page = null;

    /**
     * An associative array of the details of the Page that is being 'Devkitted'.
     * The majority of this information is from `tbl_pages` table.
     * @var array
     */
    protected $_pagedata = null;

    /**
     * The XML of the page that the XSLT will be applied to, this includes any
     * datasource results.
     * @var string
     */
    protected $_xml = null;

    /**
     * An array of the page parameters, including those provided by datasources.
     * @var array
     */
    protected $_param = array();

    /**
     * The resulting Page after it has been transformed, as a string. This is
     * similar to what you would see if you 'view-sourced' a page in a web browser
     * @var string
     */
    protected $_output = '';

    /**
     * Builds the Includes for a Devkit and sets the Content Type
     * to be text/html. The default Symphony devkit stylesheet
     * is the only include. The default doctype is enables HTML5
     */
    protected function buildIncludes()
    {
        $this->addHeaderToPage('Content-Type', 'text/html; charset=UTF-8');

        $this->Html->setElementStyle('html');
        $this->Html->setDTD('<!DOCTYPE html>');
        $this->Html->setAttribute('lang', Lang::get());
        $this->addElementToHead(new XMLElement(
            'meta',
            null,
            array(
                'http-equiv'    => 'Content-Type',
                'content'       => 'text/html; charset=UTF-8'
            )
        ));
        $this->addStylesheetToHead(ASSETS_URL . '/css/devkit.min.css', 'screen', null, false);
    }

    /**
     * This function will build the `<title>` element and create a default
     * `<h1>` with an anchor to this query string
     *
     * @param XMLElement $wrapper
     *    The parent `XMLElement` to add the header to
     * @throws InvalidArgumentException
     */
    protected function buildHeader(XMLElement $wrapper)
    {
        $this->setTitle(__(
            '%1$s – %2$s – %3$s',
            array(
                $this->_pagedata['title'],
                __($this->_title),
                __('Symphony')
            )
        ));

        $h1 = new XMLElement('h1');
        $h1->appendChild(Widget::Anchor($this->_pagedata['title'], ($this->_query_string ? '?' . trim(html_entity_decode($this->_query_string), '&') : '.')));

        $wrapper->appendChild($h1);
    }

    /**
     * Using DOMDocument, construct the Navigation list using the `devkit_navigation.xml`
     * file in the `ASSETS` folder. The default navigation file is an empty `<navigation>`
     * element. The `ManipulateDevKitNavigation` delegate allows extensions
     * to inject items into the navigation. The navigation is build by iterating over `<item>`
     * elements added. The idea is that all Devkit's can be accessed using the Navigation.
     *
     * @uses ManipulateDevKitNavigation
     * @param XMLElement $wrapper
     *    The parent XMLElement to add the navigation to
     * @throws InvalidArgumentException
     */
    protected function buildNavigation(XMLElement $wrapper)
    {
        $xml = new DOMDocument();
        $xml->preserveWhiteSpace = false;
        $xml->formatOutput = true;
        $xml->load(ASSETS . '/xml/devkit_navigation.xml');
        $root = $xml->documentElement;
        $list = new XMLElement('ul');
        $list->setAttribute('id', 'navigation');

        // Add edit link:
        $item = new XMLElement('li');
        $item->appendChild(Widget::Anchor(
            __('Edit'),
            SYMPHONY_URL . '/blueprints/pages/edit/' . $this->_pagedata['id'] . '/'
        ));
        $list->appendChild($item);

        // Translate navigation names:
        if ($root->hasChildNodes()) {
            foreach ($root->childNodes as $item) {
                if ($item->tagName == 'item') {
                    $item->setAttribute('name', __($item->getAttribute('name')));
                }
            }
        }

        /**
         * Allow navigation XML to be manipulated before it is rendered.
         *
         * @delegate ManipulateDevKitNavigation
         * @param string $context
         *  '/frontend/'
         * @param DOMDocument $xml
         */
        Symphony::ExtensionManager()->notifyMembers(
            'ManipulateDevKitNavigation',
            '/frontend/',
            array(
                'xml'   => $xml
            )
        );

        if ($root->hasChildNodes()) {
            foreach ($root->childNodes as $node) {
                if ($node->getAttribute('active') === 'yes') {
                    $item = new XMLElement('li', $node->getAttribute('name'));
                } else {
                    $item = new XMLElement('li');
                    $item->appendChild(Widget::Anchor(
                        $node->getAttribute('name'),
                        '?' . $node->getAttribute('handle') . $this->_query_string
                    ));
                }

                $list->appendChild($item);
            }
        }

        $wrapper->appendChild($list);
    }

    /**
     * This function builds a Jump menu, which is what a Devkit uses as it's
     * internal navigation. Items are added to the Jump menu using the
     * buildJumpItem function
     *
     * @see buildJumpItem
     * @param XMLElement $wrapper
     *  The parent XMLElement that the jump menu will be appended
     *  to. By default this is `<div id='jump'>`
     */
    protected function buildJump(XMLElement $wrapper)
    {
    }

    /**
     *
     * @param string $name
     *    The name of the jump
     * @param string $link
     *    The link for this jump item
     * @param boolean $active
     *    Whether this is the active link, if true, this will add an
     *    active class to the link built. By default this is false
     * @throws InvalidArgumentException
     * @return XMLElement
     */
    protected function buildJumpItem($name, $link, $active = false)
    {
        $item = new XMLElement('li');
        $anchor = Widget::Anchor($name, $link);
        $anchor->setAttribute('class', 'inactive');

        if ($active) {
            $anchor->setAttribute('class', 'active');
        }

        $item->appendChild($anchor);

        return $item;
    }

    /**
     * The content of the Devkit, defaults to empty.
     *
     * @param XMLElement $wrapper
     *  The parent XMLElement that the content will be appended
     *  to. By default this is `<div id='content'>`
     */
    protected function buildContent(XMLElement $wrapper)
    {
    }

    /**
     * The prepare function acts a pseudo constructor for the Devkit,
     * setting some base variables with the given parameters
     *
     * @param XSLTPage $page
     *  An instance of the XSLTPage, usually FrontendPage
     * @param array $pagedata
     *  An associative array of the details of the Page that is
     *  being 'Devkitted'. The majority of this information is from
     *  tbl_pages table.
     * @param string $xml
     *  The XML of the page that the XSLT will be applied to, this includes
     *  any datasource results.
     * @param array $param
     *  An array of the page parameters, including those provided by
     *  datasources.
     * @param string $output
     *  The resulting Page after it has been transformed, as a string. This is
     *  similar to what you would see if you 'view-sourced' a page.
     */
    public function prepare(XSLTPage $page, array $pagedata, $xml, array $param, $output)
    {
        $this->_page = $page;
        $this->_pagedata = $pagedata;
        $this->_xml = $xml;
        $this->_param = $param;
        $this->_output = $output;

        if (is_null($this->_title)) {
            $this->_title = __('Utility');
        }
    }

    /**
     * Called when page is generated, this function calls each of the other
     * other functions in this page to build the Header, the Navigation,
     * the Jump menu and finally the content. This function calls it's parent
     * generate function
     *
     * @see toolkit.HTMLPage#generate()
     * @throws InvalidArgumentException
     * @return string
     */
    public function build()
    {
        $this->buildIncludes();
        $this->_view = General::sanitize($this->_view);

        $header = new XMLElement('div');
        $header->setAttribute('id', 'header');
        $jump = new XMLElement('div');
        $jump->setAttribute('id', 'jump');
        $content = new XMLElement('div');
        $content->setAttribute('id', 'content');

        $this->buildHeader($header);
        $this->buildNavigation($header);

        $this->buildJump($jump);
        $header->appendChild($jump);

        $this->Body->appendChild($header);

        $this->buildContent($content);
        $this->Body->appendChild($content);

        return $this->generate();
    }
}


text:
package com.github.k24.prefsoven.field;

import android.os.Build;

import com.github.k24.prefsoven.Prefs;
import com.github.k24.prefsoven.sample.TestPrefs;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by k24 on 2016/02/21.
 */
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN)
@RunWith(RobolectricTestRunner.class)
public class FloatPrefTest {

    @Before
    public void setUp() throws Exception {
        Prefs.install(RuntimeEnvironment.application);
        Prefs.prefs(TestPrefs.class).edit().clear().commit();
    }

    @Test
    public void add() throws Exception {
        TestPrefs prefs = Prefs.oven(TestPrefs.class);

        assertThat(prefs.float1().add(1f))
                .isEqualTo(1f);
        assertThat(prefs.float1().add(1f))
                .isEqualTo(2f);
        assertThat(prefs.float1().add(1.9f))
                .isEqualTo(2f + 1.9f);
        assertThat(prefs.float1().add(-1.9f))
                .isEqualTo(2f);

        // Max
        prefs.float1().put(1f);
        assertThat(prefs.float1().add(Float.MAX_VALUE))
                .isEqualTo(Float.MAX_VALUE);
        prefs.float1().put(-1f);
        assertThat(prefs.float1().add(Float.MAX_VALUE))
                .isEqualTo(Float.MAX_VALUE - 1f);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <thrift/lib/cpp/concurrency/Util.h>

#include <thrift/lib/cpp/test/loadgen/loadgen.h>
#include <thrift/lib/cpp/test/loadgen/QpsMonitor.h>
#include <thrift/lib/cpp/test/loadgen/Worker.h>

#include "common/config/Flags.h"

DEFINE_double(interval, 1.0, "number of seconds between statistics output");
DEFINE_int32(ops_per_conn, 1, "number of operations per connection");
DEFINE_int32(num_threads, 8, "number of worker threads");
DEFINE_bool(qps_monitor, false, "use the simple QPS monitor");

using std::shared_ptr;
namespace loadgen = apache::thrift::loadgen;

class PerfLoadConfig : public loadgen::LoadConfig {
 public:
  virtual uint32_t getNumOpTypes() const {
    return 1;
  }

  virtual uint32_t pickOpType() {
    return 0;
  }

  virtual uint32_t pickOpsPerConnection() {
    return FLAGS_ops_per_conn;
  }

  virtual uint32_t getNumWorkerThreads() const {
    return FLAGS_num_threads;
  }

  virtual std::string getOpName(uint32_t opType) {
    return "noop";
  }
};

class PerfWorker : public loadgen::Worker<void, PerfLoadConfig> {
 public:
  virtual shared_ptr<void> createConnection() {
    return shared_ptr<void>();
  }

  virtual void performOperation(const shared_ptr<void>& client, uint32_t op) {
    return;
  }
};

int main(int argc, char* argv[]) {
  facebook::config::Flags::initFlags(&argc, &argv, true);

  if (argc != 1) {
    fprintf(stderr, "error: unhandled arguments:");
    for (int n = 1; n < argc; ++n) {
      fprintf(stderr, " %s", argv[n]);
    }
    fprintf(stderr, "\n");
    return 1;
  }

  shared_ptr<PerfLoadConfig> config(new PerfLoadConfig);

  if (FLAGS_qps_monitor) {
    loadgen::QpsMonitor monitor(config);
    loadgen::runLoadGen<PerfWorker>(config, FLAGS_interval, &monitor);
  } else {
    loadgen::runLoadGen<PerfWorker>(config, FLAGS_interval);
  }

  return 0;
}


text:
"""Transport adapter for Requests."""

from __future__ import absolute_import

import cachecontrol
import functools
import logging
import numbers
import time

try:
    import requests
except ImportError as error:  # pragma: NO COVER
    import six

    six.raise_from(
        ImportError(
            "The requests library is not installed, please install the "
            "requests package to use the requests transport."
        ),
        error,
    )
import requests.adapters  # pylint: disable=ungrouped-imports
import requests.exceptions  # pylint: disable=ungrouped-imports
from requests.packages.urllib3.util.ssl_ import (
    create_urllib3_context,
)  # pylint: disable=ungrouped-imports
import six  # pylint: disable=ungrouped-imports

from gsi import transport
from gsi.verification import exceptions

_LOGGER = logging.getLogger(__name__)

_DEFAULT_TIMEOUT = 120  # in seconds

class _Response(transport.Response):
    """Requests transport response adapter.
    Args:
        response (requests.Response): The raw Requests response.
    """

    def __init__(self, response):
        self._response = response

    @property
    def status(self):
        return self._response.status_code

    @property
    def headers(self):
        return self._response.headers

    @property
    def data(self):
        return self._response.content

class Request(transport.Request):
    """Requests request adapter.
    This class is used internally for making requests using various transports
    in a consistent way.
    Args:
        session (requests.Session): An instance :class:`requests.Session` used
            to make HTTP requests. If not specified, a session will be created.
    .. automethod:: __call__
    """

    def __init__(self, session=None):
        if not session:
            session = requests.Session()

        self.session = session

    def __call__(
        self,
        url,
        method="GET",
        body=None,
        headers=None,
        timeout=_DEFAULT_TIMEOUT,
        **kwargs
    ):
        """Make an HTTP request using requests.
        Args:
            url (str): The URI to be requested.
            method (str): The HTTP method to use for the request. Defaults
                to 'GET'.
            body (bytes): The payload / body in HTTP request.
            headers (Mapping[str, str]): Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`~requests.Session.request` method.
        Returns:
            google.transport.Response: The HTTP response.
        Raises:
            google.verification.exceptions.TransportError: If any exception occurred.
        """
        try:
            _LOGGER.debug("Making request: %s %s", method, url)
            response = self.session.request(
                method, url, data=body, headers=headers, timeout=timeout, **kwargs
            )
            return _Response(response)
        except requests.exceptions.RequestException as error:
            new_error = exceptions.TransportError(error)
            six.raise_from(new_error, error)

class CacheRequest(Request):
    """Requests request adapter.
    This class is used internally for making requests using various transports
    in a consistent way while caching responses when possible.
    """
    def __init__(self):
        session = requests.session()
        cached_session = cachecontrol.CacheControl(session)
        super().__init__(session=cached_session)


text:
package okuki.sample.common.network;

import retrofit2.adapter.rxjava.Result;
import rx.Observable;
import rx.functions.Func1;
import timber.log.Timber;

public final class RetroResults {

    private RetroResults() {
        throw new AssertionError("No instances.");
    }

    public static <T> Func1<Result<T>, Observable<T>> handleResult() {
        return result -> {
            if(result.isError()){
                return Observable.error(result.error());
            } else {
                try {
                    return Observable.just(result.response().body());
                } catch (Throwable t){
                    Timber.e(t, "Error handling result");
                    return Observable.error(t);
                }
            }
        };
    }
}


text:
<#
.SYNOPSIS
    Modifies the name, position and/or the dates of a Work Item Iteration.

.PARAMETER Iteration
    ${HelpParam_Iteration}

.PARAMETER NewName
    Specifies the new name of the iteration. Enter only a name, not a path and name. If you enter a path that is different from the path that is specified in the Iteration parameter, Rename-TfsIteration generates an error. To rename and move an item, use the Move-TfsIteration cmdlet.

.PARAMETER MoveBy
    Reorders an iteration by moving it either up or down inside its parent. A positive value moves an iteration down, whereas a negative one moves it up.

.PARAMETER StartDate
    Sets the start date of the iteration. To clear the start date, set it to $null. Note that when clearing a date, both must be cleared at the same time (i.e. setting both StartDate and FinishDate to $null)

.PARAMETER FinishDate
    Sets the finish date of the iteration. To clear the finish date, set it to $null. Note that when clearing a date, both must be cleared at the same time (i.e. setting both StartDate and FinishDate to $null)

.PARAMETER Project
    ${HelpParam_Project}

.PARAMETER Collection
    ${HelpParam_Collection}

.INPUTS
    Microsoft.TeamFoundation.WorkItemTracking.Client.Project
    System.String
#>
Function Set-TfsIteration
{
    [CmdletBinding()]
    [OutputType([Microsoft.TeamFoundation.Server.NodeInfo])]
    Param
    (
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
        [Alias("Path")]
        [ValidateScript({($_ -is [string]) -or ($_ -is [Microsoft.TeamFoundation.Server.NodeInfo])})]
        [object]
        $Iteration = '\**',

        [Parameter()]
        [string]
        $NewName,

        [Parameter()]
        [int]
        $MoveBy,

        [Parameter()]
        [Nullable[DateTime]]
        $StartDate,

        [Parameter()]
        [Nullable[DateTime]]
        $FinishDate,

        [Parameter()]
        [object]
        $Project,

        [Parameter()]
        [object]
        $Collection
    )

    Process
    {
        $node = Get-TfsIteration -Iteration $Iteration -Project $Project -Collection $Collection

        if (-not $node)
        {
            throw "Invalid or non-existent iteration $Iteration"
        }

        $cssService = _GetCssService -Project $Project -Collection $Collection
        $cssService4 = _GetCssService -Project $Project -Collection $Collection -Version 4

        if ($NewName)
        {
            $cssService.RenameNode($node.Uri, $NewName)
        }

        if ($MoveBy)
        {
            $cssService.ReorderNode($node.Uri, $MoveBy)
        }

        if ($StartDate -or $FinishDate)
        {
            if (-not $PSBoundParameters.ContainsKey("StartDate"))
            {
                $StartDate = $node.StartDate
            }

            if (-not $PSBoundParameters.ContainsKey("FinishDate"))
            {
                $FinishDate = $node.FinishDate
            }

            [void]$cssService4.SetIterationDates($node.Uri, $StartDate, $FinishDate)
        }

        return $cssService.GetNode($node.Uri)
    }
}


text:
// Seq Target for NLog - Copyright 2014-2017 Datalust and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using NLog.Common;
using NLog.Config;
using NLog.Layouts;

// ReSharper disable MemberCanBePrivate.Global

namespace NLog.Targets.Seq
{
    /// <summary>
    /// Writes events over HTTP to a Seq server.
    /// </summary>
    [Target("Seq")]
    public sealed class SeqTarget : Target
    {
        Layout _serverUrl;
        Layout _apiKey;
        Layout _proxyAddress;

        Uri _webRequestUri;
        string _headerApiKey;
        HttpClient _httpClient;
        LogLevel _minimumLevel = LogLevel.Trace;

        static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

        /// <summary>
        /// The layout used to format `LogEvent`s as compact JSON.
        /// </summary>
        public JsonLayout TemplatedClefLayout { get; } = new CompactJsonLayout(true);

        /// <summary>
        /// The layout used to format `LogEvent`s as compact JSON.
        /// </summary>
        public JsonLayout TextClefLayout { get; } = new CompactJsonLayout(false);

        /// <summary>
        /// Maximum size allowed for JSON payload sent to Seq-Server. Discards log events that are larger than limit.
        /// </summary>
        public int JsonPayloadMaxLength { get; set; }

        /// <summary>
        /// The address of the Seq server to write to.
        /// </summary>
        [RequiredParameter]
        public string ServerUrl { get => (_serverUrl as SimpleLayout)?.Text; set => _serverUrl = value ?? string.Empty; }

        /// <summary>
        /// A Seq <i>API key</i> that authenticates the client to the Seq server.
        /// </summary>
        public string ApiKey { get => (_apiKey as SimpleLayout)?.Text; set => _apiKey = value ?? string.Empty; }

        /// <summary>
        /// The address of the proxy to use, including port separated by a colon. If not provided, default operating system proxy will be used.
        /// </summary>

        public string ProxyAddress { get => (_proxyAddress as SimpleLayout)?.Text; set => _proxyAddress = value ?? string.Empty; }
        /// <summary>
        /// Use default credentials
        /// </summary>
        public bool UseDefaultCredentials { get; set; }

        /// <summary>
        /// A list of properties that will be attached to the events.
        /// </summary>
        [ArrayParameter(typeof(SeqPropertyItem), "property")]
        public IList<SeqPropertyItem> Properties { get; }

        /// <summary>
        /// How far should the JSON serializer follow object references before backing off
        ///
        /// 0 = Minimal Reflection for only MessageTemplate, 1 = All properties has minimal
        ///  reflection, Higher = Extensive JSON reflection
        /// </summary>
        public int MaxRecursionLimit
        {
            get => TemplatedClefLayout.MaxRecursionLimit;
            set { TemplatedClefLayout.MaxRecursionLimit = value; TextClefLayout.MaxRecursionLimit = value; }
        }

        /// <summary>
        /// Construct a <see cref="SeqTarget"/>.
        /// </summary>
        public SeqTarget()
        {
            Properties = new List<SeqPropertyItem>();
            MaxRecursionLimit = 0;  // Default behavior for Serilog
            OptimizeBufferReuse = true;
            JsonPayloadMaxLength = 128 * 1024;
        }

        /// <summary>
        /// Initializes the target. Can be used by inheriting classes
        /// to initialize logging.
        /// </summary>
        protected override void InitializeTarget()
        {
            foreach (var prop in Properties)
            {
                var attr = new JsonAttribute(prop.Name, prop.Value, prop.AsString);
                TextClefLayout.Attributes.Add(attr);
                TemplatedClefLayout.Attributes.Add(attr);
            }

            if (!string.IsNullOrEmpty(ServerUrl))
            {
                var uri = _serverUrl?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;
                if (!uri.EndsWith("/", StringComparison.InvariantCulture))
                    uri += "/";
                uri += SeqApi.BulkUploadResource;
                _webRequestUri = new Uri(uri);

                _headerApiKey = _apiKey?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;

                HttpClientHandler handler = null;

                var proxyAddress = _proxyAddress?.Render(LogEventInfo.CreateNullEvent()) ?? string.Empty;
                if (!string.IsNullOrEmpty(proxyAddress))
                    handler = new HttpClientHandler { Proxy = new WebProxy(new Uri(proxyAddress), true) };
                if (UseDefaultCredentials)
                {
                    if (handler != null)
                    {
                        handler.UseDefaultCredentials = UseDefaultCredentials;
                    }
                    else
                    {
                        handler = new HttpClientHandler { UseDefaultCredentials = UseDefaultCredentials };
                    }
                }

                _httpClient = handler == null ? new HttpClient() : new HttpClient(handler);
            }

            base.InitializeTarget();
        }

        /// <summary>
        /// Writes an array of logging events to Seq.
        /// </summary>
        /// <param name="logEvents">Logging events to be written.</param>
        protected override void Write(IList<AsyncLogEventInfo> logEvents)
        {
            try
            {
                PostBatch(logEvents).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                InternalLogger.Error(ex, "Seq(Name={0}): Failed sending LogEvents. Uri={1}", Name, _webRequestUri);
                if (LogManager.ThrowExceptions)
                    throw;

                for (var i = 0; i < logEvents.Count; ++i)
                    logEvents[i].Continuation(ex);
            }
        }

        /// <summary>
        /// Writes logging event to Seq.
        /// </summary>
        /// <param name="logEvent">Logging event to be written.</param>
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            try
            {
                PostBatch(new[] { logEvent }).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                InternalLogger.Error(ex, "Seq(Name={0}): Failed sending LogEvents. Uri={1}", Name, _webRequestUri);
                if (LogManager.ThrowExceptions)
                    throw;

                logEvent.Continuation(ex);
            }
        }

        async Task PostBatch(IList<AsyncLogEventInfo> logEvents)
        {
            if (_webRequestUri == null)
                return;

            var request = new HttpRequestMessage(HttpMethod.Post, _webRequestUri);
            if (!string.IsNullOrWhiteSpace(_headerApiKey))
                request.Headers.Add(SeqApi.ApiKeyHeaderName, _headerApiKey);

            List<AsyncLogEventInfo> extraBatch = null;
            var totalPayload = 0;
            var payload = new StringBuilder();

            for (var i = 0; i < logEvents.Count; ++i)
            {
                var evt = logEvents[i].LogEvent;

                if (evt.Level < _minimumLevel)
                    continue;

                var json = RenderCompactJsonLine(evt);

                if (JsonPayloadMaxLength > 0)
                {
                    if (json.Length > JsonPayloadMaxLength)
                    {
                        InternalLogger.Warn("Seq(Name={0}): Event JSON representation exceeds the char limit: {1} > {2}", Name, json.Length, JsonPayloadMaxLength);
                        continue;
                    }
                    if (totalPayload + json.Length > JsonPayloadMaxLength)
                    {
                        extraBatch = new List<AsyncLogEventInfo>(logEvents.Count - i);
                        for (; i < logEvents.Count; ++i)
                            extraBatch.Add(logEvents[i]);
                        break;
                    }
                }

                totalPayload += json.Length;
                payload.AppendLine(json);
            }

            request.Content = new StringContent(payload.ToString(), Utf8, SeqApi.CompactLogEventFormatMediaType);

            // Even if no events are above `_minimumLevel`, we'll send a batch to make sure we observe minimum
            // level changes sent by the server.

            using (var response = await _httpClient.SendAsync(request).ConfigureAwait(false))
            {
                if ((int)response.StatusCode > 299)
                {
                    var data = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    throw new WebException($"Received failed response {response.StatusCode} from Seq server: {data}");
                }

                if ((int)response.StatusCode == (int)HttpStatusCode.Created)
                {
                    var data = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var serverRequestedLevel = LevelMapping.ToNLogLevel(SeqApi.ReadMinimumAcceptedLevel(data));
                    if (serverRequestedLevel != _minimumLevel)
                    {
                        InternalLogger.Info("Seq(Name={0}): Setting minimum log level to {1} per server request", Name, serverRequestedLevel);
                        _minimumLevel = serverRequestedLevel;
                    }
                }
            }

            var completedCount = logEvents.Count - (extraBatch?.Count ?? 0);
            for (var i = 0; i < completedCount; ++i)
                logEvents[i].Continuation(null);

            if (extraBatch != null)
            {
                await PostBatch(extraBatch).ConfigureAwait(false);
            }
        }

        internal string RenderCompactJsonLine(LogEventInfo evt)
        {
            var hasProperties = evt.HasProperties && evt.Properties.Count > 0;
            var json = RenderLogEvent(hasProperties ? TemplatedClefLayout : TextClefLayout, evt);
            return json;
        }

        internal void TestInitialize()
        {
            InitializeTarget();
        }

        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
                _httpClient?.Dispose();
            base.Dispose(disposing);
        }
    }
}


text:
#include "tensorflow_serving/servables/tensorflow/session_bundle_factory.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "google/protobuf/wrappers.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow_serving/resources/resource_values.h"
#include "tensorflow_serving/servables/tensorflow/session_bundle_config.pb.h"
#include "tensorflow_serving/session_bundle/session_bundle.h"
#include "tensorflow_serving/test_util/test_util.h"

namespace tensorflow {
namespace serving {
namespace {

using test_util::EqualsProto;

class SessionBundleFactoryTest : public ::testing::Test {
 protected:
  SessionBundleFactoryTest()
      : export_dir_(test_util::TestSrcDirPath(
            "session_bundle/example/half_plus_two/00000123")) {}

  // Test data path, to be initialized to point at an export of half-plus-two.
  const string export_dir_;

  // Test that a SessionBundle handles a single request for the half plus two
  // model properly. The request has size=2, for batching purposes.
  void TestSingleRequest(SessionBundle* bundle) {
    Tensor input = test::AsTensor<float>({100.0f, 42.0f}, {2});
    // half plus two: output should be input / 2 + 2.
    Tensor expected_output =
        test::AsTensor<float>({100.0f / 2 + 2, 42.0f / 2 + 2}, {2});

    // Note that "x" and "y" are the actual names of the nodes in the graph.
    // The saved manifest binds these to "input" and "output" respectively, but
    // these tests are focused on the raw underlying session without bindings.
    const std::vector<std::pair<string, Tensor>> inputs = {{"x", input}};
    const std::vector<string> output_names = {"y"};
    const std::vector<string> empty_targets;
    std::vector<Tensor> outputs;

    TF_ASSERT_OK(
        bundle->session->Run(inputs, output_names, empty_targets, &outputs));

    ASSERT_EQ(1, outputs.size());
    const auto& single_output = outputs.at(0);
    test::ExpectTensorEqual<float>(expected_output, single_output);
  }
};

TEST_F(SessionBundleFactoryTest, Basic) {
  const SessionBundleConfig config;
  std::unique_ptr<SessionBundleFactory> factory;
  TF_ASSERT_OK(SessionBundleFactory::Create(config, &factory));
  std::unique_ptr<SessionBundle> bundle;
  TF_ASSERT_OK(factory->CreateSessionBundle(export_dir_, &bundle));
  TestSingleRequest(bundle.get());
}

TEST_F(SessionBundleFactoryTest, Batching) {
  SessionBundleConfig config;
  BatchingParameters* batching_params = config.mutable_batching_parameters();
  batching_params->mutable_max_batch_size()->set_value(2);
  batching_params->mutable_max_time_micros()->set_value(
      10 * 1000 * 1000 /* 10 seconds (should be plenty of time) */);
  std::unique_ptr<SessionBundleFactory> factory;
  TF_ASSERT_OK(SessionBundleFactory::Create(config, &factory));
  std::unique_ptr<SessionBundle> bundle;
  TF_ASSERT_OK(factory->CreateSessionBundle(export_dir_, &bundle));
  SessionBundle* bundle_raw = bundle.get();

  // Run multiple requests concurrently. They should be executed as
  // 'kNumRequestsToTest/2' batches.
  {
    const int kNumRequestsToTest = 10;
    std::vector<std::unique_ptr<Thread>> request_threads;
    for (int i = 0; i < kNumRequestsToTest; ++i) {
      request_threads.push_back(
          std::unique_ptr<Thread>(Env::Default()->StartThread(
              ThreadOptions(), strings::StrCat("thread_", i),
              [this, bundle_raw] { this->TestSingleRequest(bundle_raw); })));
    }
  }
}

TEST_F(SessionBundleFactoryTest, BatchingConfigError) {
  SessionBundleConfig config;
  BatchingParameters* batching_params = config.mutable_batching_parameters();
  batching_params->mutable_max_batch_size()->set_value(2);
  // The last entry in 'allowed_batch_sizes' is supposed to equal
  // 'max_batch_size'. Let's violate that constraint and ensure we get an error.
  batching_params->add_allowed_batch_sizes(1);
  batching_params->add_allowed_batch_sizes(3);
  std::unique_ptr<SessionBundleFactory> factory;
  EXPECT_FALSE(SessionBundleFactory::Create(config, &factory).ok());
}

TEST_F(SessionBundleFactoryTest, EstimateResourceRequirementWithBadExport) {
  const SessionBundleConfig config;
  std::unique_ptr<SessionBundleFactory> factory;
  TF_ASSERT_OK(SessionBundleFactory::Create(config, &factory));
  ResourceAllocation resource_requirement;
  const Status status = factory->EstimateResourceRequirement(
      "/a/bogus/export/dir", &resource_requirement);
  EXPECT_FALSE(status.ok());
}

TEST_F(SessionBundleFactoryTest, EstimateResourceRequirementWithGoodExport) {
  const uint64 kVariableFileSize = 169;
  const uint64 expected_ram_requirement =
      kVariableFileSize * SessionBundleFactory::kResourceEstimateRAMMultiplier +
      SessionBundleFactory::kResourceEstimateRAMPadBytes;
  ResourceAllocation want;
  ResourceAllocation::Entry* ram_entry = want.add_resource_quantities();
  Resource* ram_resource = ram_entry->mutable_resource();
  ram_resource->set_device(device_types::kMain);
  ram_resource->set_kind(resource_kinds::kRamBytes);
  ram_entry->set_quantity(expected_ram_requirement);

  const SessionBundleConfig config;
  std::unique_ptr<SessionBundleFactory> factory;
  TF_ASSERT_OK(SessionBundleFactory::Create(config, &factory));
  ResourceAllocation got;
  TF_ASSERT_OK(factory->EstimateResourceRequirement(export_dir_, &got));

  EXPECT_THAT(got, EqualsProto(want));
}

}  // namespace
}  // namespace serving
}  // namespace tensorflow


text:
class "Particle" {
  p = nil;
  active = true;
  lifetime = 0;
  maxLifetime = 0.5;
}

function Particle:__init(x, y, r, g, b, lifetime)
  self.posx = x
  self.posy = y
  self.maxLifetime = lifetime
  local id = love.image.newImageData(32, 32)
  for x = 0, 31 do
    for y = 0, 31 do
      local gradient = 1 - ((x-15)^2+(y-15)^2)/40
      id:setPixel(x, y, r, g, b, 255*(gradient<0 and 0 or gradient))
    end
  end

  local i = love.graphics.newImage(id)
  --local i = love.graphics.newImage("gfx/particle.png")

  self.p = love.graphics.newParticleSystem(i, 256)
  self.p:setEmissionRate          (50)
  self.p:setParticleLifetime      (2)
  self.p:setPosition              (0, 0)
  if lifetime < 1.0 then
    self.p:setDirection             (math.pi * 0.5)
		self.p:setSpread                (2)
	elseif lifetime > 100.0 then
    self.p:setDirection             (math.pi * 1.0)
		self.p:setSpread                (20)
  else
    self.p:setDirection             (math.pi * 2.0)
		self.p:setSpread                (2)
  end
  self.p:setSpeed                 (10, 20)
  self.p:setRadialAcceleration    (10)
  self.p:setTangentialAcceleration(10)
  self.p:setSizes                 (0.1, 2)
  self.p:setSizeVariation         (0.5)
  self.p:setRotation              (0)
  self.p:setSpin                  (math.pi)
  self.p:setSpinVariation         (0)
  self.p:setColors                (200, 200, 255, 240, 255, 255, 255, 10)
  self.p:stop();
end

function Particle:update(dt)
  if self.active then
    self.p:start()
    self.p:update(dt)
    self.lifetime = self.lifetime + dt
    if self.lifetime > self.maxLifetime then
      self.active = false
    end
  end
end

function Particle:draw()
  if self.active then
    love.graphics.draw(self.p, self.posx, self.posy)
  end
end

function Particle:drawAt(x, y)
  if self.active then
    love.graphics.draw(self.p, x, y)
  end
end

function Particle:setPosition(x, y)
  self.posx = x
  self.posy = y
end

function Particle:translate(x, y)
  self.posx = self.posx + x
  self.posy = self.posy + y
end

function Particle:stop()
  self.p:stop()
  self.active = false
end

function Particle:reset()
  self.p:reset()
  self.active = true
  self.lifetime = 0
end

function Particle:start()
  self.active = true
end

function Particle:isActive()
  return self.active
end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PdfReportWriter.cs" company="OxyPlot">
//   Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
//   Provides a report writer for portable document format using MigraDoc.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace OxyPlot.Pdf
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    using MigraDoc.DocumentObjectModel;
    using MigraDoc.Rendering;

    using OxyPlot.Reporting;

    using Paragraph = MigraDoc.DocumentObjectModel.Paragraph;

    /// <summary>
    /// Provides a report writer for portable document format using MigraDoc.
    /// </summary>
    public class PdfReportWriter : IDisposable, IReportWriter
    {
        /// <summary>
        /// List of plot files created during report generation.
        /// </summary>
        private readonly List<string> temporaryPlotFiles = new List<string>();

        /// <summary>
        /// The current section.
        /// </summary>
        private Section currentSection;

        /// <summary>
        /// The disposed flag.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Flag if the document has been closed.
        /// </summary>
        private bool isClosed;

        /// <summary>
        /// The style.
        /// </summary>
        private ReportStyle style;

        /// <summary>
        /// Initializes a new instance of the <see cref="PdfReportWriter" /> class.
        /// </summary>
        /// <param name="filename">The FileName.</param>
        public PdfReportWriter(string filename)
            : this(File.Create(filename))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PdfReportWriter" /> class.
        /// </summary>
        /// <param name="output">The output <see cref="Stream" />.</param>
        public PdfReportWriter(Stream output)
        {
            this.Output = output;
            this.Document = new Document();
        }

        /// <summary>
        /// Gets or sets the pdf document.
        /// </summary>
        protected Document Document { get; set; }

        /// <summary>
        /// Gets the output stream.
        /// </summary>
        protected Stream Output { get; private set; }

        /// <summary>
        /// Gets the current section.
        /// </summary>
        private Section CurrentSection
        {
            get
            {
                return this.currentSection ?? (this.currentSection = this.Document.AddSection());
            }
        }

        /// <summary>
        /// Defines the styles used in the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="reportStyle">The report Style.</param>
        public static void DefineStyles(Document document, ReportStyle reportStyle)
        {
            SetStyle(document.Styles["Normal"], reportStyle.BodyTextStyle);

            // Heading1 to Heading9 are predefined styles with an outline level. An outline level
            // other than OutlineLevel.BodyText automatically creates the outline (or bookmarks)
            // in PDF.
            for (int i = 0; i < reportStyle.HeaderStyles.Length; i++)
            {
                SetStyle(document.Styles["Heading" + (i + 1)], reportStyle.HeaderStyles[i]);
            }

            // style = document.Styles[StyleNames.Header];
            // style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);

            // style = document.Styles[StyleNames.Footer];
            // style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
            var style = document.Styles.AddStyle("TableHeader", "Normal");
            SetStyle(style, reportStyle.TableHeaderStyle);

            style = document.Styles.AddStyle("TableCaption", "Normal");
            SetStyle(style, reportStyle.TableCaptionStyle);

            style = document.Styles.AddStyle("TableText", "Normal");
            SetStyle(style, reportStyle.TableTextStyle);

            style = document.Styles.AddStyle("FigureText", "Normal");
            SetStyle(style, reportStyle.FigureTextStyle);
        }

        /// <summary>
        /// Closes this instance.
        /// </summary>
        public virtual void Close()
        {
            if (this.isClosed)
            {
                return;
            }

            var r = new PdfDocumentRenderer { Document = this.Document };
            r.RenderDocument();
            r.PdfDocument.Save(this.Output);
            this.CleanTemporaryPlotFiles();
            this.Output.Close();
            this.isClosed = true;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Writes the specified drawing.
        /// </summary>
        /// <param name="d">The drawing.</param>
        void IReportWriter.WriteDrawing(DrawingFigure d)
        {
            var p = this.WriteStartFigure(d);
            this.CurrentSection.AddParagraph("Drawings are not implemented.");
            this.WriteEndFigure(d, p);
        }

        /// <summary>
        /// Writes the specified equation.
        /// </summary>
        /// <param name="equation">The equation.</param>
        void IReportWriter.WriteEquation(Equation equation)
        {
            var p = this.CurrentSection.AddParagraph();
            p.AddText("Equations are not supported.");
        }

        /// <summary>
        /// Writes the specified header.
        /// </summary>
        /// <param name="h">The header.</param>
        void IReportWriter.WriteHeader(Header h)
        {
            if (h.Text == null)
            {
                return;
            }

            if (h.Level == 1)
            {
                this.currentSection = null;
            }

            this.CurrentSection.AddParagraph(h.Text, "Heading" + h.Level);
        }

        /// <summary>
        /// Writes the specified image.
        /// </summary>
        /// <param name="i">The image.</param>
        void IReportWriter.WriteImage(Image i)
        {
            var p = this.WriteStartFigure(i);
            if (i.Source != null)
            {
                MigraDoc.DocumentObjectModel.Shapes.Image pi = p.AddImage(Path.GetFullPath(i.Source));
                pi.Width = Unit.FromCentimeter(15);
            }

            this.WriteEndFigure(i, p);
        }

        /// <summary>
        /// Writes the specified paragraph.
        /// </summary>
        /// <param name="p">The paragraph.</param>
        void IReportWriter.WriteParagraph(Reporting.Paragraph p)
        {
            this.CurrentSection.AddParagraph(p.Text ?? string.Empty);
        }

        /// <summary>
        /// Writes the specified plot.
        /// </summary>
        /// <param name="plot">The plot.</param>
        void IReportWriter.WritePlot(PlotFigure plot)
        {
            var temporaryPlotFileName = Guid.NewGuid() + ".pdf";
            this.temporaryPlotFiles.Add(temporaryPlotFileName);
            PdfExporter.Export(plot.PlotModel, temporaryPlotFileName, plot.Width, plot.Height);

            var p = this.WriteStartFigure(plot);
            MigraDoc.DocumentObjectModel.Shapes.Image pi = p.AddImage(temporaryPlotFileName);
            pi.Width = Unit.FromCentimeter(15);

            this.WriteEndFigure(plot, p);
        }

        /// <summary>
        /// Writes the specified report.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="reportStyle">The report style.</param>
        public void WriteReport(Report report, ReportStyle reportStyle)
        {
            this.style = reportStyle;
            DefineStyles(this.Document, reportStyle);
            report.Write(this);
        }

        /// <summary>
        /// Writes the specified table.
        /// </summary>
        /// <param name="table">The table.</param>
        void IReportWriter.WriteTable(Table table)
        {
            if (table.Rows == null)
            {
                return;
            }

            var pdfTable = new MigraDoc.DocumentObjectModel.Tables.Table
                {
                    Borders = { Width = 0.25, Left = { Width = 0.5 }, Right = { Width = 0.5 } },
                    Rows = { LeftIndent = 0 }
                };

            //// pdfTable.Style = "Table";
            //// pdfTable.Borders.Color = TableBorder;

            int columns = table.Columns.Count;

            for (int j = 0; j < columns; j++)
            {
                var pdfColumn = pdfTable.AddColumn();

                // todo: the widths are not working
                //// pdfColumn.Width = Unit.FromMillimeter(table.Columns[j].ActualWidth);
                pdfColumn.Format.Alignment = ConvertToParagraphAlignment(table.Columns[j].Alignment);
            }

            foreach (var tr in table.Rows)
            {
                var pdfRow = pdfTable.AddRow();
                for (int j = 0; j < columns; j++)
                {
                    bool isHeader = tr.IsHeader || table.Columns[j].IsHeader;

                    var c = tr.Cells[j];
                    var pdfCell = pdfRow.Cells[j];
                    pdfCell.AddParagraph(c.Content ?? string.Empty);
                    pdfCell.Style = isHeader ? "TableHeader" : "TableText";
                    pdfCell.Format.Alignment = ConvertToParagraphAlignment(table.Columns[j].Alignment);
                }
            }

            // table.SetEdge(0, 0, t.Columns.Count, t.Items.Count(), Edge.Box, BorderStyle.Single, 1.5, Colors.Black);
            if (table.Caption != null)
            {
                var pa = this.CurrentSection.AddParagraph();
                pa.AddFormattedText(table.GetFullCaption(this.style), "TableCaption");
            }

            this.CurrentSection.Add(pdfTable);
        }

        /// <summary>
        /// Writes the start of a figure.
        /// </summary>
        /// <param name="f">The figure.</param>
        /// <returns>A paragraph</returns>
        protected Paragraph WriteStartFigure(Figure f)
        {
            return this.CurrentSection.AddParagraph();
        }

        /// <summary>
        /// Writes the figure text.
        /// </summary>
        /// <param name="f">The f.</param>
        /// <param name="pa">The paragraph.</param>
        protected void WriteEndFigure(Figure f, Paragraph pa)
        {
            if (f.FigureText == null)
            {
                return;
            }

            pa.AddLineBreak();
            pa.AddFormattedText(f.GetFullCaption(this.style), "FigureText");
        }

        /// <summary>
        /// Converts paragraph alignment.
        /// </summary>
        /// <param name="alignment">The alignment.</param>
        /// <returns>The pdf alignment.</returns>
        private static ParagraphAlignment ConvertToParagraphAlignment(Alignment alignment)
        {
            switch (alignment)
            {
                case Alignment.Left:
                    return ParagraphAlignment.Left;
                case Alignment.Center:
                    return ParagraphAlignment.Center;
                case Alignment.Right:
                    return ParagraphAlignment.Right;
                default:
                    return ParagraphAlignment.Justify;
            }
        }

        /// <summary>
        /// Sets a paragraph style.
        /// </summary>
        /// <param name="style">The style.</param>
        /// <param name="ps">The ps.</param>
        private static void SetStyle(Style style, ParagraphStyle ps)
        {
            style.Font.Name = ps.FontFamily;
            style.Font.Size = Unit.FromPoint(ps.FontSize);
            style.Font.Bold = ps.Bold;
            style.Font.Italic = ps.Italic;
            style.Font.Color = ToMigraDocColor(ps.TextColor);
            style.ParagraphFormat.PageBreakBefore = ps.PageBreakBefore;
            style.ParagraphFormat.LeftIndent = Unit.FromPoint(ps.LeftIndentation);
            style.ParagraphFormat.RightIndent = Unit.FromPoint(ps.RightIndentation);
            style.ParagraphFormat.LineSpacing = Unit.FromPoint(ps.LineSpacing);
            style.ParagraphFormat.SpaceBefore = Unit.FromPoint(ps.SpacingBefore);
            style.ParagraphFormat.SpaceAfter = Unit.FromPoint(ps.SpacingAfter);
        }

        /// <summary>
        /// Converts an OxyColor to a migra doc color.
        /// </summary>
        /// <param name="c">The color.</param>
        /// <returns>The converted color.</returns>
        private static Color ToMigraDocColor(OxyColor c)
        {
            return new Color(c.A, c.R, c.G, c.B);
        }

        /// <summary>
        /// Erases the temporary plot files.
        /// </summary>
        private void CleanTemporaryPlotFiles()
        {
            foreach (var fileName in this.temporaryPlotFiles)
            {
                File.Delete(fileName);
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.Close();
                }
            }

            this.disposed = true;
        }
    }
}


text:
make tsv file from csv.
like this.
![sample image](/sample_tsv.png)

# setting & usage

    npm install -g cssfmt
    git clone git@github.com:akyao/css-tools.git
    cd css-tools
    cat sample.css | cssfmt | python css2tsv.py > sample.tsv


text:
var vows = require('vows');
var assert = require('assert');
var util = require('util');
var PicplzStrategy = require('passport-picplz/strategy');

vows.describe('PicplzStrategy').addBatch({

  'strategy': {
    topic: function() {
      return new PicplzStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});
    },

    'should be named picplz': function (strategy) {
      assert.equal(strategy.name, 'picplz');
    },
  },

  'strategy when loading user profile': {
    topic: function() {
      var strategy = new PicplzStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        var body = '{ "result": "ok", "value": { "users": [ { "username": "waterbuffalo", "display_name": "Waterbuffalo", "following_count": 36, "follower_count": 139, "id": 1908, "icon": { "url": "http://a2.picplzthumbs.com/i/FwCNRNyPZJGlqJMyQXwM2wgQ_k4.png", "width": 100, "height": 100 } } ] } }';

        callback(null, body, undefined);
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'picplz');
        assert.equal(profile.id, '1908');
        assert.equal(profile.username, 'waterbuffalo');
        assert.equal(profile.displayName, 'Waterbuffalo');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile and encountering an error': {
    topic: function() {
      var strategy = new PicplzStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        callback(new Error('something-went-wrong'));
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should error' : function(err, req) {
        assert.isNotNull(err);
      },
      'should wrap error in InternalOAuthError' : function(err, req) {
        assert.equal(err.constructor.name, 'InternalOAuthError');
      },
      'should not load profile' : function(err, profile) {
        assert.isUndefined(profile);
      },
    },
  },

}).export(module);


text:
package com.nesscomputing.config;

import java.io.IOException;
import java.net.URI;

import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

import com.google.common.io.Resources;
import com.nesscomputing.config.util.LocalHttpService;
import com.nesscomputing.config.util.PropertiesSaver;
import com.nesscomputing.testing.lessio.AllowNetworkAccess;

@AllowNetworkAccess(endpoints={"127.0.0.1:*"})
public class TestHttpsConfig extends AbstractTestConfig
{
    private LocalHttpService localHttpService = null;

    public static final String USER_LOGIN ="verysecret";
    public static final String USER_PW = "evenmoresecret";

    private PropertiesSaver ps = null;

    @Before
    public void setUp() throws Exception
    {
        final ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setBaseResource(Resource.newClassPathResource("/"));
        localHttpService =  LocalHttpService.forSecureSSLHandler(resourceHandler, USER_LOGIN, USER_PW);
        localHttpService.start();

        ps = new PropertiesSaver("config.login", "config.password", "config.ssl.truststore", "config.ssl.truststore.password");

        System.setProperty("config.login", USER_LOGIN);
        System.setProperty("config.password", USER_PW);
        System.setProperty("config.ssl.truststore", Resources.getResource(this.getClass(), "/test-client-keystore.jks").toString());
        System.setProperty("config.ssl.truststore.password", "changeit");

        final URI baseUri = new URI("https", null, localHttpService.getHost(), localHttpService.getPort(), null, null, null);

        cfg = Config.getConfig(baseUri.resolve("/test-config/basic"), "values");
        cfg2 = Config.getConfig(baseUri.resolve("/test-config/basic-legacy"), "values");
    }

    @After
    public void shutdownJetty() throws IOException
    {
        localHttpService.stop();
        localHttpService = null;

        Assert.assertNotNull(ps);
        ps.apply();
        ps = null;
    }
}


text:
using HFEA.Connector.Contracts.CaFC;
using HFEA.Web.ViewModel.CaFC.Model;
using HFEA.Web.ViewModel.Constants;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HFEA.BL.ModelCreators
{
    public class BaseCaFCModelCreator
    {
        private Dictionary<string, CaFCConstants.ComparableToAverage> StatsCompareDictionary = new Dictionary<string, CaFCConstants.ComparableToAverage>()
        {
            { "Consistent with" , CaFCConstants.ComparableToAverage.Consistent },
            { "Above", CaFCConstants.ComparableToAverage.Above },
            { "Below", CaFCConstants.ComparableToAverage.Below }
        };

        protected StatisticsItem GetStatisticsItem(int nationalRate, int clinicRate, int minInterval, int maxInterval, string compareToAvg, int count, string caveat)
        {
            var result = new StatisticsItem()
            {
                Count = count,
                ClinicRate = clinicRate,
                NationalAverage = nationalRate,
                CompareToAverageString = compareToAvg,
                ReliabilityRangeMin = minInterval,
                ReliabilityRangeMax = maxInterval,
                CaveatText = caveat
            };

            if (result.ClinicRate == 0 && result.NationalAverage == 0 && (result.ReliabilityRangeMin == 0 && result.ReliabilityRangeMax == 0))
            {
                result.HideStatItem = true;
            }

            if (!string.IsNullOrEmpty(compareToAvg) && this.StatsCompareDictionary.ContainsKey(compareToAvg))
            {
                result.CompareToAverage = this.StatsCompareDictionary[compareToAvg];
            }

            return result;
        }

        protected List<string> GetAddressLines(MainAddress address)
        {
            if (address != null)
            {
                var addressList = new List<string>()
                    {
                        address.SubDwelling,
                        string.Format("{0} {1}", address.NumberName, address.Street).Trim(),
                        address.Locality,
                        address.Town,
                        address.County,
                        address.Postcode
                    };

                return addressList.Where(x => !string.IsNullOrEmpty(x)).ToList();
            }

            return null;
        }

        protected List<SatelliteClinicInfo> GetAssociatedClinicInfoList(IEnumerable<Link> linkList)
        {
            List<SatelliteClinicInfo> result = null;

            if (linkList != null && linkList.Any())
            {
                result = linkList.Select(x => new SatelliteClinicInfo()
                {
                    CentreName = x.LinkCentreName,
                    AddressLinesList = this.GetAddressLines(x.LinkCentreAddress),
                    CentrePhoneList = this.GetListOfLinesOrNull(x.LinkCentrePhone)
                }).ToList();
            }

            return result;
        }

        protected List<string> GetListOfLinesOrNull(string input)
        {
            List<string> result = null;

            if (!string.IsNullOrEmpty(input))
            {
                result = input
                    .Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)
                    .ToList();
            }

            return result;
        }

        protected List<OpenTimeItem> GetOpeningTimesList(List<OpeningTime> dayList)
        {
            List<OpenTimeItem> result = new List<OpenTimeItem>();

            if (dayList != null)
            {
                var monday = dayList.FirstOrDefault(x => x.Day == DayOfWeek.Monday);
                bool isSameMondayToFriday = monday != null
                    && dayList.Where(x => x.Day > DayOfWeek.Monday && x.Day <= DayOfWeek.Friday)
                           .All(x => x.IsOpened == monday.IsOpened
                                    && x.OpenTime == monday.OpenTime
                                    && x.CloseTime == monday.CloseTime);

                if (isSameMondayToFriday)
                {
                    dayList = dayList
                        .Where(x => x.Day == DayOfWeek.Monday || x.Day == DayOfWeek.Saturday || x.Day == DayOfWeek.Sunday)
                        .ToList();
                }

                foreach (OpeningTime day in dayList)
                {
                    result.Add(new OpenTimeItem()
                    {
                        IsOpened = day.IsOpened,
                        OpenTime = day.OpenTime,
                        CloseTime = day.CloseTime,
                        FromDay = day.Day,
                        ToDay = isSameMondayToFriday && day.Day == DayOfWeek.Monday
                                    ? DayOfWeek.Friday
                                    : day.Day
                    });
                }

                // Sort list Monday to Sunday
                result = result
                    .OrderBy(x => x.FromDay == DayOfWeek.Sunday)
                    .ThenBy(x => x.FromDay)
                    .ToList();
            }

            return result;
        }
    }
}


text:
package com.almende.dialog;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jongo.Aggregate;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.jongo.MongoCursor;
import org.jongo.marshall.jackson.JacksonMapper;
import com.almende.dialog.accounts.AdapterConfig;
import com.almende.dialog.model.Session;
import com.almende.dialog.model.ddr.DDRRecord;
import com.almende.dialog.util.ServerUtils;
import com.almende.util.ParallelInit;
import com.askfast.commons.intf.LoggerAgentInterface;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.mongodb.DB;

public class Logger {

    private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(Logger.class.getName());
    private static final int adapter_chunk_size = 20;

    public Logger() {
    }

    public void severe(String adapterID, String message, String ddrRecordId, String sessionKey) {

        severe(adapterID, null, message, ddrRecordId, sessionKey);
    }

    public void severe(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) {

        this.log(LogLevel.SEVERE, adapterID, adapterType, message, ddrRecordId, sessionKey);
    }

    public void severe(AdapterConfig adapter, String message, Session session) {

        this.log(LogLevel.SEVERE, adapter, message, session);
    }

    public void warning(String adapterID, String message, String ddrRecordId, String sessionKey) {

        warning(adapterID, null, message, ddrRecordId, sessionKey);
    }

    public void warning(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) {

        this.log(LogLevel.WARNING, adapterID, adapterType, message, ddrRecordId, sessionKey);
    }

    public void warning(AdapterConfig adapter, String message, Session session) {

        this.log(LogLevel.WARNING, adapter, message, session);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapterID
     * @param message
     * @param ddrRecordId
     * @param sessionKey
     */
    public void info(String adapterID, String message, String ddrRecordId, String sessionKey) {

        info(adapterID, null, message, ddrRecordId, sessionKey);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapterID
     * @param adapterType
     * @param message
     * @param ddrRecordId
     * @param sessionKey
     */
    public void info(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) {

        this.log(LogLevel.INFO, adapterID, adapterType, message, ddrRecordId, sessionKey);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapter
     * @param message
     * @param session
     */
    public void info(AdapterConfig adapter, String message, Session session) {

        this.log(LogLevel.INFO, adapter, message, session);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapter
     * @param ddrRecord
     * @param session
     */
    public void ddr(AdapterConfig adapter, DDRRecord ddrRecord, Session session) {

        this.log(LogLevel.DDR, adapter, ServerUtils.serializeWithoutException(ddrRecord), session);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapterID
     * @param message
     * @param ddrRecordId
     * @param sessionKey
     */
    public void debug(String adapterID, String message, String ddrRecordId, String sessionKey) {

        debug(adapterID, null, message, ddrRecordId, sessionKey);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapterID
     * @param adapterType
     * @param message
     * @param ddrRecordId
     * @param sessionKey
     */
    public void debug(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) {

        this.log(LogLevel.DEBUG, adapterID, adapterType, message, ddrRecordId, sessionKey);
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param adapter
     * @param message
     * @param session
     */
    public void debug(AdapterConfig adapter, String message, Session session) {

        this.log(LogLevel.DEBUG, adapter, message, session);
    }

    /**
     * Logs something only if a session and a trackingToken is found
     * corresponding to the sessionKey
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is used to log HTTP requests.
     * @param level
     * @param adapterId
     * @param adapterType
     * @param message
     * @param ddrRecordId
     * @param sessionKey
     */
    public void log(LogLevel level, String adapterId, String adapterType, String message, String ddrRecordId,
        String sessionKey) {

        if (sessionKey != null && (LogLevel.SEVERE.equals(level) || LogLevel.WARNING.equals(level))) {

            Log devLog = new Log(level, adapterId, adapterType, message, ddrRecordId, sessionKey);
            if (devLog.getSessionKey() != null) {
                MongoCollection collection = getCollection();
                collection.insert(devLog);
            }
        }
    }

    /**
     * @deprecated As the new {@link LoggerAgentInterface} microservice agent is
     *             used to log HTTP requests. Logs something only if a session
     *             and a trackingToken is found in the session
     * @param level
     * @param adapter
     * @param message
     * @param session
     */
    public void log(LogLevel level, AdapterConfig adapter, String message, Session session) {

        if (session != null && (LogLevel.SEVERE.equals(level) || LogLevel.WARNING.equals(level))) {

            MongoCollection collection = getCollection();
            Log devLog = new Log(level, adapter, message, session);
            collection.insert(devLog);
        }
    }

    /**
     * Updates this log in the mongo database
     * @param devLog
     */
    public static void save(Log devLog) {

        MongoCollection collection = getCollection();
        collection.save(devLog);
    }

    /**
     * Returns all the logs that match to the given parameters. AccountId is a
     * mandatory field. This is an expensive step as it fetches the logs in 2
     * steps: first loads all the trackingTokens by descending timestamp. Then
     * fetches all the logs corresponding to this tracking token in batches, so
     * that related tracking token are grouped together
     *
     * @param accountId AccountId is a mandatory field
     * @param ddrRecordID returns only those logs that has this ddrRecordId
     * @param adapters
     * @param levels
     * @param adapterType
     * @param endTime
     * @param offset
     * @param limit
     * @return
     */
    public static List<Log> find(String accountId, String ddrRecordID, Collection<String> adapters, Collection<LogLevel> levels,
        String adapterType, Long endTime, Integer offset, Integer limit) {

        List<Log> resultLogs = new ArrayList<Log>();
        try {
            if (adapters != null && !adapters.isEmpty()) {
                log.info(String.format("Initial adapters size %s", adapters.size()));
                int startingIndex = 0;
                int endIndex = adapters.size() <= adapter_chunk_size ? adapters.size() : adapter_chunk_size;
                for (int chunkCount = 0; chunkCount <= (adapters.size() / adapter_chunk_size); chunkCount++) {
                    log.info(String.format("chunkCount %s startIndex: %s endIndex %s", chunkCount, startingIndex,
                                           endIndex));
                    List<String> chunkedAdapters = new ArrayList<String>(adapters).subList(startingIndex, endIndex);
                    List<Log> logsWithLimit = getLogsWithLimit(accountId, ddrRecordID, chunkedAdapters, levels,
                        adapterType, endTime, offset, limit);
                    if (logsWithLimit != null && !logsWithLimit.isEmpty()) {
                        resultLogs.addAll(logsWithLimit);
                    }
                    //update indexes
                    startingIndex = startingIndex + adapter_chunk_size;
                    endIndex = adapters.size() >= endIndex + adapter_chunk_size ? endIndex + adapter_chunk_size
                                                                               : adapters.size();
                }
            }
            else {
                resultLogs = getLogsWithLimit(accountId, ddrRecordID, adapters, levels, adapterType, endTime, offset,
                    limit);
            }
        }
        catch (Exception e) {
            log.severe("Exception seen while trying to fetch logs. Message: " + e.getMessage());
        }
        return resultLogs;
    }

    /**
     * Fetches all the logs in the mongoDb.
     * @return
     */
    public static List<Log> findAllLogs() {

        ArrayList<Log> result = new ArrayList<Log>();
        MongoCollection collection = getCollection();
        MongoCursor<Log> logCursor = collection.find().as(Log.class);
        while (logCursor.hasNext()) {
            result.add(logCursor.next());
        }
        return result;
    }

    /**
     * fetches the logs based on the initial {@link Logger#adapter_chunk_size}
     * adapters. AccountId is a mandatory field

     * creates a jongo aggregate query similar to:

     * ( [ { $match: { adapterID: {$in:
     * ["f9a398e0-ba5d-11e3-a019-08edb99eaa2d"]}, timestamp: {$lte:
     * 1396449705737} } }, { $group: { _id: {level: "$level", id:"$logId",
     * adapterId: "$adapterID", adapterType: "$adapterType", message:"$message",
     * timestamp: "$timestamp"} } }, { $sort : {timestamp: -1} }, { $skip: 0 },
     * { $limit: 4 } ] )
     *
     * @return
     * @throws Exception
     */
    private static List<Log> getLogsWithLimit(String accountId, String ddrRecordID, Collection<String> adapters,
        Collection<LogLevel> levels, String adapterType, Long endTime, Integer offset, Integer limit) throws Exception {

        //initially collect all the match queries
        String matchQuery = "";
        if (accountId != null) {
            matchQuery += "accountId:\"" + accountId + "\"";
        }
        else {
            throw new Exception("AccountId is not expected to be null.");
        }

        if (ddrRecordID != null) {
            //fetch the sessionKey from this ddrRecordId
            DDRRecord ddrRecord = DDRRecord.getDDRRecord(ddrRecordID, accountId);
            if (ddrRecord != null && ddrRecord.getSessionKeys() != null && !ddrRecord.getSessionKeys().isEmpty()) {
                matchQuery += ", sessionKey: {$in:" + ServerUtils.serialize(ddrRecord.getSessionKeys()) + "}";
            }
            else {
                matchQuery += ", ddrRecordId:\"" + ddrRecordID + "\"";
            }
        }
        if (adapters != null) {
            int endIndex = adapters.size() <= adapter_chunk_size - 1 ? adapters.size() : adapter_chunk_size;
            List<String> subAdapterList = new ArrayList<String>(adapters).subList(0, endIndex);
            if (!subAdapterList.isEmpty()) {
                matchQuery += ", adapterID: {$in:" + ServerUtils.serialize(subAdapterList) + "}";
            }
        }
        if (adapterType != null) {
            matchQuery += ", adapterType:\"" + adapterType + "\"";
        }
        if (endTime != null) {
            matchQuery += ", timestamp:{$lte:" + endTime + "}";
        }
        if (levels != null) {
            matchQuery += ", level:{$in:" + ServerUtils.serialize(levels) + "}";
        }
        offset = offset == null ? 0 : offset;
        limit = limit == null ? 50 : limit;

        ArrayList<Log> resultLogs = new ArrayList<Log>();
        //fetch in batches of 5
        for (; resultLogs.size() <= limit;) {
            ArrayList<Log> logs = fetchLogs(accountId, matchQuery, offset, 5, limit - resultLogs.size());
            if (logs != null && !logs.isEmpty()) {
                resultLogs.addAll(logs);
            }
            else {
                break;
            }
            //if ddrRecord Id is part of the fetch, update the offset
            if (matchQuery.contains("ddrRecordId") || matchQuery.contains("sessionKey")) {
                offset += resultLogs.size();
            }
            else {
                offset += 5;
            }
        }
        return resultLogs;
    }

    /**
     * Fetches the logs for a particular matchQuery and offset.
     *
     * @param accountId
     * @param matchQuery
     *            If the ddrRecordId is part of the query, it ignores the fetch
     *            based on trackingTokens. Just returns all the logs for which
     *            this ddrRecordId matches
     * @param offset
     * @param trackingTokenFetchlimit
     * @param logLimit
     * @return
     */
    private static ArrayList<Log> fetchLogs(String accountId, String matchQuery, Integer offset,
        Integer trackingTokenFetchlimit, Integer logLimit) {

        ArrayList<Log> resultLogs = new ArrayList<Log>();
        MongoCollection collection = getCollection();
        offset = offset != null ? offset : 0;
        logLimit = logLimit != null ? logLimit : 100;

        //if ddrRecordId querying is part of the request, ignore the tracking token based fetch
        if (matchQuery.contains("ddrRecordId") || matchQuery.contains("sessionKey")) {
            matchQuery = String.format("{%s}", matchQuery);
            MongoCursor<Log> logsCursor = collection.find(matchQuery).skip(offset).limit(logLimit).as(Log.class);
            if (logsCursor != null) {
                while (logsCursor.hasNext() && resultLogs.size() < logLimit) {
                    resultLogs.add(logsCursor.next());
                }
            }
        }
        else {
            matchQuery = String.format("{$match: {%s}}", matchQuery);
            log.info("Match query: " + matchQuery);
            Aggregate aggregate = collection.aggregate(matchQuery);

            //update the aggregate query with groupQuery next. This includes all the fields to fetch
            String groupQuery = "{$group:{_id: \"$trackingToken\", timestamp:{$max: \"$timestamp\"}}}";
            aggregate = aggregate.and(groupQuery);
            //update the aggregate query with sort (on timestamp), offset and limit
            aggregate = aggregate.and("{$sort :{timestamp: -1}}").and(String.format("{$skip :%s}", offset))
                .and(String.format("{$limit :%s}", trackingTokenFetchlimit));

            List<ObjectNode> logsByTrackingToken = aggregate.as(ObjectNode.class);
            for (ObjectNode logByTrackingToken : logsByTrackingToken) {
                JsonNode trackingToken = logByTrackingToken.get("_id");
                MongoCursor<Log> logsCursor = collection
                    .find(
                        String.format("{trackingToken: \"%s\", accountId: \"%s\"}", trackingToken.asText(), accountId))
                    .sort("{timestamp: -1}").as(Log.class);
                if (logsCursor != null) {
                    while (logsCursor.hasNext() && resultLogs.size() < logLimit) {
                        resultLogs.add(logsCursor.next());
                    }
                }
            }
        }
        return resultLogs;
    }

    private static MongoCollection getCollection() {

        DB db = ParallelInit.getDatastore();
        Jongo jongo = new Jongo(db, new JacksonMapper.Builder().registerModule(new JodaModule())
                                        .enable(MapperFeature.AUTO_DETECT_GETTERS).withView(Log.class).build());
        MongoCollection collection = jongo.getCollection(Log.class.getCanonicalName().toLowerCase() + "s");
        collection.ensureIndex("{ logId: 1}");
        return collection;
    }
}


text:
package net.sabamiso.android.sendosc4a;

import java.util.Vector;

import net.sabamiso.android.p5.PseudoP5View;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.Vibrator;

public class SendOSCView extends PseudoP5View {

	class Button {
		int idx;
		float x, y, w, h;
		boolean last_pressed_status;

		public Button(int idx, int x, int y, int w, int h) {
			this.idx = idx;
			this.x = x;
			this.y = y;
			this.w = w;
			this.h = h;

			last_pressed_status = false;
		}

		public boolean isInner(float x, float y) {
			if (x < this.x)
				return false;
			if (y < this.y)
				return false;
			if (this.x + this.w < x)
				return false;
			if (this.y + this.h < y)
				return false;

			return true;
		}

		public boolean isPressed() {
			if (mousePressed == false)
				return false;
			return isInner(mouseX, mouseY);
		}

		void process() {
			if (osc == null) return;

			boolean current_pressed_status = isPressed();

			if (current_pressed_status == true && last_pressed_status == false) {
				osc.sendPressedMessage(idx);
			} else if (current_pressed_status == false
					&& last_pressed_status == true) {
				osc.sendReleasedMessage(idx);
			}

			last_pressed_status = current_pressed_status;
		}

		public void draw() {
			strokeWeight(5);
			stroke(255);
			if (isPressed()) {
				fill(255);
			} else {
				fill(64);
			}
			rect(x, y, w, h, 20);

			fill(128);
			text("" + idx, x + 14, y + 26);
			text("P:" + osc.getButtonPressedConfig(idx), x + 14, y + 44);
			text("R:" + osc.getButtonReleasedConfig(idx), x + 14, y + 62);
		}
	}

	Vector<Button> v = new Vector<Button>();
	long last_pressed_t;
	OSC osc;
	MulticastLock lock;

	public SendOSCView(Context context) {
		super(context);
	}

	@Override
	protected void setup() {
		size(360, 640);
		frameRate(30);

		createButtons();
	}

	@Override
	public void onResume() {
		super.onResume();
		osc = OSC.getInstance();
		osc.reload();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	void createButtons() {
		for (int i = 0; i < 8; ++i) {
			int bx = i % 2;
			int by = i / 2;
			int x = bx * 170 + 30;
			int y = by * 160 + 5;

			Button b = new Button(i, x, y, 130, 130);
			v.add(b);
		}
	}

	@Override
	protected void draw() {
		background(0, 0, 0);

		for (int i = 0; i < v.size(); ++i) {
			Button b = v.get(i);
			b.process();
			b.draw();
		}

		fill(128);
		text("long press : show setting activity", 90, 635);

		// check long press
		long diff = System.currentTimeMillis() - last_pressed_t;
		if (mousePressed == true && diff > 2000) {

			Vibrator v = (Vibrator) getContext().getSystemService(
					Context.VIBRATOR_SERVICE);
			v.vibrate(100);

			Intent intent = new Intent(getContext(), SettingsActivity.class);
			getContext().startActivity(intent);
		}
	}

	@Override
	protected void mousePressed() {
		last_pressed_t = System.currentTimeMillis();
	}

}


text:
"""APL 2.0 code from github.com/pkmital/tensorflow_tutorials w/ permission
from Parag K. Mital.
"""
import math
import tensorflow as tf

def batch_norm(x, phase_train, scope='bn', affine=True):
    """
    Batch normalization on convolutional maps.
    from: https://stackoverflow.com/questions/33949786/how-could-i-
    use-batch-normalization-in-tensorflow
    Only modified to infer shape from input tensor x.
    Parameters
    ----------
    x
        Tensor, 4D BHWD input maps
    phase_train
        boolean tf.Variable, true indicates training phase
    scope
        string, variable scope
    affine
        whether to affine-transform outputs
    Return
    ------
    normed
        batch-normalized maps
    """
    with tf.variable_scope(scope):
        og_shape = x.get_shape().as_list()
        if len(og_shape) == 2:
            x = tf.reshape(x, [-1, 1, 1, og_shape[1]])
        shape = x.get_shape().as_list()
        beta = tf.Variable(tf.constant(0.0, shape=[shape[-1]]),
                           name='beta', trainable=True)
        gamma = tf.Variable(tf.constant(1.0, shape=[shape[-1]]),
                            name='gamma', trainable=affine)

        batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')
        ema = tf.train.ExponentialMovingAverage(decay=0.9)
        ema_apply_op = ema.apply([batch_mean, batch_var])
        ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)

        def mean_var_with_update():
            """Summary
            Returns
            -------
            name : TYPE
                Description
            """
            with tf.control_dependencies([ema_apply_op]):
                return tf.identity(batch_mean), tf.identity(batch_var)
        mean, var = tf.cond(phase_train,
                                          mean_var_with_update,
                                          lambda: (ema_mean, ema_var))

        normed = tf.nn.batch_norm_with_global_normalization(
            x, mean, var, beta, gamma, 1e-3, affine)
        if len(og_shape) == 2:
            normed = tf.reshape(normed, [-1, og_shape[-1]])
    return normed

def lrelu(x, leak=0.2, name="lrelu"):
    """Leaky rectifier.
    Parameters
    ----------
    x : Tensor
        The tensor to apply the nonlinearity to.
    leak : float, optional
        Leakage parameter.
    name : str, optional
        Variable scope to use.
    Returns
    -------
    x : Tensor
        Output of the nonlinearity.
    """
    with tf.variable_scope(name):
        f1 = 0.5 * (1 + leak)
        f2 = 0.5 * (1 - leak)
        return f1 * x + f2 * abs(x)

def linear(x, n_units, scope=None, stddev=0.02,
           activation=lambda x: x):
    """Fully-connected network.
    Parameters
    ----------
    x : Tensor
        Input tensor to the network.
    n_units : int
        Number of units to connect to.
    scope : str, optional
        Variable scope to use.
    stddev : float, optional
        Initialization's standard deviation.
    activation : arguments, optional
        Function which applies a nonlinearity
    Returns
    -------
    x : Tensor
        Fully-connected output.
    """
    shape = x.get_shape().as_list()

    with tf.variable_scope(scope or "Linear"):
        matrix = tf.get_variable("Matrix", [shape[1], n_units], tf.float32,
                                 tf.random_normal_initializer(stddev=stddev))
        return activation(tf.matmul(x, matrix))

def conv2d(x, n_filters,
           k_h=5, k_w=5,
           stride_h=2, stride_w=2,
           stddev=0.02,
           activation=None,
           bias=True,
           padding='SAME',
           name="Conv2D"):
    """2D Convolution with options for kernel size, stride, and init deviation.

    Parameters
    ----------
    x : Tensor
        Input tensor to convolve.
    n_filters : int
        Number of filters to apply.
    k_h : int, optional
        Kernel height.
    k_w : int, optional
        Kernel width.
    stride_h : int, optional
        Stride in rows.
    stride_w : int, optional
        Stride in cols.
    stddev : float, optional
        Initialization's standard deviation.
    activation : arguments, optional
        Function which applies a nonlinearity
    padding : str, optional
        'SAME' or 'VALID'
    name : str, optional
        Variable scope to use.

    Returns
    -------
    x : Tensor
        Convolved input.
    """
    with tf.variable_scope(name):
        w = tf.get_variable(
            'w', [k_h, k_w, x.get_shape()[-1], n_filters],
            initializer=tf.truncated_normal_initializer(stddev=stddev))
        conv = tf.nn.conv2d(
            x, w, strides=[1, stride_h, stride_w, 1], padding=padding)
        if bias:
            b = tf.get_variable(
                'b', [n_filters],
                initializer=tf.truncated_normal_initializer(stddev=stddev))
            conv = tf.nn.bias_add(conv, b)
        if activation:
            conv = activation(conv)
        return conv


text:
class User < ActiveRecord::Base
  receives_notifications
end


text:
/*
  Purpose of this test is to prove that phantom properly handles cookies for the purpose of load testing
   1) cookie is persisted in process
   2) cookie is not persisted between processes (concurrent connections)

   test passed :)
*/

require('http')
  .createServer(function(req, res){
    console.log(new Date().toString() +  ': Processing Request')
    // simulate delay
    setTimeout(function(){
      if (req.headers.cookie){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('yay, we found the following cookies:');
        res.write(req.headers.cookie);
      } else {
        var cookie = Math.floor(Math.random() * 100000000000);

        res.writeHead(200, {
          'Content-Type': 'text/plain',
          'Set-Cookie' : 'a=' + cookie + '; max-age=100000000;'
        });
        res.write('NOOB - we dropped the following cookie')
        res.write(cookie + '');
      }
      res.end();
    }, 180)
  }).listen(process.argv[2] || 8080);


text:
package org.thriftee.thrift.transport;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;

import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class TTransportOutputStream extends OutputStream {

//  private static final Field outputStreamField_; static {
//    try {
//      outputStreamField_ = TIOStreamTransport.class.getDeclaredField("outputStream_");
//    } catch (Exception e) {
//      throw new RuntimeException(e);
//    }
//  }

  public static OutputStream outputStreamFor(TTransport trans) {
//    if (!(trans instanceof TIOStreamTransport)) {
      return new TTransportOutputStream(trans);
//    }
//    try {
//      return (OutputStream) outputStreamField_.get(trans);
//    } catch (IllegalAccessException e) {
//      System.err.println("[WARN]: could not get outputstream for TIOStreamTrans");
//      return new TTransportOutputStream(trans);
//    }
  }

  private final TTransport __transport;

  public TTransportOutputStream(TTransport transport) {
    this.__transport = transport;
  }

  protected TTransport transport() {
    return __transport;
  }

  private final byte[] byteRawBuf = new byte[1];

  @Override
  public void write(int b) throws IOException {
    byteRawBuf[0] = (byte)(b & 0xff);
    try {
      transport().write(byteRawBuf);
    } catch (TTransportException e) {
      throw wrap(e);
    }
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    try {
      transport().write(b, off, len);
    } catch (TTransportException e) {
      throw wrap(e);
    }
  }

  @Override
  public void write(byte[] b) throws IOException {
    try {
      transport().write(b);
    } catch (TTransportException e) {
      throw wrap(e);
    }
  }

  public IOException wrap(TTransportException e) throws IOException {
    for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
      if (t instanceof IOException) {
        throw (IOException) t;
      }
    }
    throw new IOException(
      "Error writing to thrift transport " + transport() +
      ": " + e.getMessage(), e
    );
  }

}


text:
"""
.. module:: DeleteEventForm
    :synopsis: A form for deleting an event or event series.

.. moduleauthor:: Dan Schlosser <dan@danrs.ch>
"""

from flask.ext.wtf import Form
from wtforms import BooleanField

class DeleteEventForm(Form):
    """A form for deleting an event.

    :ivar delete_all: :class:`wtforms.fields.BooleanField` - True if the event
        is recurring and all events in the series should be deleted.
    """
    delete_all = BooleanField('Delete All', default=False)