text:
package pl.touk.sputnik.processor.ktlint;

import com.pinterest.ktlint.core.KtLint;
import com.pinterest.ktlint.core.RuleSet;
import com.pinterest.ktlint.core.RuleSetProvider;
import com.pinterest.ktlint.core.api.EditorConfigOverride;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pl.touk.sputnik.configuration.Configuration;
import pl.touk.sputnik.configuration.GeneralOption;
import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewProcessor;
import pl.touk.sputnik.review.ReviewResult;
import pl.touk.sputnik.review.filter.KotlinFilter;
import pl.touk.sputnik.review.transformer.FileNameTransformer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;

class KtlintProcessor implements ReviewProcessor {
    private static final String SOURCE_NAME = "ktlint";

    private final List<RuleSet> ruleSets;
    private final List<String> excludedRules;

    KtlintProcessor(Configuration configuration) {
        excludedRules = parseExcludedRules(configuration);
        ruleSets = findRuleSets();
    }

    private List<RuleSet> findRuleSets() {
        List<RuleSet> ruleSets = new ArrayList<>();
        for (RuleSetProvider ruleSetProvider : ServiceLoader.load(RuleSetProvider.class)) {
            ruleSets.add(ruleSetProvider.get());
        }
        return ruleSets;
    }

    @NotNull
    private List<String> parseExcludedRules(Configuration configuration) {
        String excludeProperty = configuration.getProperty(GeneralOption.KTLINT_EXCLUDE);
        if (excludeProperty == null) {
            return new ArrayList<>();
        }
        return Arrays.asList(excludeProperty.split(","));
    }

    @Nullable
    @Override
    public ReviewResult process(@NotNull Review review) {
        List<String> filePaths = review.getFiles(new KotlinFilter(), new FileNameTransformer());
        return processFiles(filePaths);
    }

    private ReviewResult processFiles(List<String> filePaths) {
        ReviewResult result = new ReviewResult();
        for (String filePath : filePaths) {
            String text = readFile(filePath);
            KtLint.INSTANCE.lint(new KtLint.ExperimentalParams(
                    null,
                    text,
                    ruleSets,
                    Collections.emptyMap(),
                    new LintErrorConverter(result, filePath, excludedRules),
                    false,
                    null,
                    false,
                    EditorConfigOverride.Companion.getEmptyEditorConfigOverride(),
                    false
                    )
            );
        }
        return result;
    }

    private String readFile(String filePath) {
        try {
            return IOUtils.toString(Files.newInputStream(Paths.get(filePath)));
        } catch (IOException e) {
            throw new RuntimeException("Cannot read file " + filePath, e);
        }
    }

