text:
#include <assert.h>
#include <jni.h>
#include <QPainter>
#include <QBrush>
#include <QLinearGradient>
#include <QPen>
#include <QPaintDevice>
#include <QPainterPath>
#include <QImage>
#include <QColor>
#include <gnu_java_awt_peer_qt_QtGraphics.h>
#include "nativewrapper.h"
#include "qtimage.h"
#include "qtstrings.h"
#include "qtcomponent.h"
#include "qtgraphics.h"
#include "qtfont.h"

// Constants from java.awt.AlphaComposite
#define CLEAR     1
#define SRC       2
#define DST       9
#define SRC_OVER  3
#define DST_OVER  4
#define SRC_IN    5
#define DST_IN    6
#define SRC_OUT   7
#define DST_OUT   8
#define SRC_ATOP  10
#define DST_ATOP  11
#define XOR       12

GraphicsPainter *getPainter( JNIEnv *env, jobject obj )
{
  jclass cls = env->GetObjectClass( obj );
  jfieldID field = env->GetFieldID( cls, "nativeObject", "J" );
  return (GraphicsPainter *)env->GetLongField( obj, field );
}

static void setNativePtr( JNIEnv *env, jobject obj, void *value )
{
  jlong longValue = (jlong) value;
  jclass cls = env->GetObjectClass( obj );
  jfieldID field = env->GetFieldID( cls, "nativeObject", "J" );
  env->SetLongField( obj, field, longValue );
}

static jobject getToolkit( JNIEnv *env, jobject obj )
{
  jclass cls = env->FindClass( "gnu/java/awt/peer/qt/QtGraphics" );

  jfieldID field = env->GetFieldID( cls, "toolkit",
				    "Lgnu/java/awt/peer/qt/QtToolkit;" );
  return env->GetObjectField( obj, field );
}

///////////////////////// JNI methods ////////////////////////////////

/**
 * Clones the parent QPainter object.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_cloneNativeContext
(JNIEnv *env, jobject obj, jobject parent)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, parent );
  assert( painter );
  QPainter *newPainter = new GraphicsPainter( painter->device() );
  assert( newPainter );
  setNativePtr(env, obj, newPainter);
}

/*
 * Start of JNI methods
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_initImage
(JNIEnv *env, jobject obj, jobject image)
{
  QImage *im = getQtImage( env, image );
  assert( im );
  QPainter *painter = new GraphicsPainter( im );
  assert( painter );
  setNativePtr(env, obj, painter);
  painter->setRenderHint(QPainter::TextAntialiasing);
  painter->setRenderHint(QPainter::Antialiasing);
  painter->setRenderHint(QPainter::SmoothPixmapTransform);
}

/*
 * Start of JNI methods
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_initVolatileImage
(JNIEnv *env, jobject obj, jobject image)
{
  QPixmap *im = getQtVolatileImage( env, image );
  assert( im );
  QPainter *painter = new GraphicsPainter( im );
  assert( painter );
  setNativePtr(env, obj, painter);
  painter->setRenderHint(QPainter::TextAntialiasing);
  painter->setRenderHint(QPainter::Antialiasing);
  painter->setRenderHint(QPainter::SmoothPixmapTransform);
}

/**
 * Deletes the QPainter
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_delete
(JNIEnv *env, jobject obj)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  setNativePtr( env, obj, NULL );
  if( painter )
    {
      if( painter->isActive() )
 	painter->end();
      delete painter;
    }
}

///////////////////////////////////////////////////////////
/*
 * Sets the clip to a path.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setClipNative
(JNIEnv *env, jobject obj, jobject path)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  QPainterPath *pp = (QPainterPath *)getNativeObject( env, path );
  assert( pp );
  painter->setClipPath( *pp );
}

/*
 * Sets the clip to a rectangle.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setClipRectNative
(JNIEnv *env, jobject obj, jint x, jint y, jint w, jint h)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  painter->setClipRect( x, y, w, h );
}

/*
 * Intersects a shape with the current clip.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_intersectClipNative
(JNIEnv *env, jobject obj, jobject path)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  QPainterPath *pp = (QPainterPath *)getNativeObject( env, path );
  assert( pp );
  painter->setClipPath( *pp, Qt::IntersectClip );
}

/*
 * Intersect a rectangle with the current clip.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_intersectClipRectNative
(JNIEnv *env, jobject obj, jint x, jint y, jint w, jint h)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  painter->setClipRect( x, y, w, h, Qt::IntersectClip );
}

/*
 * Returns a QPainterPath object with the clip path of this painter.
 */
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_getClipNative
(JNIEnv *env, jobject obj)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  jclass cls = env->FindClass("gnu/java/awt/peer/qt/QPainterPath");
  jmethodID method = env->GetMethodID(cls, "<init>", "()V");

  jobject ppo = env->NewObject(cls, method);
  QPainterPath qpp = painter->clipPath();
  setNativeObject(env, ppo, &qpp);

  env->DeleteLocalRef( cls );
  return ppo;
}

/*
 * Returns a Rectangle with the bounds of this painters clip path.
 */
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_getClipBounds
(JNIEnv *env, jobject obj)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  qreal x, y, w, h;
  painter->clipPath().boundingRect().getRect(&x, &y, &w, &h);

  jclass cls = env->FindClass("java/awt/Rectangle");
  assert( cls != NULL);
  jmethodID mid = env->GetMethodID(cls, "<init>", "(IIII)V");
  assert( mid != NULL);
  jvalue values[4];

  values[0].i = (jint) x;
  values[1].i = (jint) y;
  values[2].i = (jint) w;
  values[3].i = (jint) h;

  return env->NewObjectA(cls, mid, values);
}

///////////////////////// Color stuff ////////////////////////
/**
 *
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setColor
(JNIEnv *env, jobject obj, jint r, jint g, jint b, jint alpha)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  assert( painter );
  painter->currentPen->setColor( QColor(r, g, b, alpha) );
  painter->setPen( *painter->currentPen );
  painter->currentBrush = new QBrush( QColor(r, g, b, alpha) );
  painter->setBrush( *painter->currentBrush );
  painter->currentColor = new QColor(r, g, b, alpha);
}

JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setAlphaNative
  (JNIEnv *env, jobject obj, jdouble alpha)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  assert( painter );

  QColor c = painter->currentPen->color();
  c.setAlphaF( (qreal)alpha );
  painter->currentPen->setColor(c);

  c = painter->currentBrush->color();
  c.setAlphaF( (qreal)alpha );
  painter->currentBrush->setColor( c );
}

/*
 * Class:     gnu_java_awt_peer_qt_QtGraphics
 * Method:    drawNative
 * Signature: (Lgnu/java/awt/peer/qt/QPainterPath;)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_drawNative
(JNIEnv *env, jobject obj, jobject path)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  assert( painter );
  QPainterPath *pp = (QPainterPath *)getNativeObject( env, path );
  assert( pp );
  painter->setPen( *painter->currentPen );
  painter->setBrush( Qt::NoBrush );
  painter->drawPath( *pp );
}

/*
 * Class:     gnu_java_awt_peer_qt_QtGraphics
 * Method:    fillNative
 * Signature: (Lgnu/java/awt/peer/qt/QPainterPath;)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_fillNative
(JNIEnv *env, jobject obj, jobject path)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  assert( painter );
  QPainterPath *pp = (QPainterPath *)getNativeObject( env, path );
  assert( pp );

  painter->setPen(Qt::NoPen);
  painter->setBrush( *painter->currentBrush );
  painter->drawPath( *pp );
}

/**
 * Draws a string.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_drawStringNative
(JNIEnv *env, jobject obj, jstring str, jdouble x, jdouble y)
{
  GraphicsPainter *painter = getPainter( env, obj );
  assert( painter );
  QString *qStr = getQString(env, str);
  painter->setBrush( Qt::NoBrush );
  painter->setPen( *painter->currentPen );
  painter->drawText(QPointF( (qreal)x, (qreal)y ), *qStr);
  delete qStr;
}

/*
 * Sets the native stroke
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setNativeStroke
(JNIEnv *env, jobject obj, jobject stroke)
{
  GraphicsPainter *painter = (GraphicsPainter *)getPainter( env, obj );
  assert( painter );
  QPen *pen = (QPen *)getNativeObject(env, stroke);
  assert( pen );
  painter->currentPen = new QPen( *pen );
  painter->setPen( *painter->currentPen );
}

/*
 * Sets the transform
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setQtTransform
(JNIEnv *env, jobject obj, jobject matrix)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  QMatrix *m = (QMatrix *)getNativeObject( env, matrix );
  assert( m );
  painter->setMatrix( *m );
}

/**
 * Set the font
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setFontNative
(JNIEnv *env, jobject obj, jobject fontpeer)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  QFont *font = (QFont *) getFont( env, fontpeer );
  assert( font );
  painter->setFont( *font );
}

/*
 * Sets Porter-Duff compositing.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setNativeComposite
(JNIEnv *env, jobject obj, jint compositeMode)
{
  QPainter *painter = getPainter( env, obj );
  assert( painter );
  QPainter::CompositionMode mode;

  switch( compositeMode )
    {
    case CLEAR:
      mode = QPainter::CompositionMode_Clear;
      break;
    case SRC:
      mode = QPainter::CompositionMode_Source;
      break;
    case DST:
      mode = QPainter::CompositionMode_Destination;
      break;
    case SRC_OVER:
      mode = QPainter::CompositionMode_SourceOver;
      break;
    case DST_OVER:
      mode = QPainter::CompositionMode_DestinationOver;
      break;
    case SRC_IN:
      mode = QPainter::CompositionMode_SourceIn;
      break;
    case DST_IN:
      mode = QPainter::CompositionMode_DestinationIn;
      break;
    case SRC_OUT:
      mode = QPainter::CompositionMode_SourceOut;
      break;
    case DST_OUT:
      mode = QPainter::CompositionMode_DestinationOut;
      break;
    case SRC_ATOP:
      mode = QPainter::CompositionMode_SourceAtop;
      break;
    case DST_ATOP:
      mode = QPainter::CompositionMode_DestinationAtop;
      break;
    case XOR:
      mode = QPainter::CompositionMode_Xor;
      break;
    }
  painter->setCompositionMode( mode );
}

/**
 * Sets the current brush to a linear gradient.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_setLinearGradient
(JNIEnv *env, jobject obj, jint r1, jint g1, jint b1, jint r2, jint g2,
jint b2, jdouble x1, jdouble y1, jdouble x2, jdouble y2, jboolean cyclic)
{
  GraphicsPainter *painter = getPainter( env, obj );
  assert( painter );
  QLinearGradient *lg = new QLinearGradient(QPointF( (qreal)x1, (qreal)y1 ),
					    QPointF( (qreal)x2, (qreal)y2 ) );
  lg->setColorAt( (qreal)0.0, QColor(r1, g1, b1) );
  lg->setColorAt( (qreal)1.0, QColor(r2, g2, b2) );
  if( cyclic == JNI_TRUE )
    lg->setSpread( QGradient::ReflectSpread );
  else
    lg->setSpread( QGradient::PadSpread );
  painter->currentBrush = new QBrush( *lg );
  delete lg;
}

/*
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_fill3DRect
(JNIEnv *env, jobject obj, jint x, jint y, jint w, jint h, jboolean raised)
{
  GraphicsPainter *painter = getPainter( env, obj );
  assert( painter );
  // FIXME: Adjust colors
  painter->fillRect ( x, y, w, h, QBrush( *painter->currentColor) );
  QPen *p = new QPen( *painter->currentColor );
  p->setWidth( 1 );
  painter->setPen( *p );
  painter->drawLine( x + w, y, x + w, y + h);
  painter->drawLine( x, y + h, x + w, y + h);
}

/*
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtGraphics_draw3DRect
(JNIEnv *env, jobject obj, jint x, jint y, jint w, jint h, jboolean raised)
{
  GraphicsPainter *painter = getPainter( env, obj );
  assert( painter );
  // FIXME: Adjust colors
  QPen *p = new QPen( *painter->currentColor );
  p->setWidth( 1 );
  painter->setPen( *p );
  painter->drawLine( x, y, x + w, y );
  painter->drawLine( x, y, x, y + h);
  painter->drawLine( x + w, y, x + w, y + h);
  painter->drawLine( x, y + h, x + w, y + h);
}


text:
package org.jump.parser;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.BailErrorStrategy;
import java.util.*;

import org.jump.parser.grammer.*;

public class JumpGen {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String str = "";
        str += "   # hello world \n sql() {\"yes\"} \n";

        str += "    # text";
        if (args.length > 0) {
            str = args[0];
        }

        ANTLRInputStream input = new ANTLRInputStream(str);
        JumpLexer lexer = new JumpLexer(input);

        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JumpParser parser = new JumpParser(tokens);
        parser.setErrorHandler(new BailErrorStrategy());

        ParseTree tree = parser.statement();
        Analyzer builder = new Analyzer();
        ArrayList<Object> res = (ArrayList<Object>) builder.visit(tree);
        System.out.println("Finally obtained string is: " + res.toString());
    }

    @SuppressWarnings("unchecked")
    public ParseResult parse(String queryString) {
        ANTLRInputStream input = new ANTLRInputStream(queryString);
        JumpLexer lexer = new JumpLexer(input);
        lexer.removeErrorListeners();
        lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);

        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JumpParser parser = new JumpParser(tokens);
        parser.removeErrorListeners();
        parser.addErrorListener(DescriptiveErrorListener.INSTANCE);

        ParseTree tree = parser.statement();
        Analyzer builder = new Analyzer();
        ArrayList<AbstractCommand> res = (ArrayList<AbstractCommand>) builder.visit(tree);

        return new ParseResult(res);
    }
}

redpajama_set_name: RedPajamaGithub


text:
{
  var _ref = babelHelpers.asyncToGenerator(function*() {
    let g = (() => {
      var _ref2 = babelHelpers.asyncGenerator.wrap(function*() {
        yield babelHelpers.asyncGenerator.await(2);
        yield 3;
      });

      return function g() {
        return _ref2.apply(this, arguments);
      };
    })();

    yield 1;
  });

  return function f() {
    return _ref.apply(this, arguments);
  };
}


text:
require 'ffi'

class FFI::Pointer
  def read_array_of_string
    elements = []

    loc = self

    until ((element = loc.read_pointer).null?)
     elements << element.read_string
     loc += FFI::Type::POINTER.size
    end

    elements
  end
end


text:
import Product from '@vue-storefront/core/modules/catalog/types/Product';
import { hasConfigurableChildren } from '../';
/**
 * Fill custom attributes for every configurable child
 */
