text:
function getChannels(callback) {
  chrome.runtime.getBackgroundPage(function(page) {
    callback(page.channels);
  });
}

// TODO: Use underscore.js' template system to generate the table.
function createTableRow(name, isLive, viewers) {
  var color = isLive ? "bright-red" : "gray";
  var baseUrl = "https://twitch.tv/";

  var tr = $("
");

  var a = $("").attr("href", baseUrl + name).attr("target", "_blank");
  var tdChannel = $("").append(a.text(name));

  var tdViewers = $("");
  var aViewers = a.clone().text(viewers.toLocaleString());
  tdViewers.append($("")).append(aViewers);

  var tdRemoveChannel = $("");
  var iRemoveChannel = $("");
  var divRemoveChannelButton = $(
    "
");
  divRemoveChannelButton.data("name", name);
  tdRemoveChannel.append(
    divRemoveChannelButton.append(iRemoveChannel));

  tr.append(tdChannel, tdViewers, tdRemoveChannel);
  return tr;
}

function updateChannelList(channels) {
  var tbody = $("#channel-list tbody");
  tbody.empty();
  if (channels.count() === 0) {
    tbody.append($("
").append($("").text("No channels added yet")));
  } else {
    channels.foreach(function(channel) {
      tbody.append(
        createTableRow(channel.name, channel.isLive, channel.viewers));
    });
    // Hook up the remove button callbacks.
    $(".remove-channel").click(function() {
      channels.removeChannel($(this).data("name"));
    });
  }
}

function initializeUi() {
  var addChannel = $("#add-channel");
  var channelInput = $("#channel input");
  addChannel.click(function() {
    var channel = channelInput.val();
    getChannels(function(channels) {
      // Clear the input field if we successfully added the channel.
      if (channels.addChannel(channel)) {
        channelInput.val("");
      }
    });
  });
  $("#channel").submit(function(ev) {
    ev.preventDefault();
    // We just fake a click event on form submissions to re-use the click
    // signal handler.
    addChannel.click();
  });
  var showNotifications = $("#show-notifications");
  // TODO: Add a settings API to background.js that wraps calls to
  //       chrome.storage.
  chrome.storage.local.get({"show-notifications": false}, function(result) {
    var state = result["show-notifications"] ? "check" : "uncheck";
    // FIXME: Since the storage API is asynchronous, the checkbox state will
    //        usually be set when the UI is already visible.
    showNotifications.checkbox(state);
  });
  showNotifications.checkbox({"onChange": function() {
    var state = showNotifications.checkbox("is checked");
    chrome.storage.local.set({"show-notifications": state});
  }});
  channelInput.focus();
}

document.addEventListener("DOMContentLoaded", function() {
  initializeUi();
  getChannels(function(channels) {
    // Update the channel list on changes.
    channels.onchange(updateChannelList);
    // Update the channel list once on page load.
    updateChannelList(channels);
  });
});


text:
module ActsAsTaggableOn
  VERSION = '2.4.2.pre'
end

redpajama_set_name: RedPajamaGithub


text: ![Magic Trick](image/dvberkel.gif "Me performing a magic trick")


text:
module Hate.Events.Types where

import Control.Concurrent.STM (TQueue)
import qualified Graphics.UI.GLFW as GLFW

type EventsState = TQueue TimedEvent
type Time = Double

data Event =
    EventError           !GLFW.Error !String
  | EventWindowPos       !Int !Int
  | EventWindowSize      !Int !Int
  | EventWindowClose
  | EventWindowRefresh
  | EventWindowFocus     !GLFW.FocusState
  | EventWindowIconify   !GLFW.IconifyState
  | EventFramebufferSize !Int !Int
  | EventMouseButton     !GLFW.MouseButton !GLFW.MouseButtonState !GLFW.ModifierKeys
  | EventCursorPos       !Float !Float
  | EventCursorEnter     !GLFW.CursorState
  | EventScroll          !Double !Double
  | EventKey             !GLFW.Key !Int !GLFW.KeyState !GLFW.ModifierKeys
  | EventChar            !Char
  deriving Show

type TimedEvent = (Time, Event)


text:
package rpc

import (
	"fmt"
	"io"
	"math/rand"
	"net"
	"net/rpc"
	"time"

	"github.com/cockroachdb/cockroach/proto"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
	"github.com/cockroachdb/cockroach/util/retry"
	"github.com/cockroachdb/cockroach/util/tracer"

	gogoproto "github.com/gogo/protobuf/proto"
)

// OrderingPolicy is an enum for ordering strategies when there
// are multiple endpoints available.
type OrderingPolicy int

const (
	// OrderStable uses endpoints in the order provided.
	OrderStable = iota
	// OrderRandom randomly orders available endpoints.
	OrderRandom
)

// An Options structure describes the algorithm for sending RPCs to
// one or more replicas, depending on error conditions and how many
// successful responses are required.
type Options struct {
	// N is the number of successful responses required.
	N int
	// Ordering indicates how the available endpoints are ordered when
	// deciding which to send to (if there are more than one).
	Ordering OrderingPolicy
	// SendNextTimeout is the duration after which RPCs are sent to
	// other replicas in a set.
	SendNextTimeout time.Duration
	// Timeout is the maximum duration of an RPC before failure.
	// 0 for no timeout.
	Timeout time.Duration
	// If not nil, information about the request is added to this trace.
	Trace *tracer.Trace
}

// An rpcError indicates a failure to send the RPC. rpcErrors are
// retryable.
type rpcError struct {
	error
}

func newRPCError(err error) rpcError {
	return rpcError{err}
}

// CanRetry implements the Retryable interface.
// TODO(tschottdorf): the way this is used by rpc/send suggests that it
// may be better if these weren't retriable - they are returned when the
// connection fails, i.e. for example when a node is down or the network
// fails. Retrying on such errors keeps the caller waiting for a long time
// and without a positive outlook.
func (r rpcError) CanRetry() bool { return true }

// sendOneFn is overwritten in tests to mock sendOne.
var sendOneFn = sendOne

// A SendError indicates that too many RPCs to the replica
// set failed to achieve requested number of successful responses.
// canRetry is set depending on the types of errors encountered.
type SendError struct {
	errMsg   string
	canRetry bool
}

// Error implements the error interface.
func (s SendError) Error() string {
	return "failed to send RPC: " + s.errMsg
}

// CanRetry implements the Retryable interface.
func (s SendError) CanRetry() bool { return s.canRetry }

// Send sends one or more method RPCs to clients specified by the
// slice of endpoint addrs. Arguments for methods are obtained using
// the supplied getArgs function. The number of required replies is
// given by opts.N. Reply structs are obtained through the getReply()
// function. On success, Send returns a slice of replies of length
// opts.N. Otherwise, Send returns an error if and as soon as the
// number of failed RPCs exceeds the available endpoints less the
// number of required replies.
func Send(opts Options, method string, addrs []net.Addr, getArgs func(addr net.Addr) gogoproto.Message,
	getReply func() gogoproto.Message, context *Context) ([]gogoproto.Message, error) {
	trace := opts.Trace // not thread safe!

	if opts.N <= 0 {
		return nil, SendError{
			errMsg:   fmt.Sprintf("opts.N must be positive: %d", opts.N),
			canRetry: false,
		}
	}

	if len(addrs) < opts.N {
		return nil, SendError{
			errMsg:   fmt.Sprintf("insufficient replicas (%d) to satisfy send request of %d", len(addrs), opts.N),
			canRetry: false,
		}
	}

	done := make(chan *rpc.Call, len(addrs))

	var clients []*Client
	for _, addr := range addrs {
		clients = append(clients, NewClient(addr, context))
	}

	var orderedClients []*Client
	switch opts.Ordering {
	case OrderStable:
		orderedClients = clients
	case OrderRandom:
		// Randomly permute order, but keep known-unhealthy clients last.
		var healthy, unhealthy []*Client
		for _, client := range clients {
			select {
			case <-client.Healthy():
				healthy = append(healthy, client)
			default:
				unhealthy = append(unhealthy, client)
			}
		}
		for _, idx := range rand.Perm(len(healthy)) {
			orderedClients = append(orderedClients, healthy[idx])
		}
		for _, idx := range rand.Perm(len(unhealthy)) {
			orderedClients = append(orderedClients, unhealthy[idx])
		}
	}
	// TODO(spencer): going to need to also sort by affinity; closest
	// ping time should win. Makes sense to have the rpc client/server
	// heartbeat measure ping times. With a bit of seasoning, each
	// node will be able to order the healthy replicas based on latency.

	sendFn := func(client *Client) {
		addr := client.RemoteAddr()

		if args := getArgs(addr); args != nil {
			if log.V(2) {
				log.Infof("%s: sending request to %s: %+v", method, addr, args)
			}
			trace.Event(fmt.Sprintf("sending to %s", addr))
			go sendOneFn(client, opts.Timeout, method, args, getReply(), done)
		} else {
			done <- &rpc.Call{Error: newRPCError(util.Errorf("nil arguments returned for client %s", addr))}
		}
	}

	// Start clients up to opts.N.
	head, tail := orderedClients[:opts.N], orderedClients[opts.N:]
	for _, client := range head {
		sendFn(client)
	}

	var replies []gogoproto.Message
	var errors, retryableErrors int

	// Wait for completions.
	for len(replies) < opts.N {
		select {
		case call := <-done:
			if call.Error == nil {
				// Verify response data integrity if this is a proto response.
				if req, reqOk := call.Args.(proto.Request); reqOk {
					if resp, respOk := call.Reply.(proto.Response); respOk {
						if err := resp.Verify(req); err != nil {
							call.Error = err
						}
					} else {
						call.Error = util.Errorf("response to proto request must be a proto")
					}
				}
			}
			err := call.Error
			if err == nil {
				if log.V(2) {
					log.Infof("%s: successful reply: %+v", method, call.Reply)
				}

				replies = append(replies, call.Reply.(gogoproto.Message))
				break // end the select
			}

			// Error handling.
			if log.V(1) {
				log.Warningf("%s: error reply: %s", method, err)
			}

			errors++

			// Since we have a reconnecting client here, disconnect errors are retryable.
			disconnected := err == rpc.ErrShutdown || err == io.ErrUnexpectedEOF
			if retryErr, ok := err.(retry.Retryable); disconnected || (ok && retryErr.CanRetry()) {
				retryableErrors++
			}

			if remainingNonErrorRPCs := len(addrs) - errors; remainingNonErrorRPCs < opts.N {
				return nil, SendError{
					errMsg:   fmt.Sprintf("too many errors encountered (%d of %d total): %v", errors, len(clients), err),
					canRetry: remainingNonErrorRPCs+retryableErrors >= opts.N,
				}
			}
			// Send to additional replicas if available.
			if len(tail) > 0 {
				trace.Event("error, trying next peer")
				sendFn(tail[0])
				tail = tail[1:]
			}

		case <-time.After(opts.SendNextTimeout):
			// On successive RPC timeouts, send to additional replicas if available.
			if len(tail) > 0 {
				trace.Event("timeout, trying next peer")
				sendFn(tail[0])
				tail = tail[1:]
			}
		}
	}
	return replies, nil
}

// sendOne invokes the specified RPC on the supplied client when the
// client is ready. On success, the reply is sent on the channel;
// otherwise an error is sent.
func sendOne(client *Client, timeout time.Duration, method string, args, reply gogoproto.Message, done chan *rpc.Call) {
	var timeoutChan <-chan time.Time
	if timeout != 0 {
		timeoutChan = time.After(timeout)
	}
	select {
	case <-client.Healthy():
		client.Go(method, args, reply, done)
	case <-client.Closed:
		done <- &rpc.Call{Error: newRPCError(util.Errorf("rpc to %s failed as client connection was closed", method))}
	case <-timeoutChan:
		done <- &rpc.Call{Error: newRPCError(util.Errorf("rpc to %s: client not ready after %s", method, timeout))}
	}
}


text:
<?php

/**
 * @testCase
 */

namespace NextrasTests\Orm\Collection;

use Mockery;
use Nextras\Orm\Collection\Helpers\ConditionParserHelper;
use NextrasTests\Orm\TestCase;
use Tester\Assert;

$dic = require_once __DIR__ . '/../../../bootstrap.php';

class ConditionParserHelperTest extends TestCase
{

	public function testParse()
	{
		Assert::same([['column'], '=', NULL], ConditionParserHelper::parseCondition('column'));
		Assert::same([['column'], '!=', NULL], ConditionParserHelper::parseCondition('column!'));
		Assert::same([['column'], '!=', NULL], ConditionParserHelper::parseCondition('column!='));
		Assert::same([['column'], '<=', NULL], ConditionParserHelper::parseCondition('column<='));
		Assert::same([['column'], '>=', NULL], ConditionParserHelper::parseCondition('column>='));
		Assert::same([['column'], '>', NULL], ConditionParserHelper::parseCondition('column>'));
		Assert::same([['column'], '<', NULL], ConditionParserHelper::parseCondition('column<'));

		Assert::same([['column', 'name'], '=', NULL], ConditionParserHelper::parseCondition('this->column->name'));
		Assert::same([['column', 'name'], '!=', NULL], ConditionParserHelper::parseCondition('this->column->name!'));

		Assert::same([['column', 'name'], '=', 'Book'], ConditionParserHelper::parseCondition('Book->column->name'));
		Assert::same([['column'], '=', 'NextrasTests\Orm\Book'], ConditionParserHelper::parseCondition('NextrasTests\Orm\Book->column'));
	}

	public function testFailing()
	{
		Assert::throws(function () {
			ConditionParserHelper::parseCondition('this->property.column');
		}, 'Nextras\Orm\InvalidArgumentException');

		Assert::throws(function () {
			ConditionParserHelper::parseCondition('column.name');
		}, 'Nextras\Orm\InvalidArgumentException');
	}

}

$test = new ConditionParserHelperTest($dic);
$test->run();


text:
<!DOCTYPE html>

Lore Ipsum

    Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam quis risus eget urna mollis ornare vel eu leo. Donec git ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue.

    Cras mattis <tt class="foo">consectetur</tt> purus sit amet fermentum. Donec ullamcorper nulla non metus auctor fringilla. Etiam porta sem malesuada magna mollis euismod. Duis mollis, est non commodo luctus, nisi erat porttitor <tt class="foo bar baz">ligula</tt>, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla. Donec ullamcorper nulla non metus auctor fringilla.

Hello World
ignore
Foo, bar


text:
require File.dirname(__FILE__) + '/../../../spec_helper'

has_tty? do # needed for CI until we figure out a better way
require 'readline'
require File.dirname(__FILE__) + '/shared/size'

describe "Readline::HISTORY.length" do
  it_behaves_like :readline_history_size, :length
end
end


text:
Please log in

        <input type="text" class="form-control" placeholder="User name" id="login-name" required autofocus>
        <input type="password" class="form-control" placeholder="Password" id="login-pass" required autofocus>

    <button class="btn btn-lg btn-primary btn-block" type="submit" id="login-btn">Login</button>


text:
void foo() {
}

bool foobool(int argc) {
  return argc;
}

struct S1; // expected-note {{declared here}}

int main(int argc, char **argv) {
  int i;
  #pragma omp target enter data map(to: i) device // expected-error {{expected '(' after 'device'}}
  #pragma omp target enter data map(to: i) device ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
  #pragma omp target enter data map(to: i) device () // expected-error {{expected expression}}
  #pragma omp target enter data map(to: i) device (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
  #pragma omp target enter data map(to: i) device (argc)) // expected-warning {{extra tokens at the end of '#pragma omp target enter data' are ignored}}
#pragma omp target enter data map(to: i) device (argc > 0 ? argv[1] : argv[2]) // expected-error {{expression must have integral or unscoped enumeration type, not 'char *'}}
  #pragma omp target enter data map(to: i) device (argc + argc)
  #pragma omp target enter data map(to: i) device (argc), device (argc+1) // expected-error {{directive '#pragma omp target enter data' cannot contain more than one 'device' clause}}
  #pragma omp target enter data map(to: i) device (S1) // expected-error {{'S1' does not refer to a value}}
  #pragma omp target enter data map(to: i) device (-2) // expected-error {{argument to 'device' clause must be a non-negative integer value}}
  #pragma omp target enter data map(to: i) device (-10u)
  #pragma omp target enter data map(to: i) device (3.14) // expected-error {{expression must have integral or unscoped enumeration type, not 'double'}}
  foo();

  return 0;
}


text:
package io.keen.client.java;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

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

/**
 * Relative Timeframe, as specified by API docs: https://keen.io/docs/api/#relative-timeframes
 *
 * Created by claireyoung on 7/6/15.
 * @author claireyoung
 * @since 1.0.0
 */
public class RelativeTimeframe implements Timeframe {

    private final String relativeTimeframe;
    private final String timezone;

    /**
     * Construct a RelativeTimeframe with a specified relative time window.
     * @param relativeTimeframe the relative timeframe string, as specified by the API docs.
     *                          For example, "this_minute", "this_month", "this_year", etc.
     */
    public RelativeTimeframe(String relativeTimeframe) {
        this(relativeTimeframe, null);
    }

    /**
     * Construct a RelativeTimeframe with a specified relative time window, along with a
     * timezone to use as an offset.
     * @param relativeTimeframe the relative timeframe string, as specified by the API docs.
     *                          For example, "this_minute", "this_month", "this_year", etc.
     * @param timezone the timezone offset to use with the relative timeframe
     */
    public RelativeTimeframe(final String relativeTimeframe, final String timezone) {
        if (null == relativeTimeframe || relativeTimeframe.trim().isEmpty()) {
            throw new IllegalArgumentException("'relativeTimeframe' argument must be specified and not empty.");
        }

        this.relativeTimeframe = relativeTimeframe;
        if (null != timezone && !timezone.trim().isEmpty()) {
            this.timezone = timezone;
        } else {
            this.timezone = null;
        }
    }

    /**
     * Get the relative timeframe.
     *
     * @return  the relative timeframe.
     */
    public String getTimeframe() {
        return this.relativeTimeframe;
    }

    /**
     * Construct the Timeframe map to send in the query.
     *
     * @return  the Timeframe Json map to send in the query.
     */
    @Override
    public Map<String, Object> constructTimeframeArgs() {
        Map<String, Object> timeframe = new HashMap<String, Object>(3);

        if (null != this.relativeTimeframe) {
            timeframe.put(KeenQueryConstants.TIMEFRAME, this.relativeTimeframe);
        }

        if (null != this.timezone) {
            timeframe.put(KeenQueryConstants.TIMEZONE, this.timezone);
        }

        return timeframe;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}


text:
\section{Useful Links}

The \href{http://docs.amazonwebservices.com}{main Amazon documentation webpage} contains links to oodles of documentation for the Amazon web services.

\href{http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/}{Amazon User Guide}

\href{http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/}{EC2 Userguide}.

The \href{https://aws.amazon.com/about-aws/events/}{AWS Events} page contains a listing of things like webinars, conferences and user groups - both online and real world.


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

Copyright (c) 2013, jEVETools
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of the contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

 -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.jevetools</groupId>
		<artifactId>unmarshal</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>com.jevetools.unmarshal.api.impl.tests</artifactId>

	<packaging>eclipse-test-plugin</packaging>

	<name>jEVETools Unmarshal API Impl Tests</name>
	<description>jEVETools Unmarshal API Impl Tests - JAVA EVE Online Tools Unmarshal API Implementation Tests</description>

	<build>

		<sourceDirectory>src</sourceDirectory>

		<testSourceDirectory>src</testSourceDirectory>

		<plugins>
<!--
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>findbugs-maven-plugin</artifactId>
			</plugin>
 -->
			<plugin>
				<groupId>org.eclipse.tycho</groupId>
				<artifactId>tycho-surefire-plugin</artifactId>
				<configuration>
					<!-- <argLine>-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y</argLine> -->
					<!-- <devProperties>${basedir}/dev.properties</devProperties> -->
					<!-- <surefireProperties>${basedir}/sunfire.properties</surefireProperties>  -->
					<!-- <work>/tmp/${project.groupId}-${project.version}</work> -->
					<showEclipseLog>true</showEclipseLog>
					<bundleStartLevel>
						<bundle>
							<id>org.eclipse.osgi</id>
							<level>-1</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.app</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.common</id>
							<level>2</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.ds</id>
							<level>1</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.registry</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.util</id>
							<level>1</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.osgi.services</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.core.contenttype</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.core.jobs</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.core.runtime</id>
							<level>2</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.equinox.preferences</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.jdt.junit.runtime</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.eclipse.pde.junit.runtime</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.hamcrest.core</id>
							<level>2</level>
							<autoStart>default</autoStart>
						</bundle>
						<bundle>
							<id>org.junit</id>
							<level>2</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>com.jevetools.unmarshal.python.api</id>
							<level>3</level>
							<autoStart>true</autoStart>
						</bundle>
						<bundle>
							<id>com.jevetools.unmarshal.python.api.impl</id>
							<level>3</level>
							<autoStart>true</autoStart>
						</bundle>
					</bundleStartLevel>
					<dependencies>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.core.contenttype</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.core.jobs</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.core.runtime</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.app</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.common</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.ds</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.preferences</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.registry</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.equinox.util</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.jdt.junit.runtime</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.osgi.services</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.osgi</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.pde.junit.runtime</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.hamcrest.core</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.junit</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>org.eclipse.osgi.services</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>com.jevetools.unmarshal.python.api</artifactId>
						</dependency>
						<dependency>
							<type>p2-installable-unit</type>
							<artifactId>com.jevetools.unmarshal.python.api.impl</artifactId>
						</dependency>
					</dependencies>
				</configuration>
			</plugin>

		</plugins>

	</build>

</project>


text: package org.apache.gora.aerospike;


text:
package calzone;

import calzone.model.BuildInfo;
import calzone.model.CalzoneFinishedBuild;
import calzone.model.CalzoneRunningBuild;
import jetbrains.buildServer.responsibility.ResponsibilityEntry;
import jetbrains.buildServer.serverSide.SBuildType;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class BuildFormatterTest {

    private BuildFormatter buildFormatter;
    private SBuildType buildType;
    private CalzoneRunningBuild runningBuild;
    private CalzoneFinishedBuild finishedBuild;
    private String theBuildName;
    private ResponsibilityEntry responsibilityEntry;

    @Before
    public void setUp() throws Exception {
        theBuildName = "the build name";
        runningBuild = mock(CalzoneRunningBuild.class);
        finishedBuild = mock(CalzoneFinishedBuild.class);

        responsibilityEntry = mock(ResponsibilityEntry.class);
        buildType = mock(SBuildType.class);
        when(buildType.getName()).thenReturn(theBuildName);
        when(buildType.getResponsibilityInfo()).thenReturn(this.responsibilityEntry);

        RunningBuildMaker runningBuildMaker = mock(RunningBuildMaker.class);
        when(runningBuildMaker.runningBuild(buildType)).thenReturn(runningBuild);

        FinishedBuildMaker finishedBuildMaker = mock(FinishedBuildMaker.class);
        when(finishedBuildMaker.lastFinishedBuild(buildType)).thenReturn(finishedBuild);

        buildFormatter = new BuildFormatter(finishedBuildMaker, runningBuildMaker);
    }

    @Test
    public void formatsBuildWithNoResponsibility() throws Exception {
        when(this.responsibilityEntry.getState()).thenReturn(ResponsibilityEntry.State.NONE);

        BuildInfo buildInfo = buildFormatter.format(buildType);

        assertThat(buildInfo.getBuildName(), is(theBuildName));
        assertThat(buildInfo.getLastFinished(), is(finishedBuild));
        assertThat(buildInfo.getRunningBuild(), is(runningBuild));
        assertThat(buildInfo.isResponsibilityAssigned(), is(false));
    }

    @Test
    public void formatsBuildWithResponsibility() throws Exception {
        when(this.responsibilityEntry.getState()).thenReturn(ResponsibilityEntry.State.TAKEN);

        BuildInfo buildInfo = buildFormatter.format(buildType);

        assertThat(buildInfo.getBuildName(), is(theBuildName));
        assertThat(buildInfo.getLastFinished(), is(finishedBuild));
        assertThat(buildInfo.getRunningBuild(), is(runningBuild));
        assertThat(buildInfo.isResponsibilityAssigned(), is(true));
    }

    @Test
    public void formatsBuildWithGivenUpResponsibility() throws Exception {
        when(this.responsibilityEntry.getState()).thenReturn(ResponsibilityEntry.State.GIVEN_UP);

        BuildInfo buildInfo = buildFormatter.format(buildType);

        assertThat(buildInfo.getBuildName(), is(theBuildName));
        assertThat(buildInfo.getLastFinished(), is(finishedBuild));
        assertThat(buildInfo.getRunningBuild(), is(runningBuild));
        assertThat(buildInfo.isResponsibilityAssigned(), is(false));
    }

    @Test
    public void formatsBuildWithFixedResponsibility() throws Exception {
        when(this.responsibilityEntry.getState()).thenReturn(ResponsibilityEntry.State.FIXED);

        BuildInfo buildInfo = buildFormatter.format(buildType);

        assertThat(buildInfo.getBuildName(), is(theBuildName));
        assertThat(buildInfo.getLastFinished(), is(finishedBuild));
        assertThat(buildInfo.getRunningBuild(), is(runningBuild));
        assertThat(buildInfo.isResponsibilityAssigned(), is(false));
    }
}


text:
///
/// \file  format_conversion.h
/// \brief This file contains the definitions of all format conversion functions, which
///        assist switching between various data types.
///

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                               PREPROCESSOR DIRECTIVES                               *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#pragma once
#ifndef TC_FORMAT_CONVERSION_
#define TC_FORMAT_CONVERSION_

#include <string>
#include <cctype>
#include <sstream>
#include "events.h"

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                                 FUNCTION PROTOTYPES                                 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

// String modification functions:
void StringRemoveSpaces(std::string &toRemove, char spaceChar = ' ');
void StringToLowercase(std::string &toLower);
void StringToUppercase(std::string &toUpper);

// String conversion functions:
bool StringToInt(std::string const& toConvert, int &result);
bool StringToBool(std::string const& toConvert, bool &result);
bool StringToConst(std::string const& toConvert, int &result);
bool StringToKeySym(std::string const& toConvert, SDLKey &result);

// Network conversion functions (assumes integers in network byte order):
bool StringToIp(std::string const& toConvert, Uint32 &result);
bool StringToPort(std::string const& toConvert, Uint16 &result);
bool IpToString(Uint32 const& toConvert, std::string &result);
bool PortToString(Uint16 const& toConvert, std::string &result);
Uint16 PortToInt(Uint16 const& toConvert);

// Other conversion functions:
bool KeySymToString(SDLKey const& toConvert, std::string &result);
bool KeyBindToString(KeyBind *toConvert, std::string &result);

#endif


text:
package flags

import (
	"os"
	"path"
)

// A Parser provides command line option parsing. It can contain several
// option groups each with their own set of options.
type Parser struct {
	// Embedded, see Command for more information
	*Command

	// A usage string to be displayed in the help message.
	Usage string

	// Option flags changing the behavior of the parser.
	Options Options

	internalError error
}

// Options provides parser options that change the behavior of the option
// parser.
type Options uint

const (
	// None indicates no options.
	None Options = 0

	// HelpFlag adds a default Help Options group to the parser containing
	// -h and --help options. When either -h or --help is specified on the
	// command line, the parser will return the special error of type
	// ErrHelp. When PrintErrors is also specified, then the help message
	// will also be automatically printed to os.Stderr.
	HelpFlag = 1 << iota

	// PassDoubleDash passes all arguments after a double dash, --, as
	// remaining command line arguments (i.e. they will not be parsed for
	// flags).
	PassDoubleDash

	// IgnoreUnknown ignores any unknown options and passes them as
	// remaining command line arguments instead of generating an error.
	IgnoreUnknown

	// PrintErrors prints any errors which occurred during parsing to
	// os.Stderr.
	PrintErrors

	// PassAfterNonOption passes all arguments after the first non option
	// as remaining command line arguments. This is equivalent to strict
	// POSIX processing.
	PassAfterNonOption

	// IgnoreDefaults will skip assigning default values. This may be useful
	// in cases that require knowledge of options that were actually passed in
	// -- for example, when merging options from the command line with options
	// from a config file.
	IgnoreDefaults

	// Default is a convenient default set of options which should cover
	// most of the uses of the flags package.
	Default = HelpFlag | PrintErrors | PassDoubleDash
)

// Parse is a convenience function to parse command line options with default
// settings. The provided data is a pointer to a struct representing the
// default option group (named "Application Options"). For more control, use
// flags.NewParser.
func Parse(data interface{}) ([]string, error) {
	return NewParser(data, Default).Parse()
}

// ParseArgs is a convenience function to parse command line options with default
// settings. The provided data is a pointer to a struct representing the
// default option group (named "Application Options"). The args argument is
// the list of command line arguments to parse. If you just want to parse the
// default program command line arguments (i.e. os.Args), then use flags.Parse
// instead. For more control, use flags.NewParser.
func ParseArgs(data interface{}, args []string) ([]string, error) {
	return NewParser(data, Default).ParseArgs(args)
}

// NewParser creates a new parser. It uses os.Args[0] as the application
// name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for
// more details). The provided data is a pointer to a struct representing the
// default option group (named "Application Options"), or nil if the default
// group should not be added. The options parameter specifies a set of options
// for the parser.
func NewParser(data interface{}, options Options) *Parser {
	ret := NewNamedParser(path.Base(os.Args[0]), options)

	if data != nil {
		_, ret.internalError = ret.AddGroup("Application Options", "", data)
	}

	return ret
}

// NewNamedParser creates a new parser. The appname is used to display the
// executable name in the builtin help message. Option groups and commands can
// be added to this parser by using AddGroup and AddCommand.
func NewNamedParser(appname string, options Options) *Parser {
	return &Parser{
		Command: newCommand(appname, "", "", nil),
		Options: options,
	}
}

// Parse parses the command line arguments from os.Args using Parser.ParseArgs.
// For more detailed information see ParseArgs.
func (p *Parser) Parse() ([]string, error) {
	return p.ParseArgs(os.Args[1:])
}

// ParseArgs parses the command line arguments according to the option groups that
// were added to the parser. On successful parsing of the arguments, the
// remaining, non-option, arguments (if any) are returned. The returned error
// indicates a parsing error and can be used with PrintError to display
// contextual information on where the error occurred exactly.
//
// When the common help group has been added (AddHelp) and either -h or --help
// was specified in the command line arguments, a help message will be
// automatically printed. Furthermore, the special error type ErrHelp is returned.
// It is up to the caller to exit the program if so desired.
func (p *Parser) ParseArgs(args []string) ([]string, error) {
	if p.internalError != nil {
		return nil, p.internalError
	}

	if (p.Options & IgnoreDefaults) == None {
		p.eachCommand(func(c *Command) {
			c.eachGroup(func(g *Group) {
				g.storeDefaults()
			})
		}, true)
	}

	// Add builtin help group to all commands if necessary
	if (p.Options & HelpFlag) != None {
		p.addHelpGroups(p.showBuiltinHelp)
	}

	s := &parseState{
		args:    args,
		retargs: make([]string, 0, len(args)),
		command: p.Command,
		lookup:  p.makeLookup(),
	}

	for !s.eof() {
		arg := s.pop()

		// When PassDoubleDash is set and we encounter a --, then
		// simply append all the rest as arguments and break out
		if (p.Options&PassDoubleDash) != None && arg == "--" {
			s.retargs = append(s.retargs, s.args...)
			break
		}

		if !argumentIsOption(arg) {
			// Note: this also sets s.err, so we can just check for
			// nil here and use s.err later
			if p.parseNonOption(s) != nil {
				break
			}

			continue
		}

		var err error
		var option *Option

		prefix, optname, islong := stripOptionPrefix(arg)
		optname, argument := splitOption(prefix, optname, islong)

		if islong {
			option, err = p.parseLong(s, optname, argument)
		} else {
			option, err = p.parseShort(s, optname, argument)
		}

		if err != nil {
			ignoreUnknown := (p.Options & IgnoreUnknown) != None
			parseErr := wrapError(err)

			if !(parseErr.Type == ErrUnknownFlag && ignoreUnknown) {
				s.err = parseErr
				break
			}

			if ignoreUnknown {
				s.retargs = append(s.retargs, arg)
			}
		} else {
			delete(s.lookup.required, option)
		}
	}

	if s.err == nil {
		s.checkRequired()
	}

	if s.err != nil {
		return nil, p.printError(s.err)
	}

	if len(s.command.commands) != 0 {
		return nil, p.printError(s.estimateCommand())
	} else if cmd, ok := s.command.data.(Commander); ok {
		return nil, p.printError(cmd.Execute(s.retargs))
	}

	return s.retargs, nil
}


text:
package org.jabref.gui.importer;

import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.SortedSet;
import java.util.stream.Collectors;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;

import javafx.stage.FileChooser;

import org.jabref.Globals;
import org.jabref.gui.DialogService;
import org.jabref.gui.FXDialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.actions.MnemonicAwareAction;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileExtensions;
import org.jabref.preferences.JabRefPreferences;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ImportFormats {

    private static final Log LOGGER = LogFactory.getLog(ImportFormats.class);

    private ImportFormats() {
    }

    /**
     * Create an AbstractAction for performing an Import operation.
     * @param frame The JabRefFrame of this JabRef instance.
     * @param openInNew Indicate whether the action should open into a new database or
     *  into the currently open one.
     * @return The action.
     */
    public static AbstractAction getImportAction(JabRefFrame frame, boolean openInNew) {

        class ImportAction extends MnemonicAwareAction {

            private final boolean newDatabase;

            public ImportAction(boolean newDatabase) {
                this.newDatabase = newDatabase;

                if (newDatabase) {
                    putValue(Action.NAME, Localization.menuTitle("Import into new library"));
                    putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_NEW_DATABASE));
                } else {
                    putValue(Action.NAME, Localization.menuTitle("Import into current library"));
                    putValue(Action.ACCELERATOR_KEY,
                            Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_CURRENT_DATABASE));
                }
            }

            @Override
            public void actionPerformed(ActionEvent e) {

                SortedSet<Importer> importers = Globals.IMPORT_FORMAT_READER.getImportFormats();
                List<FileExtensions> extensions = importers.stream().map(Importer::getExtensions)
                        .collect(Collectors.toList());
                FileChooser.ExtensionFilter allImports = ImportFileFilter
                        .convert(Localization.lang("Available import formats"), importers);

                FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
                        .addExtensionFilters(extensions)
                        .withInitialDirectory(Globals.prefs.get(JabRefPreferences.IMPORT_WORKING_DIRECTORY))
                        .build();
                DialogService ds = new FXDialogService();

                FileChooser fs = ds.getConfiguredFileChooser(fileDialogConfiguration);
                fs.getExtensionFilters().add(0, allImports);
                fs.setSelectedExtensionFilter(allImports);
                File f = DefaultTaskExecutor
                        .runInJavaFXThread(() -> fs.showOpenDialog(null));
                Optional<Path> selectedFile = Optional.ofNullable(f).map(File::toPath);
                FileChooser.ExtensionFilter selectedExtension = fs.getSelectedExtensionFilter();
                // Add file filter for all supported types

                selectedFile.ifPresent(file -> {
                    try {
                        if (!Files.exists(file)) {
                            JOptionPane.showMessageDialog(frame,
                                    Localization.lang("File not found") + ": '" + file.getFileName() + "'.",
                                    Localization.lang("Import"), JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        Optional<Importer> format = ImportFileFilter.convert(selectedExtension, importers);
                        ImportMenuItem importMenu = new ImportMenuItem(frame, newDatabase, format.orElse(null));
                        importMenu.automatedImport(Collections.singletonList(file.toString()));
                        // Set last working dir for import
                        Globals.prefs.put(JabRefPreferences.IMPORT_WORKING_DIRECTORY, file.getParent().toString());
                    } catch (Exception ex) {
                        LOGGER.warn("Cannot import file", ex);
                    }
                });
            }
        }

        return new ImportAction(openInNew);
    }
}


text:
package Paws::MachineLearning::DescribeMLModelsOutput;
  use Moose;
  has NextToken => (is => 'ro', isa => 'Str');
  has Results => (is => 'ro', isa => 'ArrayRef[Paws::MachineLearning::MLModel]');

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::MachineLearning::DescribeMLModelsOutput

=head1 ATTRIBUTES

=head2 NextToken => Str

The ID of the next page in the paginated results that indicates at
least one more page follows.

=head2 Results => ArrayRef[L<Paws::MachineLearning::MLModel>]

A list of C<MLModel> that meet the search criteria.

=head2 _request_id => Str

=cut

1;


text:
/* 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.
 */
package org.camunda.bpm.engine.impl.variable.serializer;

import java.io.InputStream;

import org.camunda.bpm.engine.impl.core.variable.value.UntypedValueImpl;
import org.camunda.bpm.engine.impl.persistence.entity.ByteArrayEntity;
import org.camunda.bpm.engine.impl.util.IoUtil;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.BytesValue;
import org.camunda.bpm.engine.variable.value.TypedValue;

/**
 * @author Tom Baeyens
 * @author Daniel Meyer
 */
public class ByteArrayValueSerializer extends PrimitiveValueSerializer<BytesValue> {

  public ByteArrayValueSerializer() {
    super(ValueType.BYTES);
  }

  public BytesValue convertToTypedValue(UntypedValueImpl untypedValue) {
    Object value = untypedValue.getValue();
    if (value instanceof byte[]) {
      return Variables.byteArrayValue((byte[]) value);
    } else {
      byte[] data = IoUtil.readInputStream((InputStream) value, null);
      return Variables.byteArrayValue(data);
    }
  }

  public BytesValue readValue(ValueFields valueFields) {
    return Variables.byteArrayValue(getBytes(valueFields));
  }

  public void writeValue(BytesValue variableValue, ValueFields valueFields) {
    setBytes(valueFields, variableValue.getValue());
  }

  @Override
  protected boolean canWriteValue(TypedValue typedValue) {
    return super.canWriteValue(typedValue) || typedValue.getValue() instanceof InputStream;
  }

  public static byte[] getBytes(ValueFields valueFields) {
    byte[] byteArray = null;
    if (valueFields.getByteArrayValue() != null) {
      byteArray = valueFields.getByteArrayValue().getBytes();
    }
    return byteArray;
  }

  public static void setBytes(ValueFields valueFields, byte[] bytes) {
    ByteArrayEntity byteArray = valueFields.getByteArrayValue();

    if (byteArray == null) {
      valueFields.setByteArrayValue(bytes);
    } else {
      byteArray.setBytes(bytes);
    }
  }

}


text:
class BrowseController < ApplicationController

  # GET browse
  def index()
    @product_results = Product.all
  end

  # POST browse
  def create()

  end

  # AJAX ready call for search.
  # Note: JQuery ajax is not parsed for proper parameters.
  # Case insensitive
  def search()
    name = params[:search_form][:search_bar]
    name = name.downcase
    cat = params[:search_form][:category]

    if (name.strip != "" || !cat.nil?)
      @product_results = Product.where("LOWER(unique_name) LIKE ?", "%#{name}%")
      if !cat.nil? && cat.to_i >= 0
          @product_results = @product_results.where(:category_id => cat)
      end
    else
      @product_results = Product.all
    end
    render :layout=>false
  end
end


text:
import { BaseCustomElement, reflectPropertiesToAttributes } from '../utils';

class MaterialBadge extends BaseCustomElement {

  createdCallback() {
    this.classList.add('mdl-badge');
  }

  attributeChangedCallback(attrName, oldVal, newVal) {
    this.classList.toggle('mdl-badge--overlap', this.overlap);
    this.classList.toggle('mdl-badge--no-background', this.noBackground);
    if (attrName === 'text') {
      this.setAttribute('data-badge', newVal);
    }
  }

}

export default reflectPropertiesToAttributes(MaterialBadge, [
  { propName: 'text', attrName: 'data-badge', propType: String },
  { propName: 'overlap' },
  { propName: 'noBackground' },
])


text:
package com.mmnaseri.cs.skiena.ch03.s3;

import com.mmnaseri.cs.clrs.common.Sorter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * @author Mohammad Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (11/12/16, 10:28 AM)
 */
public abstract class BaseSortTest {

    protected static final Comparator<Integer> NATURAL_ORDER = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return Integer.compare(o1, o2);
        }
    };

    protected abstract Sorter<Integer> getSorter(Comparator<Integer> comparator);

    @DataProvider
    public Object[][] arrayProvider() {
        final List<Integer[]> arrays = new ArrayList<>();
        final Random random = new Random();
        for (int i = 0; i < 100; i++) {
            final Integer[] integers = new Integer[random.nextInt(100)];
            for (int j = 0; j < integers.length; j++) {
                integers[j] = random.nextInt();
            }
            arrays.add(integers);
        }
        final List<Object[]> result = new ArrayList<>();
        for (Integer[] array : arrays) {
            result.add(new Object[]{array});
        }
        return result.toArray(new Object[result.size()][]);
    }

    @Test(dataProvider = "arrayProvider")
    public void testSorting(Integer[] array) throws Exception {
        final Integer[] copy = Arrays.asList(array).toArray(new Integer[array.length]);
        Arrays.sort(copy);
        final Sorter<Integer> sorter = getSorter(NATURAL_ORDER);
        sorter.sort(array);
        assertThat(array.length, is(copy.length));
        for (int i = 0; i < copy.length; i++) {
            Integer item = copy[i];
            assertThat(array[i], is(item));
        }
    }

}


text:
package tests.type;
/**
 * This tests an analyzers ability to deal with Enums as types
 *
 * Note: At the byte code level this test doesn't really test anything, but
 * analyzers dealing with source may have to have special handling for enum
 * semantics.
 *
 * @author Ben Holland
 */
public class TestEnum {

	public enum Day {
		SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
	}

	public static void main(String[] args) {
		Object o = Day.SUNDAY;
		System.out.println(o.getClass());
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />

        <link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/176/css/snower.css" media="all" />

<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/176/css/weimob-ui-1-1.css" media="all" />

<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/176/css/common.css" media="all" />

<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/176/css/home-8.css" media="all" />

<title>{Saivi:$tpl.wxname}</title>

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

		<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">

            <meta content="application/xhtml+xml;charset=UTF-8" http-equiv="Content-Type">

            <meta content="no-cache,must-revalidate" http-equiv="Cache-Control">

            <meta content="no-cache" http-equiv="pragma">

            <meta content="0" http-equiv="expires">

            <meta content="telephone=no, address=no" name="format-detection">

            <meta content="width=device-width, initial-scale=1.0" name="viewport">

            <meta name="apple-mobile-web-app-capable" content="yes" />

            <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <if condition="$homeInfo['musicurl'] neq false"><include file="Index:music"/></if>

<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/176/css/font-awesome.css?v=2013121116" media="all" />

<volist name="flash" id="so">

</volist>

<volist name="flash" id="so"><li <if condition="$i eq 1">class="on"</if>
</volist>

                											<volist name="info" id="vo"><a href="<if condition="$vo['url'] eq ''">{Saivi::U('Wap/Index/lists',array('classid'=>$vo['id'],'token'=>$vo['token']))}<else/>{Saivi:$vo.url|htmlspecialchars_decode}</if>" class="weimob-list-item">

{Saivi:$vo.name}

                    </volist>

<if condition="$iscopyright eq 1">{Saivi:$homeInfo.copyright}<else/>{Saivi:$siteCopyright}</if>

<include file="Index:styleInclude"/>

<if condition="$kefu['status'] eq '1'"></if>


text:
package org.jdb2de;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author  Rodrigo Tavares
 */
@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}


text:
package vpki

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	day  = 24 * time.Hour
	year = 365 * day

	//DefaultTTL is the default TTL the library will request for certificates
	DefaultTTL = day
	//DefaultStrength is the default strength of RSA keys generated
	DefaultStrength = 2048

	promVPKICertError = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "vpki_cert_error",
		Help: "vpki encountered an error obtaining a certificate",
	}, []string{"server_name"})
)

func init() {
	prometheus.MustRegister(promVPKICertError)
}

// SNICertifier abstracts the basic GetCertificate method used in TLSOpts, and
// also implemented by libraries like rsc.io/letsencrypt
type SNICertifier interface {
	GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)
}

// ListenAndServeTLS mostly mirrors the http.ListenAndServeTLS API, but
// generates the certificates for the server automatically via vault, with a
// short TTL. The function only needs an additional Certifier parameter which
// can generate signed certificates in order to work properly.
func ListenAndServeTLS(addr string, handler http.Handler, crt Certifier) error {
	certs := newCertCache(crt)

	if handler == nil {
		handler = http.DefaultServeMux
	}

	s := http.Server{
		Addr:    addr,
		Handler: handler,
		TLSConfig: &tls.Config{
			GetCertificate: func(h *tls.ClientHelloInfo) (c *tls.Certificate, err error) {
				defer func() {
					if err != nil {
						promVPKICertError.With(prometheus.Labels{"server_name": h.ServerName}).Inc()
					}
				}()

				if h.ServerName == "" {
					err = fmt.Errorf("Cannot generate certs without TLS SNI (no server name was indicated)")
					return
				}

				if crt, ok := crt.(SNICertifier); ok {
					c, err = crt.GetCertificate(h)
					return
				}

				c, err = certs.get(h.ServerName)
				return
			},
		},
	}

	return s.ListenAndServeTLS("", "")
}


text:
module FFaker
  module PhoneNumberRU
    extend ModuleUtils
    extend self

    INTERNATIONAL_COUNTRY_PREFIX = '+7'.freeze
    COUNTRY_PREFIX = '8'.freeze
    TOLL_FREE_PREFIX = '800'.freeze

    # Generate general phone number with international country code
    #   +7 929 933 24 99
    #   +7 851 921 35 92
    #
    def international_phone_number
      case rand(0..1)
      when 0 then international_mobile_phone_number
      when 1 then international_home_work_phone_number
      end
    end

    # Generate mobile phone number with international country code
    #   +7 929 933 24 99
    #   +7 978 921 35 92
    #
    def international_mobile_phone_number
      build_phone_number(international_country_code, mobile_phone_prefix)
    end

    # Generate home or work phone number with international country code
    #   +7 842 933 24 99
    #   +7 851 921 35 92
    #
    def international_home_work_phone_number
      build_phone_number(international_country_code, home_work_phone_prefix)
    end

    # Generate toll free phone number with international country code
    #   +7 800 413 01 33
    #   +7 800 153 55 22
    #
    def international_toll_free_number
      build_phone_number(international_country_code, TOLL_FREE_PREFIX)
    end

    # Generate general phone number with internal country code
    #   8 999 044 31 33
    #   8 843 944 33 33
    #
    def phone_number
      case rand(0..1)
      when 0 then mobile_phone_number
      when 1 then home_work_phone_number
      end
    end

    # Generate mobile phone number with internal country code
    #   8 949 232 22 22
    #   8 999 331 23 12
    #
    def mobile_phone_number
      build_phone_number(country_code, mobile_phone_prefix)
    end

    # Generate home or work phone number with internal country code
    #   8 011 232 22 22
    #   8 836 331 23 12
    #
    def home_work_phone_number
      build_phone_number(country_code, home_work_phone_prefix)
    end

    # Generate toll free phone number with internal country code
    #   8 800 413 01 33
    #   8 800 153 55 22
    #
    def toll_free_number
      build_phone_number(country_code, TOLL_FREE_PREFIX)
    end

    # International country code
    #   +7
    #
    def international_country_code
      INTERNATIONAL_COUNTRY_PREFIX
    end

    # Internal country code
    #   8
    #
    def country_code
      COUNTRY_PREFIX
    end

    # Home or work phone prefix
    #  081
    #  301
    #
    def home_work_phone_prefix
      fetch_sample(HOME_PHONE_PREFIXES)
    end

    # Mobile phone prefix
    #  929
    #  978
    #
    def mobile_phone_prefix
      fetch_sample(MOBILE_PHONE_PREFIXES)
    end

    private

    # Build phone number by country_code and prefix
    #
    def build_phone_number(country_code, prefix)
      "#{country_code} #{prefix} #{FFaker.numerify('###-##-##')}"
    end
  end
end


text:
namespace uc
{
    namespace pso
    {
        namespace parser
        {
            template <typename iterator, typename error_handler > struct import : public qi::grammar < iterator, ast::identifier(), ascii::space_type  >
            {
                using base = qi::grammar < iterator, ast::identifier(), ascii::space_type >;

                import( error_handler& e )  : base (m_start)
                {
                    //qi::char_type   char_;
                    //qi::uint_type   uint_;
                    //qi::raw_type    raw;
                    //qi::lexeme_type lexeme;
                    //qi::alpha_type  alpha;
                    //qi::digit_type  digit;
                    qi::lit_type    lit;

                    m_identifier = lexeme[(alpha | '_') > *( alpha | digit | '_')];
                    m_start = lit("import") > m_identifier;

                    {

                        using boost::phoenix::function;
                        using error_handler_function    = function < error_handler >;
                        using annotation_function       = function < annotation<iterator> >;

                        auto success = annotation_function( annotation<iterator>(e.m_iters, e.m_first) );

                        qi::_1_type     _1;
                        //qi::_3_type     _3;
                        qi::_val_type   _val;

                        using qi::on_error;
                        using qi::on_success;
                        using qi::fail;

                        //on_error<fail>(m_start, error_handler_function(e)( _3));
                        on_success(m_start, success(_val, _1));
                    }
                }

                qi::rule < iterator, std::string(), ascii::space_type >      m_identifier;
                qi::rule < iterator, ast::identifier(), ascii::space_type >  m_start;
            };

            template <typename iterator, typename error_handler > inline auto make_import(const error_handler& e)
            {
                return identifier<iterator, error_handler>(e);
            }

         }

    }
}


text:
post: layout
title: We win, THANK YOU, Jackson County voters
tags: lead
published: true
---

In the end, it was a rout.

Jackson County voters saw through the fog, the mist and the smoke of the proponents' $2 million campaign and sent it crashing to defeat.

I said all along that the proposed half-cent sales tax for translational medical research was the worst tax proposal I had seen in my 44 years in Kansas City. Fittingly, it was the worst defeat I have seen for any issue during that same period.

By the time the votes had been counted, it was an 84 percent to 16 percent margin.

Stunning. Amazing. Almost incomprehensible.

And yet, fitting.

The members of the **Civic Council of Greater Kansas City**, which brought us this monstrosity, need to go back to what they do best -- running their businesses.

Leave the politics to government. If you like an issue, support it. If you don't, oppose it. Just don't propose anything; let the governments make the proposals.

As for local governments, we voters sent a clear message that we will carefully analyze any new tax proposals that the Kansas City Council and the Jackson County Legislature decide to put on the ballot.

Those governments, especially county legislature, need to be more careful in the future regarding what kinds of measures the put before voters.

It's not good enough to put up a stinking, awful proposal, like Question 1, and say, "Let the voters decide." No, city and county elective bodies need to carefully consider if a proposal is _worthy_ of being put to a public vote. Does it make sense? Will it benefit the vast majority of residents? Is it worth the cost?

We don't want to see any more spurious issues on ballots that hit the taxpayers up for $1 million just to conduct an election. Future proposals need to be serious and worthwhile.


text:
package ari

// Asterisk represents a communication path for
// the Asterisk server for system-level resources
type Asterisk interface {

	// Info gets data about the asterisk system
	Info(key *Key) (*AsteriskInfo, error)

	// Variables returns the global asterisk variables
	Variables() AsteriskVariables

	// Logging returns the interface for working with asterisk logs
	Logging() Logging

	// Modules returns the interface for working with asterisk modules
	Modules() Modules

	// Config returns the interface for working with dynamic configuration
	Config() Config
}

// AsteriskInfo describes a running asterisk system
type AsteriskInfo struct {
	BuildInfo  BuildInfo  `json:"build"`
	ConfigInfo ConfigInfo `json:"config"`
	StatusInfo StatusInfo `json:"status"`
	SystemInfo SystemInfo `json:"system"`
}

// BuildInfo describes information about how Asterisk was built
type BuildInfo struct {
	Date    string `json:"date"`
	Kernel  string `json:"kernel"`
	Machine string `json:"machine"`
	Options string `json:"options"`
	Os      string `json:"os"`
	User    string `json:"user"`
}

// ConfigInfo describes information about the Asterisk configuration
type ConfigInfo struct {
	DefaultLanguage string  `json:"default_language"`
	MaxChannels     int     `json:"max_channels,omitempty"` //omitempty denotes an optional field, meaning the field may not be present if no value is assigned.
	MaxLoad         float64 `json:"max_load,omitempty"`
	MaxOpenFiles    int     `json:"max_open_files,omitempty"`
	Name            string  `json:"name"`  // Asterisk system name
	SetID           SetID   `json:"setid"` // Effective user/group id under which Asterisk is running
}

// SetID describes a userid/groupid pair
type SetID struct {
	Group string `json:"group"` // group id (not name? why string?)
	User  string `json:"user"`  // user id (not name? why string?)
}

// StatusInfo describes the state of an Asterisk system
type StatusInfo struct {
	LastReloadTime DateTime `json:"last_reload_time"`
	StartupTime    DateTime `json:"startup_time"`
}

// SystemInfo describes information about the Asterisk system
type SystemInfo struct {
	EntityID string `json:"entity_id"`
	Version  string `json:"version"`
}

// AsteriskVariables is an interface to interact with Asterisk global variables
type AsteriskVariables interface {

	// Get returns the value of the given variable; the ID field of the Key is the variable name
	Get(key *Key) (string, error)

	// Set sets the variable; the ID field of the Key is the variable name
	Set(key *Key, value string) error
}


text:
namespace drive {
namespace internal {

class WebkitFileStreamReaderImplTest : public ::testing::Test {
 protected:
  // Because the testee should live on IO thread, the main thread is
  // reused as IO thread, and UI thread will be run on background.
  WebkitFileStreamReaderImplTest()
      : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
  }

  void SetUp() override {
    worker_thread_.reset(new base::Thread("WebkitFileStreamReaderImplTest"));
    ASSERT_TRUE(worker_thread_->Start());

    // Initialize FakeDriveService.
    fake_drive_service_.reset(new FakeDriveService);
    ASSERT_TRUE(test_util::SetUpTestEntries(fake_drive_service_.get()));

    // Create a testee instance.
    fake_file_system_.reset(
        new test_util::FakeFileSystem(fake_drive_service_.get()));
  }

  FileSystemInterface* GetFileSystem() {
    return fake_file_system_.get();
  }

  DriveFileStreamReader::FileSystemGetter GetFileSystemGetter() {
    return base::Bind(&WebkitFileStreamReaderImplTest::GetFileSystem,
                      base::Unretained(this));
  }

  content::TestBrowserThreadBundle thread_bundle_;

  scoped_ptr<base::Thread> worker_thread_;

  scoped_ptr<FakeDriveService> fake_drive_service_;
  scoped_ptr<test_util::FakeFileSystem> fake_file_system_;
};

TEST_F(WebkitFileStreamReaderImplTest, ReadThenGetLength) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,               // offset
      base::Time()));  // expected modification time

  std::string content;
  ASSERT_EQ(net::OK, test_util::ReadAllData(reader.get(), &content));

  net::TestInt64CompletionCallback callback;
  int64 length = reader->GetLength(callback.callback());
  length = callback.GetResult(length);
  EXPECT_EQ(content.size(), static_cast<size_t>(length));
}

