text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal static class SyntaxNodeExtensions
    {
        public static TNode WithAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : CSharpSyntaxNode
        {
            return (TNode)node.Green.SetAnnotations(annotations).CreateRed();
        }

        public static bool IsAnonymousFunction(this SyntaxNode syntax)
        {
            Debug.Assert(syntax != null);
            switch (syntax.Kind())
            {
                case SyntaxKind.ParenthesizedLambdaExpression:
                case SyntaxKind.SimpleLambdaExpression:
                case SyntaxKind.AnonymousMethodExpression:
                    return true;
                default:
                    return false;
            }
        }

        public static bool IsQuery(this SyntaxNode syntax)
        {
            Debug.Assert(syntax != null);
            switch (syntax.Kind())
            {
                case SyntaxKind.FromClause:
                case SyntaxKind.GroupClause:
                case SyntaxKind.JoinClause:
                case SyntaxKind.JoinIntoClause:
                case SyntaxKind.LetClause:
                case SyntaxKind.OrderByClause:
                case SyntaxKind.QueryContinuation:
                case SyntaxKind.QueryExpression:
                case SyntaxKind.SelectClause:
                case SyntaxKind.WhereClause:
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        /// This method is used to keep the code that generates binders in sync
        /// with the code that searches for binders.  We don't want the searcher
        /// to skip over any nodes that could have associated binders, especially
        /// if changes are made later.
        ///
        /// "Local binder" is a term that refers to binders that are
        /// created by LocalBinderFactory.
        /// </summary>
        internal static bool CanHaveAssociatedLocalBinder(this SyntaxNode syntax)
        {
            SyntaxKind kind = syntax.Kind();
            switch (kind)
            {
                case SyntaxKind.CatchClause:
                case SyntaxKind.ParenthesizedLambdaExpression:
                case SyntaxKind.SimpleLambdaExpression:
                case SyntaxKind.AnonymousMethodExpression:
                case SyntaxKind.CatchFilterClause:
                case SyntaxKind.SwitchSection:
                case SyntaxKind.EqualsValueClause:
                case SyntaxKind.Attribute:
                case SyntaxKind.ArgumentList:
                case SyntaxKind.ArrowExpressionClause:
                case SyntaxKind.SwitchExpression:
                case SyntaxKind.SwitchExpressionArm:
                case SyntaxKind.BaseConstructorInitializer:
                case SyntaxKind.ThisConstructorInitializer:
                case SyntaxKind.ConstructorDeclaration:
                case SyntaxKind.PrimaryConstructorBaseType:
                    return true;

                case SyntaxKind.RecordDeclaration:
                    return ((RecordDeclarationSyntax)syntax).ParameterList is object;

                case SyntaxKind.RecordStructDeclaration:
                    return false;

                default:
                    return syntax is StatementSyntax || IsValidScopeDesignator(syntax as ExpressionSyntax);

            }
        }

        internal static bool IsValidScopeDesignator(this ExpressionSyntax? expression)
        {
            // All these nodes are valid scope designators due to the pattern matching and out vars features.
            CSharpSyntaxNode? parent = expression?.Parent;
            switch (parent?.Kind())
            {
                case SyntaxKind.SimpleLambdaExpression:
                case SyntaxKind.ParenthesizedLambdaExpression:
                    return ((LambdaExpressionSyntax)parent).Body == expression;

                case SyntaxKind.SwitchStatement:
                    return ((SwitchStatementSyntax)parent).Expression == expression;

                case SyntaxKind.ForStatement:
                    var forStmt = (ForStatementSyntax)parent;
                    return forStmt.Condition == expression || forStmt.Incrementors.FirstOrDefault() == expression;

                case SyntaxKind.ForEachStatement:
                case SyntaxKind.ForEachVariableStatement:
                    return ((CommonForEachStatementSyntax)parent).Expression == expression;

                default:
                    return false;
            }
        }

        /// <summary>
        /// Because the instruction cannot have any values on the stack before CLR execution
        /// we limited it to assignments and conditional expressions in C# 7.
        /// See https://github.com/dotnet/roslyn/issues/22046.
        /// In C# 8 we relaxed
        /// that by rewriting the code to move it to the statement level where the stack is empty.
        /// </summary>
        internal static bool IsLegalCSharp73SpanStackAllocPosition(this SyntaxNode node)
        {
            Debug.Assert(node != null);

            if (node.Parent.IsKind(SyntaxKind.CastExpression))
            {
                node = node.Parent;
            }

            while (node.Parent.IsKind(SyntaxKind.ConditionalExpression))
            {
                node = node.Parent;
            }

            SyntaxNode? parentNode = node.Parent;

            if (parentNode is null)
            {
                return false;
            }

            switch (parentNode.Kind())
            {
                // In case of a declaration of a Span<T> variable
                case SyntaxKind.EqualsValueClause:
                    {
                        SyntaxNode? variableDeclarator = parentNode.Parent;

                        return variableDeclarator.IsKind(SyntaxKind.VariableDeclarator) &&
                            variableDeclarator.Parent.IsKind(SyntaxKind.VariableDeclaration);
                    }
                // In case of reassignment to a Span<T> variable
                case SyntaxKind.SimpleAssignmentExpression:
                    {
                        return parentNode.Parent.IsKind(SyntaxKind.ExpressionStatement);
                    }
            }

            return false;
        }

        internal static CSharpSyntaxNode AnonymousFunctionBody(this SyntaxNode lambda)
            => ((AnonymousFunctionExpressionSyntax)lambda).Body;

        /// <summary>
        /// Given an initializer expression infer the name of anonymous property or tuple element.
        /// Returns default if unsuccessful
        /// </summary>
        internal static SyntaxToken ExtractAnonymousTypeMemberName(this ExpressionSyntax input)
        {
            while (true)
            {
                switch (input.Kind())
                {
                    case SyntaxKind.IdentifierName:
                        return ((IdentifierNameSyntax)input).Identifier;

                    case SyntaxKind.SimpleMemberAccessExpression:
                        input = ((MemberAccessExpressionSyntax)input).Name;
                        continue;

                    case SyntaxKind.ConditionalAccessExpression:
                        input = ((ConditionalAccessExpressionSyntax)input).WhenNotNull;
                        if (input.Kind() == SyntaxKind.MemberBindingExpression)
                        {
                            return ((MemberBindingExpressionSyntax)input).Name.Identifier;
                        }

                        continue;

                    default:
                        return default(SyntaxToken);
                }
            }
        }

        internal static RefKind GetRefKind(this TypeSyntax syntax)
        {
            syntax.SkipRef(out var refKind);
            return refKind;
        }

        internal static TypeSyntax SkipRef(this TypeSyntax syntax)
        {
            if (syntax.Kind() == SyntaxKind.RefType)
            {
                syntax = ((RefTypeSyntax)syntax).Type;
            }

            return syntax;
        }

        internal static TypeSyntax SkipRef(this TypeSyntax syntax, out RefKind refKind)
        {
            refKind = RefKind.None;
            if (syntax.Kind() == SyntaxKind.RefType)
            {
                var refType = (RefTypeSyntax)syntax;
                refKind = refType.ReadOnlyKeyword.Kind() == SyntaxKind.ReadOnlyKeyword ?
                    RefKind.RefReadOnly :
                    RefKind.Ref;

                syntax = refType.Type;
            }

            return syntax;
        }

        internal static ExpressionSyntax? CheckAndUnwrapRefExpression(
            this ExpressionSyntax? syntax,
            BindingDiagnosticBag diagnostics,
            out RefKind refKind)
        {
            refKind = RefKind.None;
            if (syntax?.Kind() == SyntaxKind.RefExpression)
            {
                refKind = RefKind.Ref;
                syntax = ((RefExpressionSyntax)syntax).Expression;

                syntax.CheckDeconstructionCompatibleArgument(diagnostics);
            }

            return syntax;
        }

        internal static void CheckDeconstructionCompatibleArgument(this ExpressionSyntax expression, BindingDiagnosticBag diagnostics)
        {
            if (IsDeconstructionCompatibleArgument(expression))
            {
                diagnostics.Add(ErrorCode.ERR_VarInvocationLvalueReserved, expression.GetLocation());
            }
        }

        /// <summary>
        /// See if the expression is an invocation of a method named 'var',
        /// I.e. something like "var(x, y)" or "var(x, (y, z))" or "var(1)".
        /// We report an error when such an invocation is used in a certain syntactic contexts that
        /// will require an lvalue because we may elect to support deconstruction
        /// in the future. We need to ensure that we do not successfully interpret this as an invocation of a
        /// ref-returning method named var.
        /// </summary>
        private static bool IsDeconstructionCompatibleArgument(ExpressionSyntax expression)
        {
            if (expression.Kind() == SyntaxKind.InvocationExpression)
            {
                var invocation = (InvocationExpressionSyntax)expression;
                var invocationTarget = invocation.Expression;

                return invocationTarget.Kind() == SyntaxKind.IdentifierName &&
                    ((IdentifierNameSyntax)invocationTarget).IsVar;
            }

            return false;
        }
    }
}


text:
import os
import re
import json
import pickle
import logging
import argparse
from textwrap import dedent
from collections import defaultdict, namedtuple

import nltk
import numpy as np
import scipy.sparse as sp
from six.moves.urllib.parse import urljoin, urlparse

from pagerank import pagerank
from webgraph import WebPageGraph, Link
from htmltools import iter_html_files, ParseHTML

logging.basicConfig(format='[%(levelname)-5s] %(message)s',
                    level=logging.DEBUG)

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--for-deploy", action="store_true",
                    help=("save output in a javascript file that will "
                          "be used for deployment"))

CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))

PYTHON_INDEX_DIR = os.path.join(CURRENT_DIR, 'index-files')
PYTHON_INDEX_FILE = os.path.join(PYTHON_INDEX_DIR, 'index.pickle')

JS_INDEX_DIR = os.path.join(CURRENT_DIR, '..', 'blog', 'html', '_static', 'js')
JS_INDEX_FILE = os.path.join(JS_INDEX_DIR, 'searchindex.js')

