text:
(1) Download the following [security patches](http://wso2.com/security-patch-releases) and copy the
    extracted patch folders to `files/repository/components/patches` directory.

**Security patches**
* patch1261
* patch1095

Final files folder should look like following.

```
├── files
│   ├── bin
│   ├── dbscripts
│   ├── lib
│   └── repository
│       └── components
│           ├── dropins
│           ├── lib
│           └── patches
│               ├── patch1095
│               │   └── wss4j_1.5.11.wso2v6.jar
│               └── patch1261
│                   ├── org.wso2.carbon.tomcat.ext_4.2.0.jar
│                   ├── org.wso2.carbon.tomcat.patch_4.2.0.jar
│                   ├── tomcat_7.0.34.wso2v1.jar
│                   └── tomcat-ha_7.0.34.wso2v1.jar

```

(2) Build the template module zip file by running the following command.

```
mvn clean install
```

---
### Configuration parameters
Following are the configuration parameters that is used by the template.
You can configure following in the ***module.ini*** file.

#### Read from environment variables :

    READ_FROM_ENVIRONMENT = false

-------------------------------------------------------------------------------------

#### Set the path of product directory :

    CARBON_HOME = <ESB_HOME>

---

#### Enable clustering :

    CONFIG_PARAM_CLUSTERING = true

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Membership Schema :

    CONFIG_PARAM_MEMBERSHIP_SCHEME = wka

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Domain :

    CONFIG_PARAM_DOMAIN = wso2.am.domain

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---

#### Well known members declaration :

    CONFIG_PARAM_WKA_MEMBERS = "127.0.0.1:4000,127.0.1.1:4001"

* Format - "ip_address1:port1,ip_address2:port2"
* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---

#### Set Local Member Hostname and port :

    CONFIG_PARAM_LOCAL_MEMBER_HOST = 127.0.0.1
    CONFIG_PARAM_LOCAL_MEMBER_PORT = 4000

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---

### Set Port offset :

    CONFIG_PARAM_PORT_OFFSET = 0

* Used in - < ESB_HOME >/repository/conf/carbon.xml

---
#### Set proxy ports when using a load balancer :

    CONFIG_PARAM_HTTP_PROXY_PORT = 80
    CONFIG_PARAM_HTTPS_PROXY_PORT = 443

* Used in - < ESB_HOME >/repository/conf/tomcat/catalina-server.xml

---
#### Set port mapping in manager Nodes :

    CONFIG_PARAM_PT_HTTP_PROXY_PORT  = 80
    CONFIG_PARAM_PT_HTTPS_PROXY_PORT  = 443

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml

---
#### Set worker/manger sub-domain in nodes  :

    CONFIG_PARAM_SUB_DOMAIN= worker

 * Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml
 * Used in - < ESB_HOME >/repository/conf/carbon.xml
 * Used in - < ESB_HOME >/repository/conf/registry.xml

---
#### Set worker and manager hostnames

    CONFIG_PARAM_WORKER_HOST_NAME = am.cloud-test.wso2.com
    CONFIG_PARAM_MGT_HOST_NAME = mgt.am.cloud-test.wso2.com

* Used in - < ESB_HOME >/repository/conf/axis2/axis2.xml
* Used in - < ESB_HOME >/repository/conf/carbon.xml

---

## Following are the config parameters used for setting up external database
#### Set URL

    CONFIG_PARAM_URL= jdbc:mysql://localhost:3306/

#### Set Username

    CONFIG_PARAM_USER_NAME=root

#### Set Password
```
CONFIG_PARAM_PAMSWORD=root
```
#### Set Driver class name

    CONFIG_PARAM_DRIVER_CLAMS_NAME=com.mysql.jdbc.Driver

#### Set Max Active

    CONFIG_PARAM_MAX_ACTIVE=50

#### Set Max Wait

    CONFIG_PARAM_MAX_WAIT=60000

#### Set test on borrow

    CONFIG_PARAM_TEST_ON_BORROW=true

#### Set validation query
    CONFIG_PARAM_VALIDATION_QUERY=SELECT 1

#### Set validation interval

    CONFIG_PARAM_VALIDATION_INTERVAL=30000

#### Set Local Registry database

    CONFIG_PARAM_REGISTRY_LOCAL1="jdbc/WSO2CarbonDB:REGISTRY_LOCAL1"

#### Set Registry database

    CONFIG_PARAM_REGISTRY_DB="jdbc/WSO2RegistryDB:REGISTRY_DB"

#### Set datasource and shared user database

    CONFIG_PARAM_USER_DB="jdbc/WSO2UMDB:WSO2_USER_DB"

##### Used in

* < ESB_HOME >/repository/conf/user-mgt.xml
* < ESB_HOME >/repository/conf/datasources/master-datasources.xml
* < ESB_HOME >/repository/conf/registry.xml


text:
@interface TBInstructions : CCLayer {

}

+(id)scene;

@end

redpajama_set_name: RedPajamaGithub


text:
/*
   fear he who enter here.  It appears that things have changed.  An attempt
   has been made to put things the way the should be.

        It compiles and ParallelBlackBox runs.  No further guarantees.

	Well... One.. it will print "Hello World!" on an epson DX 10 printer.
	you know.. the 10 character per second daisy wheel printer ;)

        - Trent Jarvi
*/

#if defined(__MWERKS__)/* dima */
#include "LPRPort.h"
#else /* dima */
#ifndef WIN32
#	include "config.h"
#endif
/* work around for libc5 */
/*#include <typedefs_md.h>*/
#include "gnu_io_LPRPort.h"
#endif /* dima */
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#ifndef WIN32
#	include <sys/ioctl.h>
#	include <sys/errno.h>
#	include <sys/param.h>
#else
#	include <errno.h>
#	include "win32termios.h"
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdlib.h>

#ifdef HAVE_TERMIOS_H
#	include <termios.h>
#endif
#ifdef HAVE_SYS_FCNTL_H
#   include <sys/fcntl.h>
#endif
#ifdef HAVE_SYS_FILE_H
#   include <sys/file.h>
#endif
#ifdef HAVE_SYS_SIGNAL_H
#   include <sys/signal.h>
#endif
#if defined(__linux__)
#	include <linux/lp.h>
#endif
#if defined(__FreeBSD__)
/* #	include <machine/lpt.h> ? is this changed or wrong */
#	include <dev/ppbus/lpt.h>
#endif
#ifdef __unixware__
#	include  <sys/filio.h>
#endif

extern int errno;

#include "ParallelImp.h"

#define LPRPort(foo) Java_gnu_io_LPRPort_ ## foo
/* #define DEBUG */

/*----------------------------------------------------------
LPRPort.getOutputBufferFree
   accept:    none
   perform:
   return:    number of bytes available in buffer.
   exceptions: none
   comments:  have not seen how to do this in the kernel yet.
----------------------------------------------------------*/
JNIEXPORT jint JNICALL LPRPort(getOutputBufferFree)(JNIEnv *env,
	jclass jclazz)
{
	printf("getOutputBufferFree is not implemented yet\n");

	return(0);

}
/*----------------------------------------------------------
LPRPort.setLPRMode
   accept:     mode
   perform:    set the Printer communication mode
	LPT_MODE_ANY:     pick the best possible mode
	LPT_MODE_SPP:     compatibility mode/unidirectional
	LPT_MODE_PS2:     byte mode/bidirectional
	LPT_MODE_EPP:     extended parallel port
	LPT_MODE_ECP:     enhanced capabilities port
	LPT_MODE_NIBBLE:  Nibble Mode. Bi-directional. HP Bi-tronics.
	                  4 bits at a time.
   return:     none
   exceptions: UnsupportedCommOperationException
   comments:
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(setLPRMode)(JNIEnv *env,
	jclass jclazz, jint mode)
{
	switch(mode)
	{
		case LPT_MODE_ANY:
			break;
		case LPT_MODE_SPP:
		case LPT_MODE_PS2:
		case LPT_MODE_EPP:
		case LPT_MODE_ECP:
		case LPT_MODE_NIBBLE:
		default:
			throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
				"nativeSetSerialPortParams",
				"setLPRMode was unable to proced the requested \
				mode"
			);
	}
	return(JNI_TRUE);
}

#if defined (WIN32)

#define CTL_CODE( DeviceType, Function, Method, Access ) (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))

#define FILE_DEVICE_PARALLEL_PORT       0x00000016
#define METHOD_BUFFERED                 0
#define FILE_ANY_ACCESS                 0

#define IOCTL_PAR_QUERY_INFORMATION CTL_CODE(FILE_DEVICE_PARALLEL_PORT,1,METHOD_BUFFERED,FILE_ANY_ACCESS)

#define PARALLEL_INIT            0x1
#define PARALLEL_AUTOFEED        0x2
#define PARALLEL_PAPER_EMPTY     0x4
#define PARALLEL_OFF_LINE        0x8
#define PARALLEL_POWER_OFF       0x10
#define PARALLEL_NOT_CONNECTED   0x20
#define PARALLEL_BUSY            0x40
#define PARALLEL_SELECTED        0x80

int getWin32ParallelStatusFlags(int fd){
	int status = 0;
	DWORD count;
	if(!DeviceIoControl( (HANDLE)fd, IOCTL_PAR_QUERY_INFORMATION, NULL,0, &status, sizeof(status), &count, 0) && count == 1){
		YACK();
		return 0;
	}
#ifdef DEBUG
	printf("getWin32ParallelStatusFlags: %d\n", status );
#endif
	return status;
}

jboolean getWin32ParallelStatus(int fd, int flag){
	return( (getWin32ParallelStatusFlags(fd) & flag) ? JNI_TRUE : JNI_FALSE);
}
#endif

/*----------------------------------------------------------
LPRPort.isPaperOut
   accept:      none
   perform:     check if printer reports paper is out
   return:      Paper Out: JNI_TRUE  Not Paper Out: JNI_FALSE
   exceptions:  none
   comments:    LP_NOPA    unchanged out-of-paper input, active high
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(isPaperOut)(JNIEnv *env,
	jobject jobj)
{

	int fd = get_java_var( env, jobj,"fd","I" );
#if defined (__linux__)
	int status;
	ioctl(fd, LPGETSTATUS,&status);
	return( status & LP_NOPA ? JNI_TRUE : JNI_FALSE );
#elif defined (WIN32)
	return getWin32ParallelStatus( fd, PARALLEL_PAPER_EMPTY);
#else
/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS not defined\n");
	return(JNI_TRUE);
#endif
}
/*----------------------------------------------------------
LPRPort.isPrinterBusy
   accept:      none
   perform:     Check to see if the printer is printing.
   return:      JNI_TRUE if the printer is Busy, JNI_FALSE if its idle
   exceptions:  none
   comments:    LP_BUSY     inverted busy input, active high
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(isPrinterBusy)(JNIEnv *env,
	jobject jobj)
{
	int fd = get_java_var( env, jobj,"fd","I" );
	int status;
#if defined (__linux__)
	ioctl(fd, LPGETSTATUS, &status);
#elif defined (WIN32)
	return getWin32ParallelStatus( fd, PARALLEL_BUSY);
#else
/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS not defined\n");
#endif
#if defined(__linux__)
	return( status & LP_BUSY ? JNI_TRUE : JNI_FALSE );
#endif
#if defined(__FreeBSD__)
	return( status & EBUSY ? JNI_TRUE : JNI_FALSE );
#endif
	return(JNI_FALSE);
}
/*----------------------------------------------------------
LPRPort.isPrinterError
   accept:      none
   perform:     check for printer error
   return:      JNI_TRUE if there is an printer error otherwise JNI_FALSE
   exceptions:  none
   comments:    LP_ERR   unchanged error input, active low
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(isPrinterError)(JNIEnv *env,
	jobject jobj)
{
	int fd = get_java_var( env, jobj,"fd","I" );
#if defined (__linux__)
	int status;
	ioctl(fd, LPGETSTATUS, &status);
	return( status & LP_ERR ? JNI_TRUE : JNI_FALSE );
#elif defined (WIN32)
	return getWin32ParallelStatus( fd, PARALLEL_PAPER_EMPTY |
									   PARALLEL_OFF_LINE |
									   PARALLEL_POWER_OFF |
									   PARALLEL_NOT_CONNECTED |
									   PARALLEL_BUSY);
#else
/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS not defined\n");
	return(JNI_FALSE);
#endif
}
/*----------------------------------------------------------
LPRPort.isPrinterSelected
   accept:      none
   perform:     check if printer is selected
   return:      JNI_TRUE if printer is selected other wise JNI_FALSE
   exceptions:  none
   comments:    LP_SELEC   unchanged selected input, active high
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(isPrinterSelected)(JNIEnv *env,
	jobject jobj)
{
	int fd = get_java_var( env, jobj,"fd","I" );
#if defined (__linux__)
	int status;
	ioctl(fd, LPGETSTATUS, &status);
	return( status & LP_SELEC ? JNI_TRUE : JNI_FALSE );
#elif defined (WIN32)
	return getWin32ParallelStatus( fd, PARALLEL_SELECTED);
#else
/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS not defined\n");
	return(JNI_FALSE);
#endif
}
/*----------------------------------------------------------
LPRPort.isPrinterTimedOut
   accept:       none
   perform:      Not really sure see isPaperOut
   return:       JNI_FALSE if the printer does not return out of paper other
                 wise JNI_TRUE.
   exceptions:   none
   comments:     Is this documented right in the javadocs?
	         not sure this is correct FIXME
----------------------------------------------------------*/
JNIEXPORT jboolean JNICALL LPRPort(isPrinterTimedOut)(JNIEnv *env,
	jobject jobj)
{
#if defined(__linux__)
	int fd = get_java_var( env, jobj,"fd","I" );
	int status;
	ioctl(fd, LPGETSTATUS, &status);
	return( status & LP_BUSY ? JNI_TRUE : JNI_FALSE );
#endif
#if defined(__FreeBSD__)
	printf("ParallelImp.c LPGETSTATUS not defined\n");
	/*
	return( status & EBUSY ? JNI_TRUE : JNI_FALSE );
	*/
#endif
	return( JNI_FALSE );
}

/*----------------------------------------------------------
LPRPort.Initialize

   accept:      none
   perform:     Initialize the native library
   return:      none
   comments:    lots of reading to do here. FIXME
----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(Initialize)( JNIEnv *env,
	jclass jclazz )
{
	/* This bit of code checks to see if there is a signal handler installed
	   for SIGIO, and installs SIG_IGN if there is not.  This is necessary
		for the native threads jdk, but we don't want to do it with green
		threads, because it slows things down.  Go figure. */
#if !defined(WIN32)
	struct sigaction handler;
	sigaction( SIGIO, NULL, &handler );
	if( !handler.sa_handler ) signal( SIGIO, SIG_IGN );
#endif /* !WIN32 */
}