    @NotNull
    @Override
    public String getName() {
        return SOURCE_NAME;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/MALL_C8"
    android:gravity="left"
    android:orientation="vertical"
    android:paddingBottom="88dp"
    android:paddingLeft="@dimen/interval_A"
    android:paddingRight="@dimen/interval_A">

    <TextView
        style="@style/STYLE_TITLE_BOTTOM_DIALOG"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/interval_D"
        android:paddingTop="@dimen/interval_D"
        android:text="@string/dialog_bottom_fapiao" />

    <include layout="@layout/line" />

    <LinearLayout
        android:id="@+id/dialog_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/interval_C"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingBottom="@dimen/interval_D"
        android:paddingTop="@dimen/interval_D">

        <Button
            android:id="@+id/fapiao_zengzhi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_orange"
            android:ellipsize="end"
            android:gravity="center"
            android:padding="8dp"
            android:singleLine="true"
            android:text="@string/dialog_bottom_fapiao_A"
            android:textColor="@color/MALL_C8"
            android:textSize="@dimen/dialog_text_size" />

        <Button
            android:id="@+id/fapiao_putong"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/interval_B"
            android:background="@drawable/border_normal"
            android:ellipsize="end"
            android:gravity="center"
            android:padding="8dp"
            android:singleLine="true"
            android:text="@string/dialog_bottom_fapiao_B"
            android:textColor="@color/BASE_TEXT_COLOR"
            android:textSize="@dimen/dialog_text_size" />

        <Button
            android:id="@+id/fapiao_wuxu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/interval_B"
            android:background="@drawable/border_normal"
            android:ellipsize="end"
            android:gravity="center"
            android:padding="8dp"
            android:singleLine="true"
            android:text="@string/dialog_bottom_fapiao_C"
            android:textColor="@color/BASE_TEXT_COLOR"
            android:textSize="@dimen/dialog_text_size" />

    </LinearLayout>

</LinearLayout>


text:
from typing import Any, Dict, Optional, Tuple, Text, List
import pytest

from rasa.nlu.tokenizers.tokenizer import Token
from rasa.nlu.constants import TOKENS_NAMES
from rasa.shared.nlu.constants import (
    TEXT,
    INTENT,
    RESPONSE,
    INTENT_RESPONSE_KEY,
    ACTION_TEXT,
    ACTION_NAME,
)
from rasa.shared.nlu.training_data.training_data import TrainingData
from rasa.shared.nlu.training_data.message import Message
from rasa.nlu.tokenizers.whitespace_tokenizer import WhitespaceTokenizer

def create_whitespace_tokenizer(
    config: Optional[Dict[Text, Any]] = None
) -> WhitespaceTokenizer:
    return WhitespaceTokenizer(
        {**WhitespaceTokenizer.get_default_config(), **(config if config else {}),}
    )

def test_tokens_comparison():
    x = Token("hello", 0)
    y = Token("Hello", 0)

    assert x == x
    assert y < x

    assert x != 1

    with pytest.raises(TypeError):
        assert y < "a"

@pytest.mark.parametrize(
    "text, expected_tokens, expected_indices",
    [("Forecast for lunch", ["Forecast", "for", "lunch"], [(0, 8), (9, 12), (13, 18)])],
)
def test_train_tokenizer(
    text: Text, expected_tokens: List[Text], expected_indices: List[Tuple[int]]
):
    tk = create_whitespace_tokenizer()

    message = Message.build(text=text)
    message.set(RESPONSE, text)
    message.set(INTENT, text)

    training_data = TrainingData()
    training_data.training_examples = [message]

    tk.process_training_data(training_data)

    for attribute in [RESPONSE, TEXT]:
        tokens = training_data.training_examples[0].get(TOKENS_NAMES[attribute])

        assert [t.text for t in tokens] == expected_tokens
        assert [t.start for t in tokens] == [i[0] for i in expected_indices]
        assert [t.end for t in tokens] == [i[1] for i in expected_indices]

    # check intent attribute
    tokens = training_data.training_examples[0].get(TOKENS_NAMES[INTENT])

    assert [t.text for t in tokens] == [text]

@pytest.mark.parametrize(
    "text, expected_tokens, expected_indices",
    [("Forecast for lunch", ["Forecast", "for", "lunch"], [(0, 8), (9, 12), (13, 18)])],
)
def test_train_tokenizer_e2e_actions(
    text: Text, expected_tokens: List[Text], expected_indices: List[Tuple[int]]
):
    tk = create_whitespace_tokenizer()

    message = Message.build(text=text)
    message.set(ACTION_TEXT, text)
    message.set(ACTION_NAME, text)

    training_data = TrainingData()
    training_data.training_examples = [message]

    tk.process_training_data(training_data)

    for attribute in [ACTION_TEXT, TEXT]:
        tokens = training_data.training_examples[0].get(TOKENS_NAMES[attribute])

        assert [t.text for t in tokens] == expected_tokens
        assert [t.start for t in tokens] == [i[0] for i in expected_indices]
        assert [t.end for t in tokens] == [i[1] for i in expected_indices]

@pytest.mark.parametrize(
    "text, expected_tokens, expected_indices",
    [("Forecast for lunch", ["Forecast", "for", "lunch"], [(0, 8), (9, 12), (13, 18)])],
)
def test_train_tokenizer_action_name(
    text: Text, expected_tokens: List[Text], expected_indices: List[Tuple[int]]
):
    tk = create_whitespace_tokenizer()

    message = Message.build(text=text)
    message.set(ACTION_NAME, text)

    training_data = TrainingData()
    training_data.training_examples = [message]

    tk.process_training_data(training_data)

    # check action_name attribute
    tokens = training_data.training_examples[0].get(TOKENS_NAMES[ACTION_NAME])

    assert [t.text for t in tokens] == [text]

@pytest.mark.parametrize(
    "text, expected_tokens, expected_indices",
    [("Forecast for lunch", ["Forecast", "for", "lunch"], [(0, 8), (9, 12), (13, 18)])],
)
def test_process_tokenizer(
    text: Text, expected_tokens: List[Text], expected_indices: List[Tuple[int]]
):
    tk = create_whitespace_tokenizer()

    message = Message.build(text=text)

    tk.process([message])

    tokens = message.get(TOKENS_NAMES[TEXT])

    assert [t.text for t in tokens] == expected_tokens
    assert [t.start for t in tokens] == [i[0] for i in expected_indices]
    assert [t.end for t in tokens] == [i[1] for i in expected_indices]

@pytest.mark.parametrize(
    "text, expected_tokens", [("action_listen", ["action", "listen"])]
)
def test_process_tokenizer_action_name(text: Text, expected_tokens: List[Text]):
    tk = create_whitespace_tokenizer({"intent_tokenization_flag": True})

    message = Message.build(text=text)
    message.set(ACTION_NAME, text)

    tk.process([message])

    tokens = message.get(TOKENS_NAMES[ACTION_NAME])

    assert [t.text for t in tokens] == expected_tokens

@pytest.mark.parametrize(
    "text, expected_tokens", [("I am hungry", ["I", "am", "hungry"])]
)
def test_process_tokenizer_action_test(text: Text, expected_tokens: List[Text]):
    tk = create_whitespace_tokenizer({"intent_tokenization_flag": True})

    message = Message.build(text=text)
    message.set(ACTION_NAME, text)
    message.set(ACTION_TEXT, text)

    tk.process([message])

    tokens = message.get(TOKENS_NAMES[ACTION_TEXT])
    assert [t.text for t in tokens] == expected_tokens

    message.set(ACTION_TEXT, "")
    tk.process([message])
    tokens = message.get(TOKENS_NAMES[ACTION_NAME])
    assert [t.text for t in tokens] == [text]

@pytest.mark.parametrize(
    "text, expected_tokens",
    [
        ("Forecast_for_LUNCH", ["Forecast_for_LUNCH"]),
        ("Forecast for LUNCH", ["Forecast for LUNCH"]),
    ],
)
def test_split_intent(text: Text, expected_tokens: List[Text]):
    component_config = {"intent_tokenization_flag": True, "intent_split_symbol": "+"}

    tk = create_whitespace_tokenizer(component_config)

    message = Message.build(text=text)
    message.set(INTENT, text)

    assert [t.text for t in tk._split_name(message, INTENT)] == expected_tokens

@pytest.mark.parametrize(
    "text, expected_tokens",
    [
        ("faq/ask_language", ["faq", "ask_language"]),
        ("faq/ask+language", ["faq", "ask", "language"]),
    ],
)
def test_split_intent_response_key(text, expected_tokens):
    component_config = {"intent_tokenization_flag": True, "intent_split_symbol": "+"}

    tk = create_whitespace_tokenizer(component_config)

    message = Message.build(text=text)
    message.set(INTENT_RESPONSE_KEY, text)

    assert [
        t.text for t in tk._split_name(message, attribute=INTENT_RESPONSE_KEY)
    ] == expected_tokens

@pytest.mark.parametrize(
    "token_pattern, tokens, expected_tokens",
    [
        (
            None,
            [Token("hello", 0), Token("there", 6)],
            [Token("hello", 0), Token("there", 6)],
        ),
        (
            "",
            [Token("hello", 0), Token("there", 6)],
            [Token("hello", 0), Token("there", 6)],
        ),
        (
            r"(?u)\b\w\w+\b",
            [Token("role-based", 0), Token("access-control", 11)],
            [
                Token("role", 0),
                Token("based", 5),
                Token("access", 11),
                Token("control", 18),
            ],
        ),
        (
            r".*",
            [Token("role-based", 0), Token("access-control", 11)],
            [Token("role-based", 0), Token("access-control", 11)],
        ),
        (
            r"(test)",
            [Token("role-based", 0), Token("access-control", 11)],
            [Token("role-based", 0), Token("access-control", 11)],
        ),
    ],
)
def test_apply_token_pattern(
    token_pattern: Text, tokens: List[Token], expected_tokens: List[Token]
):
    component_config = {"token_pattern": token_pattern}

    tokenizer = create_whitespace_tokenizer(component_config)
    actual_tokens = tokenizer._apply_token_pattern(tokens)

    assert len(actual_tokens) == len(expected_tokens)
    for actual_token, expected_token in zip(actual_tokens, expected_tokens):
        assert actual_token.text == expected_token.text
        assert actual_token.start == expected_token.start
        assert actual_token.end == expected_token.end

@pytest.mark.parametrize(
    "text, expected_tokens",
    [
        ("Forecast_for_LUNCH", ["Forecast_for_LUNCH"]),
        ("Forecast for LUNCH", ["Forecast for LUNCH"]),
        ("Forecast+for+LUNCH", ["Forecast", "for", "LUNCH"]),
    ],
)
def test_split_action_name(text: Text, expected_tokens: List[Text]):
    component_config = {"intent_tokenization_flag": True, "intent_split_symbol": "+"}

    tk = create_whitespace_tokenizer(component_config)

    message = Message.build(text=text)
    message.set(ACTION_NAME, text)

    assert [t.text for t in tk._split_name(message, ACTION_NAME)] == expected_tokens

def test_token_fingerprints_are_unique():
    """Tests that token fingerprints are consistent across runs and machines."""
    tokens = [
        Token("testing", 2, 9, {"x": 3}, "test"),
        Token("testing", 3, 10, {"x": 3}, "test"),
        Token("working", 2, 9, {"x": 3}, "work"),
        Token("testing", 2, 9, None, "test"),
        Token("testing", 2, 9),
        Token("testing", 3),
    ]
    fingerprints = {t.fingerprint() for t in tokens}
    assert len(fingerprints) == len(tokens)


text:
<?php
namespace FrontUsers\Models;

use FrontCore\Adapters\AbstractCoreAdapter;

class FrontUsersAclRulesModel extends AbstractCoreAdapter
{
	/**
	 * Load the admin form for User Data Access Rules
	 * @return \Zend\Form\Form
	 */
	public function getUserAccessRulesForm()
	{
		$objForm = $this->getServiceLocator()->get("FrontCore\Models\SystemFormsModel")
						->getSystemForm("Core\Forms\SystemForms\AccessControl\UserAccessRuleForm");

		return $objForm;
	}//end function

	public function fetchUserDataAccessRules($user_id)
	{
		//create the request object
		$objApiRequest = $this->getApiRequestModel();

		//setup the object and specify the action
		$objApiRequest->setApiAction("users/admin/user/data/acl/$user_id");

		//request data
		$objData = $objApiRequest->performGETRequest()->getBody();

		return $objData->data;
	}//end function

	public function fetchUserDataAccessRule($user_id)
	{
		//create the request object
		$objApiRequest = $this->getApiRequestModel();

		//setup the object and specify the action
		$objApiRequest->setApiAction("users/admin/user/data/acl/$user_id");
	}//end function

	public function createUserDataAccessRules($user_id, $arr_data)
	{
		//trigger pre event
		$result = $this->getEventManager()->trigger(__FUNCTION__ . ".pre", $this, array("user_id" => $user_id, "arr_data" => $arr_data));

		//create the request object
		$objApiRequest = $this->getApiRequestModel();

		//setup the object and specify the action
		$objApiRequest->setApiAction("users/admin/user/data/acl/$user_id");

		$objData = $objApiRequest->performPOSTRequest($arr_data)->getBody();
		$objUserDataAccessRules = $objData->data;

		//trigger post event
		$result = $this->getEventManager()->trigger(__FUNCTION__ . ".post", $this, array("user_id" => $user_id, "arr_data" => $arr_data, "objUserDataAccessRules" => $objUserDataAccessRules));

		return $objUserDataAccessRules;
	}//end function
}//end class


text:
module ServiceContract
  module Assertions

    def assert_endpoint_response(data, endpoint, allow_nil = true)
      assert_data_matches_type(data, endpoint.response_type, endpoint.name, allow_nil)
    end

    def assert_data_matches_type(data, type, name, allow_nil = true)
      # Skip out if object is nil and allowed to be nil
      return true if data.nil? && allow_nil

      # basic type checking
      assert type.valid_type?(data), "expected `#{data}` (#{name}) to be one of #{type.valid_ruby_types}, instead got a #{data.class.name}"
      assert type.valid_value?(data), "#{data} is not an allowed value of type: #{type.name}"

      # check subtype
      if type.subtype
        data.each do |datum|
          assert_data_matches_type(datum, type.subtype, type.name, allow_nil)
        end
      end

      # check subfields
      type.fields.each do |field|
        #Does data contain attributes that the contract doesn't specify?
        data_extra_attrs = (data.keys.map(&:to_sym) - type.fields.map{|n| n.name.to_sym})
        assert_equal 0, data_extra_attrs.size, "#{type.name} contains attributes not described in contract: #{data_extra_attrs.join(',')}"

        # ensure the field is present
        value = data.fetch(field.name) do
          data.fetch(field.name.to_sym) do
            assert false, "expected #{type.name} to have attribute: #{field.name}"
          end
        end

        # check the data type
        assert_data_matches_type(value, field.type, field.name, allow_nil)
      end
    end

  end
end


text:
package org.apache.derby.client.am;

import java.io.PrintWriter;
import java.sql.BatchUpdateException;
import java.sql.Types;
import org.apache.derby.jdbc.ClientDriver;
import org.apache.derby.shared.common.reference.JDBC40Translation;
import org.apache.derby.shared.common.reference.SQLState;

public abstract class Agent {
    SqlException accumulatedReadExceptions_ = null;

    private boolean enableBatchedExceptionTracking_;
    private int batchedExceptionLabelIndex_;
    private boolean[] batchedExceptionGenerated_;

    ClientConnection connection_; // made friendly for lobs only, refactor !!

    SectionManager sectionManager_ = null;

    public LogWriter logWriter_ = null;

    final CrossConverters crossConverters_;

    // Exceptions that occur on dnc's implementation of SqlException.getMessage() via stored proc
    // cannot be thrown on the getMessage() invocation because the signature of getMessage() does not
    // allow for throwing an exception.
    // Therefore, we must save the exception and throw it at our very first opportunity.
    private SqlException deferredException_;

    void checkForDeferredExceptions() throws SqlException {
        if (deferredException_ != null) {
            SqlException temp = deferredException_;
            deferredException_ = null;
            throw temp;
        }
    }

    /**
     * Checks whether a data type is supported for
     * setObject(int, Object, int) and
     * setObject(int, Object, int, int).
     *
     * @param dataType the data type to check
     * @exception SqlException if the type is not supported
     */
    void checkForSupportedDataType(int dataType) throws SqlException {

        // JDBC 4.0 javadoc for setObject() says:
        //
        // Throws: (...) SQLFeatureNotSupportedException - if
        // targetSqlType is a ARRAY, BLOB, CLOB, DATALINK,
        // JAVA_OBJECT, NCHAR, NCLOB, NVARCHAR, LONGNVARCHAR, REF,
        // ROWID, SQLXML or STRUCT data type and the JDBC driver does
        // not support this data type
        //
        // Of these types, we only support BLOB, CLOB and
        // (sort of) JAVA_OBJECT.

        switch (dataType) {
        case Types.ARRAY:
        case Types.DATALINK:
        case Types.DISTINCT:
        case Types.NCHAR:
        case Types.NCLOB:
        case Types.NVARCHAR:
        case Types.LONGNVARCHAR:
        case Types.NULL:
        case Types.OTHER:
        case Types.REF:
        case JDBC40Translation.REF_CURSOR:
        case Types.ROWID:
        case Types.SQLXML:
        case Types.STRUCT:
            throw new SqlException
                (logWriter_,
                 new ClientMessageId(SQLState.DATA_TYPE_NOT_SUPPORTED),
                 ClientTypes.getTypeString(dataType));
        }
    }

    void accumulateDeferredException(SqlException e) {
        if (deferredException_ == null) {
            deferredException_ = e;
        } else {
            deferredException_.setNextException(e);
        }
    }

    protected Agent(ClientConnection connection, LogWriter logWriter) {
        connection_ = connection;
        logWriter_ = logWriter;
        crossConverters_ = new CrossConverters(this);
    }

    private void resetAgent(LogWriter logWriter) {
        // sectionManager_ is set elsewhere
        accumulatedReadExceptions_ = null;
        enableBatchedExceptionTracking_ = false;
        batchedExceptionLabelIndex_ = 0;
        batchedExceptionGenerated_ = null;
        logWriter_ = logWriter;
        deferredException_ = null;
    }

    void resetAgent(
        ClientConnection connection,
        LogWriter logWriter,
        int loginTimeout,
        String server,
        int port) throws SqlException {

        resetAgent(logWriter);
        resetAgent_(logWriter, loginTimeout, server, port);
    }

    abstract protected void resetAgent_(LogWriter logWriter, int loginTimeout, String server, int port) throws SqlException;

    //-------------------- entry points ------------------------------------------

    public final boolean loggingEnabled() {
        return logWriter_ != null;
    }

    public final void setLogWriter(LogWriter logWriter) {
        synchronized (connection_) {
            if (logWriter_ != null) {
                logWriter_.close();
            }
            logWriter_ = logWriter;
        }
    }

    public final PrintWriter getLogWriter() {
        return (logWriter_ == null) ? null : logWriter_.printWriter_;
    }

    //----------------------------------------------------------------------------

    public final void accumulateReadException(SqlException e) {
        if (enableBatchedExceptionTracking_) {
            batchedExceptionGenerated_[batchedExceptionLabelIndex_] = true;
            labelAsBatchedException(e, batchedExceptionLabelIndex_);
        }
        if (accumulatedReadExceptions_ == null) {
            accumulatedReadExceptions_ = e;
        } else {
            accumulatedReadExceptions_.setNextException(e);
        }
    }

    // Called only for disconnect event
    private void accumulateDisconnectException(DisconnectException e) {
        if (enableBatchedExceptionTracking_) {
            batchedExceptionGenerated_[batchedExceptionLabelIndex_] = true;
            labelAsBatchedException(e, batchedExceptionLabelIndex_);
        }
        if (accumulatedReadExceptions_ != null) {
            e.setNextException(accumulatedReadExceptions_);
        }

        accumulatedReadExceptions_ = null;
    }

    // For now, it looks like the only time we accumulate chain breaking exceptions
    // is for disconnect exceptions.
    public final void accumulateChainBreakingReadExceptionAndThrow(DisconnectException e) throws DisconnectException {
        accumulateDisconnectException(e); // tacks disconnect exc to end of chain
        markChainBreakingException_(); // sets a severity code in the NET agent
        throw e; // disconnect will be caught in Reply classes, and front of original chain thrown
    }

    abstract protected void markChainBreakingException_();

    abstract public void checkForChainBreakingException_() throws SqlException;

    private final void enableBatchedExceptionTracking(int batchSize) {
        enableBatchedExceptionTracking_ = true;
        batchedExceptionGenerated_ = new boolean[batchSize];
        batchedExceptionLabelIndex_ = 0;
    }

    final void disableBatchedExceptionTracking() {
        enableBatchedExceptionTracking_ = false;
    }

    public final void setBatchedExceptionLabelIndex(int index) {
        batchedExceptionLabelIndex_ = index;
    }

    private final SqlException labelAsBatchedException(SqlException e, int index) {
        SqlException firstInChain = e;
        while (e != null) {
            e.setBatchPositionLabel(index);
            e = (SqlException) e.getNextException();
        }
        return firstInChain;
    }

    protected final void checkForExceptions() throws SqlException {
        if (accumulatedReadExceptions_ != null) {
            SqlException e = accumulatedReadExceptions_;
            accumulatedReadExceptions_ = null;
            throw e;
        }
    }

    public final void flow(ClientStatement statement) throws SqlException {
        endWriteChain();
        flush_();
        beginReadChain(statement);
    }

    final void flowBatch(ClientStatement statement, int batchSize)
            throws SqlException {
        endBatchedWriteChain();
        flush_();
        beginBatchedReadChain(statement, batchSize);
    }

    public final void flowOutsideUOW() throws SqlException {
        endWriteChain();
        flush_();
        beginReadChainOutsideUOW();
    }

    // flush() means to send all chained requests.
    abstract public void flush_() throws DisconnectException;

    // Close client resources associated with this agent, such as socket and streams for the net.
    abstract public void close_() throws SqlException;

    public void close() throws SqlException {
        close_();
        if (logWriter_ != null) {
            logWriter_.close();
        }
    }

    final void disconnectEvent() {
        // closes client-side resources associated with database connection
        try {
            close();
        } catch (SqlException doNothing) {
        }
        connection_.completeChainBreakingDisconnect();
    }

    abstract public void beginWriteChainOutsideUOW() throws SqlException;

    public void beginWriteChain(ClientStatement statement) throws SqlException {
        connection_.writeTransactionStart(statement);
    }

    final void beginBatchedWriteChain(ClientStatement statement)
            throws SqlException {
        beginWriteChain(statement);
    }

    abstract protected void endWriteChain();

    private final void endBatchedWriteChain() {
        endWriteChain();
    }

    protected void beginReadChain(ClientStatement statement)
            throws SqlException {
        connection_.readTransactionStart();
    }

    private void beginBatchedReadChain(
        ClientStatement statement,
        int batchSize)
            throws SqlException {

        enableBatchedExceptionTracking(batchSize);
        beginReadChain(statement);
    }

    protected void beginReadChainOutsideUOW() throws SqlException {
    }

    public void endReadChain() throws SqlException {
        checkForExceptions();
    }

    final void endBatchedReadChain(long[] updateCounts,
                                   SqlException accumulatedExceptions)
            throws BatchUpdateException {

        disableBatchedExceptionTracking();
        for (int i = 0; i < batchedExceptionGenerated_.length; i++) {
            if (batchedExceptionGenerated_[i]) {
                updateCounts[i] = -3;
            }
        }
        if (accumulatedExceptions == null) {
            try {
                endReadChain();
            } catch (SqlException e) {
                accumulatedExceptions = e;
            }
        }
        if (accumulatedExceptions != null) {
            throw ClientDriver.getFactory().newBatchUpdateException(logWriter_,
                new ClientMessageId(SQLState.BATCH_NON_ATOMIC_FAILURE),
                null, updateCounts, accumulatedExceptions);
        }
    }
}


text:
<?php
namespace Dropbox;

/**
 * Helper functions to validate arguments.
 *
 * @internal
 */
class Checker
{
    static function throwError($argName, $argValue, $expectedTypeName)
    {
        if ($argValue === null) throw new \InvalidArgumentException("'$argName' must not be null");

        if (is_object($argValue)) {
            // Class type.
            $argTypeName = get_class($argValue);
        } else {
            // Built-in type.
            $argTypeName = gettype($argValue);
        }
        throw new \InvalidArgumentException("'$argName' has bad type; expecting $expectedTypeName, got $argTypeName");
    }

    static function argResource($argName, $argValue)
    {
        if (!is_resource($argValue)) self::throwError($argName, $argValue, "resource");
    }

    static function argCallable($argName, $argValue)
    {
        if (!is_callable($argValue)) self::throwError($argName, $argValue, "callable");
    }

    static function argBool($argName, $argValue)
    {
        if (!is_bool($argValue)) self::throwError($argName, $argValue, "boolean");
    }

    static function argArray($argName, $argValue)
    {
        if (!is_array($argValue)) self::throwError($argName, $argValue, "array");
    }

    static function argString($argName, $argValue)
    {
        if (!is_string($argValue)) self::throwError($argName, $argValue, "string");
    }

    static function argStringOrNull($argName, $argValue)
    {
        if ($argValue === null) return;
        if (!is_string($argValue)) self::throwError($argName, $argValue, "string");
    }

    static function argStringNonEmpty($argName, $argValue)
    {
        if (!is_string($argValue)) self::throwError($argName, $argValue, "string");
        if (strlen($argValue) === 0) throw new \InvalidArgumentException("'$argName' must be non-empty");
    }

    static function argStringNonEmptyOrNull($argName, $argValue)
    {
        if ($argValue === null) return;
        if (!is_string($argValue)) self::throwError($argName, $argValue, "string");
        if (strlen($argValue) === 0) throw new \InvalidArgumentException("'$argName' must be non-empty");
    }

    static function argNat($argName, $argValue)
    {
        if (!is_int($argValue)) self::throwError($argName, $argValue, "int");
        if ($argValue < 0) throw new \InvalidArgumentException("'$argName' must be non-negative (you passed in $argValue)");
    }

    static function argNatOrNull($argName, $argValue)
    {
        if ($argValue === null) return;
        if (!is_int($argValue)) self::throwError($argName, $argValue, "int");
        if ($argValue < 0) throw new \InvalidArgumentException("'$argName' must be non-negative (you passed in $argValue)");
    }

    static function argIntPositive($argName, $argValue)
    {
        if (!is_int($argValue)) self::throwError($argName, $argValue, "int");
        if ($argValue < 1) throw new \InvalidArgumentException("'$argName' must be positive (you passed in $argValue)");
    }

    static function argIntPositiveOrNull($argName, $argValue)
    {
        if ($argValue === null) return;
        if (!is_int($argValue)) self::throwError($argName, $argValue, "int");
        if ($argValue < 1) throw new \InvalidArgumentException("'$argName' must be positive (you passed in $argValue)");
    }
}


text:
<?php
namespace Person\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Person\Model\Person;
use Person\Form\PersonForm;

class PersonController extends AbstractActionController{

	protected $personTable;

	public function indexAction(){
		return new ViewModel(array(
				'persons' => $this->getPersonTable()->fetchAll()
		));
	}

	public function addAction(){
		$form = new PersonForm();
		$form->get('submit')->setValue('Add');

		$request = $this->getRequest();
		if ($request->isPost()) {
			$person = new Person();
			$form->setInputFilter($person->getInputFilter());
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$person->exchangeArray($form->getData());
				$this->getPersonTable()->savePerson($person);

				// Redirect to list of persons
				return $this->redirect()->toRoute('person');
			}
		}
		return array('form' => $form);
	}

	public function editAction(){
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('person', array(
					'action' => 'add'
			));
		}

		//TODO Modify and check on file
		try {
			$person = $this->getPersonTable()->getPerson($id);
		}
		catch (\Exception $ex) {
			return $this->redirect()->toRoute('person', array(
					'action' => 'index'
			));
		}

		$form  = new PersonForm();
		$form->bind($person);
		$form->get('submit')->setAttribute('value', 'Edit');

		$request = $this->getRequest();
		if ($request->isPost()) {
			$form->setInputFilter($person->getInputFilter());
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$this->getPersonTable()->savePerson($person);

				// Redirect to list of persons
				return $this->redirect()->toRoute('person');
			}
		}

