text:
package lnutil

import (
	"bytes"
	"fmt"

	"github.com/mit-dci/lit/logging"

	"github.com/mit-dci/lit/btcutil/txscript"
	"github.com/mit-dci/lit/wire"
)

// CommitScript is the script for 0.13.1: OP_CHECKSIG turned into OP_CHECSIGVERIFY
func CommitScript(RKey, TKey [33]byte, delay uint16) []byte {
	builder := txscript.NewScriptBuilder()

	// 1 for penalty / revoked, 0 for timeout
	// 1, so revoked
	builder.AddOp(txscript.OP_IF)

	// Just push revokable key
	builder.AddData(RKey[:])

	// 0, so timeout
	builder.AddOp(txscript.OP_ELSE)

	// CSV delay
	builder.AddInt64(int64(delay))
	// CSV check, fails here if too early
	builder.AddOp(txscript.OP_NOP3) // really OP_CHECKSEQUENCEVERIFY
	// Drop delay value
	builder.AddOp(txscript.OP_DROP)
	// push timeout key
	builder.AddData(TKey[:])

	builder.AddOp(txscript.OP_ENDIF)

	// check whatever pubkey is left on the stack
	builder.AddOp(txscript.OP_CHECKSIG)

	// never any errors we care about here.
	s, _ := builder.Script()
	return s
}

// FundMultiPre generates the non-p2sh'd multisig script for 2 of 2 pubkeys.
// useful for making transactions spending the fundtx.
// returns a bool which is true if swapping occurs.
func FundTxScript(aPub, bPub [33]byte) ([]byte, bool, error) {
	var swapped bool
	if bytes.Compare(aPub[:], bPub[:]) == -1 { // swap to sort pubkeys if needed
		aPub, bPub = bPub, aPub
		swapped = true
	}
	bldr := txscript.NewScriptBuilder()
	// Require 1 signatures, either key// so from both of the pubkeys
	bldr.AddOp(txscript.OP_2)
	// add both pubkeys (sorted)
	bldr.AddData(aPub[:])
	bldr.AddData(bPub[:])
	// 2 keys total.  In case that wasn't obvious.
	bldr.AddOp(txscript.OP_2)
	// Good ol OP_CHECKMULTISIG.  Don't forget the zero!
	bldr.AddOp(txscript.OP_CHECKMULTISIG)
	// get byte slice
	pre, err := bldr.Script()
	return pre, swapped, err
}

// FundTxOut creates a TxOut for the funding transaction.
// Give it the two pubkeys and it'll give you the p2sh'd txout.
// You don't have to remember the p2sh preimage, as long as you remember the
// pubkeys involved.
func FundTxOut(pubA, pubB [33]byte, amt int64) (*wire.TxOut, error) {
	if amt < 0 {
		return nil, fmt.Errorf("Can't create FundTx script with negative coins")
	}
	scriptBytes, _, err := FundTxScript(pubA, pubB)
	if err != nil {
		return nil, err
	}
	scriptBytes = P2WSHify(scriptBytes)

	return wire.NewTxOut(amt, scriptBytes), nil
}

func ReceiveHTLCScript(revPKH [20]byte, remotePub [33]byte, RHash [32]byte, localPub [33]byte, locktime uint32) []byte {
	logging.Infof("Generating receive HTLC with localPub [%x] and remotePub [%x]", localPub, remotePub)
	b := txscript.NewScriptBuilder()

	b.AddOp(txscript.OP_DUP)
	b.AddOp(txscript.OP_HASH160)
	b.AddData(revPKH[:])
	b.AddOp(txscript.OP_EQUAL)
	b.AddOp(txscript.OP_IF)
	b.AddOp(txscript.OP_CHECKSIG)
	b.AddOp(txscript.OP_ELSE)
	b.AddData(remotePub[:])
	b.AddOp(txscript.OP_SWAP)
	b.AddOp(txscript.OP_SIZE)
	b.AddInt64(16)
	b.AddOp(txscript.OP_EQUAL)
	b.AddOp(txscript.OP_IF)
	b.AddOp(txscript.OP_SHA256)
	b.AddData(RHash[:])
	b.AddOp(txscript.OP_EQUALVERIFY)
	b.AddInt64(2)
	b.AddOp(txscript.OP_SWAP)
	b.AddData(localPub[:])
	b.AddInt64(2)
	b.AddOp(txscript.OP_CHECKMULTISIG)
	b.AddOp(txscript.OP_ELSE)
	b.AddOp(txscript.OP_DROP)
	b.AddInt64(int64(locktime))
	b.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
	b.AddOp(txscript.OP_DROP)
	b.AddOp(txscript.OP_CHECKSIG)
	b.AddOp(txscript.OP_ENDIF)
	b.AddOp(txscript.OP_ENDIF)

	s, _ := b.Script()
	return s
}

