text:
/*
 * Claw.h
 *
 *  Created on: Jan 13, 2011
 *      Author: Nick Alberts
 */

#ifndef CLAW_H_
#define CLAW_H_

#include "WPILib.h"
#include "conc/thread.h"
#include "conc/mutex.h"
#include "diag/ObservableWPI.h"
/**
* @brief Class that controls the claw and gripper
*/

class Claw
{
public:

	/**
	* @brief Constructs an instance of the claw class.
	*/
	Claw();

	/**
	* @brief Runs the claw servos to pull the game piece in.
	*/
	void Grab();

	/**
	* @brief Runs the claw servos to push the game piece out.
	*/
	void Release();

	/**
	* @brief Rotates the game piece above the claw.
	*/
	void RotateUp();

	/**
	* @brief Rotates the game piece below the claw.
	*/
	void RotateDown();

	Servo clawServoTop4;
	Servo clawServoTop3;
	Servo clawServoBottom1;
	Servo clawServoBottom2;

private:
	nr::conc::Thread claw_control_thread;
	nr::conc::Mutex claw_control_mutex;
	static void claw_servo_stop( void* );
	float time;
	bool clawControlRunning;
};

#endif /* CLAW_H_ */


text:
<!-- Start jargon.js -->

#A tiny JavaScript DOM library
**Utilities methods & DOM elements decorator**
##Examples
```javascript
jArgon.trim('    a string to trim    ');
var jargonObj = jArgon('div > div.foo .bar #jargon');
jargonObj.getElementsByAttribute('.fuzz[bar]');
```
##Test suite
Use Qunit, see `test/` directory.
Tested under:
   * FF, Chrome on Ubuntu 12.04
   * IE7+, Chrome, FF, Opera on Windows 7
   * Safari on iOS
   * Android Browser, Chrome on Android 4.03

##Coding convention
I use my own `.jshintrc` file, but rules similar to jQuery's