SITE_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '..', 'blog', 'html'))
SITE_ROOT = 'http://neupy.com'

def make_url_from_file(filepath):
    _, url = filepath.split(SITE_DIR)
    return urljoin(SITE_ROOT, url)

def ignore_link(link):
    patterns = [
        # Base pages
        '/rss.html',
        '/index.html',
        '/master.html',
        '/search.html',
        '/archive.html',
        '/py-modindex.html',

        # Other pages
        '/pages/home.html',
        '/apidocs/modules.html',
        '/apidocs/neupy.html',
        '/modules/generated/.+',

        # Pages that has collected information
        r'/page\d{1,}.html',
        r'.*tags/.+\.html',
        r'.*cheatsheet\.html',

        # Static files
        r'.+(css|js|jpg|png)$',
        r'/_images/.+',
        r'.*\.tar\.gz',
    ]
    uri = urlparse(link)

    for pattern in patterns:
        if re.match(pattern, uri.path):
            return True

        if uri.fragment in ('subpackages', 'submodules'):
            return True

        if uri.fragment.endswith('-package'):
            return True

    return False

def url_filter(links):
    filtered_links = []

    for link in links:
        if not ignore_link(link.uri):
            filtered_links.append(link)

    return filtered_links

def save_python_index(data):
    if not os.path.exists(PYTHON_INDEX_DIR):
        os.mkdir(PYTHON_INDEX_DIR)

    with open(PYTHON_INDEX_FILE, 'wb') as f:
        pickle.dump(data, f)

def remove_useless_keys(documents):
    useless_keys = ('filepath', 'filename', 'links', 'html', 'text')

    for document in documents:
        for useless_key in useless_keys:
            if useless_key in document:
                del document[useless_key]

def save_js_index(documents, vocabulary, tf, idf, rank):
    if not os.path.exists(JS_INDEX_DIR):
        os.mkdir(JS_INDEX_DIR)

    output_template = dedent("""
    var searchIndex = {{
        documents: {documents},
        idf: {idf},
        tf: {{
            col: {tf_col},
            row: {tf_row},
            data: {tf_value}
        }},
        vocabulary: {vocabulary},
        rank: {rank}
    }}
    """)

    remove_useless_keys(documents)
    tf = tf.tocoo()

    with open(JS_INDEX_FILE, 'w') as f:
        f.write(
            output_template.format(
                documents=json.dumps(documents, indent=4),
                idf=idf.tolist(),
                tf_col=tf.col.tolist(),
                tf_row=tf.row.tolist(),
                tf_value=tf.data.tolist(),
                vocabulary=json.dumps(vocabulary),
                rank=rank.tolist(),
            ))

def page_tagging(url):
    parsed_uri = urlparse(url)

    tagging_rules = {
        'algorithm': r'^/apidocs/neupy.algorithms',
        'layer': r'^/apidocs/neupy.layers',
        'plot': r'^/apidocs/neupy.plots',
        'documentation': r'^/docs/',
        'article': r'^/\d{4}/\d{2}/\d{2}/',
        'tutorial': r'^/\d{4}/\d{2}/\d{2}/',
    }

    for tag, tagging_rule in tagging_rules.items():
        tagging_rule_regex = re.compile(tagging_rule)

        if tagging_rule_regex.match(parsed_uri.path):
            return tag

    return None

def collect_documents(directory):
    logging.info("Collecting documents from the directory (%s)", directory)
    Document = namedtuple("Document", "filename filepath uri links "
                                      "html text title tag snippet")

    documents = []
    for filepath in iter_html_files(directory):
        current_page_url = make_url_from_file(filepath)
        filename = os.path.basename(filepath)

        if ignore_link(current_page_url):
            logging.debug('Skip "%s", because file is defined in the '
                          'ignore list', filename)
            continue

        html = ParseHTML.fromfile(filepath, current_page_url)
        tag = page_tagging(current_page_url)
        text = html.text()

        if not text:
            logging.debug('Skip "%s", because text is missed', filename)
            continue

        for subdocument in html.subdocuments():
            if ignore_link(subdocument.uri):
                logging.debug('Skip "%s", because URL is defined in the '
                              'ignore list', subdocument.uri)

            else:
                doc = Document(filename, filepath, subdocument.uri,
                               url_filter(subdocument.links),
                               subdocument.html, subdocument.text,
                               subdocument.title, tag, subdocument.snippet)
                documents.append(doc)

    return documents

if __name__ == '__main__':
    logging.info("Started building index")
    args = parser.parse_args()

    documents = []
    vocabulary = {}
    term_frequency = defaultdict(int)

    index_pointers = [0]
    indices = []
    data = []

    logging.info("Collecting documents")
    all_documents = collect_documents(SITE_DIR)

    logging.info("Define relations between documents")
    webgraph = WebPageGraph.create_from_documents(all_documents)

    for document in all_documents:
        logging.debug('Processing "%s"', document.uri)

        text = document.text
        text = text.lower().replace('.', ' ').replace('=', ' ')

        anchor_texts = []
        for _, link in webgraph.page_linked_by(Link(document.uri)):
            if link.text:
                anchor_texts.append(link.text)

        text = ' '.join([text] + anchor_texts)

        for term in nltk.word_tokenize(text):
            if term not in vocabulary:
                vocabulary[term] = len(vocabulary)

            termid = vocabulary[term]
            term_frequency[termid] += 1

            indices.append(termid)
            data.append(1)

        index_pointers.append(len(indices))
        documents.append(document._asdict())

    n_documents = len(documents)
    n_terms = len(vocabulary)

    if n_documents == 0:
        raise OSError("Cannot find site documents. Probably site "
                      "hasn't been build yet.")

    logging.info("Found {} documents".format(n_documents))
    logging.info("Found {} terms".format(n_terms))

    logging.info("Calculation TF and IDF")
    frequencies = sp.csr_matrix((data, indices, index_pointers),
                                shape=(n_documents, n_terms))
    df = (frequencies >= 1).sum(axis=0)
    idf = np.log((n_documents / df) + 1)
    idf = np.asarray(idf)[0]

    tf = np.log1p(frequencies)
    tf.data += 1

    logging.info("Applying PageRank")
    rank = webgraph.pagerank()

    logging.info("Saving index")

    if args.for_deploy:
        save_js_index(documents, vocabulary, tf, idf, rank)
    else:
        save_python_index([documents, vocabulary, tf, idf, rank])

    logging.info("Index build was finished succesfuly")

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<form>

			<div class="title" title="<?=$module->version_detail?>">Familias - <?=$datos[operacion]?><?=$module->version_info?>

<img title="Exportar los datos a formato excel" src="<?=OS_WEB_PATH?>/applications/_commons/_images/excel.png" />

<img title="Imprimir estos datos" src="<?=OS_WEB_PATH?>/applications/_commons/_images/pdf32.png" />

<img title="Acceso directo en el escritorio" src="<?=OS_WEB_PATH?>/applications/_commons/_images/link32.png" />

Ficha

Fotos

Control

						Categoría:

							<select name="id_categoria" id="id_categoria" class="roField">
								<option value="">--Seleccionar--</option>
								<?
									$items = json_decode($module->categorias);
									foreach($items as $item){
										$selection='';
										if ($item->id==$datos[id_categoria])
											$selection='selected';
										echo "<option value='$item->id' $selection>".utf8_decode($item->categoria)."</option>\n";
									}
								?>
							</select>

						Familia:
						<input class="" type="text" name="familia" id="familia" value="<?=$datos[familia]?>" size="30"/>

						Posición:
						<input class="integer" name="posicion" id="posicion" value="<?=$datos[posicion]?>" size="5"/>

						Descripción:

					<textarea class="" name="descripcion" id="descripcion"><?=$datos[descripcion]?></textarea>

						Estado:

					 		<?
							echo '<input type="radio" id="radio1" value="ON" name="estado" '.($datos[estado]=='ON'?'checked':'').'>Online';
							echo '<input type="radio" id="radio2" value="OFF" name="estado" '.($datos[estado]=='OFF'?'checked':'').'>Offline';
							?>

					<div class="fileupload" folder-write="<?=$module->dir_images?>" folder-read="<?=$module->dir_images?>" type="image">

<input type="file" name="files[]" /><input type="hidden" id="foto_1" name="foto_1" value="<?=$datos[foto_1]?>"/>Foto...

<?=($datos[foto_1])?"dir_images/$datos[foto_1]' />":""?>

 <?=$datos[foto_1]?>

					<div class="fileupload" folder-write="<?=$module->dir_images?>" folder-read="<?=$module->dir_images?>" type="image">

<input type="file" name="files[]" /><input type="hidden" id="foto_2" name="foto_2" value="<?=$datos[foto_2]?>"/>Foto...

<?=($datos[foto_2])?"dir_images/$datos[foto_2]' />":""?>

 <?=$datos[foto_2]?>

					<div class="fileupload" folder-write="<?=$module->dir_images?>" folder-read="<?=$module->dir_images?>" type="image">

<input type="file" name="files[]" /><input type="hidden" id="foto_3" name="foto_3" value="<?=$datos[foto_3]?>"/>Foto...

<?=($datos[foto_3])?"dir_images/$datos[foto_3]' />":""?>

 <?=$datos[foto_3]?>