export default function setCustomAttributesForChild (product: Product) {
  if (!hasConfigurableChildren(product)) return
  // handle custom_attributes for easier comparing in the future
  product.configurable_children.forEach((child) => {
    let customAttributesAsObject = {}
    if (child.custom_attributes) {
      child.custom_attributes.forEach((attr) => {
        customAttributesAsObject[attr.attribute_code] = attr.value
      })
      // add values from custom_attributes in a different form
      Object.assign(child, customAttributesAsObject)
    }
  })
}


text:
domainname localdomain

# Setup EPEL
repo=/etc/yum.repos.d/epel.repo
if [ ! -f $repo ] ; then

    cat <<EOM >/etc/yum.repos.d/epel-bootstrap.repo
[epel]
name=Bootstrap EPEL
mirrorlist=http://mirrors.fedoraproject.org/mirrorlist?repo=epel-\$releasever&arch=\$basearch
failovermethod=priority
enabled=0
gpgcheck=0
EOM

    yum --enablerepo=epel -y install epel-release || exit 1
    rm -f /etc/yum.repos.d/epel-bootstrap.repo
    if [ ! -f $repo ] ; then
	echo "Failed to bootstrap EPEL: no such file $repo"
	exit 1
    fi

    # Horrible hack no.1 to work around a broken mirror
    (
	grep -v mirrors.fedoraproject.org /etc/hosts
	echo '66.135.62.187	mirrors.fedoraproject.org'
    ) >> /etc/hosts.NEW && mv -f /etc/hosts.NEW /etc/hosts
    # Horrible hack no.2 to work around a broken mirror
    sed -e 's|https://|http://|g' < $repo > $repo.NEW && mv -f $repo.NEW $repo
fi

yum -y groupinstall 'Development Tools'
yum -y install \
    git valgrind-devel binutils-devel libxml2-devel \
    doxygen perl-XML-LibXML strace python-pip
pip install breathe Sphinx


text:
import { RequestHandler } from "express";

declare function connectTrimBodyMiddleware(): RequestHandler;

export = connectTrimBodyMiddleware;


text:
package erratic

import (
	"context"
	"testing"

	"github.com/coredns/coredns/plugin/pkg/dnstest"
	"github.com/coredns/coredns/plugin/test"

	"github.com/miekg/dns"
)

func TestErraticDrop(t *testing.T) {
	e := &Erratic{drop: 2} // 50% drops

	tests := []struct {
		rrtype       uint16
		expectedCode int
		expectedErr  error
		drop         bool
	}{
		{rrtype: dns.TypeA, expectedCode: dns.RcodeSuccess, expectedErr: nil, drop: true},
		{rrtype: dns.TypeA, expectedCode: dns.RcodeSuccess, expectedErr: nil, drop: false},
		{rrtype: dns.TypeAAAA, expectedCode: dns.RcodeSuccess, expectedErr: nil, drop: true},
		{rrtype: dns.TypeHINFO, expectedCode: dns.RcodeServerFailure, expectedErr: nil, drop: false},
	}

	ctx := context.TODO()

	for i, tc := range tests {
		req := new(dns.Msg)
		req.SetQuestion("example.org.", tc.rrtype)

		rec := dnstest.NewRecorder(&test.ResponseWriter{})
		code, err := e.ServeDNS(ctx, rec, req)

		if err != tc.expectedErr {
			t.Errorf("Test %d: Expected error %q, but got %q", i, tc.expectedErr, err)
		}
		if code != int(tc.expectedCode) {
			t.Errorf("Test %d: Expected status code %d, but got %d", i, tc.expectedCode, code)
		}

		if tc.drop && rec.Msg != nil {
			t.Errorf("Test %d: Expected dropped message, but got %q", i, rec.Msg.Question[0].Name)
		}
	}
}

func TestErraticTruncate(t *testing.T) {
	e := &Erratic{truncate: 2} // 50% drops

	tests := []struct {
		expectedCode int
		expectedErr  error
		truncate     bool
	}{
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, truncate: true},
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, truncate: false},
	}

	ctx := context.TODO()

	for i, tc := range tests {
		req := new(dns.Msg)
		req.SetQuestion("example.org.", dns.TypeA)

		rec := dnstest.NewRecorder(&test.ResponseWriter{})
		code, err := e.ServeDNS(ctx, rec, req)

		if err != tc.expectedErr {
			t.Errorf("Test %d: Expected error %q, but got %q", i, tc.expectedErr, err)
		}
		if code != int(tc.expectedCode) {
			t.Errorf("Test %d: Expected status code %d, but got %d", i, tc.expectedCode, code)
		}

		if tc.truncate && !rec.Msg.Truncated {
			t.Errorf("Test %d: Expected truncated message, but got %q", i, rec.Msg.Question[0].Name)
		}
	}
}

func TestAxfr(t *testing.T) {
	e := &Erratic{truncate: 0} // nothing, just check if we can get an axfr

	ctx := context.TODO()

	req := new(dns.Msg)
	req.SetQuestion("example.org.", dns.TypeAXFR)

	rec := dnstest.NewRecorder(&test.ResponseWriter{})
	_, err := e.ServeDNS(ctx, rec, req)
	if err != nil {
		t.Errorf("Failed to set up AXFR: %s", err)
	}
	if x := rec.Msg.Answer[0].Header().Rrtype; x != dns.TypeSOA {
		t.Errorf("Expected for record to be %d, got %d", dns.TypeSOA, x)
	}
}


text:
@media screen {
	body {
		width: 8.3in;
	}
}

html, body, div, span, td {
	font-family: "Helvetica", "Arial", sans-serif;
	font-size: 12px;
}

body {
	padding: 10px;
	margin: auto;
	font-size: 12px;
	line-height: 150%;
}

.common {
	font-family: "Helvetica", "Arial", sans-serif !important;
	font-size: 12px;
	padding: 10px 0px;
}

table {
	border-collapse: collapse;
	width: 100%;
	vertical-align: top;
	border-style: none !important;
}

table td {
	padding: 2px 0px;
	border-style: none !important;
}

table.table-bordered td,
table.table-bordered th {
	padding: 2px;
	vertical-align: top;
}

table h1, h2, h3, h4, h5, h6 {
	padding: 0px;
	margin: 0px;
}

table.header-table td {
	vertical-align: top;
}

table.header-table h1 {
	text-transform: uppercase;
	color: white;
	font-size: 55px;
	font-style: italic;
}

table.header-table thead tr:nth-child(1) td {
	height: 24px;
	background-color: #696969;
	vertical-align: middle;
	padding: 12px 0px 0px 0px;
	width: 100%;
}

div.page-body table td:nth-child(6),
div.page-body table td:nth-child(7) {
	text-align: right;
}

div.page-body table tr td {
	background-color: #DCDCDC !important;
}

div.page-body table th {
	background-color: #696969 !important;
	color: white !important;
}

table.footer-table td {
	vertical-align: top;
}