##Documentation:
JSDoc, [markdox](https://github.com/cbou/markdox) for generating README.md

## extend(target, extension)

Extend an object with a set a properties
##Example
```javascript
var o = { prop1: 'hello' };
jArgon.extend( o, { prop2: 'world' } );
// o = { prop1: 'hello', prop2: 'world' }
```

### Params:

* **Object** *target* - The target object to extend

* **Object** *extension* - An object containing the new properties

### Return:

* **Object** - The target object extended

## trim(str)

Call native API method if exists, use fallback otherwise

### Params:

* **String** *str* - The string to trim

### Return:

* **String** The new trimmed string

## toArray(pseudoArray)

Convert pseudo arrays (eg `arguments`, `nodeList`) to arrays

### Params:

* **PseudoArray** *pseudoArray* - The pseudoArray to convert

### Return:

* **Array** The new array

## each(fn)

Iterate over a jargon instance, executing a function for each elements.
The function context is a jargon object wrapping the element itself.
###Example
```javascript
// add classname 'fuzz' on all p tags
jArgon('p').each(function() {
  this.addClassName('fuzz');
});
```

### Params:

* **Function** *fn* - The function which will be executed recursively

### Return:

* **jArgon** The jargon instance on which the method is called

## hasName(name)

Check if a jargon instance has a given element's name.
If the jargon instance contains multiple elements, an array will be return
containing a boolean for each elements
###Example
```javascript
jArgon('.current').hasName('div');
```

### Params:

* **String** *name* - The element name

### Return:

* **Array|Boolean** True if match, false otherwise

## hasClassName(className)

Check if a jargon instance has a given class name.
If the jargon instance contains multiple elements, an array will be return
containing a boolean for each elements
###Example
```javascript
jArgon('#nav-bar').hasClassName('hidden');
```

### Params:

* **String** *className* - The class name

### Return:

* **Array|Boolean** True if match, false otherwise

## hasSelector(selector)

Check if a jargon instance has a given selector
If the jargon instance contains multiple elements, an array will be return
containing a boolean for each elements
###Example
```javascript
jArgon('a').hasSelector('.foo[href="fuzz"]');
// Supported selectors are :
// '#foo', 'div', '.foo', '.foo[href]', 'div[href]', 'div.foo',
// 'div[href="bar"]', '.foo[href="fuzz"]'
```

### Params:

* **String** *selector* - The selector

### Return:

* **Array|Boolean** True if match, false otherwise

## getElementsByClassName(selector)

Get the child elements of a jargon instance which match a class name.
If the jargon instance contains multiple elements, the resulting
child elements are merged into a single array.
###Example
```javascript
var ulElem = jArgon('ul');
// return children li elements with class 'current'
ulElem.getElementsByClassName('li.current');
// Valid selectors are :
// 'div.foo' or '.foo' or 'foo'
```

### Params:

* **String** *selector* - The selector

### Return:

* **jArgon** jArgon object containing matching elements

## getElementsByAttribute(selector)

Get the child elements of a jargon instance which match an attribute.
If the jargon instance contains multiple elements, the resulting
child elements are merged into a single array.
###Example
```javascript
var artElem = jArgon('article');
// return children a elements with href="#"
artElem.getElementsByAttribute('a[href="#"]');
// Valid selectors are :
// 'a[href]' or '.foo[href]' or 'a[href="bar"]' or '.foo[href="bar"]'
```

### Params:

* **String** *selector* - The selector

### Return:

* **jArgon** jArgon object containing matching elements

## addClassName(className)

Add a class name to the elements of a jargon instance.
If the class name already present, do nothing.
```javascript
// Valid class name:
// 'foo'
```

### Params:

* **String** *className* - The class name

### Return:

* **jArgon** jArgon object with the updated elements

## removeClassName(className)

Remove a class name to the elements of a jargon instance.
If the class name not present, do nothing.
```javascript
// Valid class name:
// 'foo'
```

### Params:

* **String** *className* - The class name

### Return:

* **jArgon** jArgon object with the updated elements

## toggleClassName(className)

Toggle a class name on the elements of a jargon instance.
```javascript
// Valid class name:
// 'foo'
```

### Params:

* **String** *className* - The class name

### Return:

* **jArgon** jArgon object with the updated elements

## jArgon(selector)

###jArgon initializer
Use cases:
   * Query document's elements on a CSS selector chain and return
     a jArgon instance which wraps matching elements. *Based on a "document only bottom-up algorithm"*
   * Wrap a single HTMLElement or a NodeList into a jArgon instance.

If the selector mismatch or if the element is unvalid, an empty jArgon object is returned.
```javascript
var jargonObj;
// a valid selector chain:
jargonObj = jArgon('div > div.foo .bar .fuzz[bar] > a[href="javascript.html"] #jargon');
// elem is a valid HTMLElement
jargonObj = jArgon( elem );
// elems is a NodeList
jargonObj = jArgon( elems );
```

### Params:

* **String|HTMLElement|NodeList** *selector* - The selector

### Return:

* **jArgon** jArgon object containing matching elements or the passed element(s)

<!-- End jargon.js -->

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
<body>
    <script src='../resources/reflected-xss-and-xss-protection.js'></script>
    <script>testMixedHeader('filter', 'block');</script>
</body>
</html>


text:
import { Guid } from './../../shared/Utilities/Guid';
import { KeyCodes } from './../../shared/models/constants';
import { PortalResources } from './../../shared/models/portal-resources';
import { Component, OnChanges, SimpleChanges, Input, Output, ViewChild, ElementRef } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { TranslateService } from '@ngx-translate/core';

type Role = undefined | 'switch' | 'button';

type LabelFormt = undefined | 'name' | 'stateName' | 'nameAndStateName' | 'mergedStateNames';

@Component({
    selector: 'slide-toggle',
    templateUrl: './slide-toggle.component.html',
    styleUrls: ['./slide-toggle.component.scss']
})
export class SlideToggleComponent implements OnChanges {

    @Output() change = new Subject<boolean>();
    @Input() disabled: boolean = false;
    @Input() on: boolean = false;
    @Input() isCommand: boolean = false;
    @Input() name: string;
    @Input() stateNames: { on: string, off: string };

    // The inputs 'displayLabelFormat' and 'ariaLabelFormat' are used for indicating the way 'name' and 'stateNames' should be used to
    // construct 'displayLabel' and 'ariaLabel'. These settings may not be honored depending on the value of 'role' and whether 'name'
    // and/or 'stateNames' are defined. This is handeled in _updateLabelAndAriaAttributes().

    // Format definitions:
    //  name -> this.name [when applied to aria-label, ' toggle' is appended]
    //  --------- if 'this.stateNames' defined ---------
    //   stateName        -> this.on ? this.stateNames.on : this.stateNames.off
    //   nameAndStateName -> this.name + ": " (this.on ? this.stateNames.on : this.stateNames.off)
    //   mergedStateNames -> this.stateNames.off + "/" + this.stateNames.on [when applied to aria-lable, ' toggle' is appended]
    //  ------ if 'this.stateNames' not defined ------
    //   stateName        -> this.on ? this.stateNames.on : this.stateNames.off
    //   nameAndStateName -> this.name + ": " (this.on ? this.stateNames.on : this.stateNames.off)
    //   mergedStateNames -> this.stateNames.off + "/" + this.stateNames.on [when applied to aria-lable, ' toggle' is appended]

    @Input() displayLabelFormat: LabelFormt;

    //If role is 'switch', 'aria-label' should stay constant, so only 'name' and 'mergedStateNames' will be honored
    @Input() ariaLabelFormat: LabelFormt;

    // We're restricting the 'role' attribute to 'switch' or 'button'.
    // If the control is being used to perform an action, the parent should pass a value of true to the 'isCommand' input, so the 'button' role is used.
    // Otherwise, the parent should pass a value of false to the 'isCommand' input or not beind to it, so the 'switch' role is used.

    //  NOTE: Testing with NVDA screen reader revealed the following issues with the 'switch' role:
    //   - Reader does not state the role. Only the 'aria-label' value and the 'aria-checked' status are read.
    //   - Reader only states the 'aria-checked' status when the value is true ('checked'). When the value is false ('not checked'), the status is not read.
    //  These issues don't occur when the 'checkbox' role is used, but using this role would technically be inorrect based on the usage of this control.
    public role: Role;

    public ariaLabel: string;

    // The 'aria-checked' attribute is REQUIRED for 'switch' role.
    public ariaChecked: boolean = null;

    // If 'aria-pressed' attribute does not apply to the 'switch' role and is optional for the 'button' role.
    // We should not use it if we are updating 'aria-label' whenever a toggle happens.
    // We should use it if we are using a constant value for 'aria-pressed'.
    public ariaPressed: boolean = null;
    public displayLabel: string;

    @Input() id: string;

    private _initialized: boolean = false;

    @ViewChild('toggleContainer') toggleContainer: ElementRef;

    constructor(private _translateService: TranslateService) {
        this.id = Guid.newGuid();
    }

    ngOnChanges(changes: SimpleChanges) {
        // These properties will only be set once, in the first execution of ngOnChanges().
        this.role = this.role || (this.isCommand ? 'button' : 'switch');
        this.displayLabelFormat = this.displayLabelFormat || 'stateName';
        this.ariaLabelFormat = this.ariaLabelFormat || 'name';

        if (!this._initialized || !!changes['on']) {
            this._updateLabelAndAriaAttributes();
        }

        this._initialized = true;
    }

    private _updateLabelAndAriaAttributes() {
        const stateNames = this._getStateNames();
        const state = this.on ? 1 : 0;

        switch (this.displayLabelFormat) {
            case 'name':
                // Use name if present. Otherwise fallback to current state name
                this.displayLabel = this.name || stateNames[state];
                break;
            case 'stateName':
                this.displayLabel = stateNames[state];
                break;
            case 'nameAndStateName':
                // If name is not present, fallback to only the current state name
                this.displayLabel = (this.name ? this.name + ': ' : '') + stateNames[state];
                break;
            case 'mergedStateNames':
                // If default state names are being used, fallback to name, then to current state name
                this.displayLabel = !stateNames.isFallback ? stateNames.combined : this.name || (stateNames[state]);
                break;
            default:
                break;
        }

        let ariaLabel: string = '';
        let ariaChecked: boolean = null;
        let ariaPressed: boolean = null;
        let addSuffix = false;

        if (this.role === 'button') {
            ariaPressed = null;
            switch (this.ariaLabelFormat) {
                case 'name':
                    // Use name if present. Otherwise fallback to current state name
                    if (this.name) {
                        addSuffix = true;
                        ariaLabel = this.name;
                        ariaPressed = this.on;
                    }
                    else {
                        ariaLabel = stateNames[state];
                    }
                    break;
                case 'stateName':
                    ariaLabel = stateNames[state];
                    break;
                case 'nameAndStateName':
                    // If name is not present, fallback to only the current state name
                    ariaLabel = (this.name ? this.name + ': ' : '') + stateNames[state];
                    break;
                case 'mergedStateNames':
                    // If default state names are being used, fallback to name, then to current state name
                    if (!stateNames.isFallback) {
                        addSuffix = true;
                        ariaLabel = stateNames.combined;
                        ariaPressed = this.on;
                    } else if (this.name) {
                        addSuffix = true;
                        ariaLabel = this.name;
                        ariaPressed = this.on;
                    } else {
                        ariaLabel = stateNames[state];
                    };
                    break;
                default:
                    break;
            }
        } else if (this.role === 'switch') {
            ariaChecked = this.on;
            switch (this.ariaLabelFormat) {
                case 'name':
                    // Use name if present. Otherwise fallback to merged state names
                    addSuffix = true;
                    ariaLabel = this.name || stateNames.combined;
                    break;
                case 'mergedStateNames':
                    // This doesn't really make sense if the default state names are being used, so just show that state name
                    addSuffix = true;
                    ariaLabel = stateNames.combined;
                    break;
                default:
                    break;
            }
        }

        this.ariaLabel = ariaLabel + (addSuffix ? ' toggle' : '');
        this.ariaPressed = ariaPressed;
        this.ariaChecked = ariaChecked;
    }

    private _getStateNames(): { [key: number]: string, isFallback: boolean, combined: string } {
        let stateNames: { [key: number]: string, isFallback: boolean, combined: string } = {
            isFallback: !this.stateNames || !this.stateNames.on || !this.stateNames.off,
            combined: ''
        };
        stateNames[0] = stateNames.isFallback ? this._translateService.instant(PortalResources.disabled) : this.stateNames.off;
        stateNames[1] = stateNames.isFallback ? this._translateService.instant(PortalResources.enabled) : this.stateNames.on;
        stateNames.combined = stateNames[0] + '/' + stateNames[1];

        return stateNames;
    }

    onClick(event: MouseEvent) {
        this._toggle();
    }

    onKeyPress(event: KeyboardEvent) {
        if (event.keyCode === KeyCodes.space) {
            this._toggle();
            event.preventDefault();
        }
    }

    private _toggle() {
        if (!this.disabled) {
            this.on = !this.on;
            this._updateLabelAndAriaAttributes();
            this.change.next(this.on);
        }
    }
}


text:
from pyface.tasks.api import Task, TaskLayout, PaneItem
from pyface.tasks.action.api import DockPaneToggleGroup, SMenuBar, \
    SMenu, SToolBar, TaskAction
from pyface.api import ConfirmationDialog, FileDialog, \
    ImageResource, YES, OK, CANCEL
from traits.api import on_trait_change

# Local imports.
from example_panes import PythonEditorPane, PythonScriptBrowserPane

class ExampleTask(Task):
    """ A simple task for editing Python code.
    """

    #### Task interface #######################################################

    id = 'example.example_task'
    name = 'Python Script Editor'

    #default_layout = TaskLayout(
    #    left=PaneItem('example.python_script_browser_pane'))

    menu_bar = SMenuBar(SMenu(TaskAction(name='Open...', method='open',
                                         accelerator='Ctrl+O'),
                              TaskAction(name='Save', method='save',
                                         accelerator='Ctrl+S'),
                              id='File', name='&File'),
                        SMenu(DockPaneToggleGroup(),
                              id='View', name='&View'))

    tool_bars = [ SToolBar(TaskAction(method='open',
                                      tooltip='Open a file',
                                      image=ImageResource('document_open')),
                           TaskAction(method='save',
                                      tooltip='Save the current file',
                                      image=ImageResource('document_save'))) ]

    ###########################################################################
    # 'Task' interface.
    ###########################################################################

    def _default_layout_default(self):
        return TaskLayout(
            left=PaneItem('example.python_script_browser_pane'))

    def activated(self):
        """ Overriden to set the window's title.
        """
        filename = self.window.central_pane.editor.path
        self.window.title = filename if filename else 'Untitled'

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        return PythonEditorPane()

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        browser = PythonScriptBrowserPane()
        handler = lambda: self._open_file(browser.selected_file)
        browser.on_trait_change(handler, 'activated')
        return [ browser ]

    ###########################################################################
    # 'ExampleTask' interface.
    ###########################################################################

    def open(self):
        """ Shows a dialog to open a file.
        """
        dialog = FileDialog(parent=self.window.control, wildcard='*.py')
        if dialog.open() == OK:
            self._open_file(dialog.path)

    def save(self):
        """ Attempts to save the current file, prompting for a path if
            necessary. Returns whether the file was saved.
        """
        editor = self.window.central_pane.editor
        try:
            editor.save()
        except IOError:
            # If you are trying to save to a file that doesn't exist, open up a
            # FileDialog with a 'save as' action.
            dialog = FileDialog(parent=self.window.control,
                                action='save as', wildcard='*.py')
            if dialog.open() == OK:
                editor.save(dialog.path)
            else:
                return False
        return True

    ###########################################################################
    # Protected interface.
    ###########################################################################

    def _open_file(self, filename):
        """ Opens the file at the specified path in the editor.
        """
        if self._prompt_for_save():
            self.window.central_pane.editor.path = filename
            self.activated()

    def _prompt_for_save(self):
        """ Prompts the user to save if necessary. Returns whether the dialog
            was cancelled.
        """
        if self.window.central_pane.editor.dirty:
            message = 'The current file has unsaved changes. ' \
                      'Do you want to save your changes?'
            dialog = ConfirmationDialog(parent=self.window.control,
                                        message=message, cancel=True,
                                        default=CANCEL, title='Save Changes?')
            result = dialog.open()
            if result == CANCEL:
                return False
            elif result == YES:
                if not self.save():
                    return self._prompt_for_save()
        return True

    @on_trait_change('window:closing')
    def _prompt_on_close(self, event):
        """ Prompt the user to save when exiting.
        """
        if not self._prompt_for_save():
            event.veto = True


text:
<?php

namespace ZendTest\Filter;

use Zend\Filter\DateTimeFormatter;
use DateTime;

/**
 * @group      Zend_Filter
 */
class DateTimeFormatterTest extends \PHPUnit_Framework_TestCase
{
    protected $defaultTimezone;

    public function setUp()
    {
        $this->defaultTimezone = date_default_timezone_get();
    }

    public function tearDown()
    {
        date_default_timezone_set($this->defaultTimezone);
    }

    public function returnUnfilteredDataProvider()
    {
        return array(
            array(null),
            array(''),
            array(new \stdClass()),
            array(array(
                '1',
                -1
            )),
            array(0.53)
        );
    }

    /**
     * @dataProvider returnUnfilteredDataProvider
     * @return void
     */
    public function testReturnUnfiltered($input)
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();

        $this->assertEquals($input, $filter($input));
    }

    public function testFormatterFormatsZero()
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();
        $result = $filter->filter(0);
        $this->assertEquals('1970-01-01T00:00:00+0000', $result);
    }

    public function testDateTimeFormatted()
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();
        $result = $filter->filter('2012-01-01');
        $this->assertEquals('2012-01-01T00:00:00+0000', $result);
    }

    public function testDateTimeFormattedWithAlternateTimezones()
    {
        $filter = new DateTimeFormatter();

        date_default_timezone_set('Europe/Paris');

        $resultParis = $filter->filter('2012-01-01');
        $this->assertEquals('2012-01-01T00:00:00+0100', $resultParis);

        date_default_timezone_set('America/New_York');

        $resultNewYork = $filter->filter('2012-01-01');
        $this->assertEquals('2012-01-01T00:00:00-0500', $resultNewYork);
    }

    public function testSetFormat()
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();
        $filter->setFormat(DateTime::RFC1036);
        $result = $filter->filter('2012-01-01');
        $this->assertEquals('Sun, 01 Jan 12 00:00:00 +0000', $result);
    }

    public function testFormatDateTimeFromTimestamp()
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();
        $result = $filter->filter(1359739801);
        $this->assertEquals('2013-02-01T17:30:01+0000', $result);
    }

    public function testAcceptDateTimeValue()
    {
        date_default_timezone_set('UTC');

        $filter = new DateTimeFormatter();
        $result = $filter->filter(new DateTime('2012-01-01'));
        $this->assertEquals('2012-01-01T00:00:00+0000', $result);
    }

    public function testInvalidArgumentExceptionThrownOnInvalidInput()
    {
        $this->setExpectedException('Zend\Filter\Exception\InvalidArgumentException');

        $filter = new DateTimeFormatter();
        $result = $filter->filter('2013-31-31');
    }
}


text:
<?php
    //Php MySqlDB-Data
    require_once('lib/conf.php');

    //Include header
    include("header.php");
?>

        Input block height
        <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">

            <input type="number" name="height" min="0">

            <input type="submit" value="Get">
        </form>

        Input block hash
        <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">

            <input type="text" name="hash" size="90">

            <input type="submit" value="Get">
        </form>

<?php
    //Get the user input and display prime chain
    getPrimeChain();

    //Include footer
    include("footer.php");
?>