TEST_F(WebkitFileStreamReaderImplTest, GetLengthThenRead) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,               // offset
      base::Time()));  // expected modification time

  net::TestInt64CompletionCallback callback;
  int64 length = reader->GetLength(callback.callback());
  length = callback.GetResult(length);

  std::string content;
  ASSERT_EQ(net::OK, test_util::ReadAllData(reader.get(), &content));
  EXPECT_EQ(content.size(), static_cast<size_t>(length));
}

TEST_F(WebkitFileStreamReaderImplTest, ReadWithOffset) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");
  const int kOffset = 5;

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      kOffset,
      base::Time()));  // expected modification time

  std::string content;
  ASSERT_EQ(net::OK, test_util::ReadAllData(reader.get(), &content));

  net::TestInt64CompletionCallback callback;
  int64 length = reader->GetLength(callback.callback());
  length = callback.GetResult(length);
  EXPECT_EQ(content.size() + kOffset, static_cast<size_t>(length));
}

TEST_F(WebkitFileStreamReaderImplTest, ReadError) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("non-existing.txt");

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,               // offset
      base::Time()));  // expected modification time

  const int kBufferSize = 10;
  scoped_refptr<net::IOBuffer> io_buffer(new net::IOBuffer(kBufferSize));
  net::TestCompletionCallback callback;
  int result = reader->Read(io_buffer.get(), kBufferSize, callback.callback());
  result = callback.GetResult(result);
  EXPECT_EQ(net::ERR_FILE_NOT_FOUND, result);
}

