text:
// ctrlext.cpp :
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

#include "stdafx.h"
#include "ctrlext.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define new DEBUG_NEW

#define _AFXCTL_INLINE inline

const CTreeCursor& CTreeCursor::operator = ( const CTreeCursor& posSrc )
{
	if( &posSrc != this ){
		m_hTreeItem= posSrc.m_hTreeItem;
		m_pTree= posSrc.m_pTree;
	}
	return *this;
}

CTreeCursor CTreeCursor::_Insert( LPCTSTR strItem, int nImageNorm, int nImageSel, HTREEITEM hAfter )
{
	TV_INSERTSTRUCT ins;
	ins.hParent= m_hTreeItem;
	ins.hInsertAfter= hAfter;
	ins.item.mask= TVIF_TEXT;
	ins.item.pszText= (LPTSTR)strItem;
	if( nImageNorm != -1 )
	{
		ins.item.mask|= TVIF_IMAGE | TVIF_SELECTEDIMAGE;
		ins.item.iImage= nImageNorm;
		ins.item.iSelectedImage= nImageSel == -1 ? nImageNorm : nImageSel;
	}
	return CTreeCursor( m_pTree->InsertItem( &ins ), m_pTree );
}

int CTreeCursor::GetChildCount( )
{
	HTREEITEM hChildItem = m_pTree->GetChildItem( m_hTreeItem );
	int count= 0;
	for( ; hChildItem; )
	{
		++count;
		hChildItem= m_pTree->GetNextSiblingItem( hChildItem );
	}
	return count;
}

int CTreeCursor::GetImageID( )
{
	TV_ITEM item;
	item.mask= TVIF_HANDLE | TVIF_IMAGE;
	item.hItem= m_hTreeItem;
	m_pTree->GetItem( &item );
	return item.iImage;
}

void CTreeCursor::DeleteAllChildren( )
{
	HTREEITEM item;
	while( m_hTreeItem != NULL && m_pTree->ItemHasChildren( m_hTreeItem ) )
	{
		item= m_pTree->GetChildItem( m_hTreeItem );
		if( m_pTree->ItemHasChildren( item ) )
		{
			CTreeCursor tc( item, m_pTree );
			tc.DeleteAllChildren( );
		}
		m_pTree->DeleteItem( item );
	}

//if (pmyTreeCtrl->ItemHasChildren(hmyItem))
//{
//   HTREEITEM hNextItem;
//   HTREEITEM hChildItem = pmyTreeCtrl->GetChildItem(hmyItem);
//
//   while (hChildItem != NULL)
//   {
//      hNextItem = pmyTreeCtrl->GetNextItem(hChildItem, TVGN_NEXT);
//      pmyTreeCtrl->DeleteItem(hChildItem);
//      hChildItem = hNextItem;
//   }
//}
}

void CTreeCursor::SetHasChildern( )
{
	TVITEM tvi;
	tvi.cChildren= 1;
	tvi.mask= TVIF_CHILDREN;
	tvi.hItem= m_hTreeItem;
	m_pTree->SetItem( &tvi );
}

// ...........................................
CTreeCursor CTreeCtrlTraverse::GetNextNode( )
{
	CTreeCursor tc;

	if( !depth )
		return CTreeCursor( NULL, &tree_ctrl );

	if( CTreeCursor( tree_pos, &tree_ctrl ).HasChildren( ) )
	{
		++depth;
		tree_pos= CTreeCursor( tree_pos, &tree_ctrl ).GetChild( );
		return CTreeCursor( tree_pos, &tree_ctrl );
	}
	else if( CTreeCursor( tree_pos, &tree_ctrl ).GetNextSibling( ).IsValid( ) )
	{
		tree_pos= CTreeCursor( tree_pos, &tree_ctrl ).GetNextSibling( );
		return CTreeCursor( tree_pos, &tree_ctrl );
	}
	else
	{
		do
		{
			tree_pos= CTreeCursor( tree_pos, &tree_ctrl ).GetParent( ).GetNextSibling( );
		}
		while( --depth && ! tree_pos );
		return CTreeCursor( tree_pos, &tree_ctrl );
	}
}

//IMPLEMENT_DYNCREATE( CTreeCtrlEx, CTreeCtrl )
IMPLEMENT_DYNAMIC( CTreeCtrlEx, CTreeCtrl )
BEGIN_MESSAGE_MAP( CTreeCtrlEx, CTreeCtrl )
	ON_WM_LBUTTONDOWN( )
END_MESSAGE_MAP()

void CTreeCtrlEx::OnLButtonDown( UINT nFlags, CPoint point )
{
	TREECLICKA nr;
	nr.hit_info= { point, 0, NULL };
	HitTest( &nr.hit_info );

	nr.hdr.code= TCN_LMOUSEBUTTON;//NOTE: in this projects resource range
	nr.hdr.hwndFrom= GetSafeHwnd( );
	nr.hdr.idFrom= GetDlgCtrlID( );
	nr.mouse_flags= nFlags;
	nr.ptClick= point;
	nr.pClass= this;

//		nr.dwFlags= 0;
	if( GetParent( )->SendMessage( WM_NOTIFY, GetParent( )->GetDlgCtrlID( ), (LPARAM)&nr ) )
		return;

	CTreeCtrl::OnLButtonDown( nFlags, point );
//	OnButtonDown( TRUE, nFlags, point);
}

/*
// .....................................................................
IMPLEMENT_DYNAMIC( CTreeCtrlEx, CMultiTree )
BEGIN_MESSAGE_MAP( CTreeCtrlEx, CMultiTree )
	ON_WM_LBUTTONDOWN( )
	ON_WM_KEYDOWN( )

END_MESSAGE_MAP( )

void CTreeCtrlEx::OnLButtonDown( UINT nFlags, CPoint point )
{
	// Set focus to control if key strokes are needed.
	// Focus is not automatically given to control on lbuttondown

	m_dwDragStart = GetTickCount( );

	if(nFlags & MK_CONTROL )
	{
		// Control key is down
		UINT flag;
		HTREEITEM hItem = HitTest( point, &flag );
		if( hItem )
		{
			// Toggle selection state
			UINT uNewSelState =
			GetItemState(hItem, TVIS_SELECTED) & TVIS_SELECTED ?
			0 : TVIS_SELECTED;
			// Get old selected (focus) item and state
			HTREEITEM hItemOld = GetSelectedItem( );
			UINT uOldSelState = hItemOld ?	GetItemState( hItemOld, TVIS_SELECTED ) : 0;
			// Select new item
			if( GetSelectedItem() == hItem )
			SelectItem( NULL );	// to prevent edit
//			CTreeCtrl::OnLButtonDown( nFlags, point );

			// Set proper selection (highlight) state for new item
			SetItemState(hItem, uNewSelState, TVIS_SELECTED);

			// Restore state of old selected item
			if (hItemOld && hItemOld != hItem)
			SetItemState(hItemOld, uOldSelState, TVIS_SELECTED);

			m_hItemFirstSel = NULL;

			return;
		}
	}
	else if(nFlags & MK_SHIFT)
	{
		// Shift key is down
		UINT flag;
		HTREEITEM hItem = HitTest( point, &flag );

		// Initialize the reference item if this is the first shift selection
		if( !m_hItemFirstSel )
		m_hItemFirstSel = GetSelectedItem();

		// Select new item
		if( GetSelectedItem() == hItem )
		SelectItem( NULL );	// to prevent edit
		CTreeCtrl::OnLButtonDown(nFlags, point);

		if( m_hItemFirstSel )
		{
			SelectItems( m_hItemFirstSel, hItem );
			return;
		}
	}
	else
	{
		// Normal - remove all selection and let default
		// handler do the rest
		ClearSelection( );
		m_hItemFirstSel = NULL;
	}
	CTreeCtrl::OnLButtonDown(nFlags, point);
}

// SelectItems - Selects items from hItemFrom to hItemTo. Does not
// - select child item if parent is collapsed. Removes
// - selection from all other items
// hItemFrom - item to start selecting from
// hItemTo - item to end selection at.
BOOL CTreeCtrlEx::SelectItems( HTREEITEM hItemFrom, HTREEITEM hItemTo )
{
	HTREEITEM hItem = GetRootItem();

	// Clear selection upto the first item
	while ( hItem && hItem!=hItemFrom && hItem!=hItemTo )
	{
	hItem = GetNextVisibleItem( hItem );
	SetItemState( hItem, 0, TVIS_SELECTED );
	}

	if ( !hItem )
	return FALSE;	// Item is not visible

	SelectItem( hItemTo );

	// Rearrange hItemFrom and hItemTo so that hItemFirst is at top
	if( hItem == hItemTo )
	{
	hItemTo = hItemFrom;
	hItemFrom = hItem;
	}

	// Go through remaining visible items
	BOOL bSelect = TRUE;
	while ( hItem )
	{
	// Select or remove selection depending on whether item
	// is still within the range.
	SetItemState( hItem, bSelect ? TVIS_SELECTED : 0, TVIS_SELECTED );

	// Do we need to start removing items from selection
	if( hItem == hItemTo )
	bSelect = FALSE;

	hItem = GetNextVisibleItem( hItem );
	}

	return TRUE;
}

void CTreeCtrlEx::ClearSelection( )
{
	// This can be time consuming for very large trees
	// and is called every time the user does a normal selection
	// If performance is an issue, it may be better to maintain
	// a list of selected items
	for ( HTREEITEM hItem=GetRootItem(); hItem!=NULL; hItem= CTreeCtrl::GetNextItem( hItem, TVGN_NEXT ) )
		if ( GetItemState( hItem, TVIS_SELECTED ) & TVIS_SELECTED )
			SetItemState( hItem, 0, TVIS_SELECTED );
}

void CTreeCtrlEx::OnKeyDown( UINT nChar, UINT nRepCnt, UINT nFlags )
{
	if ( (nChar==VK_UP || nChar==VK_DOWN) && GetKeyState( VK_SHIFT )&0x8000)
	{
	// Initialize the reference item if this is the first shift selection
	if( !m_hItemFirstSel )
	{
	m_hItemFirstSel = GetSelectedItem();
	ClearSelection();
	}

	// Find which item is currently selected
	HTREEITEM hItemPrevSel = GetSelectedItem();

	HTREEITEM hItemNext;
	if ( nChar==VK_UP )
	hItemNext = GetPrevVisibleItem( hItemPrevSel );
	else
	hItemNext = GetNextVisibleItem( hItemPrevSel );

	if ( hItemNext )
	{
	// Determine if we need to reselect previously selected item
	BOOL bReselect =
	!( GetItemState( hItemNext, TVIS_SELECTED ) & TVIS_SELECTED );

	// Select the next item - this will also deselect the previous item
	SelectItem( hItemNext );

	// Reselect the previously selected item
	if ( bReselect )
	SetItemState( hItemPrevSel, TVIS_SELECTED, TVIS_SELECTED );
	}
	return;
	}
	else if( nChar >= VK_SPACE )
	{
	m_hItemFirstSel = NULL;
	ClearSelection( );
	}
	CTreeCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
}

HTREEITEM CTreeCtrlEx::GetFirstSelectedItemX( )
{
	for ( HTREEITEM hItem = GetRootItem( ); hItem!=NULL; hItem = GetNextItem( hItem, TVGN_NEXT ) )
	if ( GetItemState( hItem, TVIS_SELECTED ) & TVIS_SELECTED )
	return hItem;

	return NULL;
}

HTREEITEM CTreeCtrlEx::GetNextSelectedItemX( HTREEITEM hItem )
{
	for ( hItem = GetNextItem( hItem, TVGN_NEXT ); hItem!=NULL; hItem = GetNextItem( hItem, TVGN_NEXT ) )
	if ( GetItemState( hItem, TVIS_SELECTED ) & TVIS_SELECTED )
	return hItem;

	return NULL;
}

HTREEITEM CTreeCtrlEx::GetPrevSelectedItemX( HTREEITEM hItem )
{
	for ( hItem = GetPrevVisibleItem( hItem ); hItem!=NULL; hItem = GetPrevVisibleItem( hItem ) )
	if ( GetItemState( hItem, TVIS_SELECTED ) & TVIS_SELECTED )
	return hItem;

	return NULL;
}

*/