<?php
    function getPrimeChain(){

        echo("
");

        //Connect to DB
        $con = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PW, MYSQL_DB);
        //If connection fails
        if(!$con){
            die("Connection to Database not established");
        }

        $sql="
        SELECT `value` FROM `numinos_prime_data`
        WHERE `info`='blocks';
        ";

        //Retrieve block number of most current block
        $primeBlockCount = mysqli_fetch_array(mysqli_query($con, $sql));

        $height = NULL;
        $hash = NULL;

        //Check for correctness and safeness of user input
        if(isset($_GET["height"])){
            $height = $_GET["height"];
            if($height > $primeBlockCount["value"] || $height < 0 || is_nan(floatval($height)) || $height == NULL){
                echo "404 - Block not found";
                return;
            }
        }
        if(isset($_GET["hash"])){
            $hash = $_GET["hash"];
            if(strlen($hash) != 64 || !ctype_xdigit($hash)){
                echo "404 - Block not found";
                return;
            }else{

                $sql="
                SELECT `index` FROM `numinos_prime_blockhashes`
                 WHERE `hash`='" . $hash . "';
                ";

                //Retrieve block number of current hash block
                $primeHashBlock = mysqli_fetch_array(mysqli_query($con, $sql));

                //Check if hash exists in the database
                if($primeHashBlock["index"] == NULL){
                    echo "404 - Block not found";
                    return;
                }else{
                    //If it does, set height to hashes height
                    $height = $primeHashBlock["index"];
                }
            }
        }

        ////If none of the two variables are set - return nothing
        if(isset($_GET["height"]) == FALSE && isset($_GET["hash"]) == FALSE){
            //Set height to latest block to show
            $height = $primeBlockCount["value"] - 1;
        }

        //If database is reachable and height is not null
        if($con && isset($height)){
            //If primechainerPath points to correct exe
            if(file_exists(PRIMECHAINERPATH)){

                //Get primeorigin, primechain and length for given height
                $sql = "
                SELECT `hash`, `primeorigin`, `primechain`, `length` FROM `numinos_prime_blockhashes`
                WHERE `index`='" . $height . "';
                ";

                //Get prime origin and prime chain type to parse to external primechain calculator primechainer.exe
                $primeDataArray = mysqli_fetch_array(mysqli_query($con, $sql));
                $primeChainType = explode(".", $primeDataArray["primechain"]);

                //array_reverse because primechains are in reverse order
                $primeChainArray = array_reverse(explode(",", shell_exec(PRIMECHAINERPATH . " " . $primeDataArray["primeorigin"] . " " . $primeChainType[0] . " " . $primeDataArray["length"])));

                //Table to wrap navigation buttons and height/hash table
                echo("

");

                //Previous Block button
                echo("
                <form action=\"" . htmlentities($_SERVER['PHP_SELF']) . "\" method=\"get\">

                <input type=\"hidden\" name=\"height\" value=\"" . ($height - 1) . "\">

                <input type=\"submit\" value=\"Previous\">

                </select>
                </form>
                ");

                //Chain height/hash table
                echo("

                  Height
                  Hash

                  " . $height . "
                  " . $primeDataArray["hash"] . "

");

                //Next Block button
                echo("
                <form action=\"" . htmlentities($_SERVER['PHP_SELF']) . "\" method=\"get\">

                <input type=\"hidden\" name=\"height\" value=\"" . ($height + 1) . "\">

                <input type=\"submit\" value=\"    Next    \">

                </select>
                </form>
                ");

                //END Table to wrap navigation buttons and height/hash table
                echo("

");

                //Chain info table
                echo("

                  Origin
                  Type
                  Length

                  " . $primeDataArray["primeorigin"] . "
                  " . substr($primeChainType[0], 0 , 3) . "
                  " . $primeDataArray["length"] . "

");

                //Chain data table
                echo("

                  Chain

");

                foreach(array_filter($primeChainArray) as $primeChainPiece){
                    echo("
" . $primeChainPiece . "
");
                }

                echo("
");

                echo("
");
            }
        }
    }
?>


text:
{
  if (name === helperName) return false;
  return original(name);
}


text:
GameObject::GameObject(glm::vec3 initPosition, Model model, char* texturePath)
{
	shaderLocations = ShaderLocations();
	position = initPosition;
	scaler = glm::vec3(1.0f, 1.0f, 1.0f);
	velocity = glm::vec3(0.0f, 0.0f, 0.0f);
	direction = None;
	boundingBoxOffset = glm::vec3(0.0f, 0.0f, 0.0f);
	boundingBox = AABB(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0, 0, 0));
	translationMatrix = glm::translate(translationMatrix, initPosition);
	rotationMatrix = glm::mat4(1.0f);
	scaleMatrix = glm::mat4(1.0f);
	modelMatrix = translationMatrix * rotationMatrix * scaleMatrix;
	this->model = model;
	LoadTextures(texturePath);
}
GameObject::~GameObject()
{

}

// Public Methods.
// Main object methods.
void GameObject::Update()
{
	Translate(position);
	scaler = glm::vec3(scaleModifier, scaleModifier, scaleModifier);
	Scale(scaler);
	modelMatrix = translationMatrix * rotationMatrix * scaleMatrix;
}
void GameObject::Update(double simLength, std::vector<GameObject*> &objectList)
{
	Translate(position);
	scaler = glm::vec3(scaleModifier, scaleModifier, scaleModifier);
	Scale(scaler);
	modelMatrix = translationMatrix * rotationMatrix * scaleMatrix;
}
void GameObject::Draw()
{
	for (int i = 0; i < model.meshes.size(); i++)
	{
		glBindVertexArray(model.meshes[i].vertexArrayObject);
		glUniformMatrix4fv(shaderLocations.modelMatrixUniform, 1, GL_FALSE, glm::value_ptr(modelMatrix));
		glUniform1i(shaderLocations.hasTextureUniform, model.meshes[i].hasTextures);
		if (model.meshes[i].hasTextures)
		{
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, textureID);
			glUniform1i(shaderLocations.textureSamplerUniform, 0);
		}
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.meshes[i].indicesBufferObject);
		glDrawElements(GL_TRIANGLES, model.meshes[i].indices.size(), GL_UNSIGNED_INT, (void*)0);
		glBindVertexArray(0);
		if (model.meshes[i].hasTextures)
		{
			glBindTexture(GL_TEXTURE_2D, 0);
		}
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	}
}

// Transformation methods.
void GameObject::Translate(glm::vec3 translation)
{
	translationMatrix = glm::translate(glm::mat4(1.0f), translation);
}
void GameObject::Rotate(float rotationAngle, glm::vec3 rotationAxis)
{
	rotationMatrix = glm::rotate(glm::mat4(1.0f), glm::radians(rotationAngle), rotationAxis);
}
void GameObject::Scale(glm::vec3 scale)
{
	scaleMatrix = glm::scale(glm::mat4(1.0f), scale);
}

// Load Assets.
void GameObject::LoadTextures(char* texturePath)
{
	if (texturePath != "")
	{
		SDL_Surface* image = SDL_LoadBMP(texturePath);
		if (image == NULL)
		{
			std::cout << "Image loading (for texture) failed." << std::endl;
			SDL_Quit();
			exit(1);
		}

		glGenTextures(1, &textureID); //generate a texture ID and store it
		glBindTexture(GL_TEXTURE_2D, textureID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);

		glBindTexture(GL_TEXTURE_2D, 0);
		SDL_FreeSurface(image);
		std::cout << "Texture loaded: " << texturePath << std::endl;
	}
}

// OpenGL Initialises.
void GameObject::Init_ShaderObjects(ShaderLocations shaderLocations)
{
	this->shaderLocations = shaderLocations;
	Init_Buffers();
	Init_VertexArray();
}
void GameObject::Init_Buffers(void)
{
	for (int i = 0; i < model.meshes.size(); i++)
	{
		if (model.meshes[i].vertexPositions.size() > 0)
		{
			glGenBuffers(1, &model.meshes[i].vertexBufferObject);
			glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].vertexBufferObject);
			glBufferData(GL_ARRAY_BUFFER, model.meshes[i].vertexPositions.size() * sizeof(glm::vec3), &model.meshes[i].vertexPositions[0], GL_STATIC_DRAW);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

		}
		if (model.meshes[i].indices.size() > 0)
		{
			glGenBuffers(1, &model.meshes[i].indicesBufferObject);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.meshes[i].indicesBufferObject);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.meshes[i].indices.size() * sizeof(unsigned int), &model.meshes[i].indices[0], GL_STATIC_DRAW);
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}
		if (model.meshes[i].colourData.size() > 0)
		{
			glGenBuffers(1, &model.meshes[i].colourBufferObject);
			glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].colourBufferObject);
			glBufferData(GL_ARRAY_BUFFER, model.meshes[i].colourData.size() * sizeof(glm::vec3), &model.meshes[i].colourData[0], GL_STATIC_DRAW);
		}

		if (model.meshes[i].uvs.size() > 0)
		{
			glGenBuffers(1, &model.meshes[i].uvBufferObject);
			glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].uvBufferObject);
			glBufferData(GL_ARRAY_BUFFER, model.meshes[i].uvs.size() * sizeof(glm::vec2), &model.meshes[i].uvs[0], GL_STATIC_DRAW);
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}
		std::cout << "Buffers OK! VBO GLuint: " << model.meshes[i].vertexBufferObject << ", IBO GLuint: " << model.meshes[i].indicesBufferObject << ", UBO GLuint: "<< model.meshes[i].uvBufferObject <<std::endl;
	}
}
void GameObject::Init_VertexArray()
{
	for (int i = 0; i < model.meshes.size(); i++)
	{
		glGenVertexArrays(1, &model.meshes[i].vertexArrayObject);			// Create a Vertex Array Object
		std::cout << "Vertex Array OK! GLuint: " << model.meshes[i].vertexArrayObject << std::endl;
		glBindVertexArray(model.meshes[i].vertexArrayObject);				// Make the just created VAO the active one.

		glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].vertexBufferObject);	// Bind positionBufferObject.
		glVertexAttribPointer(shaderLocations.vertexPositionAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);	// Specify that position data contains four floats per vertex, and goes into attribute index positionLocation

		glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].colourBufferObject);
		glVertexAttribPointer(shaderLocations.colourAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);

		if (model.meshes[i].hasTextures)
		{
			glBindBuffer(GL_ARRAY_BUFFER, model.meshes[i].uvBufferObject);
			glVertexAttribPointer(shaderLocations.uvAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
		}

		glEnableVertexAttribArray(shaderLocations.vertexPositionAttrib);		// Enable attribute at index positionLocation.
		glEnableVertexAttribArray(shaderLocations.colourAttrib);
		if (model.meshes[i].hasTextures)
		{
			glEnableVertexAttribArray(shaderLocations.uvAttrib);
		}

		glBindVertexArray(0);	// Unbind the VAO so we can't change it.

		// Clean up.
		glDisableVertexAttribArray(shaderLocations.vertexPositionAttrib); //disable vertex attribute at index positionLocation.
		glDisableVertexAttribArray(shaderLocations.colourAttrib);
		if (model.meshes[i].hasTextures)
		{
			glDisableVertexAttribArray(shaderLocations.uvAttrib);
		}
		glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind array buffer.
	}
}

void GameObject::ChangeModel(Model newModel, float newScaleModifier, ShaderLocations shaderLocations, char* newTexture)
{
	this->model = newModel;
	this->scaleModifier = newScaleModifier;
	Init_ShaderObjects(shaderLocations);
	LoadTextures(newTexture);
}


text:
Compiled example
----------------
![Example](geometry-5.png)


text:
import React from 'react';
import { Route, Switch } from 'react-router';

import Home from 'containers/home';
import Second from 'containers/second';

export default () => (
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/second" component={Second} />
  </Switch>
);


text:
<?php
namespace Slender\Base;

use Slender\Interfaces\ModulePathProviderInterface;

class SlenderModule implements ModulePathProviderInterface
{

    /**
     * Returns path to module root
     *
     * @return string Path
     */
    public static function getModulePath()
    {
        return dirname(__FILE__);
    }
}


text:
require 'vk-ruby'