Arrastra las imagenes sobre las cajas para que suban automáticamente al servidor o haz click sobre el boton foto

					<? if ($this->oUser->getRol()>1){ ?>

						Fecha modificación:
						<?=$datos[ffmodificacion]?>

						Usuario:
						<?=($datos[usuario]!="0")?$datos[usuario]:'no auditado'?>

					<?} else echo "Información reservada";?>

			<?if(!$datos[familia]){?>
			<button id="btAccept"><img src="<?=OS_WEB_PATH?>/applications/_commons/_images/ok16.png"/> Aceptar</button>
			<?}else{?>
			<button id="btUpdate"><img src="<?=OS_WEB_PATH?>/applications/_commons/_images/ok16.png"/> Modificar</button>
			<?}?>
			<button id="btCancel"><img src="<?=OS_WEB_PATH?>/applications/_commons/_images/back16.png"/> Cancelar</button>

		<input type="hidden" name="id" id="id" value="<?=$datos[id]?>"/>
		<input type="hidden" name="do" id="do" value=""/>
		<input type="hidden" name="sessionclass" id="sessionclass" value="<?=$this->getOrderActionClass()->getClassSession()?>"/>
		<input type="hidden" name="class" id="class" value="<?=$this->getOrderActionClass()->getClass()?>"/>
		<input type="hidden" name="channel" id="channel" value="html"/>
	</form>


text:
package basic.file.random;

import org.apache.commons.lang3.StringUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;

/**
 * @author linuxea
 * @date 2018/4/6
 */
public class ReadAndWrite {

	private final static String FILE_PATH_WITH_NAME = "readAndWrite.txt";
	private final RandomAccessFile randomAccessFile;

	private ReadAndWrite(RandomAccessFile randomAccessFile) {
		this.randomAccessFile = randomAccessFile;
	}