text:
import os
import re
import sys
import urllib

try:
    import unittest2 as unittest
except ImportError:
    import unittest

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

from http_spec import WSGITestBase

FWRD_PATH = '/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[0:-1])

if FWRD_PATH not in sys.path:
    sys.path.insert(1, FWRD_PATH)

from FWRD import Request, ResponseParameterError

class GetRequestSpec(WSGITestBase):
    """GET request spec"""

    def setUp(self):
        super(self.__class__, self).setUp()
        self.app.reset()
        self.app.config.formats['xsl'] = {
            'stylesheet': 'translated_response_spec.xsl',
            }
        self.app.router.clear()

    def it_should_parse_file_extensions_correctly(self):
        self.app.router.add('/foo/bar', None)
        self.make_request('/foo/bar.baz')
        self.assertEqual('baz', self.app.request.path[1])

        self.app.router.add('/foo.bar/boz', None)
        self.make_request('/foo.bar/boz.baz')
        self.assertEqual('baz', self.app.request.path[1])

    def it_should_parse_GET_params_correctly(self):
        self.app.router.add('/', None)
        self.make_request('/', qs='a=1&b[]=2&b[]=3&baz=true&b=4&b[foo]=bar&tel=01234567890&c[foo-bar]=baz')

        params = {
            'a': 1,
            'b': {'foo': 'bar'},
            'baz': True,
            'tel': '01234567890',
            'c': {'foo-bar': 'baz'},
            }

        for key, value in params.iteritems():
            self.assert_(key in self.app.request['GET'])
            self.assertEqual(value, self.app.request['GET'][key])

    def it_should_parse_float_params_correctly(self):
        self.app.router.add('/', None)
        self.make_request('/', qs='a=1.0&b=-2.4&c=53.1,32.2')

        params = {
            'a': float('1.0'),
            'b': float('-2.4'),
            'c': "53.1,32.2"
            }

        for key, value in params.iteritems():
            self.assert_(key in self.app.request['GET'])
            self.assertEqual(value, self.app.request['GET'][key])

    def it_should_match_basic_routes_correctly(self):
        routes = ['/', '/foo', '/bar']
        for route in routes:
            self.app.router.add(route, None)

        for route in routes:
            self.assertStatus(200, route=route)

    def it_should_match_parametered_routes_correctly(self):

        def foo(foo):
            pass

        def bar(dept, name=None):
            pass

        routes = {
            ('/:foo', foo): {
                '/meh': {
                    'foo': 'meh'
                    },
                '/blah': {
                    'foo': 'blah'
                    }
                },
            ('/company/:dept[/:name]', bar): {
                '/company/it': {
                    'dept': 'it'
                    },
                '/company/it/support': {
                    'dept': 'it',
                    'name': 'support'
                    },
                '/company/hr/grievance%20councelling': {
                    'dept': 'hr',
                    'name': 'grievance councelling'
                    }
                }
            }

        for route, requests in routes.iteritems():
            self.app.router.add(route[0], route[1])

            for request, params in requests.iteritems():
                self.make_request(request)

                for name, value in params.iteritems():
                    self.assert_(name in self.app.request.PATH)
                    self.assert_(name in self.app.request.params)
                    self.assertEqual(value, self.app.request.PATH[name])
                    self.assertEqual(value, self.app.request.params[name])

    def it_should_format_responses_correctly(self):

        def index():
            return "index"

        def foo():
            return {
                'a': True,
                'b': False
                }

        routes = []

        # route, extension, func, xpath:value
        routes.append(('/', '.xml', index, OrderedDict({
            '/response/@route': '/',
            '/response/@request': '/',
            '/response/@method': 'get',
            '/response/content': 'index',
            })))
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/" request="/" method="get">
  <content>index</content>
  <errors/>
</response>
'''
        # route, extension, func, xpath:value
        routes.append(('/foo', '.xml', foo, OrderedDict({
            '/response/@route': '/foo',
            '/response/@request': '/foo',
            '/response/@method': 'get',
            '/response/content/a/@nodetype': 'boolean',
            '/response/content/b/@nodetype': 'boolean',
            '/response/content/a': 'true',
            '/response/content/b': 'false',
            })))
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/foo" request="/foo" method="get">
  <content>
    true
    false
  </content>
  <errors/>
</response>
'''

        for route, ext, func, xpath in routes:
            self.app.router.add(route, func)

        for route, ext, func, xpath in routes:
            self.assertXPath(xpath, route=route+ext)

    def it_should_format_whitespace_correctly(self):

        def bar():
            return """This is a long string

With lots of whitespace

    To show correct formatting

"""

        routes =[]

        # route, extension, func, body
        routes.append(('/bar', '.xml', bar, OrderedDict({
            '/response/@route': '/bar',
            '/response/@request': '/bar',
            '/response/@method': 'get',
            '/response/content': '''This is a long string

With lots of whitespace

    To show correct formatting

'''
            })))
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/bar" request="/bar" method="get">
  <content>This is a long string

With lots of whitespace

    To show correct formatting

</content>
  <errors/>
</response>
'''

        for route, ext, func, xpath in routes:
            self.app.router.add(route, func)

        for route, ext, func, xpath in routes:
            self.assertXPath(xpath, route=route+ext)

    def it_should_ignore_additional_qs_args(self):

        def foo(foo): pass
        self.app.router.add('/unexpected_params', foo)
        self.assertStatus(200, '/unexpected_params.xml', qs='foo=1&bar=2')
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/unexpected_params" request="/unexpected_params" method="get">
  <content/>
  <errors/>
</response>
'''
        self.assertXPath({
            '/response/@route': '/unexpected_params',
            '/response/@request': '/unexpected_params',
            '/response/@method': 'get',
            '/response/content': None,
            '/response/errors': None,
            }, route='/unexpected_params.xml', qs='foo=1&bar=2')

    def it_should_process_filters_successfully(self):
        config = StringIO('''
Config:
  app_path: %s
Routes:
  - route: /[index]
    filters:
      - callable: specs.example_methods:basic_filter
        args:
          message: hello world
        ''' % os.path.dirname(os.path.abspath(__file__)))

        self.assertTrue(self.app.setup(config) != False)
        self.assertStatus(200, '/index.xml')
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/[index]" request="/index" method="get">
  <content nodetype="fixed-list">
    hello world

  </content>
  <errors/>
</response>
'''
        self.assertXPath({
            '/response/@route': '/[index]',
            '/response/@request': '/index',
            '/response/@method': 'get',
            '/response/content/@nodetype': 'fixed-list',
            '/response/content/i[1]': 'hello world',
            '/response/content/i[2]': None,
            '/response/errors': None,
            }, route='/index.xml')

    def it_should_process_multiple_filters_successfully(self):
        config = StringIO('''
Config:
  app_path: %s
Routes:
  - route: /[index]
    filters:
      - callable: specs.example_methods:hello_filter
      - callable: specs.example_methods:world_filter
        ''' % os.path.dirname(os.path.abspath(__file__)))

        self.assertTrue(self.app.setup(config) != False)
        self.assertStatus(200, '/index.xml')
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/[index]" request="/index" method="get">
  <content nodetype="fixed-list">
    hello

      world

  </content>
  <errors/>
</response>
'''

        self.assertXPath({
            '/response/@route': '/[index]',
            '/response/@request': '/index',
            '/response/@method': 'get',
            '/response/content/@nodetype': 'fixed-list',
            '/response/content/i[1]': 'hello',
            '/response/content/i[2]/@nodetype': 'fixed-list',
            '/response/content/i[2]/i[1]': 'world',
            '/response/content/i[2]/i[2]': None,
            '/response/errors': None,
            }, route='/index.xml')

    def it_should_process_global_filters_correctly(self):
        config = StringIO('''
Config:
  app_path: %s
Global Filters:
  - callable: specs.example_methods:hello_filter
Routes:
  - route: /[index]
    filters:
      - callable: specs.example_methods:world_filter
        ''' % os.path.dirname(os.path.abspath(__file__)))

        self.assertTrue(self.app.setup(config) != False)
        self.assertStatus(200, '/index.xml')
        # expects a body in the following format
        '''<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<response route="/[index]" request="/index" method="get">
  <content nodetype="fixed-list">
    hello

      world

  </content>
  <errors/>
</response>
'''

        self.assertXPath({
            '/response/@route': '/[index]',
            '/response/@request': '/index',
            '/response/@method': 'get',
            '/response/content/@nodetype': 'fixed-list',
            '/response/content/i[1]': 'hello',
            '/response/content/i[2]/@nodetype': 'fixed-list',
            '/response/content/i[2]/i[1]': 'world',
            '/response/content/i[2]/i[2]': None,
            '/response/errors': None,
            }, route='/index.xml')