module OaPerson
  module Streams
    class Vkontakte < Stream

      # Vkontakte feed
      # options are:
      #    :owner_id => 'user_id',
      #    :message => 'Updating via twitter',
      #    :attachment => 'link'
      #
      def publish(options = {})
        options = {:owner_id => options[:user_id], :message => options[:message], :attachment => options[:link]}
        client.wall.post(options)
      end

      def friends
        options = {:uid => uid, :fields => "uid,first_name,last_name", :timestamp => Time.now.getutc.to_i, :random => Time.now.to_i}
        client.friends.get(options)
      end

      # Vkontakte post photo
      # 1) photos.getUploadServer
      # 2) POST-запрос (поля file1-file5)
      # 3) photos.save
      #
      def post_photo(options = {})

      end

      def image_by_type(type)
        return nil if image.blank?
        image
      end

      def profile_photos(user_id=uid)
        options = {:owner_id => user_id, :count => 30}
        photos = client.photos.getAll(options)
        photos.shift
        photos
      end

      def profile_image_source(options)
        #client.getProfiles(:uids => uid, :fields => 'photo_big,photo,photo_medium,photo_rec').inspect
        options = {:uid => uid}.merge(options)
        client.photos.get(options)
      end

      protected

        def connect
          begin
            #OaPerson::VkClient.new(uid, access_token, your_id, 'your_secret')
            app = ::VK::Standalone.new(:app_id => OaPerson.vkontakte_app_id, :app_secret => OaPerson.vkontakte_app_secret)
            app.access_token = access_token
            app
          rescue Exception => e
            Rails.logger.error(e)
            return nil
          end
        end
    end
  end
end


text:
import { NgModule } from '@angular/core';
import { SmStZoomDirective } from './directive/zoom.directive';
var SmStUtilityModule = /** @class */ (function () {
    function SmStUtilityModule() {
    }
    SmStUtilityModule.decorators = [
        { type: NgModule, args: [{
                    declarations: [
                        SmStZoomDirective
                    ],
                    imports: [],
                    providers: [],
                    bootstrap: [],
                    exports: [SmStZoomDirective]
                },] },
    ];
    /** @nocollapse */
    SmStUtilityModule.ctorParameters = function () { return []; };
    return SmStUtilityModule;
}());
export { SmStUtilityModule };
//# sourceMappingURL=utility.module.js.map


text:
@interface WYNewsMainViewController ()

@end

@implementation WYNewsMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setChildViewControllers];

}

- (void)setChildViewControllers{
    UIViewController *newsVC = [self addChildControllerWithClsName:@"WYHomeViewController" title:@"首页" imageName:@"tabbar_news" selectedImageName:@"tabbar_news_highlighted"];
    UIViewController *importantNewsVC = [self addChildControllerWithClsName:@"UIViewController" title:@"要闻" imageName:@"tabbar_icon_importantNews_normal" selectedImageName:@"tabbar_icon_importantNews_highlight"];
    UIViewController *liveVC = [self addChildControllerWithClsName:@"UIViewController" title:@"直播" imageName:@"tabbar_icon_live_normal" selectedImageName:@"tabbar_icon_live_highlight"];
    UIViewController *videoVC = [self addChildControllerWithClsName:@"UIViewController" title:@"视频" imageName:@"tabbar_video" selectedImageName:@"tabbar_video_highlighted"];
    UIViewController *mineVC = [self addChildControllerWithClsName:@"UIViewController" title:@"我" imageName:@"tabbar_icon_me_normal" selectedImageName:@"tabbar_icon_me_highlight"];

    self.viewControllers = @[newsVC,importantNewsVC,liveVC,videoVC,mineVC];

}

- (UIViewController *)addChildControllerWithClsName:(NSString *)clsName title:(NSString *)title imageName:(NSString *)imgName selectedImageName:(NSString *)selImageName{
    Class cls = NSClassFromString(clsName);

    NSAssert(cls != nil, @"传入错误的控制器名称");

    UIViewController *vc = [cls new];

    vc.view.backgroundColor = [UIColor whiteColor];

    vc.title = title;
    vc.tabBarItem.image = [[UIImage imageNamed:imgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];

    return nav;
}

@end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.diplom.profile.histogramecomparingbalances;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author valik
 */
public class HistogrameComparingBalances extends JDialog {
     /**
      * Creates a new demo instance.
      *
      * @param title  the frame title.
      */
     public HistogrameComparingBalances () {

         CategoryDataset dataset = createDataset();
         JFreeChart chart = createChart(dataset);
         ChartPanel chartPanel = new ChartPanel(chart, false);
         chartPanel.setPreferredSize(new Dimension(600, 370));
         setContentPane(chartPanel);
     }

     /**
      * Returns a sample dataset.
      *
      * @return The dataset.
      */
     private static CategoryDataset createDataset() {

         List<AllUsersInfo> allUsersInfoList = new ArrayList<AllUsersInfo>();

         allUsersInfoList = AllUsersDao.getInstance().findAllUsersInfo();

         // row keys...
         String series1 = "Users";
         // create the dataset...
         DefaultCategoryDataset dataset = new DefaultCategoryDataset();

         for (int i = 0; i < allUsersInfoList.size(); i++) {
            dataset.addValue(allUsersInfoList.get(i).getBalance(), series1, allUsersInfoList.get(i).getName());
         }

         return dataset;
     }

     /**
      * Creates a sample chart.
      *
      * @param dataset  the dataset.
      *
      * @return The chart.
      */
    private static JFreeChart createChart(CategoryDataset dataset) {
         // create the chart...
        JFreeChart chart = ChartFactory.createBarChart(
             "Статистика",              // chart title
             "Профиль",                   // domain axis label
             "Баланс",                   // range axis label
             dataset,                   // data
             PlotOrientation.VERTICAL,  // orientation
             true,                      // include legend
             true,                      // tooltips?
             false                      // URLs?
        );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

         // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

         // get a reference to the plot for further customisation...
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);

         // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

         // disable bar outlines...
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);

         // set up gradient paints for series...
        GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue,
                0.0f, 0.0f, new Color(0, 0, 64));

        renderer.setSeriesPaint(0, gp0);

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
                 CategoryLabelPositions.createUpRotationLabelPositions(
                         Math.PI / 6.0));
         // OPTIONAL CUSTOMISATION COMPLETED.

        return chart;
    }
}


text:
package com.thaiopensource.relaxng.jaxp;

import com.thaiopensource.validation.LSInputImpl;
import com.thaiopensource.validation.SchemaFactory2;
import com.thaiopensource.xml.sax.DraconianErrorHandler;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.validation.ValidatorHandler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;

/**
 *  Test SchemaFactoryImpl.
 */
public abstract class SchemaFactoryImplTest {
  protected final Class<? extends SchemaFactory2> factoryClass;
  private static int filenameIndex = 0;

  protected SchemaFactoryImplTest(Class<? extends SchemaFactory2> factoryClass) {
    this.factoryClass = factoryClass;
  }

  protected SchemaFactory2 factory() {
    try {
      return factoryClass.newInstance();
    }
    catch (InstantiationException e) {
    }
    catch (IllegalAccessException e) {
    }
    throw new AssertionError();
  }

  @Test(dataProvider = "valid")
  public void testValidCharStream(String schemaString, String docString) throws SAXException, IOException {
    factory().newSchema(charStreamSource(schemaString)).newValidator().validate(charStreamSource(docString));
  }

  @Test(dataProvider = "valid")
  public void testValidFile(String schemaString, String docString) throws SAXException, IOException {
    factory().newSchema(fileSource(schemaString)).newValidator().validate(fileSource(docString));
  }
  @DataProvider(name = "valid")
  protected Object[][] valid() {
    return new Object[][] {
            { createSchema("doc"), "<doc/>" },
            { element("doc", new String[] { attribute("att") }),
                    "<doc att='val'/>" }
    };
  }

  private static SAXSource charStreamSource(String s) {
    return new SAXSource(new InputSource(new StringReader(s)));
  }

  private static synchronized Source fileSource(String s) throws IOException {
    final File file = new File("t" + filenameIndex++);
    Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    w.write(s);
    w.close();
    return new StreamSource(file);
  }

  static private class CountErrorHandler extends DraconianErrorHandler {
    int errorCount = 0;

    public void error(SAXParseException e) throws SAXException {
      ++errorCount;
    }
  }

  @Test
  public void testErrorHandlerNoThrow() throws SAXException, IOException {
    SchemaFactory f = factory();
    Validator v = f.newSchema(charStreamSource(createSchema("doc"))).newValidator();
    CountErrorHandler eh = new CountErrorHandler() {
      public void error(SAXParseException e) throws SAXException {
        if (errorCount == 0)
          Assert.assertEquals(e.getLineNumber(), 2);
        super.error(e);
      }
    };
    v.setErrorHandler(eh);
    Assert.assertSame(v.getErrorHandler(), eh);
    v.validate(charStreamSource("<doc>\n<bad/></doc>"));
    Assert.assertTrue(eh.errorCount > 0);
  }

  @Test(expectedExceptions = { RuntimeException.class })
  public void testErrorHandlerThrowRuntime() throws SAXException, IOException {
    SchemaFactory f = factory();
    Validator v = f.newSchema(charStreamSource(createSchema("doc"))).newValidator();
    v.setErrorHandler(new DraconianErrorHandler() {
      public void error(SAXParseException e) throws SAXException {
        Assert.assertEquals(e.getLineNumber(), 2);
        throw new RuntimeException();
      }
    });
    v.validate(charStreamSource("<doc>\n<bad/></doc>"));
    throw new AssertionError();
  }

  static class MySAXException extends SAXException { }

  @Test(expectedExceptions = { MySAXException.class })
  public void testErrorHandlerThrowSAX() throws SAXException, IOException {
    SchemaFactory f = factory();
    Validator v = f.newSchema(charStreamSource(createSchema("doc"))).newValidator();
    v.setErrorHandler(new DraconianErrorHandler() {
      public void error(SAXParseException e) throws SAXException {
        Assert.assertEquals(e.getLineNumber(), 2);
        throw new MySAXException();
      }
    });
    v.validate(charStreamSource("<doc>\n<bad/></doc>"));
    throw new AssertionError();
  }

