text:
Interpreter and Compiler for the Funw@p language.
====

## Project specifications

Funw@p (read fun with AP) is a domain specific programming language designed to support general mathematical and logical operations. The language has native support for higher order functions and parallel programming.

Funw@p helps you distribute your computationally expensive or network related problems across multiple machines in a cluster. Those machines can execute their portion of the problem and then send results back to the master program.

For more information, read the file: [PA_Proj_Midterm2014-15.pdf](./PA_Proj_Midterm2014-15.pdf)

## Introduction

The software was built with the goal to simulate the behaviour of an IDE (Integrated development environment).

It is an interpreter and a compiler, written in C#, for the Funw@p language.

Thanks to the graphical interface, it is really simple to use. You need just to run it and it will appear a Windows Form.

It contains a menu containing the items:
 - File → where you can open the file of your program written in the Funw@p language.
 - Execute → you can geynerete the Abstract Syntax Tree, compile or interpret your code.
 - ? → containing a Help and About buttons.

The image below shows the Abstract Syntax Tree of the factorial program generated by the application.

If you need more information, you can read the file: [Documentation.pdf](./Documentation.pdf).

In order to understand the Funw@p language, you can read the file: [Funw@p - Grammar.pdf](./Funw@p - Grammar.pdf).

Since it can be difficult to read the grammar, in the [Examples](./Examples) directory you can find
a list of working examples that allows you to see the potential of the language.

#### Key Features:
- Simple and clear graphical interface; it is even shown a graphical representation of the Abstract Syntax Tree
- Code full of comments and supports the Sandcastle Documentation
- No dependencies to external libraries

## Example
```c#
public IDE()
{
   InitializeComponent();
   Editor.AcceptsTab = true;
   try
   {
      // Scanner phase
      scanner = new Scanner();
      scanner.Initialize("func Main(){ println(\"Hello World!\"); }");
      tokens = scanner.Tokenize();

      // Trasform the token enumerator in list and remove all the comments
      tokenlist = new List<Token>();
      foreach (var token in tokens)
         if (token.Type != TokenType.COMMENT)
            tokenlist.Add(token);

      // Parser phase
      parser = new Parser(tokenlist);

      // Create the Abstract Syntax Tree.
      System.Tuple<Token, BlockNode> pair = parser.ParseTree();
      main = pair.Item1;
      root = pair.Item2;
      nameFile = "Hello_World";
   }
   catch (System.FunwapException ex) { System.Console.Write(ex.Message); }
}
```

## Supported Types
|   Types  |       Description       |
|:--------:|:-----------------------:|
|   void   |	No type                 |
|   int    |	Type integer            |
|   bool   |	Type boolean            |
|   char   |	Type character          |
|  string  |	Type string             |
|   url    |	Type network address    |
|   fun    |	Type function           |

## Supported Operation
| Operator |       Description       |
|:--------:|:-----------------------:|
|   OR     |	Logical OR       |
|   AND    |	Logical AND    |
|   NOT    |	Logical NOT |
|    =     |	Equality       |
|    ≠     |	Inequality       |
|    >     |	Greater than    |
|    ≥     |	Greater than or equal to operator |
|    <     |	Less than       |
|    ≤     |	Less than or equal to       |
|    +     |	Addition       |
|    -     |	Subtraction    |
|    ×     |	Multiplication |
|    ÷     |	Division       |

### License
The MIT License (MIT)

Copyright (c) 2015 Federico Conte

http://opensource.org/licenses/MIT


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Options;
using Poc.AspnetCore.Api.Models;

namespace Poc.AspnetCore.Api.Repositories
{
    public class BookRepository : BaseRepository, IBookRepository
    {
        private GeneralConfiguration Configurations { get; set; }

        public BookRepository(IOptions<GeneralConfiguration> configurations)
        {
            Configurations = configurations.Value;
        }

        async Task<IEnumerable<Book>> IBookRepository.GetAll()
        {
            using (var connection = GetConnection(Configurations.ConnectionString))
            {
                var lookup = new Dictionary<int, Book>();

                //http://stackoverflow.com/a/17748734
                var sql = @"SELECT b.*, a.*
                            FROM
                                book as b,
                                author as a,
                                author_book as ab
                             where
	                            ab.book_id = b.id and
	                            ab.author_id = a.id";

                var query = await connection.QueryAsync<Book, Author, Book>(sql, (b, a) =>
                {
                    Book book;
                    if (!lookup.TryGetValue(b.Id, out book))
                    {
                        book = b;
                        lookup.Add(b.Id, b);
                    }

                    book.Authors.Add(a);
                    return book;
                });

                var queryResult = query.ToList();
                return lookup.Values;
            }
        }