func OfferHTLCScript(revPKH [20]byte, remotePub [33]byte, RHash [32]byte, localPub [33]byte) []byte {
	logging.Infof("Generating offer HTLC with localPub [%x] and remotePub [%x]", localPub, remotePub)
	b := txscript.NewScriptBuilder()

	b.AddOp(txscript.OP_DUP)
	b.AddOp(txscript.OP_HASH160)
	b.AddData(revPKH[:])
	b.AddOp(txscript.OP_EQUAL)
	b.AddOp(txscript.OP_IF)
	b.AddOp(txscript.OP_CHECKSIG)
	b.AddOp(txscript.OP_ELSE)
	b.AddData(remotePub[:])
	b.AddOp(txscript.OP_SWAP)
	b.AddOp(txscript.OP_SIZE)
	b.AddInt64(16)
	b.AddOp(txscript.OP_EQUAL)
	b.AddOp(txscript.OP_NOTIF)
	b.AddOp(txscript.OP_DROP)
	b.AddInt64(2)
	b.AddOp(txscript.OP_SWAP)
	b.AddData(localPub[:])
	b.AddInt64(2)
	b.AddOp(txscript.OP_CHECKMULTISIG)
	b.AddOp(txscript.OP_ELSE)
	b.AddOp(txscript.OP_SHA256)
	b.AddData(RHash[:])
	b.AddOp(txscript.OP_EQUALVERIFY)
	b.AddOp(txscript.OP_CHECKSIG)
	b.AddOp(txscript.OP_ENDIF)
	b.AddOp(txscript.OP_ENDIF)

	s, _ := b.Script()
	return s
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ECharts.Entities.style {
	public class BrushStyle {

		public int? borderWidth{
			get;
			set;
		}

		public object color{
			get;
			set;
		}

		public object borderColor{
			get;
			set;
		}

		public int? width{
			get;
			set;
		}

		///
		/// <param name="borderWidth"></param>
		public BrushStyle BorderWidth(int borderWidth){
		     this.borderWidth=borderWidth;
		return this;
		}

		///
		/// <param name="color"></param>
		public BrushStyle Color(string color){
		     this.color=color;
		return this;
		}

		///
		/// <param name="borderColor"></param>
		public BrushStyle BorderColor(string borderColor){
		     this.borderColor=borderColor;
		return this;
		}

		///
		/// <param name="width"></param>
		public BrushStyle Width(int width){
		     this.width=width;
		return this;
		}

	}//end BrushStyle

}//end namespace style

redpajama_set_name: RedPajamaGithub


text:
package com.pinterest.deployservice.dao;

import com.pinterest.deployservice.bean.EnvironBean;
import com.pinterest.deployservice.bean.UpdateStatement;

import java.util.Collection;
import java.util.List;

/**
 * A collection of methods to help interact with Environments tables
 */
public interface EnvironDAO {
    void insert(EnvironBean bean) throws Exception;

    void update(String envId, EnvironBean bean) throws Exception;

    void update(String envName, String envStage, EnvironBean bean) throws Exception;

    void updateAll(EnvironBean bean) throws Exception;

    void setExternalId(EnvironBean bean, String externalId) throws Exception;

    UpdateStatement genUpdateStatement(String envId, EnvironBean bean);

    void delete(String envId) throws Exception;

    List<String> getAllEnvNames(String nameFilter, long pageIndex, int pageSize) throws Exception;

    EnvironBean getById(String envId) throws Exception;

    List<EnvironBean> getByName(String envName) throws Exception;

    EnvironBean getByStage(String envName, String envStage) throws Exception;

    EnvironBean getByCluster(String clusterName) throws Exception;

    List<String> getOverrideHosts(String envId, String envName, String envStage) throws Exception;

    long countTotalCapacity(String envId, String envName, String envStage) throws Exception;

    List<String> getTotalCapacityHosts(String envId, String envName, String envStage) throws Exception;

    Collection<String> getMissingHosts(String envId) throws Exception;

    List<EnvironBean> getEnvsByHost(String host) throws Exception;

    List<EnvironBean> getEnvsByGroups(Collection<String> groups) throws Exception;

    List<String> getCurrentDeployIds() throws Exception;

    // Return all
    List<String> getAllEnvIds() throws Exception;

    List<EnvironBean> getAllEnvs() throws Exception;
    List<EnvironBean> getAllSidecarEnvs() throws Exception;

    void deleteSchedule(String envName, String stageName) throws Exception;

    void deleteCluster(String envName, String stageName) throws Exception;

    EnvironBean getEnvByDeployConstraintId(String constraintId) throws Exception;

    void deleteConstraint(String envName, String stageName) throws Exception;
}


text:
var jcropapi;

function setupJcrop(image, original, focalPointOriginal, fields){
    image.Jcrop({
        trueSize: [original.width, original.height],
        bgColor: "rgb(192, 192, 192)",
        onSelect: function(box) {
            var x = Math.floor((box.x + box.x2) / 2);
            var y = Math.floor((box.y + box.y2) / 2);
            var w = Math.floor(box.w);
            var h = Math.floor(box.h);

            fields.x.val(x);
            fields.y.val(y);
            fields.width.val(w);
            fields.height.val(h);
        },
        onRelease: function() {
            fields.x.val(focalPointOriginal.x);
            fields.y.val(focalPointOriginal.y);
            fields.width.val(focalPointOriginal.width);
            fields.height.val(focalPointOriginal.height);
        },
    }, function(){
        jcropapi = this
    });
}

$(function() {
    var $chooser = $('div.focal-point-chooser');
    var $indicator = $('.current-focal-point-indicator', $chooser);
    var $image = $('img', $chooser);

    var original = {
        width: $image.data('originalWidth'),
        height: $image.data('originalHeight')
    }

    var focalPointOriginal = {
        x: $chooser.data('focalPointX'),
        y: $chooser.data('focalPointY'),
        width: $chooser.data('focalPointWidth'),
        height: $chooser.data('focalPointHeight')
    }

    var fields = {
        x: $('input.focal_point_x'),
        y: $('input.focal_point_y'),
        width: $('input.focal_point_width'),
        height: $('input.focal_point_height')
    }

    var left = focalPointOriginal.x - focalPointOriginal.width / 2
    var top = focalPointOriginal.y - focalPointOriginal.height / 2
    var width = focalPointOriginal.width;
    var height = focalPointOriginal.height;

    $indicator.css('left', (left * 100 / original.width) + '%');
    $indicator.css('top', (top * 100 / original.height) + '%');
    $indicator.css('width', (width * 100 / original.width) + '%');
    $indicator.css('height', (height * 100 / original.height) + '%');

    var params = [$image, original, focalPointOriginal, fields];

    setupJcrop.apply(this, params)

    $(window).resize($.debounce(300, function(){
        // jcrop doesn't support responsive images so to cater for resizing the browser
        // we have to destroy() it, which doesn't properly do it,
        // so destory it some more, then re-apply it
        jcropapi.destroy();
        $image.removeAttr('style');
        $('.jcrop-holder').remove();
        setupJcrop.apply(this, params)
    }));
});


text:
package apple.uikit.protocol;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCProtocolName;
import org.moe.natj.objc.ann.Selector;

@Generated
@Library("UIKit")
@Runtime(ObjCRuntime.class)
@ObjCProtocolName("UIDragAnimating")
public interface UIDragAnimating {
    /**
     * Instances of UIDragAnimating provide you a way to animate your own changes
     * alongside the drag and drop system's animations.
     * <p>
     * Animatable view properties that are set by the animation block will be
     * animated to their new values.
     */
    @Generated
    @Selector("addAnimations:")
    void addAnimations(@ObjCBlock(name = "call_addAnimations") Block_addAnimations animations);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_addAnimations {
        @Generated
        void call_addAnimations();
    }

    @Generated
    @Selector("addCompletion:")
    void addCompletion(@ObjCBlock(name = "call_addCompletion") Block_addCompletion completion);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_addCompletion {
        @Generated
        void call_addCompletion(@NInt long finalPosition);
    }
}


text:
using System;
using System.Linq;
using Xunit;
using Parser.BusinessLogic;
using Parser.BusinessLogic.Enums;
using Parser.BusinessLogic.Interfaces;

namespace Parser.Tests.Business
{
    public class ParserTest
    {
        [Fact]
        public void TestMethod1()
        {
            IRoseParser testParser = new RoseParser();
            testParser.ConvertToJson(new);
        }
    }

    internal class TestParsable : IRoseParsable
    {
        TestParsable(){

            FilePath = "TestPath";
            FileType = ParsableEnum.Card;
        }

        public string FilePath
        {
            get; set;
        }

        public ParsableEnum FileType
        {
            get; set;
        }
    }
}


text:
FROM alpine:3.5
MAINTAINER Roman Safronov <electroma@gmail.com>
COPY authsvc /
EXPOSE 8080
ENTRYPOINT ["/authsvc"]


text:
'use strict';

var NavigationFindReducer = require('NavigationFindReducer');
var NavigationStackReducer = require('NavigationStackReducer');
var NavigationTabsReducer = require('NavigationTabsReducer');

const NavigationReducer = {
  FindReducer: NavigationFindReducer,
  StackReducer: NavigationStackReducer,
  TabsReducer: NavigationTabsReducer,
};

module.exports = NavigationReducer;


text:
"""parse LaTeX aux file
"""

from __future__ import with_statement

import re

import pybtex.io
from pybtex.exceptions import PybtexError
from pybtex.errors import report_error

class AuxDataError(PybtexError):
    def __init__(self, message, context=None):
        super(AuxDataError, self).__init__(message, context.filename)
        self.context = context

    def get_context(self):
        if self.context.line:
            marker = '^' * len(self.context.line)
            return self.context.line + '\n' + marker

    def __unicode__(self):
        base_message = super(AuxDataError, self).__unicode__()
        lineno = self.context.lineno
        location = 'in line {0}: '.format(lineno) if lineno else ''
        return location + base_message

class AuxDataContext(object):
    lineno = None
    line = None
    filename = None

    def __init__(self, filename):
        self.filename = filename

class AuxData(object):
    command_re = re.compile(r'\\(citation|bibdata|bibstyle|@input){(.*)}')
    context = None
    style = None
    data = None
    citations = None

    def __init__(self, encoding):
        self.encoding = encoding
        self.citations = []
        self._canonical_keys = {}

    def handle_citation(self, keys):
        for key in keys.split(','):
            key_lower = key.lower()
            if key_lower in self._canonical_keys:
                existing_key = self._canonical_keys[key_lower]
                if key != existing_key:
                    msg = 'case mismatch error between cite keys {0} and {1}'
                    report_error(AuxDataError(msg.format(key, existing_key), self.context))
            self.citations.append(key)
            self._canonical_keys[key_lower] = key

    def handle_bibstyle(self, style):
        if self.style is not None:
            report_error(AuxDataError(r'illegal, another \bibstyle command', self.context))
        else:
            self.style = style

    def handle_bibdata(self, bibdata):
        if self.data is not None:
            report_error(AuxDataError(r'illegal, another \bibdata command', self.context))
        else:
            self.data = bibdata.split(',')

    def handle_input(self, filename):
        self.parse_file(filename)

    def handle_command(self, command, value):
        action = getattr(self, 'handle_%s' % command.lstrip('@'))
        action(value)

    def parse_line(self, line, lineno):
        self.context.lineno = lineno
        self.context.line = line.strip()
        match = self.command_re.match(line)
        if match:
            command, value = match.groups()
            self.handle_command(command, value)

    def parse_file(self, filename):
        previous_context = self.context
        self.context = AuxDataContext(filename)

        with pybtex.io.open_unicode(filename, encoding=self.encoding) as aux_file:
            for lineno, line in enumerate(aux_file, 1):
                self.parse_line(line, lineno)

        if previous_context:
            self.context = previous_context
        else:
            self.context.line = None
            self.context.lineno = None

        # these errors are fatal - always raise an exception instead of using
        # erorrs.report_error()
        if self.data is None:
            raise AuxDataError(r'found no \bibdata command', self.context)
        if self.style is None:
            raise AuxDataError(r'found no \bibstyle command', self.context)

def parse_file(filename, encoding):
    """Parse a file and return an AuxData object."""

    data = AuxData(encoding)
    data.parse_file(filename)
    return data


text:
package session

import (
	"net/http"

	"github.com/google/wire"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/auth"
	"github.com/skygeario/skygear-server/pkg/core/config"
	"github.com/skygeario/skygear-server/pkg/core/time"
)

type InsecureCookieConfig bool

func ProvideSessionCookieConfiguration(
	r *http.Request,
	icc InsecureCookieConfig,
	c *config.TenantConfiguration,
) CookieConfiguration {
	return NewSessionCookieConfiguration(r, bool(icc), *c.AppConfig.Session)
}

func ProvideSessionProvider(req *http.Request, s Store, aep *auth.AccessEventProvider, c *config.TenantConfiguration) Provider {
	return NewProvider(req, s, aep, *c.AppConfig.Session)
}

func ProvideSessionManager(s Store, tp time.Provider, c *config.TenantConfiguration, cc CookieConfiguration) *Manager {
	return &Manager{
		Store:  s,
		Time:   tp,
		Config: *c.AppConfig.Session,
		Cookie: cc,
	}
}

var DependencySet = wire.NewSet(
	ProvideSessionCookieConfiguration,
	ProvideSessionProvider,
	wire.Bind(new(ResolverProvider), new(Provider)),
	wire.Struct(new(Resolver), "*"),
	wire.Bind(new(auth.IDPSessionResolver), new(*Resolver)),
	ProvideSessionManager,
	wire.Bind(new(auth.IDPSessionManager), new(*Manager)),
)


text:
package com.example.ec.adapter;

import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.example.ec.R;
import com.example.ec.activity.model.Level0Item;
import com.example.ec.activity.model.Level1Item;
import com.example.ec.activity.model.RecycleEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by yzz on 2017/5/9.
 */

public class ExpandableItemAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {

    private static final String TAG = ExpandableItemAdapter.class.getSimpleName();

    public static final int TYPE_LEVEL_0 = 0;
    public static final int TYPE_LEVEL_1 = 1;

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public ExpandableItemAdapter(List<MultiItemEntity> data) {
        super(data);
        addItemType(TYPE_LEVEL_0, R.layout.item_expandable_lv0);
        addItemType(TYPE_LEVEL_1, R.layout.item_expandable_lv1);
    }

    @Override
    protected void convert(final BaseViewHolder holder, MultiItemEntity item) {

        switch (holder.getItemViewType()) {
            case TYPE_LEVEL_0:

//                holder.setImageResource(R.id.iv_head, R.mipmap.head_img0);

                final Level0Item lv0 = (Level0Item)item;
                holder.setText(R.id.tv_item0_title, lv0.title)
                        .setText(R.id.tv_item0_content, lv0.content)
                        .setChecked(R.id.cb_item0,lv0.isSelected)
                        .setImageResource(R.id.iv, lv0.isExpanded() ? R.mipmap.arrow_b : R.mipmap.arrow_r);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getAdapterPosition();
                        Log.d(TAG, "Level 0 item pos: " + pos);
                        if (lv0.isExpanded()) {
                            collapse(pos);
                        } else {
//                            if (pos % 3 == 0) {
//                                expandAll(pos, false);
//                            } else {
                            expand(pos);
//                            }
                        }
                    }
                });

                holder.itemView.findViewById(R.id.cb_item0).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getAdapterPosition();
                        if (lv0.isSelected){
                            lv0.isSelected=false;
                            for(int i=0;i<lv0.getSubItems().size();i++){
                                lv0.getSubItem(i).isSelected=false;
                            }
                        }else {
                            lv0.isSelected=true;
                            for(int i=0;i<lv0.getSubItems().size();i++){
                                lv0.getSubItem(i).isSelected=true;
                            }

                        }
                        EventBus.getDefault().post(new RecycleEvent(RecycleEvent.REFRESH,"",pos));

                    }
                });
                break;
            case TYPE_LEVEL_1:
                final Level1Item lv1 = (Level1Item)item;
                holder.setText(R.id.tv_item1_title, lv1.title)
                        .setText(R.id.tv_item1_content, lv1.subTitle)
                        .setChecked(R.id.cb_item1,lv1.isSelected);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getAdapterPosition();
                        Log.d(TAG, "Level 1 item pos: " + pos);
                    }
                });

                holder.itemView.findViewById(R.id.cb_item1).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        holder.getAssociatedObject();
                        if (lv1.isSelected){
                            lv1.isSelected=false;
                        }else {
                            lv1.isSelected=true;
                        }
                        EventBus.getDefault().post(new RecycleEvent(RecycleEvent.LEVEL_1,"",lv1.msuper));
                    }
                });
                break;
        }

    }
}