  @Test
  public void testInstanceResourceResolver() throws SAXException, IOException {
    SchemaFactory f = factory();
    Validator v = f.newSchema(charStreamSource(element("doc", element("inner")))).newValidator();
    Assert.assertNull(v.getResourceResolver());
    LSResourceResolver rr = new LSResourceResolver() {
      public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
        // In Java 5 Xerces absolutized the systemId relative to the current directory
        int slashIndex = systemId.lastIndexOf('/');
        if (slashIndex >= 0)
          systemId = systemId.substring(slashIndex + 1);
        Assert.assertEquals(systemId, "e.xml");
        Assert.assertEquals(type, "http://www.w3.org/TR/REC-xml");
        LSInput in = new LSInputImpl();
        in.setStringData("<inner/>");
        return in;
      }
    };
    v.setResourceResolver(rr);
    Assert.assertSame(v.getResourceResolver(), rr);
    v.validate(charStreamSource("<!DOCTYPE doc [ <!ENTITY e SYSTEM 'e.xml'> ]><doc>&e;</doc>"));
  }

  @Test
  public void testSchemaResourceResolver() throws SAXException, IOException {
    SchemaFactory f = factory();
    Assert.assertNull(f.getResourceResolver());
    LSResourceResolver rr = new LSResourceResolver() {
      public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
        Assert.assertEquals(systemId, "myschema");
        Assert.assertEquals(type, getLSType());
        Assert.assertNull(baseURI);
        Assert.assertNull(namespaceURI);
        Assert.assertNull(publicId);
        LSInput in = new LSInputImpl();
        in.setStringData(createSchema("doc"));
        return in;
      }
    };
    f.setResourceResolver(rr);
    Assert.assertSame(f.getResourceResolver(), rr);
    Validator v = f.newSchema(charStreamSource(externalRef("myschema"))).newValidator();
    v.validate(charStreamSource("<doc/>"));
  }

  @Test(expectedExceptions = { UnsupportedOperationException.class })
  public void testNewSchemaNoArgs() throws SAXException {
    factory().newSchema();
  }

  @DataProvider(name = "supportedFeatures")
  Object[][] createSupportedFeatures() {
    return new Object[][] {
            { XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.FALSE }
    };
  }
  @Test(dataProvider = "supportedFeatures")
  public void testSupportedFeatures(String feature, Boolean defaultValueObj) throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    boolean defaultValue = defaultValueObj;
    Assert.assertEquals(f.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), defaultValue);
    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !defaultValue);
    Assert.assertEquals(f.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), !defaultValue);
  }

  @Test(dataProvider = "supportedFeatures")
  public void testFeatureInheritance(String feature, Boolean defaultValueObj)
          throws SAXException, SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    boolean defaultValue = defaultValueObj;
    Assert.assertEquals(f.getFeature(feature), defaultValue);
    f.setFeature(feature, !defaultValue);
    ValidatorHandler vh = f.newSchema(charStreamSource(createSchema("doc"))).newValidatorHandler();
    // the docs say that only properties are inherited by the ValidatorHandler
    Assert.assertEquals(vh.getFeature(feature), defaultValue);
  }

  @Test(expectedExceptions = { SAXNotRecognizedException.class })
  public void testUnrecognizedGetFeature() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.getFeature("http://thaiopensource.com/features/no-such-feature");
    throw new AssertionError();
  }

  @Test(expectedExceptions = { SAXNotRecognizedException.class })
  public void testUnrecognizedSetFeature() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.setFeature("http://thaiopensource.com/features/no-such-feature", false);
    throw new AssertionError();
  }

  @Test(expectedExceptions = { NullPointerException.class })
  public void testNullGetFeature() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.getFeature(null);
    throw new AssertionError();
  }

  @Test(expectedExceptions = { NullPointerException.class })
  public void testNullSetFeature() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.setFeature(null, true);
    throw new AssertionError();
  }

  @Test(expectedExceptions = { SAXNotRecognizedException.class })
  public void testUnrecognizedSetProperty() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.setProperty("http://thaiopensource.com/properties-no-such-property", null);
    throw new AssertionError();
  }

  @Test(expectedExceptions = { SAXNotRecognizedException.class })
  public void testUnrecognizedGetProperty() throws SAXNotRecognizedException, SAXNotSupportedException {
    SchemaFactory f = factory();
    f.getProperty("http://thaiopensource.com/properties/no-such-property");
    throw new AssertionError();
  }

  private String createSchema(String rootElement) {
    return element(rootElement);
  }

  private String element(String name) {
    return element(name, new String[] { });
  }

  private String element(String name, String contentPattern) {
    return element(name, new String[] { contentPattern });
  }
  abstract protected String element(String name, String[] contentPatterns);
  abstract protected String attribute(String name);
  abstract protected String externalRef(String uri);
  abstract protected String getLSType();
}


text:
/*jshint esnext:true */

var RedisStore = require("./redis_store"),
    redis = require("redis"),
    debug = require("debug")("koa-cache:middleware");

var CacheMiddleware = function(options) {
  if(!(this instanceof CacheMiddleware)) {
    return new CacheMiddleware(options);
  }
  var client;
  options = options || {};
  if(options.redis) {
    client = redis.createClient(options.redis.port, options.redis.host, options.redis.clientOptions);
  } else {
    client = redis.createClient();
  }
  // overwrite option hash
  options.redis = client;
  // create the store instance
  this.store = new RedisStore(options);
};

cache = CacheMiddleware.prototype;

cache.bind = function(app) {

  debug("bind app");

  var self = this;

  app.context.cache = function*(key, value) {
    if(!key) {//get cache by session key
      key = this.cacheKey();
      debug("get cache in session %s", key);
      return key ? (yield self.store.get(key)) : null;
    }
    if(value) {//setter
      debug("save cache explictly");
      this.cacheKey(key);
      yield self.store.set(key, value);
    } else {
      debug("read cache %s", key);
      yield self.store.get(key);
    }
  };

  /**
    Session-aware cache.
   */
  app.context.cacheKey = function(key) {
    this.session.cacheKeys = this.session.cacheKeys || {};
    if(key) {//set
      debug("setup session key %s", key);
      this.session.cacheKeys[this.req.url] = key;
    } else {//get
      debug("get session key");
      return this.session.cacheKeys[this.req.url] || this.req.url;
    }
  };

  /**
    Delete a cache entry
   */
  app.context.invalidate = function*(key) {
    if(key) {
      debug("invalidate explict key %s", key);
      yield self.store.invalidate(key);
    } else {
      debug("invalidate explict session key");
      yield self.store.invalidate(this.cacheKey());
      delete this.session.cacheKeys[this.req.url];
    }
  };

};

cache.all = function() {
  return this.match();
};

cache.match = function(matcher) {
  return function*(next) {
    debug("pre cache");
    var ret, value;
    if(matcher) {
      ret = yield matcher.call(this);
    } else {
      ret = true;
    }
    if(ret) {//should continue or not
      value = yield this.cache();
      if(value) {
        debug("hit");
        this.set("X-KOA-CACHE-HIT", 1);
        this.body = value;
        return;
      }
      debug("miss");
    } else {
      debug("unmatch");
    }
    yield next;
    if(this.body) {
      debug("cache");
      yield this.cache(this.cacheKey(), this.body);
    }
  };
};

module.exports = CacheMiddleware;


text:
/**
 * Merge ticket thread tables into one
 *
 * Replace the ticket_{message,response,note} tables with a single
 * ticket_thread table that will contain data for all three current message
 * types. This simplifies much of the ticket thread code and paves the way
 * for other types of messages in the future.
 *
 * This patch automagically moves the data from the three federated tables
 * into the one combined table.
 */
DROP TABLE IF EXISTS `%TABLE_PREFIX%ticket_thread`;
CREATE TABLE `%TABLE_PREFIX%ticket_thread` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `pid` int(11) unsigned NOT NULL default '0',
  `ticket_id` int(11) unsigned NOT NULL default '0',
  `staff_id` int(11) unsigned NOT NULL default '0',
  `thread_type` enum('M','R','N') NOT NULL,
  `poster` varchar(128) NOT NULL default '',
  `source` varchar(32) NOT NULL default '',
  `title` varchar(255),
  `body` text NOT NULL,
  `ip_address` varchar(64) NOT NULL default '',
  `created` datetime NOT NULL,
  `updated` datetime NOT NULL,
  `old_pk` int(11) unsigned NOT NULL,
  `old_pid` int(11) unsigned,
  PRIMARY KEY  (`id`),
  KEY `ticket_id` (`ticket_id`),
  KEY `staff_id` (`staff_id`),
  KEY `old_pk` (`old_pk`),
  KEY `created` (`created`)
) DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `%TABLE_PREFIX%ticket_email_info`;
CREATE TABLE `%TABLE_PREFIX%ticket_email_info` (
  `message_id` int(11) unsigned NOT NULL,
  `email_mid` varchar(255) NOT NULL,
  `headers` text,
  KEY `message_id` (`email_mid`)
) DEFAULT CHARSET=utf8;

-- Transfer messages
INSERT INTO `%TABLE_PREFIX%ticket_thread`
  (`ticket_id`, `thread_type`, `body`, `ip_address`,
    `created`, `updated`, `old_pk`)
  SELECT `ticket_id`, 'M', `message`, `ip_address`,
    `created`, COALESCE(`updated`, NOW()), `msg_id`
    FROM `%TABLE_PREFIX%ticket_message`;

-- Transfer responses
INSERT INTO `%TABLE_PREFIX%ticket_thread`
  (`ticket_id`, `staff_id`, `thread_type`, `poster`, `body`, `ip_address`,
    `created`, `updated`, `old_pk`, `old_pid`)
  SELECT `ticket_id`, `staff_id`, 'R', `staff_name`, `response`, `ip_address`,
    `created`, COALESCE(`updated`, NOW()), `response_id`, `msg_id`
    FROM `%TABLE_PREFIX%ticket_response`;

-- Connect responses to (new) messages
CREATE TABLE `%TABLE_PREFIX%T_resp_links`
    SELECT `id`, `old_pk`
      FROM `%TABLE_PREFIX%ticket_thread`
     WHERE `thread_type` = 'M';

-- Add an index to speed up the linking process
ALTER TABLE `%TABLE_PREFIX%T_resp_links` ADD KEY `old_pk` (`old_pk`, `id`);

UPDATE `%TABLE_PREFIX%ticket_thread`
    SET `pid` = ( SELECT T2.`id` FROM `%TABLE_PREFIX%T_resp_links` T2
                  WHERE `old_pid` = T2.`old_pk` )
    WHERE `thread_type` = 'R'
      AND `old_pid` IS NOT NULL;

DROP TABLE `%TABLE_PREFIX%T_resp_links`;

-- Transfer notes
INSERT INTO `%TABLE_PREFIX%ticket_thread`
 (`ticket_id`, `staff_id`, `thread_type`, `body`, `title`,
   `source`, `poster`, `created`, `updated`, `old_pk`)
 SELECT `ticket_id`, N.staff_id, 'N', `note`, `title`,
   `source`, CONCAT_WS(' ', S.`firstname`, S.`lastname`),
   N.created, NOW(), `note_id`
   FROM `%TABLE_PREFIX%ticket_note` N
   LEFT JOIN `%TABLE_PREFIX%staff` S ON(S.staff_id=N.staff_id);

-- Transfer email information from messages
INSERT INTO `%TABLE_PREFIX%ticket_email_info`
    (`message_id`, `email_mid`, `headers`)
    SELECT ( SELECT T2.`id` FROM `%TABLE_PREFIX%ticket_thread` T2
             WHERE `msg_id` = T2.`old_pk`
               AND `thread_type` = 'M' ),
         `messageId`, `headers`
    FROM `%TABLE_PREFIX%ticket_message`
    WHERE `messageId` IS NOT NULL AND `messageId` <>'';

-- Change collation to utf8_general_ci - to avoid Illegal mix of collations error
ALTER TABLE `%TABLE_PREFIX%ticket_attachment`
    CHANGE `ref_type` `ref_type` ENUM('M','R','N') CHARACTER
    SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'M';

-- Update attachment table
UPDATE `%TABLE_PREFIX%ticket_attachment`
    SET `ref_id` = ( SELECT T2.`id` FROM `%TABLE_PREFIX%ticket_thread` T2
                     WHERE `ref_id` = T2.`old_pk`
                       AND `ref_type` = T2.`thread_type` );

-- Drop temporary columns
ALTER TABLE `%TABLE_PREFIX%ticket_thread` DROP COLUMN `old_pk`;
ALTER TABLE `%TABLE_PREFIX%ticket_thread` DROP COLUMN `old_pid`;

-- Drop old tables
DROP TABLE `%TABLE_PREFIX%ticket_message`;
DROP TABLE `%TABLE_PREFIX%ticket_response`;
DROP TABLE `%TABLE_PREFIX%ticket_note`;