	public static void main(String[] args) {
		RandomAccessFile randomAccessFile = null;
		try {
			randomAccessFile = new RandomAccessFile(FILE_PATH_WITH_NAME, "rw");
			ReadAndWrite readAndWrite = new ReadAndWrite(randomAccessFile);
			// read 按字节读取 三个字节一个中文(in most case) utf-8编码
			byte[] read = readAndWrite.read(3, 12);
			String string = StringUtils.toEncodedString(read, Charset.defaultCharset());
			System.out.println("read result: " + string);

			// write start 超过 end 也无效
			// 会覆盖
			readAndWrite.write(100, "我是新r 来的");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != randomAccessFile) {
					randomAccessFile.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param start
	 * @param size
	 * @return
	 */
	public byte[] read(int start, int size) {
		try {
			byte[] bytes = new byte[size];
			randomAccessFile.seek(start);
			randomAccessFile.read(bytes);
			return bytes;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param start
	 * @param data
	 */
	public void write(int start, String data) {
		byte[] bytes = data.getBytes();
		try {
			this.randomAccessFile.seek(start);
			this.randomAccessFile.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


text:
package com.twu.biblioteca.user;

import com.twu.biblioteca.com.twu.biblioteca.exceptions.InvalidLibraryNumberFormatException;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Created by watsonarw on 25/04/15.
 */
public class UserTest {

    @Test
    public void testToStringReturnsLibraryNumber() {
        User u = new User("123-4567", "Joe Citizen", "joe@email.com", "+61 412 345 678", "password");
        assertEquals("123-4567", u.toString());
    }

    @Test
    public void testGetDetailsShowsDetailsWhenAllExist() {
        User u = new User("123-4567", "Joe Citizen", "joe@email.com", "+61 412 345 678", "password");
        String expected = "User details for 123-4567\n" +
                          "Name:  Joe Citizen\n" +
                          "Email: joe@email.com\n" +
                          "Phone: +61 412 345 678\n";
        assertEquals(expected, u.getDetails());
    }

    @Test
    public void testGetDetailsShowsWhenDetailsDontAllExist() {
        User u = new User("123-4567", "", "", "", "password");
        String expected = "User details for 123-4567\n" +
                "Name:  \n" +
                "Email: \n" +
                "Phone: \n";
        assertEquals(expected, u.getDetails());
    }

    @Test(expected = InvalidLibraryNumberFormatException.class)
    public void testUserCantBeCreatedWithInvalidLibraryNumber() {
        User u = new User("123.4567", "Joe Citizen", "joe@email.com", "+61 412 345 678", "password");
        String expected = "User details for 123-4567\n" +
                "Name:  Joe Citizen\n" +
                "Email: joe@email.com\n" +
                "Phone: +61 412 345 678\n";
        assertEquals(expected, u.getDetails());
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="ClusterGenerators.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
#if FSCHECK

using System;
using System.Linq;
using System.Net;
using Akka.Actor;
using Akka.Tests.Shared.Internals.Helpers;
using FsCheck;

namespace Akka.Cluster.Tests
{
    /// <summary>
    /// INTERNAL API.
    ///
    /// FsCheck data generators for Akka.Cluster types.
    /// </summary>
    public class ClusterGenerators
    {
        public static Arbitrary<Address> AddressGenerator()
        {
            /*
             * In order to help guarantee collisions and duplicates in random tests, we hold all parts
             * of the address other than the port number constant.
             */
            Func<IPAddress, int, Address> combiner = (address, i) => new Address("akka.tcp", "cluster", address.ToString(), i);
            var producer = FsharpDelegateHelper.Create(combiner);

            return Arb.From(Gen.Map2(producer, Arb.Default.IPAddress().Generator, Gen.Choose(1, 65535)));
        }

        public static Arbitrary<UniqueAddress> UniqueAddressGenerator()
        {
            var gen1 = Arb.Default.Int32().Generator;
            var gen2 = AddressGenerator();

            // randomize both addresses and ports
            Func<int, Address, UniqueAddress> combiner = (uid, addr) => new UniqueAddress(addr, uid);
            var producer = FsharpDelegateHelper.Create(combiner);

            return Arb.From(Gen.Map2(producer, gen1, gen2.Generator));
        }

        public static Arbitrary<MemberStatus> MemberStatusGenerator()
        {
            return Arb.From(Gen.Elements(Enum.GetValues(typeof(MemberStatus)).Cast<MemberStatus>()));
        }
    }
}
#endif


text:
@interface PostListTableViewController() <SWTableViewCellDelegate>
@end

@implementation PostListTableViewController

-(void) viewDidLoad {
    [super viewDidLoad];

    [self.refreshControl beginRefreshing];
    [self refreshPosts: self.refreshControl];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"PostListTableCell";

    SWTableViewCell *cell = (SWTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[SWTableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.rightUtilityButtons = [self rightButtons];

        cell.delegate = self;
    }

    Post* post = [self.posts objectAtIndex:indexPath.row];
    cell.textLabel.text = post.title;
    cell.detailTextLabel.text = @"";

    return cell;
}

-(NSArray*) rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                icon: [UIImage imageNamed:@"delete.png"]];

    return rightUtilityButtons;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.posts count];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showPostDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        PostDetailViewController *destViewController = segue.destinationViewController;
        destViewController.post = [self.posts objectAtIndex:indexPath.row];
    }

    UIViewController* controller = segue.destinationViewController;
    controller.hidesBottomBarWhenPushed = YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self performSegueWithIdentifier:@"showPostDetail" sender:self];
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    Post* post = self.posts[indexPath.row];
    [post deleteInBackground];
    [self.posts removeObject:post];

    NSArray* indexPaths = [NSArray arrayWithObjects:indexPath, nil];
    [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}

- (IBAction)refreshPosts:(UIRefreshControl*)sender {
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"user" equalTo:[AVUser currentUser]];
    [query orderByDescending:@"createdAt"];

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.posts  = [NSMutableArray arrayWithCapacity:objects.count];
            for (int i = 0; i < objects.count; i++) {
                AVObject* object = objects[i];
                Post* post = [[Post alloc] init];
                post.avObject = object;
                post.objectId = [object objectId];
                post.title = [object valueForKey:@"title"];
                post.content =[object valueForKey:@"content"];

                [self.posts addObject:post];
            }

            [self.tableView reloadData];
        } else {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }

        [sender endRefreshing];
    }];
}
@end


text:
Open Assessments is a QTI client that can interpret QTI 1.x and 2.x as well as an authoring tool for generating
QTI files. It currently works with MIT's QBank system.

# Getting Started:
-----------------------

Make sure to install git, npm and yarn before you start then:

1. git clone https://github.com/atomicjolt/open_assessments my_project_name
2. Rename .env.example to .env. This file contains the port the server will use.
   The default 8080 should be fine, but you can also use a local domain or ngrok if you wish.
3. Install packages with

    `yarn`

4. Start server with:

  `yarn hot`

then visit http://localhost:8080

# Background
-----------------------
This code based has was originally developed in partnership with MIT and Atomic Jolt.
It has since been adapted by Lumen Learning and again by MIT. It is currently use in
production at institutions through the United States and Internationally.

### QTI
-----------------------
Open Assessments supports both QTI 1.x and 2.x

### Question Types
-----------------------
The Open Assessments Client supports the following question types:

1. multiple choice
2. true false
3. survey
4. matching
5. text input
6. text only
7. short answer
8. numerical input
9. multiple answers
10. file upload
11. audio upload
12. drag and drop
13. movable object chain
14. movable words sentence
15. movable words sandbox
16. fill the blank

#### edX Support
-----------------------
Development of edX support has been paused. Open Assessments did supports the drag and drop and multiple choice question types from edX
and the code is still in place, but has not been used or tested in recent versions. Support is still possible but will require work.
For more information on the edX xml structure see http://edx-open-learning-xml.readthedocs.org/en/latest/index.html

#### Assessment by Url
-----------------------
Assessments can be loaded directly from a remote url - the assessment need not be loaded into http://www.openassessments.com.
Just specify a src_url. CORS must be enabled on the server specified by src_url. Example:

http://www.openassessments.com/assessments/load?confidence_levels=true&eid=atest&src_url=https%253A%252F%252Fdl.dropboxusercontent.com%252Fu%252F7594429%252FedXCourse%252Fsequential%252F97cc2d1812204294b5fcbb91a1157368.xml

## Assets
-----------
Any files added to the assets directory can be used by in code and assigned to a variable. This
allows for referring to assets using dynamically generated strings. The assets will be built according to
the rules specified in your webpack configuration. Typically, this means that in production the names will
be changed to include a SHA.

First importing the assets:
  `import assets from '../libs/assets';`

Then assign the assest to a variable:
  `const img = assets("./images/atomicjolt.jpg");`

The value can then be used when rendering:
  `render(){
    const img = assets("./images/atomicjolt.jpg");
    return

;
  }`

## Static
-----------
Files added to the static directory will be copied directly into the build. These files will not be renamed.

# Tests
-----------
Karma and Jasmine are used for testing. To run tests run:

  `yarn test`

# Check for updates
-----------
Inside the client directory run:

  `yarn upgrade-interactive`

# Deploy to S3:
-----------------------

  1. Setup credentials. If you've already setup your Amazon credentials in ~/.aws/credentials
  you will be able to do something similar to the following where "myprofile" is one of
  the AWS profiles found in ~/.aws/credentials:

    export AWS_DEFAULT_PROFILE=myprofile
    export AWS_PROFILE=myprofile

  You can also use a .env file. See the [s3-website](https://github.com/klaemo/s3-website) documentation for more options.

  2. Edit configuration.

    Open up .s3-website.json and set the desired bucket name

  3. Configure the bucket as a website

    `yarn create`

  4. Deploy.

    `yarn release`

# Production
-----------------------
If you want to see what your application will look like in production run

  `yarn live`

This will serve files from the build/prod directory.

# Settings - can be passed via window.DEFAULT_SETTINGS or url params
-----------------------

    ##### General
    title                        - The title of the assessment. This value is typically read from the QTI file and is not required. Only provide this value to override the default title.

    ##### API endpoints
    api_url                      - Url endpoint that will be used when making API calls
    results_end_point            - Endpoint where results will be written. Might be the same as api_url but doesn't have to be

    ##### Assessment settings

    // Specify either a src_url, assessment_data or assessment_id. Only one is required.
    src_url                      - A url where the assessment can be downloaded. ie http://www.openassessments.com/api/assessments/55.xml
    assessment_data              - The assessment data in QTI format.
    assessment_id                - The id of the assessment. This value can be used to load an assessment from an endpoint that supports loading assessments by id. It can also be used to uniquely identify an assessment for reporting purposes.

    // Appearance related settings
    assessment_kind              - FORMATIVE, SUMMATIVE, or SHOW_WHAT_YOU_KNOW
    enable_start                 - Whether to show the assessment start screen before starting the assessment. This helps with calculating accurate timing. ie the timer won't start until the user presses start.
    icon                         -
    theme                        -

    // Functional settings
    max_attempts                 - The maximum number of attempts the assessment can be taken
    user_attempts                - The number of time the user has attempted the assessment
    questions_per_section        - Number of questions to utilize from each section.
    questions_per_page           - Number of questions to be displayed on screen at one time.
    shuffle_question_answers     - Shuffle the answers for each question.
    unlock_next                  - When the next set of items should be available to user. ON_CORRECT (Next questions are available when all currently visible questions have been answered correctly), ON_ANSWER_CHECK (When all answers have been checked), or ALWAYS (Next items are always available).
    confidence_levels            - Whether or not to show confidence controls
    locale                       - Sets player language. Languages currently supported: "en"
    audio_recorder_timeout       - Maximum allowed audio recording length, should be a value of seconds.

    // User settings
    role                         - The current user's role. This will control if certain controls show up. The server is still responsible for security.

    // API settings
    csrf_token                   - CSRF token provided by server. Will be added to all subsequent API requests.
    jwt                          - A jwt token that will be added to all subsequent API requests.

    // Settings for Analytics - these are returned to the calling server. All values are optional and are backend dependent.
    eid                          - External identifier. A value that can be used to uniquely identifier the user in another system. Might by a system id, student number, etc
    account_id                   - Account ID from Rails project.
    user_id                      - A user identifier that will be returned to the server whenever results or analytics are sent. Can be provided by the calling server as an authenticated user. Also provided during an LTI launch (see LTI section below)
    keywords                     - Keywords that will be passed to the server.
    user_assessment_id           -

    // LTI Launch values. These are provided by the server if the assessment is loaded via an LTI launch. These values live under the "lti" namespace
    is_lti                             - indicates if OEA was launched via LTI
    lti:
    resource_link_id                    - A resource_link_id provided by LTI launch
    resource_link_title                 - Title from the resource link ie "Steve Job's biography"
    resource_link_description           - Description from the resource link ie "Biography of Steve Jobs"
    user_id                             - A unique user id provided by the LTI launch. ie "292832126"
    roles                               - User roles from the LTI launch. ie "Instructor"
    lis_person_name_full                - The user's full name ie "Steve Jobs"
    lis_person_name_family              - The user's family (last) name ie "Jobs"
    lis_person_name_given               - The user's given (first) name ie "Steve"
    lis_person_contact_email_primary    - The user's email "steve@apple.com"
    lis_person_sourced_id               - ie "school.edu:user"
    context_id                          - ie "456434513"
    context_title                       - ie "Great Innovators"
    context_label                       - ie "SI182"
    lis_outcome_service_url             - A url where a score can be written. ie "http://www.imsglobal.org/developers/BLTI/tool_consumer_outcome.php"
    lis_result_sourcedid                - ie "feb-123-456-2929::28883"
    tool_consumer_instance_guid         - ie "lmsng.school.edu"
    tool_consumer_instance_description  - ie "University of School (LMSng)"
    oauth_callback                      - ie "about:blank"
    ext_submit                          - ie "Press to Launch"

    //
    images                       - Path to images provided by the server. Used with the Rails asset pipeline where the names of images include a SHA in production that can't be known by the client ahead of time. (This should probably be refactored so the images live with the client code rather than the server code)
    show_post_message_navigation - Show study plan and controls for LMS
    section_count                -

    ##### QBank specific settings - These are only use if you are using QBank as your backend
    api_url                      - For QBank assume the api_url looks like http://localhost:8091/api/v1 (the host and port will vary based on deployment)
    eid                          - Used by OEA to uniquely identify a User. In the MIT Clix project this isn't guaranteed to uniquely identify a user but since there are no logins this is as close as we can get.
    bank                         - The id of the QBank bank. Looks something like: "assessment.Bank%3A5751ccf64a40450c4f1c31bb%40ODL.MIT.EDU"
    assessment_offered_id        - An identifier provided by QBank that uniquely identifies the assessment to be taken. Use this id to get an assessment taken id. Looks something like "assessment.AssessmentOffered%3A576d7ee94a40456f9a434e4d%40ODL.MIT.EDU"

# Embed

Open Assessments is embedded into the page via an iframe. Example:
    ``

# Stats
-----------------------
For assessments loaded into http://www.openassessments.com you simply need to browse to the assessment and click on the bar graph.
Stats are available on the site, as json and as csv. Loading stats for an assessment that was loaded via a src_url is a bit trickier.
You'll want to specify an 'eid' (external identifier). In theory you can query later on based on src_url but that makes things hard to control and a
bit unpredictable. Here's an example using our MIT edX course:

http://www.openassessments.com/assessments/load?confidence_levels=true&eid=atest&src_url=https%253A%252F%252Fdl.dropboxusercontent.com%252Fu%252F7594429%252FedXCourse%252Fsequential%252F97cc2d1812204294b5fcbb91a1157368.xml

For that assessment, the eid specified was 'atest'. View the stats by asking for them by eid. Note that the /0? is important in the url as it tells the system
that you want to find the stats by eid rather than by id:

html:
http://www.openassessments.com/assessment_results/0?eid=atest

csv:
http://www.openassessments.com/assessment_results/0.csv?eid=atest

json:
http://www.openassessments.com/assessment_results/0.json?eid=atest

We recommend using a GUID for the eid to prevent conflicts with other assessments.

# Build issues on Linux
It has been observed on Linux machines (specifically Ubuntu, but may happen on other platforms as well), that
`yarn build` sometimes results in missing `css` classes in the build output. This is because `node-sass` was not
installed properly, so the `.scss` files do not get compiled by `webpack`. To solve this, you need to
re-build `node-sass`  with the following command:

```
npm rebuild node-sass
yarn build
```

You can check for this problem by looking for a component class like `c-header` in `player_styles-*hash*.css`
in `build/prod`.


text:
package org.camunda.bpm.container.impl.jboss.test;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import javax.xml.stream.XMLStreamException;

import org.camunda.bpm.container.impl.jboss.config.ManagedProcessEngineMetadata;
import org.camunda.bpm.container.impl.jboss.extension.Attribute;
import org.camunda.bpm.container.impl.jboss.extension.BpmPlatformExtension;
import org.camunda.bpm.container.impl.jboss.extension.Element;
import org.camunda.bpm.container.impl.jboss.extension.ModelConstants;
import org.camunda.bpm.container.impl.jboss.extension.SubsystemAttributeDefinitons;
import org.camunda.bpm.container.impl.jboss.service.MscManagedProcessEngineController;
import org.camunda.bpm.container.impl.jboss.service.ServiceNames;
import org.camunda.bpm.container.impl.metadata.spi.ProcessEnginePluginXml;
import org.camunda.bpm.container.impl.plugin.BpmPlatformPlugin;
import org.camunda.bpm.container.impl.plugin.BpmPlatformPlugins;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.threads.ManagedQueueExecutorService;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.junit.Test;

/**
 *
 * @author nico.rehwaldt@camunda.com
 * @author christian.lipphardt@camunda.com
 */
public class JBossSubsystemXMLTest extends AbstractSubsystemTest {

  public static final String SUBSYSTEM_WITH_SINGLE_ENGINE = "subsystemWithSingleEngine.xml";
  public static final String SUBSYSTEM_WITH_ENGINES = "subsystemWithEngines.xml";
  public static final String SUBSYSTEM_WITH_PROCESS_ENGINES_ELEMENT_ONLY = "subsystemWithProcessEnginesElementOnly.xml";
  public static final String SUBSYSTEM_WITH_ENGINES_AND_PROPERTIES = "subsystemWithEnginesAndProperties.xml";
  public static final String SUBSYSTEM_WITH_ENGINES_PROPERTIES_PLUGINS = "subsystemWithEnginesPropertiesPlugins.xml";
  public static final String SUBSYSTEM_WITH_DUPLICATE_ENGINE_NAMES = "subsystemWithDuplicateEngineNames.xml";
  public static final String SUBSYSTEM_WITH_JOB_EXECUTOR = "subsystemWithJobExecutor.xml";
  public static final String SUBSYSTEM_WITH_PROCESS_ENGINES_AND_JOB_EXECUTOR = "subsystemWithProcessEnginesAndJobExecutor.xml";
  public static final String SUBSYSTEM_WITH_JOB_EXECUTOR_AND_PROPERTIES = "subsystemWithJobExecutorAndProperties.xml";
  public static final String SUBSYSTEM_WITH_JOB_EXECUTOR_WITHOUT_ACQUISITION_STRATEGY = "subsystemWithJobExecutorAndWithoutAcquisitionStrategy.xml";
  public static final String SUBSYSTEM_WITH_ALL_OPTIONS = "subsystemWithAllOptions.xml";
  public static final String SUBSYSTEM_WITH_REQUIRED_OPTIONS = "subsystemWithRequiredOptions.xml";
  public static final String SUBSYSTEM_WITH_NO_OPTIONS = "subsystemWithNoOptions.xml";
  public static final String SUBSYSTEM_WITH_ALL_OPTIONS_WITH_EXPRESSIONS = "subsystemWithAllOptionsWithExpressions.xml";

  public static final String LOCK_TIME_IN_MILLIS = "lockTimeInMillis";
  public static final String WAIT_TIME_IN_MILLIS = "waitTimeInMillis";
  public static final String MAX_JOBS_PER_ACQUISITION = "maxJobsPerAcquisition";

  public static final ServiceName PLATFORM_SERVICE_NAME = ServiceNames.forMscRuntimeContainerDelegate();
  public static final ServiceName PLATFORM_JOBEXECUTOR_SERVICE_NAME = ServiceNames.forMscExecutorService();
  public static final ServiceName PLATFORM_BPM_PLATFORM_PLUGINS_SERVICE_NAME = ServiceNames.forBpmPlatformPlugins();
  public static final ServiceName PLATFORM_JOBEXECUTOR_MANAGED_THREAD_POOL_SERVICE_NAME =
      ServiceNames.forManagedThreadPool(SubsystemAttributeDefinitons.THREAD_POOL_NAME.getDefaultValue().asString());

  public static final ServiceName PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
    .append("camunda-bpm-platform")
    .append("process-engine")
    .append("ProcessEngineService!org.camunda.bpm.ProcessEngineService");

  public JBossSubsystemXMLTest() {
    super(ModelConstants.SUBSYSTEM_NAME, new BpmPlatformExtension(), getSubsystemRemoveOrderComparator());
  }

  private static Map<String, String> EXPRESSION_PROPERTIES = new HashMap<>();

  static {
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.isDefault", "true");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.datasource", "java:jboss/datasources/ExampleDS");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.history-level", "audit");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.configuration", "org.camunda.bpm.container.impl.jboss.config.ManagedJtaProcessEngineConfiguration");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.property.job-acquisition-name", "default");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.plugin.ldap.class", "org.camunda.bpm.identity.impl.ldap.plugin.LdapIdentityProviderPlugin");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.plugin.ldap.property.test", "abc");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.plugin.ldap.property.number", "123");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.process-engine.test.plugin.ldap.property.bool", "true");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.thread-pool-name", "job-executor-tp");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.core-threads", "5");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.max-threads", "15");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.queue-length", "15");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.keepalive-time", "10");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.allow-core-timeout", "false");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.job-acquisition.default.acquisition-strategy", "SEQUENTIAL");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.job-acquisition.default.property.lockTimeInMillis", "300000");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.job-acquisition.default.property.waitTimeInMillis", "5000");
    EXPRESSION_PROPERTIES.put("org.camunda.bpm.jboss.job-executor.job-acquisition.default.property.maxJobsPerAcquisition", "3");
  }

  @Test
  public void testParseSubsystemXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_PROCESS_ENGINES_ELEMENT_ONLY);

    List<ModelNode> operations = parse(subsystemXml);

    assertEquals(1, operations.size());
    //The add subsystem operation will happen first
    ModelNode addSubsystem = operations.get(0);
    assertEquals(ADD, addSubsystem.get(OP).asString());
    PathAddress addr = PathAddress.pathAddress(addSubsystem.get(OP_ADDR));
    assertEquals(1, addr.size());
    PathElement element = addr.getElement(0);
    assertEquals(SUBSYSTEM, element.getKey());
    assertEquals(ModelConstants.SUBSYSTEM_NAME, element.getValue());
  }

  @Test
  public void testParseSubsystemXmlWithEngines() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES);

    List<ModelNode> operations = parse(subsystemXml);
    assertEquals(3, operations.size());
  }

  @Test
  public void testParseSubsystemXmlWithEnginesAndProperties() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES_AND_PROPERTIES);

    List<ModelNode> operations = parse(subsystemXml);
    assertEquals(5, operations.size());
  }

  @Test
  public void testParseSubsystemXmlWithEnginesPropertiesPlugins() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES_PROPERTIES_PLUGINS);

    List<ModelNode> operations = parse(subsystemXml);
    assertEquals(3, operations.size());
  }

  @Test
  public void testInstallSubsystemWithEnginesPropertiesPlugins() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES_PROPERTIES_PLUGINS);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();

    ServiceContainer container = services.getContainer();

    assertNotNull("platform service should be installed", container.getRequiredService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getRequiredService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));

    ServiceController<?> defaultEngineService = container.getService(ServiceNames.forManagedProcessEngine("__default"));

    assertNotNull("process engine controller for engine __default is installed ", defaultEngineService);

    ManagedProcessEngineMetadata metadata = ((MscManagedProcessEngineController) defaultEngineService.getService()).getProcessEngineMetadata();
    Map<String, String> configurationProperties = metadata.getConfigurationProperties();
    assertEquals("default", configurationProperties.get("job-name"));
    assertEquals("default", configurationProperties.get("job-acquisition"));
    assertEquals("default", configurationProperties.get("job-acquisition-name"));

    Map<String, String> foxLegacyProperties = metadata.getFoxLegacyProperties();
    assertTrue(foxLegacyProperties.isEmpty());

    assertNotNull("process engine controller for engine __default is installed ", container.getRequiredService(ServiceNames.forManagedProcessEngine("__default")));
    assertNotNull("process engine controller for engine __test is installed ", container.getRequiredService(ServiceNames.forManagedProcessEngine("__test")));

    // check we have parsed the plugin configurations
    metadata = ((MscManagedProcessEngineController) container.getRequiredService(ServiceNames.forManagedProcessEngine("__test")).getService())
        .getProcessEngineMetadata();
    List<ProcessEnginePluginXml> pluginConfigurations = metadata.getPluginConfigurations();

    ProcessEnginePluginXml processEnginePluginXml = pluginConfigurations.get(0);
    assertEquals("org.camunda.bpm.identity.impl.ldap.plugin.LdapIdentityProviderPlugin", processEnginePluginXml.getPluginClass());
    Map<String, String> processEnginePluginXmlProperties = processEnginePluginXml.getProperties();
    assertEquals("abc", processEnginePluginXmlProperties.get("test"));
    assertEquals("123", processEnginePluginXmlProperties.get("number"));
    assertEquals("true", processEnginePluginXmlProperties.get("bool"));

    processEnginePluginXml = pluginConfigurations.get(1);
    assertEquals("org.camunda.bpm.identity.impl.ldap.plugin.LdapIdentityProviderPlugin", processEnginePluginXml.getPluginClass());
    processEnginePluginXmlProperties = processEnginePluginXml.getProperties();
    assertEquals("cba", processEnginePluginXmlProperties.get("test"));
    assertEquals("321", processEnginePluginXmlProperties.get("number"));
    assertEquals("false", processEnginePluginXmlProperties.get("bool"));

    // test correct subsystem removal
    assertRemoveSubsystemResources(services);
    try {
      ServiceController<?> service = container.getRequiredService(ServiceNames.forManagedProcessEngine("__default"));
      fail("Service '" + service.getName() + "' should have been removed.");
    } catch (Exception expected) {
      // nop
    }
    try {
      ServiceController<?> service = container.getRequiredService(ServiceNames.forManagedProcessEngine("__test"));
      fail("Service '" + service.getName() + "' should have been removed.");
    } catch (Exception expected) {
      // nop
    }
  }

  @Test
  public void testInstallSubsystemXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_PROCESS_ENGINES_ELEMENT_ONLY);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();

    ServiceContainer container = services.getContainer();

    assertNotNull("platform service should be installed", container.getService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));
    assertNull(container.getService(PLATFORM_JOBEXECUTOR_SERVICE_NAME));
  }

  @Test
  public void testInstallSubsystemXmlPlatformPlugins() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_PROCESS_ENGINES_ELEMENT_ONLY);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();

    ServiceContainer container = services.getContainer();
    ServiceController<?> serviceController = container.getService(PLATFORM_BPM_PLATFORM_PLUGINS_SERVICE_NAME);
    assertNotNull(serviceController);
    Object platformPlugins = serviceController.getValue();
    assertNotNull(platformPlugins);
    assertTrue(platformPlugins instanceof BpmPlatformPlugins);
    List<BpmPlatformPlugin> plugins = ((BpmPlatformPlugins) platformPlugins).getPlugins();
    assertEquals(1, plugins.size());
    assertTrue(plugins.get(0) instanceof ExampleBpmPlatformPlugin);
  }

  @Test
  public void testInstallSubsystemWithEnginesXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();

    ServiceContainer container = services.getContainer();
    assertNotNull("platform service should be installed", container.getService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));

    assertNotNull("process engine controller for engine __default is installed ", container.getService(ServiceNames.forManagedProcessEngine("__default")));
    assertNotNull("process engine controller for engine __test is installed ", container.getService(ServiceNames.forManagedProcessEngine("__test")));
  }

  @Test
  public void testInstallSubsystemWithEnginesAndPropertiesXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ENGINES_AND_PROPERTIES);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    assertNotNull("platform service should be installed", container.getService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));

    ServiceController<?> defaultEngineService = container.getService(ServiceNames.forManagedProcessEngine("__default"));

    assertNotNull("process engine controller for engine __default is installed ", defaultEngineService);

    ManagedProcessEngineMetadata metadata = ((MscManagedProcessEngineController) defaultEngineService.getService()).getProcessEngineMetadata();
    Map<String, String> configurationProperties = metadata.getConfigurationProperties();
    assertEquals("default", configurationProperties.get("job-name"));
    assertEquals("default", configurationProperties.get("job-acquisition"));
    assertEquals("default", configurationProperties.get("job-acquisition-name"));

    Map<String, String> foxLegacyProperties = metadata.getFoxLegacyProperties();
    assertTrue(foxLegacyProperties.isEmpty());

    assertNotNull("process engine controller for engine __test is installed ", container.getService(ServiceNames.forManagedProcessEngine("__test")));
    assertNotNull("process engine controller for engine __emptyPropertiesTag is installed ", container.getService(ServiceNames.forManagedProcessEngine("__emptyPropertiesTag")));
    assertNotNull("process engine controller for engine __noPropertiesTag is installed ", container.getService(ServiceNames.forManagedProcessEngine("__noPropertiesTag")));
  }

  @Test
  public void testInstallSubsystemWithDuplicateEngineNamesXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_DUPLICATE_ENGINE_NAMES);

    try {
      createKernelServicesBuilder(null)
          .setSubsystemXml(subsystemXml)
          .build();

    } catch (XMLStreamException fpe) {
      assertTrue("Duplicate process engine detected!", fpe.getNestedException().getMessage().contains("A process engine with name '__test' already exists."));
    }
  }

  @Test
  public void testInstallSubsystemWithSingleEngineXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_SINGLE_ENGINE);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    assertNotNull("platform service should be installed", container.getService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));

    assertNotNull("process engine controller for engine __default is installed ", container.getService(ServiceNames.forManagedProcessEngine("__default")));

    String persistedSubsystemXml = services.getPersistedSubsystemXml();
    compareXml(null, subsystemXml, persistedSubsystemXml);
  }

  @Test
  public void testParseSubsystemWithJobExecutorXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_JOB_EXECUTOR);
