text:
This chapter will familiarise you with how to use the Apache ActiveMQ Artemis
server.

We'll show where it is, how to start and stop it, and we'll describe the
directory layout and what all the files are and what they do.

For the remainder of this chapter when we talk about the Apache ActiveMQ
Artemis server we mean the Apache ActiveMQ Artemis standalone server, in its
default configuration with a JMS Service enabled.

This document will refer to the full path of the directory where the ActiveMQ
distribution has been extracted to as `${ARTEMIS_HOME}` directory.

## Installation

After downloading the distribution, the following highlights some important
folders on the distribution:

             |___ bin
             |
             |___ examples
             |      |___ common
             |      |___ features
             |      |___ perf
             |      |___ protocols
             |
             |___ lib
             |      |___ client
             |
             |___ schema
             |
             |___ web
                    |___ api
                    |___ hacking-guide
                    |___ migration-guide
                    |___ user-manual

- `bin` - binaries and scripts needed to run ActiveMQ Artemis.

- `examples` - All manner of examples. Please refer to the [examples](examples.md)
  chapter for details on how to run them.

- `lib` - jars and libraries needed to run ActiveMQ Artemis

- `schema` - XML Schemas used to validate ActiveMQ Artemis configuration files

- `web` - The folder where the web context is loaded when the broker runs.

- `api` - The api documentation is placed under the web folder.

- `user-manual` - The user manual is placed under the web folder.

## Creating a Broker Instance

A broker instance is the directory containing all the configuration and runtime
data, such as logs and data files, associated with a broker process.  It is
recommended that you do *not* create the instance directory under
`${ARTEMIS_HOME}`.  This separation is encouraged so that you can more easily
upgrade when the next version of ActiveMQ Artemis is released.

On Unix systems, it is a common convention to store this kind of runtime data
under the `/var/lib` directory.  For example, to create an instance at
'/var/lib/mybroker', run the following commands in your command line shell:

```sh
cd /var/lib
${ARTEMIS_HOME}/bin/artemis create mybroker
```

A broker instance directory will contain the following sub directories:

- `bin`: holds execution scripts associated with this instance.
- `etc`: hold the instance configuration files
- `data`: holds the data files used for storing persistent messages
- `log`: holds rotating log files
- `tmp`: holds temporary files that are safe to delete between broker runs

At this point you may want to adjust the default configuration located in the
`etc` directory.

### Options

There are several options you can use when creating an instance.

For a full list of updated properties always use:

```
 $./artemis help create
 NAME
         artemis create - creates a new broker instance

 SYNOPSIS
        artemis create [--addresses <addresses>] [--aio] [--allow-anonymous]
                [--autocreate] [--blocking] [--cluster-password <clusterPassword>]
                [--cluster-user <clusterUser>] [--clustered] [--data <data>]
                [--default-port <defaultPort>] [--disable-persistence]
                [--encoding <encoding>] [--etc <etc>] [--failover-on-shutdown] [--force]
                [--global-max-size <globalMaxSize>] [--home <home>] [--host <host>]
                [--http-host <httpHost>] [--http-port <httpPort>]
                [--java-options <javaOptions>] [--mapped] [--max-hops <maxHops>]
                [--message-load-balancing <messageLoadBalancing>] [--name <name>]
                [--nio] [--no-amqp-acceptor] [--no-autocreate] [--no-autotune]
                [--no-fsync] [--no-hornetq-acceptor] [--no-mqtt-acceptor]
                [--no-stomp-acceptor] [--no-web] [--paging] [--password <password>]
                [--ping <ping>] [--port-offset <portOffset>] [--queues <queues>]
                [--replicated] [--require-login] [--role <role>] [--shared-store]
                [--silent] [--slave] [--ssl-key <sslKey>]
                [--ssl-key-password <sslKeyPassword>] [--ssl-trust <sslTrust>]
                [--ssl-trust-password <sslTrustPassword>] [--use-client-auth]
                [--user <user>] [--verbose] [--] <directory>

 OPTIONS
         --addresses <addresses>
             Comma separated list of addresses

         --aio
             Sets the journal as asyncio.

         --allow-anonymous
             Enables anonymous configuration on security, opposite of
             --require-login (Default: input)

         --autocreate
             Auto create addresses. (default: true)

         --blocking
             Block producers when address becomes full, opposite of --paging
             (Default: false)

         --cluster-password <clusterPassword>
             The cluster password to use for clustering. (Default: input)

         --cluster-user <clusterUser>
             The cluster user to use for clustering. (Default: input)

         --clustered
             Enable clustering

         --data <data>
             Directory where ActiveMQ data are stored. Paths can be absolute or
             relative to artemis.instance directory ('data' by default)

         --default-port <defaultPort>
             The port number to use for the main 'artemis' acceptor (Default:
             61616)

         --disable-persistence
             Disable message persistence to the journal

         --encoding <encoding>
             The encoding that text files should use

         --etc <etc>
             Directory where ActiveMQ configuration is located. Paths can be absolute or
             relative to artemis.instance directory ('etc' by default)

         --failover-on-shutdown
             Valid for shared store: will shutdown trigger a failover? (Default:
             false)

         --force
             Overwrite configuration at destination directory

         --global-max-size <globalMaxSize>
             Maximum amount of memory which message data may consume (Default:
             Undefined, half of the system's memory)

         --home <home>
             Directory where ActiveMQ Artemis is installed

         --host <host>
             The host name of the broker (Default: 0.0.0.0 or input if clustered)

         --http-host <httpHost>
             The host name to use for embedded web server (Default: localhost)

         --http-port <httpPort>
             The port number to use for embedded web server (Default: 8161)

         --java-options <javaOptions>
             Extra java options to be passed to the profile

         --mapped
             Sets the journal as mapped.

         --max-hops <maxHops>
             Number of hops on the cluster configuration

         --message-load-balancing <messageLoadBalancing>
             Load balancing policy on cluster. [ON_DEMAND (default) | STRICT |
             OFF]

         --name <name>
             The name of the broker (Default: same as host)

         --nio
             Sets the journal as nio.

         --no-amqp-acceptor
             Disable the AMQP specific acceptor.

         --no-autocreate
             Disable Auto create addresses.

         --no-autotune
             Disable auto tuning on the journal.

         --no-fsync
             Disable usage of fdatasync (channel.force(false) from java nio) on
             the journal

         --no-hornetq-acceptor
             Disable the HornetQ specific acceptor.

         --no-mqtt-acceptor
             Disable the MQTT specific acceptor.

         --no-stomp-acceptor
             Disable the STOMP specific acceptor.

         --no-web
             Remove the web-server definition from bootstrap.xml

         --paging
             Page messages to disk when address becomes full, opposite of
             --blocking (Default: true)

         --password <password>
             The user's password (Default: input)

         --ping <ping>
             A comma separated string to be passed on to the broker config as
             network-check-list. The broker will shutdown when all these
             addresses are unreachable.

         --port-offset <portOffset>
             Off sets the ports of every acceptor

         --queues <queues>
             Comma separated list of queues.

         --replicated
             Enable broker replication

         --require-login
             This will configure security to require user / password, opposite of
             --allow-anonymous

         --role <role>
             The name for the role created (Default: amq)

         --shared-store
             Enable broker shared store

         --silent
             It will disable all the inputs, and it would make a best guess for
             any required input

         --slave
             Valid for shared store or replication: this is a slave server?

         --ssl-key <sslKey>
             The key store path for embedded web server

         --ssl-key-password <sslKeyPassword>
             The key store password

         --ssl-trust <sslTrust>
             The trust store path in case of client authentication

         --ssl-trust-password <sslTrustPassword>
             The trust store password

         --use-client-auth
             If the embedded server requires client authentication

         --user <user>
             The username (Default: input)

         --verbose
             Adds more information on the execution

         --
             This option can be used to separate command-line options from the
             list of argument, (useful when arguments might be mistaken for
             command-line options

         <directory>
             The instance directory to hold the broker's configuration and data.
             Path must be writable.
```

Some of these properties may be mandatory in certain configurations and the
system may ask you for additional input.

```
./artemis create /usr/server
Creating ActiveMQ Artemis instance at: /user/server

--user: is a mandatory property!
Please provide the default username:
admin

--password: is mandatory with this configuration:
Please provide the default password:

--allow-anonymous | --require-login: is a mandatory property!
Allow anonymous access?, valid values are Y,N,True,False
y

Auto tuning journal ...
done! Your system can make 0.34 writes per millisecond, your journal-buffer-timeout will be 2956000

You can now start the broker by executing:

   "/user/server/bin/artemis" run

Or you can run the broker in the background using:

   "/user/server/bin/artemis-service" start
```

## Starting and Stopping a Broker Instance

Assuming you created the broker instance under `/var/lib/mybroker` all you need
to do start running the broker instance is execute:

```sh
/var/lib/mybroker/bin/artemis run
```

Now that the broker is running, you can optionally run some of the included
examples to verify the the broker is running properly.

To stop the Apache ActiveMQ Artemis instance you will use the same `artemis`
script, but with the `stop` argument.  Example:

```sh
/var/lib/mybroker/bin/artemis stop
```

Please note that Apache ActiveMQ Artemis requires a Java 7 or later runtime to
run.

By default the `etc/bootstrap.xml` configuration is used. The configuration can
be changed e.g. by running `./artemis run -- xml:path/to/bootstrap.xml` or
another config of your choosing.

Environment variables are used to provide ease of changing ports, hosts and
data directories used and can be found in `etc/artemis.profile` on linux and
`etc\artemis.profile.cmd` on Windows.

## Server JVM settings

The run scripts set some JVM settings for tuning the garbage collection policy
and heap size. We recommend using a parallel garbage collection algorithm to
smooth out latency and minimise large GC pauses.

By default Apache ActiveMQ Artemis runs in a maximum of 1GiB of RAM. To
increase the memory settings change the `-Xms` and `-Xmx` memory settings as
you would for any Java program.

If you wish to add any more JVM arguments or tune the existing ones, the run
scripts are the place to do it.

## Library Path

If you're using the [Asynchronous IO Journal](libaio.md) on Linux, you need to
specify `java.library.path` as a property on your Java options. This is done
automatically in the scripts.

If you don't specify `java.library.path` at your Java options then the JVM will
use the environment variable `LD_LIBRARY_PATH`.