		return array(
				'id' => $id,
				'form' => $form,
		);
	}

	public function deleteAction(){

	}

	public function getPersonTable(){
		if (!$this->personTable) {
			$sm = $this->getServiceLocator();
			$this->personTable = $sm->get('Person\Model\PersonTable');
		}
		return $this->personTable;
	}
}


text:
"""A simple engine that talks to a controller over 0MQ.
it handles registration, etc. and launches a kernel
connected to the Controller's Schedulers.

Authors:

* Min RK
"""
#-----------------------------------------------------------------------------
#  Copyright (C) 2010-2011  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

from __future__ import print_function

import sys
import time
from getpass import getpass

import zmq
from zmq.eventloop import ioloop, zmqstream

from IPython.external.ssh import tunnel
# internal
from IPython.utils.traitlets import (
    Instance, Dict, Integer, Type, CFloat, Unicode, CBytes, Bool
)
from IPython.utils.py3compat import cast_bytes

from IPython.parallel.controller.heartmonitor import Heart
from IPython.parallel.factory import RegistrationFactory
from IPython.parallel.util import disambiguate_url

from IPython.zmq.session import Message
from IPython.zmq.ipkernel import Kernel, IPKernelApp

class EngineFactory(RegistrationFactory):
    """IPython engine"""

    # configurables:
    out_stream_factory=Type('IPython.zmq.iostream.OutStream', config=True,
        help="""The OutStream for handling stdout/err.
        Typically 'IPython.zmq.iostream.OutStream'""")
    display_hook_factory=Type('IPython.zmq.displayhook.ZMQDisplayHook', config=True,
        help="""The class for handling displayhook.
        Typically 'IPython.zmq.displayhook.ZMQDisplayHook'""")
    location=Unicode(config=True,
        help="""The location (an IP address) of the controller.  This is
        used for disambiguating URLs, to determine whether
        loopback should be used to connect or the public address.""")
    timeout=CFloat(2,config=True,
        help="""The time (in seconds) to wait for the Controller to respond
        to registration requests before giving up.""")
    sshserver=Unicode(config=True,
        help="""The SSH server to use for tunneling connections to the Controller.""")
    sshkey=Unicode(config=True,
        help="""The SSH private key file to use when tunneling connections to the Controller.""")
    paramiko=Bool(sys.platform == 'win32', config=True,
        help="""Whether to use paramiko instead of openssh for tunnels.""")

    # not configurable:
    user_ns=Dict()
    id=Integer(allow_none=True)
    registrar=Instance('zmq.eventloop.zmqstream.ZMQStream')
    kernel=Instance(Kernel)

    bident = CBytes()
    ident = Unicode()
    def _ident_changed(self, name, old, new):
        self.bident = cast_bytes(new)
    using_ssh=Bool(False)

    def __init__(self, **kwargs):
        super(EngineFactory, self).__init__(**kwargs)
        self.ident = self.session.session

    def init_connector(self):
        """construct connection function, which handles tunnels."""
        self.using_ssh = bool(self.sshkey or self.sshserver)

        if self.sshkey and not self.sshserver:
            # We are using ssh directly to the controller, tunneling localhost to localhost
            self.sshserver = self.url.split('://')[1].split(':')[0]

        if self.using_ssh:
            if tunnel.try_passwordless_ssh(self.sshserver, self.sshkey, self.paramiko):
                password=False
            else:
                password = getpass("SSH Password for %s: "%self.sshserver)
        else:
            password = False

        def connect(s, url):
            url = disambiguate_url(url, self.location)
            if self.using_ssh:
                self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver))
                return tunnel.tunnel_connection(s, url, self.sshserver,
                            keyfile=self.sshkey, paramiko=self.paramiko,
                            password=password,
                )
            else:
                return s.connect(url)

        def maybe_tunnel(url):
            """like connect, but don't complete the connection (for use by heartbeat)"""
            url = disambiguate_url(url, self.location)
            if self.using_ssh:
                self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver))
                url,tunnelobj = tunnel.open_tunnel(url, self.sshserver,
                            keyfile=self.sshkey, paramiko=self.paramiko,
                            password=password,
                )
            return url
        return connect, maybe_tunnel

    def register(self):
        """send the registration_request"""

        self.log.info("Registering with controller at %s"%self.url)
        ctx = self.context
        connect,maybe_tunnel = self.init_connector()
        reg = ctx.socket(zmq.DEALER)
        reg.setsockopt(zmq.IDENTITY, self.bident)
        connect(reg, self.url)
        self.registrar = zmqstream.ZMQStream(reg, self.loop)

        content = dict(queue=self.ident, heartbeat=self.ident, control=self.ident)
        self.registrar.on_recv(lambda msg: self.complete_registration(msg, connect, maybe_tunnel))
        # print (self.session.key)
        self.session.send(self.registrar, "registration_request",content=content)

    def complete_registration(self, msg, connect, maybe_tunnel):
        # print msg
        self._abort_dc.stop()
        ctx = self.context
        loop = self.loop
        identity = self.bident
        idents,msg = self.session.feed_identities(msg)
        msg = Message(self.session.unserialize(msg))

        if msg.content.status == 'ok':
            self.id = int(msg.content.id)

            # launch heartbeat
            hb_addrs = msg.content.heartbeat

            # possibly forward hb ports with tunnels
            hb_addrs = [ maybe_tunnel(addr) for addr in hb_addrs ]
            heart = Heart(*map(str, hb_addrs), heart_id=identity)
            heart.start()

            # create Shell Streams (MUX, Task, etc.):
            queue_addr = msg.content.mux
            shell_addrs = [ str(queue_addr) ]
            task_addr = msg.content.task
            if task_addr:
                shell_addrs.append(str(task_addr))

            # Uncomment this to go back to two-socket model
            # shell_streams = []
            # for addr in shell_addrs:
            #     stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop)
            #     stream.setsockopt(zmq.IDENTITY, identity)
            #     stream.connect(disambiguate_url(addr, self.location))
            #     shell_streams.append(stream)

            # Now use only one shell stream for mux and tasks
            stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop)
            stream.setsockopt(zmq.IDENTITY, identity)
            shell_streams = [stream]
            for addr in shell_addrs:
                connect(stream, addr)
            # end single stream-socket

            # control stream:
            control_addr = str(msg.content.control)
            control_stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop)
            control_stream.setsockopt(zmq.IDENTITY, identity)
            connect(control_stream, control_addr)

            # create iopub stream:
            iopub_addr = msg.content.iopub
            iopub_socket = ctx.socket(zmq.PUB)
            iopub_socket.setsockopt(zmq.IDENTITY, identity)
            connect(iopub_socket, iopub_addr)

            # disable history:
            self.config.HistoryManager.hist_file = ':memory:'

            # Redirect input streams and set a display hook.
            if self.out_stream_factory:
                sys.stdout = self.out_stream_factory(self.session, iopub_socket, u'stdout')
                sys.stdout.topic = cast_bytes('engine.%i.stdout' % self.id)
                sys.stderr = self.out_stream_factory(self.session, iopub_socket, u'stderr')
                sys.stderr.topic = cast_bytes('engine.%i.stderr' % self.id)
            if self.display_hook_factory:
                sys.displayhook = self.display_hook_factory(self.session, iopub_socket)
                sys.displayhook.topic = cast_bytes('engine.%i.pyout' % self.id)

            self.kernel = Kernel(config=self.config, int_id=self.id, ident=self.ident, session=self.session,
                    control_stream=control_stream, shell_streams=shell_streams, iopub_socket=iopub_socket,
                    loop=loop, user_ns=self.user_ns, log=self.log)

            self.kernel.shell.display_pub.topic = cast_bytes('engine.%i.displaypub' % self.id)

            # FIXME: This is a hack until IPKernelApp and IPEngineApp can be fully merged
            app = IPKernelApp(config=self.config, shell=self.kernel.shell, kernel=self.kernel, log=self.log)
            app.init_profile_dir()
            app.init_code()

            self.kernel.start()
        else:
            self.log.fatal("Registration Failed: %s"%msg)
            raise Exception("Registration Failed: %s"%msg)

        self.log.info("Completed registration with id %i"%self.id)

    def abort(self):
        self.log.fatal("Registration timed out after %.1f seconds"%self.timeout)
        if self.url.startswith('127.'):
            self.log.fatal("""
            If the controller and engines are not on the same machine,
            you will have to instruct the controller to listen on an external IP (in ipcontroller_config.py):
                c.HubFactory.ip='*' # for all interfaces, internal and external
                c.HubFactory.ip='192.168.1.101' # or any interface that the engines can see
            or tunnel connections via ssh.
            """)
        self.session.send(self.registrar, "unregistration_request", content=dict(id=self.id))
        time.sleep(1)
        sys.exit(255)

    def start(self):
        dc = ioloop.DelayedCallback(self.register, 0, self.loop)
        dc.start()
        self._abort_dc = ioloop.DelayedCallback(self.abort, self.timeout*1000, self.loop)
        self._abort_dc.start()