table.footer-table td table td:nth-child(2),
table.footer-table td table td:nth-child(3) {
	text-align: right;
}

table.footer-table tfoot td {
	background-color: #696969;
	height: 10px;
}

.imp-details {
	background-color: #DCDCDC;
}


text:
using System.IO;
using System.Xml.Linq;

namespace TraverseDirectoryXDocument
{
    public class StartUp
    {
        private const string RootDirectory = "../../../../02.XMLProccesingDotNET";
        private const string XMLPathDirectory = "../../direcorty.xml";

        public static void Main()
        {
            var directory = TraverseDirectory(RootDirectory);
            directory.Save(XMLPathDirectory);
        }

        private static XElement TraverseDirectory(string dir)
        {
            var element = new XElement("dir", new XAttribute("path", dir));

            foreach (var directory in Directory.GetDirectories(dir))
            {
                element.Add(TraverseDirectory(directory));
            }

            foreach (var file in Directory.GetFiles(dir))
            {
                element.Add(new XElement("file",
                    new XAttribute("name", Path.GetFileNameWithoutExtension(file)),
                    new XAttribute("ext", Path.GetExtension(file)
                    )));
            }

            return element;
        }
    }
}


text:
layout: post
date: 2016-07-11
title: "Pearl by Alexia Designs Style 1019 GLADIOLUS"
category: Pearl by Alexia Designs
tags: [Pearl by Alexia Designs]
---
### Pearl by Alexia Designs Style 1019 GLADIOLUS
Just **$369.99**
###

BRANDS	Pearl by Alexia Designs

Buy it: [https://www.readybrides.com/en/pearl-by-alexia-designs/46859-pearl-by-alexia-designs-style-1019-gladiolus.html](https://www.readybrides.com/en/pearl-by-alexia-designs/46859-pearl-by-alexia-designs-style-1019-gladiolus.html)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.gkehub.v1alpha.model;

/**
 * **Policy Controller**: Configuration for a single cluster. Intended to parallel the
 * PolicyController CR.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the GKE Hub API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class PolicyControllerMembershipSpec extends com.google.api.client.json.GenericJson {

  /**
   * Policy Controller configuration for the cluster.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private PolicyControllerHubConfig policyControllerHubConfig;

  /**
   * Version of Policy Controller installed.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String version;

  /**
   * Policy Controller configuration for the cluster.
   * @return value or {@code null} for none
   */
  public PolicyControllerHubConfig getPolicyControllerHubConfig() {
    return policyControllerHubConfig;
  }

  /**
   * Policy Controller configuration for the cluster.
   * @param policyControllerHubConfig policyControllerHubConfig or {@code null} for none
   */
  public PolicyControllerMembershipSpec setPolicyControllerHubConfig(PolicyControllerHubConfig policyControllerHubConfig) {
    this.policyControllerHubConfig = policyControllerHubConfig;
    return this;
  }

  /**
   * Version of Policy Controller installed.
   * @return value or {@code null} for none
   */
  public java.lang.String getVersion() {
    return version;
  }

  /**
   * Version of Policy Controller installed.
   * @param version version or {@code null} for none
   */
  public PolicyControllerMembershipSpec setVersion(java.lang.String version) {
    this.version = version;
    return this;
  }

  @Override
  public PolicyControllerMembershipSpec set(String fieldName, Object value) {
    return (PolicyControllerMembershipSpec) super.set(fieldName, value);
  }

  @Override
  public PolicyControllerMembershipSpec clone() {
    return (PolicyControllerMembershipSpec) super.clone();
  }

}


text:
package com.consol.citrus.config.xml;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import com.consol.citrus.container.Template;

/**
 * Bean definition parser for template definition in test case.
 *
 * @author Christoph Deppisch
 */
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public class TemplateParser implements BeanDefinitionParser {

    /**
     * @see org.springframework.beans.factory.xml.BeanDefinitionParser#parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
     */
	public BeanDefinition parse(Element element, ParserContext parserContext) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Template.class);

        DescriptionElementParser.doParse(element, builder);

        String name = element.getAttribute("name");
        if (!StringUtils.hasText(name)) {
            throw new BeanCreationException("Must specify proper template name attribute");
        }

        builder.addPropertyValue("name", element.getLocalName() + "(" + element.getAttribute("name") + ")");

        String globalContext = element.getAttribute("global-context");
        if (StringUtils.hasText(globalContext)) {
            builder.addPropertyValue("globalContext", globalContext);
        }

        ActionContainerParser.doParse(element, parserContext, builder);

        parserContext.getRegistry().registerBeanDefinition(name, builder.getBeanDefinition());
        return parserContext.getRegistry().getBeanDefinition(name);
    }
}


text:
{% extends 'forms/base_widget.html' %}

{% block html %}
    <input type="hidden" id="{{ field.id }}" name="{{ field.name }}" value="{{ field._value() | tojson | forceescape }}">

{% endblock %}

{% block javascript %}

{% endblock %}


text:
import java.util.*;
import java.util.stream.*;

public class _565_PizzaAnyone{
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		List<int[]> constraints = new ArrayList<>();
		while(s.hasNext()){
			String line = s.nextLine().replace(";", "");
			if(!line.trim().equals(".")){
				int[] pair = new int[2];
				for(int i = 0; i < line.length(); i += 2){
					if(line.charAt(i) == '+'){
						pair[0] |= 1 << toCode(line.charAt(i + 1));
					}else{
						pair[1] |= 1 << toCode(line.charAt(i + 1));
					}
				}
				constraints.add(pair);
			}else{
				int toppings = getToppingCombination(constraints);
        if(toppings == NO_PIZZA) System.out.println("No pizza can satisfy these requests.");
        else System.out.printf("Toppings: %s\n", toString(toppings));
				constraints = new ArrayList<>();
			}
		}
	}

  static String toString(int toppingCombination){
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < 16; i++){
      if((toppingCombination & (1 << i)) > 0){
        sb.append(getTopping(i));
      }
    }
    return sb.toString();
  }

	static final int NO_PIZZA = -1;
	static int getToppingCombination(List<int[]> constraints){
		for(int toppingCombination = 0; toppingCombination < (1 << 16); toppingCombination++){
			if(satisfiesAllConstraints(toppingCombination, constraints)){
				return toppingCombination;
			}
		}
		return NO_PIZZA;
	}

	static boolean satisfiesAllConstraints(int toppingCombination, List<int[]> constraints){
		for(int[] constraint : constraints){
      int includeToppings = constraint[0];
      int omitToppings = constraint[1];
			boolean satisfied = (toppingCombination & includeToppings) > 0;
      if(!satisfied) satisfied = (((1 << 16) - 1 - toppingCombination) & omitToppings) > 0;
			if(!satisfied) return false;
		}
		return true;
	}

	static int toCode(char topping){
		return topping - 'A';
	}

	static char getTopping(int code){
		return (char)('A' + code);
	}
}


text:
namespace Microsoft.Azure.KeyVault.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// The key restore parameters
    /// </summary>
    public partial class KeyRestoreParameters
    {
        /// <summary>
        /// Initializes a new instance of the KeyRestoreParameters class.
        /// </summary>
        public KeyRestoreParameters() { }

        /// <summary>
        /// Initializes a new instance of the KeyRestoreParameters class.
        /// </summary>
        /// <param name="keyBundleBackup">the backup blob associated with a
        /// key bundle</param>
        public KeyRestoreParameters(byte[] keyBundleBackup)
        {
            KeyBundleBackup = keyBundleBackup;
        }

        /// <summary>
        /// Gets or sets the backup blob associated with a key bundle
        /// </summary>
        [JsonConverter(typeof(Base64UrlJsonConverter))]
        [JsonProperty(PropertyName = "value")]
        public byte[] KeyBundleBackup { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (KeyBundleBackup == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "KeyBundleBackup");
            }
        }
    }
}


text:
* Added ability to download files directly for non-tabular data
* Added scripts to download Bioclim and Mammal Supertree data
* Added a script for the MammalDIET database
* Fixed bug where some nationally standardized FIA surveys where not included
* Added check for wxpython on installation to allow non-gui installs
* Fixed several minor issues with Gentry script including a missing site and a column in one file that was misnamed
* Windows install now adds the retriever to the path to facilitate command line use
* Fixed a bug preventing installation from PyPI
* Added icons to installers
* Fixed the retriever failing when given a script it couldn't handle

# v1.6.0

* Added full OS X support to the Retriever
* Added a proper Windows installer
* Fixed a number of bugs


text:
import { TropicalWarning32 } from "../../";

export = TropicalWarning32;


text:
print "Using native Sybase Open Client\n"
require_dependency 'models/course'
require 'logger'

ActiveRecord::Base.logger = Logger.new("debug.log")

ActiveRecord::Base.configurations = {
  'arunit' => {
    :adapter  => 'sybase',
    :host     => 'database_ASE',
    :username => 'sa',
    :database => 'activerecord_unittest'
  },
  'arunit2' => {
    :adapter  => 'sybase',
    :host     => 'database_ASE',
    :username => 'sa',
    :database => 'activerecord_unittest2'
  }
}

ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'


text:
using System;
using System.IO;
using LiteDB.Platform;

namespace LiteDB.Tests
{
    public class TestBase
    {
        public TestBase()
        {
            LitePlatform.Initialize(new LitePlatformFullDotNet());
        }
    }

    public class TestPlatform
    {
        public static string GetFullPath(string filename)
        {
            return Path.GetFullPath(Directory.GetCurrentDirectory() + "../../../../TestResults/") + filename;
        }

        public static long GetFileSize(string filename)
        {
            return new FileInfo(filename).Length;
        }

        public static void FileWriteAllText(string filename, string content)
        {
            File.WriteAllText(filename, content);
        }

        public static void DeleteFile(string filename)
        {
            File.Delete(filename);
        }

        public static string FileReadAllText(string filename)
        {
            return File.ReadAllText(filename);
        }
    }
}


text:
package server

import (
	"github.com/stretchr/testify/assert"
	"net/http"
	"testing"
)

func TestAccessTokenFromXForwarded(t *testing.T) {
	req := &http.Request{
		Header: map[string][]string{
			forwardedHeader: {"tok"},
		},
	}

	assert.Equal(t, "tok", getAccessToken(req))
}

func TestAccessTokenFromAuthBearerFormatted(t *testing.T) {
	req := &http.Request{
		Header: map[string][]string{
			authHeader: {"Bearer tok"},
		},
	}

	assert.Equal(t, "tok", getAccessToken(req))
}

func TestAccessTokenFromAuthUnexpectedFormat(t *testing.T) {
	req := &http.Request{
		Header: map[string][]string{
			authHeader: {"tok"},
		},
	}

	assert.Equal(t, "tok", getAccessToken(req))
}


