text:
module Pay
  module Stripe
    module Webhooks
      class CustomerDeleted
        def call(event)
          object = event.data.object
          billable = Pay.find_billable(processor: :stripe, processor_id: object.id)

          # Couldn't find user, we can skip
          return unless billable.present?

          billable.update(
            processor_id: nil,
            trial_ends_at: nil,
            card_type: nil,
            card_last4: nil,
            card_exp_month: nil,
            card_exp_year: nil
          )

          billable.subscriptions.update_all(
            trial_ends_at: nil,
            ends_at: Time.zone.now
          )
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.jbpm.designer.repository;

public class AssetNotFoundException extends Exception {
}


text:
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
from auth.views import create_user, authenticate_user, refresh_token, delete_token
from rest_framework.test import force_authenticate
from rest_framework.authtoken.models import Token
import json

# Test requests
class AuthenticationRequests(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_register(self):
        # Create an instance of a Post request.
        request = self.factory.post('/api/v1/auth/register', data=json.dumps({'username': 'name', 'password': 'password'}),
                                    content_type='application/json')

        # Test response
        response = create_user(request)
        self.assertEqual(response.data['status'], 'success')
        # See if user is added
        self.assertEqual(len(User.objects.all()), 1)

    def test_login(self):
        User.objects.create_user(username='name', password='password')
        # Create an instance of a Post request.
        request = self.factory.post('/api/v1/auth/login',
                                    data=json.dumps({'username': 'name', 'password': 'password'}),
                                    content_type='application/json')

        # Test response
        response = authenticate_user(request)
        self.assertEqual(response.data['status'], 'success')
        self.assertNotEqual(len(response.data['token']), 0)

    def test_getting_token(self):
        user = User.objects.create_user(username='name', password='password')
        # Create an instance of a Post request.
        request = self.factory.get('/api/v1/auth/token')

        # create a user
        force_authenticate(request, user=user)

        # Test response
        response = refresh_token(request)
        self.assertEqual(response.data['status'], 'success')
        self.assertNotEqual(len(response.data['token']), 0)

    def test_delete_token(self):
        user = User.objects.create_user(username='name', password='password')
        Token.objects.create(user=user)
        # Create an instance of a Post request.
        request = self.factory.delete('/api/v1/auth/logout')

        # create a user
        force_authenticate(request, user=user)

        # Test response
        response = delete_token(request)
        self.assertEqual(response.data['status'], 'success')
        # Should be zero token
        self.assertEqual(len(Token.objects.all()),0)


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<orgao xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <url>http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/322</url>
    <nome>Conselho Administrativo de Defesa Econômica (CADE)</nome>
    <conteudo><![CDATA[Autarquia federal vinculada ao [Ministério da Justiça] com a missão de zelar pela livre concorrência no mercado, sendo responsável por investigar e decidir, em última instância, sobre a matéria concorrencial, bem como fomentar e disseminar a cultura da livre concorrência.

Dentre os serviços ofertados ao público estão a consulta a processos em tramitação e julgados no âmbito do Cade; autenticação de documentos; e procedimentos para notificação e julgamento de atos de concentração.

[Ministério da Justiça]:/orgao/ministerio-da-justica-mj]]></conteudo>
    <contato><![CDATA[[Site Oficial](http://www.cade.gov.br/)
[Ouvidoria](http://www.ouvidorias.gov.br/cidadao/lista-de-ouvidorias/adm_direta/ministerio-da-justica-mj)]]></contato>
</orgao>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>wlan-decoder-java: fr.bmartel.protocol.wlan.frame.control.ContentionFreeReceiveAckFrame Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

wlan-decoder-java
    1.0

Main Page

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Namespaces Functions Variables Pages

fr

bmartel

protocol

wlan

frame

control

ContentionFreeReceiveAckFrame

Public Member Functions |
List of all members

fr.bmartel.protocol.wlan.frame.control.ContentionFreeReceiveAckFrame Class Reference

Inheritance diagram for fr.bmartel.protocol.wlan.frame.control.ContentionFreeReceiveAckFrame:

<map name="fr_8bmartel_8protocol_8wlan_8frame_8control_8_contention_free_receive_ack_frame_inherit__map" id="fr_8bmartel_8protocol_8wlan_8frame_8control_8_contention_free_receive_ack_frame_inherit__map">
<area shape="rect" id="node2" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1_i_wlan_frame.html" title="fr.bmartel.protocol.wlan.frame.\lIWlanFrame" alt="" coords="43,5,240,51"/><area shape="rect" id="node4" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1inter_1_1_i_wlan_control_frame.html" title="fr.bmartel.protocol.wlan.inter.\lIWlanControlFrame" alt="" coords="47,74,236,121"/><area shape="rect" id="node6" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1control_1_1inter_1_1_i_contention_free_receive_ack_frame.html" title="fr.bmartel.protocol.wlan.frame.control.inter.\lIContentionFreeReceiveAckFrame" alt="" coords="7,143,276,190"/></map>
[legend]

Collaboration diagram for fr.bmartel.protocol.wlan.frame.control.ContentionFreeReceiveAckFrame:

<map name="fr_8bmartel_8protocol_8wlan_8frame_8control_8_contention_free_receive_ack_frame_coll__map" id="fr_8bmartel_8protocol_8wlan_8frame_8control_8_contention_free_receive_ack_frame_coll__map">
<area shape="rect" id="node2" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1_i_wlan_frame.html" title="fr.bmartel.protocol.wlan.frame.\lIWlanFrame" alt="" coords="43,5,240,51"/><area shape="rect" id="node4" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1inter_1_1_i_wlan_control_frame.html" title="fr.bmartel.protocol.wlan.inter.\lIWlanControlFrame" alt="" coords="47,74,236,121"/><area shape="rect" id="node6" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1control_1_1inter_1_1_i_contention_free_receive_ack_frame.html" title="fr.bmartel.protocol.wlan.frame.control.inter.\lIContentionFreeReceiveAckFrame" alt="" coords="7,143,276,190"/></map>
[legend]

Public Member Functions

 	ContentionFreeReceiveAckFrame (byte[] frame)

byte[] 	getBssid ()

byte[] 	getReceiverAddr ()

byte[] 	getDurationId ()

Detailed Description

Control Frame : Contention free and Receive ACK

duration id : 2 Bytes

receiver address : 6 Bytes

BSSID address : 6 Bytes

Author

Bertrand Martel

Constructor & Destructor Documentation

          fr.bmartel.protocol.wlan.frame.control.ContentionFreeReceiveAckFrame.ContentionFreeReceiveAckFrame
          (
          byte[]
          frame)

Build a request to send control frame contention free and receive ack

Parameters

frame	wlan frame with control frame omitted

The documentation for this class was generated from the following file:

/home/abathur/Bureau/wlandecoder/wlandecoder/src/fr/bmartel/protocol/wlan/frame/control/ContentionFreeReceiveAckFrame.java

<address class="footer">
Generated on Tue May 5 2015 23:30:27 for wlan-decoder-java by

 1.8.4
</address>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src vscode-resource:; script-src 'unsafe-inline' vscode-resource:; style-src 'unsafe-inline' vscode-resource:;"
    />
    <link
      rel="stylesheet"
      href="@PWD/ui/shared/vendor/bootstrap/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="@PWD/ui/shared/vendor/fontawesome/css/fontawesome.min.css"
    />
    <link
      rel="stylesheet"
      href="@PWD/ui/shared/vendor/fontawesome/css/solid.min.css"
    />

    <link rel="stylesheet" href="@PWD/ui/shared/styles.css" />

      <page-header></page-header>

        Select Your Existing Gist

              Saved Gist ID!

            The Gist ID has been saved to the configuration. You may now close
            this tab.

            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Back
            </button>
            <button
              type="button"
              class="btn btn-primary"
              onclick="vscode.postMessage({close: true});"
            >
              Close Tab
            </button>


text:
package std.quartz;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import std.util.DataConverter;
import std.util.DataSourceManager;

public class ArticleKeywordJob implements Job {

	private static Logger logger = Logger.getLogger(ArticleKeywordJob.class);

	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		Connection connection = DataSourceManager.open(DataSourceManager.BY_JDBC_DEFAULT);
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			// 截断article_keyword表
			preparedStatement = connection.prepareStatement("TRUNCATE article_keyword");
			preparedStatement.execute();
			// 收集关键词
			Map<String, Integer> akFinalMap = new HashMap<String, Integer>();// 最终关键词集合
			Map<String, Set<Integer>> akVsIdMap = new HashMap<String, Set<Integer>>();// 关键词关联文章id集合
			preparedStatement = connection.prepareStatement("select the_id, article_keyword from article_info where visibility = 0");
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				String articleKeyword = resultSet.getString("article_keyword");
				Integer theId = resultSet.getInt("the_id");
				if (articleKeyword != null && !"".equals(articleKeyword)) {
					String[] akArr = articleKeyword.split("\r\n");// 以换行符分隔
					if (akArr != null && akArr.length > 0) {
						for (int i = 0, j = akArr.length; i < j; i++) {
							String key = akArr[i];
							akFinalMap.put(key, akFinalMap.containsKey(key) ? akFinalMap.get(key) + 1 : 1);
							if (!akVsIdMap.containsKey(key)) {
								akVsIdMap.put(key, new HashSet<Integer>());
							}
							akVsIdMap.get(key).add(theId);
						}
					}
				}
			}
			if (akFinalMap != null && akFinalMap.size() > 0) {
				for (Entry<String, Integer> keyword : akFinalMap.entrySet()) {
					preparedStatement = connection.prepareStatement("INSERT INTO article_keyword (the_value, the_count, article_info_ids) VALUES ('" + DataConverter.encode_base64(keyword.getKey()) + "', '" + keyword.getValue() + "', '" + akVsIdMap.get(keyword.getKey()).toString().replace(" ", "").replace("[", "").replace("]", "") + "');");
					preparedStatement.executeUpdate();
				}
			}
		} catch (SQLException e) {
			logger.error("处理文章关键词", e);
		} finally {
			DataSourceManager.close(connection, preparedStatement, resultSet);
		}

	}

}


text:
package fi.csc.microarray.cluster;

import java.io.File;

import fi.csc.microarray.util.Files;
import fi.csc.microarray.util.LookaheadStringReader;

/**
 * Parser for parenthesis formatted trees. Parses String and generates
 * a corresponding tree of ClusterBranchNodes and ClusterLeafNodes.
 *
 * @author Aleksi Kallio
 *
 */
public class ClusterParser {

	private static final String SEPARATE_PARTS = ":";
	private static final String CLOSE_TREE = ";";
	private static final String SEPARATE_BRANCHES = ",";
	private static final String CLOSE_BRANCH = ")";
	private static final String OPEN_BRANCH = "(";

	private LookaheadStringReader reader;

	public ClusterParser(String tree) {
		// remove whitespace first
		this.reader = new LookaheadStringReader(tree.replace("\n", "").replace(" ", ""));
	}

	public ClusterBranchNode getTree() throws TreeParseException {
		if (reader == null) {
			throw new IllegalStateException("Tree already parsed, cannot reparse");
		}

		// parse root branch
		//   (it is different (no length), so it is parsed here
		//   instead of using parseBranch)
		readAndCheck(OPEN_BRANCH);
		ClusterNode leftBranch = parseBranchOrLeaf();
		readAndCheck(SEPARATE_BRANCHES);
		ClusterNode rightBranch = parseBranchOrLeaf();
		readAndCheck(CLOSE_BRANCH);
		readAndCheck(CLOSE_TREE);

		// disable parsing
		reader = null;

		// parse AST
		ClusterBranchNode rootBranch = new ClusterBranchNode();
		rootBranch.setLeftBranch(leftBranch);
		rootBranch.setRightBranch(rightBranch);
		return rootBranch;
	}

	private ClusterBranchNode parseBranch() throws TreeParseException {

		// parse
		readAndCheck(OPEN_BRANCH);
		ClusterNode leftBranch = parseBranchOrLeaf();
		readAndCheck(SEPARATE_BRANCHES);
		ClusterNode rightBranch = parseBranchOrLeaf();
		readAndCheck(CLOSE_BRANCH);
		String length = parseLength();

		// construct AST
		ClusterBranchNode branch = new ClusterBranchNode();
		branch.setLeftBranch(leftBranch);
		branch.setRightBranch(rightBranch);
		branch.setLength(length);
		return branch;
	}

	private ClusterNode parseBranchOrLeaf() throws TreeParseException {
		ClusterNode node;
		if (reader.lookahead().equals(OPEN_BRANCH)) {
			node = parseBranch();
		} else {
			node = parseLeaf();
		}
		return node;
	}

	private ClusterLeafNode parseLeaf() throws TreeParseException {

		// parse
		String gene = parseGene();
		String length = parseLength();

		// construct AST
		ClusterLeafNode leaf = new ClusterLeafNode();
		leaf.setGene(gene);
		leaf.setLength(length);
		return leaf;
	}

	private String parseGene() {
		String gene = reader.readTo(SEPARATE_PARTS);
		return gene;
	}

	private String parseLength() throws TreeParseException {
		readAndCheck(SEPARATE_PARTS);
		String length = reader.readTo(SEPARATE_BRANCHES, CLOSE_BRANCH);
		return length;

	}

	private void readAndCheck(String s) throws TreeParseException {
		try {
			String r = reader.read();
			if (!r.equals(s)) {
				throw new TreeParseException("expected \"" + s + "\" but found \"" + r + "\"", reader);
			}
		} catch (StringIndexOutOfBoundsException se) {
			throw new TreeParseException("unexpected end of string", reader);
		}
	}

	public static void main(String[] args) throws Exception  {
		String tree = Files.fileToString(new File("test.tre")); // for testing parsing issues
		new ClusterParser(tree).getTree();
	}
}


text:
<component name="libraryTable">
  <library name="android-observablescrollview-1.6.0-sources">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/android-observablescrollview-1.6.0-sources.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
- Add command-line interface (#73)
- Improve test coverage

### Changed
- Update dependencies

## 2.8.11 - 2020-03-15
### Changed
- Remove coverage from dev dependencies
- Update .travis.yml

## 2.8.9 - 2020-03-14
### Changed
- Cache '%PROGRAMDATA%\chocolatey\bin'

## 2.8.8 - 2020-03-14
### Changed
- Update pytest

## 2.8.7 - 2020-03-14
### Added
- Add type hinting
- Cache pypoetry on CI

## 2.8.6 - 2020-03-13
### Fixed
- Fix #44

### Changed
- Refactor tests
- Update formatters and linters

## 2.8.5 - 2020-03-10
### Changed
- Migrate from pipenv to poetry

## 2.8.4 - 2020-03-08
### Fixed
- Missing right should raise an exception

## 2.8.3 - 2020-03-08
### Fixed
- Discontinues parsing when \right is reached (#63)

## 2.8.2 - 2020-03-06
### Fixed
- IndexError: list index out of range (#61)

## 2.8.1 - 2020-03-06
### Fixed
- Add support for \math* (#60)

### Added
- Add .gitignore

### Changed
- Update copyright year
- Update dev packages

## 2.8.0 - 2019-11-23
### Added
- OSX tests
- pycodestyle linter

### Changed
- Move package metadata to setup.cfg

### Fixed
- Group items in array rows correctly (#55)

### Removed
- Drop Python 2 support

## 2.7.1 - 2019-08-23
- Add xmlns in <math> (#56)

## 2.7.0 - 2019-06-05
### Added
- Support Math alphabets (#51)

### Fixed
- Correctly show \bar (#52)

## 2.6.7 - 2019-04-03
### Removed
- Drop Python 3.4 support

### Changed
- Update CI to use pipenv

## 2.6.6 - 2019-03-23
### Fixed
- Incorrect conversion when parentheses next to exponent (#44)
- Escaping of "<", ">" kept in XML (#46)

## 2.6.5 - 2019-03-23
### Fixed
- Escaping of "<", ">" kept in XML (#46)

## 2.6.4 - 2019-02-10
### Fixed
- IndexError on r'\sqrt { ( - 25 ) ^ { 2 } } = \pm 25' (#42)

## 2.6.3 - 2019-01-13
### Changed
- Update copyright

## 2.6.2 - 2018-10-17
### Added
- More shields (#37)

## 2.6.1 - 2018-10-13
### Added
- Support universal wheel (#35)

## 2.6.0 - 2018-10-13
### Fixed
- Drop TexSoup (#33)

### Changed
- Support Python 2.7

## 2.5.2 - 2018-10-10
### Added
- Deploy to PyPI from Travis CI (#25)

## 2.5.1 - 2018-10-10
### Changed
- Show README badges in table

## 2.5.0 - 2018-10-09
### Added
- AppVeyor Integration (#26)
- Implement Caching in Travis-CI and AppVeyor (#28)

## 2.4.0 - 2018-10-07
### Added
- Codecov Integration (#22)

## 2.3.0 - 2018-10-07
### Added
- Travis CI Integration (#18)

## 2.2.0 - 2018-10-04
### Changed
- Use TexSoup parser

### Removed
- Drop Python 2.7.x support

## 2.1.1.2 - 2018-10-02
### Fixed
- README not rendering rendering in PyPI (#11)

## 2.1.0 - 2018-09-29
### Added
- Support \over (#8)

## 2.0.3 - 2018-09-29
### Fixed
- Unescape texts (#5)

## 2.0.2 - 2017-09-02
### Fixed
- latex2mathml folder not included in package.

## 2.0.1 - 2017-09-02
### Changed
- LaTeX inputs and MathML outputs are shown in table in README.
- unimathsymbols.txt will be read once.
- Element class remove in exchange of xml.etree.xElementTree.

### Added
- File headers are included to source.

## 1.1.1 - 2016-07-21
### Fixed
- Python 3 compatibility (importing, xrange, iterator.next)

## 1.0.10 - 2016-02-14
### Added
- Support for arrays including arrays with vertical bars and horizontal lines (borders not supported)

## 1.0.9 - 2016-01-16
### Removed
- Flask viewer

### Changed
- Updated README.md

## 1.0.8 - 2016-01-10
### Added
- Viewer - Support for other browsers using CSS Fallback for MathML (https://github.com/fred-wang/mathml.css)
- Conversion of latex commands within matrix environments

### Fixed
- Incorrect aggregation of latex commands within matrix environment
- Removed newline and whitespaces when prettyprinting elements with text but without children

## 1.0.7 - 2016-01-09
### Added
- Pretty feature for Element class

### Changed
- Refactored codes
- Updated README file

## 1.0.6 - 2016-01-08
### Added
- Simple viewer using bootstrap and openshift

## 1.0.5 - 2016-01-06
### Fixed
- VERSION file not added to MANIFEST

## 1.0.4 - 2016-01-06
### Added
- additional matrices (pmatrix, bmatrix, bmatrix*, Bmatrix, Bmatrix*, vmatrix, vmatrix*, Vmatrix, Vmatrix*)

### Changed
- changed test asserts in command_test.py and converter_test.py from string format to Element object

### Fixed
- negative sign (-) becomes a separate element inside a matrix environment

## 1.0.3 - 2016-01-04
### Added
- matrix
    - \begin{matrix}..\end{matrix}
    - \matrix{...} -> taken from MathJax

## 1.0.2 - 2016-01-03
### Added
- added support for binomial
- added support for \left and \right commands
- added support for space commands \, \: \; \quad \qquad \<blank>
- added support for overline and underline

### Fixed
- aggregator bug on superscripts and subscipts

## 1.0.1 - 2016-01-02
### Added
- aggregator for grouping latex code with curly braces({})
- simple mathml viewer using flask
- parser for latex (unicode) symbols from http://milde.users.sourceforge.net/LUCR/Math/
- support for subscript and superscript
- support for fractions (\frac only)
- support for radicals

### Changed
- updated Element class, added attributes

## 1.0.0 - 2015-12-31
### Added
- latex string tokenizer
- Element class for xml elements
- simple converter implementation


text:
<?php

class AuthorizationPlugin extends Zend_Controller_Plugin_Abstract
{
	private $config;

	/**
	 * When build, apply the following config elements.
	 *
	 * @param unknown_type $config
	 */
	public function __construct($config)
	{
		$this->config = $config;
	}

	/**
	 * Called before Zend_Controller_Front begins evaluating the
	 * request against its routes.
	 *
	 * @return void
	 */
	public function routeStartup() {}

	/**
	 * Called after Zend_Controller_Front exits from the router.
	 *
	 * This callback allows for proxy or filter behavior.  The
	 * $action must be returned for the Zend_Controller_Dispatcher_Token to enter the
	 * dispatch loop.  To abort before the dispatch loop is
	 * entered, return FALSE.
	 *
	 * @param  Zend_Controller_Dispatcher_Token|boolean $action
	 * @return Zend_Controller_Dispatcher_Token|boolean
	 */
	public function routeShutdown($action) {return $action;}

	/**
	 * Called before Zend_Controller_Front enters its dispatch loop.
	 * During the dispatch loop.
	 *
	 * This callback allows for proxy or filter behavior.  The
	 * $action must be returned for the Zend_Controller_Dispatcher_Token to enter the
	 * dispatch loop.  To abort before the dispatch loop is
	 * entered, return FALSE.
	 *
	 * @param  Zend_Controller_Dispatcher_Token|boolean $action
	 * @return Zend_Controller_Dispatcher_Token|boolean
	 */
	public function dispatchLoopStartup($action) {return $action;}

	/**
	 * Called before an action is dispatched by Zend_Controller_Dispatcher.
	 *
	 * This callback allows for proxy or filter behavior.  The
	 * $action must be returned for the Zend_Controller_Dispatcher_Token to be dispatched.
	 * To abort the dispatch, return FALSE.
	 *
	 * @param  Zend_Controller_Request_Http $action
	 * @return Zend_Controller_Request_Http
	 */
	public function preDispatch($action)
	{

		/*@var $action Zend_Controller_Request_Http */
		$controllerName = strtolower($action->getControllerName());
		$actionName = strtolower($action->getActionName());
		$moduleName = strtolower($action->getModuleName());

		// Check for authorization.
		$app = NovemberApplication::getInstance();
		$currentUser = $app->getUser();

		if ($currentUser->getRole() == User::ROLE_LOCKED) {
		    $action->setControllerName(ifset($this->config, 'login_controller', 'user'));
		    $action->setActionName(ifset($this->config, 'login_action', 'login'));
			return $action;
		}

		// Get the restrictions for the current request (if any)
		$conf = ifset($this->config, $moduleName);

		$roles = '';

		if (is_string($conf)) {
		    $roles = $conf;
		} else if (is_array($conf)) {
		    // check for a default
		    $roles = ifset($conf, 'default_roles', '');
		    // If there's something in the controllername entry...
		    $controllerConf = ifset($conf, $controllerName, $roles);
		    if (is_array($controllerConf)) {
		        $roles = ifset($controllerConf, $actionName, $roles);
		    } else {
		        $roles = $controllerConf;
		    }
		}

		// Are there required roles to authenticate?
		$loginRequired = false;

		za()->log(__CLASS__.':'.__LINE__." - Authorizing ".$currentUser->getUsername()." for roles $roles");
		if ($roles != '') {
		    $loginRequired = true;
            $roles = explode(',', $roles);
            // If the user has any of the roles, let them in
            foreach ($roles as $role) {
                if ($currentUser->hasRole($role)) {
                    return $action;
                }
            }
	    }

	    // If we've got this far, then we should ask the DB if the current user has
        // access to the current module and controller
        // We're expecting user_access =>
        // user_role
        // OR array (controller => user_role)
        $userAccess = ifset($conf, 'user_access');

        if ($userAccess != null) {
            $loginRequired = true;
            // if it's a string, just get the access for the module
            $accessService = za()->getService('AccessService');

            // See if they have access to this module
            $access = $accessService->getAccessList($currentUser->getUsername(), $moduleName);
            if (count($access)) {
                // okay, they have access, so we're all cool
                return $action;
            }
        }

	    if ($loginRequired) {
            $url = build_url($controllerName, $actionName, $action->getUserParams(), false, $moduleName);
            $_SESSION[NovemberController::RETURN_URL] = $url;
            // $action->setModuleName(ifset($this->config, 'login_module', 'default'));
            $action->setControllerName($this->config['login_controller']);
			$action->setActionName($this->config['login_action']);
	    }

		return $action;
	}

	/**
	 * Called after an action is dispatched by Zend_Controller_Dispatcher.
	 *
	 * This callback allows for proxy or filter behavior.  The
	 * $action must be returned, otherwise the next action
	 * will not be dispatched.  To exit the dispatch loop without
	 * dispatching the action, return FALSE.
	 *
	 * @param  Zend_Controller_Dispatcher_Token|boolean $action
	 * @return Zend_Controller_Dispatcher_Token|boolean
	 */
	public function postDispatch($action) {return $action;}

	/**
	 * Called before Zend_Controller_Front exists its dispatch loop.
	 *
	 * @return void
	 */
	public function dispatchLoopShutdown() {}
}
?>


text:
<?php

// Enrico Simonetti
// 2016-12-22

namespace Sugarcrm\Sugarcrm\custom\Console\Command\SystemData;

use Sugarcrm\Sugarcrm\Console\CommandRegistry\Mode\InstanceModeInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Sugarcrm\Sugarcrm\custom\systemdata\SystemDataCli;

class SystemDataUsersImport extends Command implements InstanceModeInterface
{
    protected function data()
    {
        return new SystemDataCli();
    }

    protected function configure()
    {
        $this
            ->setName('systemdata:import:users')
            ->setDescription('Import Users from JSON data file')
            ->addArgument(
                'path',
                InputArgument::REQUIRED,
                'Source path for the JSON data file'
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path');
        if ($this->data()->checkJsonFile($path)) {
            $data = $this->data()->getData($path);
            $res = $this->data()->saveToObject('users', $data);
            if (!empty($res)) {
                foreach ($res as $message) {
                    $output->writeln($message);
                }
            }
        } else {
            $output->writeln(
                sprintf(
                    translate('LBL_SYSTEMDATA_MSG_ERROR_PATH'),
                    $path
                )
            );
        }
    }
}


text:
from django.db import models
from django_extensions.db.models import TimeStampedModel

class Interest(TimeStampedModel):

    email = models.EmailField(max_length=100)

    def __unicode__(self):
        return self.email


text:
<!DOCTYPE html>

SDFset


text:
/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/property.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#if defined(MAGICKCORE_FPX_DELEGATE)
#if !defined(vms) && !defined(macintosh) && !defined(MAGICKCORE_WINDOWS_SUPPORT)
#include <fpxlib.h>
#else
#include "Fpxlib.h"
#endif
#endif

#if defined(MAGICKCORE_FPX_DELEGATE)
/*
  Forward declarations.
*/
static MagickBooleanType
  WriteFPXImage(const ImageInfo *,Image *);
#endif

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I s F P X                                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  IsFPX() returns MagickTrue if the image format type, identified by the
%  magick string, is FPX.
%
%  The format of the IsFPX method is:
%
%      MagickBooleanType IsFPX(const unsigned char *magick,const size_t length)
%
%  A description of each parameter follows:
%
%    o magick: compare image format pattern against these bytes.
%
%    o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsFPX(const unsigned char *magick,const size_t length)
{
  if (length < 4)
    return(MagickFalse);
  if (memcmp(magick,"\320\317\021\340",4) == 0)
    return(MagickTrue);
  return(MagickFalse);
}

#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d F P X I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadFPXImage() reads a FlashPix image file and returns it.  It
%  allocates the memory necessary for the new Image structure and returns a
%  pointer to the new image.  This method was contributed by BillR@corbis.com.
%
%  The format of the ReadFPXImage method is:
%
%      Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  FPXColorspace
    colorspace;

  FPXImageComponentDesc
    *alpha_component,
    *blue_component,
    *green_component,
    *red_component;

  FPXImageDesc
    fpx_info;

  FPXImageHandle
    *flashpix;

  FPXStatus
    fpx_status;

  FPXSummaryInformation
    summary_info;

  Image
    *image;

  IndexPacket
    index;

  MagickBooleanType
    status;

  register IndexPacket
    *indexes;

  register ssize_t
    i,
    x;

  register PixelPacket
    *q;

  register unsigned char
    *a,
    *b,
    *g,
    *r;

  size_t
    memory_limit;

  ssize_t
    y;

  unsigned char
    *pixels;

  unsigned int
    height,
    tile_width,
    tile_height,
    width;

  size_t
    scene;

  /*
    Open image.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  (void) CloseBlob(image);
  /*
    Initialize FPX toolkit.
  */
  fpx_status=FPX_InitSystem();
  if (fpx_status != FPX_OK)
    ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
  memory_limit=20000000;
  fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
  if (fpx_status != FPX_OK)
    {
      FPX_ClearSystem();
      ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
    }
  tile_width=64;
  tile_height=64;
  flashpix=(FPXImageHandle *) NULL;
  {
#if defined(macintosh)
    FSSpec
      fsspec;

    FilenameToFSSpec(image->filename,&fsspec);
    fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
    fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
      &width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
  }
  if (fpx_status == FPX_LOW_MEMORY_ERROR)
    {
      FPX_ClearSystem();
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    }
  if (fpx_status != FPX_OK)
    {
      FPX_ClearSystem();
      ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
        image->filename);
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  if (colorspace.numberOfComponents == 0)
    {
      FPX_ClearSystem();
      ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
    }
  if (image_info->view == (char *) NULL)
    {
      float
        aspect_ratio;

      /*
        Get the aspect ratio.
      */
      aspect_ratio=(float) width/height;
      fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
      if (fpx_status != FPX_OK)
        ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
      if (width != (size_t) floor((aspect_ratio*height)+0.5))
        Swap(width,height);
    }
  fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
  if (fpx_status != FPX_OK)
    {
      FPX_ClearSystem();
      ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
    }
  if (summary_info.title_valid)
    if ((summary_info.title.length != 0) &&
        (summary_info.title.ptr != (unsigned char *) NULL))
      {
        char
          *label;

        /*
          Note image label.
        */
        label=(char *) NULL;
        if (~summary_info.title.length >= (MaxTextExtent-1))
          label=(char *) AcquireQuantumMemory(summary_info.title.length+
            MaxTextExtent,sizeof(*label));
        if (label == (char *) NULL)
          {
            FPX_ClearSystem();
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          }
        (void) CopyMagickString(label,(char *) summary_info.title.ptr,
          summary_info.title.length+1);
        (void) SetImageProperty(image,"label",label);
        label=DestroyString(label);
      }
  if (summary_info.comments_valid)
    if ((summary_info.comments.length != 0) &&
        (summary_info.comments.ptr != (unsigned char *) NULL))
      {
        char
          *comments;

        /*
          Note image comment.
        */
        comments=(char *) NULL;
        if (~summary_info.comments.length >= (MaxTextExtent-1))
          comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
            MaxTextExtent,sizeof(*comments));
        if (comments == (char *) NULL)
          {
            FPX_ClearSystem();
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          }
        (void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
          summary_info.comments.length+1);
        (void) SetImageProperty(image,"comment",comments);
        comments=DestroyString(comments);
      }
  /*
    Determine resolution by scene specification.
  */
  for (i=1; ; i++)
    if (((width >> i) < tile_width) || ((height >> i) < tile_height))
      break;
  scene=i;
  if (image_info->number_scenes != 0)
    while (scene > image_info->scene)
    {
      width>>=1;
      height>>=1;
      scene--;
    }
  if (image_info->size != (char *) NULL)
    while ((width > image->columns) || (height > image->rows))
    {
      width>>=1;
      height>>=1;
      scene--;
    }
  image->depth=8;
  image->columns=width;
  image->rows=height;
  if ((colorspace.numberOfComponents % 2) == 0)
    image->matte=MagickTrue;
  if (colorspace.numberOfComponents == 1)
    {
      /*
        Create linear colormap.
      */
      if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
        {
          FPX_ClearSystem();
          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
        }
    }
  if (image_info->ping != MagickFalse)
    {
      (void) FPX_CloseImage(flashpix);
      FPX_ClearSystem();
      return(GetFirstImageInList(image));
    }
  /*
    Allocate memory for the image and pixel buffer.
  */
  pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
    1UL)*colorspace.numberOfComponents*sizeof(*pixels));
  if (pixels == (unsigned char *) NULL)
    {
      FPX_ClearSystem();
      (void) FPX_CloseImage(flashpix);
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    }
  /*
    Initialize FlashPix image description.
  */
  fpx_info.numberOfComponents=colorspace.numberOfComponents;
  for (i=0; i < 4; i++)
  {
    fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
    fpx_info.components[i].horzSubSampFactor=1;
    fpx_info.components[i].vertSubSampFactor=1;
    fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
    fpx_info.components[i].lineStride=image->columns*
      fpx_info.components[i].columnStride;
    fpx_info.components[i].theData=pixels+i;
  }
  fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
    NIFRGB_R : MONOCHROME;
  red_component=(&fpx_info.components[0]);
  fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
    NIFRGB_G : ALPHA;
  green_component=(&fpx_info.components[1]);
  fpx_info.components[2].myColorType.myColor=NIFRGB_B;
  blue_component=(&fpx_info.components[2]);
  fpx_info.components[3].myColorType.myColor=ALPHA;
  alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
  FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
  /*
    Initialize image pixels.
  */
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
    if (q == (PixelPacket *) NULL)
      break;
    indexes=GetAuthenticIndexQueue(image);
    if ((y % tile_height) == 0)
      {
        /*
          Read FPX image tile (with or without viewing affine)..
        */
        if (image_info->view != (char *) NULL)
          fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
            tile_height-1,scene,&fpx_info);
        else
          fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
            (float) y/image->rows,(float) image->columns/image->rows,
            (float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
            (ssize_t) tile_height,&fpx_info);
        if (fpx_status == FPX_LOW_MEMORY_ERROR)
          {
            pixels=(unsigned char *) RelinquishMagickMemory(pixels);
            (void) FPX_CloseImage(flashpix);
            FPX_ClearSystem();
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          }
      }
    /*
      Transfer a FPX pixels.
    */
    r=red_component->theData+(y % tile_height)*red_component->lineStride;
    g=green_component->theData+(y % tile_height)*green_component->lineStride;
    b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
    a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      if (fpx_info.numberOfComponents > 2)
        {
          SetPixelRed(q,ScaleCharToQuantum(*r));
          SetPixelGreen(q,ScaleCharToQuantum(*g));
          SetPixelBlue(q,ScaleCharToQuantum(*b));
        }
      else
        {
          index=ScaleCharToQuantum(*r);
          SetPixelIndex(indexes+x,index);
          SetPixelRed(q,index);
          SetPixelGreen(q,index);
          SetPixelBlue(q,index);
        }
      SetPixelOpacity(q,OpaqueOpacity);
      if (image->matte != MagickFalse)
        SetPixelAlpha(q,ScaleCharToQuantum(*a));
      q++;
      r+=red_component->columnStride;
      g+=green_component->columnStride;
      b+=blue_component->columnStride;
      a+=alpha_component->columnStride;
    }
    if (SyncAuthenticPixels(image,exception) == MagickFalse)
      break;
    status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
      image->rows);
    if (status == MagickFalse)
      break;
  }
  pixels=(unsigned char *) RelinquishMagickMemory(pixels);
  (void) FPX_CloseImage(flashpix);
  FPX_ClearSystem();
  return(GetFirstImageInList(image));
}
#endif

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r F P X I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterFPXImage() adds attributes for the FPX image format to
%  the list of supported formats.  The attributes include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterFPXImage method is:
%
%      size_t RegisterFPXImage(void)
%
*/
ModuleExport size_t RegisterFPXImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("FPX");
#if defined(MAGICKCORE_FPX_DELEGATE)
  entry->decoder=(DecodeImageHandler *) ReadFPXImage;
  entry->encoder=(EncodeImageHandler *) WriteFPXImage;
#endif
  entry->adjoin=MagickFalse;
  entry->seekable_stream=MagickTrue;
  entry->blob_support=MagickFalse;
  entry->magick=(IsImageFormatHandler *) IsFPX;
  entry->description=ConstantString("FlashPix Format");
  entry->module=ConstantString("FPX");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r F P X I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterFPXImage() removes format registrations made by the
%  FPX module from the list of supported formats.
%
%  The format of the UnregisterFPXImage method is:
%
%      UnregisterFPXImage(void)
%
*/
ModuleExport void UnregisterFPXImage(void)
{
  (void) UnregisterMagickInfo("FPX");
}

#if defined(MAGICKCORE_FPX_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e F P X I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WriteFPXImage() writes an image in the FlashPix image format.  This
%  method was contributed by BillR@corbis.com.
%
%  The format of the WriteFPXImage method is:
%
%      MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
%
%  A description of each parameter follows.
%
%    o image_info: the image info.
%
%    o image:  The image.
%
*/

static void ColorTwistMultiply(FPXColorTwistMatrix first,
  FPXColorTwistMatrix second,FPXColorTwistMatrix *color_twist)
{
  /*
    Matrix multiply.
  */
  assert(color_twist != (FPXColorTwistMatrix *) NULL);
  color_twist->byy=(first.byy*second.byy)+(first.byc1*second.bc1y)+
    (first.byc2*second.bc2y)+(first.dummy1_zero*second.dummy4_zero);
  color_twist->byc1=(first.byy*second.byc1)+(first.byc1*second.bc1c1)+
    (first.byc2*second.bc2c1)+(first.dummy1_zero*second.dummy5_zero);
  color_twist->byc2=(first.byy*second.byc2)+(first.byc1*second.bc1c2)+
    (first.byc2*second.bc2c2)+(first.dummy1_zero*second.dummy6_zero);
  color_twist->dummy1_zero=(first.byy*second.dummy1_zero)+
    (first.byc1*second.dummy2_zero)+(first.byc2*second.dummy3_zero)+
    (first.dummy1_zero*second.dummy7_one);
  color_twist->bc1y=(first.bc1y*second.byy)+(first.bc1c1*second.bc1y)+
    (first.bc1c2*second.bc2y)+(first.dummy2_zero*second.dummy4_zero);
  color_twist->bc1c1=(first.bc1y*second.byc1)+(first.bc1c1*second.bc1c1)+
    (first.bc1c2*second.bc2c1)+(first.dummy2_zero*second.dummy5_zero);
  color_twist->bc1c2=(first.bc1y*second.byc2)+(first.bc1c1*second.bc1c2)+
    (first.bc1c2*second.bc2c2)+(first.dummy2_zero*second.dummy6_zero);
  color_twist->dummy2_zero=(first.bc1y*second.dummy1_zero)+
    (first.bc1c1*second.dummy2_zero)+(first.bc1c2*second.dummy3_zero)+
    (first.dummy2_zero*second.dummy7_one);
  color_twist->bc2y=(first.bc2y*second.byy)+(first.bc2c1*second.bc1y)+
    (first.bc2c2*second.bc2y)+(first.dummy3_zero*second.dummy4_zero);
  color_twist->bc2c1=(first.bc2y*second.byc1)+(first.bc2c1*second.bc1c1)+
    (first.bc2c2*second.bc2c1)+(first.dummy3_zero*second.dummy5_zero);
  color_twist->bc2c2=(first.bc2y*second.byc2)+(first.bc2c1*second.bc1c2)+
    (first.bc2c2*second.bc2c2)+(first.dummy3_zero*second.dummy6_zero);
  color_twist->dummy3_zero=(first.bc2y*second.dummy1_zero)+
    (first.bc2c1*second.dummy2_zero)+(first.bc2c2*second.dummy3_zero)+
    (first.dummy3_zero*second.dummy7_one);
  color_twist->dummy4_zero=(first.dummy4_zero*second.byy)+
    (first.dummy5_zero*second.bc1y)+(first.dummy6_zero*second.bc2y)+
    (first.dummy7_one*second.dummy4_zero);
  color_twist->dummy5_zero=(first.dummy4_zero*second.byc1)+
    (first.dummy5_zero*second.bc1c1)+(first.dummy6_zero*second.bc2c1)+
    (first.dummy7_one*second.dummy5_zero);
  color_twist->dummy6_zero=(first.dummy4_zero*second.byc2)+
    (first.dummy5_zero*second.bc1c2)+(first.dummy6_zero*second.bc2c2)+
    (first.dummy7_one*second.dummy6_zero);
  color_twist->dummy7_one=(first.dummy4_zero*second.dummy1_zero)+
    (first.dummy5_zero*second.dummy2_zero)+
    (first.dummy6_zero*second.dummy3_zero)+(first.dummy7_one*second.dummy7_one);
}

static void SetBrightness(double brightness,FPXColorTwistMatrix *color_twist)
{
  FPXColorTwistMatrix
    effect,
    result;

  /*
    Set image brightness in color twist matrix.
  */
  assert(color_twist != (FPXColorTwistMatrix *) NULL);
  brightness=sqrt((double) brightness);
  effect.byy=brightness;
  effect.byc1=0.0;
  effect.byc2=0.0;
  effect.dummy1_zero=0.0;
  effect.bc1y=0.0;
  effect.bc1c1=brightness;
  effect.bc1c2=0.0;
  effect.dummy2_zero=0.0;
  effect.bc2y=0.0;
  effect.bc2c1=0.0;
  effect.bc2c2=brightness;
  effect.dummy3_zero=0.0;
  effect.dummy4_zero=0.0;
  effect.dummy5_zero=0.0;
  effect.dummy6_zero=0.0;
  effect.dummy7_one=1.0;
  ColorTwistMultiply(*color_twist,effect,&result);
  *color_twist=result;
}

static void SetColorBalance(double red,double green,double blue,
  FPXColorTwistMatrix *color_twist)
{
  FPXColorTwistMatrix
    blue_effect,
    green_effect,
    result,
    rgb_effect,
    rg_effect,
    red_effect;

  /*
    Set image color balance in color twist matrix.
  */
  assert(color_twist != (FPXColorTwistMatrix *) NULL);
  red=sqrt((double) red)-1.0;
  green=sqrt((double) green)-1.0;
  blue=sqrt((double) blue)-1.0;
  red_effect.byy=1.0;
  red_effect.byc1=0.0;
  red_effect.byc2=0.299*red;
  red_effect.dummy1_zero=0.0;
  red_effect.bc1y=(-0.299)*red;
  red_effect.bc1c1=1.0-0.299*red;
  red_effect.bc1c2=(-0.299)*red;
  red_effect.dummy2_zero=0.0;
  red_effect.bc2y=0.701*red;
  red_effect.bc2c1=0.0;
  red_effect.bc2c2=1.0+0.402*red;
  red_effect.dummy3_zero=0.0;
  red_effect.dummy4_zero=0.0;
  red_effect.dummy5_zero=0.0;
  red_effect.dummy6_zero=0.0;
  red_effect.dummy7_one=1.0;
  green_effect.byy=1.0;
  green_effect.byc1=(-0.114)*green;
  green_effect.byc2=(-0.299)*green;
  green_effect.dummy1_zero=0.0;
  green_effect.bc1y=(-0.587)*green;
  green_effect.bc1c1=1.0-0.473*green;
  green_effect.bc1c2=0.299*green;
  green_effect.dummy2_zero=0.0;
  green_effect.bc2y=(-0.587)*green;
  green_effect.bc2c1=0.114*green;
  green_effect.bc2c2=1.0-0.288*green;
  green_effect.dummy3_zero=0.0;
  green_effect.dummy4_zero=0.0;
  green_effect.dummy5_zero=0.0;
  green_effect.dummy6_zero=0.0;
  green_effect.dummy7_one=1.0;
  blue_effect.byy=1.0;
  blue_effect.byc1=0.114*blue;
  blue_effect.byc2=0.0;
  blue_effect.dummy1_zero=0.0;
  blue_effect.bc1y=0.886*blue;
  blue_effect.bc1c1=1.0+0.772*blue;
  blue_effect.bc1c2=0.0;
  blue_effect.dummy2_zero=0.0;
  blue_effect.bc2y=(-0.114)*blue;
  blue_effect.bc2c1=(-0.114)*blue;
  blue_effect.bc2c2=1.0-0.114*blue;
  blue_effect.dummy3_zero=0.0;
  blue_effect.dummy4_zero=0.0;
  blue_effect.dummy5_zero=0.0;
  blue_effect.dummy6_zero=0.0;
  blue_effect.dummy7_one=1.0;
  ColorTwistMultiply(red_effect,green_effect,&rg_effect);
  ColorTwistMultiply(rg_effect,blue_effect,&rgb_effect);
  ColorTwistMultiply(*color_twist,rgb_effect,&result);
  *color_twist=result;
}

static void SetSaturation(double saturation,FPXColorTwistMatrix *color_twist)
{
  FPXColorTwistMatrix
    effect,
    result;

  /*
    Set image saturation in color twist matrix.
  */
  assert(color_twist != (FPXColorTwistMatrix *) NULL);
  effect.byy=1.0;
  effect.byc1=0.0;
  effect.byc2=0.0;
  effect.dummy1_zero=0.0;
  effect.bc1y=0.0;
  effect.bc1c1=saturation;
  effect.bc1c2=0.0;
  effect.dummy2_zero=0.0;
  effect.bc2y=0.0;
  effect.bc2c1=0.0;
  effect.bc2c2=saturation;
  effect.dummy3_zero=0.0;
  effect.dummy4_zero=0.0;
  effect.dummy5_zero=0.0;
  effect.dummy6_zero=0.0;
  effect.dummy7_one=1.0;
  ColorTwistMultiply(*color_twist,effect,&result);
  *color_twist=result;
}

static MagickBooleanType WriteFPXImage(const ImageInfo *image_info,Image *image)
{
  FPXBackground
    background_color;

  FPXColorspace
    colorspace =
    {
      TRUE, 4,
      {
        { NIFRGB_R, DATA_TYPE_UNSIGNED_BYTE },
        { NIFRGB_G, DATA_TYPE_UNSIGNED_BYTE },
        { NIFRGB_B, DATA_TYPE_UNSIGNED_BYTE },
        { ALPHA, DATA_TYPE_UNSIGNED_BYTE }
      }
    };

  const char
    *comment,
    *label;

  FPXCompressionOption
    compression;

  FPXImageDesc
    fpx_info;

  FPXImageHandle
    *flashpix;

  FPXStatus
    fpx_status;

  FPXSummaryInformation
    summary_info;

  MagickBooleanType
    status;

  QuantumInfo
    *quantum_info;

  QuantumType
    quantum_type;

  register const PixelPacket
    *p;

  register ssize_t
    i;

  size_t
    memory_limit;

  ssize_t
    y;

  unsigned char
    *pixels;

  unsigned int
    tile_height,
    tile_width;

  /*
    Open input file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFalse)
    return(status);
  if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
    (void) TransformImageColorspace(image,sRGBColorspace);
  (void) CloseBlob(image);
  /*
    Initialize FPX toolkit.
  */
  image->depth=8;
  memory_limit=20000000;
  fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
  if (fpx_status != FPX_OK)
    ThrowWriterException(DelegateError,"UnableToInitializeFPXLibrary");
  tile_width=64;
  tile_height=64;
  colorspace.numberOfComponents=3;
  if (image->matte != MagickFalse)
    colorspace.numberOfComponents=4;
  if ((image_info->type != TrueColorType) &&
      IsGrayImage(image,&image->exception))
    {
      colorspace.numberOfComponents=1;
      colorspace.theComponents[0].myColor=MONOCHROME;
    }
  background_color.color1_value=0;
  background_color.color2_value=0;
  background_color.color3_value=0;
  background_color.color4_value=0;
  compression=NONE;
  if (image->compression == JPEGCompression)
    compression=JPEG_UNSPECIFIED;
  if (image_info->compression == JPEGCompression)
    compression=JPEG_UNSPECIFIED;
  {
#if defined(macintosh)
    FSSpec
      fsspec;

    FilenameToFSSpec(filename,&fsspec);
    fpx_status=FPX_CreateImageByFilename((const FSSpec &) fsspec,image->columns,
#else
    fpx_status=FPX_CreateImageByFilename(image->filename,image->columns,
#endif
      image->rows,tile_width,tile_height,colorspace,background_color,
      compression,&flashpix);
  }
  if (fpx_status != FPX_OK)
    return(status);
  if (compression == JPEG_UNSPECIFIED)
    {
      /*
        Initialize the compression by quality for the entire image.
      */
      fpx_status=FPX_SetJPEGCompression(flashpix,(unsigned short)
        image->quality == UndefinedCompressionQuality ? 75 : image->quality);
      if (fpx_status != FPX_OK)
        ThrowWriterException(DelegateError,"UnableToSetJPEGLevel");
    }
  /*
    Set image summary info.
  */
  summary_info.title_valid=MagickFalse;
  summary_info.subject_valid=MagickFalse;
  summary_info.author_valid=MagickFalse;
  summary_info.comments_valid=MagickFalse;
  summary_info.keywords_valid=MagickFalse;
  summary_info.OLEtemplate_valid=MagickFalse;
  summary_info.last_author_valid=MagickFalse;
  summary_info.rev_number_valid=MagickFalse;
  summary_info.edit_time_valid=MagickFalse;
  summary_info.last_printed_valid=MagickFalse;
  summary_info.create_dtm_valid=MagickFalse;
  summary_info.last_save_dtm_valid=MagickFalse;
  summary_info.page_count_valid=MagickFalse;
  summary_info.word_count_valid=MagickFalse;
  summary_info.char_count_valid=MagickFalse;
  summary_info.thumbnail_valid=MagickFalse;
  summary_info.appname_valid=MagickFalse;
  summary_info.security_valid=MagickFalse;
  label=GetImageProperty(image,"label");
  if (label != (const char *) NULL)
    {
      size_t
        length;

      /*
        Note image label.
      */
      summary_info.title_valid=MagickTrue;
      length=strlen(label);
      summary_info.title.length=length;
      if (~length >= (MaxTextExtent-1))
        summary_info.title.ptr=(unsigned char *) AcquireQuantumMemory(
          length+MaxTextExtent,sizeof(*summary_info.title.ptr));
      if (summary_info.title.ptr == (unsigned char *) NULL)
        ThrowWriterException(DelegateError,"UnableToSetImageTitle");
      (void) CopyMagickString((char *) summary_info.title.ptr,label,
        MaxTextExtent);
    }
  comment=GetImageProperty(image,"comment");
  if (comment != (const char *) NULL)
    {
      /*
        Note image comment.
      */
      summary_info.comments_valid=MagickTrue;
      summary_info.comments.ptr=(unsigned char *) AcquireString(comment);
      summary_info.comments.length=strlen(comment);
    }
  fpx_status=FPX_SetSummaryInformation(flashpix,&summary_info);
  if (fpx_status != FPX_OK)
    ThrowWriterException(DelegateError,"UnableToSetSummaryInfo");
  /*
    Initialize FlashPix image description.
  */
  quantum_info=AcquireQuantumInfo(image_info,image);
  if (quantum_info == (QuantumInfo *) NULL)
    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
  pixels=GetQuantumPixels(quantum_info);
  fpx_info.numberOfComponents=colorspace.numberOfComponents;
  for (i=0; i < (ssize_t) fpx_info.numberOfComponents; i++)
  {
    fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
    fpx_info.components[i].horzSubSampFactor=1;
    fpx_info.components[i].vertSubSampFactor=1;
    fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
    fpx_info.components[i].lineStride=
      image->columns*fpx_info.components[i].columnStride;
    fpx_info.components[i].theData=pixels+i;
  }
  fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents != 1
    ? NIFRGB_R : MONOCHROME;
  fpx_info.components[1].myColorType.myColor=NIFRGB_G;
  fpx_info.components[2].myColorType.myColor=NIFRGB_B;
  fpx_info.components[3].myColorType.myColor=ALPHA;
  /*
    Write image pixelss.
  */
  quantum_type=RGBQuantum;
  if (image->matte != MagickFalse)
    quantum_type=RGBAQuantum;
  if (fpx_info.numberOfComponents == 1)
    quantum_type=GrayQuantum;
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    size_t
      length;

    p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
    if (p == (const PixelPacket *) NULL)
      break;
    length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
      quantum_type,pixels,&image->exception);
    (void) length;
    fpx_status=FPX_WriteImageLine(flashpix,&fpx_info);
    if (fpx_status != FPX_OK)
      break;
    status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
      image->rows);
    if (status == MagickFalse)
      break;
  }
  quantum_info=DestroyQuantumInfo(quantum_info);
  if (image_info->view != (char *) NULL)
    {
      FPXAffineMatrix
        affine;

      FPXColorTwistMatrix
        color_twist;

      FPXContrastAdjustment
        contrast;

      FPXFilteringValue
        sharpen;

      FPXResultAspectRatio
        aspect_ratio;

      FPXROI
        view_rect;

      MagickBooleanType
        affine_valid,
        aspect_ratio_valid,
        color_twist_valid,
        contrast_valid,
        sharpen_valid,
        view_rect_valid;

      /*
        Initialize default viewing parameters.
      */
      contrast=1.0;
      contrast_valid=MagickFalse;
      color_twist.byy=1.0;
      color_twist.byc1=0.0;
      color_twist.byc2=0.0;
      color_twist.dummy1_zero=0.0;
      color_twist.bc1y=0.0;
      color_twist.bc1c1=1.0;
      color_twist.bc1c2=0.0;
      color_twist.dummy2_zero=0.0;
      color_twist.bc2y=0.0;
      color_twist.bc2c1=0.0;
      color_twist.bc2c2=1.0;
      color_twist.dummy3_zero=0.0;
      color_twist.dummy4_zero=0.0;
      color_twist.dummy5_zero=0.0;
      color_twist.dummy6_zero=0.0;
      color_twist.dummy7_one=1.0;
      color_twist_valid=MagickFalse;
      sharpen=0.0;
      sharpen_valid=MagickFalse;
      aspect_ratio=(double) image->columns/image->rows;
      aspect_ratio_valid=MagickFalse;
      view_rect.left=(float) 0.1;
      view_rect.width=aspect_ratio-0.2;
      view_rect.top=(float) 0.1;
      view_rect.height=(float) 0.8; /* 1.0-0.2 */
      view_rect_valid=MagickFalse;
      affine.a11=1.0;
      affine.a12=0.0;
      affine.a13=0.0;
      affine.a14=0.0;
      affine.a21=0.0;
      affine.a22=1.0;
      affine.a23=0.0;
      affine.a24=0.0;
      affine.a31=0.0;
      affine.a32=0.0;
      affine.a33=1.0;
      affine.a34=0.0;
      affine.a41=0.0;
      affine.a42=0.0;
      affine.a43=0.0;
      affine.a44=1.0;
      affine_valid=MagickFalse;
      if (0)
        {
          /*
            Color color twist.
          */
          SetBrightness(0.5,&color_twist);
          SetSaturation(0.5,&color_twist);
          SetColorBalance(0.5,1.0,1.0,&color_twist);
          color_twist_valid=MagickTrue;
        }
      if (affine_valid)
        {
          fpx_status=FPX_SetImageAffineMatrix(flashpix,&affine);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetAffineMatrix");
        }
      if (aspect_ratio_valid)
        {
          fpx_status=FPX_SetImageResultAspectRatio(flashpix,&aspect_ratio);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetAspectRatio");
        }
      if (color_twist_valid)
        {
          fpx_status=FPX_SetImageColorTwistMatrix(flashpix,&color_twist);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetColorTwist");
        }
      if (contrast_valid)
        {
          fpx_status=FPX_SetImageContrastAdjustment(flashpix,&contrast);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetContrast");
        }
      if (sharpen_valid)
        {
          fpx_status=FPX_SetImageFilteringValue(flashpix,&sharpen);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetFilteringValue");
        }
      if (view_rect_valid)
        {
          fpx_status=FPX_SetImageROI(flashpix,&view_rect);
          if (fpx_status != FPX_OK)
            ThrowWriterException(DelegateError,"UnableToSetRegionOfInterest");
        }
    }
  (void) FPX_CloseImage(flashpix);
  FPX_ClearSystem();
  return(MagickTrue);
}
#endif


text:
class ModeIndicator(object):
    """
    This class adds a mode status indicator to a viewer's lower right-hand
    corner.

    Usage:
    Instantiate this class with a Ginga ImageView{Toolkit} object as the
    sole constructor argument.  Save a reference to the mode indicator
    object somewhere so it doesn't get collected.
    """

    def __init__(self, viewer):
        self.viewer = viewer

        # set to false to disable
        self.visible = True

        # for displaying modal keyboard state
        self.mode_obj = None
        bm = viewer.get_bindmap()
        bm.add_callback('mode-set', self.mode_change_cb)
        viewer.add_callback('configure', self._configure_cb)

    def mode_change_cb(self, bindmap, mode, modetype):
        # delete the old indicator
        obj = self.mode_obj
        self.mode_obj = None
        #canvas = self.viewer.get_canvas()
        canvas = self.viewer.private_canvas
        if obj:
            try:
                canvas.deleteObject(obj)
            except:
                pass

        if not self.visible:
            return True

        # if not one of the standard modifiers, display the new one
        if not mode in (None, 'ctrl', 'shift'):
            Text = canvas.getDrawClass('text')
            Rect = canvas.getDrawClass('rectangle')
            Compound = canvas.getDrawClass('compoundobject')

            if modetype == 'locked':
                text = '%s [L]' % (mode)
            else:
                text = mode

            xsp, ysp = 4, 6
            wd, ht = self.viewer.get_window_size()
            if self.viewer._originUpper:
                x1, y1 = wd-12*len(text), ht-12
            else:
                # matplotlib case
                x1, y1 = wd-12*len(text), 12

            o1 = Text(x1, y1, text,
                      fontsize=12, color='yellow', coord='canvas')

            wd, ht = self.viewer.renderer.get_dimensions(o1)

            # yellow text on a black filled rectangle
            if self.viewer._originUpper:
                a1, b1, a2, b2 = x1-xsp, y1+ysp, x1+wd+xsp, y1-ht
            else:
                # matplotlib case
                a1, b1, a2, b2 = x1-xsp, y1-ysp, x1+wd+2*xsp, y1+ht+ysp
            o2 = Compound(Rect(a1, b1, a2, b2,
                               color='black', coord='canvas',
                               fill=True, fillcolor='black'),
                               o1)
            self.mode_obj = o2
            canvas.add(o2)

        return True

    def _configure_cb(self, view, width, height):
        # redraw the mode indicator since the window has been resized
        bm = view.get_bindmap()
        mode, modetype = bm.current_mode()
        self.mode_change_cb(bm, mode, modetype)

#END


text:
WARNING
=
Do not try this at home. Your LPC810 may be damaged if operating at more than 30Mhz.
The source code is purely for educational purposes on how to set MCU clock speed and
so a simple benchmark.

Introduction
=
LPC800 Mini-Kit and Nokia 6020 LCD.
Shows how to dinamically set MCU speed using PLL.
Overclocks MCU up to 72Mhz. Maximal safe speed is 30Mhz according to datasheet.
Sets MCU speed from 2 Mhz to 72 Mhz in small increments, diplays 100 filled rectangles
on LCD, and shows taken time in milliseconds.
Communication between board and LCD is 9-bit SPI at MCU speed.

Hardware
=
* Custom made Nokia 6020 LCD backpack.
* NXP LPC800-Mini-Kit: MCU clock is 12Mhz from internal oscillator.

Connections
=

Nokia 6020 LCD backpack:

* VCC to 3.3V
* GND to GND
* CLK to PIO0_4
* MOSI to PIO0_0
* RST to PIO0_1
* CE to GND
* VLED to 5V

Software
=
Used peripherals:

* GPIO.
* SPI0 (9-bit, speed is the same as MCU clock (2Mhz -72Mhz).
* Multi-Rate Timer (MRT) for millisesonds delay.

Project uses external libraries:

* LPCOpen Software Development Platform 3.02
* xprintf library

Links
=
More info at: https://kbiva.wordpress.com/2014/11/10/overclocking-lpc81x/

Video: http://youtu.be/aPeuHSqAGag


text:
/** \file tb2grammarconstr.hpp
 *  \brief Dynamic programming based global cost function : sgrammar_dp
 */

#ifndef TB2GRAMMARCCONSTR_HPP_
#define TB2GRAMMARCCONSTR_HPP_

#include "tb2dpglobalconstr.hpp"
#include "tb2wgrammar.hpp"
#include <vector>
#include <fstream>
#include <string>
using namespace std;

class GrammarConstraint : public DPGlobalConstraint {
private:

    // dimension: i x j x |N|
    Cost ***f;
    Cost ***up;
    bool ***marked;

    Cost ***curf;

    // dimension: i x |sigma|
    Cost **u;

    // grammar, assuming in CNF

    /*struct Rule {
        int from;
        int weight;
        int to[2];
    };

    int nNonTerminals, nTerminals, startSymbol;
    vector<Rule> nonTerm2nonTerm;
    vector<Rule> nonTerm2term;*/
    WCNFCFG cfg;
    Cost top;

    template<class T>
    void resizeTable(T*** &table) {
        table = new T**[arity() + 1];
        for (int i = 0; i < arity() + 1; i++) {
            table[i] = new T*[arity() + 1];
            for (int j = 0; j < arity() + 1; j++) {
                table[i][j] = new T[cfg.getNumNonTerminals()];
            }
        }
    }

    template<class T>
    void deleteTable(T*** &table) {
        for (int i = 0; i < arity() + 1; i++) {
            for (int j = 0; j < arity() + 1; j++) {
                delete[] table[i][j];
            }
            delete[] table[i];
        }
        delete[] table;
        table = NULL;
    }

    void recomputeTable(Cost*** table, Cost*** upTable = NULL);
    void recompute();

    Cost unary(int ch, int var, Value v);

protected:
    Cost minCostOriginal();
    Cost minCostOriginal(int var, Value val, bool changed);
    Result minCost(int var, Value val, bool changed);

public:

    static const int WEIGHTED = 1;
    static const int VAR = 0;

    GrammarConstraint(WCSP * wcsp, EnumeratedVariable ** scope, int arity);
    virtual ~GrammarConstraint();

    Cost eval(String s);

    void read(istream & file);
    //void setDefaultViolationCost(Cost cost) {if(configuring) def = cost;}
    //void setViolationMeasure(int measure) {if(configuring) mode = measure;}
    WeightedCNFCFG* getGrammar() {return &cfg;}
    void initMemoization();

    string getName() {
        return "sgrammar";
    }
};

#endif /* TB2GRAMMARCCONSTR_HPP_ */


text:
package com.aneeshpu.dpdeppop.datatypes;

import com.aneeshpu.dpdeppop.schema.ConnectionFactory;
import org.junit.Ignore;
import org.junit.Test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static junit.framework.Assert.assertNotNull;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class FloatDataTypeTest {

    private Connection connection = new ConnectionFactory().getConnection();

    @Test
    public void generates_a_float_value() {

        final FloatDataType floatDataType = new FloatDataType("float");
        assertNotNull(floatDataType.generateDefaultValue());
    }

    @Test
    @Ignore("need to implement money data type instead of float")
    public void retrieves_generated_string_value_from_result_set() throws SQLException {

        final Statement statement = connection.createStatement();
        connection.setAutoCommit(false);

        final String accountInsertQuery = "insert into account (name) values ('aneesh')";
        statement.executeUpdate(accountInsertQuery, Statement.RETURN_GENERATED_KEYS);

        final ResultSet generatedKeys = statement.getGeneratedKeys();
        generatedKeys.next();
        final int accountId = generatedKeys.getInt("id");

        System.out.println("inserted account id:" + accountId);

        final String invoiceInsertQuery = "insert into invoice (amount, account_id) values (100," + accountId + ")";
        statement.executeUpdate(invoiceInsertQuery, Statement.RETURN_GENERATED_KEYS);

        final ResultSet generatedKeysForInvoiceTable = statement.getGeneratedKeys();
        generatedKeysForInvoiceTable.next();

        final int invoiceId = generatedKeysForInvoiceTable.getInt("id");

        final String paymentInsertQuery = "insert into payment(invoice_id, amount, status) values (" + invoiceId + ",132,2)";
        statement.executeUpdate(paymentInsertQuery, Statement.RETURN_GENERATED_KEYS);

        final ResultSet generatedKeysResultSet = statement.getGeneratedKeys();
        generatedKeysResultSet.next();

        final FloatDataType floatDataType = new FloatDataType("float");

        assertThat(floatDataType.getGeneratedValue(generatedKeysResultSet, "amount"), is(equalTo(132f)));

        connection.rollback();

    }

}


text:
<?php
/**
 * Melody library
 *
 * @category   Melody
 * @package    Melody_ModelBundle
 * @subpackage Melody_ModelBundle_Schema
 * @version    $Id:  $
 * @link       https://github.com/AlexandreBeaurain/melody
 */

namespace Melody\ModelBundle\Schema;

use Melody\ModelBundle\Schema;
use Symfony\Component\DependencyInjection\Container;
use Melody\ModelBundle\Schema\Dia\Attribute;
use Melody\ModelBundle\Schema\Dia\Composite;
use Melody\ModelBundle\Schema\Dia\Connection;
use Melody\ModelBundle\Schema\Dia\Object;

/**
 * Class for reading and writing dia file.
 */
class Dia extends Schema
{

    protected $file;
    protected $classes = array();
    protected $id2classes = array();
    protected $types = array(
        'boolean',
        'integer',
        'float',
        'decimal',
        'string',
        'array',
        'object',
        'blob',
        'clob',
        'timestamp',
        'time',
        'date',
        'enum',
        'gzip'
    );
    protected $values = array(
        'notnull',
        'type',
        'unique',
        'default',
        'primary',
        'i18n'
    );
    protected $behaviors = array(
        'Versionable',
        'Timestampable',
        'Sluggable',
        'NestedSet',
        'Searchable',
        'Geocodable',
        'SoftDelete',
        'Sortable'
    );

    public function __construct($file) {
        $this->file = $file;
        if ( ! is_file( $file ) ) {
            throw \FileNotFoundException($file.' not found');
        }
        $dom = new \DOMDocument();
        $dom->loadXML(implode("\n",gzfile($file)));
        $this->classes = array();
        $o_class_list = array();
        $o_generalization_list = array();
        $o_association_list = array();
        foreach( $dom->getElementsByTagName('object') as $element ) {
            $o = new Object($element);
            switch ( $o->getType() ) {
                case 'UML - Class':
                    $o_class_list[] = $o;
                    $this->parseClass($o);
                    break;
                case 'UML - Generalization':
                    $o_generalization_list[] = $o;
                    break;
                case 'UML - Association':
                    $o_association_list[] = $o;
                    break;
            }
        }
        foreach( $o_generalization_list as $o ) {
            $this->parseGeneralization($o);
        }
        foreach( $o_association_list as $o ) {
            $this->parseAssociation($o);
        }
    }

    public function getSchema() {
        return $this->classes;
    }

    protected function parseAttributeValue($value) {
        $values = array();
        foreach( explode(' ',$value) as $part ) {
            $parts = explode(':',$part,2);
            if ( strlen($parts[0]) > 0 ) {
                if ( isset( $parts[1] ) ) {
                    $values[$parts[0]] = $parts[1];
                }
                else {
                    $values[$parts[0]] = true;
                }
            }
        }
        return $values;
    }

    protected function parseAttribute($className, Composite $attribute) {
        $a = $attribute->getAttributes();
        $attributeName = $a['name']->getValue();
        $type = $a['type']->getValue();
        $description = $a['comment']->getValue();
        $values = $this->parseAttributeValue( $a['value']->getValue() );
        $match = array();
        if ( preg_match('|^string\(([\d]+)\)$|ims', $type, $match ) ) {
            $size = (int) $match[1];
            $type = 'string';
            $values['size'] = $size;
        }
        if ( isset( $values['notnull'] ) ) {
            unset( $values['notnull'] );
            $values['required'] = true;
        }
        if ( isset( $values['unique'] ) ) {
            unset( $values['unique'] );
            $values['index'] = 'unique';
        }
        if ($description) {
            $values['description'] = $description;
        }
        if ( isset( $values['collation'] ) ) {
            $values['vendor']['Collate'] = $values['collation'];
            unset( $values['collation'] );
        }
        if ( isset( $values['i18n'] ) ) {
            unset( $values['i18n'] );
            $i18nClassName = $className.'_i18n';
            $this->classes[$className]['_attributes']['isI18N'] = true;
            $this->classes[$className]['_attributes']['i18nTable'] = $className.'_i18n';
            $this->classes[$i18nClassName]['id']['type'] = 'integer';
            $this->classes[$i18nClassName]['id']['required'] = true;
            $this->classes[$i18nClassName]['id']['primaryKey'] = true;
            $this->classes[$i18nClassName]['id']['foreignTable'] = $className;
            $this->classes[$i18nClassName]['id']['foreignReference'] = 'id';
            $this->classes[$i18nClassName]['id']['onDelete'] = 'cascade';
            $this->classes[$i18nClassName]['culture']['type'] = 'varchar';
            $this->classes[$i18nClassName]['culture']['size'] = 7;
            $this->classes[$i18nClassName]['culture']['required'] = true;
            $this->classes[$i18nClassName]['culture']['primaryKey'] = true;
            $this->classes[$i18nClassName]['culture']['isCulture'] = true;
            $this->classes[$i18nClassName][$attributeName]['type'] = $type;
            if ( isset( $values['slug'] ) ) {
                unset( $values['slug'] );
                $values['primaryString'] = true;
                $this->classes[$i18nClassName]['_behaviors']['sluggable'] = array(
                    'slug_column' => 'slug_column',
                    'replacement' => '-'
                );
                $this->classes[$i18nClassName]['slug_column']['type'] = 'varchar';
                $this->classes[$i18nClassName]['slug_column']['size'] = 255;
            }
            foreach ( $values as $name => $value ) {
                $this->classes[$i18nClassName][$attributeName][$name] = $value;
            }
        }
        else {
            $this->classes[$className][$attributeName]['type'] = $type;
            if ( isset( $values['slug'] ) ) {
                unset( $values['slug'] );
                $values['primaryString'] = true;
                $this->classes[$className]['_behaviors']['sluggable'] = array(
                    'slug_column' => 'slug_column',
                    'replacement' => '-'
                );
                $this->classes[$className]['slug_column']['type'] = 'varchar';
                $this->classes[$className]['slug_column']['size'] = 255;
            }
            foreach ( $values as $name => $value ) {
                $this->classes[$className][$attributeName][$name] = $value;
            }
        }
    }

    protected function parseOperation($className, Composite $operation) {
        $o = $operation->getAttributes();
        $operationName = $o['name']->getValue();
        switch( $operationName ) {
            case 'Versionable':
                $this->classes[$className]['version']['type'] = 'integer';
                $this->classes[$className]['_behaviors']['versionable'] = array('version_column'=>'version');
                break;
            case 'Timestampable':
                $this->classes[$className]['created_at']['type'] = 'timestamp';
                $this->classes[$className]['updated_at']['type'] = 'timestamp';
                break;
            case 'NestedSet':
                //$this->classes[$className]['_attributes']['treeMode'] = 'NestedSet';
                $this->classes[$className]['tree_left']['type'] = 'integer';
                //$this->classes[$className]['tree_left']['nestedSetLeftKey'] = true;
                $this->classes[$className]['tree_right']['type'] = 'integer';
                //$this->classes[$className]['tree_right']['nestedSetRightKey'] = true;
                $this->classes[$className]['tree_level']['type'] = 'integer';
                $this->classes[$className]['_behaviors']['nested_set'] = array(
                    'left_column' => 'tree_left',
                    'right_column' => 'tree_right',
                    'level_column' => 'tree_level',
                );
                break;
            case 'Searchable':
                break;
            case 'Sortable':
                $this->classes[$className]['order']['type'] = 'integer';
                $options = array(
                    'rank_column' => 'order'
                );
                $values = $o['parameters']->getValue() ? $o['parameters']->getValue() : array();
                foreach ( $values as $param) {
                    $p = $param->getAttributes();
                    $options['scope_column'] = $p['name']->getValue();
                    $options['use_scope'] = true;
                }
                $this->classes[$className]['_behaviors']['sortable'] = $options;
                break;
            case 'Geocodable':
                $geocodableAddressFields = array();
                foreach ($o['parameters']->getValue() as $param) {
                    $p = $param->getAttributes();
                    $geocodableAddressFields[] =  $p['name']->getValue();
                }
                $this->classes[$className]['_behaviors']['geocodable'] = array(
                    'geocode_address'=>true,
                    'address_columns'=>implode(',',$geocodableAddressFields)
                );
                break;
            case 'SoftDelete':
                $this->classes[$className]['deleted_at']['type'] = 'timestamp';
                break;
            case 'Unique':
                $name = 'uniq_'.(isset($this->classes[$className]['_uniques']) ? count($this->classes[$className]['_uniques']) : 0);
                foreach ($o['parameters']->getValue() as $param) {
                    $p = $param->getAttributes();
                    $this->classes[$className]['_uniques'][$name][] = $p['name']->getValue();
                }
                break;
        }
    }

    protected function parseClass(Object $o) {
        $oa = $o->getAttributes();
        $className = Container::underscore( $oa['name']->getValue() );
        $this->id2classes[$o->getId()] = $className;
        $description = $oa['comment']->getValue();
        $this->classes[$className]['_attributes']['description'] = $description;
        if ( isset(  $oa['stereotype'] ) && $oa['stereotype']->getValue() ) {
            $this->classes[$className]['_attributes']['phpName'] = $oa['stereotype']->getValue();
        }
        $this->classes[$className]['id']['type'] = 'integer';
        $this->classes[$className]['id']['required'] = true;
        $this->classes[$className]['id']['primaryKey'] = true;
        $this->classes[$className]['id']['autoIncrement'] = true;
        if ( isset( $oa['attributes']) ) {
            $attributes = $oa['attributes']->getValue();
            if ( ! empty($attributes) ) {
                foreach( $attributes as $attribute ) {
                    $this->parseAttribute($className,$attribute);
                }
            }
        }
        if ( isset($oa['operations']) ) {
            $operations = $oa['operations']->getValue();
            if ( ! empty($operations) ) {
                foreach( $operations as $operation ) {
                    $this->parseOperation($className,$operation);
                }
            }
        }
    }

    protected function parseGeneralization(Object $o) {
        $connection = $o->getConnection();
        $oa = $o->getAttributes();
        $fromClassName = isset($this->id2classes[$connection->getFrom()]) ? $this->id2classes[$connection->getFrom()] : $oa['name']->getValue();
        $toClassName = isset($this->id2classes[$connection->getTo()]) ? $this->id2classes[$connection->getTo()] : $oa['name']->getValue();
        if ( isset( $this->classes[$toClassName]['id']['autoIncrement'] ) ) {
            unset( $this->classes[$toClassName]['id']['autoIncrement'] );
        }
        $this->classes[$toClassName]['id']['foreignTable'] = $fromClassName;
        $this->classes[$toClassName]['id']['foreignReference'] = 'id';
        $this->classes[$toClassName]['id']['onDelete'] = 'cascade';
        // concrete_inheritance / class_table_inheritance / single_inheritance
        $this->classes[$toClassName]['_behaviors']['class_table_inheritance'] = array(
            'extends' => $fromClassName
        );
        if ( isset( $this->classes[$toClassName]['_attributes']['isI18N'] ) && isset( $this->classes[$fromClassName]['_attributes']['isI18N'] ) ) {
            $toI18nClassName = $this->classes[$toClassName]['_attributes']['i18nTable'];
            $fromI18nClassName = $this->classes[$fromClassName]['_attributes']['i18nTable'];
            $this->classes[$toI18nClassName]['_behaviors']['class_table_inheritance'] = array(
                'extends' => $fromI18nClassName,
                'descendant_column' => 'descendant_class_i18n'
            );
            $fkey = array(
                'foreignTable' => $fromI18nClassName,
                'onDelete' => 'cascade',
                'references' => array(
                    array('local'=>'id','foreign'=>'id'),
                    array('local'=>'culture','foreign'=>'culture')
                )
            );
            $this->classes[$toI18nClassName]['_foreignKeys'][] = $fkey;
        }
    }

    protected function parseAssociationValues(Object $o) {
        $oa = $o->getAttributes();
        $direction = $oa['direction']->getValue();
        $connection = $o->getConnection();
        $associationName = $oa['name']->getValue();
        $type = $oa['assoc_type']->getValue();
        $multiplicities = array();
        foreach( array('a','b') as $extremity ) {
            $match = array();
            if ( preg_match('|([\*0-9]+)[ \.]*([\*n0-9]*)|ims',$oa['multipicity_'.$extremity]->getValue(),$match) ) {
                if ( $match[1] == '*' ) {
                    $multiplicities[$extremity] = array(
                            'min'=>0
                    );
                }
                else {
                    $multiplicities[$extremity] = array(
                            'min'=> (int) $match[1]
                    );
                }
                if ( strlen($match[2]) == 0 ) {
                    if ( $match[1] != '*' ) {
                        $multiplicities[$extremity]['max'] = $multiplicities[$extremity]['min'];
                    }
                }
                else if ( ! in_array( $match[2], array('*','n') ) ) {
                    $multiplicities[$extremity]['max'] = (int) $match[2];
                }
            }
            else {
                $multiplicities[$extremity] = array('min'=>( $type == 2 ) ? 1 : 0,'max'=>1);
            }

        }
        switch( $direction ) {
            default:
            case 1:
                $fromClassName = isset( $this->id2classes[$connection->getFrom()] ) ? $this->id2classes[$connection->getFrom()] : $oa['role_a']->getValue();
                $toClassName = isset( $this->id2classes[$connection->getTo()] ) ? $this->id2classes[$connection->getTo()] : $oa['role_b']->getValue();
                $toMultiplicity = $multiplicities['a'];
                $fromMultiplicity = $multiplicities['b'];
                break;
            case 2:
                $toClassName = isset( $this->id2classes[$connection->getFrom()] ) ? $this->id2classes[$connection->getFrom()] : $oa['role_a']->getValue();
                $fromClassName = isset( $this->id2classes[$connection->getTo()] ) ? $this->id2classes[$connection->getTo()] : $oa['role_b']->getValue();
                $fromMultiplicity = $multiplicities['a'];
                $toMultiplicity = $multiplicities['b'];
                break;
        }
        if ( ! $associationName ) {
            if ( ( ! isset( $fromMultiplicity['max'] ) ) || ( $fromMultiplicity['max'] > 1 ) ) {
                if ( $fromClassName > $toClassName ) {
                    $associationName = $toClassName.'_'.$fromClassName;
                }
                else {
                    $associationName = $fromClassName.'_'.$toClassName;
                }
            }
            else {
                $associationName = $toClassName;
            }
        }
        return array($associationName,$fromClassName,$toClassName,$fromMultiplicity,$toMultiplicity);
    }

    protected function parseAssociation(Object $o) {
        list($associationName,$fromClassName,$toClassName,$fromMultiplicity,$toMultiplicity) = $this->parseAssociationValues($o);
        $associationName = strtr( Container::underscore( $associationName ), array('.'=>'_') );
        $fromClassName = strtr( Container::underscore( $fromClassName ), array('.'=>'_') );
        $toClassName = strtr( Container::underscore( $toClassName ), array('.'=>'_') );
        if (
                ( ! isset($fromMultiplicity['max']) || $fromMultiplicity['max'] > 1 ) &&
                ( ! isset($toMultiplicity['max']) || $toMultiplicity['max'] > 1 )
        ) {
            $this->classes[$associationName]['id']['type'] = 'integer';
            $this->classes[$associationName]['id']['required'] = true;
            $this->classes[$associationName]['id']['primaryKey'] = true;
            $this->classes[$associationName]['id']['autoIncrement'] = true;
            $this->classes[$associationName][$fromClassName.'_id']['type'] = 'integer';
            $this->classes[$associationName][$fromClassName.'_id']['required'] = true;
            $this->classes[$associationName][$fromClassName.'_id']['foreignTable'] = $fromClassName;
            $this->classes[$associationName][$fromClassName.'_id']['foreignReference'] = 'id';
            $this->classes[$associationName][$fromClassName.'_id']['onDelete'] = 'cascade';
            $this->classes[$associationName][$toClassName.'_id']['type'] = 'integer';
            $this->classes[$associationName][$toClassName.'_id']['required'] = true;
            $this->classes[$associationName][$toClassName.'_id']['foreignTable'] = $toClassName;
            $this->classes[$associationName][$toClassName.'_id']['foreignReference'] = 'id';
            $this->classes[$associationName][$toClassName.'_id']['onDelete'] = 'cascade';
            $this->classes[$associationName]['_attributes']['isCrossRef'] = true;
            $this->classes[$associationName]['_attributes']['phpName'] = Container::camelize($associationName);
        }
        else {
            $this->classes[$fromClassName][$associationName.'_id']['type'] = 'integer';
            if ( $toMultiplicity['min'] ) {
                $this->classes[$fromClassName][$associationName.'_id']['required'] = true;
            }
            $this->classes[$fromClassName][$associationName.'_id']['foreignTable'] = $toClassName;
            $this->classes[$fromClassName][$associationName.'_id']['foreignReference'] = 'id';
            $this->classes[$fromClassName][$associationName.'_id']['required'] = $toMultiplicity['min']?'true':'false' ;
            $this->classes[$fromClassName][$associationName.'_id']['onDelete'] = $toMultiplicity['min']?'cascade':'setnull';
        }
    }

}


text:
package io.gatling.http

import org.asynchttpclient.Request

package object response {

  type ResponseBuilderFactory = Request => ResponseBuilder
}


text:
require 'spec_helper'

describe Bitstamp::Orders do
  before { setup_bitstamp }

  describe :all, vcr: {cassette_name: 'bitstamp/orders/all'} do
    subject { Bitstamp.orders.all }
    it { should be_kind_of Array }
    describe "first order" do
      subject { Bitstamp.orders.all.first }
      its(:price) { should == "1.01" }
      its(:amount) { should == "1.00000000" }
      its(:type) { should == 0 }
      its(:datetime) { should == "2013-09-26 23:15:04" }
    end
  end

  describe :sell do
    context "no permission found", vcr: {cassette_name: 'bitstamp/orders/sell/failure'} do
      subject { Bitstamp.orders.sell(:amount => 1, :price => 1000) }
      it { should be_kind_of Bitstamp::Order }
      its(:error) { should == "No permission found" }
    end
    # context "bitcoins available", vcr: {cassette_name: 'bitstamp/orders/sell/success'} do
    #   subject { Bitstamp.orders.sell(:amount => 1, :price => 1000) }
    #   xit { should be_kind_of Bitstamp::Order }
    #   its(:error) { should be_nil }
    # end
  end

  describe :buy, vcr: {cassette_name: 'bitstamp/orders/buy'} do
    subject { Bitstamp.orders.buy(:amount => 1, :price => 1.01) }
    it { should be_kind_of Bitstamp::Order }
    its(:price) { should == "1.01" }
    its(:amount) { should == "1" }
    its(:type) { should == 0 }
    its(:datetime) { should == "2013-09-26 23:26:56.849475" }
    its(:error) { should be_nil }
  end
end


text:
layout: default
title: CAS - Hazelcast Ticket Registry
---

# Hazelcast Ticket Registry

Hazelcast Ticket Registry is a distributed ticket registry implementation based on [Hazelcast distributed grid library](http://hazelcast.org/). The registry implementation is cluster-aware and is able to auto-join a cluster of all the CAS nodes that expose this registry. Hazelcast will use port auto-increment feature to assign a TCP port to each member of a cluster starting from initially provided arbitrary port (`5701` by default).

Hazelcast will evenly distribute the ticket data among all the members of a cluster in a very efficient manner. Also, by default, the data collection on each node is configured with 1 backup copy, so that Hazelcast will use it to make strong data consistency guarantees i.e. the loss of data on live nodes will not occur should any other *primary data owner* members die. The data will be re-partitioned among the remaining live cluster members.

This ticket registry implementation is enabled by simply including the module in the Maven overlay pom:

```xml
<dependency>
    <groupId>org.jasig.cas</groupId>
    <artifactId>cas-server-integration-hazelcast</artifactId>
    <version>${cas.version}</version>
</dependency>
```

## Configuration

Enable the registry via:

```xml
<alias name="hazelcastTicketRegistry" alias="ticketRegistry" />
```

This module has a flexible configuration strategy which by default auto-configures `HazelcastInstance` used by the TicketRegistry
implementation to retrieve Hazelcast's `IMap` instance for its distributed tickets storage. Some aspects of `HazelcastInstance`
configuration in this auto-configuration mode are controlled by the following exposed properties which could be set via
an external `cas.properties` file (with sensible defaults for all the properties if not explicitly set):

```properties
# hz.config.location=file:/etc/cas/hazelcast.xml
# hz.mapname=tickets
# hz.cluster.logging.type=slf4j
# hz.cluster.portAutoIncrement=true
# hz.cluster.port=5701
# hz.cluster.members=cas1.example.com,cas2.example.com
# hz.cluster.tcpip.enabled=true
# hz.cluster.multicast.enabled=false
# hz.cluster.max.heapsize.percentage=85
# hz.cluster.max.heartbeat.seconds=300
# hz.cluster.eviction.percentage=10
# hz.cluster.eviction.policy=LRU
# hz.cluster.instance.name=${host.name}
# hz.cluster.logging.type=slf4j
# hz.cluster.backupCount=1
# hz.cluster.asyncBackupCount=0
```

Should the more fine-grained configuration need arise, there is an option to use a native Hazelcast configuration XML format
where all the configuration options for `HazelcastInstance` exposed by Hazelcast are available. In order to trigger this configuration mode,
there are two basic steps required:

* Place native `hazelcast.xml` file containing the custom configuration for Hazelcast Instance into an external filesystem location
  of choice (`/etc/cas/hazelcast.xml` by convention).

* Indicate the location of the external native config file by the following property:

```properties
hz.config.location=file:/etc/cas/hazelcast.xml
```

Here's a simple example of `hazelcast.xml` that configures AWS cluster join strategy instead of a default TCP/IP one:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-3.6.xsd"
           xmlns="http://www.hazelcast.com/schema/config"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <network>
        <port auto-increment="true" port-count="100">5701</port>
        <join>
            <multicast enabled="false">
                <multicast-group>224.2.2.3</multicast-group>
                <multicast-port>55327</multicast-port>
            </multicast>
            <tcp-ip enabled="false">
                <member-list>
                    <member>127.0.0.1</member>
                </member-list>
            </tcp-ip>
            <aws enabled="true">
                <access-key>my-access-key</access-key>
                <secret-key>my-secret-key</secret-key>
                <!--optional, default is us-east-1 -->
                <region>us-west-1</region>
                <!--optional, default is ec2.amazonaws.com. If set, region shouldn't be set as it will override this property -->
                <host-header>ec2.amazonaws.com</host-header>
                <!-- optional, only instances belonging to this group will be discovered, default will try all running instances -->
                <security-group-name>hazelcast-sg</security-group-name>
                <tag-key>type</tag-key>
                <tag-value>hz-nodes</tag-value>
            </aws>
        </join>
    </network>

    <map name="tickets">
        <max-idle-seconds>28800</max-idle-seconds>
        <!--
            Valid values are:
            NONE (no eviction),
            LRU (Least Recently Used),
            LFU (Least Frequently Used).
            NONE is the default.
        -->
        <eviction-policy>LFU</eviction-policy>
        <!--
            Maximum size of the map. When max size is reached,
            map is evicted based on the policy defined.
            Any integer between 0 and Integer.MAX_VALUE. 0 means
            Integer.MAX_VALUE. Default is 0.
        -->
        <max-size policy="USED_HEAP_PERCENTAGE">85</max-size>
        <!--
            When max. size is reached, specified percentage of
            the map will be evicted. Any integer between 0 and 100.
            If 25 is set for example, 25% of the entries will
            get evicted.
        -->
        <eviction-percentage>10</eviction-percentage>
    </map>

</hazelcast>
```

For more information on the Hazelcast configuration options available, refer to [the Hazelcast documentation](http://docs.hazelcast.org/docs/3.6/manual/html/configuringhazelcast.html)

## Logging
To enable additional logging for the registry, configure the log4j configuration file to add the following
levels:

```xml
...
<AsyncLogger name="com.hazelcast" level="debug" additivity="false">
    <AppenderRef ref="console"/>
    <AppenderRef ref="file"/>
</AsyncLogger>
...
```