text:
function assert(o) { if (!o) throw new Error('AssertionError') }
var generator = {
  string: function () {
    return 'string'
  },
  bool: function () {
    return true
  }
}
var r = jsonSpawn(generator)('p/a:string,z:bool')
assert(r.p.a)
assert(r.p.a === 'string')
assert(r.z)
assert(r.z === true)
document.getElementById('res').innerHTML = 'ok'


text:
class CreateBusinessCases < ActiveRecord::Migration
  def change
    create_table :business_cases do |t|
      t.integer :testing_ground_id
      t.text :financials
      t.timestamps
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Persoonia gunnii var. angustifolia Benth.

### Remarks
null


text:
@InterfaceAudience.Private
package org.apache.hadoop.yarn.lib;
import org.apache.hadoop.classification.InterfaceAudience;


text:
- If you want to __load and play__ soundfonts in the browser use: https://github.com/danigb/soundfont-player
- If you want to just __load__ midi.js pre-rendered soundfonts use: https://github.com/danigb/audio-loader


text: _What My Friends Eat <strong>(WMFE)</strong>_-app backend


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.ftfl.icareprofile.ICareProfileListActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>

</menu>


text:
**⚠ This project is no longer maintained ⚠**

***

# Infinite Fire

A small library that helps you connecting Firebase to a RecyclerView.