        Task IBookRepository.Save(Book book)
        {
            throw new NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Introduction</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="GIO Reference Manual">
<link rel="up" href="pt01.html" title="Part I. GIO Overview">
<link rel="prev" href="pt01.html" title="Part I. GIO Overview">
<link rel="next" href="ch02.html" title="Compiling GIO applications">
<meta name="generator" content="GTK-Doc V1.14 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GIO Reference Manual

Introduction

    GIO is striving to provide a modern, easy-to-use VFS API that sits
    at the right level in the library stack. The goal is to overcome the
    shortcomings of GnomeVFS and provide an API that is so good that
    developers prefer it over raw POSIX calls. Among other things
    that means using GObject. It also means not cloning the POSIX
    API, but providing higher-level, document-centric interfaces.

    The abstract file system model of GIO consists of a number of
    interfaces and base classes for I/O and files:

<col align="left" valign="top">

GFile

reference to a file

GFileInfo

information about a file or filesystem

GFileEnumerator

list files in directories

GDrive

represents a drive

GVolume

represents a file system in an abstract way

GMount

represents a mounted file system

    Then there is a number of stream classes, similar to the input and
    output stream hierarchies that can be found in frameworks like Java:

<col align="left" valign="top">

GInputStream

read data

GOutputStream

write data

GIOStream

read and write data

GSeekable

interface optionally implemented by streams to support seeking

    There are interfaces related to applications and the types
    of files they handle:

<col align="left" valign="top">

GAppInfo

information about an installed application

GIcon

abstract type for file and application icons

    There is support for network programming, including name resolution, lowlevel socket
    APIs and highlevel client and server helper classes:

<col align="left" valign="top">

GSocket

lowlevel platform independent socket object

GResolver

asynchronous and cancellable DNS resolver

GSocketClient

high-level network client helper

GSocketService

high-level network server helper

GSocketConnection

network connection stream

    Beyond these, GIO provides facilities for file monitoring,
    asynchronous I/O and filename completion. In addition to the
    interfaces, GIO provides implementations for the local case.
    Implementations for various network file systems are provided
    by the GVFS package as loadable modules.

    Other design choices which consciously break with the GnomeVFS
    design are to move backends out-of-process, which minimizes the
    dependency bloat and makes the whole system more robust. The backends
    are not included in GIO, but in the separate GVFS package. The GVFS
    package also contains the GVFS daemon, which spawn further mount
    daemons for each individual connection.

Figure 1. GIO in the GTK+ library stack

    The GIO model of I/O is stateful: if an application establishes e.g.
    a SFTP connection to a server, it becomes available to all applications
    in the session; the user does not have to enter his password over
    and over again.

    One of the big advantages of putting the VFS in the GLib layer
    is that GTK+ can directly use it, e.g. in the filechooser.

          Generated by GTK-Doc V1.14


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//doing this to avoid path third const
$__parent_folder = rtrim(realpath(rtrim(dirname(__FILE__), "/") . '/../'), '/') . '/';

if ( ! class_exists('Addon_builder_freeform'))
{
	require_once $__parent_folder . 'addon_builder/addon_builder.php';
}

if ( ! class_exists('Freeform_base_ft'))
{
	require_once $__parent_folder . 'freeform_base_ft.php';
}

if ( ! class_exists('Freeform_cacher'))
{
	require_once $__parent_folder . 'libraries/Freeform_cacher.php';
}

unset($__parent_folder);

class Freeform_fields extends Addon_builder_freeform
{
	private $data_cache		= array();
	private $default_path	= '';

	// --------------------------------------------------------------------

	/**
	 * Constructor
	 *
	 * @access	public
	 * @return	null
	 */

	public function __construct()
	{
		parent::__construct();

		ee()->load->model('freeform_field_model');
		ee()->load->model('freeform_fieldtype_model');

		$this->default_path = $this->addon_path . 'default_fields/';
	}
	//END __construct

	// --------------------------------------------------------------------

	/**
	 * Freeform Field Instance
	 *
	 * Returns an object instance of a field with settings and passed in
	 * options applied
	 *
	 * @access	public
	 * @param 	mixed 	array of options or just a field id
	 * @return	object 	reference to the object to use
	 */

	public function & get_field_instance ($options = array())
	{
		//was just a field_id passed?
		if ( ! is_array($options) AND $this->is_positive_intlike($options))
		{
			$options = array('field_id' => $options);
		}

		$defaults = array(
			'field_id'			=> 0,
			'form_id'			=> 0,
			'entry_id'			=> 0,
			'edit'				=> FALSE,
			'extra_settings'	=> array(),
			'field_data'		=> array(),
			'use_cache'			=> TRUE
		);

		foreach ($defaults as $key => $value)
		{
			$$key = (isset($options[$key])) ? $options[$key] : $value;
		}

		$cache = new Freeform_cacher(func_get_args(), __FUNCTION__, __CLASS__);

		if ($field_id > 0 AND empty($field_data))
		{
			$field_data = $this->data->get_field_info_by_id($field_id);
		}

		if ($field_id == 0 OR $field_data == FALSE)
		{
			$false = FALSE;
			return $false;
		}

		if ( ! $use_cache OR ! $cache->is_set())
		{
			//get class instance of field
			$new_instance = $this->instantiate_fieldtype($field_data['field_type']);

			$new_instance->show_all_sites	= $this->data->show_all_sites();
			$new_instance->field_id			= $field_id;
			$new_instance->field_name		= $field_data['field_name'];
			$settings						= json_decode($field_data['settings'], TRUE);
			$new_instance->settings			= is_array($settings) ? $settings : array();

			$cache->set($new_instance);
		}

		$instance = $cache->get();

		$instance->form_id 		= $form_id;
		$instance->entry_id 	= $entry_id;
		$instance->edit 		= $edit;

		//extra settings?
		foreach ($extra_settings as $key => $value)
		{
			$instance->settings[$key] = $value;
		}

		return $instance;
	}
	//END get_field_instance

	// --------------------------------------------------------------------

	/**
	 * Freeform Fieldtype Instance
	 * this seems useless, but we need instanciate fieldtype to be _not_
	 * passed by ref, but here we are
	 *
	 * returns an object instance of of the requested fieldtype
	 * This is only a separate function so we can return by reference
	 *
	 * @access	public
	 * @param 	string  name of item to look for
	 * @return	object 	reference to the object to use
	 */

	public function & get_fieldtype_instance ($name, $use_cache = TRUE)
	{
		$cache = new Freeform_cacher(func_get_args(), __FUNCTION__, __CLASS__);

		if ($use_cache AND $cache->is_set())
		{
			$return = $cache->get();
		}
		else
		{
			$return = $cache->set($this->instantiate_fieldtype($name));
		}

		return $return;
	}
	//END get_fieldtype_instance

	// --------------------------------------------------------------------

	/**
	 * instantiate Fieldtype
	 *
	 * files a fieldtypes class and creates a new instance of it
	 *
	 * @access	public
	 * @param 	string  name of item to look for
	 * @return	object 	new instance of object
	 */

	public function instantiate_fieldtype ($name = '')
	{
		//for now, since we just support one per directory...
		$ft_lower_name	= strtolower($name);
		$ft_class_name	= ucfirst($ft_lower_name . '_freeform_ft');
		$file 			= 'freeform_ft.' . $ft_lower_name . '.php';
		$third_path 	= PATH_THIRD . $ft_lower_name . '/';
		$include_pkg	= FALSE;

		if ( ! class_exists($ft_class_name))
		{
			//is this a default?
			if ( file_exists($this->default_path . $file))
			{
				include_once $this->default_path . $file;
			}
			else if ( file_exists($third_path . $file))
			{
				include_once $third_path . $file;
				$include_pkg	= TRUE;
			}

		}

		if ( ! class_exists($ft_class_name))
		{
			//replace with text type as a fallback in case something bad
			//happened or there was a force uninstall
			return $this->instantiate_fieldtype('text');
		}

		if ( $include_pkg )
		{
			ee()->load->add_package_path($third_path);
			$this->lang_autoload($name);
		}

		return new $ft_class_name();
	}
	//END instantiante_fieldtype

	// --------------------------------------------------------------------

	/**
	 * Freeform Fieldtype Available Fieldtypes
	 *
	 * returns an array of all of the installed fieldtypes with instances
	 *
	 * @access	public
	 * @param 	boolean use cache?
	 * @return	array 	available fieldtypes, install status, and versions
	 */

	public function get_available_fieldtypes ($use_cache = TRUE)
	{
		$cache = new Freeform_cacher(func_get_args(), __FUNCTION__, __CLASS__);
		if ($use_cache AND $cache->is_set()){ return $cache->get(); }

		$installed_fieldtypes 		= ee()->freeform_fieldtype_model->installed_fieldtypes();
		$installable_fieldtypes 	= $this->get_installable_fieldtypes($installed_fieldtypes);

		//this makes sure any updates run before we try to use them
		//
		foreach ($installed_fieldtypes as $name => $version)
		{
			$installed_fieldtypes[$name] = $installable_fieldtypes[$name];
		}

		ksort($installed_fieldtypes);

		return $cache->set($installed_fieldtypes);
	}
	//get_available_fieldtypes

	// --------------------------------------------------------------------

	/**
	 * Freeform Fieldtype defaults
	 *
	 * returns all of the default fieldtypes with
	 * install status, and versions
	 *
	 * @access	public
	 * @param 	boolean use cache?
	 * @return	array 	default fieldtypes, install status, and versions
	 */

	public function get_default_fieldtypes ($use_cache = TRUE)
	{
		$cache = new Freeform_cacher(func_get_args(), __FUNCTION__, __CLASS__);
		if ($use_cache AND $cache->is_set()){ return $cache->get(); }

		ee()->load->helper('directory');

		$fieldtypes		= array();

		$installed_fieldtypes = ee()->freeform_fieldtype_model->installed_fieldtypes();

		if ($installed_fieldtypes === FALSE)
		{
			$installed_fieldtypes = array();
		}

		$pattern		= "/freeform_ft\.([a-z_\-0-9]+)\.php/is";

		// -------------------------------------
		//	default fields
		// -------------------------------------

		$default_fields = array();

		foreach($this->data->defaults['default_fields'] as $default_field)
		{
			$potential_path = $this->addon_path .
									'default_fields/freeform_ft.' .
									$default_field . '.php';

			if (file_exists($potential_path))
			{
				$default_fields[] = $potential_path;
			}
		}

		foreach ($default_fields as $file)
		{
			if ( preg_match($pattern, $file, $match))
			{
				$ft_lower_name = $match[1];
				$ft_class_name = ucfirst($ft_lower_name . '_freeform_ft');

				include_once $file;

				//if we cannot even get a class, move on
				if (class_exists($ft_class_name))
				{
					$ft_temp = new $ft_class_name;

					$installed = array_key_exists($ft_lower_name, $installed_fieldtypes);

					//version, description required, dog
					$fieldtypes[$ft_lower_name] = array(
						'name' 			=> $ft_temp->info['name'],
						'version' 		=> $ft_temp->info['version'],
						'description'	=> $ft_temp->info['description'],
						'installed' 	=> $installed,
						'default_type' 	=> TRUE,
						'class_name'	=> $ft_class_name
					);

					//mem and crap
					unset($ft_temp);
				}
			}
		}
		//END foreach ($default_fields as $file)

		ksort($fieldtypes);

		return $cache->set($fieldtypes);
	}
	//END get_default_fieldtypes

	// --------------------------------------------------------------------

	/**
	 * Freeform Fieldtype installable
	 *
	 * returns all of the installable fieldtypes with
	 * install status, and versions
	 *
	 * @access	public
	 * @param 	array  	filter array to only get what we need? (TODO)
	 * @param 	boolean use cache?
	 * @return	array 	installable fieldtypes, install status, and versions
	 */

	public function get_installable_fieldtypes ($filter = array(), $use_cache = TRUE)
	{
		$cache = new Freeform_cacher(func_get_args(), __FUNCTION__, __CLASS__);
		if ($use_cache AND $cache->is_set()){ return $cache->get(); }

		ee()->load->helper('directory');

		$fieldtypes 			= $this->get_default_fieldtypes();

		ksort($fieldtypes);

		return $cache->set($fieldtypes);
	}
	//END get_installable_fieldtypes

	// --------------------------------------------------------------------

	/**
	 * Atempts to load a lang file for a directory but only if the file exists
	 *
	 * @access  public
	 * @param  	string $name name of package to attempt to auto load for
	 * @return 	void
	 */

	public function lang_autoload ($name = '', $alternate_file_name = '')
	{
		// -------------------------------------
		//	pre-flight checks
		// -------------------------------------

		$name 					= trim(strtolower($name));

		if ($name == '')
		{
			return;
		}

		$alternate_file_name 	= trim(strtolower($alternate_file_name));
		$loaded 				= in_array($name, ee()->lang->is_loaded);

		if ($loaded AND
			($alternate_file_name == '' OR
			 $name == $alternate_file_name OR
			 in_array($alternate_file_name, ee()->lang->is_loaded)))
		{
			return;
		}

		//check for lang or alternate lang

		$deft_lang 	= ( ! ee()->config->item('language')) ?
						'english' :
						ee()->config->item('language');

		$pkg_path		= PATH_THIRD . strtolower($name) . '/';
		$lang_dir 	 	= $pkg_path . 'language/' . $deft_lang . '/';

		if (is_dir($lang_dir))
		{
			//load standard lang file
			if ( ! $loaded AND
				(file_exists($lang_dir . $name . '_lang.php') OR
				file_exists($lang_dir . 'lang.' . $name . '.php')))
			{
				ee()->lang->loadfile($name);
			}

			//this allows for extra lang files per addon
			if ($alternate_file_name AND $name !== $alternate_file_name)
			{
				if (file_exists($lang_dir . $alternate_file_name . '_lang.php') OR
					file_exists($lang_dir . 'lang.' . $alternate_file_name . '.php'))
				{
					ee()->lang->loadfile($alternate_file_name);
				}
			}
		}
	}
	//END lang_autoload

	// --------------------------------------------------------------------

	/**
	 * Uninstall Fieldtype
	 *
	 * @access	public
	 * @param 	string name of fieldtype to uninstall
	 * @return	void
	 */

	public function uninstall_fieldtype ($name)
	{
		//we have to have this field and do not want it uninstalled
		if ($name == 'text')
		{
			return FALSE;
		}

		$obj = $this->get_fieldtype_instance($name);

		if ( is_object($obj))
		{
			$obj->uninstall();
		}

		//set fields to default text
		ee()->freeform_field_model->update(
			array('field_type' => 'text'),
			array('field_type' => $name)
		);

		$success = ee()->freeform_fieldtype_model->delete(array(
			'fieldtype_name' => $name
		));

		Freeform_cacher::clear(__CLASS__, 'get_available_fieldtypes');

		return $success;
	}
	//END uninstall_fieldtype

	// --------------------------------------------------------------------

	/**
	 * Install Fieldtype
	 *
	 * @access	public
	 * @param 	string name of fieldtype to install
	 * @return	void
	 */

	public function install_fieldtype ($name)
	{
		$obj = $this->get_fieldtype_instance(strtolower($name));

		if ( ! is_object($obj)){ return FALSE; }

		$obj->install();

		ee()->freeform_fieldtype_model->insert(array(
			'fieldtype_name' 	=> $name,
			'version' 			=> $obj->info['version']
		));

		Freeform_cacher::clear(__CLASS__, 'get_available_fieldtypes');

		return TRUE;
	}
	//END install_fieldtype

	// --------------------------------------------------------------------

	/**
	 * Get fieldtype display settings.
	 * allows the use of the table class add_rows
	 * or direct template returning
	 *
	 * @access	public
	 * @param 	string name of fieldtype to get display settings for
	 * @param 	object instnace of object to save mem
	 * @return	string its blank if no output was set, else html
	 */

	public function fieldtype_display_settings_output ($name, $settings = array(), $obj = NULL)
	{
		if ( ! $obj OR ! is_object($obj))
		{
			$obj = $this->get_fieldtype_instance(strtolower($name));
		}

		ee()->load->library('table');
		ee()->load->helper('form');

		$settings_return = $obj->display_settings($settings);

		$return = '';

		//
		if ( ! empty(ee()->table->rows))
		{
			ee()->table->set_template(array(
				'table_open'  => '<table class="mainTable padTable ' .
								 'freeform_table headless" style="width:100%;">'
			));
			$return = ee()->table->generate();
		}
		else if ($settings_return AND
				is_string($settings_return) AND
				trim($settings_return) !== '')
		{
			$return = trim($settings_return);
		}

		//cleanup, isle 4!
		ee()->table->clear();

		return $return;
	}
	//END get_fieldtype_display_settings

	// --------------------------------------------------------------------

	/**
	 * Installs default freeform fieldtypes
	 * deletes all default ones first
	 *
	 * @access  public
	 * @return  null
	 */

	public function install_default_freeform_fields ()
	{
		//delete existing
		ee()->freeform_fieldtype_model->delete(array('default_field' => 'y'));

		$default_fieldtypes = $this->get_default_fieldtypes();

		//insert current
		foreach ($default_fieldtypes as $name => $data)
		{
			ee()->freeform_fieldtype_model->insert(array(
				'fieldtype_name' 	=> $name,
				'version' 			=> FREEFORM_VERSION,
				'default_fieldtype' => 'y'
			));
		}

		Freeform_cacher::clear(__CLASS__, 'get_available_fieldtypes');
	}
	//END install_default_freeform_fields

	// --------------------------------------------------------------------

	/**
	 * updates default freeform fieldtypes
	 *
	 * @access  public
	 * @return  boolean		success
	 */

	public function update_default_freeform_fields ($install_missing = FALSE)
	{
		ee()->load->model('freeform_fieldtype_model');

		if ($install_missing)
		{
			//delete existing
			$installed =	ee()->freeform_fieldtype_model
								->key('fieldtype_name', 'fieldtype_name')
								->where('default_field','y')
								->get();

			$default_fieldtypes = $this->get_default_fieldtypes();

			//insert
			foreach ($default_fieldtypes as $name => $data)
			{
				if ( ! isset($installed[$name]))
				{
					ee()->freeform_fieldtype_model->insert(array(
						'fieldtype_name'	=> $name,
						'version'			=> FREEFORM_VERSION,
						'default_fieldtype'	=> 'y'
					));
				}
			}

			Freeform_cacher::clear(__CLASS__, 'get_available_fieldtypes');
		}

		return ee()->freeform_fieldtype_model->update(
			array('version'			=> FREEFORM_VERSION),
			array('default_field'	=> 'y')
		);
	}
	//END update_default_freeform_fields

	// --------------------------------------------------------------------

	/**
	 * Apply Field Method
	 *
	 * Applies a method to each field while feeding it data
	 *
	 * @access  public
	 * @param 	array 	options
	 * @return  array
	 */

	public function apply_field_method ($options = array())
	{
		$defaults = array(
			'form_id'			=> 0,
			'entry_id'			=> 0,
			'edit'				=> FALSE,
			'method'			=> 'display_field',
			'form_data'			=> array(),
			'field_data'		=> array(),
			'field_input_data'	=> array(),
			'variables'			=> array(),
			'tagdata'			=> (
				isset(ee()->TMPL) AND is_object(ee()->TMPL) ?
					ee()->TMPL->tagdata : ''
			),
			'export_type'		=> ''
		);

		$options = array_merge($defaults, $options);

		//make local keys, but only from defaults
		//no funny business
		foreach ($defaults as $key => $value)
		{
			$$key = (isset($options[$key]) ? $options[$key] : $value);
		}

		// -------------------------------------
		//	checks
		// -------------------------------------

		if (($form_id == 0 AND empty($form_data)))
		{
			return FALSE;
		}

		// -------------------------------------
		//	form_data
		// -------------------------------------

		if ( $form_id == 0 AND isset($form_data['form_id']))
		{
			$form_id = $form_data['form_id'];
		}
		else if (empty($form_data))
		{
			$form_data = $this->data->get_form_info($form_id);
		}

		// -------------------------------------
		//	entry id
		// -------------------------------------

		if ( $entry_id == 0 AND isset($field_input_data['entry_id']))
		{
			$entry_id = $field_input_data['entry_id'];
		}

		if ( $entry_id != 0 AND ! is_array($entry_id) AND empty($field_input_data))
		{
			$field_input_data = $this->data->get_entry_data_by_id(
				$entry_id,
				$form_id
			);
		}

		// -------------------------------------
		//	field data
		// -------------------------------------

		if (empty($field_data) AND isset($form_data['fields']))
		{
			$field_data = $form_data['fields'];
		}

		//some functions need a single entry_id, and if this is an array
		//of IDs then we just send 0
		$send_entry_id = $this->is_positive_intlike($entry_id) ? $entry_id : 0;

		$multipart = FALSE;

		// -------------------------------------
		//	display fields
		// -------------------------------------

		foreach ($field_data as $field_id => $f_data)
		{
			// -------------------------------------
			//	get instance of field
			// -------------------------------------

			//get class instance of field
			$instance =& $this->get_field_instance(array(
				'field_id'			=> $field_id,
				'form_id'			=> $form_id,
				'entry_id'			=> $send_entry_id,
				'edit'				=> $edit,
				'field_data'		=> $f_data,
				'extra_settings'	=> array(
					'entry_id'	=> $send_entry_id,
					'preview'	=> (
						isset($f_data['preview']) AND
						$f_data['preview'] === TRUE
					)
				)
			));

			//if we cannot call it, move on
			//we have pre-defines for all functions but still
			if ( ! is_callable(array($instance, $method)))
			{
				continue;
			}

			// -------------------------------------
			//	names n stuff
			// -------------------------------------

			$col_name		= ee()->freeform_form_model->form_field_prefix . $field_id;

			$f_prefix		= (
				$method == 'display_field' OR
				$method == 'replace_tag'
			) ? 'freeform:field:' : '';

			$field_tag_name = $f_prefix . $f_data['field_name'];

			// -------------------------------------
			//	some methods have no need for tagdata
			// -------------------------------------

			if ($method == 'delete')
			{
				//delete should always get
				if ( ! is_array($entry_id))
				{
					$entry_id = array($entry_id);
				}

				$instance->delete($entry_id);

				continue;
			}
			else if ($method == 'remove_from_form')
			{
				$instance->remove_from_form($form_id);

				continue;
			}
			else if ($method == 'pre_process_entries')
			{
				$instance->pre_process_entries($entry_id);

				continue;
			}

			// -------------------------------------
			//	reload previous data
			// -------------------------------------

			$display_field_data = '';

			if (isset($field_input_data[$f_data['field_name']]))
			{
				$display_field_data = $field_input_data[$f_data['field_name']];
			}
			else if (isset($field_input_data[$col_name]))
			{
				$display_field_data = $field_input_data[$col_name];
			}
			//if we didn't meet the previous two issets, then we have nothing
			else if ($method == 'export')
			{
				continue;
			}

			// -------------------------------------
			//	export?
			// -------------------------------------

			if ($method == 'export')
			{
				$variables[$f_data['field_name']] = $instance->export(
					$display_field_data,
					$export_type
				);

				continue;
			}

			// -------------------------------------
			//	CP display?
			// -------------------------------------

			if ($method == 'display_entry_cp')
			{
				$variables[$col_name] = $instance->display_entry_cp(
					$display_field_data
				);

				continue;
			}

			// -------------------------------------
			//	does the isntance require a multipart form
			// -------------------------------------

			if ($instance->requires_multipart)
			{
				$multipart = TRUE;
			}

			// -------------------------------------
			//	parse tagdata?
			// -------------------------------------

			if ($tagdata AND preg_match_all(
				"/" . LD . preg_quote($field_tag_name, '/') . '\b(.*?)' .
				RD . "/s",
				$tagdata,
				$matches
			))
			{
				//we need a sep tagdata for positioning
				$p_tagdata = $tagdata;

				//pre process?
				if ($method == 'replace_tag' AND
					is_callable(array($instance, 'pre_process')))
				{
					$display_field_data = $instance->pre_process($display_field_data);
				}

				$total_matches 	= count($matches[0]);

				for ($i = 0; $i < $total_matches; $i++)
				{
					$args 				= array();
					$attr 				= array();
					$params 			= array();
					$tagpair_tagdata	= array();

					// Checking for variables/tags embedded within tags
					// {exp:channel:entries channel="{master_channel_name}"}
					if (stristr(substr($matches[0][$i], 1), LD) !== FALSE)
					{
						$matches[0][$i] = ee()->functions->full_tag($matches[0][$i], $tagdata);
					}

					if (trim($matches[1][$i]) != '')
					{
						$args = ee()->functions->assign_parameters($matches[1][$i]);

						if ($args)
						{
							//Because I'm a jerkpants! That's why!
							//Oh, and it would totally screw up saving data.
							unset($args['attr:name'], $args['attr:value']);

							//separate attr's and params
							foreach ( $args as $key => $value)
							{
								if (substr($key, 0, 5) == 'attr:')
								{
									$attr[substr($key, 5)] = $value;
								}
								else
								{
									$params[$key] = $value;
								}
							}
						}
					}

					$tagpair_replace 	= $matches[0][$i];

					$p_start			= strpos($p_tagdata, $matches[0][$i]);
					$t_length 			= strlen($matches[0][$i]);
					$d_start 			= $p_start + $t_length;
					$field_tag_open		= LD . $field_tag_name;
					$field_tag_close	= LD . '/' . $field_tag_name . RD;

					$p_tagdata			= substr($p_tagdata, $d_start);

					$next_start			= strpos($p_tagdata, $field_tag_open);
					$next_end			= strpos($p_tagdata, $field_tag_close);

					if ($next_end !== FALSE AND ($next_start === FALSE OR $next_start > $next_end))
					{
						$tagpair_tagdata 	= substr($p_tagdata, 0, $next_end);

						//if we have the same thing, but with different insides
						//we dont want to send it to the array as the same thing
						$tagpair_replace = substr(trim($tagpair_replace), 0, -1) .
							' freeform_replace_marker="' . $i . '"' . RD;

						//our replace method will take care of all
						//tag pairs that are exactly the same
						$tagdata 			= str_replace(
							$matches[0][$i] . $tagpair_tagdata . $field_tag_close,
							$tagpair_replace,
							$tagdata
						);

						//shrink subset
						$p_tagdata = substr($p_tagdata, $next_end + strlen($next_end));
					}

					//remove the beginning and ending {}
					$var_name = trim(trim($tagpair_replace), '{}');

					//default value available?
					if ($display_field_data == '' AND
						isset($params['default_value']))
					{
						$display_field_data = str_replace('|', "\n", $params['default_value']);
					}

					if ($method == 'display_field')
					{
						$variables[$var_name] =
							$instance->display_field(
								$display_field_data,
								$params,
								$attr,
								$tagpair_tagdata
							);
					}
					else if ($method == 'replace_tag')
					{
						$variables[$var_name] =
							$instance->replace_tag(
								$display_field_data,
								$params,
								$tagpair_tagdata
							);
					}
				}
				//END for ($i
			}
			//END if preg_match_all
		}
		//END foreach ($form_data['fields'] as $field_id => $field_data)

		//since these all default, its safe to return them each time
		//it just wont matter for things like removing forms and deleting
		//entries
		return array(
			'variables' => $variables,
			'tagdata' 	=> $tagdata,
			'multipart' => $multipart
		);
	}
	//END apply_field_method

	// --------------------------------------------------------------------

	/**
	 * Delete Field
	 *
	 * checks field to see if its in any forms, then removes the field
	 *
	 * @access public
	 * @param  mixed 	int/array of ints 	$field_id field id to delete
	 * @return boolean	success
	 */

	public function delete_field ($field_ids)
	{
		if ( ! is_array($field_ids) AND
			 ! $this->is_positive_intlike($field_ids))
		{
			return FALSE;
		}

		if ( ! is_array($field_ids))
		{
			$field_ids = array($field_ids);
		}

		$field_ids = array_filter($field_ids, array($this, 'is_positive_intlike'));

		ee()->load->library('freeform_forms');

		//go through each field and remove it from every form its in
		$remove_fields = array();

		foreach ($field_ids as $field_id)
		{
			$field_form_data = $this->data->get_form_info_by_field_id($field_id);

			if ( $field_form_data !== FALSE )
			{
				foreach ($field_form_data as $form_id => $form_data)
				{
					ee()->freeform_forms->remove_field_from_form($form_id, $field_id);
				}
			}

			$instance =& $this->get_field_instance($field_id);

			if (is_callable(array($instance, 'delete_field')))
			{
				$instance->delete_field();
			}

			$remove_fields[] = $field_id;
		}

		if (empty($remove_fields)){ return FALSE; }

		//delete all fields
		ee()->freeform_field_model->where_in('field_id', $remove_fields)->delete();

		Freeform_cacher::clear(__CLASS__, 'get_field_instance');

		return TRUE;
	}
	//END delete_field

	// --------------------------------------------------------------------

	/**
	 * validate
	 *
	 * runs field validation against passed data
	 *
	 * @access	public
	 * @param	int  	ID of form to check
	 * @param	array 	field input data to validate
	 * @param	bool	include_names
	 * @return	array 	error array
	 */

	public function validate ($form_id, $field_input_data, $include_labels = TRUE)
	{
		$errors = array();

		if ( ! $this->data->is_valid_form_id($form_id))
		{
			return $this->actions()->full_stop(lang('invalid_form_id'));
		}

		$form_data = $this->data->get_form_info($form_id);

		//loading for fields themselves if they want it
		ee()->load->library('form_validation');

		foreach ($form_data['fields'] as $field_id => $field_data)
		{
			if ( ! isset($field_input_data[$field_data['field_name']]))
			{
				continue;
			}

			//get class instance of field
			$instance =& $this->get_field_instance(array(
				'field_id'			=> $field_id,
				'form_id'			=> $form_id
			));

			if ( ! is_object($instance) OR
				 ! is_callable(array($instance, 'validate')))
			{
				continue;
			}

			$output = $instance->validate(
				$field_input_data[$field_data['field_name']]
			);

			if ($output !== TRUE)
			{

				$prefix = ($include_labels) ?  $field_data['field_label'] . ': ' : '';

				//if the field itself defines errors, lets show them
				//else we show a generic
				if ( is_array($output) AND ! empty($output))
				{
					if ( ! isset($errors[$field_data['field_name']]))
					{
						$errors[$field_data['field_name']] = array();
					}
					//did this start as a string?
					else if ( ! is_array($errors[$field_data['field_name']]))
					{
						$errors[$field_data['field_name']] = (array) $errors[$field_data['field_name']];
					}

					//if we are prefixing for general output
					//lets make sure any incoming items are prefixed as well
					if ($prefix AND ! empty($errors[$field_data['field_name']]))
					{
						foreach ($errors[$field_data['field_name']] as $e_k => $e_v)
						{
							if (substr($e_v, 0, strlen($prefix)) !== $prefix)
							{
								$errors[$field_data['field_name']][$e_k] = $prefix . $e_v;
							}
						}
					}

					//add new errors
					foreach($output as $field_error)
					{
						$errors[$field_data['field_name']][] = $prefix . $field_error;
					}
				}
				else if (is_string($output))
				{
					$errors[$field_data['field_name']] = $prefix . $output;
				}
				else
				{
					$errors[$field_data['field_name']] = $prefix . lang('generic_invalid_field_input');
				}
			}
		}

		return $errors;
	}
	//END validate

}
//END Freeform_notifications


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Albedo.Refraction;
using Xunit;

namespace Albedo.UnitTests.Refraction
{
    public class ConstructorInfoElementRefractionTests
    {
        [Fact]
        public void SutIsReflectionElementRefraction()
        {
            var sut = new ConstructorInfoElementRefraction<object>();
            Assert.IsAssignableFrom<IReflectionElementRefraction<object>>(sut);
        }

        [Theory, ClassData(typeof(SourceObjects))]
        public void rObjectsReturnsCorrectResult(object[] objects)
        {
            var sut = new ConstructorInfoElementRefraction<object>();

            var actual = sut.Refract(objects);

            var expected = objects
                .OfType<ConstructorInfo>()
                .Select(ci => new ConstructorInfoElement(ci))
                .Cast<IReflectionElement>();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void rNullSourceThrows()
        {
            var sut = new ConstructorInfoElementRefraction<object>();
            Assert.Throws<ArgumentNullException>(() => sut.Refract(null));
        }

        private class SourceObjects : IEnumerable<object[]>
        {
            public IEnumerator<object[]> GetEnumerator()
            {
                yield return new[]
                {
                    new object[]
                    {
                        this.GetType().GetConstructors().First()
                    }
                };
                yield return new[]
                {
                    new object[]
                    {
                        this.GetType().GetConstructors().First(),
                        typeof(Version).GetConstructors().First()
                    }
                };
                yield return new[]
                {
                    new object[]
                    {
                        this.GetType().GetConstructors().First(),
                        typeof(Version),
                        typeof(Version).GetConstructors().First()
                    }
                };
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }
        }

    }
}


text:
import Control.Exception
import Criterion.Main
import Prelude hiding (catch)

import qualified LSC2008.TestCatch
import qualified LSC2008.TestCircuits1
import qualified LSC2008.TestCircuits2
import qualified LSC2008.TestCircuits3
import qualified LSC2008.TestCountdown1
import qualified LSC2008.TestCountdown2
import qualified LSC2008.TestHuffman1
import qualified LSC2008.TestHuffman2
import qualified LSC2008.TestListSet1
import qualified LSC2008.TestMate
import qualified LSC2008.TestMux2
import qualified LSC2008.TestRedBlack
import qualified LSC2008.TestRegExp
import qualified LSC2008.TestSumPuz
import qualified LSC2008.TestTurner

import qualified LSC2012.TestCatch
import qualified LSC2012.TestCircuits1
import qualified LSC2012.TestCircuits2
import qualified LSC2012.TestCircuits3
import qualified LSC2012.TestCountdown1
import qualified LSC2012.TestCountdown2
import qualified LSC2012.TestHuffman1
import qualified LSC2012.TestHuffman2
import qualified LSC2012.TestListSet1
import qualified LSC2012.TestMate
import qualified LSC2012.TestMux2
import qualified LSC2012.TestRedBlack
import qualified LSC2012.TestRegExp
import qualified LSC2012.TestSumPuz
import qualified LSC2012.TestTurner

ignore :: IO a -> IO ()
ignore x = (x >> return ()) `catch` (\ e -> print (e :: SomeException))

lsc2008 =
  [ bench "TestCatch" $ ignore $ LSC2008.TestCatch.bench "4"
  , bench "TestCircuits1" $ ignore $ LSC2008.TestCircuits1.bench "10"
  , bench "TestCircuits2" $ ignore $ LSC2008.TestCircuits2.bench "7"
  , bench "TestCircuits3" $ ignore $ LSC2008.TestCircuits3.bench "4"
  , bench "TestCountdown1" $ ignore $ LSC2008.TestCountdown1.bench "5"
  , bench "TestCountdown2" $ ignore $ LSC2008.TestCountdown2.bench "4"
  , bench "TestHuffman1" $ ignore $ LSC2008.TestHuffman1.bench "8"
  , bench "TestHuffman2" $ ignore $ LSC2008.TestHuffman2.bench "5"
  , bench "TestListSet1" $ ignore $ LSC2008.TestListSet1.bench "11"
  , bench "TestMate" $ ignore $ LSC2008.TestMate.bench "4"
  , bench "TestMux2" $ ignore $ LSC2008.TestMux2.bench "10"
  , bench "TestRedBlack" $ ignore $ LSC2008.TestRedBlack.bench "4"
  , bench "TestRegExp" $ ignore $ LSC2008.TestRegExp.bench "2"
  , bench "TestSumPuz" $ ignore $ LSC2008.TestSumPuz.bench "4"
  , bench "TestTurner" $ ignore $ LSC2008.TestTurner.bench "3" ]

lsc2012 =
  [ bench "TestCatch" $ ignore $ LSC2012.TestCatch.bench "4"
  , bench "TestCircuits1" $ ignore $ LSC2012.TestCircuits1.bench "10"
  , bench "TestCircuits2" $ ignore $ LSC2012.TestCircuits2.bench "7"
  , bench "TestCircuits3" $ ignore $ LSC2012.TestCircuits3.bench "4"
  , bench "TestCountdown1" $ ignore $ LSC2012.TestCountdown1.bench "5"
  , bench "TestCountdown2" $ ignore $ LSC2012.TestCountdown2.bench "4"
  , bench "TestHuffman1" $ ignore $ LSC2012.TestHuffman1.bench "8"
  , bench "TestHuffman2" $ ignore $ LSC2012.TestHuffman2.bench "5"
  , bench "TestListSet1" $ ignore $ LSC2012.TestListSet1.bench "11"
  , bench "TestMate" $ ignore $ LSC2012.TestMate.bench "4"
  , bench "TestMux2" $ ignore $ LSC2012.TestMux2.bench "10"
  , bench "TestRedBlack" $ ignore $ LSC2012.TestRedBlack.bench "4"
  , bench "TestRegExp" $ ignore $ LSC2012.TestRegExp.bench "2"
  , bench "TestSumPuz" $ ignore $ LSC2012.TestSumPuz.bench "4"
  , bench "TestTurner" $ ignore $ LSC2012.TestTurner.bench "3" ]

main = defaultMain [ bgroup "LSC2008" lsc2008, bgroup "LSC2012" lsc2012]


text:
package de.terrestris.shoguncore.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import de.terrestris.shoguncore.dao.LayerDataSourceDao;
import de.terrestris.shoguncore.model.layer.source.LayerDataSource;
import de.terrestris.shoguncore.model.module.Module;

/**
 * Service class for the {@link Module} model.
 *
 * @author Nils Bühner
 * @see AbstractCrudService
 */
@Service("layerDataSourceService")
public class LayerDataSourceService<E extends LayerDataSource, D extends LayerDataSourceDao<E>> extends
    PermissionAwareCrudService<E, D> {

    /**
     * Default constructor, which calls the type-constructor
     */
    @SuppressWarnings("unchecked")
    public LayerDataSourceService() {
        this((Class<E>) LayerDataSource.class);
    }

    /**
     * Constructor that sets the concrete entity class for the service.
     * Subclasses MUST call this constructor.
     */
    protected LayerDataSourceService(Class<E> entityClass) {
        super(entityClass);
    }

    /**
     * We have to use {@link Qualifier} to define the correct dao here.
     * Otherwise, spring can not decide which dao has to be autowired here
     * as there are multiple candidates.
     */
    @Override
    @Autowired
    @Qualifier("layerDataSourceDao")
    public void setDao(D dao) {
        this.dao = dao;
    }
}


text:
package org.drools.core.phreak;

import org.drools.core.base.DroolsQuery;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.LeftTupleSets;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.PathMemory;
import org.drools.core.reteoo.QueryElementNode.QueryElementNodeMemory;
import org.drools.core.reteoo.QueryTerminalNode;
import org.drools.core.reteoo.RuleTerminalNode;
import org.drools.core.spi.PropagationContext;
import org.drools.core.util.LinkedList;

import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: mdproctor
* Date: 03/05/2013
* Time: 15:42
* To change this template use File | Settings | File Templates.
*/
public class PhreakQueryTerminalNode {
    public void doNode(QueryTerminalNode qtnNode,
                       InternalWorkingMemory wm,
                       LeftTupleSets srcLeftTuples,
                       LinkedList<StackEntry> stack) {
        if (srcLeftTuples.getDeleteFirst() != null) {
            doLeftDeletes(qtnNode, wm, srcLeftTuples, stack);
        }

        if (srcLeftTuples.getUpdateFirst() != null) {
            doLeftUpdates(qtnNode, wm, srcLeftTuples, stack);
        }

        if (srcLeftTuples.getInsertFirst() != null) {
            doLeftInserts(qtnNode, wm, srcLeftTuples, stack);
        }

        srcLeftTuples.resetAll();
    }

    public void doLeftInserts(QueryTerminalNode qtnNode,
                              InternalWorkingMemory wm,
                              LeftTupleSets srcLeftTuples,
                              LinkedList<StackEntry> stack) {

        for (LeftTuple leftTuple = srcLeftTuples.getInsertFirst(); leftTuple != null; ) {
            LeftTuple next = leftTuple.getStagedNext();
            //qtnNode.assertLeftTuple( leftTuple, leftTuple.getPropagationContext(), wm );

            PropagationContext pCtx = RuleTerminalNode.findMostRecentPropagationContext(leftTuple,
                                                                                leftTuple.getPropagationContext());

            // find the DroolsQuery object
            LeftTuple rootEntry = leftTuple.getRootLeftTuple();

            DroolsQuery dquery = (DroolsQuery) rootEntry.getLastHandle().getObject();
            dquery.setQuery(qtnNode.getQuery());
            if (dquery.getStackEntry() != null) {
                checkAndTriggerQueryReevaluation(wm, stack, rootEntry, dquery);
            }

            // Add results to the adapter
            dquery.getQueryResultCollector().rowAdded(qtnNode.getQuery(),
                                                      leftTuple,
                                                      pCtx,
                                                      wm);

            leftTuple.clearStaged();
            leftTuple = next;
        }
    }

    public void doLeftUpdates(QueryTerminalNode qtnNode,
                              InternalWorkingMemory wm,
                              LeftTupleSets srcLeftTuples,
                              LinkedList<StackEntry> stack) {

        for (LeftTuple leftTuple = srcLeftTuples.getUpdateFirst(); leftTuple != null; ) {
            LeftTuple next = leftTuple.getStagedNext();

            PropagationContext pCtx = RuleTerminalNode.findMostRecentPropagationContext(leftTuple,
                                                                                leftTuple.getPropagationContext());

            // qtnNode.modifyLeftTuple( leftTuple, leftTuple.getPropagationContext(), wm );
            LeftTuple rootEntry = leftTuple;

            // find the DroolsQuery object
            while (rootEntry.getParent() != null) {
                rootEntry = rootEntry.getParent();
            }
            DroolsQuery dquery = (DroolsQuery) rootEntry.getLastHandle().getObject();
            dquery.setQuery(qtnNode.getQuery());
            if (dquery.getStackEntry() != null) {
                checkAndTriggerQueryReevaluation(wm, stack, rootEntry, dquery);
            }

            // Add results to the adapter
            dquery.getQueryResultCollector().rowUpdated(qtnNode.getQuery(),
                                                        leftTuple,
                                                        pCtx,
                                                        wm);

            leftTuple.clearStaged();
            leftTuple = next;
        }
    }

    public void doLeftDeletes(QueryTerminalNode qtnNode,
                              InternalWorkingMemory wm,
                              LeftTupleSets srcLeftTuples,
                              LinkedList<StackEntry> stack) {

        for (LeftTuple leftTuple = srcLeftTuples.getDeleteFirst(); leftTuple != null; ) {
            LeftTuple next = leftTuple.getStagedNext();

            //qtnNode.retractLeftTuple( leftTuple, leftTuple.getPropagationContext(), wm );

            PropagationContext pCtx = RuleTerminalNode.findMostRecentPropagationContext(leftTuple,
                                                                                leftTuple.getPropagationContext());

            LeftTuple rootEntry = leftTuple;

            // find the DroolsQuery object
            while (rootEntry.getParent() != null) {
                rootEntry = rootEntry.getParent();
            }
            DroolsQuery dquery = (DroolsQuery) rootEntry.getLastHandle().getObject();
            dquery.setQuery(qtnNode.getQuery());

            if (dquery.getStackEntry() != null) {
                checkAndTriggerQueryReevaluation(wm, stack, rootEntry, dquery);
            }

            // Add results to the adapter
            dquery.getQueryResultCollector().rowRemoved(qtnNode.getQuery(),
                                                        leftTuple,
                                                        pCtx,
                                                        wm);

            leftTuple.clearStaged();
            leftTuple = next;
        }
    }

    public static void checkAndTriggerQueryReevaluation(InternalWorkingMemory wm, LinkedList<StackEntry> stack, LeftTuple rootEntry, DroolsQuery dquery) {
        StackEntry stackEntry = dquery.getStackEntry();
        if (!isAdded(stack, stackEntry)) {
            // Ignore unless stackEntry is not added to stack

            // node must be marked as dirty
            ((QueryElementNodeMemory)stackEntry.getNodeMem()).setNodeDirtyWithoutNotify();
            if (stackEntry.getLiaNode()== rootEntry.getLeftTupleSink().getLeftTupleSource()) {
                // query is recursive, so just re-add the stack entry to the current stack. This happens for reactive queries, triggered by a beta node right input
                stack.add(stackEntry);
            } else {
                // parents is anther rule/query need to notify for agenda to schedule. query is reactive, triggered by right input,
                List<PathMemory> pmems = dquery.getRuleMemories();
                if (pmems != null) {
                    // StackEntry is null, when query is called directly from java

                    // reactivity comes form within the query, so need to notify parent rules to evaluate the results
                    for (int i = 0, length = pmems.size(); i < length; i++) {
                        PathMemory pmem = pmems.get(i);
                        pmem.doLinkRule(wm); // method already ignores is rule is activated and on agenda
                    }
                }
            }
        }
    }

    public static boolean isAdded(LinkedList<StackEntry> stack, StackEntry stackEntry) {
        if (stackEntry == null || stackEntry.getPrevious() != null || stackEntry.getNext() != null || stack.getFirst() == stackEntry) {
            return true;
        }

        return false;
    }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"plugin"

	// DO NOT IMPORT THIRD PARTY PACKAGES
	// The 3rd party package version used by go server may be
	// different from the one in user's source code and will
	// cause plugin version mismatched. Hence, we should never
	// import any external packages except the Fission or built-in
	// packages.

	"github.com/fission/fission/environments/go/context"
)

const (
	CODE_PATH = "/userfunc/user"
)

type (
	FunctionLoadRequest struct {
		// FilePath is an absolute filesystem path to the
		// function. What exactly is stored here is
		// env-specific. Optional.
		FilePath string `json:"filepath"`

		// FunctionName has an environment-specific meaning;
		// usually, it defines a function within a module
		// containing multiple functions. Optional; default is
		// environment-specific.
		FunctionName string `json:"functionName"`

		// URL to expose this function at. Optional; defaults
		// to "/".
		URL string `json:"url"`
	}
)

var userFunc http.HandlerFunc

func loadPlugin(codePath, entrypoint string) (http.HandlerFunc, error) {

	// if codepath's a directory, load the file inside it
	info, err := os.Stat(codePath)
	if err != nil {
		return nil, fmt.Errorf("error checking plugin path: %v", err)
	}
	if info.IsDir() {
		files, err := ioutil.ReadDir(codePath)
		if err != nil {
			return nil, fmt.Errorf("error reading directory: %v", err)
		}
		if len(files) == 0 {
			return nil, fmt.Errorf("no files to load: %v", codePath)
		}
		fi := files[0]
		codePath = filepath.Join(codePath, fi.Name())
	}

	log.Printf("loading plugin from %v", codePath)
	p, err := plugin.Open(codePath)
	if err != nil {
		return nil, fmt.Errorf("error loading plugin: %v", err)
	}
	sym, err := p.Lookup(entrypoint)
	if err != nil {
		return nil, fmt.Errorf("entry point not found: %v", err)
	}

	switch h := sym.(type) {
	case *http.Handler:
		return (*h).ServeHTTP, nil
	case *http.HandlerFunc:
		return *h, nil
	case func(http.ResponseWriter, *http.Request):
		return h, nil
	case func(context.Context, http.ResponseWriter, *http.Request):
		return func(w http.ResponseWriter, r *http.Request) {
			c := context.New()
			h(c, w, r)
		}, nil
	default:
		panic("Entry point not found: bad type")
	}
}

func specializeHandler() func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if userFunc != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Not a generic container"))
			return
		}

		_, err := os.Stat(CODE_PATH)
		if err != nil {
			if os.IsNotExist(err) {
				log.Printf("code path (%v) does not exist: %v", CODE_PATH, err)
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(CODE_PATH + ": not found"))
				return
			} else {
				log.Printf("unknown error looking for code path(%v): %v", CODE_PATH, err)
				err = fmt.Errorf("unknown error: %v", err)
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
		}

		log.Println("specializing ...")
		userFunc, err = loadPlugin(CODE_PATH, "Handler")
		if err != nil {
			err = fmt.Errorf("error specializing function: %v", err)
			log.Println(err.Error())
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}
		log.Println("done")
	}
}

func specializeHandlerV2() func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if userFunc != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Not a generic container"))
			return
		}

		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Printf("error reading request body: %v", err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		var loadreq FunctionLoadRequest
		err = json.Unmarshal(body, &loadreq)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		_, err = os.Stat(loadreq.FilePath)
		if err != nil {
			if os.IsNotExist(err) {
				log.Printf("code path (%v) does not exist: %v", loadreq.FilePath, err)
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(loadreq.FilePath + ": not found"))
				return
			} else {
				log.Printf("unknown error looking for code path(%v): %v", loadreq.FilePath, err)
				err = fmt.Errorf("unknown error: %v", err)
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
		}

		log.Println("specializing ...")
		userFunc, err = loadPlugin(loadreq.FilePath, loadreq.FunctionName)
		if err != nil {
			err = fmt.Errorf("error specializing function: %v", err)
			log.Println(err.Error())
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}
		log.Println("done")
	}
}

func readinessProbeHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
}

func main() {

	http.HandleFunc("/healthz", readinessProbeHandler)
	http.HandleFunc("/specialize", specializeHandler())
	http.HandleFunc("/v2/specialize", specializeHandlerV2())

	// Generic route -- all http requests go to the user function.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if userFunc == nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Generic container: no requests supported"))
			return
		}
		userFunc(w, r)
	})

	log.Println("listening on 8888 ...")
	http.ListenAndServe(":8888", nil)
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Configuration;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.contentitem;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.language;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.DataLayer;
using umbraco.BusinessLogic.Utils;
using umbraco.cms.presentation.Trees;
using umbraco.BusinessLogic.Actions;
using Umbraco.Core;

namespace umbraco
{
    [Tree(Constants.Applications.Settings, "dictionary", "Dictionary", action: "openDictionary()", sortOrder: 3)]
    public class loadDictionary : BaseTree
	{
        public loadDictionary(string application) : base(application) { }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            rootNode.NodeType = "init" + TreeAlias;
            rootNode.NodeID = "init";
            rootNode.Action = "javascript:openDictionary()";
        }

        protected override void CreateAllowedActions(ref List<IAction> actions)
        {
            actions.Clear();
            actions.Add(ActionNew.Instance);
            actions.Add(ActionDelete.Instance);
            actions.Add(ContextMenuSeperator.Instance);
            actions.Add(ActionRefresh.Instance);
        }