TEST_F(WebkitFileStreamReaderImplTest, GetLengthError) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("non-existing.txt");

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,               // offset
      base::Time()));  // expected modification time

  net::TestInt64CompletionCallback callback;
  int64 result = reader->GetLength(callback.callback());
  result = callback.GetResult(result);
  EXPECT_EQ(net::ERR_FILE_NOT_FOUND, result);
}

TEST_F(WebkitFileStreamReaderImplTest, LastModification) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");

  base::Time expected_modification_time;
  ASSERT_TRUE(google_apis::util::GetTimeFromString(
      "2011-12-14T00:40:47.330Z", &expected_modification_time));

  FileError error = FILE_ERROR_FAILED;
  scoped_ptr<ResourceEntry> entry;
  fake_file_system_->GetResourceEntry(
      kDriveFile,
      google_apis::test_util::CreateCopyResultCallback(&error, &entry));
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);

  google_apis::DriveApiErrorCode status = google_apis::DRIVE_OTHER_ERROR;
  scoped_ptr<google_apis::FileResource> server_entry;
  fake_drive_service_->UpdateResource(
      entry->resource_id(),
      std::string(),  // parent_resource_id
      std::string(),  // title
      expected_modification_time, base::Time(),
      google_apis::drive::Properties(),
      google_apis::test_util::CreateCopyResultCallback(&status, &server_entry));
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(google_apis::HTTP_SUCCESS, status);

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,  // offset
      expected_modification_time));

  net::TestInt64CompletionCallback callback;
  int64 result = reader->GetLength(callback.callback());
  result = callback.GetResult(result);

  std::string content;
  ASSERT_EQ(net::OK, test_util::ReadAllData(reader.get(), &content));
  EXPECT_GE(content.size(), static_cast<size_t>(result));
}