//    System.out.println(normalizeXML(subsystemXml));

    List<ModelNode> operations = parse(subsystemXml);
//    System.out.println(operations);
    assertEquals(4, operations.size());

    ModelNode jobExecutor = operations.get(1);
    PathAddress pathAddress = PathAddress.pathAddress(jobExecutor.get(ModelDescriptionConstants.OP_ADDR));
    assertEquals(2, pathAddress.size());

    PathElement element = pathAddress.getElement(0);
    assertEquals(ModelDescriptionConstants.SUBSYSTEM, element.getKey());
    assertEquals(ModelConstants.SUBSYSTEM_NAME, element.getValue());
    element = pathAddress.getElement(1);
    assertEquals(Element.JOB_EXECUTOR.getLocalName(), element.getKey());
    assertEquals(Attribute.DEFAULT.getLocalName(), element.getValue());

    assertEquals("job-executor-tp", jobExecutor.get(Element.THREAD_POOL_NAME.getLocalName()).asString());

    ModelNode jobAcquisition = operations.get(2);
    assertEquals("default", jobAcquisition.get(Attribute.NAME.getLocalName()).asString());
    assertEquals("SEQUENTIAL", jobAcquisition.get(Element.ACQUISITION_STRATEGY.getLocalName()).asString());
    assertFalse(jobAcquisition.has(Element.PROPERTIES.getLocalName()));

    jobAcquisition = operations.get(3);
    assertEquals("anders", jobAcquisition.get(Attribute.NAME.getLocalName()).asString());
    assertEquals("SEQUENTIAL", jobAcquisition.get(Element.ACQUISITION_STRATEGY.getLocalName()).asString());
  }

  @Test
  public void testInstallSubsystemWithJobExecutorXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_JOB_EXECUTOR);
    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    commonSubsystemServicesAreInstalled(container);
  }

  @Test
  public void testParseSubsystemWithJobExecutorAndPropertiesXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_JOB_EXECUTOR_AND_PROPERTIES);

    List<ModelNode> operations = parse(subsystemXml);
    assertEquals(5, operations.size());

    // "default" job acquisition ///////////////////////////////////////////////////////////
    ModelNode jobAcquisition = operations.get(2);
    assertEquals("default", jobAcquisition.get(Attribute.NAME.getLocalName()).asString());
    assertFalse(jobAcquisition.has(Element.PROPERTIES.getLocalName()));

    // "anders" job acquisition ////////////////////////////////////////////////////////////
    jobAcquisition = operations.get(3);
    assertEquals("anders", jobAcquisition.get(Attribute.NAME.getLocalName()).asString());
    assertTrue(jobAcquisition.has(Element.PROPERTIES.getLocalName()));
    assertTrue(jobAcquisition.hasDefined(Element.PROPERTIES.getLocalName()));

    ModelNode properties = jobAcquisition.get(Element.PROPERTIES.getLocalName());
    assertEquals(3, properties.asPropertyList().size());

    assertTrue(properties.has(LOCK_TIME_IN_MILLIS));
    assertTrue(properties.hasDefined(LOCK_TIME_IN_MILLIS));
    assertEquals(600000, properties.get(LOCK_TIME_IN_MILLIS).asInt());

    assertTrue(properties.has(WAIT_TIME_IN_MILLIS));
    assertTrue(properties.hasDefined(WAIT_TIME_IN_MILLIS));
    assertEquals(10000, properties.get(WAIT_TIME_IN_MILLIS).asInt());

    assertTrue(properties.has(MAX_JOBS_PER_ACQUISITION));
    assertTrue(properties.hasDefined(MAX_JOBS_PER_ACQUISITION));
    assertEquals(5, properties.get(MAX_JOBS_PER_ACQUISITION).asInt());

    // "mixed" job acquisition ////////////////////////////////////////////////////////////
    jobAcquisition = operations.get(4);
    assertEquals("mixed", jobAcquisition.get(Attribute.NAME.getLocalName()).asString());
    assertTrue(jobAcquisition.has(Element.PROPERTIES.getLocalName()));
    assertTrue(jobAcquisition.hasDefined(Element.PROPERTIES.getLocalName()));

    properties = jobAcquisition.get(Element.PROPERTIES.getLocalName());
    assertEquals(1, properties.asPropertyList().size());

    assertTrue(properties.has(LOCK_TIME_IN_MILLIS));
    assertTrue(properties.hasDefined(LOCK_TIME_IN_MILLIS));
    assertEquals(500000, properties.get(LOCK_TIME_IN_MILLIS).asInt());

    assertFalse(properties.has(WAIT_TIME_IN_MILLIS));
    assertFalse(properties.hasDefined(WAIT_TIME_IN_MILLIS));
    assertFalse(properties.has(MAX_JOBS_PER_ACQUISITION));
    assertFalse(properties.hasDefined(MAX_JOBS_PER_ACQUISITION));

  }

  @Test
  public void testInstallSubsystemWithJobExecutorAndPropertiesXml() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_JOB_EXECUTOR_AND_PROPERTIES);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    commonSubsystemServicesAreInstalled(container);

    // "default" job acquisition ///////////////////////////////////////////////////////////
    ServiceController<?> defaultJobAcquisitionService = container.getService(ServiceNames.forMscRuntimeContainerJobExecutorService("default"));
    assertNotNull("platform job acquisition service 'default' should be installed", defaultJobAcquisitionService);

    Object value = defaultJobAcquisitionService.getValue();
    assertNotNull(value);
    assertTrue(value instanceof JobExecutor);

    JobExecutor defaultJobExecutor = (JobExecutor) value;
    assertEquals(300000, defaultJobExecutor.getLockTimeInMillis());
    assertEquals(5000, defaultJobExecutor.getWaitTimeInMillis());
    assertEquals(3, defaultJobExecutor.getMaxJobsPerAcquisition());

    // ServiceName: 'org.camunda.bpm.platform.job-executor.job-executor-tp'
    ServiceController<?> managedQueueExecutorServiceController = container.getService(ServiceNames.forManagedThreadPool(SubsystemAttributeDefinitons.DEFAULT_JOB_EXECUTOR_THREADPOOL_NAME));
    assertNotNull(managedQueueExecutorServiceController);
    Object managedQueueExecutorServiceObject = managedQueueExecutorServiceController.getValue();
    assertNotNull(managedQueueExecutorServiceObject);
    assertTrue(managedQueueExecutorServiceObject instanceof ManagedQueueExecutorService);
    ManagedQueueExecutorService managedQueueExecutorService = (ManagedQueueExecutorService) managedQueueExecutorServiceObject;
    assertEquals("Number of core threads is wrong", SubsystemAttributeDefinitons.DEFAULT_CORE_THREADS, managedQueueExecutorService.getCoreThreads());
    assertEquals("Number of max threads is wrong", SubsystemAttributeDefinitons.DEFAULT_MAX_THREADS, managedQueueExecutorService.getMaxThreads());
    assertEquals(SubsystemAttributeDefinitons.DEFAULT_KEEPALIVE_TIME, TimeUnit.NANOSECONDS.toSeconds(managedQueueExecutorService.getKeepAlive()));
    assertEquals(false, managedQueueExecutorService.isBlocking());
    assertEquals(SubsystemAttributeDefinitons.DEFAULT_ALLOW_CORE_TIMEOUT, managedQueueExecutorService.isAllowCoreTimeout());

    ServiceController<?> threadFactoryService = container.getService(ServiceNames.forThreadFactoryService(SubsystemAttributeDefinitons.DEFAULT_JOB_EXECUTOR_THREADPOOL_NAME));
    assertNotNull(threadFactoryService);
    assertTrue(threadFactoryService.getValue() instanceof ThreadFactory);

    // "anders" job acquisition /////////////////////////////////////////////////////////
    ServiceController<?> andersJobAcquisitionService = container.getService(ServiceNames.forMscRuntimeContainerJobExecutorService("anders"));
    assertNotNull("platform job acquisition service 'anders' should be installed", andersJobAcquisitionService);

    value = andersJobAcquisitionService.getValue();
    assertNotNull(value);
    assertTrue(value instanceof JobExecutor);

    JobExecutor andersJobExecutor = (JobExecutor) value;
    assertEquals(600000, andersJobExecutor.getLockTimeInMillis());
    assertEquals(10000, andersJobExecutor.getWaitTimeInMillis());
    assertEquals(5, andersJobExecutor.getMaxJobsPerAcquisition());

    // "mixed" job acquisition /////////////////////////////////////////////////////////
    ServiceController<?> mixedJobAcquisitionService = container.getService(ServiceNames.forMscRuntimeContainerJobExecutorService("mixed"));
    assertNotNull("platform job acquisition service 'mixed' should be installed", mixedJobAcquisitionService);

    value = mixedJobAcquisitionService.getValue();
    assertNotNull(value);
    assertTrue(value instanceof JobExecutor);

    JobExecutor mixedJobExecutor = (JobExecutor) value;
    assertEquals(500000, mixedJobExecutor.getLockTimeInMillis());
    // default values
    assertEquals(5000, mixedJobExecutor.getWaitTimeInMillis());
    assertEquals(3, mixedJobExecutor.getMaxJobsPerAcquisition());

  }

  @Test
  public void testJobAcquisitionStrategyOptional() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_JOB_EXECUTOR_WITHOUT_ACQUISITION_STRATEGY);
    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    commonSubsystemServicesAreInstalled(container);
  }

  @Test
  public void testParseSubsystemXmlWithEnginesAndJobExecutor() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_PROCESS_ENGINES_AND_JOB_EXECUTOR);

    List<ModelNode> operations = parse(subsystemXml);
    System.out.println(operations);
    assertEquals(6, operations.size());
  }

  @Test
  public void testInstallSubsystemXmlWithEnginesAndJobExecutor() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_PROCESS_ENGINES_AND_JOB_EXECUTOR);

    KernelServices services = createKernelServicesBuilder(null)
        .setSubsystemXml(subsystemXml)
        .build();
    ServiceContainer container = services.getContainer();

    commonSubsystemServicesAreInstalled(container);
    assertNotNull("process engine controller for engine __default is installed ", container.getService(ServiceNames.forManagedProcessEngine("__default")));
    assertNotNull("process engine controller for engine __test is installed ", container.getService(ServiceNames.forManagedProcessEngine("__test")));

    String persistedSubsystemXml = services.getPersistedSubsystemXml();
    compareXml(null, subsystemXml, persistedSubsystemXml);
  }

  @Test
  public void testParseAndMarshalModelWithAllAvailableOptions() throws Exception {
    parseAndMarshalSubsystemModelFromFile(SUBSYSTEM_WITH_ALL_OPTIONS);
  }

  @Test
  public void testParseAndMarshalModelWithRequiredOptionsOnly() throws Exception {
    parseAndMarshalSubsystemModelFromFile(SUBSYSTEM_WITH_REQUIRED_OPTIONS);
  }

  @Test
  public void testParseAndMarshalModelWithAllAvailableOptionsWithExpressions() throws Exception {
    System.getProperties().putAll(EXPRESSION_PROPERTIES);
    try {
      parseAndMarshalSubsystemModelFromFile(SUBSYSTEM_WITH_ALL_OPTIONS_WITH_EXPRESSIONS);
    } finally {
      for (String key : EXPRESSION_PROPERTIES.keySet()) {
        System.clearProperty(key);
      }
    }
  }

  @Test
  public void testParseSubsystemXmlWithAllOptionsWithExpressions() throws Exception {
    String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ALL_OPTIONS_WITH_EXPRESSIONS);

    List<ModelNode> operations = parse(subsystemXml);

    assertEquals(4, operations.size());
    // all elements with expression allowed should be an expression now
    assertExpressionType(operations.get(1), "default", "datasource", "history-level", "configuration");
    assertExpressionType(operations.get(1).get("properties"), "job-acquisition-name");
    assertExpressionType(operations.get(1).get("plugins").get(0), "class");
    assertExpressionType(operations.get(1).get("plugins").get(0).get("properties"), "test", "number", "bool");
    assertExpressionType(operations.get(2), "thread-pool-name", "core-threads", "max-threads", "queue-length", "keepalive-time", "allow-core-timeout");
    assertExpressionType(operations.get(3), "acquisition-strategy");
    assertExpressionType(operations.get(3).get("properties"), "lockTimeInMillis", "waitTimeInMillis", "maxJobsPerAcquisition");
    // all other elements should be string still
    assertStringType(operations.get(1), "name");// process-engine name
    assertStringType(operations.get(3), "name");// job-acquisition name
  }

  @Test
  public void testInstallSubsystemXmlWithAllOptionsWithExpressions() throws Exception {
    System.getProperties().putAll(EXPRESSION_PROPERTIES);
    try {
      String subsystemXml = FileUtils.readFile(SUBSYSTEM_WITH_ALL_OPTIONS_WITH_EXPRESSIONS);
      KernelServices services = createKernelServicesBuilder(null)
          .setSubsystemXml(subsystemXml)
          .build();
      ServiceContainer container = services.getContainer();

      assertNotNull("platform service should be installed", container.getRequiredService(PLATFORM_SERVICE_NAME));
      assertNotNull("process engine service should be bound in JNDI", container.getRequiredService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));

      ServiceController<?> defaultEngineService = container.getService(ServiceNames.forManagedProcessEngine("__test"));

      assertNotNull("process engine controller for engine __test is installed ", defaultEngineService);

      ManagedProcessEngineMetadata metadata = ((MscManagedProcessEngineController) defaultEngineService.getService()).getProcessEngineMetadata();
      Map<String, String> configurationProperties = metadata.getConfigurationProperties();
      assertEquals("default", configurationProperties.get("job-acquisition-name"));

      Map<String, String> foxLegacyProperties = metadata.getFoxLegacyProperties();
      assertTrue(foxLegacyProperties.isEmpty());

      assertNotNull("process engine controller for engine __test is installed ", container.getRequiredService(ServiceNames.forManagedProcessEngine("__test")));

      // check we have parsed the plugin configurations
      List<ProcessEnginePluginXml> pluginConfigurations = metadata.getPluginConfigurations();

      assertEquals(1, pluginConfigurations.size());

      ProcessEnginePluginXml processEnginePluginXml = pluginConfigurations.get(0);
      assertEquals("org.camunda.bpm.identity.impl.ldap.plugin.LdapIdentityProviderPlugin", processEnginePluginXml.getPluginClass());
      Map<String, String> processEnginePluginXmlProperties = processEnginePluginXml.getProperties();
      assertEquals("abc", processEnginePluginXmlProperties.get("test"));
      assertEquals("123", processEnginePluginXmlProperties.get("number"));
      assertEquals("true", processEnginePluginXmlProperties.get("bool"));
    } finally {
      for (String key : EXPRESSION_PROPERTIES.keySet()) {
        System.clearProperty(key);
      }
    }
  }

  // HELPERS

  /**
   *  Parses and marshall the given subsystemXmlFile into one controller, then reads the model into second one.
   *  Compares the models afterwards.
   * @param subsystemXmlFile the name of the subsystem xml file
   * @throws Exception
   */
  protected void parseAndMarshalSubsystemModelFromFile(String subsystemXmlFile) throws Exception {
    String subsystemXml = FileUtils.readFile(subsystemXmlFile);
    // Parse the subsystem xml and install into the first controller
    KernelServices servicesA = createKernelServicesBuilder(null).setSubsystemXml(subsystemXml).build();
    // Get the model and the persisted xml from the first controller
    ModelNode modelA = servicesA.readWholeModel();
    String marshalled = servicesA.getPersistedSubsystemXml();

    // Make sure the xml is the same
    compareXml(null, subsystemXml, marshalled);

    // Install the persisted xml from the first controller into a second controller
    KernelServices servicesB = createKernelServicesBuilder(null).setSubsystemXml(marshalled).build();
    ModelNode modelB = servicesB.readWholeModel();

    // Make sure the models from the two controllers are identical
    compare(modelA, modelB);
  }

  protected void commonSubsystemServicesAreInstalled(ServiceContainer container) {
    assertNotNull("platform service should be installed", container.getService(PLATFORM_SERVICE_NAME));
    assertNotNull("process engine service should be bound in JNDI", container.getService(PROCESS_ENGINE_SERVICE_BINDING_SERVICE_NAME));
    assertNotNull("platform jobexecutor service should be installed", container.getService(PLATFORM_JOBEXECUTOR_SERVICE_NAME));
    assertNotNull("platform jobexecutor managed threadpool service should be installed", container.getService(PLATFORM_JOBEXECUTOR_MANAGED_THREAD_POOL_SERVICE_NAME));
    assertNotNull("bpm platform plugins service should be installed", container.getService(PLATFORM_BPM_PLATFORM_PLUGINS_SERVICE_NAME));
  }

  protected static Comparator<PathAddress> getSubsystemRemoveOrderComparator() {
    final List<PathAddress> REMOVE_ORDER_OF_SUBSYSTEM = Arrays.asList(
        PathAddress.pathAddress(BpmPlatformExtension.SUBSYSTEM_PATH),
        PathAddress.pathAddress(BpmPlatformExtension.JOB_EXECUTOR_PATH),
        PathAddress.pathAddress(BpmPlatformExtension.JOB_ACQUISTIONS_PATH),
        PathAddress.pathAddress(BpmPlatformExtension.PROCESS_ENGINES_PATH)
    );

    return new Comparator<PathAddress>() {
      protected PathAddress normalizePathAddress(PathAddress pathAddress) {
        if (pathAddress.size() == 1 && pathAddress.equals(REMOVE_ORDER_OF_SUBSYSTEM.get(0))) {
          return pathAddress;
        } else {
          // strip subsystem parentAddress
          return pathAddress.subAddress(1, pathAddress.size());
        }
      }

      protected int getOrder(PathAddress pathAddress) {
        for (PathAddress orderedAddress : REMOVE_ORDER_OF_SUBSYSTEM) {
          if (orderedAddress.getLastElement().getKey().equals(pathAddress.getLastElement().getKey())) {
            return REMOVE_ORDER_OF_SUBSYSTEM.indexOf(orderedAddress);
          }
        }
        throw new IllegalArgumentException("Unable to find a match for path address: " + pathAddress);
      }

      @Override
      public int compare(PathAddress o1, PathAddress o2) {
        int orderO1 = getOrder(normalizePathAddress(o1));
        int orderO2 = getOrder(normalizePathAddress(o2));

        if (orderO1 < orderO2) {
          return -1;
        } else if (orderO1 > orderO2) {
          return 1;
        } else {
          return 0;
        }
      }
    };
  }

  private void assertExpressionType(ModelNode operation, String... elements) {
    assertModelType(ModelType.EXPRESSION, operation, elements);
  }

  private void assertStringType(ModelNode operation, String... elements) {
    assertModelType(ModelType.STRING, operation, elements);
  }

  private void assertModelType(ModelType type, ModelNode operation, String... elements) {
    for (String element : elements) {
      assertEquals(type, operation.get(element).getType());
    }
  }
}