		public override void RenderJS(ref StringBuilder Javascript)
        {
            Javascript.Append(
                @"
			function openDictionaryItem(id) {
				UmbClientMgr.contentFrame('settings/editDictionaryItem.aspx?id=' + id);
			}
			");
        }

        public override void Render(ref XmlTree tree)
        {

            Dictionary.DictionaryItem[] tmp;
            if (this.id == this.StartNodeID)
                tmp = Dictionary.getTopMostItems;
            else
                tmp = new Dictionary.DictionaryItem(this.id).Children;

            foreach (Dictionary.DictionaryItem di in tmp)
            {
                XmlTreeNode xNode = XmlTreeNode.Create(this);
                xNode.NodeID = di.id.ToString(); //dictionary_ + id..
                xNode.Text = di.key;
                xNode.Action = string.Format("javascript:openDictionaryItem({0});", di.id);
                xNode.Icon = "settingDataType.gif";
                xNode.OpenIcon = "settingDataType.gif";
                xNode.NodeType = "DictionaryItem"; //this shouldn't be like this, it should be this.TreeAlias but the ui.config file points to this name.
                xNode.Source = this.GetTreeServiceUrl(di.id);
				xNode.HasChildren = di.hasChildren;

                OnBeforeNodeRender(ref tree, ref xNode, EventArgs.Empty);
                if (xNode != null)
                {
                    tree.Add(xNode);
                    OnAfterNodeRender(ref tree, ref xNode, EventArgs.Empty);
                }

            }
        }

	}

}