You will need to make sure libaio is installed on Linux. For more information
refer to the [libaio chapter](libaio.html#runtime-dependencies).

## System properties

Apache ActiveMQ Artemis can take a system property on the command line for
configuring logging.

For more information on configuring logging, please see the section on
[Logging](logging.md).

## Configuration files

The configuration file used to bootstrap the server (e.g.  `bootstrap.xml` by
default) references the specific broker configuration files.

- `broker.xml`. This is the main ActiveMQ configuration file. All the
  parameters in this file are described [here](configuration-index.md)

It is also possible to use system property substitution in all the
configuration files. by replacing a value with the name of a system property.
Here is an example of this with a connector configuration:

```xml
<connector name="netty">tcp://${activemq.remoting.netty.host:localhost}:${activemq.remoting.netty.port:61616}</connector>
```

Here you can see we have replaced 2 values with system properties
`activemq.remoting.netty.host` and `activemq.remoting.netty.port`. These values
will be replaced by the value found in the system property if there is one, if
not they default back to localhost or 61616 respectively. It is also possible
to not supply a default. i.e.  `${activemq.remoting.netty.host}`, however the
system property *must* be supplied in that case.

### Bootstrap configuration file

The stand-alone server is basically a set of POJOs which are instantiated by
Airline commands.

The bootstrap file is very simple. Let's take a look at an example:

```xml
<broker xmlns="http://activemq.org/schema">

   <jaas-security domain="activemq"/>

   <server configuration="file:/path/to/broker.xml"/>

   <web bind="http://localhost:8161" path="web">
       <app url="activemq-branding" war="activemq-branding.war"/>
       <app url="artemis-plugin" war="artemis-plugin.war"/>
       <app url="console" war="console.war"/>
   </web>
</broker>
```

- `server` - Instantiates a core server using the configuration file from the
  `configuration` attribute. This is the main broker POJO necessary to do all
   the real messaging work.

- `jaas-security` - Configures JAAS-based security for the server. The
  `domain` attribute refers to the relevant login module entry in
  `login.config`. If different behavior is needed then a custom security
  manager can be configured by replacing `jaas-security` with
  `security-manager`. See the "Custom Security Manager" section in the
  [security chapter](security.md) for more details.

- `web` - Configures an embedded Jetty instance to serve web applications like
  the admin console.

### Broker configuration file

The configuration for the Apache ActiveMQ Artemis core server is contained in
`broker.xml`. This is what the FileConfiguration bean uses to configure the
messaging server.

There are many attributes which you can configure Apache ActiveMQ Artemis. In
most cases the defaults will do fine, in fact every attribute can be defaulted
which means a file with a single empty `configuration` element is a valid
configuration file. The different configuration will be explained throughout
the manual or you can refer to the configuration reference
[here](configuration-index.md).

## Windows Server

On windows you will have the option to run ActiveMQ Artemis as a service.  Just
use the following command to install it:

```
 $ ./artemis-service.exe install
```

The create process should give you a hint of the available commands available
for the artemis-service.exe

## Adding Bootstrap Dependencies

Bootstrap dependencies like logging handlers must be accessible by the log
manager at boot time. Package the dependency in a jar and put it on the boot
classpath before of log manager jar. This can be done appending the jar at the
variable `JAVA_ARGS`, defined in `artemis.profile`, with the option `-Xbootclasspath/a`.

## Adding Runtime Dependencies

Runtime dependencies like diverts, transformers, broker plugins, JDBC drivers,
password decoders, etc. must be accessible by the broker at runtime. Package
the dependency in a jar, and put it on the broker's classpath. This can be done
by placing the jar file in the `lib` directory of the broker distribution
itself or in the `lib` directory of the broker instance. A broker instance does
not have a `lib` directory by default so it may need to be created.  It should
be on the "top" level with the `bin`, `data`, `log`, etc. directories.


text:
package ru.job4j.count;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

/**
 * Тестирование класса-счетчика
 */
public class CountTest extends Thread {

    /**
     * Класс описывает нить со счетчиком.
     */
    private class ThreadCount extends Thread {
        private final Count count;

        private ThreadCount(final Count count) {
            this.count = count;
        }

        @Override
        public void run() {
            this.count.increment();
        }
    }

    /**
     * Два потока поочередно вызывают инкремент,
     * результат должен увеличиться на 2.
     */
    @Test
    public void whenExecute2ThreadThen2() throws InterruptedException {
        //Создаем счетчик.
        final Count count = new Count();
        //Создаем нити.
        Thread first = new ThreadCount(count);
        Thread second = new ThreadCount(count);
        //Запускаем нити.
        first.start();
        second.start();
        //Заставляем главную нить дождаться выполнения наших нитей.
        first.join();
        second.join();
        //Проверяем результат.
        assertThat(count.get(), is(2));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.olat.modules.fo.restapi;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.olat.modules.fo.Forum;
import org.olat.modules.fo.ForumManager;
import org.olat.modules.fo.Message;

/**
 * Description:

 * Web service to manage forum element. This implementation is only for import.
 *

 * Initial Date: 20 apr. 2010

 *
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class ForumWebService {

	private final Forum forum;

	public ForumWebService(final Forum forum) {
		this.forum = forum;
	}

	/**
	 * Retrieves the threads in the forum
	 *
	 * @response.representation.200.qname {http://www.example.com}messageVOes
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The root message of the thread
	 * @response.representation.200.example {@link org.olat.modules.fo.restapi.Examples#SAMPLE_MESSAGEVOes}
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The author, forum or message not found
	 * @param forumKey The id of the forum
	 * @return The list of threads
	 */
	@GET
	@Path("threads")
	public Response getThreads() {
		if (forum == null) { return Response.serverError().status(Status.NOT_FOUND).build(); }

		final ForumManager fom = ForumManager.getInstance();
		final List<Message> messages = fom.getMessagesByForum(forum);
		final List<MessageVO> threads = new ArrayList<MessageVO>();
		for (final Message message : messages) {
			if (message.getParent() == null) {
				threads.add(new MessageVO(message));
			}
		}

		final MessageVO[] threadArr = new MessageVO[threads.size()];
		threads.toArray(threadArr);
		return Response.ok(threads).build();
	}

	/**
	 * Retrieves the messages in the thread
	 *
	 * @response.representation.200.qname {http://www.example.com}messageVOes
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The root message of the thread
	 * @response.representation.200.example {@link org.olat.modules.fo.restapi.Examples#SAMPLE_MESSAGEVOes}
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The author, forum or message not found
	 * @param threadKey The key of the thread
	 * @return The messages of the thread
	 */
	@GET
	@Path("posts/{threadKey}")
	public Response getMessages(@PathParam("threadKey") final Long threadKey) {
		if (forum == null) { return Response.serverError().status(Status.NOT_FOUND).build(); }

		final ForumManager fom = ForumManager.getInstance();
		final List<Message> messages = fom.getThread(threadKey);
		final MessageVO[] messageArr = new MessageVO[messages.size()];
		int i = 0;
		for (final Message message : messages) {
			messageArr[i++] = new MessageVO(message);
		}
		return Response.ok(messageArr).build();
	}
}


text:
title: Miesto
image_align: left
---

## Miesto
### Prednášky: **Pisztoryho palác Bratislava**


text:
/**
 * @file mali_osk_memory.c
 * Implementation of the OS abstraction layer for the kernel device driver
 */

#include "mali_osk.h"
#include <linux/slab.h>
#include <linux/vmalloc.h>

void inline *_mali_osk_calloc(u32 n, u32 size)
{
	return kcalloc(n, size, GFP_KERNEL);
}

void inline *_mali_osk_malloc(u32 size)
{
	return kmalloc(size, GFP_KERNEL);
}

void inline _mali_osk_free(void *ptr)
{
	kfree(ptr);
}

void inline *_mali_osk_valloc(u32 size)
{
	return vmalloc(size);
}

void inline _mali_osk_vfree(void *ptr)
{
	vfree(ptr);
}

void inline *_mali_osk_memcpy(void *dst, const void *src, u32  len)
{
	return memcpy(dst, src, len);
}

void inline *_mali_osk_memset(void *s, u32 c, u32 n)
{
	return memset(s, c, n);
}

mali_bool _mali_osk_mem_check_allocated(u32 max_allocated)
{
	/* No need to prevent an out-of-memory dialogue appearing on Linux,
	 * so we always return MALI_TRUE.
	 */
	return MALI_TRUE;
}


text:
package com.bitdubai.fermat_cbp_api.layer.cbp_business_transaction.cash_money_stock_replenishment.exceptions;

import com.bitdubai.fermat_api.FermatException;

/**
 * Created by Yordin Alayn on 24.09.15.
 */

public class CantUpdateStatusCashMoneyStockReplenishmentException extends FermatException {

    public static final String DEFAULT_MESSAGE = "Falled To Update the Status the Business Transaction Cash Money Stock Replenishment.";
    public CantUpdateStatusCashMoneyStockReplenishmentException(String message, Exception cause, String context, String possibleReason) {
        super(message, cause, context, possibleReason);
    }
}


text:
---
layout: page
title: "About"
description: "This is YaoYao"
header-img: "img/about-bg.jpg"
---

<select class="sel-lang" onchange= "onLanChange(this.options[this.options.selectedIndex].value)">
    <option value="0" selected> 中文 Chinese </option>
    <option value="1"> 英文 English </option>
</select>

Hi,我是刘要,华东师范大学软件学院 机器人运动与视觉实验室的学生。我的研究方向是基于视觉导航的四旋翼飞行器。更多我的项目及论文可以查看我的作品集。

联系方式:mearshen [at] gmail DOT com

Hi, I am Yao Liu, a graduate student at  Robot motion & vision Lab ,East China Normal University. And I major in vision-based quadrotor. For more about my publications and projects, please visit my Portfolio.

contact me: mearshen [at] gmail DOT com

Please enable JavaScript to view the comments powered by Disqus.

{% if site.duoshuo_username %}

{% endif %}

{% if site.disqus_username %}

{% endif %}


text:
<?php
class Controller_User_Checkout extends Controller_Base
{
	public $template = 'user/template';
	public function action_index()
	{
		$data['user'] = Model_User::find($this->current_user->id);
		$this->template->title = "Checkout";
		$this->template->content = View::forge('user/checkout/index', $data);

	}
	public function action_order()
	{
		$data['order'] = Model_Checkout::find('all');
		$this->template->title = "Checkout";
		$this->template->content = View::forge('user/checkout/order', $data);
	}

	public function action_view($id = null)
	{
		is_null($id) and Response::redirect('checkout');

		if ( ! $data['checkout'] = Model_Checkout::find($id))
		{
			Session::set_flash('error', 'Could not find checkout #'.$id);
			Response::redirect('checkout');
		}

		$this->template->title = "Checkout";
		$this->template->content = View::forge('checkout/view', $data);

	}

	public function action_create()
	{
		if (Input::method() == 'POST')
		{
			$result['count'] = 0;
			$result['cart'] = Session::get('cart');
			$user = Model_User::find($this->current_user->id);
			if(is_null($result['cart'])){
				$result['count'] = 0;
				Session::set_flash('error', 'Your cart is being null.Please choose product!');
				Response::redirect('cart');
			}
			else{
				foreach ($result['cart'] as $key=>$value) {
					$checkout = Model_Checkout::forge(array(
						'user_id' =>$this->current_user->id,
						'product' => $value['tensanpham'],
						'quantity' => $value['quantity'],
						'price' => $value['price'],
						'username' => $user['username'],
						'address' => Input::post('address'),
						'phone' => Input::post('phone'),
						'email' => Input::post('email'),
						'datereceive' => Input::post('datereceive'),
						'description' => Input::post('description'),
						'status' => false,
						));
					if ($checkout and $checkout->save())
					{
						$result['count']++;
					}
					else
					{
						Session::set_flash('error', 'Could not save checkout.');
						Response::redirect('user/checkout');
					}
				}
			}
			Session::set_flash('success', 'Your had order!');
			Session::delete('cart');
			Response::redirect('user/order');
		}
	}

	public function action_edit($id = null)
	{
		is_null($id) and Response::redirect('checkout');

		if ( ! $checkout = Model_Checkout::find($id))
		{
			Session::set_flash('error', 'Could not find checkout #'.$id);
			Response::redirect('checkout');
		}

		$val = Model_Checkout::validate('edit');

		if ($val->run())
		{
			$checkout->username = Input::post('username');
			$checkout->product = Input::post('product');
			$checkout->quantity = Input::post('quantity');
			$checkout->price = Input::post('price');
			$checkout->status = Input::post('status');

			if ($checkout->save())
			{
				Session::set_flash('success', 'Updated checkout #' . $id);

				Response::redirect('checkout');
			}
			else
			{
				Session::set_flash('error', 'Could not update checkout #' . $id);
			}
		}
		else
		{
			if (Input::method() == 'POST')
			{
				$checkout->username = $val->validated('username');
				$checkout->product = $val->validated('product');
				$checkout->quantity = $val->validated('quantity');
				$checkout->price = $val->validated('price');
				$checkout->status = $val->validated('status');

				Session::set_flash('error', $val->error());
			}

			$this->template->set_global('checkout', $checkout, false);
		}

		$this->template->title = "Checkouts";
		$this->template->content = View::forge('checkout/edit');

	}

	public function action_delete($id = null)
	{
		is_null($id) and Response::redirect('user/checkout');
		if ($checkout = Model_Checkout::find($id))
		{
			$checkout->delete();
			Session::set_flash('success', 'Deleted checkout #'.$id);
		}
		else
		{
			Session::set_flash('error', 'Could not delete checkout #'.$id);
		}

		Response::redirect('user/order');

	}

}


text:
using Mapsui.Extensions;
using Mapsui.Rendering.Skia.SkiaWidgets;
using Mapsui.UI;
using Mapsui.Utilities;
using Mapsui.Widgets;
using Mapsui.Widgets.PerformanceWidget;
using SkiaSharp;

namespace Mapsui.Samples.Common.Maps
{
    public class PerformanceWidgetSample : IMapControlSample
    {
        private IMapControl? _mapControl;
        private readonly Performance _performance = new Performance(10);

        public string Name => "4 Performance Widget";

        public string Category => "Widgets";

        public void OnClick(object? sender, WidgetTouchedEventArgs args)
        {
            _mapControl?.Performance?.Clear();
            _mapControl?.RefreshGraphics();

            args.Handled = true;
        }

        public void Setup(IMapControl mapControl)
        {
            _mapControl = mapControl;

            //I like bing Hybrid
            mapControl.Map = BingSample.CreateMap(BingHybrid.DefaultCache, BruTile.Predefined.KnownTileSource.BingHybrid);

            var widget = new PerformanceWidget(_performance);

            widget.WidgetTouched += OnClick;

            mapControl.Map.Widgets.Add(widget);
            mapControl.Performance = _performance;
            mapControl.Renderer.WidgetRenders[typeof(PerformanceWidget)] = new PerformanceWidgetRenderer(10, 10, 12, SKColors.Black, SKColors.White);
        }
    }
}


text:
package br.com.wfcreations.annms.core.sqlann.statements;

import br.com.wfcreations.annms.core.exception.ANNMSRequestExecutionException;
import br.com.wfcreations.annms.core.exception.ANNMSRequestValidationException;
import br.com.wfcreations.annms.core.sqlann.SQLANNStatement;
import br.com.wfcreations.annms.core.transport.message.ResultMessage;
import br.com.wfcreations.annms.core.transport.message.ShowStatusResultMessage;

public class ShowStatusStatement implements SQLANNStatement {

	public final String query;

	public ShowStatusStatement(String query) {
		this.query = query;
	}

	@Override
	public void checkAccess() {
	}

	@Override
	public void validate() throws ANNMSRequestValidationException {
	}

	@Override
	public ResultMessage execute() throws ANNMSRequestExecutionException {
		return new ShowStatusResultMessage();
	}
}


text:
package com.xjeffrose.xio.server;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class XioResponseClassifier extends ChannelDuplexHandler {

  private boolean noOp;

  public XioResponseClassifier(boolean noOp) {
    this.noOp = noOp;
  }

  @Override
  @SuppressWarnings("deprecated")
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    log.error("Exception Caught in XioResponseClassifier: ", cause);
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    if (noOp) {
      ctx.pipeline().remove(this);
      ctx.fireChannelActive();
    }

  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelInactive();
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ctx.fireChannelRead(msg);
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelReadComplete();
  }
}


text:
package net.ernstsson.sqlbuilder;

import org.junit.Test;

import static java.lang.String.format;
import static net.ernstsson.sqlbuilder.InLocator.IN;
import static net.ernstsson.sqlbuilder.InLocator.in;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

public final class InLocatorTest {
    private static final Integer VALUE_ONE = 1;
    private static final Integer VALUE_TWO = 3;
    private static final Integer VALUE_THREE = 5;
    private static final String SHOULD_GENERATE_SQL_FOR_BETWEEN_FORMATTER = "%s ('%s', '%s', '%s')";
    private static final String EXPECTED_SHOULD_GENERATE_SQL_FOR_BETWEEN_SQL = format(
            SHOULD_GENERATE_SQL_FOR_BETWEEN_FORMATTER, IN, VALUE_ONE, VALUE_TWO, VALUE_THREE);

    @Test
    public void shouldGenerateSqlForThreeValues() {
        assertThat(in(VALUE_ONE, VALUE_TWO, VALUE_THREE).toSql(), is(EXPECTED_SHOULD_GENERATE_SQL_FOR_BETWEEN_SQL));
    }

    @Test(expected = AssertionError.class)
    public void shouldThrowExceptionNoValues() {
        in();
    }

    @Test
    public void shouldHaveHashCode() {
        assertThat(in(VALUE_ONE, VALUE_TWO, VALUE_THREE).hashCode(), notNullValue());
    }

    @Test
    public void shouldHaveEquals() {
        final LocatorStatement in = in(VALUE_ONE, VALUE_TWO, VALUE_THREE);
        assertThat(in.equals(in), is(true));
    }

    @Test
    public void shouldHaveToString() {
        assertThat(in(VALUE_ONE, VALUE_TWO).toString(), notNullValue());
    }
}


text:
from AppKit import NSScroller, NSColor, NSAttributedString, NSMenuItem, NSShadowAttributeName, NSShadow, \
    NSForegroundColorAttributeName, NSFont, NSFontAttributeName, NSSmallControlSize, NSView
import vanilla

class OpenTypeControlsView(vanilla.ScrollView):

    def __init__(self, posSize, callback):
        self._callback = callback
        # put the controls group into a flipped group.
        # this will give better scroll behavior.
        width = posSize[2] - NSScroller.scrollerWidth() - 2
        view = DefconAppKitTopAnchoredNSView.alloc().init()
        view.setFrame_(((0, 0), (width, 0)))
        # call the super
        super(OpenTypeControlsView, self).__init__(posSize, view, hasHorizontalScroller=False, drawsBackground=False)
        # build the view for the controls
        self._controlGroup = vanilla.Group((0, 0, width, 0))
        view.addSubview_(self._controlGroup.getNSView())
        # build the static controls
        top = 10
        # mode
        self._controlGroup.modeTitle = vanilla.TextBox((10, top, -10, 14),
            NSAttributedString.alloc().initWithString_attributes_("DISPLAY MODE", titleControlAttributes), sizeStyle="small")
        top += 20
        self._controlGroup.modeRadioGroup = vanilla.RadioGroup((10, top, -10, 38),
            ["Glyph Preview", "Glyph Records"], callback=self._controlEditCallback)
        self._controlGroup.modeRadioGroup.set(0)
        top += 48
        self._controlGroup.line1 = vanilla.HorizontalLine((10, top, -10, 1))
        top += 11
        # case
        self._controlGroup.caseTitle = vanilla.TextBox((10, top, -10, 14),
            NSAttributedString.alloc().initWithString_attributes_("CASE CONVERSION", titleControlAttributes), sizeStyle="small")
        top += 20
        self._controlGroup.caseRadioGroup = vanilla.RadioGroup((10, top, -10, 58),
            ["Unchanged", "Uppercase", "Lowercase"], callback=self._controlEditCallback)
        self._controlGroup.caseRadioGroup.set(0)
        top += 68
        # language, script and direction
        self._controlGroup.scriptTitle = vanilla.TextBox((10, top, -10, 14),
            NSAttributedString.alloc().initWithString_attributes_("SCRIPT & LANGUAGE", titleControlAttributes), sizeStyle="small")
        top += 20
        self._controlGroup.scriptPopUpButton = vanilla.PopUpButton((10, top, -10, 20), [], callback=self._controlEditCallback)
        top += 25
        self._controlGroup.languagePopUpButton = vanilla.PopUpButton((10, top, -10, 20), [], callback=self._controlEditCallback)
        top += 35
        self._controlGroup.directionTitle = vanilla.TextBox((10, top, -10, 14),
            NSAttributedString.alloc().initWithString_attributes_("WRITING DIRECTION", titleControlAttributes), sizeStyle="small")
        top += 20
        self._controlGroup.directionRadioGroup = vanilla.RadioGroup((10, top, -10, 38),
            ["Left to Right", "Right to Left"], callback=self._controlEditCallback)
        self._controlGroup.directionRadioGroup.set(0)
        top += 48
        # GSUB and GPOS
        self._controlGroup.line2 = vanilla.HorizontalLine((10, top, -10, 1))
        top += 11
        # set document view height
        (x, y), (w, h) = self._nsObject.documentView().frame()
        self._nsObject.documentView().setFrame_(((x, y), (w, top)))
        x, y, w, h = self._controlGroup.getPosSize()
        self._controlGroup.setPosSize((x, y, w, top))
        # storage
        self._dynamicTop = top
        self._gsubAttributes = {}
        self._gposAttributes = {}
        self._featureNames = {}

    def _breakCycles(self):
        self._callback = None
        super(OpenTypeControlsView, self)._breakCycles()

    def _controlEditCallback(self, sender):
        self._callback(self)

    def setFont(self, font):
        # script list
        if font is None:
            scriptList = []
        else:
            scriptList = ["DFLT"] + font.getScriptList()
        unsupportedScripts = [i for i in scriptTags if i not in scriptList]
        if unsupportedScripts:
            scriptList.append(NSMenuItem.separatorItem())
            scriptList += unsupportedScripts
        self._controlGroup.scriptPopUpButton.setItems(scriptList)
        # language list
        if font is None:
            languageList = []
        else:
            languageList = ["Default"] + font.getLanguageList()
        unsupportedLanguages = [i for i in languageTags if i not in languageList]
        if unsupportedLanguages:
            languageList.append(NSMenuItem.separatorItem())
            languageList += unsupportedLanguages
        self._controlGroup.languagePopUpButton.setItems(languageList)
        # teardown existing controls
        for attr in self._gsubAttributes:
            delattr(self._controlGroup, attr)
        for attr in self._gposAttributes:
            delattr(self._controlGroup, attr)
        for attr in self._featureNames:
            delattr(self._controlGroup, attr)
        if hasattr(self._controlGroup, "gposTitle"):
            del self._controlGroup.gposTitle
        if hasattr(self._controlGroup, "gsubTitle"):
            del self._controlGroup.gsubTitle
        # stylistic set names
        if hasattr(font, "stylisticSetNames"):
            stylisticSetNames = font.stylisticSetNames
        else:
            stylisticSetNames = {}
        # GSUB
        top = self._dynamicTop
        if font is None:
            gsub = None
        else:
            gsub = font.gsub
        if gsub is None:
            gsubFeatureList = []
        else:
            gsubFeatureList = gsub.getFeatureList()
        self._gsubAttributes = {}
        self._featureNames = {}
        if gsubFeatureList:
            self._controlGroup.gsubTitle = vanilla.TextBox((10, top, -10, 14),
                NSAttributedString.alloc().initWithString_attributes_("GSUB", titleControlAttributes), sizeStyle="small")
            top += 20
            for tag in gsubFeatureList:
                state = font.gsub.getFeatureState(tag)
                attr = "gsubCheckBox_%s" % tag
                obj = vanilla.CheckBox((10, top, -10, 22), tag, value=state, callback=self._controlEditCallback)
                setattr(self._controlGroup, attr, obj)
                self._gsubAttributes[attr] = tag
                top += 20
                # stylistic set name
                if tag in stylisticSetNames:
                    attr = "ssName_%s" % tag
                    setName = stylisticSetNames[tag]
                    if hasattr(self._controlGroup, attr):
                        obj = getattr(self._controlGroup, attr)
                        obj.set(setName)
                    else:
                        obj = vanilla.TextBox((26, top, -10, 13), setName, sizeStyle="mini")
                        setattr(self._controlGroup, attr, obj)
                    self._featureNames[attr] = setName
                    top += 13
            top += 10
        # GPOS
        if font is None:
            gpos = None
        else:
            gpos = font.gpos
        if gpos is None:
            gposFeatureList = []
        else:
            gposFeatureList = gpos.getFeatureList()
        self._gposAttributes = {}
        if gposFeatureList:
            self._controlGroup.gposTitle = vanilla.TextBox((10, top, -10, 14),
                NSAttributedString.alloc().initWithString_attributes_("GPOS", titleControlAttributes), sizeStyle="small")
            top += 20
            for tag in gposFeatureList:
                state = font.gpos.getFeatureState(tag)
                attr = "gposCheckBox_%s" % tag
                obj = vanilla.CheckBox((10, top, -10, 22), tag, value=state, callback=self._controlEditCallback)
                setattr(self._controlGroup, attr, obj)
                self._gposAttributes[attr] = tag
                top += 20
            top += 10
        # set the view size
        (x, y), (w, h) = self._nsObject.documentView().frame()
        self._nsObject.documentView().setFrame_(((x, y), (w, top)))
        x, y, w, h = self._controlGroup.getPosSize()
        self._controlGroup.setPosSize((x, y, w, top))

    def get(self):
        mode = ["preview", "records"][self._controlGroup.modeRadioGroup.get()]
        caseConversion = ["unchanged", "upper", "lower"][self._controlGroup.caseRadioGroup.get()]
        script = self._controlGroup.scriptPopUpButton.getItems()
        if script:
            script = script[self._controlGroup.scriptPopUpButton.get()]
        else:
            script = None
        language = self._controlGroup.languagePopUpButton.getItems()
        if language:
            language = language[self._controlGroup.languagePopUpButton.get()]
        else:
            language = None
        if language == "Default":
            language = None
        gsubStates = {}
        for attr, tag in self._gsubAttributes.items():
            gsubStates[tag] = getattr(self._controlGroup, attr).get()
        gposStates = {}
        for attr, tag in self._gposAttributes.items():
            gposStates[tag] = getattr(self._controlGroup, attr).get()
        rightToLeft = self._controlGroup.directionRadioGroup.get()
        status = dict(
            mode=mode,
            case=caseConversion,
            script=script,
            language=language,
            gsub=gsubStates,
            gpos=gposStates,
            rightToLeft=rightToLeft
        )
        return status

# --------------------
# Misc. Internal Stuff
# --------------------

class DefconAppKitTopAnchoredNSView(NSView):

    def isFlipped(self):
        return True

# title attributes
shadow = NSShadow.alloc().init()
shadow.setShadowColor_(NSColor.colorWithCalibratedWhite_alpha_(1, 1))
shadow.setShadowBlurRadius_(1.0)
shadow.setShadowOffset_((1.0, -1.0))
titleControlAttributes = {
    NSForegroundColorAttributeName: NSColor.colorWithCalibratedWhite_alpha_(.4, 1),
    NSShadowAttributeName: shadow,
    NSFontAttributeName: NSFont.boldSystemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSSmallControlSize))
}