text:
Foundation.utils.S(document).ready(function(){
  //Authorization popup window code
  Foundation.utils.S.oauthGH = function(options){
    options.windowName = options.windowName ||  'ConnectWithOAuth'; // should not include space for IE
    options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=400';
    options.callback = options.callback || function(){ window.location.reload(); };
    var that = this;
    that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
    that._oauthInterval = window.setInterval(function(){
      var $link = "";
      if (that._oauthWindow.location.href)
        $link = that._oauthWindow.location.href;
      if($link.indexOf(options.redirectUrl) > -1){
         options.callback(that._oauthWindow);
         that._oauthWindow.close();
         clearInterval(that._oauthInterval);
        }
    }, 1000);
  };

});


text:
using System;

namespace Akka.Streams.Actors
{
    ///<summary>
    /// An <see cref="ActorSubscriber"/> defines a <see cref="IRequestStrategy"/>
    /// to control the stream back pressure.
    /// </summary>
    public interface IRequestStrategy
    {
         /// <summary>
         /// Invoked by the <see cref="ActorSubscriber"/> after each incoming message to
         /// determine how many more elements to request from the stream.
         /// </summary>
         /// <param name="remainingRequested">current remaining number of elements
         /// that have been requested from upstream but not received yet</param>
         /// <returns>demand of more elements from the stream, returning 0 means that no
         /// more elements will be requested for now</returns>
        int RequestDemand(int remainingRequested);
    }