-- Finished with patch
UPDATE `%TABLE_PREFIX%config`
    SET `schema_signature`='abe9c0cb845be52c10fcd7b3e626a589';


text:
layout: post
title: Financial Statements
---

In this segment we'll examine fiancial statements issued by each public company.

  * [Income statement](#consolidated-income-statement)
  * [Balance sheet](#consolidated-statement-of-financial-position)
  * [Cash Flow statement](#consolidated-statement-of-cash-flows)

Each company that has its stocks traded on a stock exchange is obliged to issue financial statements so that investors can invest accordingly.

The _income statement_ is one of the three financial statements - the other two are the _balance sheet_ and _cash flow statement_.

In the context of corporate financial reporting, the income statement summarizes a company's revenues (sales) and expenses quarterly and annually for its fiscal year. The final net figure, as well as various others in this statement, are of major interest to the investment community.

##Consolidated income statement

|---------------------------|-----------|
| Revenue                   | 22 868    |
| Cost of goods sold        | -15 183   |
| **Gross Profit**          | **7 685** |
| Marketing expenses        | -5 076  |
| Administrative expenses   | -2 125  |
| Other operating income    | 145     |
| Other operating expenses  | -272    |
| **Operating profit**      | **67**  |
| Finance income            | 420     |
| Finance expenses          | -48     |
| **Profit before tax**     | **468** |
| Income tax expense        | 10      |
| **Profit for the period** | **119** |
| Attributable to :         |         |
| - *Equity holders of the Parent company* | *108* |
| - *Non-controlling interest*             | *11*  |
|  |  |
| Earnings per share
  of the Parent company | 0.01 |

For more information visit [Investopedia](http://www.investopedia.com/terms/i/incomestatement.asp)

---

##Consolidated Statement of Financial Position

|-------------------------|-----------|-----------|
| **ASSETS** | Now | Before |
| **Current assets** |  |  |
| Cash and cash equivalents | 19 165 | 16 260 |
| Trade and other receivables | 10 846 | 14 746 |
| Inventories | 24 873 | 24 598 |
| **Total current assets** | **55 080** | **55 847** |
|  |  |  |
| **Non-current assets** |  |  |
| Long-term receivables | 10 | 6 |
| Intangible assets | 719 | 443 |
| Investment property | 1 592 | 1 618 |
| Property, plant and equipment | 18 157 | 17 041 |
| **Total non-current assets** | **21 549** | **19 990** |
| **TOTAL ASSETS** | **76 629** | **75 837** |
|  |  |  |
| **LIABILITIES AND EQUITY** |  |  |
| **Current liabilities** |  |  |
| Borrowings | 79 | 47 |
| Trade and other payables | 10 837 | 11 171 |
| Tax liabilities | 905 | 1 008 |
| **Total current liabilities** | **11 821** | **12 226** |
|  |  |  |
| **Non-current liabilities** |  |  |
| Borrowings | 10 503 | 6 587 |
| Deferred tax liability | 1 953 | 2 162 |
| **Total non-current liabilities** | **1 953** | **2 162** |
| **Total liabilities** | **13 774** | **14 388** |
|  |  |  |
| **Equity** |  |  |
| Share capital | 11 820 | 15 760 |
| Share premium | 13 822 | 13 822 |
| Treasury shares | -224 | -20 |
| Retained earnings | 26 860 | 20 513 |
| **Total equity attributable to equity** |  |  |
| **holders of the Parent company** | **52 844** | **51 396** |
| Non-controlling interest in equity | 10 011 | 10 053 |
| **Total equity** | **62 855** | **61 449** |
| **TOTAL EQUITY AND LIABILITIES** | **76 629** | **75 837** |

---

##Consolidated Statement of Cash Flows

|---------------------------|-----------|
| Cash flow from operating activities|  |
| **Profit for the period** | **11 866** |
| Adjustments for: |  |
| - Depreciation and amortization | 2 588 |
| Income tax expense | 3 894 |
| Change in inventories | -275 |
| Interest paid | -30 |
| Income tax paid | -4 199 |
| **Net cash from operating activities** | **18 612** |
|  |  |
| **Cash flow from investing activities** |  |
| Interest received | 1 027 |
| Proceeds from sale of property, plant and equipment | 184 |
| Acquisition of property, plant and equipment | -3 664 |
| Acquisition of intangible assets | -466 |
| **Net cash used in/from investing activities** | **-3 292** |
|  |  |
| **Cash flow from financing activities** |  |
| Proceeds from borrowings | 39 |
| Dividends paid | -4 518 |
| Acquisition of own shares | -204 |
| Reduction of share capital | -3 933 |
| **Net cash used in/ from financing activities** | -8 616 |

---

_**AK**_


text:
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;

namespace FishBowl.Models
{
    public class FishBowlModel
    {
        private readonly ParticipantsRepository _participantsRepository;
        private List<ChatMessage> _chatMessages = new List<ChatMessage>();
        private readonly static FishBowlModel _instance =
            new FishBowlModel(GlobalHost.ConnectionManager.GetHubContext<FishBowlHub>().Clients, new ParticipantsRepository());

        private readonly object _participantLock = new object();
        private readonly List<Participant> _participants = new List<Participant>();
        private int _maxSpeakers = 4;

        private FishBowlModel(IHubConnectionContext clients, ParticipantsRepository participantsRepository)
        {
            _participantsRepository = participantsRepository;
            Clients = clients;
            InitializeParticipants();
        }

        private void InitializeParticipants()
        {
            _participants.AddRange(_participantsRepository.GetRegisteredParticipants());
            _chatMessages = new List<ChatMessage>();
        }

        private Participant GetParticipant(string name)
        {
            return _participants.FirstOrDefault(m => m.Name == name);
        }

        public void Enter(string name)
        {
            var myParticipant = GetParticipant(name);

            if (myParticipant != null)
            {
                if (_participants.Count(m => m.Speaking) < _maxSpeakers)
                {
                    myParticipant.Speaking = true;
                }
                else
                {
                    myParticipant.Waiting = true;
                }
            }
            Broadcast(string.Format("{0} has entered the Fish Bowl", name));
        }

        public void Leave(string name)
        {
            var myParticipant = GetParticipant(name);

            if (myParticipant != null)
            {
                myParticipant.Speaking = false;
            }

            var waitingParticipant = _participants.FirstOrDefault(m => m.Waiting);
            if (waitingParticipant != null)
            {
                waitingParticipant.Waiting = false;
                waitingParticipant.Speaking = true;
            }
            Broadcast(string.Format("{0} has left the Fish Bowl", name));
        }

        public void Initialize()
        {
            Broadcast(string.Empty);
        }

        public void StartFishBowl(int maxSpeakers)
        {
            _maxSpeakers = maxSpeakers;
            Clients.All.loadAvatars(_participantsRepository.GetAvatars());
            Broadcast(string.Empty);
        }

        private void Broadcast(string message)
        {
            Clients.All.loadParticipants(_participants);
            Clients.All.loadChat(_chatMessages);

            if (!string.IsNullOrEmpty(message))
            {
                Clients.All.showAlert(message);
            }

        }
        public static FishBowlModel Instance
        {
            get
            {
                return _instance;
            }
        }

        private IHubConnectionContext Clients
        {
            get;
            set;
        }

        public void SignIn(IEnumerable<Participant> participantsToSignIn)
        {
            var signedIn = string.Empty;
            foreach (var participantToSignIn in participantsToSignIn.Where(m => m.SignedIn))
            {
                var myParticipant = _participants.FirstOrDefault(m => m.Name == participantToSignIn.Name && !m.SignedIn);
                if (myParticipant != null)
                {
                    myParticipant.SignedIn = true;
                    myParticipant.Speaking = false;
                    myParticipant.Waiting = false;
                    if (signedIn.Length > 0)
                    {
                        signedIn += ", " ;
                    }
                    signedIn += participantToSignIn.Name;
                }
            }
            if (signedIn.Length > 0)
            {
                Broadcast(string.Format("{0} {1} signed in", signedIn, signedIn.IndexOf(",", System.StringComparison.Ordinal) < 0 ? "has" : "have"));
            }
        }

        public void Register(string name, string avatarName, bool autoSignIn)
        {
            _participantsRepository.Register(name, avatarName);

            var newParticipant = _participantsRepository.GetRegisteredParticipants().FirstOrDefault(m => m.Name == name);
            if (newParticipant != null)
            {
                newParticipant.SignedIn = autoSignIn;
            }
            _participants.Add(newParticipant);
            Broadcast(string.Format("{0} has registered", name));
        }

        public void SendChat(string message)
        {
            _chatMessages.Add(new ChatMessage(message));
            Clients.All.loadChat(_chatMessages);
            Clients.All.showAlert("New chat message");
        }

        public void SignOut(string name)
        {
            var myParticipant = GetParticipant(name);

            if (myParticipant != null)
            {
                myParticipant.SignedIn = false;
            }

            Broadcast(string.Format("{0} has signed out", name));
        }
    }

    public class ChatMessage
    {
        public ChatMessage(string message)
        {
            Message = message;
        }
        public string Message { get; set; }
        public bool Read { get; set; }
    }
}


text:
var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    endPoints = [
       { x: 130, y: 70 },
       { x: 430, y: 270 },
    ],
    controlPoints = [
       { x: 130, y: 250 },
       { x: 450, y: 70 },
    ];

function drawGrid(color, stepx, stepy) {
   context.save()

   context.strokeStyle = color;
   context.fillStyle = '#ffffff';
   context.lineWidth = 0.5;
   context.fillRect(0, 0, context.canvas.width, context.canvas.height);

   for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
     context.beginPath();
     context.moveTo(i, 0);
     context.lineTo(i, context.canvas.height);
     context.stroke();
   }

   for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
     context.beginPath();
     context.moveTo(0, i);
     context.lineTo(context.canvas.width, i);
     context.stroke();
   }

   context.restore();
}

function drawBezierCurve() {
   context.strokeStyle = 'blue';
   context.fillStyle = 'yellow';

   context.beginPath();
   context.moveTo(endPoints[0].x, endPoints[0].y);
   context.bezierCurveTo(controlPoints[0].x, controlPoints[0].y,
                         controlPoints[1].x, controlPoints[1].y,
                         endPoints[1].x, endPoints[1].y);
   context.stroke();
}

function drawEndPoints() {
   context.strokeStyle = 'blue';
   context.fillStyle = 'red';

   endPoints.forEach( function (point) {
      context.beginPath();
      context.arc(point.x, point.y, 5, 0, Math.PI*2, false);
      context.stroke();
      context.fill();
   });
}

function drawControlPoints() {
   context.strokeStyle = 'yellow';
   context.fillStyle = 'blue';

   controlPoints.forEach( function (point) {
      context.beginPath();
      context.arc(point.x, point.y, 5, 0, Math.PI*2, false);
      context.stroke();
      context.fill();
   });
}

drawGrid('lightgray', 10, 10);

drawControlPoints();
drawEndPoints();
drawBezierCurve();


text:
module Main where

import Control.Monad.Except
import Control.Monad.RWS
import System.Environment
import Data.Foldable

import qualified Data.Map.Strict as Map

import Parser
import Syntax
import Type
import Kind

main :: IO ()
main = do
    src <- fmap head getArgs >>= readFile
    let parsed = parseDefs src
    case runExcept $ run parsed of
        (Right res) -> print res
        (Left err) -> print err

run :: [(String, Either Type Term)] -> ThrowsError Type
run defs = do
    ran <- evalRWST (typeExprs $ reverse defs) emptyCtx letters
    return $ fst ran

-- This stuff is really pretty hacky.

getMain :: TyCtx -> ThrowsError Type
getMain ctx = case Map.lookup "main" ctx of
    (Just main) -> return main
    Nothing -> throwError NoMain

tyIfNotAlready :: Either Type Term -> Typing Type
tyIfNotAlready (Right term) = ty term
tyIfNotAlready (Left typ) = return typ

typeExprs :: [(String, Either Type Term)] -> Typing Type
typeExprs [] = do
    envs <- ask
    lift $ getMain (_typeCtx envs)
typeExprs ((name, rhs) : rest) = do
    ty <- tyIfNotAlready rhs
    kn <- kind ty
    local (insertBoth name ty kn) (typeExprs rest)


text:
import numpy as np
from stingray.pulse import fold_events, get_TOA, phase_exposure
from stingray.pulse import profile_stat, z_n, pulse_phase
from stingray.pulse import z_n, z_n_events, z_n_binned_events, z_n_gauss, htest
from stingray.pulse import z_n_events_all, z_n_binned_events_all, z_n_gauss_all
from stingray.pulse import get_orbital_correction_from_ephemeris_file
from stingray.pulse import HAS_PINT
import pytest
import os
import warnings
import matplotlib.pyplot as plt

def _template_fun(phase, ph0, amplitude, baseline=0):
    return baseline + amplitude * np.cos((phase - ph0) * 2 * np.pi)

class TestAll(object):
    """Unit tests for the stingray.pulsar module."""
    @classmethod
    def setup_class(cls):
        cls.curdir = os.path.abspath(os.path.dirname(__file__))
        cls.datadir = os.path.join(cls.curdir, 'data')

    @pytest.mark.remote_data
    @pytest.mark.skipif('not HAS_PINT')
    def test_pint_installed_correctly(self):

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=ResourceWarning)

            import pint.toa as toa
            from pint.residuals import Residuals
            import pint.models.model_builder as mb
            import astropy.units as u
            parfile = os.path.join(self.datadir, 'example_pint.par')
            timfile = os.path.join(self.datadir, 'example_pint.tim')

            toas = toa.get_TOAs(timfile, ephem="DE405",
                                planets=False, include_bipm=False)
            model = mb.get_model(parfile)

            pint_resids_us = Residuals(toas, model).time_resids.to(u.s)

        # Due to the gps2utc clock correction. We are at 3e-8 seconds level.
        assert np.all(np.abs(pint_resids_us.value) < 3e-6)

    @pytest.mark.remote_data
    @pytest.mark.skipif('not HAS_PINT')
    def test_orbit_from_parfile(self):
        import pint.toa as toa
        parfile = os.path.join(self.datadir, 'example_pint.par')
        timfile = os.path.join(self.datadir, 'example_pint.tim')

        toas = toa.get_TOAs(timfile, ephem="DE405",
                            planets=False, include_bipm=False)
        mjds = np.array([m.value for m in toas.get_mjds(high_precision=True)])

        mjdstart, mjdstop = mjds[0] - 1, mjds[-1] + 1

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=UserWarning)
            correction_sec, correction_mjd, model = \
                get_orbital_correction_from_ephemeris_file(mjdstart, mjdstop,
                                                           parfile, ntimes=1000,
                                                           return_pint_model=True)

        mjdref = 50000
        toa_sec = (mjds - mjdref) * 86400
        corr = correction_mjd(mjds)
        corr_s = correction_sec(toa_sec, mjdref)
        assert np.allclose(corr, corr_s / 86400 + mjdref)

    @pytest.mark.skipif('HAS_PINT')
    def test_orbit_from_parfile_raises(self):
        print("Doesn't have pint")
        with pytest.raises(ImportError):
            get_orbital_correction_from_ephemeris_file(0, 0,
                                                       parfile='ciaociao')

    def test_stat(self):
        """Test pulse phase calculation, frequency only."""
        prof = np.array([2, 2, 2, 2])
        np.testing.assert_array_almost_equal(profile_stat(prof), 0)

    def test_zn(self):
        """Test pulse phase calculation, frequency only."""
        ph = np.array([0, 1])
        np.testing.assert_array_almost_equal(z_n(ph, 2), 8)
        ph = np.array([])
        np.testing.assert_array_almost_equal(z_n(ph, 2), 0)
        ph = np.array([0.2, 0.7])
        ph2 = np.array([0, 0.5])
        np.testing.assert_array_almost_equal(z_n(ph, 2), z_n(ph2, 2))

    def test_pulse_phase1(self):
        """Test pulse phase calculation, frequency only."""
        times = np.arange(0, 4, 0.5)
        ph = pulse_phase(times, 1, ph0=0, to_1=False)
        np.testing.assert_array_almost_equal(ph, times)

    def test_pulse_phase2(self):
        """Test pulse phase calculation, fdot only."""
        times = np.arange(0, 4, 0.5)
        ph = pulse_phase(times, 0, 1, ph0=0, to_1=False)
        np.testing.assert_array_almost_equal(ph, 0.5 * times ** 2)

    def test_pulse_phase3(self):
        """Test pulse phase calculation, fddot only."""
        times = np.arange(0, 4, 0.5)
        ph = pulse_phase(times, 0, 0, 1, ph0=0, to_1=False)
        np.testing.assert_array_almost_equal(ph, 1/6 * times ** 3)

    def test_phase_exposure1(self):
        start_time = 0
        stop_time = 1
        period = 1
        nbin = 16
        expo = phase_exposure(start_time, stop_time, period, nbin)
        np.testing.assert_array_almost_equal(expo, np.ones(nbin))

    def test_phase_exposure2(self):
        start_time = 0
        stop_time = 0.5
        period = 1
        nbin = 16
        expo = phase_exposure(start_time, stop_time, period, nbin)
        expected = np.ones(nbin)
        expected[nbin//2:] = 0
        np.testing.assert_array_almost_equal(expo, expected)

    def test_phase_exposure3(self):
        start_time = 0
        stop_time = 1
        gtis = np.array([[0, 0.5]])
        period = 1
        nbin = 16
        expo = phase_exposure(start_time, stop_time, period, nbin, gtis=gtis)
        expected = np.ones(nbin)
        expected[nbin//2:] = 0
        np.testing.assert_array_almost_equal(expo, expected)

    def test_phase_exposure4(self):
        start_time = 0
        stop_time = 1
        gtis = np.array([[-0.2, 1.2]])
        period = 1
        nbin = 16
        expo = phase_exposure(start_time, stop_time, period, nbin, gtis=gtis)
        expected = np.ones(nbin)
        np.testing.assert_array_almost_equal(expo, expected)

    def test_pulse_profile1(self):
        nbin = 16
        times = np.arange(0, 1, 1/nbin)

        period = 1
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=UserWarning)
            ph, p, pe = fold_events(times, 1, nbin=nbin)

        np.testing.assert_array_almost_equal(p, np.ones(nbin))
        np.testing.assert_array_almost_equal(ph, np.arange(nbin)/nbin +
                                             0.5/nbin)
        np.testing.assert_array_almost_equal(pe, np.ones(nbin))

    def test_pulse_profile2(self):
        nbin = 16
        dt = 1/nbin
        times = np.arange(0, 2, dt)
        gtis = np.array([[-0.5*dt, 2 + 0.5*dt]])

        period = 1
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=UserWarning)
            ph, p, pe = fold_events(times, 1, nbin=nbin, expocorr=True, gtis=gtis)

        np.testing.assert_array_almost_equal(ph, np.arange(nbin)/nbin +
                                             0.5/nbin)
        np.testing.assert_array_almost_equal(p, 2 * np.ones(nbin))
        np.testing.assert_array_almost_equal(pe, 2**0.5 * np.ones(nbin))

    def test_pulse_profile3(self):
        nbin = 16
        dt = 1/nbin
        times = np.arange(0, 2 - dt, dt)
        gtis = np.array([[-0.5*dt, 2 - dt]])

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=UserWarning)
            ph, p, pe = fold_events(times, 1, nbin=nbin, expocorr=True,
                                gtis=gtis)

        np.testing.assert_array_almost_equal(ph, np.arange(nbin)/nbin +
                                             0.5/nbin)
        np.testing.assert_array_almost_equal(p, 2 * np.ones(nbin))
        expected_err = 2**0.5 * np.ones(nbin)
        expected_err[-1] = 2  # Because of the change of exposure
        np.testing.assert_array_almost_equal(pe, expected_err)

    def test_zn_2(self):
        with pytest.warns(DeprecationWarning) as record:
            np.testing.assert_almost_equal(z_n(np.arange(1), n=1, norm=1), 2)
            np.testing.assert_almost_equal(z_n(np.arange(1), n=2, norm=1), 4)
            np.testing.assert_almost_equal(z_n(np.arange(2), n=2, norm=1), 8)
            np.testing.assert_almost_equal(
                z_n(np.arange(2)+0.5, n=2, norm=1), 8)

        assert np.any(["The use of ``z_n(phase, norm=profile)``"
                       in r.message.args[0] for r in record])

    def test_get_TOA1(self):
        np.random.seed(1234)
        period = 1.2
        tstart = 122
        start_phase = 0.2123
        phases = np.arange(0, 1, 1 / 32)
        template = _template_fun(phases, start_phase, 10, 20)
        prof = np.random.poisson(template)

        toa, toaerr = \
            get_TOA(prof, period, tstart,
                    template=_template_fun(phases, 0, 1, 0))

        real_toa = tstart + start_phase * period
        assert (real_toa >= toa - toaerr * 3) & (real_toa <= toa + toaerr * 3)

    def test_get_TOA2(self):
        np.random.seed(1234)
        period = 1.2
        tstart = 122
        start_phase = 0.2123
        phases = np.arange(0, 1, 1 / 32)
        template = _template_fun(phases, start_phase, 10, 20)
        prof = np.random.poisson(template)

        toa, toaerr = \
            get_TOA(prof, period, tstart,
                    template=_template_fun(phases, 0, 1, 0), nstep=200)

        real_toa = tstart + start_phase * period
        assert (real_toa >= toa - toaerr * 3) & (real_toa <= toa + toaerr * 3)

    def test_get_TOA3(self):
        np.random.seed(1234)
        period = 1.2
        tstart = 122
        start_phase = 0.2123
        phases = np.arange(0, 1, 1 / 32)
        template = _template_fun(phases, start_phase, 10, 20)
        prof = np.random.poisson(template)

        toa, toaerr = \
            get_TOA(prof, period, tstart, quick=True,
                    template=_template_fun(phases, 0, 1, 0), nstep=200,
                    use_bootstrap=True)

        real_toa = tstart + start_phase * period
        assert (real_toa >= toa - toaerr * 3) & (real_toa <= toa + toaerr * 3)

    def test_get_TOA4(self):
        np.random.seed(1234)
        period = 1.2
        tstart = 122
        start_phase = 0.2123
        phases = np.arange(0, 1, 1 / 32)
        template = _template_fun(phases, start_phase, 10, 20)
        prof = np.random.poisson(template)

        toa, toaerr = \
            get_TOA(prof, period, tstart,
                    template=_template_fun(phases, 0, 1, 0), nstep=200,
                    debug=True)

        real_toa = tstart + start_phase * period
        assert (real_toa >= toa - toaerr * 3) & (real_toa <= toa + toaerr * 3)

    def test_get_TOA_notemplate(self):
        np.random.seed(1234)
        period = 1.2
        tstart = 122
        start_phase = 0.2123
        phases = np.arange(0, 1, 1 / 32)
        template = _template_fun(phases, start_phase, 10, 20)
        prof = np.random.poisson(template)

        toa, toaerr = \
            get_TOA(prof, period, tstart, nstep=200,
                    debug=True)

        real_toa = tstart + start_phase * period
        assert (real_toa >= toa - toaerr * 3) & (real_toa <= toa + toaerr * 3)