text:
package Pod::Select;

use vars qw($VERSION);
$VERSION = 1.35;  ## Current version of this package
require  5.005;    ## requires this Perl version or later

#############################################################################

=head1 NAME

Pod::Select, podselect() - extract selected sections of POD from input

=head1 SYNOPSIS

    use Pod::Select;

    ## Select all the POD sections for each file in @filelist
    ## and print the result on standard output.
    podselect(@filelist);

    ## Same as above, but write to tmp.out
    podselect({-output => "tmp.out"}, @filelist):

    ## Select from the given filelist, only those POD sections that are
    ## within a 1st level section named any of: NAME, SYNOPSIS, OPTIONS.
    podselect({-sections => ["NAME|SYNOPSIS", "OPTIONS"]}, @filelist):

    ## Select the "DESCRIPTION" section of the PODs from STDIN and write
    ## the result to STDERR.
    podselect({-output => ">&STDERR", -sections => ["DESCRIPTION"]}, \*STDIN);

or

    use Pod::Select;

    ## Create a parser object for selecting POD sections from the input
    $parser = new Pod::Select();

    ## Select all the POD sections for each file in @filelist
    ## and print the result to tmp.out.
    $parser->parse_from_file("<&STDIN", "tmp.out");

    ## Select from the given filelist, only those POD sections that are
    ## within a 1st level section named any of: NAME, SYNOPSIS, OPTIONS.
    $parser->select("NAME|SYNOPSIS", "OPTIONS");
    for (@filelist) { $parser->parse_from_file($_); }

    ## Select the "DESCRIPTION" and "SEE ALSO" sections of the PODs from
    ## STDIN and write the result to STDERR.
    $parser->select("DESCRIPTION");
    $parser->add_selection("SEE ALSO");
    $parser->parse_from_filehandle(\*STDIN, \*STDERR);