text:
var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    _ = require('underscore'),
    url = require('url'),
    URI = require('URIjs'),
    Path = require('path');

var errors = {
  'notimplemented': function(method, cls){
    Error.call(this); //super constructor
    Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object

    this.name = 'Method not implemented';
    this.message =  method + ' - must be implemented when extending ' + cls;
  },
  'import_problem': function(problem){
    Error.call(this); //super constructor
    Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object

    this.name = 'Import Error';
    this.message = problem;
  },
  'tbi': function(func){
    Error.call(this); //super constructor
    Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object

    this.name = 'Function not defined (yet)';
    this.message = 'The function ' + func + ' has not been written yet please provide your own';
  }
};

Object.keys(errors).forEach(function(fnName){
  util.inherits(errors[fnName], Error);
});

var readyStates = {
  'unitialised': 0,
  'initialised': 1,
  'running': 2,
  'complete': 3
};

/**
 * Very simple log function that outputs to console
 *
 * @param {string} message Message to push to console
 * @param {string} level The type of message
 */
function basicLogger (message, level){
  if(!level || !console[level]){
    level = 'log';
  }

  console[level](message);
}

/**
 * BaseImporter psuedo class to be extended
 *
 */
function BaseImporter () {
  //some intialising stuff
  //expects extending class to call
  //newClass.super_.call(this);
  this._schema = null;
  this._export = null;
  this._types = {};
  this._model = {
    properties:{},
    definitions:{},
    ids:{}
  };
  this.error = null;

  var baseImporter = this; //alias to keep scope of this

  //setup listeners
  this.on('readyStateChanged', function (readyState) {
    //state changed
    if(readyStates.complete === readyState){
      //state says loading has finished
      if(baseImporter.error){
        //the load failed
        baseImporter.emit('failed', baseImporter.error);
      } else {
        //the load succeeded
        baseImporter.emit('success', null, baseImporter.getModel());
      }

      console.log('Import complete');

      //finally send general complete notification
      baseImporter.emit('complete', baseImporter.error, baseImporter.getModel());
    }
  });
}

util.inherits(BaseImporter, EventEmitter);

BaseImporter.prototype.keywords = ['title', 'description', 'default', 'multipleOf', 'maximum', 'exclusiveMaximum',
                                   'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'items',
                                   'enum', 'type', 'required'];

/**
 * Abstract function to be overwritten
 *
 * @param {object} schema, Description
 * @param {function} callback Description
 */
BaseImporter.prototype.importSchema = function (schema, callback) {
  throw new errors.notimplemented('importSchema', 'BaseImporter');
};

/**
 * Abstract function to be overwritten
 */
BaseImporter.prototype.exportORM = function () {
  throw new errors.notimplemented('exportORM', 'BaseImporter');
};

/**
 * A function that will retrieve (and parse) a schema
 *
 * @param {string} uri URI to the schema to be loaded
 * @param {function} callback A callback function that will called with the requested schema
 */
BaseImporter.prototype.getExternalSchema = function (uri, callback) {
  throw new errors.tbi('getExternalSchema');
};

/**
 * Internal function to kick off import of schema
 */
BaseImporter.prototype.doImport = function () {
  var baseImporter = this;

  baseImporter.setReadyState(readyStates.running);

  baseImporter.indexIDs(this._schema, null, null, '', function(){
    process.nextTick(function () {
      baseImporter.emit('indexing:complete');
    });
  });

  baseImporter.on('indexing:complete', function () {

    baseImporter._export = {};

    //handle schema references
    if(baseImporter._schema.$ref){
      baseImporter.resolveRef.call(baseImporter,baseImporter._schema.$ref, function (ref){
        if(!ref){
          baseImporter.log('failed to resolve :: ' + baseImporter._schema.$ref);
          console.log(baseImporter._definitions);
        }else{
          //deal with a reference
          //@todo is this the best way to achieve this?
          baseImporter._model.properties = _.extend(baseImporter._model.properties, ref);
        }
        doImportContinue();
      });
    }else{
      doImportContinue();
    }

    //@todo get rid of this hacky hacky solution
    function doImportContinue () {
      if(baseImporter._schema.definitions){
        //deal with definitions
        Object.keys(baseImporter._schema.definitions).forEach(function(stDef){
          //@todo make pointer to the _model
          baseImporter.doImportDefinition.call(baseImporter, stDef, baseImporter._schema.definitions[stDef], baseImporter._model.definitions);
        });
      }

      if(baseImporter._schema.properties){
        Object.keys(baseImporter._schema.properties).forEach(function(stProp){
          baseImporter.doImportProperty.call(baseImporter, stProp, baseImporter._schema.properties[stProp], baseImporter._model.properties);
        });
      }

      baseImporter.setReadyState(readyStates.complete);
    }

  });

  baseImporter.on('indexing:failed', function (err) {
    baseImporter.error = err;
    baseImporter.setReadyState(readyStates.complete);
  });
};

/**
 * Returns the internal model of the schema
 *
 * @return {object}
 */
BaseImporter.prototype.getModel = function () {
  return this._model;
};

/**
 * Returns true if ready state is 'complete' and there are no errors
 *
 * @return boolean
 */
BaseImporter.prototype.isLoaded = function () {
  return this.getReadyState === readyStates.complete && false === this.error;
};

/**
 * Returns the current readyState
 *
 * @return int
 */
BaseImporter.prototype.getReadyState = function () {
  return this.readyState;
};

/**
 * Set the current readyState
 *
 * @param {string|int} newState Description
 * @return int
 */
BaseImporter.prototype.setReadyState = function (newState) {
  var currentState = this.readyState;

  if('number' === typeof newState){
    //assumes an integer would be direct from readyStates
    this.readyState = newState;
  }else if('string' === typeof newState){
    //only set if the string is a known state
    this.readyState = readyStates[newState] || this.readyState;
  }

  if(currentState !== this.readyState){
    //readyState has changed notify listeners
    this.emit('readyStateChanged', this.readyState);
  }

  return this.readyState;
};

/**
 * Load a schema from a json resource
 *
 * @param {string|buffer} schemaJSON Description
 */
BaseImporter.prototype.loadSchemaFromJSON = function (schemaJSON) {
  try{
    schema = JSON.parse(schemaJSON);
    if(schema){
      this._schema = schema;
      this.setReadyState(readyStates.initialised);
      this.doImport();
    }
  } catch (e) {
    this.error = e;
    this.setReadyState(readyStates.complete);
  }
};

/**
 * Function to walk the imported schema for ids
 * for use in reference resolutions
 *
 * @param {object} schemaIn The schema or part there of to be indexed
 * @param {string} scope Current scope to be used
 * @param {string} index Alternative id usually from the key of the property/definition
 * @param {function} callback Function to call when all actions complete
 */
BaseImporter.prototype.indexIDs = function (schemaIn, scope, index, path, callback) {
  var baseimporter = this;

  var currentScope = scope || false;
  var keys = Object.keys(schemaIn);
  var newScope = false;
  path = path || '';
  index = index || '';

  var listenFor = []; //array for use in recursion

  /**
   * Factory function for generating next tick
   * Always returns a function, though passed an undefined nextSchema the
   * returned function will be empty
   *
   * @param {object} nextSchema Object to index
   * @param {string} nextScope Scope to resolve against
   * @param {string} nextIndex Index of the property/definiton passed as nextSchema
   *
   * @return {function} a function to be passed to process.nextTick()
   */
  var factoryNext = function(nextSchema, nextScope, nextIndex, nextPath, nextCBack){
    var nSchema = nextSchema || false;
    var nScope = nextScope;
    var nIndex = nextIndex;
    var nPath = nextPath;
    var nCBack = nextCBack || function(){};

    if(false === nSchema){
      return function(){};
    }else{
      return function(){
        baseimporter.indexIDs.call(baseimporter, nSchema, nScope, nIndex, nPath, nCBack);
      };
    }
  };

  var myCallback = function ( name ) {
    if(-1 !== listenFor.indexOf(name)){
      listenFor.splice(listenFor.indexOf(name), 1);
    }
    if(0 === listenFor.length){
      //all child processes have reported in
      process.nextTick(function () {
        callback(index);
      });
    }
  };

  if(keys && keys.length){
    if(schemaIn.id){
      if(!currentScope){
        //no parent scope set to this id
        newScope = schemaIn.id;
      }else{
        var iduri = new URI(schemaIn.id);
        if(true === iduri.is('relative')){
          newScope = iduri.relativeTo(currentScope);
        }else if(true === iduri.is('absolute')){
          newScope = schemaIn.id;
        }
      }
    }else if('string' === typeof index){
      if(!currentScope){
        newScope = index;
      }else{
        var iduri = new URI(index);

        newScope = iduri.absoluteTo(currentScope).toString();
      }
    }

    if(false !== newScope){
      //store index
      baseimporter._model.ids[schemaIn.id||index] = {absolute:newScope};
      baseimporter._model.ids[schemaIn.id||index].path = Path.join(path, index);
      //continue loop down through
      //properties
      if(schemaIn.properties){
        //run the properties
        Object.keys(schemaIn.properties).forEach(function(prop){
          //recurrance - defer to nextTick
          listenFor.push(prop);
          process.nextTick(factoryNext(schemaIn.properties[prop], newScope, prop, Path.join(baseimporter._model.ids[schemaIn.id||index].path, 'properties'), myCallback));
        });
      }
      //definitions
      if(schemaIn.definitions){
        //run the properties
        Object.keys(schemaIn.definitions).forEach(function(def){
          //recurrance - defer to nextTick
          listenFor.push(def);
          process.nextTick(factoryNext(schemaIn.definitions[def], newScope, def, Path.join(baseimporter._model.ids[schemaIn.id||index].path,'definitions'), myCallback));
        });
      }
    }

    if(0 === listenFor.length){
      //not waiting for anything - fire the callback
      callback(index);
    }

  }
};

/**
 * Resolve a $ref in a schema
 *
 * @param {string} reference The reference to be reolved
 * @param {string} scope The resolution scope for the reference
 * @return {object|boolean} Returns false if the Ref cannot be resolved
 */
BaseImporter.prototype.resolveRef = function (reference, cback) {

  //types of reference
  // - Canonical (MUST)
  // - inline referencing (OPTIONAL)

  //types of reference
  // "#schema"
  // "#/definitions/schema"
  // "#/properties/schema"
  // "http://someplace.com/#properties/schema"
  // "http://someplace.com/#definitions/schema"

  var refURI = new URI(reference);
  var importer = this;

  if(refURI.is('absolute')){
    //Canonical
    importer.getExternalSchema(refURI.href(), function (err, schema) {
      if(err){
        return cback(false);
      }
      return cback(schema.findRef(refURI.fragment()));
    });
  }else if(refURI.is('relative')){
    //relative
    if(refURI.host()){
      importer.log('Problem resolving relative path with host');
    }else{
      //it's completely internal
      return cback(importer.findRef(refURI.fragment()));
    }
  }

  return false;
};