# all script and language tags
_scriptTags = """arab
armn
beng
bopo
brai
byzm
cans
cher
hani
cyrl
DFLT
deva
ethi
geor
grek
gujr
guru
jamo
hang
hebr
kana
knda
khmr
lao
latn
mlym
mong
mymr
ogam
orya
runr
sinh
syrc
taml
telu
thaa
thai
tibt
yi""".splitlines()

scriptTags = []
for i in _scriptTags:
    if len(i) < 4:
        i += " " * (4 - len(i))
    scriptTags.append(i)

_languageTags = """Default
ABA
ABK
ADY
AFK
AFR
AGW
ALT
AMH
ARA
ARI
ARK
ASM
ATH
AVR
AWA
AYM
AZE
BAD
BAG
BAL
BAU
BBR
BCH
BCR
BEL
BEM
BEN
BGR
BHI
BHO
BIK
BIL
BKF
BLI
BLN
BLT
BMB
BML
BRE
BRH
BRI
BRM
BSH
BTI
CAT
CEB
CHE
CHG
CHH
CHI
CHK
CHP
CHR
CHU
CMR
COP
CRE
CRR
CRT
CSL
CSY
DAN
DAR
DCR
DEU
DGR
DHV
DJR
DNG
DNK
DUN
DZN
EBI
ECR
EDO
EFI
ELL
ENG
ERZ
ESP
ETI
EUQ
EVK
EVN
EWE
FAN
FAR
FIN
FJI
FLE
FNE
FON
FOS
FRA
FRI
FRL
FTA
FUL
GAD
GAE
GAG
GAL
GAR
GAW
GEZ
GIL
GMZ
GON
GRN
GRO
GUA
GUJ
HAI
HAL
HAR
HAU
HAW
HBN
HIL
HIN
HMA
HND
HO
HRI
HRV
HUN
HYE
IBO
IJO
ILO
IND
ING
INU
IRI
IRT
ISL
ISM
ITA
IWR
JAV
JII
JAN
JUD
JUL
KAB
KAC
KAL
KAN
KAR
KAT
KAZ
KEB
KGE
KHA
KHK
KHM
KHS
KHV
KHW
KIK
KIR
KIS
KKN
KLM
KMB
KMN
KMO
KMS
KNR
KOD
KOK
KON
KOP
KOR
KOZ
KPL
KRI
KRK
KRL
KRM
KRN
KRT
KSH
KSI
KSM
KUI
KUL
KUM
KUR
KUU
KUY
KYK
LAD
LAH
LAK
LAM
LAO
LAT
LAZ
LCR
LDK
LEZ
LIN
LMA
LMB
LMW
LSB
LSM
LTH
LUB
LUG
LUH
LUO
LVI
MAJ
MAK
MAL
MAN
MAR
MAW
MBN
MCH
MCR
MDE
MEN
MIZ
MKD
MLE
MLG
MLN
MLR
MLY
MND
MNG
MNI
MNK
MNX
MOK
MOL
MON
MOR
MRI
MTH
MTS
MUN
NAG
NAN
NAS
NCR
NDB
NDG
NEP
NEW
NHC
NIS
NIU
NKL
NLD
NOG
NOR
NSM
NTA
NTO
NYN
OCR
OJB
ORI
ORO
OSS
PAA
PAL
PAN
PAP
PAS
PGR
PIL
PLG
PLK
PRO
PTG
QIN
RAJ
RCR
RBU
RIA
RMS
ROM
ROY
RSY
RUA
RUS
SAD
SAN
SAT
SAY
SEK
SEL
SGO
SHN
SIB
SID
SIG
SKS
SKY
SLA
SLV
SML
SMO
SNA
SND
SNH
SNK
SOG
SOT
SQI
SRB
SRK
SRR
SSL
SSM
SUR
SVA
SVE
SWA
SWK
SWZ
SXT
SYR
TAB
TAJ
TAM
TAT
TCR
TEL
TGN
TGR
TGY
THA
THT
TIB
TKM
TMN
TNA
TNE
TNG
TOD
TRK
TSG
TUA
TUL
TUV
TWI
UDM
UKR
URD
USB
UYG
UZB
VEN
VIT
WA
WAG
WCR
WEL
WLF
XHS
YAK
YBA
YCR
YIC
YIM
ZHP
ZHS
ZHT
ZND
ZUL""".splitlines()