    /// <summary>
    /// Requests one more element when remainingRequested is 0, i.e.
    /// * max one element in flight.
    /// </summary>
    public sealed class OneByOneRequestStrategy : IRequestStrategy
    {
        /// <summary>
        /// TBD
        /// </summary>
        public static readonly OneByOneRequestStrategy Instance = new OneByOneRequestStrategy();
        private OneByOneRequestStrategy() { }

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="remainingRequested">TBD</param>
        /// <returns>TBD</returns>
        public int RequestDemand(int remainingRequested) => remainingRequested == 0 ? 1 : 0;
    }

    /// <summary>
    /// When request is only controlled with manual calls to <see cref="ActorSubscriber.Request"/>.
    /// </summary>
    public sealed class ZeroRequestStrategy : IRequestStrategy
    {
        /// <summary>
        /// TBD
        /// </summary>
        public static readonly ZeroRequestStrategy Instance = new ZeroRequestStrategy();
        private ZeroRequestStrategy() { }

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="remainingRequested">TBD</param>
        /// <returns>TBD</returns>
        public int RequestDemand(int remainingRequested) => 0;
    }

    /// <summary>
    /// Requests up to the highWatermark when the remainingRequested is
    /// below the lowWatermark. This a good strategy when the actor performs work itself.
    /// </summary>
    public sealed class WatermarkRequestStrategy : IRequestStrategy
    {
        /// <summary>
        /// TBD
        /// </summary>
        public readonly int HighWatermark;
        /// <summary>
        /// TBD
        /// </summary>
        public readonly int LowWatermark;

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="highWatermark">TBD</param>
        public WatermarkRequestStrategy(int highWatermark)
        {
            HighWatermark = highWatermark;
            LowWatermark = Math.Max(1, highWatermark / 2);
        }

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="highWatermark">TBD</param>
        /// <param name="lowWatermark">TBD</param>
        public WatermarkRequestStrategy(int highWatermark, int lowWatermark)
        {
            HighWatermark = highWatermark;
            LowWatermark = lowWatermark;
        }

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="remainingRequested">TBD</param>
        /// <returns>TBD</returns>
        public int RequestDemand(int remainingRequested)
        {
            return remainingRequested < LowWatermark ? HighWatermark - remainingRequested : 0;
        }
    }