/**
 * Search by fragment
 *
 * @param {string} frag Fragment to search by
 */
BaseImporter.prototype.findRef = function (frag) {
  var searchId = Path.basename(frag);
  if(!searchId){
    searchId = Path.basename(Path.dirname(frag));
  }

  if(!searchId){
    throw new errors.import_problem('Cannot find searchid in ref from : ' + frag );
  }

  if(searchId == '.'){
    //root
    return this._model.properties;
  }

  if(this._model.ids[searchId]){

    //find from precalc'd path
    pth = this._model.ids[searchId].path.split('/');
    var pntr = this._model;

    pth.forEach(function(elname){
      if(pntr && pntr[elname]){
        pntr = pntr[elname];
      } else {
        pntr = false;
      }
    });

    return pntr;
  }else{
    this.log('findRef not fully implemented');
  }
};

/**
 * Function to import a definiton from an element
 *
 *
 * @param String stDef Description
 * @param Object src Description
 * @param Object parent Description
 */
BaseImporter.prototype.doImportDefinition = function ( stDef, src, parent){
  var baseImporter = this;

  //@todo more validation of input
  if('string' !== typeof stDef){
    throw new errors.import_problem('Property name type expected "String" but found "' + (typeof stDef) + '"');
  }

  if('object' !== typeof src){
    throw new errors.import_problem('Source element type expected "Object" but found "' + (typeof src) + '"');
  }

  if('object' !== typeof parent){
    throw new errors.import_problem('Parent element type expected "Object" but found "' + (typeof parent) + '"');
  }

  var def = parent[stDef] = {};

  baseImporter.keywords.forEach(function (stKey) {
    if('undefined' !== typeof src[stKey]){
      def[stKey] = src[stKey];
    }
  });

  if(src.properties){
    Object.keys(src.properties).forEach(function(stProp){
      baseImporter.doImportProperty.call(baseImporter, stProp, src.properties[stProp], def);
    });
  }

};

/**
 * @private
 * Function to import the properties from an element
 *
 * @param String stProp String of the property key
 * @param Object src The object from the schema
 * @param Object parent The target
 */
BaseImporter.prototype.doImportProperty = function ( stProp, src, parent){

  //@todo more validation of input
  if('string' !== typeof stProp){
    throw new errors.import_problem('Property name type expected "String" but found "' + (typeof stProp) + '"');
  }

  if('object' !== typeof src){
    throw new errors.import_problem('Source element type expected "Object" but found "' + (typeof src) + '"');
  }

  if('object' !== typeof parent){
    throw new errors.import_problem('Parent element type expected "Object" but found "' + (typeof parent) + '"');
  }

  //setup the export object
  var exprop = parent[stProp] = {};

  //check the property type
  if(src.type){
    exprop.type = src.type;
    //@todo move this to post process
    /*//check if this type can be mapped
    if(this._types[src.type]){
      exprop.type = this._types[src.type];
    }*/
  }

  var importer = this;
  //handle schema references
  if(src.$ref){
    importer.resolveRef.call(this,src.$ref, function (ref){
      if(!ref){
        importer.log('failed to resolve :: ' + src.$ref);
        console.log(importer._definitions);
      }else{
        //deal with a reference
        //@todo is this the best way to achieve this?
        exprop = parent[stProp] = _.extend(exprop,ref);
      }
      doImportPropContinue();

    });
  }else{
    doImportPropContinue();
  }

  function doImportPropContinue () {
    importer.keywords.forEach(function (stKey) {
      if('undefined' !== typeof src[stKey]){
        exprop[stKey] = src[stKey];
      }
    });

    //handle sub properties
    if(src.properties){
      Object.keys(src.properties).forEach(function(stSubProp){
        importer.doImportProperty.call(importer, stSubProp, src.properties[stSubProp], exprop);
      });
    }
  }
};

BaseImporter.prototype.log = basicLogger;

//import manager store references
//each one is an instance of BaseImporter
//
var importManagerCache = {};
var baseImportManagerDefaults = {
  importClass: BaseImporter,
  logger: false
};

function BaseImportManager (opts) {
  opts = opts || {};
  this.options = _.extend(baseImportManagerDefaults, opts);

  if(this.options.logger){
    this.log = this.options.logger;
  }
}

util.inherits(BaseImportManager, EventEmitter);

/**
 * Stub function for loading a file, to be provided by the implementor
 *
 * @param {string} uri Description
 * @param {function} callback Callback function to provided contents of the file at
 */
BaseImportManager.prototype.readFile = function (uri, callback) {
  callback(new errors.notimplemented('readFile', 'BaseImportManager'), null);
};

/**
 * Fetch a schema from the specified uri
 *
 * @param {string} uri URI to the schema
 * @param {function} callback The callback that will be called with schema as 2nd param
 */
BaseImportManager.prototype.fetchSchema = function (uri, callback) {

  if(!uri){
    return false;
  }

  if(importManagerCache[uri]){
    if(importManagerCache[uri].isLoaded()){
      callback(null, importManagerCache[uri]);
      return true;
    }else if(importManagerCache[uri].getReadyState() < readyStates.complete){
      //listen for the end event fired after success or failure to load
      importManagerCache[uri].once('complete', function(err, model){
          callback(err, importManagerCache[uri]);
      });
      return true;
    }else{
      //it's not loaded successfully
      //and it's not mid-load
      //it must have failed
      callback(importManagerCache[uri].error, null);
      return true;
    }
  }

  //it wasn't in the cache needs loaded
  var importManager = this;

  importManager.readFile(uri, function (err, contents) {
    if( importManagerCache[uri] ){
      //another request for this uri has already taken place while the file was read
      return importManager.fetchSchema(uri, callback);
    }

    importManagerCache[uri] = new importManager.options.importClass();
    //swap out the getExternal schema function for the managers fetchSchema
    importManagerCache[uri].getExternalSchema = importManager.fetchSchema.bind(importManager); //@todo check this doesn't need bind

    //there was an error fetching the file, attach this to the new instance
    if(err){
      importManagerCache[uri].error = err;
      importManagerCache[uri].setReadyState(readyStates.complete);
      return callback(err, null);
    }

    importManagerCache[uri].once('complete', function(err, model){
        callback(err, importManagerCache[uri]);
    });

    importManagerCache[uri].loadSchemaFromJSON(contents);
  });

  return true;
};

BaseImportManager.prototype.getImporter = function (uri) {
  //@todo will overwrite existing instance, should it?
  //@todo also serious duplication of code from fetchSchema
  importManagerCache[uri] = new this.options.importClass();
  importManagerCache[uri].getExternalSchema = this.fetchSchema.bind(this); //@todo check this doesn't need bind

  return importManagerCache[uri];
};

//provide a copy of the ready states but not the reference used internally
BaseImportManager.prototype.readyStates = _.clone(readyStates);

BaseImportManager.prototype.log = basicLogger;

module.exports = {
  "BaseImporter":BaseImporter,
  "BaseImportManager": BaseImportManager,
  "errors": errors
};


text:
jfieldID queryArgsCountField;

jint sqliteOnJNILoad(JavaVM *vm, void *reserved, JNIEnv *env) {
	jclass class = (*env)->FindClass(env, "com/jmv/frre/moduloestudiante/SQLite/SQLitePreparedStatement");
	queryArgsCountField = (*env)->GetFieldID(env, class, "queryArgsCount", "I");
	return JNI_VERSION_1_4;
}

int Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_step(JNIEnv* env, jobject object, int statementHandle) {
	sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;

    int errcode = sqlite3_step(handle);
    if (errcode == SQLITE_ROW)  {
        return 0;
    } else if(errcode == SQLITE_DONE) {
        return 1;
    }  else if(errcode == SQLITE_BUSY) {
        return -1;
    }
	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
}

int Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_prepare(JNIEnv *env, jobject object, int sqliteHandle, jstring sql) {
	sqlite3* handle = (sqlite3 *)sqliteHandle;

    char const *sqlStr = (*env)->GetStringUTFChars(env, sql, 0);

    sqlite3_stmt *stmt_handle;

    int errcode = sqlite3_prepare_v2(handle, sqlStr, -1, &stmt_handle, 0);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, handle, errcode);
    } else {
    	int argsCount = sqlite3_bind_parameter_count(stmt_handle);
    	(*env)->SetIntField(env, object, queryArgsCountField, argsCount);
    }

    if (sqlStr != 0) {
        (*env)->ReleaseStringUTFChars(env, sql, sqlStr);
    }

    return (int)stmt_handle;
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_reset(JNIEnv *env, jobject object, int statementHandle) {
	sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;

	int errcode = sqlite3_reset(handle);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_finalize(JNIEnv *env, jobject object, int statementHandle) {
	sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;

	int errcode = sqlite3_finalize (handle);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindByteBuffer(JNIEnv *env, jobject object, int statementHandle, int index, jobject value, int length) {
	sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;
    jbyte *buf = (*env)->GetDirectBufferAddress(env, value);

	int errcode = sqlite3_bind_blob(handle, index, buf, length, SQLITE_STATIC);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindString(JNIEnv *env, jobject object, int statementHandle, int index, jstring value) {
	sqlite3_stmt *handle = (sqlite3_stmt*)statementHandle;

	char const *valueStr = (*env)->GetStringUTFChars(env, value, 0);

	int errcode = sqlite3_bind_text(handle, index, valueStr, -1, SQLITE_TRANSIENT);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }

	if (valueStr != 0) {
        (*env)->ReleaseStringUTFChars(env, value, valueStr);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindInt(JNIEnv *env, jobject object, int statementHandle, int index, int value) {
	sqlite3_stmt *handle = (sqlite3_stmt*)statementHandle;

	int errcode = sqlite3_bind_int(handle, index, value);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindLong(JNIEnv *env, jobject object, int statementHandle, int index, long long value) {
	sqlite3_stmt *handle = (sqlite3_stmt*)statementHandle;

	int errcode = sqlite3_bind_int64(handle, index, value);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindDouble(JNIEnv* env, jobject object, int statementHandle, int index, double value) {
	sqlite3_stmt *handle = (sqlite3_stmt*)statementHandle;

	int errcode = sqlite3_bind_double(handle, index, value);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}

void Java_com_jmv_frre_moduloestudiante_SQLite_SQLitePreparedStatement_bindNull(JNIEnv* env, jobject object, int statementHandle, int index) {
	sqlite3_stmt *handle = (sqlite3_stmt*)statementHandle;

	int errcode = sqlite3_bind_null(handle, index);
    if (SQLITE_OK != errcode) {
    	throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
    }
}


text:
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework

Namespace TypeHelpers

    Public Class ContactSensorPruner
        Inherits TreeListPruner

        Protected m_bShowOnlyContactSensors As Boolean = True

        Public Sub New(ByVal bShowOnlyContactSensors As Boolean)
            m_bShowOnlyContactSensors = bShowOnlyContactSensors
        End Sub

        Protected Sub MakeSelectable(ByVal tnNode As Crownwood.DotNetMagic.Controls.Node)
            tnNode.Selectable = True
            tnNode.ForeColor = Color.Black
        End Sub

        Protected Sub MakeUnSelectable(ByVal tnNode As Crownwood.DotNetMagic.Controls.Node)
            tnNode.Selectable = False
            tnNode.ForeColor = System.Drawing.SystemColors.ControlDark
        End Sub

        Public Overrides Function PruneTree(ByVal tnNodes As Crownwood.DotNetMagic.Controls.NodeCollection) As Integer
            Dim iSelectable As Integer = 0
            Dim aryRemoveNodes As New ArrayList

            For Each tnNode As Crownwood.DotNetMagic.Controls.Node In tnNodes

                Dim bSelected As Boolean = False
                If Not tnNode.Tag Is Nothing Then
                    If Util.IsTypeOf(tnNode.Tag.GetType(), GetType(AnimatGUI.TypeHelpers.LinkedDataObject)) Then
                        Dim liPart As AnimatGUI.TypeHelpers.LinkedDataObject = DirectCast(tnNode.Tag, AnimatGUI.TypeHelpers.LinkedDataObject)

                        If Not liPart.Item Is Nothing AndAlso Util.IsTypeOf(liPart.Item.GetType(), GetType(DataObjects.Physical.RigidBody)) Then
                            Dim doPart As DataObjects.Physical.RigidBody = DirectCast(liPart.Item, DataObjects.Physical.RigidBody)

                            If (doPart.IsContactSensor AndAlso m_bShowOnlyContactSensors) OrElse (Not doPart.IsContactSensor AndAlso Not m_bShowOnlyContactSensors) Then
                                MakeSelectable(tnNode)
                                bSelected = True
                                iSelectable = iSelectable + 1
                            End If

                            liPart.Pruner = Me
                        End If

                    End If
                End If

                If Not bSelected Then
                    MakeUnSelectable(tnNode)
                End If

                Dim iBranchSelectables As Integer = PruneTree(tnNode.Nodes)

                If iBranchSelectables = 0 And Not bSelected Then
                    aryRemoveNodes.Add(tnNode)
                End If
                iSelectable = iSelectable + iBranchSelectables
            Next

            'Prune out any nodes that have nothing selectable in them.
            For Each tnNode As Crownwood.DotNetMagic.Controls.Node In aryRemoveNodes
                tnNodes.Remove(tnNode)
            Next

            Return iSelectable
        End Function

        Public Overrides Sub PruneList(ByVal lbList As ListBox)
        End Sub
    End Class

End Namespace


text:
package org.kie.server.services.casemgmt;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

import org.jbpm.casemgmt.api.CaseRuntimeDataService;
import org.jbpm.casemgmt.api.generator.CaseIdGenerator;
import org.jbpm.casemgmt.impl.AuthorizationManagerImpl;
import org.jbpm.casemgmt.impl.CaseRuntimeDataServiceImpl;
import org.jbpm.casemgmt.impl.CaseServiceImpl;
import org.jbpm.casemgmt.impl.event.CaseConfigurationDeploymentListener;
import org.jbpm.casemgmt.impl.generator.InMemoryCaseIdGenerator;
import org.jbpm.casemgmt.impl.generator.TableCaseIdGenerator;
import org.jbpm.kie.services.impl.FormManagerService;
import org.jbpm.kie.services.impl.KModuleDeploymentService;
import org.jbpm.runtime.manager.impl.jpa.EntityManagerFactoryManager;
import org.jbpm.services.api.DefinitionService;
import org.jbpm.services.api.DeploymentService;
import org.jbpm.services.api.ProcessService;
import org.jbpm.services.api.RuntimeDataService;
import org.jbpm.services.api.UserTaskService;
import org.jbpm.shared.services.impl.TransactionalCommandService;
import org.kie.server.api.KieServerConstants;
import org.kie.server.services.api.KieContainerCommandService;
import org.kie.server.services.api.KieContainerInstance;
import org.kie.server.services.api.KieServerApplicationComponentsService;
import org.kie.server.services.api.KieServerExtension;
import org.kie.server.services.api.KieServerRegistry;
import org.kie.server.services.api.SupportedTransports;
import org.kie.server.services.impl.KieServerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CaseKieServerExtension implements KieServerExtension {

    public static final String EXTENSION_NAME = "Case-Mgmt";

    private static final Logger logger = LoggerFactory.getLogger(CaseKieServerExtension.class);

    private static final Boolean disabled = Boolean.parseBoolean(System.getProperty(KieServerConstants.KIE_CASE_SERVER_EXT_DISABLED, "false"));
    private static final Boolean jbpmDisabled = Boolean.parseBoolean(System.getProperty(KieServerConstants.KIE_JBPM_SERVER_EXT_DISABLED, "false"));

    private String persistenceUnitName = KieServerConstants.KIE_SERVER_PERSISTENCE_UNIT_NAME;

    private List<Object> services = new ArrayList<Object>();
    private boolean initialized = false;

    private KieServerRegistry registry;

    private CaseManagementServiceBase caseManagementServiceBase;
    private CaseManagementRuntimeDataServiceBase caseManagementRuntimeDataService;

    private KieContainerCommandService kieContainerCommandService;

    @Override
    public boolean isInitialized() {
        return initialized;
    }

    @Override
    public boolean isActive() {
        return disabled == false && jbpmDisabled == false;
    }

    @Override
    public void init(KieServerImpl kieServer, KieServerRegistry registry) {
        this.registry = registry;
        KieServerExtension jbpmExtension = registry.getServerExtension("jBPM");
        if (jbpmExtension == null) {
            initialized = false;
            logger.warn("jBPM extension not found, Case Management cannot work without jBPM extension, disabling itself");
            return;
        }
        List<Object> jbpmServices = jbpmExtension.getServices();
        RuntimeDataService runtimeDataService = null;
        ProcessService processService = null;
        DeploymentService deploymentService = null;

        for( Object object : jbpmServices ) {
            // in case given service is null (meaning was not configured) continue with next one
            if (object == null) {
                continue;
            }
            if( RuntimeDataService.class.isAssignableFrom(object.getClass()) ) {
                runtimeDataService = (RuntimeDataService) object;
                continue;
            } else if( ProcessService.class.isAssignableFrom(object.getClass()) ) {
                processService = (ProcessService) object;
                continue;
            } else if( DeploymentService.class.isAssignableFrom(object.getClass()) ) {
                deploymentService = (DeploymentService) object;
                continue;
            }
        }
        CaseIdGenerator caseIdGenerator = getCaseIdGenerator();

        // build case runtime data service
        CaseRuntimeDataServiceImpl caseRuntimeDataService = new CaseRuntimeDataServiceImpl();
        ((CaseRuntimeDataServiceImpl) caseRuntimeDataService).setCaseIdGenerator(caseIdGenerator);
        ((CaseRuntimeDataServiceImpl) caseRuntimeDataService).setRuntimeDataService(runtimeDataService);
        ((CaseRuntimeDataServiceImpl) caseRuntimeDataService).setCommandService(new TransactionalCommandService(EntityManagerFactoryManager.get().getOrCreate(persistenceUnitName)));
        ((CaseRuntimeDataServiceImpl) caseRuntimeDataService).setIdentityProvider(registry.getIdentityProvider());

        // build case service
        CaseServiceImpl caseService = new CaseServiceImpl();
        ((CaseServiceImpl) caseService).setCaseIdGenerator(caseIdGenerator);
        ((CaseServiceImpl) caseService).setCaseRuntimeDataService(caseRuntimeDataService);
        ((CaseServiceImpl) caseService).setProcessService(processService);
        ((CaseServiceImpl) caseService).setDeploymentService(deploymentService);
        ((CaseServiceImpl) caseService).setRuntimeDataService(runtimeDataService);
        ((CaseServiceImpl) caseService).setCommandService(new TransactionalCommandService(EntityManagerFactoryManager.get().getOrCreate(persistenceUnitName)));
        ((CaseServiceImpl) caseService).setAuthorizationManager(new AuthorizationManagerImpl(registry.getIdentityProvider(),
                new TransactionalCommandService(EntityManagerFactoryManager.get().getOrCreate(persistenceUnitName))));
        ((CaseServiceImpl) caseService).setIdentityProvider(registry.getIdentityProvider());

        // build case configuration on deployment listener
        CaseConfigurationDeploymentListener configurationListener = new CaseConfigurationDeploymentListener(registry.getIdentityProvider());

        // configure case mgmt services as listeners
        ((KModuleDeploymentService)deploymentService).addListener((CaseRuntimeDataServiceImpl) caseRuntimeDataService);
        ((KModuleDeploymentService)deploymentService).addListener(configurationListener);

        this.caseManagementServiceBase = new CaseManagementServiceBase(caseService, caseRuntimeDataService, registry);
        this.caseManagementRuntimeDataService = new CaseManagementRuntimeDataServiceBase(caseRuntimeDataService, registry);

        this.services.add(this.caseManagementServiceBase);
        this.services.add(this.caseManagementRuntimeDataService);

        this.kieContainerCommandService = new CaseKieContainerCommandServiceImpl(registry, caseManagementServiceBase, caseManagementRuntimeDataService);

        initialized = true;
    }

    private CaseIdGenerator getCaseIdGenerator() {
        String selectedGenerator = System.getProperty(KieServerConstants.CFG_CASE_ID_GENERATOR);

        if (selectedGenerator == null) {
            return new TableCaseIdGenerator(new TransactionalCommandService(EntityManagerFactoryManager.get().getOrCreate(persistenceUnitName)));
        }

        ServiceLoader<CaseIdGenerator> generators = ServiceLoader.load(CaseIdGenerator.class);

        for (CaseIdGenerator generator : generators) {
            if (generator.getIdentifier().equals(selectedGenerator))  {
                return generator;
            }
        }

        throw new IllegalStateException("Unable to find case id generator identified by " + selectedGenerator);
    }

    @Override
    public void destroy(KieServerImpl kieServer, KieServerRegistry registry) {
        if (!initialized) {
            return;
        }
    }

    @Override
    public void createContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) {
        if (!initialized) {
            return;
        }
    }

    @Override
    public void updateContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) {
        if (!initialized) {
            return;
        }
        // recreate configuration for updated container
        disposeContainer(id, kieContainerInstance, parameters);
        createContainer(id, kieContainerInstance, parameters);
    }

    @Override
    public boolean isUpdateContainerAllowed(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) {
        return true;
    }

    @Override
    public void disposeContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) {
        if (!initialized) {
            return;
        }
    }

    @Override
    public List<Object> getAppComponents(SupportedTransports type) {
        List<Object> appComponentsList = new ArrayList<Object>();
        if (!initialized) {
            return appComponentsList;
        }
        ServiceLoader<KieServerApplicationComponentsService> appComponentsServices = ServiceLoader.load(KieServerApplicationComponentsService.class);

        Object [] services = {
                caseManagementServiceBase,
                caseManagementRuntimeDataService,
                registry
        };
        for( KieServerApplicationComponentsService appComponentsService : appComponentsServices ) {
            appComponentsList.addAll(appComponentsService.getAppComponents(EXTENSION_NAME, type, services));
        }
        return appComponentsList;
    }

    @Override
    public <T> T getAppComponents(Class<T> serviceType) {
        if (!initialized) {
            return null;
        }
        if (serviceType.isAssignableFrom(kieContainerCommandService.getClass())) {
            return (T) kieContainerCommandService;
        }
        return null;
    }

    @Override
    public String getImplementedCapability() {
        return KieServerConstants.CAPABILITY_CASE;
    }

    @Override
    public List<Object> getServices() {
        return services;
    }

    @Override
    public String getExtensionName() {
        return EXTENSION_NAME;
    }

    @Override
    public Integer getStartOrder() {
        return 10;
    }

    @Override
    public String toString() {
        return EXTENSION_NAME + " KIE Server extension";
    }
}


text:
import Vue from 'vue';
import canaryCalloutMixin from './mixins/canary_callout_mixin';
import environmentsComponent from './components/environments_app.vue';
import { parseBoolean } from '../lib/utils/common_utils';
import Translate from '../vue_shared/translate';

Vue.use(Translate);

export default () =>
  new Vue({
    el: '#environments-list-view',
    components: {
      environmentsComponent,
    },
    mixins: [canaryCalloutMixin],
    data() {
      const environmentsData = document.querySelector(this.$options.el).dataset;

      return {
        endpoint: environmentsData.environmentsDataEndpoint,
        newEnvironmentPath: environmentsData.newEnvironmentPath,
        helpPagePath: environmentsData.helpPagePath,
        deployBoardsHelpPath: environmentsData.deployBoardsHelpPath,
        canCreateEnvironment: parseBoolean(environmentsData.canCreateEnvironment),
        canReadEnvironment: parseBoolean(environmentsData.canReadEnvironment),
      };
    },
    render(createElement) {
      return createElement('environments-component', {
        props: {
          endpoint: this.endpoint,
          newEnvironmentPath: this.newEnvironmentPath,
          helpPagePath: this.helpPagePath,
          deployBoardsHelpPath: this.deployBoardsHelpPath,
          canCreateEnvironment: this.canCreateEnvironment,
          canReadEnvironment: this.canReadEnvironment,
          ...this.canaryCalloutProps,
        },
      });
    },
  });


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2020 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <color name="greyAlpha">#55999999</color>
    <color name="lightGreyAlpha">#55DDDDDD</color>

    <color name="red">#FF5252</color>
    <color name="yellow">#FFA000</color>
    <color name="green">#8BC34A</color>
</resources>


text:
product: material
title: Componente React Interruptor
components: Switch, FormControl, FormGroup, FormLabel, FormControlLabel, SwitchUnstyled
githubLabel: 'component: switch'
materialDesign: 'https://material.io/components/selection-controls#switches'
---

# Interruptor

Interruptores alternam o estado de uma única configuração ligado ou desligado.

[Interruptores](https://material.io/design/components/selection-controls.html#switches) são a forma preferida de ajustes de configuração em mobile. The option that the switch controls, as well as the state it's in, should be made clear from the corresponding inline label.

{{"component": "modules/components/ComponentLinkHeader.js"}}

## Interruptores básicos

{{"demo": "BasicSwitches.js"}}

## Caixas de seleção com FormGroup

Você pode fornecer um rótulo para o `Switch` graças ao componente `FormControlLabel`.

{{"demo": "SwitchLabels.js"}}

## Tamanho

Use a propriedade `size` para alterar o tamanho do interruptor.

{{"demo": "SwitchesSize.js"}}

## Cor

{{"demo": "ColorSwitches.js"}}

## Controlled

Você pode controlar o interruptor com as propriedades `checked` e `onChange`:

{{"demo": "ControlledSwitches.js"}}

## Interruptores com FormGroup

`FormGroup` is a helpful wrapper used to group selection controls components that provides an easier API. However, you are encouraged to use [Checkboxes](/components/checkboxes/) instead if multiple related controls are required. (Veja: [Quando usar](#when-to-use)).

{{"demo": "SwitchesGroup.js"}}

## Interruptores customizados

Aqui estão alguns exemplos de customização do componente. Você pode aprender mais sobre isso na [página de documentação de sobrescritas](/customization/how-to-customize/).

{{"demo": "CustomizedSwitches.js"}}

🎨 If you are looking for inspiration, you can check [MUI Treasury's customization examples](https://mui-treasury.com/styles/switch/).

## Posicionamento do rótulo

The switch also comes with an unstyled version. It's ideal for doing heavy customizations and minimizing bundle size.

### Unstyled component

```jsx
import SwitchUnstyled from '@mui/base/SwitchUnstyled';
```

The `SwitchUnstyled` component provides default components and assigns CSS classes you can style entirely on your own. You are free to choose any styling solution - plain CSS classes, a CSS framework, Emotion, etc. It is also possible to replace these default components by other HTML elements or custom components. It is also possible to replace these default components by other HTML elements or custom components.

There are three components you can override by the `components` prop: `Root`, `Thumb` and `Input`. Each one's props can be set using the `componentsProps` object.

{{"demo": "UnstyledSwitches.js"}}

### useSwitch hook

For the ultimate customizability, a `useSwitch` hook is available. It accepts almost the same options as the SwitchUnstyled component minus the `component`, `components`, and `componentsProps` props.

```jsx
import { useSwitch } from '@mui/base/SwitchUnstyled';
```

#### Basic example

{{"demo": "UseSwitchesBasic.js"}}

#### Customized look and feel

{{"demo": "UseSwitchesCustom.js"}}

## Quando usar

Você pode alterar o posicionamento do rótulo:

{{"demo": "FormControlLabelPosition.js"}}

## Acessibilidade

- [Caixas de seleção vs. interruptores](https://uxplanet.org/checkbox-vs-toggle-switch-7fc6e83f10b8)

## Accessibility

- Ele irá renderizar um elemento com a regra de `checkbox` e não `switch`, pois esta regra não é amplamente suportada ainda. Por favor, teste primeiro se a tecnologia assistiva do seu público-alvo suporta essa regra corretamente. Em seguida, você pode alterar a regra com `<Switch inputProps={{ role: 'switch' }}>`
- Todos os controles de formulário devem ter rótulos, e isso inclui os botões de opção, caixas de seleção e interruptores. Na maioria dos casos, isso é feito usando o elemento `<label>` ([FormControlLabel](/api/form-control-label/)).
- Quando um rótulo não pode ser usado, é necessário adicionar um atributo diretamente no componente de entrada. Nesse caso você pode aplicar um atributo adicional (por exemplo, `aria-label`,`aria-labelledby`, `title`) através da propriedade `inputProps`.

```jsx
<code>
  <Switch value="checkedA" inputProps={{ 'aria-label': 'Switch A' }} />
</code>
```


text:
using namespace ofxLaser;

void DacBase::setArmed(bool _armed){
   armed = _armed;
};
const vector<ofAbstractParameter*>& DacBase::getDisplayData() {
    return displayData;

};


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.UploadImgUrlModel = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Validator = require('Validator');

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var UploadImgUrlModel = function () {
    function UploadImgUrlModel(imageUrl) {
        _classCallCheck(this, UploadImgUrlModel);

        this.imageUrl = imageUrl;
    }

    _createClass(UploadImgUrlModel, [{
        key: 'imageUrl',
        get: function get() {
            return this._imageUrl;
        },
        set: function set(filteredImgUrl) {

            _Validator.Validator.validateImageUrl(filteredImgUrl);
            this._imageUrl = filteredImgUrl;
        }
    }]);

    return UploadImgUrlModel;
}();

exports.UploadImgUrlModel = UploadImgUrlModel;


text:
package com.xdebugxgames.trouble.with.tribbles.client;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.xdebugxgames.trouble.with.tribbles.IActivityRequestHandler;
import com.xdebugxgames.trouble.with.tribbles.Tribbles;

public class HtmlLauncher extends GwtApplication implements IActivityRequestHandler {

        @Override
        public GwtApplicationConfiguration getConfig () {
                return new GwtApplicationConfiguration(487, 864);
        }

        @Override
        public ApplicationListener getApplicationListener () {
                return new Tribbles(this);
        }

		@Override
		public void sendMsg(String msgg) {
			// TODO Auto-generated method stub

		}

		@Override
		public void saveGame(byte[] s) {
			// TODO Auto-generated method stub

		}

		@Override
		public void loadGame() {
			// TODO Auto-generated method stub

		}
}


text:
package specs

// Descriptor describes the disposition of targeted content.
type Descriptor struct {
	// MediaType contains the MIME type of the referenced object.
	MediaType string `json:"mediaType"`

	// Digest is the digest of the targeted content.
	Digest string `json:"digest"`

	// Size specifies the size in bytes of the blob.
	Size int64 `json:"size"`
}


text:
require File.expand_path('../support/helpers', __FILE__)

describe 'apache2::mod_perl' do
  include Helpers::Apache

  it 'enables perl_module' do
    apache_enabled_modules.must_include "perl_module"
  end

  it 'installs the apache request library' do
    req_pkg = case node['platform']
      when 'debian', 'ubuntu' then 'libapache2-request-perl'
      else 'perl-libapreq2'
    end
    package(req_pkg).must_be_installed
  end

end


text:
package org.apache.beam.runners.fnexecution.translation;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.Mockito.when;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.Components;
import org.apache.beam.model.pipeline.v1.RunnerApi.Environment;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.construction.graph.ExecutableStage;
import org.apache.beam.runners.core.construction.graph.ImmutableExecutableStage;
import org.apache.beam.runners.core.construction.graph.PipelineNode;
import org.apache.beam.runners.core.construction.graph.PipelineNode.PCollectionNode;
import org.apache.beam.runners.core.construction.graph.SideInputReference;
import org.apache.beam.runners.fnexecution.state.StateRequestHandlers.SideInputHandler;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.coders.VarIntCoder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow.IntervalWindowCoder;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.KV;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/** Tests for {@link BatchSideInputHandlerFactory}. */
@RunWith(JUnit4.class)
public class BatchSideInputHandlerFactoryTest {

  private static final String TRANSFORM_ID = "transform-id";
  private static final String SIDE_INPUT_NAME = "side-input";
  private static final String COLLECTION_ID = "collection";
  private static final RunnerApi.FunctionSpec MULTIMAP_ACCESS =
      RunnerApi.FunctionSpec.newBuilder().setUrn(PTransformTranslation.MULTIMAP_SIDE_INPUT).build();
  private static final RunnerApi.FunctionSpec ITERABLE_ACCESS =
      RunnerApi.FunctionSpec.newBuilder().setUrn(PTransformTranslation.ITERABLE_SIDE_INPUT).build();
  private static final ExecutableStage EXECUTABLE_STAGE =
      createExecutableStage(
          Arrays.asList(
              SideInputReference.of(
                  PipelineNode.pTransform(TRANSFORM_ID, RunnerApi.PTransform.getDefaultInstance()),
                  SIDE_INPUT_NAME,
                  PipelineNode.pCollection(
                      COLLECTION_ID, RunnerApi.PCollection.getDefaultInstance()))));
  private static final byte[] ENCODED_NULL = encode(null, VoidCoder.of());
  private static final byte[] ENCODED_FOO = encode("foo", StringUtf8Coder.of());

  @Rule public ExpectedException thrown = ExpectedException.none();

  @Mock private BatchSideInputHandlerFactory.SideInputGetter context;

  @Before
  public void setUpMocks() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void invalidSideInputThrowsException() {
    ExecutableStage stage = createExecutableStage(Collections.emptyList());
    BatchSideInputHandlerFactory factory = BatchSideInputHandlerFactory.forStage(stage, context);
    thrown.expect(instanceOf(IllegalArgumentException.class));
    factory.forSideInput(
        "transform-id",
        "side-input",
        MULTIMAP_ACCESS,
        KvCoder.of(VoidCoder.of(), VoidCoder.of()),
        GlobalWindow.Coder.INSTANCE);
  }

  @Test
  public void emptyResultForEmptyCollection() {
    BatchSideInputHandlerFactory factory =
        BatchSideInputHandlerFactory.forStage(EXECUTABLE_STAGE, context);
    SideInputHandler<Integer, GlobalWindow> handler =
        factory.forSideInput(
            TRANSFORM_ID,
            SIDE_INPUT_NAME,
            MULTIMAP_ACCESS,
            KvCoder.of(VoidCoder.of(), VarIntCoder.of()),
            GlobalWindow.Coder.INSTANCE);
    // We never populated the broadcast variable for "side-input", so the mock will return an empty
    // list.
    Iterable<Integer> result = handler.get(ENCODED_NULL, GlobalWindow.INSTANCE);
    assertThat(result, emptyIterable());
  }

  @Test
  public void singleElementForCollection() {
    when(context.getSideInput(COLLECTION_ID))
        .thenReturn(
            Arrays.asList(WindowedValue.valueInGlobalWindow(KV.<Void, Integer>of(null, 3))));

    BatchSideInputHandlerFactory factory =
        BatchSideInputHandlerFactory.forStage(EXECUTABLE_STAGE, context);
    SideInputHandler<Integer, GlobalWindow> handler =
        factory.forSideInput(
            TRANSFORM_ID,
            SIDE_INPUT_NAME,
            MULTIMAP_ACCESS,
            KvCoder.of(VoidCoder.of(), VarIntCoder.of()),
            GlobalWindow.Coder.INSTANCE);
    Iterable<Integer> result = handler.get(ENCODED_NULL, GlobalWindow.INSTANCE);
    assertThat(result, contains(3));
  }

  @Test
  public void groupsValuesByKey() {
    when(context.getSideInput(COLLECTION_ID))
        .thenReturn(
            Arrays.asList(
                WindowedValue.valueInGlobalWindow(KV.of("foo", 2)),
                WindowedValue.valueInGlobalWindow(KV.of("bar", 3)),
                WindowedValue.valueInGlobalWindow(KV.of("foo", 5))));

    BatchSideInputHandlerFactory factory =
        BatchSideInputHandlerFactory.forStage(EXECUTABLE_STAGE, context);
    SideInputHandler<Integer, GlobalWindow> handler =
        factory.forSideInput(
            TRANSFORM_ID,
            SIDE_INPUT_NAME,
            MULTIMAP_ACCESS,
            KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()),
            GlobalWindow.Coder.INSTANCE);
    Iterable<Integer> result = handler.get(ENCODED_FOO, GlobalWindow.INSTANCE);
    assertThat(result, containsInAnyOrder(2, 5));
  }

  @Test
  public void groupsValuesByWindowAndKey() {
    Instant instantA = new DateTime(2018, 1, 1, 1, 1, DateTimeZone.UTC).toInstant();
    Instant instantB = new DateTime(2018, 1, 1, 1, 2, DateTimeZone.UTC).toInstant();
    Instant instantC = new DateTime(2018, 1, 1, 1, 3, DateTimeZone.UTC).toInstant();
    IntervalWindow windowA = new IntervalWindow(instantA, instantB);
    IntervalWindow windowB = new IntervalWindow(instantB, instantC);
    when(context.getSideInput(COLLECTION_ID))
        .thenReturn(
            Arrays.asList(
                WindowedValue.of(KV.of("foo", 1), instantA, windowA, PaneInfo.NO_FIRING),
                WindowedValue.of(KV.of("bar", 2), instantA, windowA, PaneInfo.NO_FIRING),
                WindowedValue.of(KV.of("foo", 3), instantA, windowA, PaneInfo.NO_FIRING),
                WindowedValue.of(KV.of("foo", 4), instantB, windowB, PaneInfo.NO_FIRING),
                WindowedValue.of(KV.of("bar", 5), instantB, windowB, PaneInfo.NO_FIRING),
                WindowedValue.of(KV.of("foo", 6), instantB, windowB, PaneInfo.NO_FIRING)));

    BatchSideInputHandlerFactory factory =
        BatchSideInputHandlerFactory.forStage(EXECUTABLE_STAGE, context);
    SideInputHandler<Integer, IntervalWindow> handler =
        factory.forSideInput(
            TRANSFORM_ID,
            SIDE_INPUT_NAME,
            MULTIMAP_ACCESS,
            KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()),
            IntervalWindowCoder.of());
    Iterable<Integer> resultA = handler.get(ENCODED_FOO, windowA);
    Iterable<Integer> resultB = handler.get(ENCODED_FOO, windowB);
    assertThat(resultA, containsInAnyOrder(1, 3));
    assertThat(resultB, containsInAnyOrder(4, 6));
  }

  @Test
  public void iterableAccessPattern() {
    Instant instantA = new DateTime(2018, 1, 1, 1, 1, DateTimeZone.UTC).toInstant();
    Instant instantB = new DateTime(2018, 1, 1, 1, 2, DateTimeZone.UTC).toInstant();
    Instant instantC = new DateTime(2018, 1, 1, 1, 3, DateTimeZone.UTC).toInstant();
    IntervalWindow windowA = new IntervalWindow(instantA, instantB);
    IntervalWindow windowB = new IntervalWindow(instantB, instantC);
    when(context.getSideInput(COLLECTION_ID))
        .thenReturn(
            Arrays.asList(
                WindowedValue.of(1, instantA, windowA, PaneInfo.NO_FIRING),
                WindowedValue.of(2, instantA, windowA, PaneInfo.NO_FIRING),
                WindowedValue.of(3, instantB, windowB, PaneInfo.NO_FIRING),
                WindowedValue.of(4, instantB, windowB, PaneInfo.NO_FIRING)));

    BatchSideInputHandlerFactory factory =
        BatchSideInputHandlerFactory.forStage(EXECUTABLE_STAGE, context);
    SideInputHandler<Integer, IntervalWindow> handler =
        factory.forSideInput(
            TRANSFORM_ID,
            SIDE_INPUT_NAME,
            ITERABLE_ACCESS,
            VarIntCoder.of(),
            IntervalWindowCoder.of());
    Iterable<Integer> resultA = handler.get(null, windowA);
    Iterable<Integer> resultB = handler.get(null, windowB);
    assertThat(resultA, containsInAnyOrder(1, 2));
    assertThat(resultB, containsInAnyOrder(3, 4));
  }

  private static ExecutableStage createExecutableStage(Collection<SideInputReference> sideInputs) {
    Components components = Components.getDefaultInstance();
    Environment environment = Environment.getDefaultInstance();
    PCollectionNode inputCollection =
        PipelineNode.pCollection("collection-id", RunnerApi.PCollection.getDefaultInstance());
    return ImmutableExecutableStage.of(
        components,
        environment,
        inputCollection,
        sideInputs,
        Collections.emptyList(),
        Collections.emptyList(),
        Collections.emptyList(),
        Collections.emptyList());
  }

  private static <T> byte[] encode(T value, Coder<T> coder) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      coder.encode(value, out);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return out.toByteArray();
  }
}


text:
package abi44_0_0.host.exp.exponent.modules.api.components.picker;

import abi44_0_0.com.facebook.react.bridge.Arguments;
import abi44_0_0.com.facebook.react.bridge.WritableMap;
import abi44_0_0.com.facebook.react.uimanager.events.Event;
import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter;

public class PickerItemSelectEvent extends Event<PickerItemSelectEvent> {
  public static final String EVENT_NAME = "topSelect";

  private final int mPosition;

  public PickerItemSelectEvent(int id, int position) {
    super(id);
    mPosition = position;
  }

  @Override
  public String getEventName() {
    return EVENT_NAME;
  }

  @Override
  public void dispatch(RCTEventEmitter rctEventEmitter) {
    rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData());
  }

  private WritableMap serializeEventData() {
    WritableMap eventData = Arguments.createMap();
    eventData.putInt("position", mPosition);
    return eventData;
  }
}


text:
"use strict";

const { expect } = require("chai");

const { OperatorType, OperatorAssoc, Operator } = $expr;

const { createDummyParser } = $testutil.helpers;

describe("infix", () => {
  it("should create an infix operator object", () => {
    const parser = createDummyParser();
    {
      const op = Operator.infix(parser, OperatorAssoc.NONE);
      expect(op).to.deep.equal({
        type  : OperatorType.INFIX,
        parser: parser,
        assoc : OperatorAssoc.NONE,
      });
    }
    {
      const op = Operator.infix(parser, OperatorAssoc.LEFT);
      expect(op).to.deep.equal({
        type  : OperatorType.INFIX,
        parser: parser,
        assoc : OperatorAssoc.LEFT,
      });
    }
    {
      const op = Operator.infix(parser, OperatorAssoc.RIGHT);
      expect(op).to.deep.equal({
        type  : OperatorType.INFIX,
        parser: parser,
        assoc : OperatorAssoc.RIGHT,
      });
    }
  });
});