/*----------------------------------------------------------
LPRPort.open

   accept:      The device to open.  ie "/dev/lp0"
   perform:     open the device and return the filedescriptor
   return:      fd
   exceptions:  PortInUseException
   comments:    Very often people complain about not being able to get past
                this function and it turns out to be permissions on the
                device file or bios has the device disabled.
		FIXME  Lock Files?
----------------------------------------------------------*/
JNIEXPORT jint JNICALL LPRPort(open)( JNIEnv *env, jobject jobj,
	jstring jstr )
{
	/*struct termios ttyset;*/
	const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 );
#ifdef WIN32
	int fd = (int)CreateFile( filename, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 );
#else
	int fd = open( filename, O_RDWR | O_NONBLOCK );
#endif
	(*env)->ReleaseStringUTFChars( env, jstr, NULL );
	if( fd < 0 ) goto fail;
	return (jint)fd;

fail:
	throw_java_exception_system_msg( env, PORT_IN_USE_EXCEPTION, "open" );
	return -1;
}

/*----------------------------------------------------------
LPRPort.nativeClose

   accept:      none
   perform:     get the fd from the java end and close it
   return:      none
   exceptions:  none
----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(nativeClose)( JNIEnv *env,
	jobject jobj )
{
	int fd = get_java_var( env, jobj,"fd","I" );

#ifdef WIN32
	CloseHandle( (HANDLE)fd );
#else
	close( fd );
#endif
	return;
}

/*----------------------------------------------------------
LPRPort.writeByte

   accept:      byte to write (passed as int)
   perform:     write a single byte to the port
   return:      none
   exceptions:  IOException
----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(writeByte)( JNIEnv *env,
	jobject jobj, jint ji )
{
	unsigned char byte = (unsigned char)ji;
	int fd = get_java_var( env, jobj,"fd","I" );

#ifdef WIN32
	DWORD countWritten; /* Fixme, should be a loop until all is written */
	if( WriteFile( (HANDLE)fd, &byte, sizeof( unsigned char ), &countWritten, NULL ) < 0 ) return;
#else
	if( write( fd, &byte, sizeof( unsigned char ) ) >= 0 ) return;
#endif
	throw_java_exception_system_msg( env, IO_EXCEPTION, "writeByte" );
}

/*----------------------------------------------------------
LPRPort.writeArray

   accept:      jbarray: bytes used for writing
                offset: offset in array to start writing
                count: Number of bytes to write
   perform:     write length bytes of jbarray
   return:      none
   exceptions:  IOException
----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(writeArray)( JNIEnv *env,
	jobject jobj, jbyteArray jbarray, jint offset, jint count )
{
#ifdef WIN32
	DWORD countWritten; /* Fixme, should be a loop until all is written */
	COMMTIMEOUTS timeouts;
	int errorCount = 0;
#endif
	int fd = get_java_var( env, jobj,"fd","I" );
	jbyte *body = (*env)->GetByteArrayElements( env, jbarray, 0 );
	unsigned char *bytes = (unsigned char *)malloc( count );
	int i;
	for( i = 0; i < count; i++ ) bytes[ i ] = body[ i + offset ];
	(*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
#ifdef WIN32
	/*
	we set a timeout because all calls are sequentiell (also with asynchron)
	 this means that the default timeout of unlimited
	blocks all calls (also close and status request) if the device is down
	*/
	GetCommTimeouts( (HANDLE)fd, &timeouts );
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 2000; /*  2000 is the min value for the default Windows NT and Windows 2000 driver */
	SetCommTimeouts( (HANDLE)fd, &timeouts );
	while( count > 0 ){
		if(!WriteFile( (HANDLE)fd, bytes, count, &countWritten, NULL ) && countWritten == 0){
			/*
			this are 20 * 2 seconds, in this time a printer (or other parallel device)
			should solv all problems like buffer full, etc
			*/
			if(errorCount++ < 20){
				Sleep( 20 ); /* make a small pause to execute all other requests in all other threads */
				continue;
			}
			throw_java_exception_system_msg( env, IO_EXCEPTION, "writeArray" );
			break;
		}
		errorCount = 0;
		bytes += countWritten;
		count -= countWritten;
	}
#else
	if( write( fd, bytes, count ) < 0 )
		throw_java_exception_system_msg( env, IO_EXCEPTION, "writeArray" );
#endif
	free( bytes );
}

/*----------------------------------------------------------
read_byte_array

   accept:      int                fd   file descriptor to read from
                unsigned char *buffer   buffer to read data into
                int            length   number of bytes to read
                int         threshold   receive threshold
                int           timeout   milliseconds to wait before returning
   perform:     read bytes from the port into a buffer
   return:      status of read
                -1 fail (IOException)
                 0 timeout
                >0 number of bytes read
   comments:    According to the Communications API spec, a receive threshold
                of 1 is the same as having the threshold disabled.
----------------------------------------------------------*/
int read_byte_array( int fd, unsigned char *buffer, int length, int threshold,
	int timeout )
{
	int ret, left, bytes = 0;
	fd_set rfds;
	struct timeval sleep;

	FD_ZERO( &rfds );
	FD_SET( fd, &rfds );
	sleep.tv_sec = timeout / 1000;
	sleep.tv_usec = 1000 * ( timeout % 1000 );
	left = length;

	while( bytes < length && bytes < threshold )
	{
		if( timeout > 0 )
		{
         /* FIXME: In Linux, select updates the timeout automatically, so
            other OSes will need to update it manually if they want to have
            the same behavior.  For those OSes, timeouts will occur after no
            data AT ALL is received for the timeout duration.  No big deal. */
			do {
				ret=select( fd + 1, &rfds, NULL, NULL, &sleep );
			} while(ret < 0 && errno ==EINTR);
			if( ret == 0 ) break;
			if( ret < 0 ) return -1;
		}
#if defined(WIN32)
		if(!ReadFile( (HANDLE)fd, buffer + bytes, left, (DWORD *)&ret, NULL )){
			YACK();
			ret = -1;
		}
#else
		ret = read( fd, buffer + bytes, left );
#endif
		if( ret == 0 ) break;
		if( ret < 0 ) return -1;
		bytes += ret;
		left -= ret;
	}
	return bytes;
}

/*----------------------------------------------------------
LPRPort.readByte

   accept:      none
   perform:     Read a single byte from the port
   return:      The byte read
   exceptions:  IOException
----------------------------------------------------------*/
JNIEXPORT jint JNICALL LPRPort(readByte)( JNIEnv *env,
	jobject jobj )
{
	int bytes, fd, timeout;
	unsigned char buffer[ 1 ];

	fd = get_java_var( env, jobj,"fd","I" );
	timeout = get_java_var( env, jobj, "timeout","I");

	bytes = read_byte_array( fd, buffer, 1, 1, timeout );
	if( bytes < 0 )
	{
		throw_java_exception_system_msg( env, IO_EXCEPTION, "readByte" );

		return -1;
	}
	return (bytes ? (jint)buffer[ 0 ] : -1);
}

/*----------------------------------------------------------
LPRPort.readArray

   accept:       offset (bytes to skip) and Length (bytes to read)
   perform:      read bytes from the port into a byte array
   return:       bytes read on success
                 0 on read timeout
   exceptions:   IOException
   comments:     throws IOException if asked to read > SSIZE_MAX
----------------------------------------------------------*/
JNIEXPORT jint JNICALL LPRPort(readArray)( JNIEnv *env,
	jobject jobj, jbyteArray jbarray, jint offset, jint length )
{
	int bytes, i, fd, threshold, timeout;
	jbyte *body;
	unsigned char *buffer;
	fd = get_java_var( env, jobj,"fd","I" );
	threshold = get_java_var( env, jobj,"threshold","I" );
	timeout = get_java_var( env, jobj,"threshold","I" );

	if( (size_t) length < 1 || (size_t) length > SSIZE_MAX )
	{
		throw_java_exception( env, IO_EXCEPTION, "readArray",
			"Invalid length" );
		return -1;
	}

	buffer = (unsigned char *)malloc( sizeof( unsigned char ) * length );
	if( buffer == 0 )
	{
		throw_java_exception( env, IO_EXCEPTION, "readArray",
			"Unable to allocate buffer" );

		return -1;
	}

	bytes = read_byte_array( fd, buffer, length, threshold, timeout );
	if( bytes < 0 )
	{
		free( buffer );
		throw_java_exception_system_msg( env, IO_EXCEPTION, "readArray" );

		return -1;
	}

	body = (*env)->GetByteArrayElements( env, jbarray, 0 );
	for( i = 0; i < bytes; i++ ) body[ i + offset ] = buffer[ i ];
	(*env)->ReleaseByteArrayElements( env, jbarray, body, 0 );
	free( buffer );
	return (bytes ? bytes : -1);
}