// TODO(hashimoto): Enable this test. crbug.com/346625
TEST_F(WebkitFileStreamReaderImplTest, DISABLED_LastModificationError) {
  const base::FilePath kDriveFile =
      util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");

  scoped_ptr<WebkitFileStreamReaderImpl> reader(new WebkitFileStreamReaderImpl(
      GetFileSystemGetter(), worker_thread_->task_runner().get(), kDriveFile,
      0,  // offset
      base::Time::FromInternalValue(1)));

  net::TestInt64CompletionCallback callback;
  int64 result = reader->GetLength(callback.callback());
  result = callback.GetResult(result);
  EXPECT_EQ(net::ERR_UPLOAD_FILE_CHANGED, result);
}

}  // namespace internal
}  // namespace drive


text:
__CANEY_STREAMSV1_BEGIN

memory_chunk::memory_chunk(memory::shared_const_buf&& buffer) : m_buffer(std::move(buffer)) {}

file_size memory_chunk::bytes() const {
	return file_size{m_buffer.size()};
}

memory_chunk memory_chunk::split(file_size bytes) {
	memory_chunk result{m_buffer.shared_slice(0, boost::numeric_cast<std::size_t>(bytes.get()))};
	remove(bytes);
	return result;
}

void memory_chunk::remove(file_size bytes) {
	m_buffer = m_buffer.shared_slice(boost::numeric_cast<std::size_t>(bytes.get()));
}