languageTags = []
for i in _languageTags:
    if len(i) < 4:
        i += " " * (4 - len(i))
    languageTags.append(i)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{{ site.title }}</title>
    <meta name="description" content="{{ site.name }}'s Résumé">
    <meta name="author" content="{{ site.name }} @{{ site.twitter }}">

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

    <link rel="stylesheet" href="{{ site.baseurl }}static/css/vitae-base.css">
    <link rel="stylesheet" href="{{ site.baseurl }}static/css/vitae-skeleton.css">
    <link rel="stylesheet" href="{{ site.baseurl }}static/css/vitae-layout.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="shortcut icon" href="{{ site.baseurl }}static/img/favicon.ico">

{{ site.name }}

              {{ site.tel }}

          <address>

                  {{ site.address }},

                  {{ site.city }}

                  {{ site.country }}

          </address>

              {{ site.email }}

           home

          {{ content }}

        {% include footer.html %}


text:
package models

import database.helper.LdapUserStatus
import play.api.libs.json.{Json, Writes}

import java.util.UUID

case class Lecturer(
    systemId: String,
    campusId: String,
    lastname: String,
    firstname: String,
    email: String,
    id: UUID = UUID.randomUUID
) extends User {
  override def status = LdapUserStatus.LecturerStatus
}