class PostRequestSpec(WSGITestBase):
    '''POST request spec'''

    def setUp(self):
        super(self.__class__, self).setUp()
        self.app.config.formats['xsl'] = {
            'stylesheet': 'translated_response_spec.xsl',
            }

    def it_should_parse_params_correctly(self):
        self.app.router.add('/', None, methods='GET,POST')
        self.make_request('/', method='POST', qs='a=1&b[]=2&b[]=3&baz=true&b=4&b[foo]=bar&tel=01234567890')

        params = {
            'a': 1,
            'b': {'foo': 'bar'},
            'baz': True,
            'tel': '01234567890'
            }

        self.assertEqual(self.app.request['POST'], params)

    def it_should_parse_grouped_params_correctly(self):
        self.app.router.add('/', None, methods='POST')
        self.make_request('/', method='POST', qs="a[x]=1&a[y]=2&a[z][]=3&a[z][]=4&a[z][]=5&b[foo][0]=foo&b[foo][1]=bar")

        params = {
            'a': {
                'x': 1,
                'y': 2,
                'z': [3,4,5],
                },
            'b': {'foo': {
                '0': 'foo',
                '1': 'bar',
                }},
            }

        self.assertEqual(self.app.request['POST'], params)

    def it_should_unquote_params_correctly(self):
        self.app.router.add('/', None, methods='POST')
        self.make_request('/', method='POST', qs="a=%26+%26+%26")

        params = {
            'a': '& & &'
            }

        self.assertEqual(self.app.request['POST'], params)

    def it_should_parse_non_ascii_characters(self):
        self.app.router.add('/', None, methods='POST')
        self.make_request('/', method='POST', qs='a='+urllib.quote_plus("\u017D"))

        params = {
            'a': "\u017D" # Latin Z with caron
            }

        self.assertEqual(self.app.request['POST'], params)

    def it_should_parse_multipart_posts_correctly(self):
        self.skipTest('Not yet implemented')

    def ensure_get_does_not_clobber_post_params(self):
        """ensure GET does not clobber POST params"""
        self.skipTest('Not yet implemented')

    def it_should_not_allow_incorrect_content_length(self):
        self.skipTest('Not yet implemented')

redpajama_set_name: RedPajamaGithub


text:
		<TITLE>
			Tutorial 2: Build a Genetic Algorithm for an Integer Problem
		</TITLE>

						ECJ

				Tutorial 2: Build a Genetic Algorithm for an Integer Problem

			In the second tutorial, we will build a generational GA for a problem requiring our individuals to be integer vectors.  The tutorial will also delve into many specific aspects of ECJ, including how to use parameter files and parent parameters, the relationship between species and individuals, how to make custom breeding operators and pipelines, how to run with more than one thread of execution, how to base the seeds on the wall clock time, and how to print out parameter information.

			If you've not done Tutorial 1, I suggest you do so.

				Create an app subdirectory and parameters file

			Go into the <tt>ec/app</tt> directory and create a directory called <tt>tutorial2</tt>. In this directory, create a file called <tt>tutorial2.params</tt>. In this file, add as a first line the following: <tt>

parent.0		= ../../simple/simple.params

			</tt>

			This specifies that <tt>../../simple/simple.params </tt> will be the first parent of our parameter file. This means that if the parameter is not specified in <tt>tutorial.params</tt>, ECJ will next look in <tt>../../simple/simple.params</tt> to find that parameter.

			 As discussed in the introduction to Parameter files, ECJ has a particular way of looking up parameters. When a parameter is requested by the system, ECJ tries the following in order:

ECJ looks to see if it was dynamically set by the system at some point by something which directly called the <tt>set</tt> method in the ec.util.ParameterDatabase. In ECJ, this presently never occurs (no class directly sets values in the database).

ECJ looks to see if the user had specified the parameter on the command line with the <tt>-p</tt> option.

ECJ looks in the root <tt>params</tt> file that was specified on the command line with the <tt>-file</tt> option.

ECJ starts looking through parent parameter files specified with <tt>parent.x</tt> declarations, starting with those declared in the root. The figure at right shows an example. This is done in a depth-first, left-to-right, preorder fashion. The rule is: a parameter file is checked before its parent parameter files are checked, and <tt>parent.x</tt> and its parents are checked before <tt>parent.x+1</tt> and its parents are checked. In case you were wondering, <tt>0</tt> is the smallest legal value of <tt>x</tt>.

			Most ECJ packages have parameter files which lay out some default parameters to help you get started, so you don't have to type them in yourself. The <tt>../../simple/simple.params</tt> file in particular lays out common parameter settings. It lays out a lot of parameters which had to be explicitly specified in Tutorial 1, namely:

						<tt>

state =                                 ec.simple.SimpleEvolutionState
init =                                  ec.simple.SimpleInitializer
finish =                                ec.simple.SimpleFinisher
exch =                                  ec.simple.SimpleExchanger
breed =                                 ec.simple.SimpleBreeder
eval =                                  ec.simple.SimpleEvaluator
stat =                                  ec.simple.SimpleStatistics
generations =                           51
quit-on-run-complete =                  true
pop =                                   ec.Population
pop.subpops =                           1
pop.subpop.0 =                          ec.Subpopulation
pop.subpop.0.size =                     1024
stat.file                               $out.stat

						</tt>

			These parameters specify a standard generational evolution procedure, with a very basic statistics object, a single subpopulation of 1024 individuals, 51 generations, and a simple, one-objective Fitness. The statistics object writes out to the <tt>out.stat</tt> file, located in the directory where we issued our command (that's what the $ is for -- without it, it'd be located in the directory where the <tt>simple.params</tt> file was located).

			Some of these parameters are inappropriate for a genetic algorithm: in the <tt>tutorial2.params</tt> file, we'll override two of them: <tt>

pop.subpop.0.size = 100
generations = 200

			</tt>

			<tt>simple.params</tt> in turn relies on a parent of its own: <tt>ec.params</tt>, located in the <tt>ec</tt> directory. <tt>ec.params</tt> specifies the following default parameter settings for us, so we don't have to:

						<tt>

store =                                 true
flush =                                 true
evalthreads =                           1
breedthreads =                          1
seed.0 =                                4357
gc =                                    false
gc-modulo =                             1
aggressive =                            true
checkpoint =                            false
checkpoint-modulo =                     1
checkpoint-prefix =                     ec

						</tt>

			You'll notice these are the same parameters that we typed in by hand in Tutorial 1. Now we don't have to. So what do we have to specify? Mostly, we have to specify the representation, problem domain, and breeding pipeline.

				Define the Representation -- And All About Species

			Our representation this time will be a vector of 20 integers. The integer values will be permitted to range from -12312 to 2341212 (why those values? Why not?). We begin by specifying the individual, an ec.vector.IntegerVectorIndividual. <tt>

pop.subpop.0.species		= ec.vector.IntegerVectorSpecies
pop.subpop.0.species.ind	= ec.vector.IntegerVectorIndividual
pop.subpop.0.species.fitness = ec.simple.SimpleFitness

			</tt>

			IntegerVectorIndividuals, among others, use a special species called ec.vector.IntegerVectorSpecies. Species objects are set up in a one-to-many arrangement with Individuals: a subpopulation of Individuals will all share the same Species instance. The basic purpose of a Species object is to provide a place where you can store non-constant information that needs to be shared among all the Individuals in subpopulation. You'll see this many-to-one pattern in lots of other places.

			Why not just store shared information as static member variables directly in IntegerVectorIndividual? Two reasons. First, static variables are very difficult to serialize, and that messes up ECJ's checkpointing. Second, this would tie storage to a given class name. Let's say you have two subpopulations, both with IntegerVectorIndividual, but one subpopulation consists of individuals whose genes range from -1 to 4 and the other subpopulation consists of individuals whose genes range from -10 to 10. If the global min and max values are stored as class variables in IntegerVectorIndividual, then you've got a problem. But if they're separately stored in shared Species instances, each group can have its own Species.

			Why not just store shared information in the Subpopulation? After all, all the individuals belong to the same subpopulation, right? That's true, but only for that generation. Subpopulations are groups which are very similar in function to prototypes: Subpopulations can create new Subpopulations. We need a more permanent storage facility.

			IntegerVectorSpecies is a subclass of ec.vector.VectorSpecies (which we used in Tutorial 1 for our BitVectorIndividuals). VectorSpecies is in turn a subclass of ec.Species. As stipulated in its documentation, IntegerVectorSpecies requires two parameters: <tt>min-gene</tt> and <tt>max-gene</tt>, which specify the minimum and maximum values the integers may take on. You can also specify them on a gene-by-gene basis, but we'll just do a default for all genes as: <tt>