=head1 REQUIRES

perl5.005, Pod::Parser, Exporter, Carp

=head1 EXPORTS

podselect()

=head1 DESCRIPTION

B<podselect()> is a function which will extract specified sections of
pod documentation from an input stream. This ability is provided by the
B<Pod::Select> module which is a subclass of B<Pod::Parser>.
B<Pod::Select> provides a method named B<select()> to specify the set of
POD sections to select for processing/printing. B<podselect()> merely
creates a B<Pod::Select> object and then invokes the B<podselect()>
followed by B<parse_from_file()>.

=head1 SECTION SPECIFICATIONS

B<podselect()> and B<Pod::Select::select()> may be given one or more
"section specifications" to restrict the text processed to only the
desired set of sections and their corresponding subsections.  A section
specification is a string containing one or more Perl-style regular
expressions separated by forward slashes ("/").  If you need to use a
forward slash literally within a section title you can escape it with a
backslash ("\/").

The formal syntax of a section specification is:

=over 4

=item *

I<head1-title-regex>/I<head2-title-regex>/...

=back

Any omitted or empty regular expressions will default to ".*".
Please note that each regular expression given is implicitly
anchored by adding "^" and "$" to the beginning and end.  Also, if a
given regular expression starts with a "!" character, then the
expression is I<negated> (so C<!foo> would match anything I<except>
C<foo>).

Some example section specifications follow.

=over 4

=item *

Match the C<NAME> and C<SYNOPSIS> sections and all of their subsections:

C<NAME|SYNOPSIS>

=item *

Match only the C<Question> and C<Answer> subsections of the C<DESCRIPTION>
section:

C<DESCRIPTION/Question|Answer>

=item *

Match the C<Comments> subsection of I<all> sections:

C</Comments>

=item *

Match all subsections of C<DESCRIPTION> I<except> for C<Comments>:

C<DESCRIPTION/!Comments>

=item *

Match the C<DESCRIPTION> section but do I<not> match any of its subsections:

C<DESCRIPTION/!.+>

=item *

Match all top level sections but none of their subsections:

C</!.+>

=back

=begin _NOT_IMPLEMENTED_

=head1 RANGE SPECIFICATIONS