def create_pulsed_events(nevents, freq, t0=0, t1=1000, nback=0):
    from numpy.random import Generator, PCG64
    rg = Generator(PCG64())
    events = rg.normal(0.5, 0.1, nevents - nback)
    events = events - np.floor(events)

    if nback > 0:
        events = np.concatenate((events, rg.uniform(0, 1, nback)))
    pulse_no = rg.integers(0, np.rint((t1 - t0) * freq), nevents)
    events = np.sort(events + pulse_no)
    return t1 + events / freq

def poissonize_gaussian_profile(prof, err):
    lam = 10000
    factor = np.sqrt(lam) / err
    return (prof - prof.mean()) * factor + lam

class TestZandH(object):
    """Unit tests for the stingray.pulsar module."""
    @classmethod
    def setup_class(cls):
        nevents = 10000
        f = 1.2123
        cls.events = create_pulsed_events(nevents, f)
        phases = cls.events * f
        cls.phases = phases - np.floor(phases)

        cls.prof512, cls.bins = \
            np.histogram(cls.phases, range=[0, 1], bins=512)

    def test_zn_events(self):
        phases = self.phases
        ks, ze = z_n_events_all(phases, nmax=10)
        m, h = htest(phases, nmax=10, datatype="events")
        assert np.isclose(h + 4 * m - 4, z_n(phases, n=m, datatype="events"))
        assert np.isclose(h + 4 * m - 4, ze[m - 1])

    def test_zn_poisson(self):
        phases = self.phases
        prof512, bins = self.prof512, self.bins
        ks, ze = z_n_events_all(phases, nmax=10)
        ksp, zp = z_n_binned_events_all(prof512, nmax=10)

        assert np.allclose(ze, zp, rtol=0.01)
        m, h = htest(prof512, datatype="binned", nmax=10)

        assert np.isclose(h + 4 * m - 4, z_n(prof512, n=m, datatype="binned"))
        assert np.isclose(h + 4 * m - 4, zp[m - 1])

    def test_zn_poisson_zeros(self):
        prof512 = np.zeros(512)
        ksp, zp = z_n_binned_events_all(prof512, nmax=10)
        assert np.allclose(zp, 0)

    def test_deprecated_norm_use(self):
        prof512, bins = self.prof512, self.bins
        with pytest.warns(DeprecationWarning) as record:
            z = z_n(prof512, n=3, datatype="binned")
            z_dep = z_n(np.zeros(prof512.size), norm=prof512, n=3, datatype="binned")
            np.testing.assert_almost_equal(z, z_dep)

        assert np.any(["The use of ``z_n(phase, norm=profile)``"
                       in r.message.args[0] for r in record])

    def test_zn_gauss(self):
        nbin = 512
        dph = 1 / nbin
        err = 0.1
        ph = np.arange(-0.5 + dph / 2, 0.5, dph)
        prof = np.random.normal(np.exp(-ph**2 / 2 / 0.1**2), err)

        prof_poiss = poissonize_gaussian_profile(prof, err)

        ksp, zp = z_n_binned_events_all(prof_poiss, nmax=10)
        ksg, zg = z_n_gauss_all(prof, err, nmax=10)
        assert np.allclose(zg, zp, rtol=0.01)

        mg, hg = htest(prof, err=err, datatype="gauss", nmax=10)
        mp, hp = htest(prof_poiss, datatype="binned", nmax=10)

        assert np.isclose(hg, hp)
        assert np.isclose(mg, mp)
        assert np.isclose(hg + 4 * mg - 4,
                          z_n(prof, n=mg, err=err, datatype="gauss"))

    def test_wrong_args_H_datatype(self):
        with pytest.raises(ValueError) as excinfo:
            htest([1], 2, datatype="gibberish")
        assert "Unknown datatype requested for htest (gibberish)" in str(excinfo.value)

    def test_wrong_args_Z_datatype(self):
        with pytest.raises(ValueError) as excinfo:
            z_n([1], 2, datatype="gibberish")
        assert "Unknown datatype requested for Z_n (gibberish)" in str(excinfo.value)

    def test_wrong_args_H_gauss_noerr(self):
        with pytest.raises(ValueError) as excinfo:
            htest([1], 2, datatype="gauss")
        assert "If datatype='gauss', you need to " in str(excinfo.value)

    def test_wrong_args_Z_gauss_noerr(self):
        with pytest.raises(ValueError) as excinfo:
            z_n([1], 2, datatype="gauss")
        assert "If datatype='gauss', you need to " in str(excinfo.value)


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VR_PERFORM_INTERACTION_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VR_PERFORM_INTERACTION_REQUEST_H_