# Note that min-gene and max-gene are defined in the SPECIES, not in the INDIVIDUAL
pop.subpop.0.species.min-gene	= -12312
pop.subpop.0.species.max-gene 	= 2341212

			</tt>

			VectorSpecies requires some parameters: the genome size, the chunk size (which specifies crossover boundaries -- usually it's just 1), the crossover type (if we do crossover), the probability that uniform crossover (if we use it) will cross over a gene, and the probability that a gene will get mutated (if we do mutation). We enter them as follows: <tt>

pop.subpop.0.species.genome-size	= 20
pop.subpop.0.species.crossover-type	= two
pop.subpop.0.species.crossover-prob	= 1.0
pop.subpop.0.species.mutation-prob	= 0.05

			</tt>

			We don't need to specify the chunk size -- it'll by default be set to 1 for us. The parameters above say that the genome consists of 20 integers, we'll use two-point crossover (so <tt>crossover-prob</tt> doesn't really matter), and we'll mutate with a gene-independent probability of <tt>0.05</tt>.

			Besides <tt>ind</tt>, Species has parameters which specify the breeding pipeline. Let's do that next.

				Specify the Breeding Pipeline

			To introduce various new features, we'll design a preposterous breeding pipeline. The pipeline will pick two parents, one by fitness proportionate selection, and one through a tournament selection (of size 5) which always returns the worst individual in the tournament. These two parents will be crossed over (using two-point crossover as specified above), but only the child of the first parent will be used (the other will be thrown away). The child will then be mutated, with our specified gene-by-gene 0.05 probability, but the mutation procedure will flip the minus-sign of the integer, and that's all. Don't expect this to optimize very well! :-)

			We begin at the end, by specifying a custom mutation class (which we'll make later): <tt>

# Use our own custom mutation class
pop.subpop.0.species.pipe = ec.app.tutorial2.OurMutatorPipeline
pop.subpop.0.species.pipe.source.0	= ec.vector.breed.VectorCrossoverPipeline
# Toss the second child
pop.subpop.0.species.pipe.source.0.toss = true
pop.subpop.0.species.pipe.source.0.source.0 = ec.select.FitProportionateSelection
pop.subpop.0.species.pipe.source.0.source.1 = ec.select.TournamentSelection
pop.subpop.0.species.pipe.source.0.source.1.size = 5
# Pick the worst individual in the tournament
pop.subpop.0.species.pipe.source.0.source.1.pick-worst = true

			</tt>

			Now we have to write the mutation class. In the <tt>tutorial2</tt> directory, create a file called <tt>OurMutatorPipeline.java</tt>.  Add the following to the file:

<tt>

package ec.app.tutorial2;
import ec.vector.*;
import ec.*;
import ec.util.*;

/*
 * OurMutatorPipeline.java
 */

/**
 OurMutatorPipeline is a BreedingPipeline which negates the sign of genes.
 The individuals must be IntegerVectorIndividuals.  Because we're lazy,
 we'll use the individual's species' mutation-probability parameter to tell
 us whether or not to mutate a given gene.

 <p><b>Typical Number of Individuals Produced Per <tt>produce(...)</tt> call</b><br>
 (however many its source produces)

 <p><b>Number of Sources</b><br>
 1
*/
public class OurMutatorPipeline extends BreedingPipeline
    {

</tt>

OurMutatorPipeline is a BreedingPipeline, which means it is a non-leaf node in the breeding pipeline tree, responsible not for selection of individuals but for modification of whatever is handed to it.  BreedingPipelines are ec.Prototypes and so must define various methods, most of which have (empty) default implementations in BreedingPipeline for you, to make implementation easier for you..  The only Prototype method which is not explicitly handled is <tt>defaultBase(...)</tt>, which specifies the default parameter dabase for OurMutatorPipeline.  Since we have no parameters
	    that we're loading (we're stealing the mutation-probability parameter from elsewhere), there's no
		need for a base, but we define a simple one anyway:

<tt>

    //used only for our default base
    public static final String P_OURMUTATION = "our-mutation";

    // We have to specify a default base, even though we never use it
    public Parameter defaultBase() { return VectorDefaults.base().push(P_OURMUTATION); }

</tt>

Next, BreedingPipeline stipulates that we have to state how many sources our breeding pipeline must have (it can be variable or a fixed number).  In our case, we have just a single breeding source.  We take all our individuals from that source and mutate them and return them.

<tt>

    public static final int NUM_SOURCES = 1;

    // Return 1 -- we only use one source
    public int numSources() { return NUM_SOURCES; }

</tt>

Here's the main part of the class.  We have to implement the <tt>produce(...)</tt> method, which fills an array with "bred" individuals and returns it.  We get those individuals by asking our source for them, then mutating them as we please.  The method looks like this:

<tt>

    // We're supposed to create a most _max_ and at least _min_ individuals,
    // drawn from our source and mutated, and stick them into slots in inds[]
    // starting with the slot inds[start].  Let's do this by telling our
    // source to stick those individuals into inds[] and then mutating them
    // right there.  produce(...) returns the number of individuals actually put into inds[]
    public int produce(final int min,
		       final int max,
		       final int start,
		       final int subpopulation,
		       final Individual[] inds,
		       final EvolutionState state,
		       final int thread) throws CloneNotSupportedException
        {

</tt>

The <tt>CloneNotSupportedException</tt> is there because in some situations produce(...) might use a clone(...) method call.  In this example, we don't.

The easy way to mutate is to just ask our source to stick those individuals into <tt>inds[]</tt>, and then mutate them.  We also have to make sure that they're they're copies -- we don't want to stick original individuals from the previous population into the next one.  This is a guarantee that all BreedingPipelines must make.  We keep this guarantee by checking to see what our source is.  If it's
			a BreedingPipeline too, it already copied the individuals for us (keeping it's guarantee).  If
		  it's a SelectionMethod, the individuals aren't copies but originals, so we need to copy them.

First we need to figure out how many individuals we'll produce.  We can do this in two ways.  First, we could compute how many individuals we want beforehand: for example, Crossover operations typicaly produce two individuals no matter what, unless they're forced to (say) produce a single individual.  But since we're making a mutator, we'll take a different tack: we simply ask our sources to produce some number of individuals (their choice), then we mutate all those individuals and return them.  In this case, we first produce the individuals, and the variable n is set to how many were created:

<tt>

        // grab individuals from our source and stick 'em right into inds.
        // we'll modify them from there
        int n = sources[0].produce(min,max,start,subpopulation,inds,state,thread);

</tt>

Next we need to determine if we should bother mutating these individuals at all.  With a certain probability we will just return the individuals unmutated:

<tt>

	// should we bother?
	if (!state.random[thread].nextBoolean(likelihood))
		// DON'T produce children from source -- we already did
		return reproduce(n, start, subpopulation, inds, state, thread, false);

</tt>

If we've gotten this far, it's time to actually mutate the individuals we got from our source.  We'll first
copy them if the source isn't a BreedingPipeline.
Copying is done through the <tt>clone()</tt> method.  This is a method in Individual which is guaranteed to creat
e a deep clone of the individual, including its Fitness.  In some situations (such as crossing over GPIndividuals, w
here cloning the individual is very expensive) you may wish to light clone the Individual, then clone parts of it as
 necessary.  In that case you can judiciously use <tt>lightClone()</tt> instead.  But that's not very common.

<tt>

        // clone the individuals if necessary -- if our source is a BreedingPipeline
        // they've already been cloned, but if the source is a SelectionMethod, the
        // individuals are actual individuals from the previous population
        if (!(sources[0] instanceof BreedingPipeline))
            for(int q=start;q<n+start;q++)
                inds[q] = (Individual)(inds[q].clone());

</tt>

Next we'll test to make certain that the individuals are in fact IntegerVectorIndividuals.  It's a quick hack of a test, not a complete one, but usually the complete one is unnecessary.  We'll also extract
	the IntegerVectorSpecies object the individuals are sharing, so we can get the per-gene <tt>mutationProbability</tt>
	value out of it.

<tt>

        // Check to make sure that the individuals are IntegerVectorIndividuals and
        // grab their species.  For efficiency's sake, we assume that all the
        // individuals in inds[] are the same type of individual and that they all
        // share the same common species -- this is a safe assumption because they're
        // all breeding from the same subpopulation.

        if (!(inds[start] instanceof IntegerVectorIndividual))
            // uh oh, wrong kind of individual
            state.output.fatal("OurMutatorPipeline didn't get an " +
            "IntegerVectorIndividual.  The offending individual is " +
            "in subpopulation " + subpopulation + " and it's:" + inds[start]);
        IntegerVectorSpecies species = (IntegerVectorSpecies)(inds[start].species);

</tt>

Now we're ready to go through the individuals and mutate them.  For each gene in each individual,
we'll flip a coin of per-gene <tt>mutationProbability</tt>, and change the sign of the gene if it comes up heads.
We set the flag in the individual indicating that its evaluation is invalid and needs to be reevaluated.
Finally, we'll return the number of individuals we created (<tt>n</tt>), and the class is done:

<tt>

        // mutate 'em!
        for(int q=start;q<n+start;q++)
            {
            IntegerVectorIndividual i = (IntegerVectorIndividual)inds[q];
            for(int x=0;x<i.genome.length;x++)
                if (state.random[thread].nextBoolean(species.mutationProbability(x)))
                    i.genome[x] = -i.genome[x];
            // it's a "new" individual, so it's no longer been evaluated
            i.evaluated=false;
            }
        return n;
        }
     }

</tt>

Define the Problem

For our problem, we'll define a problem which alternately adds and subtracts genes, then takes the absolute value of the result as the fitness.  Create a file called "AddSubtract.java".  In this file, add (similar to Tutorial 1):

<tt>

package ec.app.tutorial2;
import ec.*;
import ec.simple.*;
import ec.util.*;
import ec.vector.*;

public class AddSubtract extends Problem implements SimpleProblemForm
    {
    public void evaluate(final EvolutionState state,
                         final Individual ind,
                         final int subpopulation,
                         final int threadnum)
        {
        if (ind.evaluated) return;

        if (!(ind instanceof IntegerVectorIndividual))
            state.output.fatal("Whoa!  It's not a IntegerVectorIndividual!!!",null);

        IntegerVectorIndividual ind2 = (IntegerVectorIndividual)ind;

</tt>

Now we add/subtract genes to get our fitness:

<tt>

        int rawfitness = 0;
        for(int x=0; x<ind2.genome.length; x++)
            if (x % 2 == 0) rawfitness += ind2.genome[x];
                else rawfitness -= ind2.genome[x];

</tt>

I have no idea what the ideal fitness here is.  Plus with our odd mutation operator, it's unlikely we'll get it.  So let's bypass the issue and just state that individuals are NEVER ideal -- even if they are.
	We finish out with:

<tt>

        // We finish by taking the ABS of rawfitness as mentioned.  By the way,
        // in SimpleFitness, fitness values must be set up so that 0 is <= the worst
        // fitness and +infinity is >= the ideal possible fitness.  Our raw fitness
        // value here satisfies this.
        if (rawfitness < 0) rawfitness = -rawfitness;
        if (!(ind2.fitness instanceof SimpleFitness))
            state.output.fatal("Whoa!  It's not a SimpleFitness!!!",null);
        ((SimpleFitness)ind2.fitness).setFitness(state,
                // what the heck, lets normalize the fitness for genome length
                // so it's within float range
                (float)(((double)rawfitness)/ind2.genome.length),
                //... is the individual ideal?  Indicate here...
                false);
        ind2.evaluated = true;
        }
    }

</tt>

Save the file, and compile both Java files in the <tt>tutorial2</tt> directory.  Add the following parameters to the <tt>tutorial2.params</tt> file to specify that we're using AddSubtract as our Problem:

<tt>

eval.problem            = ec.app.tutorial2.AddSubtract

</tt>

Run the Experiment

Run the problem by going into the <tt>tutorial2</tt> directly and typing the command (at least on a UNIX box):

<tt>

java ec.Evolve -file tutorial2.params

</tt>

Because Java no longer guarantees exact floating point results, the final result may vary from platform to platform, but as far as I am aware, the only JVM which gives different results from the others is Microsoft's JVM.  On a non-Microsoft JVM the last few lines of the out.stat file says

<tt>

Best Individual of Run:
Evaluated: true
Fitness: 1430113.9
 1777241 -955954 760157 -1180365 2011420 -2018763 1458181 491644 521531 -1835900
 819498 -2134796 1707889 -1326509 2324432 -1148173 1809439 -2129740 2031426 -1142507

</tt>

Now, let's run this with two simulataneous threads.  This would be useful in particular if you have a multiprocessor computer. You can multithread the evaluation process, the breeding process, or both.  Let's do both.  When you have more than one thread, you need to have more than one seed.  We have only specified one seed (seed.0=4357).  So we'll need to specify a second one.  We'll add the parameters on the command line, though of course you could add them to your parameter file:

<tt>

java ec.Evolve -file tutorial2.params -p breedthreads=2 -p evalthreads=2 -p seed.1=1234

</tt>

With two threads, the second one starting with seed 1234, we now get the following best individual:

<tt>

Best Individual of Run:
Evaluated: true
Fitness: 1134800.9
 -2144673 -1202304 -529156 1934348 -2266614 1518874 -523776 1940636 -1432431 -537864
 -982131 195106 -2023895 1775415 -198611 1216088 -2125361 1065844 -1420719 1142507

</tt>

Even though the process is multithreaded, it's been arranged so that the results will be the same across runs with the same initial seeds.  Try running it again and see for yourself.

ECJ, under most conditions, is guaranteed deterministic.  That means that every time ECJ is run, you'll get the same results for the same parameter settings and seeds.  Perhaps you'd like ECJ to differ each time you run it.  The good way to do this is to set an explicit new seed each run.  But you can also just tell ECJ to base the seeds on the current timer.  For example, we could set both seeds to timer values and run multithreaded like this:

<tt>

java ec.Evolve -file tutorial2.params -p breedthreads=2 -p evalthreads=2 -p seed.1=time -p seed.0=time

</tt>

Notice that the seeds wind up being different from each other, even though both are based on the current number of milliseconds.  One last thing.  If you add the parameter <tt>print-params=true</tt>, as ECJ requests parameters from the database, the database will print out the parameters and their values.  This helps you see what parameters are actually being used  For example, if you issue the following:

<tt>

java ec.Evolve -file tutorial2.params -p print-params=true

</tt>

You are likely to get the following back:

<tt>

        P: store = true
        P: flush = true
        P: breedthreads = 1
        P: evalthreads = 1
        P: seed.0 = 4357
        P: seed.0 = 4357
        P: state = ec.simple.SimpleEvolutionState

| ECJ
| An evolutionary computation system (version 8)
| Copyright 2001 by Sean Luke
| URL: http://www.cs.umd.edu/projects/plus/ec/ecj/
| Mail: sean@cs.gmu.edu
| Date: June 20, 2001
| Current Java: 1.3.1 / Java HotSpot(TM) Client VM-1.3.1
| Suggested Java: 1.2.2
| Minimum Java: 1.1

Threads:  breed/1 eval/1
Seed: 4357
Setting up
        P: checkpoint = false
        P: checkpoint-prefix = ec
        P: checkpoint-modulo = 1
        P: gc-modulo = 1
        P: generations = 200
        P: gc = false
        P: aggressive = true
        P: quit-on-run-complete = true
        P: init = ec.simple.SimpleInitializer
        P: finish = ec.simple.SimpleFinisher
        P: breed = ec.simple.SimpleBreeder
        P: pop.subpops = 1
        P: eval = ec.simple.SimpleEvaluator
        P: eval.problem = ec.app.tutorial2.AddSubtract
        P: stat = ec.simple.SimpleStatistics
        P: stat.file = $out.stat
        P: exch = ec.simple.SimpleExchanger
Initializing Generation 0
        P: pop = ec.Population
        P: pop.subpops = 1
        P: pop.subpop.0 = ec.Subpopulation
        P: pop.subpop.0.species = ec.vector.IntegerVectorSpecies
        P: pop.subpop.0.species.genome-size = 20
        P: pop.subpop.0.species.mutation-prob = 0.05
        P: pop.subpop.0.species.crossover-type = two
        P: pop.subpop.0.species.pipe = ec.app.tutorial2.OurMutatorPipeline
        P: pop.subpop.0.species.pipe.source.0 = ec.vector.breed.VectorCrossoverPipeline
        P: pop.subpop.0.species.pipe.source.0 = ec.vector.breed.VectorCrossoverPipeline
        P: pop.subpop.0.species.pipe.source.0.source.0 = ec.select.FitProportionateSelection
        P: pop.subpop.0.species.pipe.source.0.source.0 = ec.select.FitProportionateSelection
        P: pop.subpop.0.species.pipe.source.0.source.1 = ec.select.TournamentSelection
        P: pop.subpop.0.species.pipe.source.0.source.1 = ec.select.TournamentSelection
        P: pop.subpop.0.species.pipe.source.0.source.1.size = 5
        P: pop.subpop.0.species.pipe.source.0.source.1.pick-worst = true
        P: pop.subpop.0.species.pipe.source.0.toss = true
        P: pop.subpop.0.species.ind = ec.vector.IntegerVectorIndividual
        P: pop.subpop.0.species.min-gene = -12312
        P: pop.subpop.0.species.max-gene = 2341212
        P: pop.subpop.0.species.fitness = ec.simple.SimpleFitness
        P: pop.subpop.0.size = 100
        P: pop.subpop.0.duplicate-retries = 0
Generation 1
Generation 2
Generation 3
Generation 4
Generation 5
...

</tt>

Notice that some parameters are requested more than once.  There are other ways of printing out parameters as well -- see the ec.Evolve parameter listings for more ways to do this.


text:
package grantAccessToUser

import (
	"github.com/AitorGuerrero/UserGo/user"
	"github.com/AitorGuerrero/UserGo/user/manager"
)

type Command struct {
	UserSource user.Source
	ManagerSource manager.Source
}

type Request struct {
	ManagerId string
	UserId string
	Namespace string
}

func (c Command) Execute(r Request) (err error) {
	var mi, ui user.Id
	mi = user.ParseId(r.ManagerId);
	ui = user.ParseId(r.UserId);
	m, err := c.ManagerSource.Get(mi)
	if _, ok := err.(manager.NotExistsError); ok {
		return ManagerDoesNotExist{err, req.ManagerId}
	}
	u, err := c.UserSource.Get(ui)
	if _, ok := err.(user.NotExistentUser); ok {
		return UserDoesNotExist{err, string(ui)}
	}
	err = m.GrantAccessToUser(u, user.Namespace(r.Namespace))
	if _, ok := err.(manager.DoesNotOwnTheUser); ok {
		return ManagerDoesNotOwnTheUser{err, req.UserId, req.ManagerId}
	}
	if _, ok := err.(manager.ManagerDoesNotOwnTheNamespace); ok {
		return ManagerDoesNotOwnTheNamespace{err, req.ManagerId, req.Namespace}
	}

	return
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <name>React Sample</name>
  <groupId>com.mrfeelings</groupId>
  <artifactId>react-sample</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>

  <dependencies>

    <dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>javax.ws.rs-api</artifactId>
      <version>2.0</version>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet</artifactId>
      <version>2.14</version>
    </dependency>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20140107</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>reactSample</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
module.exports = {
  name: '',
  rootDir: __dirname + '/..',
  scriptPreprocessor: "<rootDir>/node_modules/babel-jest",
  unmockedModulePathPatterns: [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ],
  testPathIgnorePatterns: [
    "node_modules"
  ],
  testPathDirs: [
    "<rootDir>/__tests__/"
  ],
  testFileExtensions: ['js']
}


text:
A number spinner based on knockout, Support keyboard operations and continuous changing.

## Usage

~~~ spinner

~~~

## Who helps

* **Sarath** ([@sarathsaleem](https://github.com/sarathsaleem))
* **Roland Liwag** ([@rolandliwag](https://github.com/rolandliwag))


text:
chorus.pages.PublishedWorkletShowPage = chorus.pages.Base.extend({
    setup: function(workletId) {
        this.subscribePageEvent("worklet:run", this.runEventHandler);
        this.subscribePageEvent("menu:worklet", this.menuEventHandler);

        this.worklet = new chorus.models.PublishedWorklet({ id:workletId });
        this.worklet.fetch();
        this.handleFetchErrorsFor(this.worklet);

        this.pollForRunStatus = _.bind(function() {
            this.worklet.fetch({
                success: _.bind(function(model) {
                    if(!model.get('running')) {
                        chorus.PageEvents.trigger("worklet:run", "runStopped");
                    }
                }, this)
            });
        }, this);

        this.onceLoaded(this.worklet, this.buildPage);
    },

    menuEventHandler: function(menu_item) {
        if (menu_item === 'close') {
            this.closePage();
        }
    },

    closePage: function() {
        chorus.router.navigate('#/touchpoints');
    },

    runEventHandler: function(event) {
        if (event === 'runStarted') {
            if (_.isUndefined(this.pollerID)) {
                this._last_hist_len = this.history.length;
                this.sidebar.runEventHandler('runStarted');
                this.pollerID = setInterval(this.pollForRunStatus, 1000);
            }
        }
        else if (event === 'runStopped') {
            // We want to continue polling until we have a history; running stop and history are asynchronously updated.
            // Unless we "clicked stop"; in which case we don't expect an update in the history.
            this.history.fetchAll({ wait: true });
            if (this.clickedStop !== true && this._last_hist_len === this.history.length) {
                return;
            }

            if (this.clickedStop !== true) {
                this.mainContent.content.workletHistory._showLatestEntry = true;
            }
            this.clickedStop = false;

            clearInterval(this.pollerID);
            this.pollerID = void 0;
        }
        else if (event === 'clickedStop') {
            this.clickedStop = true;
        }
    },

    buildPage: function() {
        this.history = this.worklet.activities({
            resultsOnly: true,
            currentUserOnly: true
        });
        this.history.fetchAll();

        this.headerView = new chorus.views.WorkletHeader({
            worklet: this.worklet,
            menuOptions: [],
            state: 'publishedRun'
        });

        this.subNav = this.headerView;
        this.sidebar = new chorus.views.WorkletParameterSidebar({
            worklet: this.worklet,
            state: 'running'
        });

        this.contentView = new chorus.views.PublishedWorkletContent({
            worklet: this.worklet,
            history: this.history,
            mainPage: this
        });

        this.mainContent = new chorus.views.MainContentView({
            worklet: this.worklet,
            content: this.contentView
        });

        this.render();

        if(this.worklet.get('running')) {
            chorus.PageEvents.trigger("worklet:run", "runStarted");
        }

    }
});


text:
<instrumentlibrary>
	<instruments>
		<!-- paths are always relative to the location of the loader component -->
		<!-- only one of each type of instruments can be loaded at one time (for now at least)-->
		<instrument	id="Breadboard.OpenLabs"
			displayname="breadboard"
			type="breadboard"
			image="images/breadboard300.jpg"
			path="breadboard/breadboard.swf"
			jsclass="Breadboard" />

		<instrument id="Multimeter.Fluke23"
			displayname="multimeter"
			buttontext="Multimeter"
			type="multimeter"
			image="images/multimeter300.jpg"
			path="multimeter/multimeter.swf"
			jsclass="FlukeMultimeter" />

		<instrument id="Fgen.HP33120A"
			displayname="func_gen"
			type="functiongenerator"
			image="images/functiongenerator300.jpg"
			path="functiongenerator/functiongenerator.swf"
			jsclass="HPFunctionGenerator" />

		<instrument id="Osc.Agilent54622A"
			displayname="oscilloscope"
			type="oscilloscope"
			image="images/oscilloscope300.jpg"
			path="oscilloscope/oscilloscope.swf"
			jsclass="AgilentOscilloscope" />

		<instrument id="DCPower.AgilentE3631A"
			displayname="dc_power"
			buttontext="DC Power"
			type="dcpower"
			image="images/tripledc300.jpg"
			path="tripledc/tripledc.swf"
			jsclass="TripleDC" />

		<!-- National instruments -->
		<!--
		<instrument id="Multimeter.NIDMM"
			displayname="Multimeter - National Instruments"
			type="multimeter"
			image="images/nidmm.jpg"
			path="nidmm/NI_DMM.swf" />

		<instrument id="Fgen.NIFGen"
			displayname="Function Generator - National Instruments"
			type="functiongenerator"
			image="images/nifgen.jpg"
			path="nifgen/NI_FGEN.swf" />

		<instrument id="Osc.NIOsc"
			displayname="Oscilloscope -  National Instruments"
			type="oscilloscope"
			image="images/niosc.jpg"
			path="niosc/NI_OSC.swf" />

		<instrument id="DCPower.NIDCPower"
			displayname="DC Power - National Instruments"
			type="dcpower"
			image="images/nidcpower.jpg"
			path="nidcpower/NI_DCPower.swf" />
			-->
	</instruments>

	<setups>
		<setup name="BTH"><!-- the first is the default setup -->
			<setup_instrument id="Breadboard.OpenLabs" />
			<setup_instrument id="Multimeter.Fluke23" />
			<setup_instrument id="Fgen.HP33120A" />
			<setup_instrument id="Osc.Agilent54622A" />
			<setup_instrument id="DCPower.AgilentE3631A" />
		</setup>
	</setups>

</instrumentlibrary>


text:
module Y2016.M12.D06.Solution where

import Control.Arrow ((&&&))

-- below imports available from 1HaskellADay git repository

import Data.Monetary.BitCoin

import Y2016.M12.D01.Solution
import Y2016.M12.D05.Solution

{--
Yesterday we looked at the SMA/Simple Moving Average as a trend-indicator, and
we saw that it is a more responsive indicator than using simply the mean gain

... a much more responsive indicator.

In theory, and in practice, the more responsive an indicator is the faster
one can react to 'where the data are going.' The more able you are to react,
the better your decisions are ... in theory. And, it turns out, in practice,
too... that is: based on your decision-making, bad decisions usually lead to
bad results. YMMV.

So, SMA has good responsiveness. Good enough?

Hm.

The more responsive you can be, the (even more) responsive you find you need
to be. So, is there a more-responsive technical indicator

1. Why, yes, and
2. there are several (and more than several) indicators other than SMA that
may be more apt for decision-making on your data sets.

Today, let's look at one of them: the EMA, or Exponential Moving Average.

The SMA/Simple Moving Average is 'responsive' over the last n data points, but
evenly so. What if timely is more important, so the most recent data point is
the most relevant. The EMA/Exponential Moving Average, also called the Weighted
Moving Average, addresses this: it gives the most weight to the most recent
data point, the second-most weight to the previous data point, on, as you can
presume, in an exponentially-diminished set of weights.

Now, I can write all about the EMA, but there's a lovely site that does this
already. I'll let you read that, and we'll write the code, in Haskell, here.

http://www.investopedia.com/articles/trading/10/simple-exponential-moving-averages-compare.asp?ad=dirN&qo=investopediaSiteSearch&qsrc=0&o=40186

Okay, so let's distill the article.

The EMA is computed thus:

EMA = (P * α) + (Previous EMA * (1 - α))

    where P = current data-point
          α = smoothing factor = 2 / ( 1 + n)
          n = number of data points in a period

So, in Haskell, you define:
--}

ema :: Fractional a => Int -> a -> [a] -> a
ema n prevEMA = (prevEMA * (1 - α) +) . (α *) . head -- given the list never ends
   where α = 2.0 / (1.0 + fromIntegral n)

-- define ema

-- question: is this the best approach, type-wise? As EMA is defined recursively
-- should ema's declaration be Int -> [a] -> [a]? Or should the previous EMA
-- be stored in, e.g. the State-monad? What is a good number for the first
-- previous EMA? How do we handle that first case in the function definition?

-- Thoughts on this from type-theorists?

-- Now for the BitCoin Price history, chart the historical prices against
-- EMA 12 and EMA 26, as you did yesterday for SMA

btcEMA12and26 :: FilePath -> BitCoinPrices -> IO ()
btcEMA12and26 = btcAnalyses "EMA 12,EMA 26" computeEMAs

-- starter-function kicks off the computation with the first value as seed

computeEMAs :: Fractional a => [a] -> [Indicators a]
computeEMAs = uncurry computeEMAs' . ((head &&& head) &&& id)

-- the worker-function inlines EMA computations into the time-series

computeEMAs' :: Fractional a => (a, a) -> [a] -> [Indicators a]
computeEMAs' _ [] = []
computeEMAs' (p12, p26) list@(h:t) =
   let nuance = (ema 12 p12 &&& ema 26 p26) list in
   (h, nuance):computeEMAs' nuance t

{--
The computeEMAs' function is a stateful mapping over the price-history.

Reminder: The historical BitCoin prices are available from the URL:

http://www.investopedia.com/articles/trading/10/simple-exponential-moving-averages-compare.asp?ad=dirN&qo=investopediaSiteSearch&qsrc=0&o=40186

or I've taken a snapshot at:

https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M12/D01/market-price-btc.csv

You can get the BitCoinPrices value by using Y2016.M12.D01.Exercise.btcPriceHistoryFromURL

so:

*Y2016.M12.D06.Solution>
   btcPriceHistoryFromURL "Y2016/M12/D01/market-price-btc.csv" >>=
   btcEMA12and26 "Y2016/M12/D06/btcEMA12and26.csv"

Shows the EMA 12 and EMA 26 indicators in action. Rather boring-looking. The
interesting bits come to play in the interplay of the indicators, themselves.

But that is for another day.
--}


text:
<?php
/*
Template Name: Origins Timeline
*/
/**
 * The template for displaying the origins timeline in chronlogical order.
 *
 */

$templates = array( 'page-origins.twig', 'archive.twig' );

global $paged;
if (!isset($paged) || !$paged){
    $paged = 1;
}

$context = Timber::get_context();
$post = new TimberPost();

$context['post'] = $post;
$feed_category = get_field_objects($data["post"]->ID)['feed_category']['value'];

$args = array(
  'cat' => $feed_category,
  'posts_per_page' => 1000,
  'paged' => false,
  'orderby' => "date",
  'order' => 'ASC'
);

query_posts($args);

$posts = Timber::get_posts();

$posts_by_year = array();

foreach ($posts as $post) {
  $post_date = strtotime($post->post_date);
  $post_year = date('Y', $post_date);

  if (array_key_exists($post_year, $posts_by_year)) {
    array_push($posts_by_year[$post_year], $post);
  } else {
    $posts_by_year[$post_year] = array();
  }
}

$context['posts'] = $posts;
$context['posts_by_year'] = $posts_by_year;
$context['pagination'] = Timber::get_pagination();
$context['current_page'] = $paged;
Timber::render( $templates, $context );


text:
import { by, device, element, expect as detoxExpect, waitFor } from 'detox';

import { sleepAsync } from './Utils';
import { expectResults } from './utils/report';

let TESTS = [
  'Basic',
  // 'Asset',
  // 'FileSystem',
  // 'Font',
  'Permissions',
  // 'Blur',
  'LinearGradient',
  'Constants',
  // 'Contacts',
  'Crypto',
  // 'GLView',
  'Haptics',
  'Localization',
  // 'SecureStore',
  // 'Segment',
  // 'SQLite',
  'Random',
  'Permissions',
  'KeepAwake',
  'FirebaseCore',
  'FirebaseAnalytics',
  // 'Audio',
  'HTML',
];

const MIN_TIME = 50000;

describe('test-suite', () => {
  TESTS.map(testName => {
    it(
      `passes ${testName}`,
      async () => {
        const platform = device.getPlatform();
        await device.launchApp({
          newInstance: true,
          url: `bareexpo://test-suite/run?tests=${testName}`,
        });

        const launchWaitingTime = platform === 'ios' ? 100 : 3000;
        await sleepAsync(launchWaitingTime);

        await detoxExpect(element(by.id('test_suite_container'))).toExist();
        try {
          await waitFor(element(by.id('test_suite_text_results')))
            .toExist()
            .withTimeout(MIN_TIME);
        } catch (err) {
          // test hasn't completed within the timeout
          // continue and log the intermediate results
        }

        if (platform === 'ios') {
          const attributes = await element(by.id('test_suite_final_results')).getAttributes();
          const input = attributes.text;
          expectResults({
            testName,
            input,
          });
        } else {
          // Platforms do no support `getAttributes()`, using text matching instead
          await detoxExpect(element(by.id('test_suite_text_results'))).toHaveText('Complete: 0 tests failed.');
        }
      },
      MIN_TIME * 1.5
    );
  });
});


text:
<?php
require_once 'src/commonfunctions.php';
class commonfuncTest extends PHPUnit_Framework_TestCase {
	public function testGameTitle() {
		$this->assertEquals('Game', gametitle(array('Title' => 'Game')));
		$this->assertEquals('Game (USA)', gametitle(array('Title' => 'Game', 'Country' => 'USA')));
		$this->assertEquals('Game (v1.0)', gametitle(array('Title' => 'Game', 'Version' => '1.0')));
		$this->assertEquals('Game (USA v1.0)', gametitle(array('Title' => 'Game', 'Version' => '1.0', 'Country' => 'USA')));
		try {
			gametitle(null);
			gametitle(array('Country' => 'USA'));
			$this->fail('Exception not thrown');
		} catch (InvalidArgumentException $e) {
		} catch (Exception $e) {
			$this->fail('Inappropriate exception thrown');
		}
	}
	public function testMemoryData() {
		$vals = array(1,0,2,1,0);
		$memfilter = new memoryData();
		$memfilter->setData($vals);
		$this->assertEquals(1, $memfilter->getByte());
		$this->assertEquals(0, $memfilter->getByte());
		$memfilter->seekTo(0);
		$this->assertEquals(1, $memfilter->getByte());
		$memfilter->seekTo(0);
		$this->assertEquals(1, $memfilter->getShort());
		$memfilter->seekTo(0);
		$this->assertEquals(16908289, $memfilter->getLong());
		$this->assertEquals(4, $memfilter->currentOffset());
		$memfilter->seekTo(0);
		$this->assertEquals(1, $memfilter->getVar(2));
	}
}
?>


text:
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for
   details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */

#include "lwt_config.h"

#if !defined(LWT_ON_WINDOWS)

#include <caml/alloc.h>
#include <caml/bigarray.h>
#include <caml/mlvalues.h>
#include <caml/unixsupport.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "unix_recv_send_utils.h"

value lwt_unix_bytes_send(value fd, value buf, value ofs, value len,
                          value flags)
{
    int ret;
    ret =
        send(Int_val(fd), (char *)Caml_ba_array_val(buf)->data + Long_val(ofs),
             Long_val(len), caml_convert_flag_list(flags, msg_flag_table));
    if (ret == -1) uerror("send", Nothing);
    return Val_int(ret);
}
#endif


text:
using System;
using System.Runtime.Serialization;

namespace Rhino.Licensing
{
    ///<summary>
    /// Thrown when license is found but is past it's expiration date
    ///</summary>
    public class LicenseExpiredException : RhinoLicensingException
    {
        /// <summary>
        /// Creates a new instance of <seealso cref="RhinoLicensingException"/>.
        /// </summary>
        public LicenseExpiredException()
        {
        }

        /// <summary>
        /// Creates a new instance of <seealso cref="RhinoLicensingException"/>.
        /// </summary>
        /// <param name="message">error message</param>
        public LicenseExpiredException(string message) : base(message)
        {
        }

        /// <summary>
        /// Creates a new instance of <seealso cref="RhinoLicensingException"/>.
        /// </summary>
        /// <param name="message">error message</param>
        /// <param name="inner">inner exception</param>
        public LicenseExpiredException(string message, Exception inner) : base(message, inner)
        {
        }

        /// <summary>
        /// Creates a new instance of <seealso cref="RhinoLicensingException"/>.
        /// </summary>
        /// <param name="info">serialization information</param>
        /// <param name="context">streaming context</param>
        public LicenseExpiredException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text: This is Daisy's blog


text:
LuaSocket 2.0.2 license
Copyright � 2004-2007 Diego Nehab

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
]]--
--[[
	Changes made by LuCI project:
		* Renamed to luci.ltn12 to avoid collisions with luasocket
		* Added inline documentation
]]--
-----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id$
-----------------------------------------------------------------------------

-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G

--- Diego Nehab's LTN12 - Filters, sources, sinks and pumps.
-- See http://lua-users.org/wiki/FiltersSourcesAndSinks for design concepts
module("luci.ltn12")

filter = {}
source = {}
sink = {}
pump = {}

-- 2048 seems to be better in windows...
BLOCKSIZE = 2048
_VERSION = "LTN12 1.0.1"

-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------

--- LTN12 Filter constructors
-- @class module
-- @name luci.ltn12.filter

--- Return a high level filter that cycles a low-level filter
-- by passing it each chunk and updating a context between calls.
-- @param low   Low-level filter
-- @param ctx   Context
-- @param extra Extra argument passed to the low-level filter
-- @return LTN12 filter
function filter.cycle(low, ctx, extra)
    base.assert(low)
    return function(chunk)
        local ret
        ret, ctx = low(ctx, chunk, extra)
        return ret
    end
end

--- Chain a bunch of filters together.
-- (thanks to Wim Couwenberg)
-- @param ... filters to be chained
-- @return LTN12 filter
function filter.chain(...)
    local n = table.getn(arg)
    local top, index = 1, 1
    local retry = ""
    return function(chunk)
        retry = chunk and retry
        while true do
            if index == top then
                chunk = arg[index](chunk)
                if chunk == "" or top == n then return chunk
                elseif chunk then index = index + 1
                else
                    top = top+1
                    index = top
                end
            else
                chunk = arg[index](chunk or "")
                if chunk == "" then
                    index = index - 1
                    chunk = retry
                elseif chunk then
                    if index == n then return chunk
                    else index = index + 1 end
                else base.error("filter returned inappropriate nil") end
            end
        end
    end
end

-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------

--- LTN12 Source constructors
-- @class module
-- @name luci.ltn12.source

-- create an empty source
local function empty()
    return nil
end

--- Create an empty source.
-- @return LTN12 source
function source.empty()
    return empty
end

--- Return a source that just outputs an error.
-- @param err Error object
-- @return LTN12 source
function source.error(err)
    return function()
        return nil, err
    end
end

--- Create a file source.
-- @param handle File handle ready for reading
-- @param io_err IO error object
-- @return LTN12 source
function source.file(handle, io_err)
    if handle then
        return function()
            local chunk = handle:read(BLOCKSIZE)
            if not chunk then handle:close() end
            return chunk
        end
    else return source.error(io_err or "unable to open file") end
end

--- Turn a fancy source into a simple source.
-- @param src fancy source
-- @return LTN12 source
function source.simplify(src)
    base.assert(src)
    return function()
        local chunk, err_or_new = src()
        src = err_or_new or src
        if not chunk then return nil, err_or_new
        else return chunk end
    end
end

--- Create a string source.
-- @param s Data
-- @return LTN12 source
function source.string(s)
    if s then
        local i = 1
        return function()
            local chunk = string.sub(s, i, i+BLOCKSIZE-1)
            i = i + BLOCKSIZE
            if chunk ~= "" then return chunk
            else return nil end
        end
    else return source.empty() end
end

--- Creates rewindable source.
-- @param src LTN12 source to be made rewindable
-- @return LTN12 source
function source.rewind(src)
    base.assert(src)
    local t = {}
    return function(chunk)
        if not chunk then
            chunk = table.remove(t)
            if not chunk then return src()
            else return chunk end
        else
            t[#t+1] = chunk
        end
    end
end

--- Chain a source and a filter together.
-- @param src LTN12 source
-- @param f LTN12 filter
-- @return LTN12 source
function source.chain(src, f)
    base.assert(src and f)
    local last_in, last_out = "", ""
    local state = "feeding"
    local err
    return function()
        if not last_out then
            base.error('source is empty!', 2)
        end
        while true do
            if state == "feeding" then
                last_in, err = src()
                if err then return nil, err end
                last_out = f(last_in)
                if not last_out then
                    if last_in then
                        base.error('filter returned inappropriate nil')
                    else
                        return nil
                    end
                elseif last_out ~= "" then
                    state = "eating"
                    if last_in then last_in = "" end
                    return last_out
                end
            else
                last_out = f(last_in)
                if last_out == "" then
                    if last_in == "" then
                        state = "feeding"
                    else
                        base.error('filter returned ""')
                    end
                elseif not last_out then
                    if last_in then
                        base.error('filter returned inappropriate nil')
                    else
                        return nil
                    end
                else
                    return last_out
                end
            end
        end
    end
end

--- Create a source that produces contents of several sources.
-- Sources will be used one after the other, as if they were concatenated
-- (thanks to Wim Couwenberg)
-- @param ... LTN12 sources
-- @return LTN12 source
function source.cat(...)
    local src = table.remove(arg, 1)
    return function()
        while src do
            local chunk, err = src()
            if chunk then return chunk end
            if err then return nil, err end
            src = table.remove(arg, 1)
        end
    end
end

-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------

--- LTN12 sink constructors
-- @class module
-- @name luci.ltn12.sink

--- Create a sink that stores into a table.
-- @param t output table to store into
-- @return LTN12 sink
function sink.table(t)
    t = t or {}
    local f = function(chunk, err)
        if chunk then t[#t+1] = chunk end
        return 1
    end
    return f, t
end

--- Turn a fancy sink into a simple sink.
-- @param snk fancy sink
-- @return LTN12 sink
function sink.simplify(snk)
    base.assert(snk)
    return function(chunk, err)
        local ret, err_or_new = snk(chunk, err)
        if not ret then return nil, err_or_new end
        snk = err_or_new or snk
        return 1
    end
end

--- Create a file sink.
-- @param handle file handle to write to
-- @param io_err IO error
-- @return LTN12 sink
function sink.file(handle, io_err)
    if handle then
        return function(chunk, err)
            if not chunk then
                handle:close()
                return 1
            else return handle:write(chunk) end
        end
    else return sink.error(io_err or "unable to open file") end
end

-- creates a sink that discards data
local function null()
    return 1
end

--- Create a sink that discards data.
-- @return LTN12 sink
function sink.null()
    return null
end

--- Create a sink that just returns an error.
-- @param err Error object
-- @return LTN12 sink
function sink.error(err)
    return function()
        return nil, err
    end
end

--- Chain a sink with a filter.
-- @param f LTN12 filter
-- @param snk LTN12 sink
-- @return LTN12 sink
function sink.chain(f, snk)
    base.assert(f and snk)
    return function(chunk, err)
        if chunk ~= "" then
            local filtered = f(chunk)
            local done = chunk and ""
            while true do
                local ret, snkerr = snk(filtered, err)
                if not ret then return nil, snkerr end
                if filtered == done then return 1 end
                filtered = f(done)
            end
        else return 1 end
    end
end

-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------

--- LTN12 pump functions
-- @class module
-- @name luci.ltn12.pump

--- Pump one chunk from the source to the sink.
-- @param src LTN12 source
-- @param snk LTN12 sink
-- @return Chunk of data or nil if an error occured
-- @return Error object
function pump.step(src, snk)
    local chunk, src_err = src()
    local ret, snk_err = snk(chunk, src_err)
    if chunk and ret then return 1
    else return nil, src_err or snk_err end
end

--- Pump all data from a source to a sink, using a step function.
-- @param src LTN12 source
-- @param snk LTN12 sink
-- @param step step function (optional)
-- @return 1 if the operation succeeded otherwise nil
-- @return Error object
function pump.all(src, snk, step)
    base.assert(src and snk)
    step = step or pump.step
    while true do
        local ret, err = step(src, snk)
        if not ret then
            if err then return nil, err
            else return 1 end
        end
    end
end


text:
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class maracaDeviceInterface : deviceInterface {
  maracaSignalGenerator signal;
  maracaUI _maracaUI;
  omniJack jackOut;
  double _sampleDuration;

  [DllImport("SoundStageNative")]
  public static extern void MaracaProcessAudioBuffer(float[] buffer, float[] controlBuffer, int length, int channels, ref double _phase, double _sampleDuration);

  public override void Awake() {
    base.Awake();
    _sampleDuration = 1.0 / AudioSettings.outputSampleRate;
    signal = GetComponent<maracaSignalGenerator>();
    _maracaUI = GetComponentInChildren<maracaUI>();
    jackOut = GetComponentInChildren<omniJack>();
  }

  void Update() {
    signal.curShake = _maracaUI.shakeVal;
  }

  void OnDestroy() {
    if (_maracaUI.transform.parent != transform) Destroy(_maracaUI.gameObject);
  }

  double _phaseB = 0;
  private void OnAudioFilterRead(float[] buffer, int channels) {
    if (jackOut.near != null || signal.curShake < .01f) return;

    double dspTime = AudioSettings.dspTime;
    float[] b = new float[buffer.Length];
    signal.processBuffer(b, dspTime, channels);

    MaracaProcessAudioBuffer(buffer, b, buffer.Length, channels, ref _phaseB, _sampleDuration);
  }

  public override InstrumentData GetData() {
    MaracaData data = new MaracaData();
    data.deviceType = menuItem.deviceType.Maracas;
    GetTransformData(data);
    data.jackOutID = jackOut.transform.GetInstanceID();
    return data;
  }

  public override void Load(InstrumentData d) {
    MaracaData data = d as MaracaData;
    base.Load(data);
    jackOut.ID = data.jackOutID;
  }
}

public class MaracaData : InstrumentData {
  public int jackOutID;
}


text:
package com.hendrix.erdos.utils;

import com.hendrix.erdos.graphs.IGraph;
import com.hendrix.erdos.types.Edge;

import java.util.HashMap;

/**
 * edges utilities
 *
 * @author Tomer Shalev
 */
@SuppressWarnings("UnusedDeclaration")
public class SEdgeUtils {

    /**
     * compute the index of a given edge in a graph. it is okay for occasional query.
     * for frequent queries use {@link #getEdgesIndices(IGraph)}
     *
     * @param edge  the edge whose index is wished to be found
     * @param graph the graph in which the edge is in
     *
     * @return the index of the edge, or -1 if none.
     */
    static public int indexOf(Edge edge, IGraph graph) {
        int index = 0;
        for (Edge e : graph.edges()) {
            if(edge.equals(e))
                return index;
            index++;
        }

        return -1;
    }

    /**
     * find the edge at a specific index. it is okay for occasional query.
     * for frequent queries use {@link #getIndicesEdges(IGraph)}
     *
     * @param index the index of the edge
     * @param graph a graph in which the edge is in
     *
     * @return the edge at the specified index/location, or {@code null} otherwise
     */
    static public Edge getEdgeAt(int index, IGraph graph) {
        int idx = 0;
        for (Edge e : graph.edges()) {
            if(idx == index)
                return e;
            idx++;
        }

        return null;
    }

    /**
     * get a complete mapping between edges and their corresponding indices in a graph
     *
     * @param graph the graph
     *
     * @return a correspondence mapping
     *
     * @see #getIndicesEdges(IGraph)
     */
    static public HashMap<Edge, Integer> getEdgesIndices(IGraph graph) {
        HashMap<Edge, Integer> map = new HashMap<>();
        int idx = 0;
        for (Edge e : graph.edges()) {
            map.put(e, idx++);
        }

        return map;
    }

    /**
     * get a complete mapping between indices and their corresponding edges in a graph
     *
     * @param graph the graph
     *
     * @return a correspondence mapping
     *
     * @see #getEdgesIndices(IGraph)
     */
    static public HashMap<Integer, Edge> getIndicesEdges(IGraph graph) {
        HashMap<Integer, Edge> map = new HashMap<>();
        int idx = 0;
        for (Edge e : graph.edges()) {
            map.put(idx++, e);
        }

        return map;
    }

}


text:
'use strict';
module.exports = function(app){
  var BaseService = app.getService('Base', true);
  var ApplicationService = BaseService.extend(function(app){
    this.app = app;
    this.serviceName = "Application";
  }).methods({
    start : function(){
      console.log('supr service:'+ this.num++);
    }
  });
  return ApplicationService;
};


text:
import {Component} from "@angular/core";
import {Restangular} from "./../../src";

import 'rxjs/Rx';
import {RequestShowService} from "../request-show-service/request-show.service";
import {BehaviorSubject} from "rxjs";

@Component({
  selector: 'request-calc',
  styleUrls: ['./request-calc/request-calc.style.css'],
  templateUrl: './request-calc/request-calc.template.html'
})
export class RequestCalcComponent {
  public allAccounts: any;
  public oneAccountsBuildings: any;
  public account: any;
  public form: any;
  public selectType: any = "one";
  public selectMethod: any = "get";

  public elementToPost: any = {};
  public SubElement:any;

  public queryArr = [];
  public headersArr = [];

  public types = ["one", "all"];
  public methods = [
    {name: "get", disabled: false}, {name: "post", disabled: false},
    {name: "put", disabled: false}, {name: "remove", disabled: false},
    {name: "head", disabled: false},{name: "trace", disabled: false},
    {name: "options", disabled: false},{name: "getList", disabled: false},
    {name: "putElement", disabled: true}];

  public request = {
    endpoint: "",
    id: "",
    headers: {},
    queryParams: {},
    subelement: ""
  };

  public requestToShow$: any;
  public responseToShow$: any = new BehaviorSubject(null);

  constructor(public restangular: Restangular, private requestShowService: RequestShowService) {
  }

  Submit(form,e) {

    if(form.invalid)return false;

    this.sendRequest(form)
  }

  private formParams(param) {
    let params = {};
    param.filter(r=>!!r.name).map(param => {
      params[param.name] = param.value;
    });
    return params;
  }

  makeRequest(form) {
    form.value.queryParams = this.formParams(this.queryArr);
    form.value.headers = this.formParams(this.headersArr);
    this.request.queryParams = form.value.queryParams;
    this.request.headers = form.value.headers;
  }

  sendRequest(form) {
    let elementToPost = {};
    this.makeRequest(form);
    if(this.selectMethod == "post") {
      elementToPost["" + this.elementToPost.name] = this.elementToPost.value;
    }
    if (this.selectType == "all") {
      if (this.selectMethod == "post") {
        this.restangular[this.selectType](form.value.endpoint)[this.selectMethod](elementToPost, form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
      else if (this.selectMethod == "get") {
        this.restangular[this.selectType](form.value.endpoint)[this.selectMethod](form.value.id, form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
      else {
        this.restangular[this.selectType](form.value.endpoint)[this.selectMethod](form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
    }
    else {
      if (this.selectMethod == "post") {
        this.restangular[this.selectType](form.value.endpoint,form.value.id)[this.selectMethod](form.value.subelement, elementToPost, form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
      else if (this.selectMethod == "getList") {
        this.restangular[this.selectType](form.value.endpoint,form.value.id)[this.selectMethod](form.value.subelement, form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
      else {
        this.restangular[this.selectType](form.value.endpoint,form.value.id)[this.selectMethod](form.value.queryParams, form.value.headers).subscribe(res => {
          this.responseToShow$.next(res);
        },this.errorShow).unsubscribe();
      }
    }
    form.reset();
  }

  errorShow(err) {
    console.log("Error from server with ErrorInterceptor",err);
  }

  addQueryParams() {
    this.queryArr.push({});
  }

  addHeaders() {
    this.headersArr.push({});
  }

  changeSelectedType(ev) {

    if (ev.target.value == "all") {
      this.methods.map(method => {
        method.name == "put" ? method.disabled = true : method.disabled = false;
        return method;
      });
    }
    else {
      this.methods.map(method => {
        method.name == "putElement" ? method.disabled = true : method.disabled = false;
        return method;
      });
    }
  }

  ngOnInit() {

    this.responseToShow$.subscribe(res => {
    });

    this.requestToShow$ = this.requestShowService.requestToShow;

    // let formData = new FormData();
    //   formData.append("name", "test");
    //
    // this.restangular.all('users')
    // .customPOST(formData, undefined, undefined, { 'Content-Type': undefined });

  }

}


text:
Game.PubSub = {

  enable: function(cfg, on) {

    var n, max;

    on.subscribe = function(event, callback) {
      this.subscribers = this.subscribers || {};
      this.subscribers[event] = this.subscribers[event] || [];
      this.subscribers[event].push(callback);
    },

    on.publish = function(event) {
      if (this.subscribers && this.subscribers[event]) {
        var subs = this.subscribers[event],
            args = [].slice.call(arguments, 1),
            n, max;
        for(n = 0, max = subs.length ; n < max ; n++)
          subs[n].apply(on, args);
      }
    }

    if (cfg) {
      for(n = 0, max = cfg.length ; n < max ; n++)
        on.subscribe(cfg[n].event, cfg[n].action);
    }

  }

}