object Lecturer {
  implicit val writes: Writes[Lecturer] = Json.writes[Lecturer]
}


text:
package org.drip.spaces.metric;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  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.
 */

/**
 * RdContinuousHilbert implements the Bounded/Unbounded, Continuous l^2 R^d Spaces.
 *
 * The Reference we've used is:
 *
 * 	- Carl, B., and I. Stephani (1990): Entropy, Compactness, and Approximation of Operators, Cambridge
 * 		University Press, Cambridge UK.
 *
 * @author Lakshmi Krishnamurthy
 */

public class RdContinuousHilbert extends org.drip.spaces.metric.RdContinuousBanach {

	/**
	 * Construct the Standard l^2 R^d Hilbert Space Instance
	 *
	 * @param iDimension The Space Dimension
	 * @param distRd The R^d Borel Sigma Measure
	 *
	 * @return The Standard l^2 R^d Hilbert Space Instance
	 */

	public static final RdContinuousHilbert StandardHilbert (
		final int iDimension,
		final org.drip.measure.continuousmarginal.Rd distRd)
	{
		try {
			return 0 >= iDimension ? null : new RdContinuousHilbert (new
				org.drip.spaces.tensor.R1ContinuousVector[iDimension], distRd);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * RdContinuousHilbert Space Constructor
	 *
	 * @param aR1CV Array of R^1 Continuous Vector Spaces
	 * @param distRd The Multivariate Borel Sigma Measure
	 *
	 * @throws java.lang.Exception Thrown if the Inputs are Invalid
	 */

	public RdContinuousHilbert (
		final org.drip.spaces.tensor.R1ContinuousVector[] aR1CV,
		final org.drip.measure.continuousmarginal.Rd distRd)
		throws java.lang.Exception
	{
		super (aR1CV, distRd, 2);
	}

	@Override public double sampleMetricNorm (
		final double[] adblX)
		throws java.lang.Exception
	{
		if (!validateInstance (adblX))
			throw new java.lang.Exception ("RdContinuousHilbert::sampleMetricNorm => Invalid Inputs");

		double dblNorm = 0.;
		int iDimension = adblX.length;

		for (int i = 0; i < iDimension; ++i) {
			double dblAbsoluteX = java.lang.Math.abs (adblX[i]);

			dblNorm += dblAbsoluteX * dblAbsoluteX;
		}

		return dblNorm;
	}
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Bailey, Bot. Bull. Dept. Agric. , Queensland 7: 31 (1891)

#### Original name
Pyrgillus caliciisporus F. Wilson

### Remarks
null


text:
package reactivemongo.api

import scala.concurrent.{ ExecutionContext, Future }

/**
 * Cursor wrapper, to help to define custom cursor classes.
 * @see CursorProducer
 */
trait WrappedCursor[T] extends Cursor[T] with WrappedCursorCompat[T] {

  /** The underlying cursor */
  protected def wrappee: Cursor[T]

  final def foldBulks[A](
      z: => A,
      maxDocs: Int = -1
    )(suc: (A, Iterator[T]) => Cursor.State[A],
      err: Cursor.ErrorHandler[A]
    )(implicit
      ec: ExecutionContext
    ): Future[A] = wrappee.foldBulks(z, maxDocs)(suc, err)

  final def foldBulksM[A](
      z: => A,
      maxDocs: Int = -1
    )(suc: (A, Iterator[T]) => Future[Cursor.State[A]],
      err: Cursor.ErrorHandler[A]
    )(implicit
      ec: ExecutionContext
    ): Future[A] = wrappee.foldBulksM(z, maxDocs)(suc, err)

  final def foldWhile[A](
      z: => A,
      maxDocs: Int = -1
    )(suc: (A, T) => Cursor.State[A],
      err: Cursor.ErrorHandler[A]
    )(implicit
      ec: ExecutionContext
    ): Future[A] = wrappee.foldWhile(z, maxDocs)(suc, err)

  final def foldWhileM[A](
      z: => A,
      maxDocs: Int = -1
    )(suc: (A, T) => Future[Cursor.State[A]],
      err: Cursor.ErrorHandler[A]
    )(implicit
      ec: ExecutionContext
    ): Future[A] = wrappee.foldWhileM(z, maxDocs)(suc, err)

  final def head(implicit ec: ExecutionContext): Future[T] = wrappee.head

  final def headOption(implicit ec: ExecutionContext): Future[Option[T]] =
    wrappee.headOption
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using NaturalSoftware.Kinect;
using Ventuz.OSC;

namespace KineCon
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        KinectSensorWrapper kinect;

        UdpWriter udpWriter;

        public MainWindow()
        {
            InitializeComponent();

            Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded( object sender, RoutedEventArgs e )
        {
            try {
                udpWriter = new UdpWriter( ConfigurationManager.AppSettings["DestinationAddress"],
                                           int.Parse( ConfigurationManager.AppSettings["DestinationPort"] ) );

                kinect = new KinectSensorWrapper();
                kinect.AllFrameReady += kinect_AllFrameReady;
                kinect.Start();
            }
            catch ( Exception ex ) {
                MessageBox.Show( ex.Message );
                Close();
            }
        }

        void kinect_AllFrameReady( KinectUpdateFrameData e )
        {
            try {
                TextMessage.Text = "";

                if ( !e.IsAllUpdated ) {
                    return;
                }

                ImageColor.Source = e.ColorFrame.ToBitmapSource();

                var skeletons = e.SkeletonFrame.GetTrackedSkeleton();
                if ( skeletons.Count() != 2 ) {
                    return;
                }

                var player1 = skeletons.First().Joints[JointType.Head];
                var player2 = skeletons.Last().Joints[JointType.Head];
                if ( !player1.IsTrackingOrInferred() || !player2.IsTrackingOrInferred() ) {
                    return;
                }

                var distance = (int)(Math.Sqrt( Math.Pow( player2.Position.X - player1.Position.X, 2 ) +
                                                Math.Pow( player2.Position.Y - player1.Position.Y, 2 ) +
                                                Math.Pow( player2.Position.Z - player1.Position.Z, 2 ) ) * 1000);

                TextMessage.Text = distance.ToString();

                udpWriter.Send( new OscBundle( 0, new OscElement( "/distance", distance ) ) );
            }
            catch ( Exception ex ) {
                Trace.WriteLine( ex.Message );
            }
        }
    }
}


text:
module('lively.bindings.Core').requires().toRun(function() {

Object.subclass('AttributeConnection',
'settings', {
    doNotSerialize: ['isActive', 'converter', 'updater']
},
'initializing', {

    initialize: function(source, sourceProp, target, targetProp, spec) {
        this.init(source, sourceProp, target, targetProp, spec);
    },
    init: function(source, sourceProp, target, targetProp, spec) {
        this.sourceObj = source;
        this.sourceAttrName = sourceProp;
        this.targetObj = target;
        this.targetMethodName = targetProp;
        this.varMapping = {source: source, target: target};
        if (spec) {
            if (spec.removeAfterUpdate) this.removeAfterUpdate = true;
            if (spec.forceAttributeConnection) this.forceAttributeConnection = true;
            // when converter function references objects from its environment
            // we can't serialize it. To fail as early as possible we will
            // serialize the converter / updater already in the setters
            if (spec.converter) this.setConverter(spec.converter);
            if (spec.updater) this.setUpdater(spec.updater);
            if (spec.varMapping) {
                this.varMapping = Object.extend(spec.varMapping, this.varMapping);
            }
        }
        return this;
    },

    onSourceAndTargetRestored: function() {
        if (this.sourceObj && this.targetObj) this.connect();
    },

    copy: function(copier) {
        return AttributeConnection.fromLiteral(this.toLiteral(), copier);
    },

    fixInstanceAfterCopyingFromSite: function(name, ref, index) {
        // alert("removed connection: "  + this)
        this.disconnect();
    },

    clone: function() {
        //rk 2012-10-09: What is the reason to have clone AND copy?!
        var con = new this.constructor(
            this.getSourceObj(), this.getSourceAttrName(),
            this.getTargetObj(), this.getTargetMethodName(),
            this.getSpec());
        if (this.dependedBy) con.dependedBy = this.dependedBy;
        return con;
    }

},
'accessing', {
    getTargetObj: function() { return this.targetObj },
    getSourceObj: function() { return this.sourceObj },
    getSourceAttrName: function() { return this.sourceAttrName },
    getTargetMethodName: function() { return this.targetMethodName },
    getSourceValue: function() { return this.getSourceObj()[this.getSourceAttrName()] },
    getPrivateSourceValue: function() { return this.sourceObj[this.privateAttrName(this.sourceAttrName)] },

    getConverter: function() {
        if (!this.converterString) return null;
        if (!this.converter)
            this.converter = lively.Closure.fromSource(this.converterString, this.varMapping).recreateFunc();
        return this.converter;
    },

    setConverter: function(funcOrSource) {
        delete this.converter;
        return this.converterString = funcOrSource ? String(funcOrSource) : null;
    },

    getUpdater: function() {
        if (!this.updaterString) return null;
        if (!this.updater) {
            this.updater = lively.Closure.fromSource(this.updaterString, this.varMapping).recreateFunc();
        }
        return this.updater;
    },

    setUpdater: function(funcOrSource) {
        delete this.updater;
        return this.updaterString = funcOrSource ? String(funcOrSource) : null;
    },

    getSpec: function() {
        var spec = {};
        if (this.updaterString) spec.updater = this.getUpdater();
        if (this.converterString) spec.converter = this.getConverter();
        if (this.removeAfterUpdate) spec.removeAfterUpdate = true;
        if (this.forceAttributeConnection) spec.forceAttributeConnection = true;
        return spec;
    },

    resetSpec: function() {
        delete this.removeAfterUpdate;
        delete this.forceAttributeConnection;
        delete this.converter;
        delete this.converterString;
        delete this.updater;
        delete this.updaterString;
    },

    privateAttrName: function(attrName) { return '$$' + attrName },

    activate: function() { this.isActive = true },

    deactivate: function() { delete this.isActive; }

},
'connecting', {

    connect: function() {
        var existing = this.getExistingConnection()
        if (existing !== this) {
            // when existing == null just add new connection when
            // existing === this then connect was called twice or we are in
            // deserialization. Just do nothing then.
            existing && existing.disconnect();
            this.addAttributeConnection();
        }

        // Check for existing getters that might be there and not belong to
        // lively.bindings We deal with them in addSourceObjGetterAndSetter()
        var existingSetter = this.sourceObj.__lookupSetter__(this.sourceAttrName),
            existingGetter = this.sourceObj.__lookupGetter__(this.sourceAttrName);

        // Check if a method is the source. We check both the value behind
        // sourceAttrName and $$sourceAttrName because when deserializing
        // scripts those get currently stored in $$sourceAttrName (for
        // non-scripts it doesn't matter since those methods should be in the
        // prototype chain)
        var methodOrValue = !existingSetter && !existingGetter &&
            (this.getSourceValue() || this.getPrivateSourceValue());

        // method connect... FIXME refactori into own class!
        if (Object.isFunction(methodOrValue) && !this.forceAttributeConnection) {
            if (!methodOrValue.isWrapped) {
                this.addConnectionWrapper(this.sourceObj, this.sourceAttrName, methodOrValue);
            }
        } else { // attribute connect
            this.addSourceObjGetterAndSetter(existingGetter, existingSetter);
        }

        return this;
    },

    disconnect: function() {
        var obj = this.sourceObj;
        if (!obj || !obj.attributeConnections) return this.removeSourceObjGetterAndSetter();
        obj.attributeConnections = obj.attributeConnections.reject(function(con) {
            return this.isSimilarConnection(con);
        }, this);
        var connectionsWithSameSourceAttr = obj.attributeConnections.select(function(con) {
            return this.getSourceAttrName() == con.getSourceAttrName();
        }, this);
        if (obj.attributeConnections.length == 0) {
            delete obj.attributeConnections;
        }
        if (connectionsWithSameSourceAttr.length == 0) {
            this.removeSourceObjGetterAndSetter();
        }
        return null;
    },

    update: function (newValue, oldValue) {
        // This method is optimized for Safari and Chrome.
        // See lively.bindings.tests.BindingTests.BindingsProfiler
        // The following requirements exists:
        // - Complete Customization of control (how often, if at all, binding
        //   should be activated, parameters passed, delay,... )
        // - run converter with oldValue and newValue
        // - when updater is existing run converter only if update is proceeded
        // - bind is slow
        // - arguments is slow when it's items are accessed or it's converted
        //   using Array.from. Note 2014-02-10: We currently need to modify the
        //   argument array for allowing conversion.

        if (this.isActive/*this.isRecursivelyActivated()*/) return null;
        var connection = this, updater = this.getUpdater(), converter = this.getConverter(),
            target = this.targetObj, propName = this.targetMethodName;
        if (!target || !propName) {
            var msg = 'Cannot update ' + this.toString(newValue)
                    + ' because of no target ('
                    + target + ') or targetProp (' + propName+') ';
            if (this.isWeakConnection) { this.disconnect(); }
            console.error(msg);

            return null;
        }
        var targetMethod = target[propName], callOrSetTarget = function(newValue, oldValue) {
            // use a function and not a method to capture this in self and so
            // that no bind is necessary and oldValue is accessible. Note that
            // when updater calls this method arguments can be more than just
            // the new value
            var args = Array.from(arguments);
            if (converter) {
                newValue = converter.call(connection, newValue, oldValue);
                args[0] = newValue;
            }
            var result = (typeof targetMethod === 'function') ?
                targetMethod.apply(target, args) :
                target[propName] = newValue;
            if (connection.removeAfterUpdate) connection.disconnect();
            return result;
        };

        try {
            this.isActive = true;
            return updater ?
                updater.call(this, callOrSetTarget, newValue, oldValue) :
                callOrSetTarget(newValue, oldValue);
        } catch(e) {
            // FIXME: checks should not be scatter all over the code
            if (lively.Config.get('loadRewrittenCode') && e.unwindException)
                throw e.unwindException;
            dbgOn(Config.debugConnect);
            var world = Global.lively &&
                lively.morphic.World &&
                lively.morphic.World.current();
            if (world) {
                world.logError(e, 'AttributeConnection>>update: ');
            } else {
                alert('Error when trying to update ' + this + ' with value '
                     + newValue + ':\n' + e + '\n' + e.stack);
            }
        } finally {
            delete this.isActive;
        }

        return null;
    }

},
'private helper', {

    addSourceObjGetterAndSetter: function(existingGetter, existingSetter) {
        if ((existingGetter && existingGetter.isAttributeConnectionGetter) ||
            (existingSetter && existingSetter.isAttributeConnectionSetter)) {
            return;
        }

        var sourceObj = this.sourceObj,
            sourceAttrName = this.sourceAttrName,
            newAttrName = this.privateAttrName(sourceAttrName);

        if (sourceObj[newAttrName]) {
            console.warn('newAttrName ' + newAttrName + ' already exists.' +
                         'Are there already other connections?');
        }

        // add new attr to the serialization ignore list
        if (!sourceObj.hasOwnProperty('doNotSerialize')) sourceObj.doNotSerialize = [];
        sourceObj.doNotSerialize.pushIfNotIncluded(newAttrName);

        if (!sourceObj.hasOwnProperty('doNotCopyProperties')) sourceObj.doNotCopyProperties = [];
        sourceObj.doNotCopyProperties.pushIfNotIncluded(newAttrName);

        if (existingGetter)
            sourceObj.__defineGetter__(newAttrName, existingGetter);
        if (existingSetter)
            sourceObj.__defineSetter__(newAttrName, existingSetter);

        // assign old value to new slot
        if (!existingGetter && !existingSetter && sourceObj.hasOwnProperty(sourceAttrName))
            sourceObj[newAttrName] = sourceObj[sourceAttrName];

        this.sourceObj.__defineSetter__(sourceAttrName, function(newVal) {
            var oldVal = sourceObj[newAttrName];
            sourceObj[newAttrName] = newVal;
            if (sourceObj.attributeConnections === undefined) {
                console.error('Sth wrong with sourceObj, has no attributeConnections');
                return null;
            }
            var conns = sourceObj.attributeConnections.clone();
            for (var i = 0; i < conns.length; i++) {
                var c = conns[i];
                if (c && c.getSourceAttrName() === sourceAttrName) {
                    c.update(newVal, oldVal);
                }
            }
            return newVal;
        });
        this.sourceObj.__lookupSetter__(sourceAttrName).isAttributeConnectionSetter = true;

        this.sourceObj.__defineGetter__(this.sourceAttrName, function() {
            return sourceObj[newAttrName];
        });
        this.sourceObj.__lookupGetter__(sourceAttrName).isAttributeConnectionGetter = true;
    },

    addConnectionWrapper: function(sourceObj, methodName, origMethod) {
        if (!Object.isFunction(origMethod)) {
            throw new Error('addConnectionWrapper didnt get a method to wrap');
        }

        // save so that it can be restored
        sourceObj[this.privateAttrName(methodName)] = origMethod;
        sourceObj[methodName] = function connectionWrapper() {
            if (this.attributeConnections === undefined)
                throw new Error('Sth wrong with this, has no attributeConnections')
            var conns = this.attributeConnections.clone(),
                result = this[methodName].originalFunction.apply(this, arguments);
            for (var i = 0, len = conns.length; i < len; i++) {
                var c = conns[i];
                if (c.getSourceAttrName() === methodName) result = c.update(result);
            }
            return result;
        };

        sourceObj[methodName].isWrapped = true;
        sourceObj[methodName].isConnectionWrapper = true;
        sourceObj[methodName].originalFunction = origMethod; // for getOriginal()
    },

    removeSourceObjGetterAndSetter: function() {
        // delete the getter and setter and the slot were the real value was stored
        // assign the real value to the old slot
        var realAttrName = this.sourceAttrName,
            helperAttrName = this.privateAttrName(realAttrName),
            srcObj = this.sourceObj;

        if (!srcObj) return;

        if (srcObj.__lookupGetter__(realAttrName)) {
            delete srcObj[realAttrName];
            srcObj[realAttrName] = srcObj[helperAttrName];
            delete srcObj[helperAttrName];
        } else if(srcObj[realAttrName] && srcObj[realAttrName].isConnectionWrapper) {
            srcObj[realAttrName] = srcObj[realAttrName].originalFunction
        }

        if (srcObj.doNotSerialize && srcObj.doNotSerialize.include(helperAttrName)) {
            srcObj.doNotSerialize = srcObj.doNotSerialize.without(helperAttrName);
            if (srcObj.doNotSerialize.length == 0) delete srcObj.doNotSerialize;
        }

        if (srcObj.doNotCopyProperties && srcObj.doNotCopyProperties.include(helperAttrName)) {
            srcObj.doNotCopyProperties = srcObj.doNotCopyProperties.without(helperAttrName);
            if (srcObj.doNotCopyProperties.length == 0) delete srcObj.doNotCopyProperties;
        }
    },

    addAttributeConnection: function() {
        if (!this.sourceObj.attributeConnections)
            this.sourceObj.attributeConnections = [];
        this.sourceObj.attributeConnections.push(this);
    },

    getExistingConnection: function() {
        var conns = this.sourceObj && this.sourceObj.attributeConnections;
        if (!conns) return null;
        for (var i = 0, len = conns.length; i < len; i++) {
            if (this.isSimilarConnection(conns[i])) return conns[i];
        }
        return null;
    }

},
'testing', {

    isRecursivelyActivated: function() {
        // is this enough? Maybe use Stack?
        return this.isActive
    },

    isSimilarConnection: function(other) {
        if (!other) return false;
        if (other.constructor != this.constructor) return false;
        return this.sourceObj == other.sourceObj &&
            this.sourceAttrName == other.sourceAttrName &&
            this.targetObj == other.targetObj &&
            this.targetMethodName == other.targetMethodName;
    }
},
'debugging', {
    toString: function(optValue) {
        try {
            return Strings.format(
                'AttributeConnection(%s.%s %s %s.%s)',
                this.getSourceObj(),
                this.getSourceAttrName(),
                optValue ? ('-->' + String(optValue) + '-->') : '-->',
                this.getTargetObj(),
                this.getTargetMethodName());
        } catch(e) {
            return '<Error in AttributeConnection>>toString>';
        }
    }
});

AttributeConnection.addMethods({
    toLiteral: function() {
        var self  = this;
        function getId(obj) {
            if (!obj) {
                console.warn('Cannot correctly serialize connections having '
                            + 'undefined source or target objects');
                return null;
            }
            if (obj.id && Object.isFunction(obj.id))
                return obj.id();
            if (obj.nodeType && obj.getAttribute) { // is it a real node?
                var id = obj.getAttribute('id')
                if (!id) { // create a new id
                    id = 'ElementConnection--' + Date.now();
                    obj.setAttribute('id', id);
                }
                return id;
            }
            console.warn('Cannot correctly serialize connections having '
                        + 'source or target objects that have no id: ' + self);
            return null
        }
        var literal = {
            sourceObj: getId(this.sourceObj),
            sourceAttrName: this.sourceAttrName,
            targetObj: getId(this.targetObj),
            targetMethodName: this.targetMethodName
        };
        if (this.converterString) literal.converter = this.converterString;
        if (this.updaterString) literal.updater = this.updaterString;
        if (this.removeAfterUpdate) literal.removeAfterUpdate = true;
        if (this.forceAttributeConnection) literal.forceAttributeConnection = true;
        return literal;
    }
})

Object.extend(AttributeConnection, {
    fromLiteral: function(literal, importer) {
        if (!importer)
            throw new Error('AttributeConnection needs importer for resolving uris!!!');

        // just create the connection, connection not yet installed!!!
        var con = new AttributeConnection(
            null, literal.sourceAttrName, null, literal.targetMethodName, literal);

        // when target/source obj are restored asynchronly
        new AttributeConnection(con, 'sourceObj', con, 'onSourceAndTargetRestored',
            {removeAfterUpdate: true}).connect();
        new AttributeConnection(con, 'targetObj', con, 'onSourceAndTargetRestored',
            {removeAfterUpdate: true}).connect();

        function restore(id, fieldName) {
            if (!id) {
                console.warn('cannot deserialize ' + fieldName + ' when deserilaizing a lively.bindings.connect');
                return
            }
            if (id.split('--')[0] == 'ElementConnection') { // FIXME brittle!!!
                con[fieldName] = importer.canvas().ownerDocument.getElementById(id);
                return
            }
            importer.addPatchSite(con, fieldName, id);
        };

        restore(literal.sourceObj, 'sourceObj');
        restore(literal.targetObj, 'targetObj');

        return con;
    }
});

AttributeConnection.addMethods('serialization', {
    onrestore: function() {
        try {
            if (!this.sourceObj) { throw new Error("Restoring AttributeConnection, but lost its source."); }
            this.connect();
        } catch(e) {
            dbgOn(true);
            console.error('AttributeConnection>>onrestore: Cannot restore ' + this + '\n' + e);
        }
    },
});

Object.extend(lively.bindings, {

    documentation: 'connect parameters: source, sourceProp, target, targetProp, spec\n'
                 + 'spec can be: {\n'
                 + '  removeAfterUpdate: Boolean,\n'
                 + '  forceAttributeConnection: Boolean,\n'
                 + '  converter: Function,\n'
                 + '  updater: Function,\n'
                 + '  varMapping: Object\n'
                 + '}',

    connect: function connect(sourceObj, attrName, targetObj, targetMethodName, specOrConverter) {
        // 1: determine what kind of connection to create. Default is
        //    AttributeConnection but source.connections/
        //    source.getConnectionPoints can specify different settings
        var connectionPoints = (sourceObj.getConnectionPoints && sourceObj.getConnectionPoints())
                            || (sourceObj.connections),
            connectionPoint = connectionPoints && connectionPoints[attrName],
            klass = (connectionPoint && connectionPoint.map && lively.morphic && lively.morphic.GeometryConnection)
                 || (connectionPoint && connectionPoint.connectionClassType && lively.Class.forName(connectionPoint.connectionClassType))
                 || AttributeConnection,
            spec;

        // 2: connection settings: converter/updater/...
        if (Object.isFunction(specOrConverter)) {
            console.warn('Directly passing a converter function to connect() '
                         + 'is deprecated! Use spec object instead!');
            spec = {converter: specOrConverter};
        } else {
            spec = specOrConverter;
        }

        // 3: does a similar connection exist? Yes: update it with new specs,
        //    no: create new connection
        var connection = new klass(sourceObj, attrName, targetObj, targetMethodName, spec),
            existing = connection.getExistingConnection();
        if (existing) {
            existing.resetSpec();
            existing.init(sourceObj, attrName, targetObj, targetMethodName, spec);
            return existing;
        }
        var result = connection.connect();

        // 4: notify source object if it has a #onConnect method
        if (Object.isFunction(sourceObj.onConnect)) {
            sourceObj.onConnect(attrName, targetObj, targetMethodName)
        }

        // 5: If wanted updated the connection right now
        if (connectionPoint && connectionPoint.updateOnConnect) {
            connection.update(sourceObj[attrName]);
        }
        return result;
    },

    disconnect: function(sourceObj, attrName, targetObj, targetMethodName) {
        if (!sourceObj.attributeConnections) return;

        sourceObj.attributeConnections.clone().forEach(function(con) {
            if (con.getSourceAttrName() == attrName
            &&  con.getTargetObj() === targetObj
            &&  con.getTargetMethodName() == targetMethodName) con.disconnect(); });

        if (typeof sourceObj['onDisconnect'] == 'function') {
            sourceObj.onDisconnect(attrName, targetObj, targetMethodName);
        };
    },

    disconnectAll: function(sourceObj) {
        while (sourceObj.attributeConnections && sourceObj.attributeConnections.length > 0) {
            sourceObj.attributeConnections[0].disconnect();
        }
    },

    once: function(sourceObj, attrName, targetObj, targetMethodName, spec) {
        spec = spec || {};
        spec.removeAfterUpdate = true;
        return lively.bindings.connect(sourceObj, attrName, targetObj, targetMethodName, spec);
    },

    signal: function(sourceObj, attrName, newVal) {
        var connections = sourceObj.attributeConnections;
        if (!connections) return;
        var oldVal = sourceObj[attrName];
        for (var i = 0, len = connections.length; i < len; i++) {
            var c = connections[i];
            if (c.getSourceAttrName() == attrName) c.update(newVal, oldVal);
        }
    },

    callWhenNotNull: function(sourceObj, sourceProp, targetObj, targetSelector) {
        // ensure that sourceObj[sourceProp] is not null, then run targetObj[targetProp]()
        if (sourceObj[sourceProp] != null) {
            targetObj[targetSelector](sourceObj[sourceProp]);
        } else {
            lively.bindings.connect(
                sourceObj, sourceProp, targetObj, targetSelector,
                {removeAfterUpdate: true});
        }
    },

    callWhenPathNotNull: function(source, path, target, targetProp) {
        var helper = {
            key: path.pop(),
            whenDefined: function(context) {
                lively.bindings.callWhenNotNull(context, this.key, target, targetProp)
            }
        }

        while (path.length > 0) {
            helper = {
                key: path.pop(),
                next: helper,
                whenDefined: function(context) {
                    lively.bindings.callWhenNotNull(context, this.key, this.next, 'whenDefined')
                }
            }
        }

        helper.whenDefined(source);
    },

    noUpdate: function(noUpdateSpec, func) {
        var globalNoUpdate = false, result;
        if (!func && Object.isFunction(noUpdateSpec)) {
            func = noUpdateSpec; globalNoUpdate = true; }
        if (globalNoUpdate) { // rather a hack for now
            var proto = lively.bindings.AttributeConnection.prototype;
            if (!proto.isActive) proto.isActive = 0;
            proto.isActive++;
            try {
                result = func();
            } finally {
                proto.isActive--;
                if (proto.isActive <= 0) proto.isActive;
            }
        } else {
            var obj = noUpdateSpec.sourceObj,
                attr = noUpdateSpec.sourceAttribute,
                targetObj = noUpdateSpec.targetObj,
                targetAttr = noUpdateSpec.targetAttribute,
                filter = targetObj && targetAttr ?
                    function(ea) { return ea.getSourceAttrName() === attr
                                       && targetObj === ea.getTargetObj()
                                       && targetAttr === ea.getTargetMethodName(); }:
                    function(ea) { return ea.getSourceAttrName() === attr; },
                conns = obj.attributeConnections.select(filter);
            conns.invoke('activate');
            try {
                result = func();
            } finally {
                conns.invoke('deactivate');
            }
        }
        return result;
    },

    // moving classes into Namespace
    AttributeConnection: AttributeConnection

});

Object.extend(Global, {
    connect: lively.bindings.connect,
    disconnect: lively.bindings.disconnect,
    disconnectAll: lively.bindings.disconnectAll,
    signal: lively.bindings.signal,
    updateAttributeConnection: lively.bindings.signal
});

}); // end of module


text:
package com.github.akovari.rdfp.api.ql

import org.joda.time.DateTime
import org.joda.time.format.{ISODateTimeFormat, DateTimeFormatterBuilder, DateTimeFormat}
import org.parboiled.errors.ErrorUtils
import org.parboiled.scala._

/**
  * Created by akovari on 18.8.2014.
  */
object UQLParser {
  val True = BooleanNode(value = true)
  val False = BooleanNode(value = false)
  val dateTimeFormatter = new DateTimeFormatterBuilder().append(null, Array(
    DateTimeFormat.forPattern("yyyy/MM/dd").withZoneUTC().getParser,
    DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC().getParser,
    ISODateTimeFormat.dateTime().withZoneUTC().getParser)
  ).toFormatter

  sealed abstract class AstNode

  sealed abstract class AstValue[+T](value: T) extends AstNode

  sealed abstract class Condition extends AstNode {
    def hasField(name: String): Boolean = false
  }

  sealed abstract class BooleanCondition(left: Condition, right: Condition) extends Condition {
    override def hasField(name: String): Boolean = left.hasField(name) || right.hasField(name)
  }

  sealed abstract class SimpleCondition(name: String, value: AstNode) extends Condition {
    override def hasField(name: String): Boolean = this.name == name
  }

  sealed abstract class NegativeCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  sealed abstract class NullValue extends AstValue(null)

  case class EqualsCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class NotEqualsCondition(name: String, value: AstNode) extends NegativeCondition(name, value)

  case class LikeCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class ILikeCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class LowerCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class GreaterCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class LowerOrEqualCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class GreaterOrEqualCondition(name: String, value: AstNode) extends SimpleCondition(name, value)

  case class InCondition(name: String, value: ArrayNode) extends SimpleCondition(name, value)

  case class NotInCondition(name: String, value: ArrayNode) extends NegativeCondition(name, value)

  case class IncludesCondition(name: String, value: ArrayNode) extends SimpleCondition(name, value)

  case class ExcludesCondition(name: String, value: ArrayNode) extends NegativeCondition(name, value)

  case class AndCondition(left: Condition, right: Condition) extends BooleanCondition(left, right)

  case class OrCondition(left: Condition, right: Condition) extends BooleanCondition(left, right)

  case class Entity(value: String) extends AstValue(value)

  case class Filter(entity: Entity, condition: Condition) extends AstNode

  case class ArrayNode(value: List[AstValue[_]]) extends AstValue(value)

  case class StringNode(value: String) extends AstValue(value)

  case class NumberNode(value: BigDecimal) extends AstValue(value)

  case class DateTimeNode(value: DateTime) extends AstValue(value)

  case class BooleanNode(value: Boolean) extends AstValue(value)

  case object Null extends NullValue

  def parseUQL(uql: String): Filter = new UQLParser().parseUQL(uql)

}

class UQLParser extends CommonParser {

  import UQLParser._

  def UQLFilter: Rule1[Filter] = rule {
    UQLEntity ~ ANDSign ~ UQLAnyCondition ~~> ((entity, condition) => Filter(entity, condition)) ~ EOI
  }

  def UQLEntity: Rule1[Entity] = rule {
    "entity" ~ EqualsSign ~ UQLString ~~> (name => Entity(name.value))
  }

  def UQLAnyCondition: Rule1[Condition] = rule(UQLBooleanCondition | UQLCondition | UQLNestedCondition)

  def UQLBooleanCondition = rule(UQLAndCondition | UQLOrCondition)

  def UQLNestedCondition: Rule1[Condition] = rule {
    LeftParen ~ UQLAnyCondition ~ RightParen
  }

  def LeftParen: Rule0 = rule(WhiteSpace ~ "(" ~ WhiteSpace)

  def RightParen: Rule0 = rule(WhiteSpace ~ ")" ~ WhiteSpace)

  def UQLAndCondition: Rule1[AndCondition] = rule {
    (UQLCondition | UQLNestedCondition) ~ ANDSign ~ (UQLCondition | UQLNestedCondition) ~~> ((left, right) => AndCondition(left, right))
  }

  def UQLOrCondition: Rule1[OrCondition] = rule {
    (UQLCondition | UQLNestedCondition) ~ ORSign ~ (UQLCondition | UQLNestedCondition) ~~> ((left, right) => OrCondition(left, right))
  }

  def ANDSign: Rule0 = rule(WhiteSpace ~ ignoreCase("AND") ~ WhiteSpace)

  def ORSign: Rule0 = rule(WhiteSpace ~ ignoreCase("OR") ~ WhiteSpace)

  def UQLCondition: Rule1[Condition] = rule(UQLEqualsCondition | UQLNotEqualsCondition | UQLLowerCondition |
    UQLGreaterCondition | UQLLowerOrEqualCondition | UQLGreaterOrEqualCondition | UQLInCondition |
    UQLIncludesCondition | UQLExcludesCondition | UQLLikeCondition | UQLNotInCondition | UQLILikeCondition)

  def UQLEqualsCondition: Rule1[EqualsCondition] = rule {
    UQLIdent ~ EqualsSign ~ Value ~~> ((name, value) => EqualsCondition(name.value, value))
  }

  def UQLNotEqualsCondition: Rule1[NotEqualsCondition] = rule {
    UQLIdent ~ NotEqualsSign ~ Value ~~> ((name, value) => NotEqualsCondition(name.value, value))
  }

  def UQLLowerCondition: Rule1[LowerCondition] = rule {
    UQLIdent ~ LowerThanSign ~ Value ~~> ((name, value) => LowerCondition(name.value, value))
  }

  def UQLGreaterCondition: Rule1[GreaterCondition] = rule {
    UQLIdent ~ GreaterThanSign ~ Value ~~> ((name, value) => GreaterCondition(name.value, value))
  }

  def UQLLowerOrEqualCondition: Rule1[LowerOrEqualCondition] = rule {
    UQLIdent ~ LowerOrEqualThanSign ~ Value ~~> ((name, value) => LowerOrEqualCondition(name.value, value))
  }

  def UQLGreaterOrEqualCondition: Rule1[GreaterOrEqualCondition] = rule {
    UQLIdent ~ GreaterOrEqualThanSign ~ Value ~~> ((name, value) => GreaterOrEqualCondition(name.value, value))
  }

  def UQLInCondition: Rule1[InCondition] = rule {
    UQLIdent ~ InSign ~ UQLArray ~~> ((name, value) => InCondition(name.value, value))
  }

  def UQLNotInCondition: Rule1[NotInCondition] = rule {
    UQLIdent ~ NotSign ~ InSign ~ UQLArray ~~> ((name, value) => NotInCondition(name.value, value))
  }

  def UQLIncludesCondition: Rule1[IncludesCondition] = rule {
    UQLIdent ~ IncludesSign ~ UQLArray ~~> ((name, value) => IncludesCondition(name.value, value))
  }

  def UQLExcludesCondition: Rule1[ExcludesCondition] = rule {
    UQLIdent ~ ExcludesSign ~ UQLArray ~~> ((name, value) => ExcludesCondition(name.value, value))
  }

  def UQLLikeCondition: Rule1[LikeCondition] = rule {
    UQLIdent ~ LikeSign ~ Value ~~> ((name, value) => LikeCondition(name.value, value))
  }

  def UQLILikeCondition: Rule1[ILikeCondition] = rule {
    UQLIdent ~ (InsensitiveSign ~ LikeSign | ILikeSign) ~ Value ~~> ((name, value) => ILikeCondition(name.value, value))
  }

  def EqualsSign: Rule0 = rule(WhiteSpace ~ ("=" | ignoreCase("IS")) ~ WhiteSpace)

  def NotEqualsSign: Rule0 = rule(WhiteSpace ~ ("!=" | ignoreCase("NE")) ~ WhiteSpace)

  def LowerThanSign: Rule0 = rule(WhiteSpace ~ ("<" | ignoreCase("LT")) ~ WhiteSpace)

  def GreaterThanSign: Rule0 = rule(WhiteSpace ~ (">" | ignoreCase("GT")) ~ WhiteSpace)

  def LowerOrEqualThanSign: Rule0 = rule(WhiteSpace ~ ("<=" | ignoreCase("LTE")) ~ WhiteSpace)

  def GreaterOrEqualThanSign: Rule0 = rule(WhiteSpace ~ (">=" | ignoreCase("GTE")) ~ WhiteSpace)

  def InSign: Rule0 = rule(WhiteSpace ~ ignoreCase("IN") ~ WhiteSpace)

  def IncludesSign: Rule0 = rule(WhiteSpace ~ ignoreCase("INCLUDES") ~ WhiteSpace)

  def ExcludesSign: Rule0 = rule(WhiteSpace ~ ignoreCase("EXCLUDES") ~ WhiteSpace)

  def LikeSign: Rule0 = rule(WhiteSpace ~ ignoreCase("LIKE") ~ WhiteSpace)

  def ILikeSign: Rule0 = rule(WhiteSpace ~ ignoreCase("ILIKE") ~ WhiteSpace)

  def InsensitiveSign: Rule0 = rule(WhiteSpace ~ ignoreCase("INSENSITIVE") ~ WhiteSpace)

  def NotSign: Rule0 = rule(WhiteSpace ~ ignoreCase("NOT") ~ WhiteSpace)

  def Value[_]: Rule1[AstValue[_]] = rule {
    UQLString | UQLDate | UQLNumber | UQLArray | UQLTrue | UQLFalse | UQLNull
  }

  def UQLString: Rule1[StringNode] = rule(WhiteSpace ~ "\"" ~ zeroOrMore(Character) ~> StringNode ~ "\"" ~ WhiteSpace)

  def UQLIdent: Rule1[StringNode] = rule(WhiteSpace ~ (Ident ~> StringNode) ~ WhiteSpace)

  def UQLTrue: Rule1[BooleanNode] = rule {
    WhiteSpace ~ "true" ~ WhiteSpace ~ push(True)
  }

  def UQLFalse: Rule1[BooleanNode] = rule {
    WhiteSpace ~ "false" ~ WhiteSpace ~ push(False)
  }

  def UQLNull: Rule1[NullValue] = rule {
    WhiteSpace ~ "null" ~ WhiteSpace ~ push(Null)
  }

  def UQLNumber: Rule1[NumberNode] = rule {
    WhiteSpace ~ group(Integer ~ optional(Frac ~ optional(Exp))) ~> (s => NumberNode(BigDecimal(s))) ~ WhiteSpace
  }

  def UQLArray: Rule1[ArrayNode] = rule {
    WhiteSpace ~ "[ " ~ WhiteSpace ~ zeroOrMore(Value, separator = ", ") ~ WhiteSpace ~ "] " ~ WhiteSpace ~~> ArrayNode
  }

  def UQLDate: Rule1[DateTimeNode] = rule {
    WhiteSpace ~ group(nTimes(4, Digit) ~ ("/" | "-") ~ nTimes(2, Digit) ~ ("/" | "-") ~ nTimes(2, Digit) ~ optional("T" ~ nTimes(2, Digit) ~ ":" ~ nTimes(2, Digit) ~ ":" ~ nTimes(2, Digit) ~ "." ~ nTimes(3, Digit) ~ ("Z" | (("+" | "-") ~ nTimes(2, Digit) ~ ":" ~ nTimes(2, Digit))))) ~> (d => DateTimeNode(dateTimeFormatter.parseDateTime(d)))
  }

  def parseUQL(uql: String): Filter = {
    val parsingResult = ReportingParseRunner(UQLFilter).run(uql)
    parsingResult.result match {
      case Some(astRoot) => astRoot
      case None => throw new ParsingException( s"""Invalid UQL query: \n${ErrorUtils.printParseErrors(parsingResult)}""")
    }
  }
}