boost::asio::const_buffer memory_chunk::get_const_buffer() const {
	return m_buffer;
}

namespace {
	struct chunk_split_visitor : public boost::static_visitor<chunk> {
		file_size m_bytes;
		chunk_split_visitor(file_size bytes) : m_bytes(bytes) {}

		template <typename T>
		chunk operator()(T& content) const {
			return chunk(content.split(m_bytes));
		}
	};

	struct chunk_remove_visitor : public boost::static_visitor<void> {
		file_size m_bytes;
		chunk_remove_visitor(file_size bytes) : m_bytes(bytes) {}

		template <typename T>
		void operator()(T& content) const {
			content.remove(m_bytes);
		}
	};

	struct chunk_get_const_buffer : public boost::static_visitor<caney::optional<boost::asio::const_buffer>> {
		template <typename T>
		caney::optional<boost::asio::const_buffer> operator()(T& content) const {
			return content.get_const_buffer();
		}
	};
} // anonymous namespace

chunk::chunk(memory_chunk&& chunk) : m_value(std::move(chunk)) {}

chunk::chunk(memory::shared_const_buf&& buffer) : chunk(memory_chunk(std::move(buffer))) {}

file_size chunk::bytes() const {
	return file_size(boost::get<memory_chunk>(m_value).bytes());
}