/*----------------------------------------------------------
LPRPort.nativeavailable

   accept:      none
   perform:     find out the number of bytes available for reading
   return:      available bytes
                -1 on error
   exceptions:  none
----------------------------------------------------------*/
JNIEXPORT jint JNICALL LPRPort(nativeavailable)( JNIEnv *env,
	jobject jobj )
{
	int fd = get_java_var( env, jobj,"fd","I" );
	int result;
/*
	char message[80];

	ENTER( "LPRPort:nativeavailable" );
*/
/*
    On SCO OpenServer FIONREAD always fails for serial devices,
    so try ioctl FIORDCHK instead; will only tell us whether
    bytes are available, not how many, but better than nothing.

    This turns out to be true on Solaris also.  taj.
*/
#ifdef FIORDCHK  /* __unixware__ __sun__ probably others */
	result = ioctl(fd, FIORDCHK, 0);
#else
	if( ioctl( fd, FIONREAD, &result ) < 0 )
	{
		goto fail;
	}
#endif /* FIORDCHK */
	if (result == -1) {
		goto fail;
	}
	if( result )
	{
/*		sprintf(message, "    nativeavailable: FIORDCHK result %d, \
				errno %d\n", result , result == -1 ? errno : 0);
		report( message );
*/
	}
/*
	LEAVE( "LPRPort:nativeavailable" );
*/
	return (jint)result;
fail:
/*
	report("LPRPort:nativeavailable:  ioctl() failed\n");
	LEAVE( "LPRPort:nativeavailable" );
*/
	throw_java_exception_system_msg( env, IO_EXCEPTION, "nativeavailable" );
	return (jint)result;
}

/*----------------------------------------------------------
LPRPort.setHWFC

   accept:      state (JNI_FALSE 0, JNI_TRUE 1)
   perform:     set hardware flow control to state
   return:      none
   exceptions:  IOException
----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(setHWFC)( JNIEnv *env,
	jobject jobj, jboolean state )
{
	/* int fd = get_java_var( env, jobj,"fd","I" ); */
	return;
}

/*----------------------------------------------------------
LPRPort.eventLoop

   accept:      none
   perform:     periodically check for ParallelPortEvents
   return:      none
   exceptions:  none
   comments:    lots of work needed here.  Yes its a mess.
struct lp_stats
{
	unsigned long chars;
	unsigned long sleeps;
	unsigned int maxrun;
	unsigned int maxwait;
	unsigned int meanwait;
	unsigned int mdev;
};

----------------------------------------------------------*/
JNIEXPORT void JNICALL LPRPort(eventLoop)( JNIEnv *env,
	jobject jobj )
{
	int fd, ret;
	unsigned int pflags = 0;
	fd_set rfds;
	struct timeval sleep;
	jboolean interrupted = 0;

	fd = get_java_var( env, jobj,"fd","I" );

	interrupted = is_interrupted(env, jobj);

	FD_ZERO( &rfds );
	while( !interrupted )
	{
		FD_SET( fd, &rfds );
		/* Check every 1 second, or on receive data */
		sleep.tv_sec = 1;
		sleep.tv_usec = 0;
		do {
			ret = select( fd + 1, &rfds, NULL, NULL, &sleep );
		}
		while (ret < 0 && errno == EINTR);
		if( ret < 0 ) break;
		interrupted = is_interrupted(env, jobj);
		if(interrupted) {
			return;
		}

#if defined(LPGETSTATUS)
		ioctl( fd, LPGETSTATUS, &pflags );
#elif defined(WIN32)
		pflags = getWin32ParallelStatusFlags(fd);
#else
	/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS is undefined!\n");
#endif

/*
			PAR_EV_BUFFER:
			PAR_EV_ERROR:
*/

#if defined(PARALLEL_BUSY)
		if (pflags & PARALLEL_BUSY)
			send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
#elif defined(LP_BUSY)
		if (pflags&LP_BUSY)    /* inverted input, active high */
			send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
#elif defined(EBUSY)
		if (pflags&EBUSY)    /* inverted input, active high */
			send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
#endif /* EBUSY LP_BUSY */
/*  FIXME  this has moved into the ifdef __kernel__?  Need to get the
           posix documentation on this.
		if (pflags&LP_ACK)
			send_event( env, jobj, PAR_EV_ERROR, JNI_TRUE );
*/

#if defined (__linux__)
		/* unchanged input, active low */
		if (pflags&LP_NOPA)   /* unchanged input, active high */
			send_event( env, jobj, PAR_EV_ERROR, 1 );
		if (pflags&LP_SELEC)  /* unchanged input, active high */
			send_event( env, jobj, PAR_EV_ERROR, 1 );
		if (pflags&LP_ERR)  /* unchanged input, active low */
			send_event( env, jobj, PAR_EV_ERROR, 1 );
#else
	/*  FIXME??  */
	printf("ParallelImp.c LPGETSTATUS is undefined!\n");
#endif
		usleep(1000);
	}
	return;
}

JNIEXPORT void JNICALL LPRPort(setInputBufferSize)(JNIEnv *env,
	jobject jobj, jint size )
{
#ifdef DEBUG
	printf("setInputBufferSize is not implemented\n");
#endif
}
JNIEXPORT jint JNICALL LPRPort(getInputBufferSize)(JNIEnv *env,
	jobject jobj)
{
#ifdef DEBUG
	printf("getInputBufferSize is not implemented\n");
#endif
	return(1);
}
JNIEXPORT void JNICALL LPRPort(setOutputBufferSize)(JNIEnv *env,
	jobject jobj, jint size )
{
#ifdef DEBUG
	printf("setOutputBufferSize is not implemented\n");
#endif
}
JNIEXPORT jint JNICALL LPRPort(getOutputBufferSize)(JNIEnv *env,
	jobject jobj)
{
#ifdef DEBUG
	printf("getOutputBufferSize is not implemented\n");
#endif
	return(1);
}

/*----------------------------------------------------------
throw_java_exception

   accept:      env (keyhole to java)
                *exc (exception class name)
                *foo (function name)
                *msg (error message)
   perform:     Throw a new java exception
   return:      none
   exceptions:  haha!
   comments:
----------------------------------------------------------*/
void throw_java_exception( JNIEnv *env, char *exc, char *foo, char *msg )
{
#define MSG_SIZE 128
	char buf[ 128 ];
	jclass clazz = (*env)->FindClass( env, exc );
	if( !clazz )
	{
		(*env)->ExceptionDescribe( env );
		(*env)->ExceptionClear( env );
		return;
	}
	/* reduce the message size if it to large for the message buffer */
	if(MSG_SIZE < (strlen( msg ) + strlen(foo) + 5)){
		msg[ MSG_SIZE - strlen(foo) - 5] = 0;
	}
#if defined(_GNU_SOURCE)
	snprintf( buf, 60, "%s in %s", msg, foo );
#else
	sprintf( buf,"%s in %s", msg, foo );
#endif /* _GNU_SOURCE */
	(*env)->ThrowNew( env, clazz, buf );
/* ct7 * Added DeleteLocalRef */
	(*env)->DeleteLocalRef( env, clazz );
}

void throw_java_exception_system_msg( JNIEnv *env, char *exc, char *foo )
{
#ifdef WIN32
	char *allocTextBuf;
	FormatMessage (
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPSTR)&allocTextBuf,
		16,
		NULL );
	throw_java_exception( env, exc, foo, allocTextBuf );
	LocalFree(allocTextBuf);
#else
	throw_java_exception( env, exc, foo, strerror( errno ) );
#endif
}
/*----------------------------------------------------------
 report_error

   accept:      string to send to report as an error
   perform:     send the string to stderr or however it needs to be reported.
   return:      none
   exceptions:  none
   comments:
----------------------------------------------------------*/
void report_error(char *msg)
{
#ifndef DEBUG_MW
	fprintf(stderr, msg);
#else
	mexWarnMsgTxt( msg );
#endif /* DEBUG_MW */
}

/*----------------------------------------------------------
 report

   accept:      string to send to stderr
   perform:     if DEBUG is defined send the string to stderr.
   return:      none
   exceptions:  none
   comments:
----------------------------------------------------------*/
void report(char *msg)
{
#ifdef DEBUG
        fprintf(stderr, msg);
#endif /* DEBUG */
}

/*----------------------------------------------------------
 is_interrupted

   accept:
   perform:     see if the port is being closed.
   return:      a positive value if the port is being closed.
   exceptions:  none
   comments:
----------------------------------------------------------*/
jboolean is_interrupted(JNIEnv *env, jobject jobj)
{
	jmethodID foo;
	jclass jclazz;
	int result;

	(*env)->ExceptionClear(env);

	jclazz = (*env)->GetObjectClass( env, jobj );
	if(jclazz == NULL) return JNI_TRUE;

	foo = (*env)->GetMethodID( env, jclazz, "checkMonitorThread", "()Z");
	if(foo == NULL) return JNI_TRUE;

	result = (*env)->CallBooleanMethod( env, jobj, foo );

#ifdef DEBUG
	if((*env)->ExceptionOccurred(env)) {
		report ("an error occured calling sendEvent()\n");
		(*env)->ExceptionDescribe(env);
		(*env)->ExceptionClear(env);
	}
#endif /* DEBUG */
	(*env)->DeleteLocalRef( env, jclazz );

	return(result);
}
/*----------------------------------------------------------
 send_event

   accept:      The event type and the event state
   perform:     if state is > 0 send a JNI_TRUE event otherwise send JNI_FALSE
   return:      a positive value if the port is being closed.
   exceptions:  none
   comments:
----------------------------------------------------------*/
int send_event(JNIEnv *env, jobject jobj, jint type, int flag)
{
	int result;
	jmethodID foo;
	jclass jclazz = (*env)->GetObjectClass( env, jobj );

	if(jclazz == NULL) return JNI_TRUE;
	foo = (*env)->GetMethodID( env, jclazz, "sendEvent", "(IZ)Z" );

	(*env)->ExceptionClear(env);

	result = (*env)->CallBooleanMethod( env, jobj, foo, type,
		flag > 0 ? JNI_TRUE : JNI_FALSE );

#ifdef DEBUG
	if((*env)->ExceptionOccurred(env)) {
		report ("an error occured calling sendEvent()\n");
		(*env)->ExceptionDescribe(env);
		(*env)->ExceptionClear(env);
	}
#endif /* DEBUG */
	(*env)->DeleteLocalRef( env, jclazz );
	return(result);
}
/*----------------------------------------------------------
get_java_var

   accept:      env (keyhole to java)
                jobj (java RXTXPort object)

   return:      the fd field from the java object
   exceptions:  none
   comments:
----------------------------------------------------------*/
int get_java_var( JNIEnv *env, jobject jobj, char *id, char *type )
{
	int result = 0;
	jclass jclazz = (*env)->GetObjectClass( env, jobj );
	jfieldID jfd = (*env)->GetFieldID( env, jclazz, id, type );
	if( !jfd )
	{
		(*env)->ExceptionDescribe( env );
		(*env)->ExceptionClear( env );
		return result;
	}
	result = (int)( (*env)->GetIntField( env, jobj, jfd ) );
/* ct7 & gel * Added DeleteLocalRef */
	(*env)->DeleteLocalRef( env, jclazz );
	return result;
}


text:
//-----------------------------------------------------------------------
// <copyright file="EntityTests.cs" company="Patrick Ricky Smith">
//  This file is part of the Twitterizer library (http://www.twitterizer.net/)
//
//  Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are
//  permitted provided that the following conditions are met:
//
//  - Redistributions of source code must retain the above copyright notice, this list
//    of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//  - Neither the name of the Twitterizer nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <author>Ricky Smith</author>
// Test class for entities.
//-----------------------------------------------------------------------

using System.Linq;
using NUnit.Framework;
using Twitterizer;
using Twitterizer.Entities;