    /// <summary>
    /// Requests up to the max and also takes the number of messages
    /// that have been queued internally or delegated to other actors into account.
    /// Concrete subclass must implement <see cref="InFlight"/>.
    /// It will request elements in minimum batches of the defined <see cref="BatchSize"/>.
    /// </summary>
    public abstract class MaxInFlightRequestStrategy : IRequestStrategy
    {
        /// <summary>
        /// TBD
        /// </summary>
        public readonly int Max;

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="max">TBD</param>
        protected MaxInFlightRequestStrategy(int max)
        {
            Max = max;
        }

        /// <summary>
        /// Concrete subclass must implement this method to define how many
        /// messages that are currently in progress or queued.
        /// </summary>
        public abstract int InFlight { get; }

        /// <summary>
        /// Elements will be requested in minimum batches of this size.
        /// Default is 5. Subclass may override to define the batch size.
        /// </summary>
        public virtual int BatchSize => 5;

        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="remainingRequested">TBD</param>
        /// <returns>TBD</returns>
        public int RequestDemand(int remainingRequested)
        {
            var batch = Math.Min(BatchSize, Max);
            return remainingRequested + InFlight <= (Max - batch)
                ? Math.Max(0, Max - remainingRequested - InFlight)
                : 0;
        }
    }
}


text:
function g = modelOutputGrad(model, X, dim)

% MODELOUTPUTGRAD Compute derivatives with respect to params of model outputs.
% FORMAT
% DESC gives the gradients of the outputs from the model with
% respect to the parameters for a given set of inputs.
% ARG model : the model structure for which gradients are computed.
% ARG X : input locations where gradients are to be computed.
% RETURN g : gradients of the model output with respect to the
% model parameters for the given input locations. The size of the
% returned matrix is of dimension number of data x number of
% parameters x number of model outputs (which maintains
% compatability with NETLAB).
%
% FORMAT
% DESC gives the gradients of the outputs from the model with
% respect to the parameters for a given set of inputs.
% ARG model : the model structure for which gradients are computed.
% ARG X : input locations where gradients are to be comxfputed.
% ARG dim : the dimension of the model for which gradients are required.
% RETURN g : gradients of the model output with respect to the
% model parameters for the given input locations. The size of the
% returned matrix is of dimension number of data x number of
% parameters.
%
% SEEALSO : modelCreate, modelLogLikelihood, modelLogLikeGradients, mlpderiv
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006
%
% MODIFICATIONS : Cark Henrik Ek, 2007

% GPMAT

if(nargin>2)
  fhandle = str2func([model.type 'OutputGrad']);
  g = fhandle(model, X, dim);
else
  fhandle = str2func([model.type 'OutputGrad']);
  gtemp = fhandle(model, X);

  if isfield(model, 'paramGroups')
    g = zeros(size(X, 1), size(model.paramGroups, 2), size(gtemp, 3));
    for i = 1:size(gtemp, 3)
      g = gtemp(:, :, i)*model.paramGroups;
    end
  else
    g = gtemp;
  end
end


text:
layout: post
title: Kochen mit HTML 5
date: 2014-04-04 22:21:57.000000000 +02:00
categories: article
tags:
- Veranstaltungen
- CSS3
- HTML5
- java
status: publish
type: post
published: true
meta:
  _edit_last: '3'
author: uwe
---

Mit Entsetzen habe ich gerade festgestellt, dass schon wieder eine ganze Woche seit dem Vortrag vergangen ist. Inzwischen war Dirk Weil in Hamburg und hat über Java EE7 erzählt. Stefan Saasen (Entwicklungsleiter Atlassian Stash) erläuterte das Ökosystem rund um Atlassians Produktpalette bezüglich git. Es war zumindest nicht langweilig! :-)

 Live Coding....

Doch zurück zum Donnerstag. Es war unser erster Abend bei der Triology GmbH in Braunschweig und ich würde behaupten, wir hatten einen gelungenen Einstieg. Mit wenigen Worten zur Theorie und viel Live-Coding zeigten uns Mark Stein und Michael Seemann, wie man mit verfügbarten Open Source Libs / Tools entwicklen kann.

 Michael Seeman über das UI

Es war auch die Premiere mit gleichzeitiger Nutzung von zwei Beamern und einer getrennten Entwicklung von UI und Backend. Das Ergebnis konnte sich sehen lassen.  Für Speis und Trank war auch gesorgt und ich freue mich schon auf weitere Veranstaltungen vor Ort.

Anbei noch die Links:

HTML 5 Live Cooking (Sourcen)

Podcast innoQ (CSS Frameworks)

Weiterhin findet ihr hier den aktuellen Newsletter des iJUG mit Bericht und Fotos von der JavaLand.  Arno hat bereits die nächsten Termine für hacking@haase bekanntgegeben. Es handelt sich um den:

11.04.2014

09.05.2014

13.06.2014

Bei Interesse einfach bei  ihm melden.  Übrigens werde ich während der Fußball-WM keine Veranstaltung planen. :-)