chunk chunk::split(file_size bytes) {
	return boost::apply_visitor(chunk_split_visitor(bytes), m_value);
}

void chunk::remove(file_size bytes) {
	boost::apply_visitor(chunk_remove_visitor(bytes), m_value);
}

caney::optional<boost::asio::const_buffer> chunk::get_const_buffer() const {
	return boost::apply_visitor(chunk_get_const_buffer(), m_value);
}

chunk_queue::chunk_queue(chunk&& c) {
	m_queue.emplace_back(std::move(c));
}

void chunk_queue::append(chunk&& c) {
	m_queue.emplace_back(std::move(c));
}

void chunk_queue::append(chunk_queue&& other) {
	m_queue.splice(m_queue.end(), std::move(other.m_queue));
}

bool chunk_queue::empty() const {
	return m_queue.empty();
}

void chunk_queue::clear() {
	m_queue.clear();
}

std::list<chunk> const& chunk_queue::queue() const {
	return m_queue;
}

chunk_queue chunk_queue::split(file_size bytes) {
	chunk_queue result;
	while (bytes > file_size{0}) {
		if (m_queue.empty()) std::terminate();
		if (m_queue.front().bytes() >= bytes) {
			bytes -= m_queue.front().bytes();
			// move chunk from m_queue to result.m_queue
			result.m_queue.splice(result.m_queue.end(), m_queue, m_queue.begin());
		} else {
			result.append(m_queue.front().split(bytes));
			return result;
		}
	}
	return result;
}