namespace Twitterizer2.TestCases
{
    [TestFixture]
    public class EntityTests
    {
        [Test]
        public static void LinkifyText()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            var StatusResult = TwitterStatus.Show(tokens, 10506615291641857);
            Assert.IsNotNull(StatusResult);
            Assert.That(StatusResult.Result == RequestResult.Success);
            Assert.IsNotNull(StatusResult.ResponseObject);

            if (StatusResult.ResponseObject.Entities == null)
                return;

            string linkedText = StatusResult.ResponseObject.Text;

            var entitiesSorted = StatusResult.ResponseObject.Entities.OrderBy(e => e.StartIndex).Reverse();

            foreach (TwitterEntity entity in entitiesSorted)
            {
                if (entity is TwitterHashTagEntity)
                {
                    TwitterHashTagEntity tagEntity = (TwitterHashTagEntity)entity;

                    linkedText = string.Format(
                        "{0}{1}{2}",
                        linkedText.Substring(0, entity.StartIndex),
                        tagEntity.Text,
                        linkedText.Substring(entity.EndIndex));
                }

                if (entity is TwitterUrlEntity)
                {
                    TwitterUrlEntity urlEntity = (TwitterUrlEntity)entity;

                    linkedText = string.Format(
                        "{0}{1}{2}",
                        linkedText.Substring(0, entity.StartIndex),
                        urlEntity.Url,
                        linkedText.Substring(entity.EndIndex));
                }

                if (entity is TwitterMentionEntity)
                {
                    TwitterMentionEntity mentionEntity = (TwitterMentionEntity)entity;

                    linkedText = string.Format(
                        "{0}@{1}{2}",
                        linkedText.Substring(0, entity.StartIndex),
                        mentionEntity.ScreenName,
                        linkedText.Substring(entity.EndIndex));
                }
            }
        }

        [Test]
        public static void BuiltInLinkify()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            var StatusResult = TwitterStatus.Show(tokens, 10506615291641857);
            Assert.IsNotNull(StatusResult);
            Assert.That(StatusResult.Result == RequestResult.Success);
            Assert.IsNotNull(StatusResult.ResponseObject);

            /*string linkifiedText =*/ StatusResult.ResponseObject.LinkifiedText();
        }
    }
}


text:
package org.clulab.odin

import java.io._
import java.nio.charset.{ StandardCharsets, MalformedInputException }
import org.clulab.odin._
import org.scalatest._

class TestExtractorEngine extends FlatSpec with Matchers {

  "ExtractorEngine" should "read utf8 encoded data" in {
    var stream = getClass.getResourceAsStream("/org/clulab/odin/master_utf8.yml")
    lazy val engine = ExtractorEngine.fromStream(stream, new Actions, identityAction, StandardCharsets.UTF_8)
    noException should be thrownBy engine
    engine.extractors.head.name should equal ("lingüística")
  }

  it should "read latin1 encoded data" in {
    val stream = getClass.getResourceAsStream("/org/clulab/odin/master_latin1.yml")
    lazy val engine = ExtractorEngine.fromStream(stream, new Actions, identityAction, StandardCharsets.ISO_8859_1)
    noException should be thrownBy engine
    engine.extractors.head.name should equal ("lingüística")
  }

  it should "fail with an exception when byte sequence is not valid for given charset" in {
    var stream = getClass.getResourceAsStream("/org/clulab/odin/master_latin1.yml")
    lazy val engine = ExtractorEngine.fromStream(stream, new Actions, identityAction, StandardCharsets.UTF_8)
    a [MalformedInputException] should be thrownBy engine
  }

  it should "read data incorrectly if using the wrong charset" in {
    val stream = getClass.getResourceAsStream("/org/clulab/odin/master_utf8.yml")
    val engine = ExtractorEngine.fromStream(stream, new Actions, identityAction, StandardCharsets.ISO_8859_1)
    engine.extractors.head.name should not equal ("lingüística")
  }

}


text:
module CandyWrapper
  VERSION = "0.0.1"
end


text:
from google.cloud import eventarc_publishing_v1

async def sample_publish_events():
    # Create a client
    client = eventarc_publishing_v1.PublisherAsyncClient()

    # Initialize request argument(s)
    request = eventarc_publishing_v1.PublishEventsRequest(
    )

    # Make the request
    response = await client.publish_events(request=request)

    # Handle the response
    print(response)

# [END eventarcpublishing_v1_generated_Publisher_PublishEvents_async]


text:
package com.xinfan.blueblue.util;

import java.util.Calendar;
import java.util.TimeZone;

public class CalendarUtils
{
  private static final int MILLIS_SECONDS_UNIT = 1000;

  public static Calendar getCalendar(long paramLong)
  {
    Calendar localCalendar = Calendar.getInstance();
    localCalendar.setTimeZone(TimeZone.getDefault());
    localCalendar.setTimeInMillis(1000L * paramLong);
    return localCalendar;
  }

  public static Calendar getCalendar(String paramString1, String paramString2)
  {
    Calendar localCalendar = Calendar.getInstance();
    localCalendar.setTime(DateUtil.getDate(paramString1, paramString2));
    return localCalendar;
  }

  public static int getDateOfYear(Calendar paramCalendar)
  {
    return paramCalendar.get(6);
  }

  public static int getHourOfDay(Calendar paramCalendar)
  {
    return paramCalendar.get(11);
  }

  public static int getMinute(Calendar paramCalendar)
  {
    return paramCalendar.get(12);
  }

  public static Calendar getSystemCalendar()
  {
    Calendar localCalendar = Calendar.getInstance();
    localCalendar.setTime(DateUtil.getSystemDate());
    return localCalendar;
  }

  public static int getYear(Calendar paramCalendar)
  {
    return paramCalendar.get(1);
  }
}


text:
import React, { PureComponent } from 'react';
import { Tab, TabList } from 'binary-components';

export default class JpTradeTypesPicker extends PureComponent {

    render() {
        return (
            <TabList>
                <Tab text="Higher/Lower" />
                <Tab text="Touch/No Touch" />
                <Tab text="Ends In/Out" />
                <Tab text="Stays In/Goes Out" />
            </TabList>
        );
    }
}


text:
@if "%_echo%" neq "on" echo off
setlocal

:: Note: We've disabled node reuse because it causes file locking issues.
::       The issue is that we extend the build with our own targets which
::       means that that rebuilding cannot successfully delete the task
::       assembly.

:ReadArguments
:: Read in the args to determine whether to run the native build, managed build, or both (default)
set "__args=%*"
if /i [%1] == [native] (set __buildSpec=native&&set "__args=%__args:~6%"&&shift&&goto Tools)
if /i [%1] == [managed] (set __buildSpec=managed&&set "__args=%__args:~7%"&&shift&&goto Tools)

:Tools
:: Setup VS
if not defined VisualStudioVersion (
    if defined VS140COMNTOOLS (
        call "%VS140COMNTOOLS%\VsDevCmd.bat"
        goto :Build
    )

    echo Error: build.cmd requires Visual Studio 2015.
    echo        Please see https://github.com/dotnet/corefx/blob/master/Documentation/project-docs/developer-guide.md for build instructions.
    exit /b 1
)

:Build
:: Restore the Tools directory
call %~dp0init-tools.cmd

:: Call the builds
if "%__buildSpec%"=="managed"  goto :BuildManaged

:BuildNative
:: Run the Native Windows build
echo [%time%] Building Native Libraries...
IF EXIST "%~dp0src\native\Windows\build-native.cmd" (
    call %~dp0src\native\Windows\build-native.cmd %__args% >nativebuild.log
    IF ERRORLEVEL 1 (
        echo Native component build failed see nativebuild.log for more details.
    ) else (
        echo [%time%] Successfully built Native Libraries.
    )
)

:: If we only wanted to build the native components, exit
if "%__buildSpec%"=="native" goto :eof