#include "application_manager/commands/hmi/request_to_hmi.h"

namespace application_manager {

namespace commands {

/**
 * @brief VRPerformInteractionRequest command class
 **/
class VRPerformInteractionRequest : public RequestToHMI {
  public:
    /**
     * @brief VRPerformInteractionRequest class constructor
     *
     * @param message Incoming SmartObject message
     **/
    explicit VRPerformInteractionRequest(const MessageSharedPtr& message);

    /**
     * @brief VRPerformInteractionRequest class destructor
     **/
    virtual ~VRPerformInteractionRequest();

    /**
     * @brief Execute command
     **/
    virtual void Run();

  private:
    DISALLOW_COPY_AND_ASSIGN(VRPerformInteractionRequest);
};

}  // namespace commands

}  // namespace application_manager

#endif  //  SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VR_PERFORM_INTERACTION_REQUEST_H_


text:
<?php

namespace PHPExiftool\Driver\Tag\MakerNotes;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class PreviewImage extends AbstractTag
{

    protected $Id = 28;

    protected $Name = 'PreviewImage';

    protected $FullName = 'QuickTime::Flip';

    protected $GroupName = 'MakerNotes';

    protected $g0 = 'QuickTime';

    protected $g1 = 'MakerNotes';

    protected $g2 = 'Image';

    protected $Type = 'undef';

    protected $Writable = false;

    protected $Description = 'Preview Image';

    protected $local_g2 = 'Preview';

}


text:
"""
Utilitats per enviar mails.
"""

import smtplib
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate
from email.header import Header
from email.mime.text import MIMEText

from .constants import APP_CHARSET
from .aes import AESCipher
from .services import MAIL_SERVERS

class Mail(object):
    """Classe principal a instanciar."""

    def __init__(self, server='sisap'):
        """Inicialització de paràmetres."""
        self.srv = MAIL_SERVERS[server]['host']
        self.prt = MAIL_SERVERS[server]['port']
        self.usr = MAIL_SERVERS[server]['user']
        self.pwd = MAIL_SERVERS[server]['password']
        self.me = MAIL_SERVERS[server]['me']
        self.to = []
        self.cc = []
        self.subject = ''
        self.text = ''
        self.attachments = []

    def __construct(self):
        """Construcció del missatge, cridat per send."""
        self.message = MIMEMultipart()
        self.message['From'] = self.me
        self.message['To'] = COMMASPACE.join(self.to)
        self.message['Cc'] = COMMASPACE.join(self.cc)
        self.message['Date'] = formatdate(localtime=True)
        self.message['Subject'] = Header(self.subject, APP_CHARSET)
        self.message.attach(MIMEText(self.text, 'plain', APP_CHARSET))
        for filename, iterable in self.attachments:
            data = '\r\n'.join([', '.join(map(str, row)) for row in iterable])
            attachment = MIMEText(data, 'plain', APP_CHARSET)
            attachment.add_header(
                'Content-Disposition',
                'attachment',
                filename=filename
            )
            self.message.attach(attachment)
        self.to += self.cc

    def __connect(self):
        """Connexió al servidor, cridat per send."""
        self.server = smtplib.SMTP_SSL(self.srv, self.prt)
        self.server.login(self.usr, AESCipher().decrypt(self.pwd))

    def send(self):
        """Enviament del mail."""
        if self.to or self.cc:
            self.__construct()
            self.__connect()
            self.server.sendmail(self.me, self.to, self.message.as_string())
            self.server.close()


text:
package com.eStore.domain;

import android.graphics.Bitmap;

public class Product {

	private String category;
	private String price;
	private String name;
	private String specification;
	private String image;
	private Bitmap transformedImage;

	public Product(String category, String price, String name,
			String specification, String image, String code) {
		super();
		this.category = category;
		this.price = price;
		this.name = name;
		this.specification = specification;
		this.image = image;
		this.code = code;
	}
	public Product() {
		// TODO Auto-generated constructor stub
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSpecification() {
		return specification;
	}
	public void setSpecification(String specification) {
		this.specification = specification;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	private String code;

	public Bitmap getTransformedImage() {
		return transformedImage;
	}
	public void setTransformedImage(Bitmap transformedImage) {
		this.transformedImage = transformedImage;
	}
	@Override
	public String toString() {
		return "Product [category=" + category + ", price=" + price + ", name="
				+ name + ", specification=" + specification + ", image="
				+ image + ", code=" + code + "]";
	}

}


text:
Emailplate is a email template engine designed to make inline css html with your familiar template engine, css preprocessor.

## Installation

    $ npm install emailplate

## Quick Start

```js
var Emailplate = require('emailplate');
var emailplate = new Emailplate({
  views: __dirname + '/emailplates'
});

emailplate.render('sample', function(err, inlineCssHtml){
  console.log(inlineCssHtml);
});
```

## Themes

This `views` option set where the template theme directory is.

The default theme layout have three files: html.<ext>, style.stylus, emailplate.json

```
emailplates
`-- blueprint
    |-- emailplate.json
    |-- html.hbs
    `-- style.styl
```

- html.(html|hbs|eco|jade|...)

  emailplate support most template engine that consolidate.js supported

[consolidate.js]: https://github.com/visionmedia/consolidate.js

- style.styl

  We use stylus because it can support css, sass, less basic syntax. It is robust.

- emailplate.(json|js|coffee)

  We need some information about the theme setting.

## API

### Initialize

```js
var Emailplate = require('emailplate')
  , emailplate = new Emailplate();
```

### Getter, Setter

```js
emailplate.set('views', __dirname + '/emailplates');
emailplate.get('views');
```

### Get all themes info

```js
emailplate.themes(function(err, infos) {

});
```

### Get single theme info

```js
emailplate.theme('themeName', function(err, info) {

});
```

### Render theme

```js
emailplate.render('themeName', {title: "emailplate test"}, function(err, html) {

});
```

## License

Copyright (c) 2013 Jarvis Ao Ieong
Licensed under the MIT license.


text:
#include <QApplication>

#include "calculatorform.h"

int main(int argc, char *argv[])
{
     QApplication app(argc, argv);
     CalculatorForm calculator;
     calculator.show();
     return app.exec();
}