B<podselect()> and B<Pod::Select::select()> may be given one or more
"range specifications" to restrict the text processed to only the
desired ranges of paragraphs in the desired set of sections. A range
specification is a string containing a single Perl-style regular
expression (a regex), or else two Perl-style regular expressions
(regexs) separated by a ".." (Perl's "range" operator is "..").
The regexs in a range specification are delimited by forward slashes
("/").  If you need to use a forward slash literally within a regex you
can escape it with a backslash ("\/").

The formal syntax of a range specification is:

=over 4

=item *

/I<start-range-regex>/[../I<end-range-regex>/]

=back

Where each the item inside square brackets (the ".." followed by the
end-range-regex) is optional. Each "range-regex" is of the form:

    =cmd-expr text-expr

Where I<cmd-expr> is intended to match the name of one or more POD
commands, and I<text-expr> is intended to match the paragraph text for
the command. If a range-regex is supposed to match a POD command, then
the first character of the regex (the one after the initial '/')
absolutely I<must> be a single '=' character; it may not be anything
else (not even a regex meta-character) if it is supposed to match
against the name of a POD command.

If no I<=cmd-expr> is given then the text-expr will be matched against
plain textblocks unless it is preceded by a space, in which case it is
matched against verbatim text-blocks. If no I<text-expr> is given then
only the command-portion of the paragraph is matched against.

Note that these two expressions are each implicitly anchored. This
means that when matching against the command-name, there will be an
implicit '^' and '$' around the given I<=cmd-expr>; and when matching
against the paragraph text there will be an implicit '\A' and '\Z'
around the given I<text-expr>.

Unlike with section-specs, the '!' character does I<not> have any special
meaning (negation or otherwise) at the beginning of a range-spec!

Some example range specifications follow.

=over 4

=item
Match all C<=for html> paragraphs:

C</=for html/>

=item
Match all paragraphs between C<=begin html> and C<=end html>
(note that this will I<not> work correctly if such sections
are nested):

C</=begin html/../=end html/>

=item
Match all paragraphs between the given C<=item> name until the end of the
current section:

C</=item mine/../=head\d/>

=item
Match all paragraphs between the given C<=item> until the next item, or
until the end of the itemized list (note that this will I<not> work as
desired if the item contains an itemized list nested within it):

C</=item mine/../=(item|back)/>

=back

=end _NOT_IMPLEMENTED_

=cut

#############################################################################

use strict;
#use diagnostics;
use Carp;
use Pod::Parser 1.04;
use vars qw(@ISA @EXPORT $MAX_HEADING_LEVEL);

@ISA = qw(Pod::Parser);
@EXPORT = qw(&podselect);

## Maximum number of heading levels supported for '=headN' directives
*MAX_HEADING_LEVEL = \3;

#############################################################################

=head1 OBJECT METHODS

The following methods are provided in this module. Each one takes a
reference to the object itself as an implicit first parameter.

=cut

##---------------------------------------------------------------------------

## =begin _PRIVATE_
##
## =head1 B<_init_headings()>
##
## Initialize the current set of active section headings.
##
## =cut
##
## =end _PRIVATE_

use vars qw(%myData @section_headings);

sub _init_headings {
    my $self = shift;
    local *myData = $self;

    ## Initialize current section heading titles if necessary
    unless (defined $myData{_SECTION_HEADINGS}) {
        local *section_headings = $myData{_SECTION_HEADINGS} = [];
        for (my $i = 0; $i < $MAX_HEADING_LEVEL; ++$i) {
            $section_headings[$i] = '';
        }
    }
}

##---------------------------------------------------------------------------

=head1 B<curr_headings()>

            ($head1, $head2, $head3, ...) = $parser->curr_headings();
            $head1 = $parser->curr_headings(1);

This method returns a list of the currently active section headings and
subheadings in the document being parsed. The list of headings returned
corresponds to the most recently parsed paragraph of the input.

If an argument is given, it must correspond to the desired section
heading number, in which case only the specified section heading is
returned. If there is no current section heading at the specified
level, then C<undef> is returned.

=cut

sub curr_headings {
    my $self = shift;
    $self->_init_headings()  unless (defined $self->{_SECTION_HEADINGS});
    my @headings = @{ $self->{_SECTION_HEADINGS} };
    return (@_ > 0  and  $_[0] =~ /^\d+$/) ? $headings[$_[0] - 1] : @headings;
}

##---------------------------------------------------------------------------

=head1 B<select()>

            $parser->select($section_spec1,$section_spec2,...);

This method is used to select the particular sections and subsections of
POD documentation that are to be printed and/or processed. The existing
set of selected sections is I<replaced> with the given set of sections.
See B<add_selection()> for adding to the current set of selected
sections.

Each of the C<$section_spec> arguments should be a section specification
as described in L<"SECTION SPECIFICATIONS">.  The section specifications
are parsed by this method and the resulting regular expressions are
stored in the invoking object.

If no C<$section_spec> arguments are given, then the existing set of
selected sections is cleared out (which means C<all> sections will be
processed).

This method should I<not> normally be overridden by subclasses.

=cut

use vars qw(@selected_sections);

sub select {
    my $self = shift;
    my @sections = @_;
    local *myData = $self;
    local $_;

### NEED TO DISCERN A SECTION-SPEC FROM A RANGE-SPEC (look for m{^/.+/$}?)

    ##---------------------------------------------------------------------
    ## The following is a blatant hack for backward compatibility, and for
    ## implementing add_selection(). If the *first* *argument* is the
    ## string "+", then the remaining section specifications are *added*
    ## to the current set of selections; otherwise the given section
    ## specifications will *replace* the current set of selections.
    ##
    ## This should probably be fixed someday, but for the present time,
    ## it seems incredibly unlikely that "+" would ever correspond to
    ## a legitimate section heading
    ##---------------------------------------------------------------------
    my $add = ($sections[0] eq "+") ? shift(@sections) : "";

    ## Reset the set of sections to use
    unless (@sections > 0) {
        delete $myData{_SELECTED_SECTIONS}  unless ($add);
        return;
    }
    $myData{_SELECTED_SECTIONS} = []
        unless ($add  &&  exists $myData{_SELECTED_SECTIONS});
    local *selected_sections = $myData{_SELECTED_SECTIONS};

    ## Compile each spec
    my $spec;
    for $spec (@sections) {
        if ( defined($_ = &_compile_section_spec($spec)) ) {
            ## Store them in our sections array
            push(@selected_sections, $_);
        }
        else {
            carp "Ignoring section spec \"$spec\"!\n";
        }
    }
}

##---------------------------------------------------------------------------

=head1 B<add_selection()>

            $parser->add_selection($section_spec1,$section_spec2,...);

This method is used to add to the currently selected sections and
subsections of POD documentation that are to be printed and/or
processed. See <select()> for replacing the currently selected sections.

Each of the C<$section_spec> arguments should be a section specification
as described in L<"SECTION SPECIFICATIONS">. The section specifications
are parsed by this method and the resulting regular expressions are
stored in the invoking object.

This method should I<not> normally be overridden by subclasses.

=cut

sub add_selection {
    my $self = shift;
    $self->select("+", @_);
}

##---------------------------------------------------------------------------

=head1 B<clear_selections()>

            $parser->clear_selections();

This method takes no arguments, it has the exact same effect as invoking
<select()> with no arguments.

=cut

sub clear_selections {
    my $self = shift;
    $self->select();
}

##---------------------------------------------------------------------------

=head1 B<match_section()>

            $boolean = $parser->match_section($heading1,$heading2,...);

Returns a value of true if the given section and subsection heading
titles match any of the currently selected section specifications in
effect from prior calls to B<select()> and B<add_selection()> (or if
there are no explictly selected/deselected sections).

The arguments C<$heading1>, C<$heading2>, etc. are the heading titles of
the corresponding sections, subsections, etc. to try and match.  If
C<$headingN> is omitted then it defaults to the current corresponding
section heading title in the input.

This method should I<not> normally be overridden by subclasses.

=cut

sub match_section {
    my $self = shift;
    my (@headings) = @_;
    local *myData = $self;

    ## Return true if no restrictions were explicitly specified
    my $selections = (exists $myData{_SELECTED_SECTIONS})
                       ?  $myData{_SELECTED_SECTIONS}  :  undef;
    return  1  unless ((defined $selections) && (@{$selections} > 0));

    ## Default any unspecified sections to the current one
    my @current_headings = $self->curr_headings();
    for (my $i = 0; $i < $MAX_HEADING_LEVEL; ++$i) {
        (defined $headings[$i])  or  $headings[$i] = $current_headings[$i];
    }

    ## Look for a match against the specified section expressions
    my ($section_spec, $regex, $negated, $match);
    for $section_spec ( @{$selections} ) {
        ##------------------------------------------------------
        ## Each portion of this spec must match in order for
        ## the spec to be matched. So we will start with a
        ## match-value of 'true' and logically 'and' it with
        ## the results of matching a given element of the spec.
        ##------------------------------------------------------
        $match = 1;
        for (my $i = 0; $i < $MAX_HEADING_LEVEL; ++$i) {
            $regex   = $section_spec->[$i];
            $negated = ($regex =~ s/^\!//);
            $match  &= ($negated ? ($headings[$i] !~ /${regex}/)
                                 : ($headings[$i] =~ /${regex}/));
            last unless ($match);
        }
        return  1  if ($match);
    }
    return  0;  ## no match
}

##---------------------------------------------------------------------------

=head1 B<is_selected()>

            $boolean = $parser->is_selected($paragraph);

This method is used to determine if the block of text given in
C<$paragraph> falls within the currently selected set of POD sections
and subsections to be printed or processed. This method is also
responsible for keeping track of the current input section and
subsections. It is assumed that C<$paragraph> is the most recently read
(but not yet processed) input paragraph.

The value returned will be true if the C<$paragraph> and the rest of the
text in the same section as C<$paragraph> should be selected (included)
for processing; otherwise a false value is returned.

=cut

sub is_selected {
    my ($self, $paragraph) = @_;
    local $_;
    local *myData = $self;

    $self->_init_headings()  unless (defined $myData{_SECTION_HEADINGS});

    ## Keep track of current sections levels and headings
    $_ = $paragraph;
    if (/^=((?:sub)*)(?:head(?:ing)?|sec(?:tion)?)(\d*)\s+(.*?)\s*$/)
    {
        ## This is a section heading command
        my ($level, $heading) = ($2, $3);
        $level = 1 + (length($1) / 3)  if ((! length $level) || (length $1));
        ## Reset the current section heading at this level
        $myData{_SECTION_HEADINGS}->[$level - 1] = $heading;
        ## Reset subsection headings of this one to empty
        for (my $i = $level; $i < $MAX_HEADING_LEVEL; ++$i) {
            $myData{_SECTION_HEADINGS}->[$i] = '';
        }
    }

    return  $self->match_section();
}

#############################################################################

=head1 EXPORTED FUNCTIONS

The following functions are exported by this module. Please note that
these are functions (not methods) and therefore C<do not> take an
implicit first argument.

=cut

##---------------------------------------------------------------------------

=head1 B<podselect()>

            podselect(\%options,@filelist);

B<podselect> will print the raw (untranslated) POD paragraphs of all
POD sections in the given input files specified by C<@filelist>
according to the given options.

If any argument to B<podselect> is a reference to a hash
(associative array) then the values with the following keys are
processed as follows:

=over 4

=item B<-output>

A string corresponding to the desired output file (or ">&STDOUT"
or ">&STDERR"). The default is to use standard output.

=item B<-sections>

A reference to an array of sections specifications (as described in
L<"SECTION SPECIFICATIONS">) which indicate the desired set of POD
sections and subsections to be selected from input. If no section
specifications are given, then all sections of the PODs are used.

=begin _NOT_IMPLEMENTED_

=item B<-ranges>

A reference to an array of range specifications (as described in
L<"RANGE SPECIFICATIONS">) which indicate the desired range of POD
paragraphs to be selected from the desired input sections. If no range
specifications are given, then all paragraphs of the desired sections
are used.

=end _NOT_IMPLEMENTED_

=back

All other arguments should correspond to the names of input files
containing POD sections. A file name of "-" or "<&STDIN" will
be interpreted to mean standard input (which is the default if no
filenames are given).

=cut

sub podselect {
    my(@argv) = @_;
    my %defaults = ();
    my $pod_parser = new Pod::Select(%defaults);
    my $num_inputs = 0;
    my $output = ">&STDOUT";
    my %opts;
    local $_;
    for (@argv) {
        if (ref($_)) {
        next unless (ref($_) eq 'HASH');
            %opts = (%defaults, %{$_});

            ##-------------------------------------------------------------
            ## Need this for backward compatibility since we formerly used
            ## options that were all uppercase words rather than ones that
            ## looked like Unix command-line options.
            ## to be uppercase keywords)
            ##-------------------------------------------------------------
            %opts = map {
                my ($key, $val) = (lc $_, $opts{$_});
                $key =~ s/^(?=\w)/-/;
                $key =~ /^-se[cl]/  and  $key  = '-sections';
                #! $key eq '-range'    and  $key .= 's';
                ($key => $val);
            } (keys %opts);

            ## Process the options
            (exists $opts{'-output'})  and  $output = $opts{'-output'};

            ## Select the desired sections
            $pod_parser->select(@{ $opts{'-sections'} })
                if ( (defined $opts{'-sections'})
                     && ((ref $opts{'-sections'}) eq 'ARRAY') );

            #! ## Select the desired paragraph ranges
            #! $pod_parser->select(@{ $opts{'-ranges'} })
            #!     if ( (defined $opts{'-ranges'})
            #!          && ((ref $opts{'-ranges'}) eq 'ARRAY') );
        }
        else {
            $pod_parser->parse_from_file($_, $output);
            ++$num_inputs;
        }
    }
    $pod_parser->parse_from_file("-")  unless ($num_inputs > 0);
}

#############################################################################

=head1 PRIVATE METHODS AND DATA

B<Pod::Select> makes uses a number of internal methods and data fields
which clients should not need to see or use. For the sake of avoiding
name collisions with client data and methods, these methods and fields
are briefly discussed here. Determined hackers may obtain further
information about them by reading the B<Pod::Select> source code.

Private data fields are stored in the hash-object whose reference is
returned by the B<new()> constructor for this class. The names of all
private methods and data-fields used by B<Pod::Select> begin with a
prefix of "_" and match the regular expression C</^_\w+$/>.

=cut

##---------------------------------------------------------------------------

=begin _PRIVATE_

=head1 B<_compile_section_spec()>

            $listref = $parser->_compile_section_spec($section_spec);

This function (note it is a function and I<not> a method) takes a
section specification (as described in L<"SECTION SPECIFICATIONS">)
given in C<$section_sepc>, and compiles it into a list of regular
expressions. If C<$section_spec> has no syntax errors, then a reference
to the list (array) of corresponding regular expressions is returned;
otherwise C<undef> is returned and an error message is printed (using
B<carp>) for each invalid regex.

=end _PRIVATE_

=cut

sub _compile_section_spec {
    my ($section_spec) = @_;
    my (@regexs, $negated);

    ## Compile the spec into a list of regexs
    local $_ = $section_spec;
    s|\\\\|\001|g;  ## handle escaped backward slashes
    s|\\/|\002|g;   ## handle escaped forward slashes

    ## Parse the regexs for the heading titles
    @regexs = split('/', $_, $MAX_HEADING_LEVEL);

    ## Set default regex for ommitted levels
    for (my $i = 0; $i < $MAX_HEADING_LEVEL; ++$i) {
        $regexs[$i]  = '.*'  unless ((defined $regexs[$i])
                                     && (length $regexs[$i]));
    }
    ## Modify the regexs as needed and validate their syntax
    my $bad_regexs = 0;
    for (@regexs) {
        $_ .= '.+'  if ($_ eq '!');
        s|\001|\\\\|g;       ## restore escaped backward slashes
        s|\002|\\/|g;        ## restore escaped forward slashes
        $negated = s/^\!//;  ## check for negation
        eval "/$_/";         ## check regex syntax
        if ($@) {
            ++$bad_regexs;
            carp "Bad regular expression /$_/ in \"$section_spec\": $@\n";
        }
        else {
            ## Add the forward and rear anchors (and put the negator back)
            $_ = '^' . $_  unless (/^\^/);
            $_ = $_ . '$'  unless (/\$$/);
            $_ = '!' . $_  if ($negated);
        }
    }
    return  (! $bad_regexs) ? [ @regexs ] : undef;
}

##---------------------------------------------------------------------------

=begin _PRIVATE_

=head2 $self->{_SECTION_HEADINGS}

A reference to an array of the current section heading titles for each
heading level (note that the first heading level title is at index 0).

=end _PRIVATE_

=cut

##---------------------------------------------------------------------------

=begin _PRIVATE_

=head2 $self->{_SELECTED_SECTIONS}

A reference to an array of references to arrays. Each subarray is a list
of anchored regular expressions (preceded by a "!" if the expression is to
be negated). The index of the expression in the subarray should correspond
to the index of the heading title in C<$self-E<gt>{_SECTION_HEADINGS}>
that it is to be matched against.

=end _PRIVATE_

=cut

#############################################################################

=head1 SEE ALSO

L<Pod::Parser>

=head1 AUTHOR

Please report bugs using L<http://rt.cpan.org>.

Brad Appleton E<lt>bradapp@enteract.comE<gt>

Based on code for B<pod2text> written by
Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>

=cut

1;
# vim: ts=4 sw=4 et


text:
<?php

class StaticController extends Controller {
	function deck() {
		$deck_id=$_GET['id'];
		$deck=new Deck();
		$deck->createFromIDLite($deck_id);
		$deck->last_revision_id = $deck->getLastRevisionID ();
		$usage=$deck->getUsage();
		$deck->comments=$deck->getComments();
		$translations=$deck->getTranslatedTo();
		$this->set ( 'deck', $deck );
		$this->set ( 'translations', $translations );
		$this->set ( 'usage', $usage );
		$this->set ( 'page_title', $deck->title.' - SlideWiki' );
		$this->set ( 'page_keywords', join ( ',', $deck->getTags ( $deck->id ) ) );
	}
	function activities() {
		$stream = new Stream ();
		$stream->getMainPageStream ( 50 );
		$this->set ( 'stream', $stream );
		$this->set ( 'page_title', 'Latest activities - SlideWiki' );
		$this->set ( 'page_keywords', 'SlideWiki, activities, presentations');
	}

        function test(){
            $item_id=$_GET['id'];
            $test = new Test();
            $test->createFromItem($item_id);
            $test->questions = $test->getAllQuestions();
            $this->set('test',$test);
            $this->set ( 'page_title', 'SlideWiki - List of questions for '.$test->title );
			$this->set ( 'page_keywords', 'SlideWiki, questions');
        }
}


text:
package com.github.dockerjava.jaxrs;

import static javax.ws.rs.client.Entity.entity;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.github.dockerjava.api.command.PushImageCmd;
import com.github.dockerjava.api.command.PushImageCmd.Response;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.PushEventStreamItem;

// Shaded, but imported
import com.google.common.collect.ImmutableList;

public class PushImageCmdExec extends AbstrDockerCmdExec<PushImageCmd, Response> implements PushImageCmd.Exec {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(PushImageCmdExec.class);

	public PushImageCmdExec(WebTarget baseResource) {
		super(baseResource);
	}

	@Override
	protected ResponseImpl execute(PushImageCmd command) {
		WebTarget webResource = getBaseResource().path("/images/" + name(command) + "/push")
		    .queryParam("tag", command.getTag());

		final String registryAuth = registryAuth(command.getAuthConfig());
		LOGGER.trace("POST: {}", webResource);
		InputStream is =  webResource
                .request()
				.header("X-Registry-Auth", registryAuth)
				.accept(MediaType.APPLICATION_JSON)
				.post(
				    entity(Response.class, MediaType.APPLICATION_JSON)).readEntity(
			InputStream.class);

	  return new ResponseImpl(is);
	}

	private String name(PushImageCmd command) {
		String name = command.getName();
		AuthConfig authConfig = command.getAuthConfig();
		return name.contains("/") ? name : authConfig.getUsername();
	}

  public static class ResponseImpl extends Response {

    private final InputStream proxy;

    ResponseImpl(InputStream proxy) {
      this.proxy = proxy;
    }

    @Override
    public Iterable<PushEventStreamItem> getItems() throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      // we'll be reading instances of MyBean
      ObjectReader reader = mapper.reader(PushEventStreamItem.class);
      // and then do other configuration, if any, and read:
      Iterator<PushEventStreamItem> items = reader.readValues(proxy);

        try {
            return ImmutableList.copyOf(items);
        } finally {
            proxy.close();
        }
    }

    @Override
    public int read() throws IOException {
      return proxy.read();
    }
  }
}


text:
module ActiveRecord
  # Represents exceptions that have propagated up through the JDBC API.
  class JDBCError < WrappedDatabaseException

    def initialize(message = nil, cause = $!)
      super( ( message.nil? && cause ) ? cause.message : message )
      if cause.is_a? Java::JavaSql::SQLException
        @jdbc_exception, @cause = cause, nil
      else
        @cause, @jdbc_exception = cause, nil
      end
    end

    # The DB (or JDBC driver implementation specific) vendor error code.
    # @see #jdbc_exception
    # @return [Integer, NilClass]
    def error_code
      if ( @error_code ||= nil ).nil?
        @error_code = jdbc_exception ? jdbc_exception.getErrorCode : nil
      else
        @error_code
      end
    end
    # @deprecated
    # @see #error_code
    def errno; error_code end

    # SQL code as standardized by ISO/ANSI and Open Group (X/Open), although
    # some codes have been reserved for DB vendors to define for themselves.
    # @see #jdbc_exception
    # @return [String, NilClass]
    def sql_state; jdbc_exception ? jdbc_exception.getSQLState : nil end

    # The full Java exception (SQLException) object that was raised (if any).
    # @note Navigate through chained exceptions using `jdbc_exception.next_exception`.
    def jdbc_exception; @jdbc_exception end
    alias_method :sql_exception, :jdbc_exception

    # true if the current error might be recovered e.g. by re-trying the transaction
    def recoverable?; jdbc_exception.is_a?(Java::JavaSql::SQLRecoverableException) end
    # true when a failed operation might be able to succeed when retried (e.g. timeouts)
    def transient?; jdbc_exception.is_a?(Java::JavaSql::SQLTransientException) end

    # Likely (but not necessarily) the same as {#jdbc_exception}.
    def cause; ( @cause ||= nil ) || jdbc_exception end
    # @override
    # @private for correct super-class (StatementInvalid) compatibility
    alias_method :original_exception, :cause

    # @override
    def set_backtrace(backtrace)
      @raw_backtrace = backtrace
      if ( nested = cause ) && ! nested.equal?(self)
        backtrace = backtrace - ( nested.respond_to?(:raw_backtrace) ? nested.raw_backtrace : nested.backtrace )
        backtrace << "#{nested.backtrace.first}: #{nested.message} (#{nested.class.name})"
        backtrace.concat nested.backtrace[1..-1] || []
      end
      super(backtrace)
    end

    # @private
    def raw_backtrace; @raw_backtrace ||= backtrace end

  end
end


text:
class Class # :nodoc:
  def class_inheritable_reader(*syms)
    syms.each do |sym|
      next if sym.is_a?(Hash)
      class_eval <<-EOS
        def self.#{sym}
          read_inheritable_attribute(:#{sym})
        end

        def #{sym}
          self.class.#{sym}
        end
      EOS
    end
  end

  def class_inheritable_writer(*syms)
    options = syms.last.is_a?(Hash) ? syms.pop : {}
    syms.each do |sym|
      class_eval <<-EOS
        def self.#{sym}=(obj)
          write_inheritable_attribute(:#{sym}, obj)
        end

        #{"
        def #{sym}=(obj)
          self.class.#{sym} = obj
        end
        " unless options[:instance_writer] == false }
      EOS
    end
  end

  def class_inheritable_array_writer(*syms)
    options = syms.last.is_a?(Hash) ? syms.pop : {}
    syms.each do |sym|
      class_eval <<-EOS
        def self.#{sym}=(obj)
          write_inheritable_array(:#{sym}, obj)
        end

        #{"
        def #{sym}=(obj)
          self.class.#{sym} = obj
        end
        " unless options[:instance_writer] == false }
      EOS
    end
  end

  def class_inheritable_hash_writer(*syms)
    options = syms.last.is_a?(Hash) ? syms.pop : {}
    syms.each do |sym|
      class_eval <<-EOS
        def self.#{sym}=(obj)
          write_inheritable_hash(:#{sym}, obj)
        end

        #{"
        def #{sym}=(obj)
          self.class.#{sym} = obj
        end
        " unless options[:instance_writer] == false }
      EOS
    end
  end

  def class_inheritable_accessor(*syms)
    class_inheritable_reader(*syms)
    class_inheritable_writer(*syms)
  end

  def class_inheritable_array(*syms)
    class_inheritable_reader(*syms)
    class_inheritable_array_writer(*syms)
  end

  def class_inheritable_hash(*syms)
    class_inheritable_reader(*syms)
    class_inheritable_hash_writer(*syms)
  end

  def inheritable_attributes
    @inheritable_attributes ||= EMPTY_INHERITABLE_ATTRIBUTES
  end

  def write_inheritable_attribute(key, value)
    if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES)
      @inheritable_attributes = {}
    end
    inheritable_attributes[key] = value
  end

  def write_inheritable_array(key, elements)
    write_inheritable_attribute(key, []) if read_inheritable_attribute(key).nil?
    write_inheritable_attribute(key, read_inheritable_attribute(key) + elements)
  end

  def write_inheritable_hash(key, hash)
    write_inheritable_attribute(key, {}) if read_inheritable_attribute(key).nil?
    write_inheritable_attribute(key, read_inheritable_attribute(key).merge(hash))
  end

  def read_inheritable_attribute(key)
    inheritable_attributes[key]
  end

  def reset_inheritable_attributes
    @inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES
  end

  private
    # Prevent this constant from being created multiple times
    EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze unless const_defined?(:EMPTY_INHERITABLE_ATTRIBUTES)

    def inherited_with_inheritable_attributes(child)
      inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes)

      if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES)
        new_inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES
      else
        new_inheritable_attributes = inheritable_attributes.inject({}) do |memo, (key, value)|
          memo.update(key => (value.dup rescue value))
        end
      end

      child.instance_variable_set('@inheritable_attributes', new_inheritable_attributes)
    end

    alias inherited_without_inheritable_attributes inherited
    alias inherited inherited_with_inheritable_attributes
end