text:
'use strict';

var Resource = require('../Resource');
var method = Resource.method;

/**
 * User
 * @module user
 */
module.exports = Resource.extend({

  /**
   * @function
   * @param {String} username username of the user
   * @param {Object} options Optional request options
   */
  get: method({
    method: 'GET',
    path: '/users/:username',
    urlParams: ['username'],
    options: {
      treat404asEmpty: true
    }
  }),

  /**
   * Undocumented function to return a user by her ID.
   * @function
   * @param {String} id id of the user
   * @param {Object} options Optional request options
   */
  getById: method({
    method: 'GET',
    path: '/user/:id',
    urlParams: ['id'],
    options: {
      treat404asEmpty: true
    }
  }),

  /**
   * @function
   * @param {Object} options Optional request options
   */
  getAuthUser: method({
    method: 'GET',
    path: '/user'
  }),

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Scutellinia dispora Clem.

### Remarks
null


text:
name: SoftLayer DNS
title: SoftLayer DNS Provider
layout: default
jsId: SOFTLAYER
---

# SoftLayer DNS Provider

NOTE: This provider is currently has no maintainer. We are looking for
a volunteer. If this provider breaks it may be disabled or removed if
it can not be easily fixed.

## Configuration

To use this provider, add an entry to `creds.json` with `TYPE` set to `SOFTLAYER`
along with authentication fields.
Authenticating with SoftLayer requires at least a `username` and `api_key` for authentication. It can also optionally take a `timeout` and `endpoint_url` parameter however these are optional and will use standard defaults if not provided.

Example:

```json
{
  "softlayer": {
    "TYPE": "SOFTLAYER",
    "api_key": "mysecretapikey",
    "username": "myusername"
  }
}
```

To maintain compatibility with existing softlayer CLI services these can also be provided by the `SL_USERNAME` and `SL_API_KEY` environment variables or specified in the `~/.softlayer`, but this is discouraged. More information about these methods can be found at [the softlayer-go library documentation](https://github.com/softlayer/softlayer-go#sessions).

## Usage

An example `dnsconfig.js` configuration:

```js
var REG_NONE = NewRegistrar("none"); // no registrar
var DSP_SOFTLAYER = NewDnsProvider("softlayer");

D("example.tld", registrary, DnsProvider(DSP_SOFTLAYER),
    A("test", "1.2.3.4")
);
```

## Metadata
This provider does not recognize any special metadata fields unique to SoftLayer dns.
For compatibility with the pre-generated NAMESERVER fields it's recommended to set the NS TTL to 86400 such as:

```js
D("example.tld", REG_NONE, DnsProvider(SOFTLAYER),
    NAMESERVER_TTL(86400),

    A("test", "1.2.3.4")
);
```


text:
<!DOCTYPE html>

    <title>Farmácias Populares</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no"/>

    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Roboto:400,500,700,400italic'>
    <link rel="stylesheet" href="./bower_components/angular-material/angular-material.min.css"/>
    <link rel="stylesheet" href="./bower_components/openlayers3/build/ol.css"/>
    <link rel="stylesheet"
          href="./bower_components/angular-openlayers-directive/dist/angular-openlayers-directive.css"/>
    <link rel="stylesheet" href="assets/app.css"/>

<md-sidenav class="site-sidenav md-sidenav-left md-whiteframe-z2" md-component-id="left">

    <md-toolbar>

Opções

    </md-toolbar>

    <md-list>
        <md-list-item layout-align="center center">

        </md-list-item>
        <md-list-item>
            Informe o tamanho do raio em quilômetros.
        </md-list-item>
        <md-list-item>

                <md-slider flex min="1" max="25" ng-model="distance" aria-label="red" id="red-slider" class>
                </md-slider>

                    <input type="number" ng-model="distance" aria-label="red" aria-controls="red-slider" style="border: hidden"> km

        </md-list-item>
        <md-list-item>
            Informe a quantidade máxima de farmácias a serem exibidas.
        </md-list-item>
        <md-list-item>

                <md-slider flex min="1" max="50" ng-model="quantity" aria-label="quantity" id="quantity-slider" class>
                </md-slider>

                    <input type="number" ng-model="quantity" aria-label="quantity" aria-controls="quantity-slider" style="border: hidden"> total

        </md-list-item>
    </md-list>
</md-sidenav>

    <md-toolbar layout="row" class="md-whiteframe-z1">
        <md-button class="menu" ng-click="ctrl.toggleMenu()">
            <md-icon md-svg-icon="menu"></md-icon>
        </md-button>

Rede de Farmácias Populares

    </md-toolbar>

    <md-content id="content">

            <md-button class="md-fab" aria-label="Github" ng-click="ctrl.irParaCodigoFonte()">
                <md-icon md-svg-src="assets/svg/github.svg"></md-icon>
            </md-button>

        <md-card style="width:20em;height:490px; position: fixed; z-index:1000; top: 5.9em; right:0.5em; overflow-y: scroll">
            <md-card-content>

Farmácias por UF

                <md-list>
                    <md-list-item ng-repeat="state in ctrl.states">
                        <md-button ng-click="ctrl.byState(state.name)" style="background-color: {{state.color}}; color: {{state.colorText}}"
                                   class="md-raised">
                            {{state.name}} - ({{state.total}})
                        </md-button>
                    </md-list-item>
                </md-list>
            </md-card-content>
        </md-card>

            <openlayers width="100%" height="720px" ol-center="center" ol-defaults="defaults">

            </openlayers>

    </md-content>


text:
Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
	launch: function() {

		// Radian
		var project_oid = '/project/37192747640';

		this.add({
			xtype: 'rallycombobox',
			width: 600,
			fieldLabel: 'Select Initiative:',
			// Default to I46
			value: '/portfolioitem/initiative/36106803051',
			// Display Template
			displayTpl: Ext.create('Ext.XTemplate','<tpl for=".">','{FormattedID} - {Name}','</tpl>'),
			// List Template
			tpl: Ext.create('Ext.XTemplate','<tpl for=".">','
{FormattedID} - {Name}
','</tpl>'),
			storeConfig: {
				autoLoad: true,
				model: 'PortfolioItem/Initiative',
				fetch: ['FormattedID', 'Name'],
				sorters: [
					{
						property: 'ObjectID',
						direction: 'ASC'
					}
				],
				remoteGroup: false,
				remoteSort: false,
				remoteFilter: false,
				limit: Infinity,
				context: {
					project: project_oid,
					projectScopeDown: true,
					projectScopeUp: false
				}
			},
			// stateful: false,
			listeners: {
				select: this._onSelect,
				ready: this._onLoad,
				scope: this
			}
		});
	},

	_onLoad: function() {
		var project_oid = '/project/37192747640';

		this.add({
			xtype: 'rallycardboard',
			types: ['User Story'],
			attribute: 'ScheduleState',
			// context: this.getContext(),
			storeConfig: {
				fetch: ['Feature'],
				context: {
					project: project_oid,
					projectScopeDown: true,
					projectScopeUp: false
				},
				filters: [
					this._getFilter()
				]
			},
			columnConfig: {
				plugins: [
					{ptype: 'rallycolumncardcounter'}
				]
			},
			cardConfig: {
				fields: ['Feature','Iteration','Project'],
				showIconsAndHighlightBorder: false,
				editable: false,
				showAge: true
			}
			// rowConfig: {
				// field: 'Release'
			// }
		});
	},

	_onSelect: function() {
		var board = this.down('rallycardboard');
		board.refresh({
			storeConfig: {
				filters: [this._getFilter()]
			}
		});
	},

	_getFilter: function() {
		var combo = this.down('rallycombobox');
		console.log(combo.getValue());
		var filters = Ext.create('Rally.data.QueryFilter', {
			property: 'Feature.Parent.Parent',
			operator: '=',
			value: combo.getValue()
		});
		filters = filters.and({
			property: 'DirectChildrenCount',
			operator: '=',
			value: '0'
		});
		filters = filters.and({
			property: 'Iteration',
			operator: '=',
			value: null
		});
		// filters = filters.and({
			// property: 'AcceptedDate',
			// operator: '<',
			// value: 'LastMonth'
		// });
		// filters = filters.or({
			// property: 'ScheduleState',
			// operator: '!=',
			// value: 'Accepted'
		// });
		filters.toString();
		return filters;
	}

});


text:
<?php

namespace Oro\Bundle\AddressBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

use Oro\Bundle\EntityConfigBundle\Metadata\Annotation\ConfigField;
use Oro\Bundle\FormBundle\Entity\PrimaryItem;

/**
 * Typed Address
 *
 * @ORM\MappedSuperclass
 */
abstract class AbstractTypedAddress extends AbstractAddress implements PrimaryItem
{
    /**
     * Many-to-many relation field, relation parameters must be in specific class
     *
     * @var Collection
     */
    protected $types;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_primary", type="boolean", nullable=true)
     * @ConfigField(
     *      defaultValues={
     *          "importexport"={
     *              "excluded"=true
     *          }
     *      }
     * )
     */
    protected $primary;

    public function __construct()
    {
        $this->types = new ArrayCollection();
        $this->primary = false;
    }

    /**
     * @return Collection|AddressType[]
     */
    public function getTypes()
    {
        return $this->types;
    }

    /**
     * @param Collection $types
     * @return AbstractTypedAddress
     */
    public function setTypes(Collection $types)
    {
        $this->types = $types;

        return $this;
    }

    /**
     * Get list of address types names
     *
     * @return array
     */
    public function getTypeNames()
    {
        $result = array();
        /** @var AddressType $type */
        foreach ($this->getTypes() as $type) {
            $result[] = $type->getName();
        }
        return $result;
    }

    /**
     * Gets instance of address type entity by it's name if it exist.
     *
     * @param string $typeName
     * @return AddressType|null
     */
    public function getTypeByName($typeName)
    {
        foreach ($this->getTypes() as $type) {
            if ($type->getName() === $typeName) {
                return $type;
            }
        }
        return null;
    }

    /**
     * Checks if address has type with specified name
     *
     * @param string $typeName
     * @return bool
     */
    public function hasTypeWithName($typeName)
    {
        return null !== $this->getTypeByName($typeName);
    }

    /**
     * Get list of address types names
     *
     * @return array
     */
    public function getTypeLabels()
    {
        $result = array();

        foreach ($this->getTypes() as $type) {
            $result[] = $type->getLabel();
        }

        return $result;
    }

    /**
     * @param AddressType $type
     * @return AbstractTypedAddress
     */
    public function addType(AddressType $type)
    {
        if (!$this->getTypes()->contains($type)) {
            $this->getTypes()->add($type);
        }

        return $this;
    }

    /**
     * @param AddressType $type
     * @return AbstractTypedAddress
     */
    public function removeType(AddressType $type)
    {
        if ($this->getTypes()->contains($type)) {
            $this->getTypes()->removeElement($type);
        }

        return $this;
    }

    /**
     * @param bool $primary
     * @return AbstractTypedAddress
     */
    public function setPrimary($primary)
    {
        $this->primary = (bool)$primary;

        return $this;
    }

    /**
     * @return bool
     */
    public function isPrimary()
    {
        return (bool)$this->primary;
    }

    /**
     * {@inheritdoc}
     */
    public function isEmpty()
    {
        return parent::isEmpty()
            && $this->types->isEmpty()
            && !$this->primary;
    }
}


text:
A generator for [Yeoman](http://yeoman.io).

Create a webapp skeleton with the following tools:

- Gulp
- Bower
- Browserify / Browserify-shim
- Sass
- CoffeeScript (optional)
- Testem with Mocha/Chai/Sinon

Default Bower dependencies:

- jQuery
- Underscore

## Getting Started

### What is Yeoman?

Trick question. It's not a thing. It's this guy:

![](http://i.imgur.com/JHaAlBJ.png)

Basically, he wears a top hat, lives in your computer, and waits for you to tell him what kind of application you wish to create.

Not every new computer comes with a Yeoman pre-installed. He lives in the [npm](https://npmjs.org) package repository. You only have to ask for him once, then he packs up and moves into your hard drive. *Make sure you clean up, he likes new and shiny things.*

```
$ npm install -g yo
```

### Yeoman Generators

Yeoman travels light. He didn't pack any generators when he moved in. You can think of a generator like a plug-in. You get to choose what type of application you wish to create, such as a Backbone application or even a Chrome extension.

To install generator-gulpify-webapp from npm, run:

```
$ npm install -g generator-gulpify-webapp
```

Finally, initiate the generator:

```
$ yo gulpify-webapp
```

### Getting To Know Yeoman

Yeoman has a heart of gold. He's a person with feelings and opinions, but he's very easy to work with. If you think he's too opinionated, he can be easily convinced.

If you'd like to get to know Yeoman better and meet some of his friends, [Grunt](http://gruntjs.com) and [Bower](http://bower.io), check out the complete [Getting Started Guide](https://github.com/yeoman/yeoman/wiki/Getting-Started).

## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License)


text:
package org.drools.guvnor.client.qa.testscenarios;

import org.drools.guvnor.client.common.ImageButton;
import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.resources.Images;
import org.drools.ide.common.client.modeldriven.testing.ExecutionTrace;
import org.drools.ide.common.client.modeldriven.testing.Fixture;
import org.drools.ide.common.client.modeldriven.testing.FixtureList;
import org.drools.ide.common.client.modeldriven.testing.Scenario;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HorizontalPanel;

public abstract class FactWidget extends HorizontalPanel {

    protected static Constants     constants = GWT.create( Constants.class );
    private static Images          images    = GWT.create( Images.class );

    protected final ScenarioWidget parent;
    protected final Scenario       scenario;
    protected final FixtureList    definitionList;

    public FactWidget(String factType,
                      FixtureList definitionList,
                      Scenario scenario,
                      ScenarioWidget parent,
                      ExecutionTrace executionTrace,
                      String headerText) {
        this.parent = parent;
        this.scenario = scenario;
        this.definitionList = definitionList;

        add( new DataInputWidget( factType,
                                  definitionList,
                                  scenario,
                                  parent,
                                  executionTrace,
                                  headerText ) );
        add( new DeleteButton( definitionList ) );
    }

    protected void onDelete() {
        if ( Window.confirm( constants.AreYouSureYouWantToRemoveThisBlockOfData() ) ) {
            for ( Fixture f : definitionList )
                scenario.removeFixture( f );
            parent.renderEditor();
        }
    }

    class DeleteButton extends ImageButton {
        public DeleteButton(final FixtureList definitionList) {
            super( images.deleteItemSmall(),
                   constants.RemoveThisBlockOfData() );

            addClickHandler( new ClickHandler() {

                public void onClick(ClickEvent event) {
                    onDelete();
                }
            } );
        }
    }
}


text:
public class TestEquals {
    public static void main(String[] args) {
        Integer m = new Integer(3);
        Integer n = new Integer(3);
        System.out.println("m==n: " + (m == n));
        System.out.println("m.equals(n): " + m.equals(n));
    }
}


text:
package UAV::Pilot::Exception;

use v5.14;
use Moose;
use namespace::autoclean;

with 'Throwable';

has 'error' => (
    is  => 'rw',
    isa => 'Str',
);

sub to_string
{
    my ($self) = @_;
    return $self->error;
}

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::NumberOutOfRangeException;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::IOException;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::FileNotFoundException;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::IOException';

has 'file' => (
    is  => 'ro',
    isa => 'Str',
);

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::CommandNotFoundException;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::IOException';

has 'cmd' => (
    is  => 'ro',
    isa => 'Str',
);

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::NavPacketException::BadHeader;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

has 'got_header' => (
    is  => 'ro',
    isa => 'Int',
);

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::VideoException;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::ArdupilotPacketException::BadHeader;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

has 'got_header' => (
    is  => 'ro',
    isa => 'Int',
);

no Moose;
__PACKAGE__->meta->make_immutable;

package UAV::Pilot::ArdupilotPacketException::BadChecksum;

use v5.14;
use Moose;
use namespace::autoclean;
extends 'UAV::Pilot::Exception';

has 'got_checksum1' => (
    is  => 'ro',
    isa => 'Int',
);
has 'got_checksum2' => (
    is  => 'ro',
    isa => 'Int',
);
has 'expected_checksum1' => (
    is  => 'ro',
    isa => 'Int',
);
has 'expected_checksum2' => (
    is  => 'ro',
    isa => 'Int',
);

no Moose;
__PACKAGE__->meta->make_immutable;

1;
__END__

=head1 NAME

  UAV::Pilot::Exceptions

=head1 DESCRIPTION

Exceptions that could be thrown by L<UAV::Pilot> modules.  All inherit from
L<UAV::Pilot::Exception>, which does the role L<Throwable>.

=head1 EXCEPTIONS

=head2 UAV::Pilot::NumberOutOfRangeException

=head2 UAV::Pilot::IOException

=head2 UAV::Pilot::CommandNotFoundException

=head2 UAV::Pilot::NavPacketException::BadHeader

=head2 UAV::Pilot::VideoException

=head2 UAV::Pilot::ArdupilotPacketException::BadHeader

=head2 UAV::Pilot::ArdupilotPacketException::BadChecksum

=cut


text:
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
    Context "Validate parameters" {
        [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')}
        [object[]]$knownParameters = 'Source','SourceSqlCredential','Destination','DestinationSqlCredential','BackupDevice','Force','EnableException'
        $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
        It "Should only contain our specific parameters" {
            (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0
        }
    }
}

if (-not $env:appveyor) {
    Describe "$commandname Integration Tests" -Tags "IntegrationTests" {
        Context "Setup" {
            BeforeAll {
                $devicename = "dbatoolsci-backupdevice"
                $backupdir = (Get-DbaDefaultPath -SqlInstance $script:instance1).Backup
                $backupfilename = "$backupdir\$devicename.bak"
                $server = Connect-DbaInstance -SqlInstance $script:instance1
                $server.Query("EXEC master.dbo.sp_addumpdevice  @devtype = N'disk', @logicalname = N'$devicename',@physicalname = N'$backupfilename'")
                $server.Query("BACKUP DATABASE master TO DISK = '$backupfilename'")
            }
            AfterAll {
                $server.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'")
                $server1 = Connect-DbaInstance -SqlInstance $script:instance2
                try {
                    $server1.Query("EXEC master.dbo.sp_dropdevice @logicalname = N'$devicename'")
                } catch {
                    # don't care
                }
            }

            $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2 -WarningVariable warn -WarningAction SilentlyContinue
            if ($warn) {
                It "warns if it has a problem moving (issue for local to local)" {
                    $warn -match "backup device to destination" | Should Be $true
                }
            } else {
                It "should report success" {
                    $results.Status | Should Be "Successful"
                }
            }

            $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2
            It "Should say skipped" {
                $results.Status -ne "Successful" | Should be $true
            }
        }
    }
}


text: <?php print_unescaped($this->inc('widget_dashboard')); ?>


text:
class CPlayerLocalData
{
public:
	// Save/restore
	DECLARE_SIMPLE_DATADESC();
	// Prediction data copying
	DECLARE_CLASS_NOBASE( CPlayerLocalData );
	DECLARE_EMBEDDED_NETWORKVAR();

	CPlayerLocalData();

	void UpdateAreaBits( CBasePlayer *pl, unsigned char chAreaPortalBits[MAX_AREA_PORTAL_STATE_BYTES] );

public:

	CNetworkArray( unsigned char, m_chAreaBits, MAX_AREA_STATE_BYTES );								// Which areas are potentially visible to the client?
	CNetworkArray( unsigned char, m_chAreaPortalBits, MAX_AREA_PORTAL_STATE_BYTES );	// Which area portals are open?

	CNetworkVar( int,	m_iHideHUD );		// bitfields containing sections of the HUD to hide
	CNetworkVar( float, m_flFOVRate );		// rate at which the FOV changes (defaults to 0)

	Vector				m_vecOverViewpoint;			// Viewpoint overriding the real player's viewpoint

	// Fully ducked
	CNetworkVar( bool, m_bDucked );
	// In process of ducking
	CNetworkVar( bool, m_bDucking );
	// In process of duck-jumping
	CNetworkVar( bool, m_bInDuckJump );
	// During ducking process, amount of time before full duc
	CNetworkVar( float, m_flDucktime );
	CNetworkVar( float, m_flDuckJumpTime );
	// Jump time, time to auto unduck (since we auto crouch jump now).
	CNetworkVar( float, m_flJumpTime );
	// Step sound side flip/flip
	int m_nStepside;;
	// Velocity at time when we hit ground
	CNetworkVar( float, m_flFallVelocity );
	// Previous button state
	int m_nOldButtons;
	class CSkyCamera *m_pOldSkyCamera;
	// Base velocity that was passed in to server physics so
	//  client can predict conveyors correctly.  Server zeroes it, so we need to store here, too.
	// auto-decaying view angle adjustment
	CNetworkQAngle( m_vecPunchAngle );
	CNetworkQAngle( m_vecPunchAngleVel );
	// Draw view model for the player
	CNetworkVar( bool, m_bDrawViewmodel );

	// Is the player wearing the HEV suit
	CNetworkVar( bool, m_bWearingSuit );
	CNetworkVar( bool, m_bPoisoned );
	CNetworkVar( float, m_flStepSize );
	CNetworkVar( bool, m_bAllowAutoMovement );

	// 3d skybox
	CNetworkVarEmbedded( sky3dparams_t, m_skybox3d );
	// world fog
	CNetworkVarEmbedded( fogplayerparams_t, m_PlayerFog );
	fogparams_t			m_fog;
	// audio environment
	CNetworkVarEmbedded( audioparams_t, m_audio );

	CNetworkVar( bool, m_bSlowMovement );
};

EXTERN_SEND_TABLE(DT_Local);

#endif // PLAYERLOCALDATA_H


text:
'use strict';

/**
 * AccessToken Model
 */
let Accesstoken, Accesstokens;
let ghostBookshelf = require('./base');
let Basetoken = require('./basetoken');

Accesstoken = Basetoken.extend({
  tableName: 'accesstokens',

  permittedAttributes: function () {
    return [
      'id', 'user_id', 'client_id', 'token', 'expires'
    ];
  }
});

Accesstokens = ghostBookshelf.Collection.extend({
  model: Accesstoken
});

module.exports = {
  Accesstoken: ghostBookshelf.model('Accesstoken', Accesstoken),
  Accesstokens: ghostBookshelf.collection('Accesstokens', Accesstokens)
};


text:
<?php

namespace AclManager\View\Helper;

use Acl\Controller\Component\AclComponent;
use Cake\Controller\Component\AuthComponent;
use Cake\Controller\ComponentRegistry;
use Cake\Core\Configure;
use Cake\ORM\TableRegistry;
use Cake\View\Helper;
use Cake\View\View;

class AclManagerHelper extends Helper
{
    /**
     * Helpers used.
     *
     * @var array
     */
    public $helpers = ['Html'];

    /**
     * Acl Instance.
     *
     * @var object
     */
    public $Acl;
    public $Auth;

    /**
     * AclManagerHelper constructor
     *
     * @param \Cake\View\View $View
     * @param array $config
     */
    public function __construct(View $View, $config = [])
    {
        parent::__construct($View, $config);

        $collection = new ComponentRegistry();
        $this->Acl = new AclComponent($collection, Configure::read('Acl'));
    }

    /**
     *  Check if the ARO has access to the aco
     *  Set as private as knowing the ARO is almost useless
     *
     * @param Model|array|string $aro The Aro of the object you want to check
     * @param Model|array|string $aco The path of the Aco like App/Blog/add
     * @param string $action CRUD Actions to check
     * @return bool
     */
    private function _check($aro, $aco, $action = '*')
    {
        if (empty($aro) || empty($aco)) {
            return false;
        }

        return $this->Acl->check($aro, $aco, $action);
    }

    /**
     *  Check if the User ID has access to the aco
     *
     * @param string $aco The path of the Aco like App/Blog/add
     * @param int|null $uid The ID of the User you want to check
     * @param string $action CRUD Actions to check
     * @return bool
     */
    public function checkUser($aco, $uid = null, $action = '*')
    {
        $uid = $this->getView()->getRequest()->getSession()->read('Auth.User.id');

        if (empty($uid)) {
            return false;
        }

        return $this->_check(['model' => 'Users', 'foreign_key' => $uid], $aco, $action);
    }

    /**
     *  Check if the Group ID has access to the aco
     *
     * @param string $aco The path of the Aco like App/Blog/add
     * @param int|null $gid The ID of the User you want to check
     * @param string $action CRUD Actions to check
     * @return bool
     */
    public function checkGroup($aco, $gid = null, $action = '*')
    {
        if (empty($gid)) {
            return false;
        }

        $gid = $this->getView()->getRequest()->getSession()->read('Auth.User.group_id');

        return $this->_check(['model' => 'Groups', 'foreign_key' => $gid], $aco, $action);
    }

    /**
     * @param int $aro
     * @param int $id
     * @return \Cake\Datasource\EntityInterface|mixed
     */
    public function getName($aro, $id)
    {
        return $this->__getName($aro, $id);
    }

    /**
     * Return value from permissions input
     *
     * @param string|null $value
     *
     * @return bool
     */
    public function value(string $value = null)
    {
        if ($value == null) {
            return false;
        }

        $o = explode('.', $value);
        $data = $this->getView()->getRequest()->getData();

        return $data[$o[0]][$o[1]][$o[2]];
    }

    /**
     * Find ARO/ACO id
     *
     * @param string $aro
     * @param int $id
     *
     * @return \Cake\Datasource\EntityInterface
     */
    protected function __getName($aro, $id)
    {
        $model = TableRegistry::getTableLocator()->get($aro);

        return $model->get($id, ['recursive' => -1]);
    }
}


text:
layout: post
title: Growing OO Software, Guided by Tests - Object-Oriented Style
comments: true
---

So far this book talked a lot about how to get started with the development process and how to keep going using TDD. Now it starts to focus on OO design, an important thing when you start to refactor your code, or even when you start creating mock objects, code that is easy to maintain is more valuable than code easy to write, it means that implementing a feature in the most direct way can damage the maintainability of the system. This chapter focus on how to achieve a good software design even when its become tricky.

##Designing for Maintainability

With TDD we grow our systems slice by slice, as the code scales up, the only way we can continue to understand and maintain it is refactoring the code and structuring the functionality into objects, packages and etc. There is two principal heuristics to guide this approach:

###Separation of concerns

When we have to change the behavior of a system, we want to change as little code as possible. If all the relevant changes are in one area of code, we don't have to hunt around the system to get the job done, to achieve this we gather together code that will change for the same reason.

###Higher levels of abstraction

The best way for humans to deal with complexity is avoid it by working at higher levels of abstraction, that's why most people order food from a menu in terms of dishes, rather than detail the recipes used to create them.

Using this you can structure your application towards something like Cockburn's "ports and adapters" architecture, in which the code for the business domain is isolated from its dependencies on technical infrastructure, such as databases and user interfaces.

##No And's, Or's, or But's

Every object should have a single, clearly defined responsibility; this is the "single responsability" principle, when implementing something this principle helps us decide whether to extend an existing object or create a new one. The heuristic here is that we should be able to describe what an object does without using any "and"s or "or"s, if find ourselves using this conjunctions, this object probably needs to be broken up into other objects.

##Composite Simpler Than the Sum of Its Parts

All objects in a system are composed of other objects, except for the primitive types built into the language(in some languages even the "primitive" types are objects). When composing objects into a new type, we want the new type to exhibit simpler behavior than all of its component parts considered together. The composite object's API must hide the existence of its component parts and the interactions between them, and expose a simpler abstraction to its peers, so, the API of a composite object should not be more complicated than any of its components.


text:
<?php

namespace Tonada\ToolsBundle\Lib\Content;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Example\ItemBundle\Entity\SingleContent;

class TonadaPages implements \ArrayAccess {

    public $pages;
    private $container;
    private $em;
    private $repository;
    private $inflector;

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function __construct (ContainerInterface $container, $class) {
        $this->container = $container;
        $this->em = $this->container->get('doctrine')->getManager();
        $this->repository = $this->em->getRepository($class);
        $this->loadPages();
    }

    private function loadPages () {
        $pages = $this->repository->findAll();
        if (empty($this->pages)) {
            foreach ($pages as $page) {
                $this->pages[$page->getSlug()] = $page;
            }
        }
    }

    public function offsetExists ($offset) {
        return true;
    }

    public function offsetGet ($offset) {
        if (!isset($this->pages[$offset])) {
            $page = $this->repository->findOneBy(array ('slug' => $offset));
            if (!$page) {
                $page = new SingleContent();
                $page->setTitle($offset);
                $page->setBody('Por favor editame en el panel administrativo');
                $page->setSlug($offset);
                $this->em->persist($page);
                $this->em->flush();
            }
            $this->pages[$offset] = $page;
        }
        return $this->pages[$offset];
    }

    public function offsetSet ($offset, $value) {

    }

    public function offsetUnset ($offset) {
        unset($this->pages[$offset]);
    }

}

?>