Inspired by the official [FirebaseUI-Android library](https://github.com/firebase/FirebaseUI-Android).

## Demo

Add your own google-services.json to the app folder to run the demo app!
Use the following rules for your database:
```json
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "chat": {
      ".read": "true",
      "$chat": {
        ".write": "true",
        ".validate": "newData.hasChildren(['name', 'text'])",
        "name": {".validate": "true"},
        "text": {".validate": "true"},
        "$other": {".validate": "false"}
      }
    }
  }
}
```

## How to use Infinite Fire

The core of Infinite Fire is the InfiniteFireArray.
```java
InfiniteFireArray<ModelClass> array = new InfiniteFireArray<>(

        // Your model's class. InfiniteFireArray uses DataSnapshot#getValue(ModelClass.class) to marshal
        // DataSnapshots to ModelClass.
        ModelClass.class,

        // Your Firebase Query.
        // Do NOT use Query#limitToFirst() or Query#limitToLast(), InfiniteFireArray will do that for you.
        // Do sort your Query by using Query#orderByKey() or Query#orderByString(String)
        query,

        // The number of inital items.
        // InfiniteFireArray will limit the Query using this int.
        20,

        // This number of items loaded each time you call InfiniteFireArray.more().
        // InfiniteFireArray will use this number to raise the limit of the initial Query.
        20,

        // Defines if your Query will be limited using Query#limitToFirst() or Query#limitToLast()
        // In most cases you want this to be false to load the newest items first.
        false,

        // Defines if InfiniteFireArray changes the order of the items after the inital load.
        // For more info see below.
        false
);
```

Then implement InfiniteFireRecyclerViewAdapter and pass the InfiniteFireArray as parameter.
```java
class MyRecyclerView extends InfiniteFireRecyclerViewAdapter {...}
MyRecyclerView recyclerView = new MyRecyclerView(array);
```

For more information take a look at the examples.

## Features

### Scroll-to-load-more.
Use ```InfiniteFireArray#more()``` to implement a scroll-to-load-more pattern.
It raises the limit of your Query incrementally.

### Pull-to-refresh.
Firebase offers real-time functionality.
InfiniteFireArray uses the ```Query#addChildEventListener()``` to keep your data up to date.

There are use-cases though in which constantly changing the order of your items results in a really bad user experience.
Think about a grid view that is sorted by a value that changes a lot, e.g. a comments counter -- your view would look like a memory game.

InfiniteFireArray allows you to maintain the order while still updating the existing items in real-time.
Implementing a ```SwipeRefreshLayout``` allows you to call ```InfiniteArray#reset()``` to "reload" the data and set the limit of the Query to its orignial limit.

### Loading events.
Attach a ```InfiniteFireArray.OnLoadingStatusListener``` to receive loading events.

Please note that these events only indicate when the inital sync is completed.
InfiniteFireArray will still receive real-time updates without dispatching further events after the inital sync.

## How to install Infinite Fire

Get it from [Jitpack](https://jitpack.io/#marcorei/Infinite-Fire/) via Gradle or Maven.

## Thanks
- [FirebaseUI-Android library](https://github.com/firebase/FirebaseUI-Android) Inspiration for this library, uses an Array to connect Firebase to RecyclerViews
- [Kato](https://twitter.com/katowulf) Great support, thank you!