:BuildManaged
:: Clear the 'Platform' env variable for this session,
:: as it's a per-project setting within the build, and
:: misleading value (such as 'MCD' in HP PCs) may lead
:: to build breakage (issue: #69).
set Platform=

:: Log build command line
set _buildproj=%~dp0build.proj
set _buildlog=%~dp0msbuild.log
set _binclashLoggerDll=%~dp0Tools\net45\Microsoft.DotNet.Build.Tasks.dll
set _binclashlog=%~dp0binclash.log
set _buildprefix=echo
set _buildpostfix=^> "%_buildlog%"
call :build %__args%

:: Build
set _buildprefix=
set _buildpostfix=
echo [%time%] Building Managed Libraries...
call :build %__args%

goto :AfterBuild

:build
%_buildprefix% msbuild "%_buildproj%" /nologo /maxcpucount /v:minimal /clp:Summary /nodeReuse:false /flp:v=normal;LogFile="%_buildlog%";Append "/l:BinClashLogger,%_binclashLoggerDll%;LogFile=%_binclashlog%" %__args% %_buildpostfix%
set BUILDERRORLEVEL=%ERRORLEVEL%
goto :eof

:AfterBuild

echo.
:: Pull the build summary from the log file
findstr /ir /c:".*Warning(s)" /c:".*Error(s)" /c:"Time Elapsed.*" "%_buildlog%"
echo [%time%] Build Exit Code = %BUILDERRORLEVEL%

exit /b %BUILDERRORLEVEL%


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#if STDC_HEADERS
# include <stdlib.h>
# include <string.h>
#elif HAVE_STRINGS_H
# include <strings.h>
#endif /*STDC_HEADERS*/

#if HAVE_UNISTD_H
# include <unistd.h>
# include <sys/types.h>
#endif

#include <errno.h>
#include <stdio.h>
#include <fcntl.h>

#include "mplib.h"
#include "xmalloc.h"

/*******************************************************************************************
 *                                    Parse functions
 *******************************************************************************************/

 id3_text_content*
 mp_parse_artist(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_text_content*
 mp_parse_title(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_text_content*
 mp_parse_album(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_text_content*
 mp_parse_year(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_text_content*
 mp_parse_genre(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_text_content*
 mp_parse_track(const id3_content* content)
 {
	 return mp_parse_text(content);
 }

 id3_comment_content*
 mp_parse_comment(const id3_content* content)
 {
	 id3_comment_content* cc;
	 int i, e;

	 if(!content || !content->data)
	 {
		 errno = MP_EERROR;
		 return NULL;
	 }

	 if(content->encrypted)
	 {
		 errno = MP_EFENCR;
		 return NULL;
	 }
	 if(content->compressed)
	 {
		 errno = MP_EFCOMPR;
		 return NULL;
	 }

	 cc = XMALLOCD0(id3_comment_content, "mp_parse_comment:cc");

	 e = content->data[0];
	 if(e >= ISO_8859_1 && e <= UTF8) cc->encoding = e;
	 else cc->encoding = 0;

	 cc->language = xmallocd(4, "mp_parse_comment:cc->language");
	 cc->language[0] = content->data[1];
	 cc->language[1] = content->data[2];
	 cc->language[2] = content->data[3];
	 cc->language[3] = 0;

	 if(content->data[4]) /* short descr. */
	 {
		 i = strlen(content->data + 4) + 1;
		 cc->short_descr = xmallocd(i, "mp_parse_comment:cc->short_descr");
		 strncpy(cc->short_descr, content->data + 4, i);
	 }
	 else
	 {
		 cc->short_descr = NULL;
		 i = 1;
	 }

	 if((int)(content->length - 4 - i) > 0)
	 {
		 cc->text = xmallocd(content->length - 4 - i + 1, "mp_parse_comment:cc->text");
		 memcpy(cc->text, content->data + 4 + i, content->length - 4 - i);
		 cc->text[content->length - 4 - i] = 0;
	 }
	 else
	 {
		 cc->text = NULL;
		 mp_free_comment_content(cc);
		 cc = NULL;
	 }

	 return cc;
 }

 id3_text_content*
 mp_parse_text(const id3_content* content)
 {
	 id3_text_content* tc;
	 int e;

	 if(!content || !content->data)
	 {
		 errno = MP_EERROR;
		 return NULL;
	 }

	 if(content->encrypted)
	 {
		 errno = MP_EFENCR;
		 return NULL;
	 }
	 if(content->compressed)
	 {
		 errno = MP_EFCOMPR;
		 return NULL;
	 }

	 tc = XMALLOCD0(id3_text_content, "mp_parse_text:tc");
	 tc->text = xmallocd(content->length, "mp_parse_text:tc->text");
	 e = content->data[0];
	 if(e >= ISO_8859_1 && e <= UTF8) tc->encoding = e;
	 else tc->encoding = 0;

	 memcpy(tc->text, content->data + 1, content->length - 1);
	 tc->text[content->length - 1] = 0;
	 /* XXX multiple entries */
	 return tc;
 }

 /*******************************************************************************************
 *                                    Assemble functions
 *******************************************************************************************/

 id3_content*
 mp_assemble_artist_content(const char* text, id3_encoding enc)
 {
	 return mp_assemble_text_content(text, enc);
 }

 id3_content*
 mp_assemble_title_content(const char* text, id3_encoding enc)
 {
	 return mp_assemble_text_content(text, enc);
 }

 id3_content*
 mp_assemble_album_content(const char* text, id3_encoding enc)
 {
	 return mp_assemble_text_content(text, enc);
 }

 id3_content*
 mp_assemble_year_content(const char* text, id3_encoding enc)
 {
	 return mp_assemble_text_content(text, enc);
 }

 id3_content*
 mp_assemble_genre_content(const char* text, id3_encoding enc)
 {
	 return mp_assemble_text_content(text, enc);
 }

 id3_content*
 mp_assemble_text_content(const char* text, id3_encoding enc)
 {
	 id3_content *ret;

	 if(!text) return NULL;

	 ret = XMALLOCD0(id3_content, "mp_assemble_text_content:ret");
	 ret->length = strlen(text) + 1;
	 ret->data = xmallocd(ret->length, "mp_asseble_text_content:ret->data");
	 ret->data[0] = enc;
	 strncpy(ret->data + 1, text, strlen(text));

	 return ret;
 }

 id3_content*
 mp_assemble_comment_content(const char* text, const char* short_descr, id3_encoding enc, const char* lang)
 {
	 id3_content *ret;

	 if(!text) return NULL;

	 ret = XMALLOCD0(id3_content, "mp_assemble_comment_content:ret");
	 ret->length = strlen(text) + 5;
	 if(short_descr) ret->length += strlen(short_descr);

	 ret->data = xmallocd(ret->length, "mp_assemble_comment_content:ret->data");
	 ret->data[0] = enc;
	 if(lang && strlen(lang) == 3)
	 {
		 ret->data[1] = lang[0];
		 ret->data[2] = lang[1];
		 ret->data[3] = lang[2];
	 }
	 else
	 {
		 ret->data[1] = 'X';
		 ret->data[2] = 'X';
		 ret->data[3] = 'X';
	 }
	 if(short_descr) strcpy(ret->data + 4, short_descr);
	 else ret->data[4] = 0;

	 if(short_descr) strncpy(ret->data + 5 + strlen(short_descr), text, strlen(text));
	 else strncpy(ret->data + 5, text, strlen(text));

	 return ret;

 }


text:
<?xml version="1.0" encoding="utf-8"?>

<?xml-stylesheet href="http://waterboard.lk/web/plugins/system/osolcaptcha/osolCaptcha/captchaStyle.css" type="text/css"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>Progress Monitoring</title>
		<description><![CDATA[National Water Supply and Drainage Board]]></description>
		<link>http://waterboard.lk/web/index.php?option=com_content&view=category&id=34&Itemid=293&lang=en</link>
		<lastBuildDate>Mon, 19 Oct 2015 18:11:42 +0000</lastBuildDate>
		<generator>Joomla! - Open Source Content Management</generator>
		<atom:link rel="self" type="application/rss+xml" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=34&Itemid=293&lang=en&format=feed&type=rss"/>
		<language>en-gb</language>
		<managingEditor>donotreply@waterboard.lk (National Water Supply and Drainage Board)</managingEditor>
		<item>
			<title>Contact Us</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=100&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=100&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[

RSC(WC) Office

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. M.K.Hapuarachchi
DGM
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
dgmwc
@waterboard.lk
+94 11 2812672
+94 11 2812671
+94 77 3295825
+94 2843596

Mrs. M.T.D.Abeywardana
AGM (Development)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
agmdevwc
@waterboard.lk
+94 11 2812672
+94 11 2856420-2
+94 77 7562373

Mr. A.K. Kapuruge
AGM (O&M)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
agmonmwc
@waterboard.lk
+94 11 2812672
+94 11 2814294
+94 77 7891511
+94 11 2791051

Mr. W.D. Anuruddha Perera
Manager (Construction)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
managerconwc
@waterboard.lk
+94 11 2812672
+94 11 2856420-2
+94 77 7263597
+94 11 2790879

Mr. D.W.N.Suranjith
Manager (Commercial)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
managercomwc
@waterboard.lk
+94 11 2812672

+94 11 2856420-2/+94 115355513

+94 773751236

+94 91

3920604

Mr. A.R.D. Attanayaka
Chief Engineer (E&M)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
cengenmwc
@waterboard.lk
+94 11 2812672
+94 11 2856420-2
+94 77 7700938
+94 38 2236905

Mr. S.H. Wickramarachchi
Chief Engineer (Co-ordination)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
cengcordwc
@waterboard.lk
+94 11 2812672
+94 11 2824436/ +94 11 2856420-2
+94 71 4416303
+94 11 2651420

Mrs. S. Jeyaranie
Chief Engineer (Development)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
cedvwc
@waterboard.lk
+94 11 2812672
+94 11 2856420-2
+94 77 2240537
+94 11 2722361

Mr. K. Premakumara
Chief Engineer (NRW)
NWSDB, No.17/2, Siri Vipulasena Mawatha, Colombo 10.

+94 11 2662091
+94 77 7772433

Mrs. U.J.Samarasinghe
Chief Accountant
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
chiefacctwc
@waterboard.lk
+94 11 2812672
+94 11 5355512/ +94 11 2856420-2

+94 77

7800856

Mr. K.H.N.G. Kumarasinghe
Engineer (IT)
Regional Support Center – (Western Central), No.175/A, Nawala Rd, Nugegoda.
engcompwc
@gmail.com

+94 71 2261698

Mr. K.K.D.J. Senevirathna
Engineer Metering
NWSDB, Mudali Mw, Kohuwala

+94 11 2853844
+94 77 721599

Mr. U.K. Chiththananda
OIC (construction)
NWSDB, Mudali Mw, Kohuwala

+94 11 2829613
+94 77 2442041

Mr. U.L.U.A. Karunarathna
OIC (Distribution and Main Works)
NWSDB, No. 3, White Park, Maligakanda, Colombo 1

Manager (Colombo South)

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. A.V.P.Dhammika
Manager (Colombo South)
NWS&DB, No 1-2/1, White Park, Malaigakanda, Colombo 10
managercc
@waterboard.lk
+94 11 2682442
+94 11 2682250, +94 11 2672285, +94 11 2681975
+94 773 785860
+94 11 2415027

Mr. P.A.S. Anuradha
Area Engineer (Fort)
NWS&DB, No 1-2/1, White Park, Malaigakanda, Colombo 10
aeccw
@waterboard.lk
+94 11 2672285
+94 11 2681975, +94 11 2672285
+94 771 097633

Mr. D.G.P.N. De Silva
Area Engineer (Pamankada)
NWS&DB, No. 634/2A, Havelok Road, Colombo 06
aeccs
@waterboard.lk
+94 11 2500425
+94 11 2500425, +94 11 250257,3 +94 11 2588029
+94 77 7256434

Mr. S.M.R. Jayathilake
Engineer (Priority)
No 1-2/1, 3 rd Floor, White Park, Malaigakanda, Colombo 10
wbengprioritywc
@waterboard.lk
+94 11 5558690
+94 11 2682142, +94 11 5558690
+94 77 4098152

Mr. S.M.L.A. De Alwis
OIC (Slave Island)
NWS&DB, No. 153/1, Union Place, Colombo 02

+94 11 2448547
+94 77 3620347

Mr. T.N.K. Weerakkody
OIC (Hultsdroft)
NWS&DB, No. 140, St. Andrew's Place (Lower), Colombo 15

+94 11 2524830
+94 773 621018

Mr. R.A.P. Ranasinghe
OIC (Thimbirigasyaya)
NWS&DB, No. 73/7, Elwitigala Road, Colombo 08

+94 11 2687684
+94 77 7800162

Mr. M.A.M. Asif
OIC (Pamankada)
NWS&DB, No. 634/2A, Havelok Road, Colombo 06

+94 11 2367976
+94 773 622976

Manager (Colombo North)

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. R.A.N. Dharmasiri Manager (Colombo North)
NWSDB, No. 3, White Park, Maligakanda, Colombo 10
manageropcc
@waterboard.lk
+94 11 2669322
+94 11 2667929/ +94 11 2669322
+94 77 7789524

Mr. U.K.D. Sunilchandra
Area Engineer (Mattakkuliya)
NWSDB, No.175, Centre Rd, Mattakkuliya, Colombo 15
aeccn
@waterboard.lk
+94 11 2524849
+94 11 2524849

Mr. D.C. Gunarathna
Area Engineer (Maligawatta)
No 1-2/1, 3 rd Floor, White Park, Malaigakanda, Colombo 10
aece
@waterboard.lk
+94 11 2437562
+94 11 2437562-3
+94 77 2240577

Mr. W.M.D.G.B. Wickramasingha
OIC (Mattakkuliya)
NWSDB, No. 175, Centre Rd, Mattakkuliya, Colombo 15

+94 11 2524842
+94 77 3618567
+94 11 4861015

Mr. W.W.K. Jayasinghe
OIC (Kotahena)
NWSDB, White Park, Maligakanda

+94 11 2546685

+94 33 2263094

Mr. H.W. Gunawardana
OIC (Maligawatta)
No 1-2/1, 3 rd Floor, White Park, Malaigakanda, Colombo 10

+94 11 2452327
+94 71 8069689

Mr. K.L. Wijekularathna
OIC (Borrella)
NWSDB, No.74, Kinsey Rd, Colombo 08

+94 11 2686845

+94 11 2237809

Manager (Kotte)

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. H.M. Abeykon
Manager (Kotte)
NWSDB, Sri Naga Vihara Road, Pagoda, Nugegoda
managertecn
@waterboard.lk
+94 11 2769122
+94 11 5032873 / +94 11 2853990/ +94 11 5024607
+94 777633713
+94 37 7201055

Mr. W.A.N.U. Kumara
Area Engineer (Battaramulla)
NWSDB, No. 75, Robert Gunawardena Mawatha, Battamulla
aebattaramulla
@waterboard.lk
+94 11 2877119
+94 11 2877119
+94 77 7891328
+94 11 2980334

Mr. D.A.D.U. Nishantha
Area Engineer (Kotte)
NWSDB, Sri Naga Vihara Road, Pagoda Nugegoda
aekotte
@waterboard.lk
+94 11 2769122
+94 11 2853990/ +94 11 5024607/ +94 11 5024609
+94 71 4426642
+94 11 4925873

Mr. R. Jinadasa
Area Engineer (Kolonnawa)
NWSDB, Gnanasiri Mawatha, Kolonnawa
aekolonnawa
@waterboard.lk
+94 11 5558359
+94 11 2530106
+94 77 7891331
+94 11 2970615

Mr. H.P.N.C. Siriwardana
O.I.C. (Kotte)
NWSDB, Kuruduwatta Road, Pitakotte

+94 2820895
+94 71 4870574

Mr. N.W.P. Deshabandu
O.I.C. (Battaramulla)
NWSDB, Kanatta Rd, Batapoththa, Battaramulla

+94 11 5551920
+94 77 7846845

Mr. D.M.S. Duwegoda
O.I.C. (Kolonnawa)
NWSDB, No. 6/5, IDH Rd, Kolonnawa

+94 11 2572152
+94 71 4802034
+94 11 2572152

Mrs. G.A.I. Premawardana
O.I.C. (Kaduwela)
NWSDB, No. 4/374, Perera Mawatha, Kaduwela

+94 11 2579353
+94 77 3900114
+94 11 2563677

Manager (Maharagama)

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. A.D.K.K. Wijegunawardana
Manager (Maharagama)
NWSDB, 295/1, Makumbura, Pannipitiya
managertecs
@waterboard.lk
+94 11 2781870
+94 11 2782396, +94 11 2781870

Mr. P.A.M. Sumanasekara
Area Engineer (Maharagama)
NWSDB, No. 138 A, Dehiwala Rd, Maharagama
aemaharagama
@waterboard.lk
+94 11 2851716
+94 11 5559100, +94 11 2851716
+94 77 7272950

Mrs. C.A. Pushpalatha
Area Engineer (Kesbewa)
NWSDB, No. 24, Park Road, Piliyandala
aepiliyandala
@waterboard.lk
+94 11 2614790
+94 11 2615102, +94 11 2614790
+94 77 7891326

Mr. B.P. Wijedeera
O.I.C. (Maharagama)
NWSDB, Vidyakara Mw, Maharagama

+94 11 2840380
+94 77 7707659
+94 11 2894262

Mrs. S.H. Sooriyarachchi
O.I.C. (Miriswatta)
NWSDB, Miriswatta, Piliyandala

+94 11 2604189
+94 77 2240573
+94 11 2604740

Mr. K.L Weerawarnakula
O.I.C. (Pannipitiya)
NWSDB, Kulasewana Mw, Pannipitiya

+94 11 2847847
+94 77 2240569
+94 11 2783571

Mrs. H.C.W.M.H. Samarasinghe
O.I.C. (Homagama)
NWSDB, Courts Rd, Homagama

+94 11 2857412
+94 77 2240568
+94 11 2753746

Mr. L.M. Rathnayaka
O.I.C. (Pelanwatta)
NWSDB, Gorakapitiya Rd, Pelanwatta, Pannipitiya

+94 11 2837387
+94 77 1960336

Mr. A. Nimalsiri perera
O.I.C. (Awissavella)
NWSDB, Vidayala Mw, Awissawella

+94 36 2222658
+94 71 4487826
+94 36 2230033

Manager (NRW)

Name & Designation
Official Address (NWSDB)
E-mail
Fax No.
Office Tel.
Mobile Tel.
Residance Tel.

Mr. S.G.G. Rajkumar
AGM (NRW)
NRW Office, NWSDB, Telewala Rd, Ratmalana
agmnrw
@waterboard.lk
+94 11 2638804
+94 11 5556709, +94 11 2638804
+94 77 3952717
+94 11 2688411

Mr. T.B. Heenkenda
Manager (NRW)
NRW Office, NWSDB, Telewala Rd, Ratmalana
managernrw
@waterboard.lk
+94 11 2638804
+94 11 5556709, +94 11 2638804
+94 77 7891332

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:04:55 +0000</pubDate>
		</item>
		<item>
			<title>Water Coverage</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=99&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=99&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[

Manager Area
Total No. of Connections (Domestic) - May 2015
Average Population Benefited - May 2015
Total Population - 2012 (from Statistics Report)
Population Predicted for 2010
Water Coverage % as at May 2015

A
B
C
D=C*(1+1.1%)^3
E=(B*100)/C

Colombo City (North)
67,432
323,674
329,346
335,035
97%

Colombo City (South)
52,669
237,011
236,968
241,061
98%

Kotte
141,091
592,582
640,255
651,315
91%

Maharagama
111,559
468,548
770,031
783,332
60%

RSC (WC)
372,751
1,621,814
1,976,600
2,010,744
81%

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:04:37 +0000</pubDate>
		</item>
		<item>
			<title>Organizational Structure</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=98&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=98&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[
This page is under construction
]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:03:50 +0000</pubDate>
		</item>
		<item>
			<title>Public Relations Activities</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=97&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=97&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[
This page is under construction
]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:03:32 +0000</pubDate>
		</item>
		<item>
			<title>Ongoing Projects to Enhance Coverage</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=96&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=96&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[

Name of The Project
Source of Funds
Project Cost (Mn)
Beneficiaries
Designed Service Connections
Present Status

Jaltara-Ranala Phase I Stage II
Capital
283
8852
2000
Implementation Stage

Kaluganga Project
JICA
JPY 8388
+
Rs 2458.0
250000
50000
Implementation Stage

Hanwella Water Supply Scheme Augmentation
Capital
102
17250
3450
Implementation Stage

Kalu Ganga Water Supply Project

Total Project Cost
:
JPY 8388.0 million + Rs 2458.0 million
(Including Master Plan Update & Institutional Development)

Supervision of Construction Work
:
National Water Supply & Drainage Board
NJS Consultants Ltd, Japan

Date of Commencement
:
December 2009
(Construction Work)

Scheduled Date of Completion
:
November 2015

Project Beneficiaries
:
A total of 250,000 people (50,000 families) living in Kesbewa, Piliyandala, Boralesgamuwa, Madapatha, Polgasowita, Kahathuduwa, Gonapola, Kumbuka, Panadura-Kiriberiya, Niwdawa, Horana and surrounding areas will benefit from this project

And

Service level improvements of existing consumers living in Southern Part of Pettah, Hultsdorf, Kotahena and Maradana.

Physical Progress as at 31.03.2012
:
55.85%

Financial Progress as at 31.03.2012
:
32.14%

Greater Colombo Water Rehabilitation Project

Scope
:
Improvement of low pressure in Kollannawa area and organizational development.

Project Cost
:
Rs.792.63 Million

Source of Funding
:
JICA

Project Duration
:
From10/2008 To 07/2012

Area of Coverage
:
Mulleriyawa & Kotikawatta areas

Physical Progress
:
75.64%

Augmentation of Colombo Water Supply System

Scope
:

Replacement of deteriorated pipes, valves and associated appurtenants Approx. 400km in Colombo City.

Regularization of water supply to the tenement gardens.

Minimization of stand posts.

Project Cost
:
Rs. 17,990 Million

Source of Funding
:
ADB

Current Position
:
Negotiation for funds

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:03:08 +0000</pubDate>
		</item>
		<item>
			<title>Water Loss Management</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=95&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=95&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[

Water Loss Management
[ PDF - 458 ]

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:02:22 +0000</pubDate>
		</item>
		<item>
			<title>Billing System</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=94&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=94&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[
How to make the payment of water Bills

At any Cashier Point of the Water Board (Island Wide) - By cash or cheques

(Working days- from 9.00 a.m. to 3.00 p. m.)

(All cheques should be drawn in favour of the "National Water Supply & Drainage Board" and crossed "Account Payee only". Also ensure that you enter your Account Number on the reverse of the Cheque. Send the bill intact for payments.)

Note: In the event of your cheque/s has been dishonoured SLRs. 100/= per cheque will be debited to your account.

The following cashier points (belongs to Water Board) are available in the RSC – Western Central Area

RSC – Western Central Office
:
NWS&DB, No.71, 2nd Floor, Welikada Plaza, Rajagiriya

Area Engineer Office
:
NWS&DB, No.138, F 97, People's Park Building, Colombo 11

Area Engineer Office
:
NWS&DB, Parisara Mawatha, Maligawatta, Colombo 10

Area Engineer Office
:
NWS&DB, No.634/2A, Havelock Road, Colombo 06

Manager/ Area Engineer
:
NWS&DB, Sri Nagavihara Road, Pagoda Office Nugegoda

Area Engineer Office
:
NWS&DB, 138/A, Dehiwala Road, Maharagama

The following Authorized Agents are available in the RSC – Western Central Area

Agent
Area
Mode of Payment

Manager's Office - TEC(S) Area

Sanasa Bank
Boralasgamuwa
Cash & Cheques

Sanasa Bank
Godigamuwa South
Cash

Sanasa Bank
Makandana
Cash & Cheques

Sanasa Bank
Udahamulla
Cash

Vinoja A.P.O.
Maharagama
Cash

Manager's  Office - TEC(N) Area

Gamons Agency Post Office
Nugegoda
Cash & Cheques

M.P.C.S.
Kollonnawa
Cash

M.P.C.S.
Kaduwela
Cash

Jambo Textiles
Pitakotte
Cash & Cheques

Sanasa Bank
Gangodawila
Cash & Cheques

Sanasa Bank
Nawala Koswatta
Cash & Cheques

M.P.C.S.
Baththaramulla
Cash

B.K. Sirinimal
Jubilee Post
Cash & Cheques

Sanasa Bank
Udahamulla
Cash

Pensioners Thrift & Credit Co-operative
Gangodawila
Cash & Cheques

* Abbreviations

A P O
:
Agency Post Office

M P C S
:
Multi-Purpose Corporate Society

Cargills food City

Singer Sri Lanka

Abans Ltd

Banks

Name
Mode of Payment

 Bank of Ceylon
Cash & Cheques, ATM & Internet

 Peoples  Bank
Cash & Cheques, ATM & Internet

 HSBC  Bank
ATM & Internet

 City Bank
A/C No: 20091019

 Deutsche  Bank
Cash & Cheques

 Commercial  Bank
Cash & Cheques

 NDB
Cash & Cheques

 Union Bank
Telephone & Internet Banking

 Standard Chartered Bank
Telephone Banking

 Seylan Bank
Only for Seylan Customers

 Nation Trust Bank
Cash & Cheques

 HNB
Cash & Cheques

 Pan Asia Bank
Cash & Cheques

 Sampath Bank
Sampathnet

 NSB
Cash only

www.waterboard.lk (on line through Internet)

Mobile Telephone SMS Service (Pending)

How to Calculate the Bills Amount

Click here to view

How to make complaints regarding the bill errors?

How the bill errors would be corrected?

If you notice an error in your water bill you can complaint it over the phone or in writing to the relevant Area Engineer's Office. In addition you are free to visit our Consumer Relation Desk located in your Area Engineer's Office.

If you have inquires regarding your monthly bill please contact your relevant office within 21 days from the day you receive the bill.

How Do You Identify the Relevant Office?

Please Check the First 4 Digits in your water bill Account No. & look at the table (back side of the bill) for the relevant office in  your bill.

Ex :-  10 / 37  / 602 /107 / 18     2

10 / 37  -  Area Engineer (Battaramulla) or Manager Office (TEC – North)

Concession on large bills due to Internal Leaks

According to your monthly water bill, sometimes, you can review an unusual large consumption & very heavy water bill value. If you have noticed the above situation you should check the internal leaks in your distribution pipe lines.

If you have an Internal Leak it can be Internal and Invisible.

If you have noticed the above situation you should inform to the relevant Area Engineers' office / Manager's Office immediately.

How to calculate the concession?

Example:-

Your monthly consumption  average is 20 units (Cubic Meters)

This month your consumption is 42 units due to internal leak.

Rs.

Bill value for 42 units Consumption
xxxxxxxxxxxx

Less:-
Bill value for 20 units Consumption (According to Last Bills)
(xxxxxxxxxxx)

Less:-
Production cost for additional 22 units consumed ( 42  - 20)
(xxxxxxxxxxx)

Concession to the Consumer
xxxxxxxxxxxx

Note: This concession due to internal leaks is given once in the consumer's life time.

Laws & regulations in illegal connections and water usage

There are provisions given under the National Water Supply Drainage Board Act No.02 of 1974  and Amended by Act No. 13 of 1992.
]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:01:53 +0000</pubDate>
		</item>
		<item>
			<title>Details of Connections - 2015</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=93&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=93&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:01:21 +0000</pubDate>
		</item>
		<item>
			<title>Key Performance Indicators</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=92&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=92&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[
Key Performance Indicators are used to monitor and compare the performance of NWSDB with other foreign Water Authorities. They can also be used to compare the performance of various Regional Support Centres within the Board. The Cooperate Plan prepared for the period from 2007 to 2011 stipulates targets for each RSC and the Board. Board has started to monitor the performance indicators commencing from January 2011. Indicators are generally prepared for each quarter. Following table shows Key Performance Indicators for western Central RSC together with RSC target and Board overall Target

Key Performance Indicators (KPIs) as at end of Every Quarter in 2015 - RSC (WC)

Item
Description
Formula
1st Quarter
2nd Quarter
3rd Quarter
4th Quarter

1
Service Levels

Piped Water Connected Coverage
Regional Population Served *100
Total Regional Population
 80.7%2

Water Availability
Water Availability
 23.05 hrs/day

Water Quality
No. of tests that pass SLS Standards *100
Total No. of Tests carried out
 100%

2
Operational Efficiency

UFW(%)
Total Water un-accounted for * 100
Total Water Produced
 38.8%

Staff/1000 Connections
Total No of Staff
Total No. of Connections in '000
 3.3

Energy Cost/ cum water Produced
Total Energy Cost(Rs.).
Total Water Produced in Cum
 Rs. 1.05

Estimated Bills per 1000 connections
Total no of estimated Bills.
Total No. of Connections in '000
 4.1

Defective meters per 1000 connections
Total no of defective meters.
Total No. of Connections in '000
 2.5

3
Financial Performance

Operating Ratio
Operating Expense.
Operation Revenue
 0.32

Debtage
Total arrears without Current month billing
Average Monthly Billing
 0.87

Stock efficiency
Total no. of complaints at perticular month. Total No. of Connections in '000
596.3

4
Customer Service
Total no. of complaints at perticular month. Total No. of Connections in '000
 16

Item
Description
Formula
     RSC (WC)
 Island Wide

Target

Actual
Target
Actual

1
Service Levels

Piped Water Connected Coverage
Regional Population Served *100
Total Regional Population
91.8%
82.9%
45.0%
43.7%

Water Availability
Water Availability
24 hrs/day
23.04 hrs/day
24 hrs/day
hrs/day

Water Quality
No. of tests that pass SLS Standards *100
Total No. of Tests carried out
100%
100%
100%
99%

2
Operational Efficiency

UFW(%)
Total Water un-accounted for * 100
Total Water Produced
24.9%
39.1%
25.4%
29.3%

Staff/1000 Connections
Total No of Staff
Total No. of Connections in '000
 3.8
3.3
5.8
5.8

Energy Cost/ cum water Produced
Total Energy Cost(Rs.).
Total Water Produced in Cum
 Rs.10.05
Rs.1.49
-
Rs.6.13

Estimated Bills per 1000 connections
Total no of estimated Bills.
Total No. of Connections in '000
 30
14
15
11

Defective meters per 1000 connections
Total no of defective meters.
Total No. of Connections in '000

3.52
-
3.79

3
Financial Performance

Operating Ratio
Operating Expense.
Operation Revenue
 0.38
0.30
<1
1.03

Debtage
Total arrears without Current month billing
Average Monthly Billing
 2.20
1.15
1.00
1.51

Stock efficiency
Total no. of complaints at perticular month. Total No. of Connections in '000
1300
609
-
2414

4
Customer Service
Total no. of complaints at perticular month. Total No. of Connections in '000
 80
16
-
76.23

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 06:00:57 +0000</pubDate>
		</item>
		<item>
			<title>Internal Water Leaks</title>
			<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=91&catid=34&Itemid=293&lang=en</link>
			<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=91&catid=34&Itemid=293&lang=en</guid>
			<description><![CDATA[
How to identify why your water consumption has gone up?

1.

Inform the relevant Area Engineer office by using the complaint form

Inspection team will visit your place and they will carry out the initial visual and manual inspection. This initial inspection will be carried out free of charge.

Tips to identify an internal leak by yourself

Take the meter reading daily at the same time.

Close all the taps and check whether your water meter is still working.

If it is still working then check the cisterns for leaks.
How to check your cisterns?

Fill up the cistern and close the inlet valve. Mark the water level. Wait for 2 hours and check the level. If it reduces, then the piston of cistern is leaking. Get it repaired as soon as possible. Till it repaired, close the valve (Stop tap) in the cistern supplies line.

Check the ball valves in the cistern. If it is not working properly then water from the cistern will overflow in to the water closet. Get it repaired as soon as possible. Till it repaired close the valve (stop tap) in the cistern supplies line.

Check the surrounding (inside your premises after the water meter) during the night time (as the pressure in the system is high to night you can observe if there is a leak in your garden.), if you can observe wet patches in the garden or wet areas in walls, it can be a leak in a covered pipeline. Check the covered pipe lines in those places and get them repaired.

Check the ball valve in your overhead tank. If it is not functioning properly, your overhead tank can overflow during the night time.

Check the underground sump for leaks.
How to check?

Fill your overhead tank to full.

Then wait till your ground sump get filled

Close the valve after the water meter.

Mark the water level in the ground sump

Do not use water from the sump or do not pump water to the over head tank after closing the valve.

Observe for 24hours. (As you have enough water in your overhead tank you can wait for 24 hours without pumping water to overhead tank.) Some time you will be able to observe reducing the water level after few hours. Then no need to wait for 24 hours.

If the water level reduces, it means your ground sump is leaking. Ground sump should be covered to minimize the evaporation losses. If it is having leaks take necessary measures to get it repaired as soon as possible. (Empty the sump, check for cracks, and repair the cracks with a suitable water proofing material.)

Check your garden taps whether they are turned off tightly to stop drips and functioning properly.

2.
If inspection team cannot identify any leak by visual and manual inspection they will inform you to decide whether to request for inspection using specific instruments for leak detections. If you request for inspection using specific instruments for leak detection, you have to make a payment of Rs. 1,680.00 (including VAT) to the relevant Area Engineer Office.

3.
If cannot identify any leak using instrument, then you can request for checking the water meter. For water meter testing you have to make a payment of Rs. 3,360.00 (including VAT) to the relevant Area Engineer Office. If the error percentage in the test report indicates more than ±2%, NWSDB will take action to correct the bill to an average consumption considering the previous months. If the water meter is defective, the meter testing charges will be refunded.

4.
If you have helpers at home, aware them for closing the taps properly. Water loss due to partly opened taps is appended below.

]]></description>
			<author>test@maoil.com (piyo)</author>
			<category>Western Central</category>
			<pubDate>Mon, 01 Sep 2014 05:59:20 +0000</pubDate>
		</item>
	</channel>
</rss>


text:
'use strict';

const util = require('./index');
const expect = require('chai').expect;

describe('util', ()=> {

  it('should indicate that undefined values are not specified', ()=> {
    expect(util.isSpecified()).to.equal(false);
  });

  it('should indicate that null values are not specified', ()=> {
    expect(util.isSpecified(null)).to.equal(false);
  });

  ['', { some: 'obj' }, new Date(), 0, 1].forEach(value => {
    it('should indicate that ' + JSON.stringify(value) + ' is specified', ()=> {
      expect(util.isSpecified(value)).to.equal(true);
    });
  });

  it('should get the default value when no value has been specified', () => {
    let value, defaultValue = 'default';
    expect(util.getOptionalValue(value, defaultValue)).to.equal(defaultValue);
  });

  it('should get the value when it has been specified', () => {
    let value = 'value', defaultValue = 'default';
    expect(util.getOptionalValue(value, defaultValue)).to.equal(value);
  });

  [0, 1, '0', '5'].forEach(value => {
    it('should indicate that "' + value + '" is a positive integer', () => {
      expect(util.isPositiveInteger(value)).to.equal(true);
    });
  });

  [-1, '', 'ab', '-5'].forEach(value => {
    it('should indicate that "' + value + '" is not a positive integer', () => {
      expect(util.isPositiveInteger(value)).to.equal(false);
    });
  });

  it('should concat when both target and source are arrays', () => {
    let target = [{item: 1}];
    let source = [{item: 2}, {item: 3}];
    expect(util.concatArrays(target, source)).to.deep.equal(target.concat(source));
  });

  it('should not concat when the target is not an array', () => {
    let target = {};
    let source = [{item: 2}, {item: 3}];
    expect(typeof util.concatArrays(target, source)).to.equal('undefined');
  });

  it('should not concat when the source is not an array', () => {
    let target = [{item: 1}];
    let source = 'something';
    expect(typeof util.concatArrays(target, source)).to.equal('undefined');
  });

});


text:
using base::android::AttachCurrentThread;
using base::android::ScopedJavaGlobalRef;
using bookmarks::android::JavaBookmarkIdCreateBookmarkId;
using bookmarks::android::JavaBookmarkIdGetId;
using bookmarks::android::JavaBookmarkIdGetType;
using bookmarks::BookmarkNode;
using bookmarks::BookmarkType;
using content::WebContents;
using content::BrowserThread;

namespace enhanced_bookmarks {
namespace android {

EnhancedBookmarksBridge::EnhancedBookmarksBridge(JNIEnv* env,
    jobject obj,
    Profile* profile) : weak_java_ref_(env, obj) {
  profile_ = profile;
  enhanced_bookmark_model_ =
      EnhancedBookmarkModelFactory::GetForBrowserContext(profile_);
  enhanced_bookmark_model_->SetVersionSuffix(chrome::VersionInfo().OSType());
}

void EnhancedBookmarksBridge::Destroy(JNIEnv*, jobject) {
  delete this;
}

ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddFolder(JNIEnv* env,
    jobject obj,
    jobject j_parent_id_obj,
    jint index,
    jstring j_title) {
  DCHECK(enhanced_bookmark_model_->loaded());
  long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj);
  const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID(
      enhanced_bookmark_model_->bookmark_model(),
      static_cast<int64>(bookmark_id));
  const BookmarkNode* new_node = enhanced_bookmark_model_->AddFolder(
      parent, index, base::android::ConvertJavaStringToUTF16(env, j_title));
  if (!new_node) {
    NOTREACHED();
    return ScopedJavaLocalRef<jobject>();
  }
  ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId(
      env, new_node->id(), BookmarkType::BOOKMARK_TYPE_NORMAL);
  return new_java_obj;
}

void EnhancedBookmarksBridge::MoveBookmark(JNIEnv* env,
                                           jobject obj,
                                           jobject j_bookmark_id_obj,
                                           jobject j_parent_id_obj) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(enhanced_bookmark_model_->loaded());

  long bookmark_id = JavaBookmarkIdGetId(env, j_bookmark_id_obj);
  const BookmarkNode* node = bookmarks::GetBookmarkNodeByID(
      enhanced_bookmark_model_->bookmark_model(),
      static_cast<int64>(bookmark_id));
  if (!IsEditable(node)) {
    NOTREACHED();
    return;
  }
  bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj);
  const BookmarkNode* new_parent_node = bookmarks::GetBookmarkNodeByID(
      enhanced_bookmark_model_->bookmark_model(),
      static_cast<int64>(bookmark_id));
  enhanced_bookmark_model_->Move(node, new_parent_node,
                                 new_parent_node->child_count());
}

ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddBookmark(
    JNIEnv* env,
    jobject obj,
    jobject j_parent_id_obj,
    jint index,
    jstring j_title,
    jstring j_url) {
  DCHECK(enhanced_bookmark_model_->loaded());
  long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj);
  const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID(
      enhanced_bookmark_model_->bookmark_model(),
      static_cast<int64>(bookmark_id));

  const BookmarkNode* new_node = enhanced_bookmark_model_->AddURL(
      parent,
      index,
      base::android::ConvertJavaStringToUTF16(env, j_title),
      GURL(base::android::ConvertJavaStringToUTF16(env, j_url)),
      base::Time::Now());
  if (!new_node) {
    NOTREACHED();
    return ScopedJavaLocalRef<jobject>();
  }
  ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId(
      env, new_node->id(), BookmarkType::BOOKMARK_TYPE_NORMAL);
  return new_java_obj;
}

bool EnhancedBookmarksBridge::IsEditable(const BookmarkNode* node) const {
  if (!node || (node->type() != BookmarkNode::FOLDER &&
      node->type() != BookmarkNode::URL)) {
    return false;
  }
  return profile_->GetPrefs()->GetBoolean(
        bookmarks::prefs::kEditBookmarksEnabled);
}

static jlong Init(JNIEnv* env, jobject obj, jobject j_profile) {
  return reinterpret_cast<jlong>(new EnhancedBookmarksBridge(
        env, obj, ProfileAndroid::FromProfileAndroid(j_profile)));
}

bool RegisterEnhancedBookmarksBridge(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace android
}  // namespace enhanced_bookmarks


text:
import sublime

from bisect import bisect_left

from types import Region, span, Bracket, LeftBracket, RightBracket, Scope

#
# Cursors and regions
#

def cursors_of_view(view):
    """Locates points of all cursors of the view.

    Args:
        view - an instance of sublime.View where to look for cursors

    Returns:
        [point] - a list of cursor points, sorted
    """
    return [region.begin() for region in view.sel() if region.empty()]

def current_lines_of_view(view, cursors):
    """Extracts regions of the current lines of the view.

    Also merges consecutive regions.

    Args:
        view - an instance of sublime.View

        [cursors] - a sorted list of cursors selected in the view

    Returns:
        [regions] - a list of resulting line Regions, sorted
    """
    if not cursors: return []

    def as_region(sublime_region):
        return Region(sublime_region.begin(), sublime_region.end())

    lines = [as_region(view.line(cursor)) for cursor in cursors]

    def consecutive(this, next):
        return (this.end + 1) == next.begin

    result = []
    previous_line = lines[0]

    for next_line in lines[1:]:
        if consecutive(previous_line, next_line):
            previous_line = span(previous_line, next_line)
        else:
            result.append(previous_line)
            previous_line = next_line

    result.append(previous_line)
    return result

def expand_cursors_to_regions(cursors, amount, view):
    """Computes the vicinities of the cursors.

    Args:
        [cursors] - a list of cursors that will be centers of the regions

        amount - radius (in points) of desired regions

        view - the sublime.View the cursors are from

    Returns:
        [regions] - a list of regions corresponding to the cursors
    """
    assert (amount >= 0)
    view_begin, view_end = 0, view.size() - 1

    def clamp_expand(cursor):
        begin, end = cursor - amount, cursor + amount
        if begin < view_begin: begin = view_begin
        if end > view_end: end = view_end
        return Region(begin, end)

    return map(clamp_expand, cursors)

def merge_adjacent_regions(regions, cursors):
    """Merges overlapping regions and computes the cursors contained in them.

    Args:
        [regions] - a list of regions obtained by expanding the cursors

        [cursors] - a list of cursors that are the centers of the regions

    Returns:
        [(Region, [cursors])]
            - a list disjoint regions and the cursors they contain,
              the list is sorted by regions, the cursors are also sorted
    """
    if not regions: return []
    assert len(regions) == len(cursors)

    current_region = regions[0]
    current_cursors = set([cursors[0]])

    result = []

    for next_region, next_cursor in zip(regions[1:], cursors[1:]):
        if current_region.touches(next_region):
            current_region = span(current_region, next_region)
            current_cursors.add(next_cursor)
        else:
            result.append((current_region, sorted(current_cursors)))
            current_region = next_region
            current_cursors = set([next_cursor])

    result.append((current_region, sorted(current_cursors)))
    return result

#
# Brackets
#

def locate_brackets(view, region, supported_brackets, suitable_scope):
    """Locates all brackets in the specified region of the view.

    Args:
        view - a sublime.View to scan for brackets

        region - the exact region in the view to scan through

        [supported_brackets]
            - a list of (left_bracket, right_bracket) tuples of strings
              that specify textual representation of the brackets

        suitable_scope
            - a predicate of signature (scope) that tells whether
              the given scope should be checked for brackets
    Returns:
        [bracket] - a list of brackets that were found
    """
    def substring_matches_at(point, haystack, needle):
        region = sublime.Region(point, point + len(needle))
        return haystack.substr(region) == needle

    # We assume that brackets match unambiguously: i.e., a bracket must not be
    # a prefix of some other bracket (though, they may be textually equal).

    brackets = []

    point = region.begin
    while point < region.end:

        if suitable_scope(view.scope_name(point)):

            for left, right in supported_brackets:

                if substring_matches_at(point, view, left):
                    brackets.append(LeftBracket(point, left))
                    point += len(left) - 1
                    break

                if substring_matches_at(point, view, right):
                    brackets.append(RightBracket(point, right))
                    point += len(right) - 1
                    break

        point += 1

    return brackets

#
# Indexing
#

def index_brackets(brackets, cursor):
    """Assigns nesting indices to brackets relative to the given cursor.

    Nesting index is a tuple of (outer_nesting_level, inner_nesting_level)
    which are integers that describe how deeply the given bracket is nested
    inside the text.

    A picture is worth a thousand of words, so here is an explanation of
    the principle by which the brackets get their indices. Consider the
    following bracket expression, the cursor is marked with a vertical bar:

        ((()((())()(|())(()(()))))())

    The brackets here receive the following indices:

        ( ( ( ) ( ( ( ) ) ( ) ( ( ) ) ( ( ) ( ( ) ) ) ) ) ( ) )     bracket
                               |
        3 2 1 1 1 0 0 0 0 0 0 0 - - 0 0 0 0 0 0 0 0 0 1 2 2 2 3     outer
        0 0 1 1 0 1 2 2 1 1 1 0 1 1 0 1 2 2 2 3 3 2 1 0 0 1 1 0     inner

    which may be a bit confusing... until you arrage the brackets like this,
    trying to guess their nesting level:

        (                      |                              )
          (                    |                        ) ( )
            ( ) (              |                      )
                  (     ) ( ) (|    ) (             )
                    ( )        |( )     ( ) (     )
                               |              ( )

    Then, by considering the 'distance' of the bracket pair from the cursor,
    we can divide the brackets into layers:
                                                                  outer   inner
        (                      |                              )     3       0
        - - - - - - - - - - - -|- - - - - - - - - - - - - - - -
          (                    |                        )           2       0
                               |                          ( )               1
        - - - - - - - - - - - -|- - - - - - - - - - - - - - - -
                (              |                      )             1       0
            ( )                |                                            1
        - - - - - - - - - - - -|- - - - - - - - - - - - - - - -
                              (|    )                               0       0
                  (     ) ( )  |      (             )                       1
                    ( )        |        ( ) (     )                         2
                               |              ( )                           3
        - - - - - - - - - - - -|- - - - - - - - - - - - - - - -
                               |( )                                -1       1

    Now you can see a few simple patterns here:

      - matching brackets have matching indices

      - for each outer index level there is at most one bracket pair with
        zero inner index, it is called 'mainline' that contains the cursor

      - inner index tells how many nesting levels should be crossed to get
        from this bracket to the mainline bracket of the same outer index

      - outer index tells how many mainline bracket pairs should be crossed
        from outside the expression to get to the nesting level of the cursor

    Args:
        [brackets] - a list of brackets to index

        cursor - the cursor which is used as a kernel

    Returns:
        [indices] - a list of indices assigned to brackets
    """
    def cursor_insertion_index(cursor, brackets):
        """Returns the index of the bracket immediately following the cursor."""
        # The bracket with the index returned will the first bracket that is
        # located to the right of the cursor's point. Special arrangements
        # need to be done for multicharacter left brackets to ensure that
        # they are treated by bisect_left as 'located to the left' only
        # when they are _entirely_ located to the left of the cursor.
        return bisect_left(map(Bracket.inside_point, brackets), cursor)

    cii = cursor_insertion_index(cursor, brackets)

    def index_left(brackets, cii):
        """Indexes brackets located to the left of the cursor."""
        left_indices = []
        outer_depth = -1
        next_depth = 0

        for bracket in reversed(brackets[0:cii]):
            inner_depth = next_depth

            if bracket.is_left():
                if next_depth == 0:
                    outer_depth += 1
                else:
                    next_depth -= 1
            else:
                next_depth += 1
                inner_depth += 1

            left_indices.append((outer_depth, inner_depth))

        left_indices.reverse()
        return left_indices

    def index_right(brackets, cii):
        """Indexes brackets located to the right of the cursor."""
        right_indices = []
        outer_depth = -1
        next_idepth = 0

        for bracket in brackets[cii:]:
            inner_depth = next_idepth

            if bracket.is_right():
                if next_idepth == 0:
                    outer_depth += 1
                else:
                    next_idepth -= 1
            else:
                next_idepth += 1
                inner_depth += 1

            right_indices.append((outer_depth, inner_depth))

        return right_indices

    return index_left(brackets, cii) + index_right(brackets, cii)

def merge_bracket_indices(per_cursor_indices):
    """Merges indices assigned to brackets from several cursors.

    The reasonable way to combine indices from two different cursors is
    to take a minimum; because index of a bracket is the amount of nesting
    levels that need to be crossed to get from the bracket to the cursor.
    Therefore, it's pretty logical to take the shortest available path.

    The only peculiarity is the outer index -1 that should not be considered
    lesser than index 0. Conversely, -1 should be treated as +Infinity because
    it marks brackets that are unreachable along the shortest path between the
    cursor and the outside of the bracket expression.

    Args:
        [per_cursor_indices]
            - a list of index lists assigned to the same bracket set
              over a set of cursors
    Returns:
        [indices] - the resulting flattened index list for the brackets
    """
    def outer_min(o1, o2):
        return max(o1, o2) if (o1 == -1) or (o2 == -1) else min(o1, o2)

    def index_minimum(((o1, i1), (o2, i2))):
        return outer_min(o1, o2), min(i1, i2)

    def merge_indices(current_min, next):
        return map(index_minimum, zip(current_min, next))

    return reduce(merge_indices, per_cursor_indices)

#
# Scopes
#

def compute_bracket_scopes(brackets, indices):
    """Computes bracket scopes from brackets and their indices.

    A pair of 'matching' brackets form a scope. Brackets match when they are
    the left and right one, and have the same index. Each bracket can belong
    to at most one scope. A bracket can belong to no scope if the region does
    not include the corresponding matching bracket.

    Args:
        [brackets] - a list of brackets where the scopes are to be found

        [indices] - a list of indices of the corresponding brackets

    Returns:
        [scopes] - the resulting list of bracket scopes
    """
    def indices_equal((o1, i1), (o2, i2)):
        return (o1 == o2) and (i1 == i2)

    scopes = []

    indexed_brackets = zip(indices, brackets)

    for i, (left_index, left_bracket) in enumerate(indexed_brackets):
        if left_bracket.is_right(): continue

        remaining_brackets = enumerate(indexed_brackets[i+1:], i+1)
        for j, (right_index, right_bracket) in remaining_brackets:
            if right_bracket.is_left(): continue

            if indices_equal(left_index, right_index):
                scopes.append(Scope(left_index, left_bracket, right_bracket))
                break

    return scopes