void chunk_queue::remove(file_size bytes) {
	while (bytes > file_size{0}) {
		if (m_queue.empty()) std::terminate();
		if (m_queue.front().bytes() >= bytes) {
			bytes -= m_queue.front().bytes();
			m_queue.pop_front();
		} else {
			m_queue.front().remove(bytes);
			return;
		}
	}
}

void foo1() {
	using Chunk = std::vector<uint8_t>;
	using filter_t = filter<Chunk>;

	std::shared_ptr<filter_t> filter = std::make_shared<filter_t>();
	connect(filter, filter);
}

void foo2() {
	using Chunk = chunk;
	using filter_t = filter<Chunk>;

	std::shared_ptr<filter_t> filter = std::make_shared<filter_t>();
	connect(filter, filter);
}

__CANEY_STREAMSV1_END


text:
package org.apache.shardingsphere.shardingjdbc.jdbc.core.context;

import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationProperties;
import org.apache.shardingsphere.underlying.executor.kernel.ExecutorKernel;
import org.apache.shardingsphere.sql.parser.SQLParserEngine;
import org.apache.shardingsphere.underlying.common.rule.BaseRule;
import org.apache.shardingsphere.underlying.common.database.type.DatabaseType;

/**
 * Runtime context.
 *
 * @param <T> type of rule
 */
public interface RuntimeContext<T extends BaseRule> extends AutoCloseable {

    /**
     * Get rule.
     *
     * @return rule
     */
    T getRule();

    /**
     * Get properties.
     *
     * @return properties
     */
    ConfigurationProperties getProperties();

    /**
     * Get database type.
     *
     * @return database type
     */
    DatabaseType getDatabaseType();

    /**
     * Get executor kernel.
     *
     * @return executor kernel
     */
    ExecutorKernel getExecutorKernel();

    /**
     * Get SQL parser engine.
     *
     * @return SQL parser engine
     */
    SQLParserEngine getSqlParserEngine();
}