text:
<?php

namespace Behat\Mink;

use Behat\Mink\Element\Element;
use Behat\Mink\Element\ElementInterface;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Element\TraversableElement;
use Behat\Mink\Exception\ElementNotFoundException;
use Behat\Mink\Exception\ExpectationException;
use Behat\Mink\Exception\ResponseTextException;
use Behat\Mink\Exception\ElementHtmlException;
use Behat\Mink\Exception\ElementTextException;

/**
 * Mink web assertions tool.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class WebAssert
{
    protected $session;

    /**
     * Initializes assertion engine.
     *
     * @param Session $session
     */
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    /**
     * Checks that current session address is equals to provided one.
     *
     * @param string $page
     *
     * @throws ExpectationException
     */
    public function addressEquals($page)
    {
        $expected = $this->cleanUrl($page);
        $actual = $this->getCurrentUrlPath();

        $this->assert($actual === $expected, sprintf('Current page is "%s", but "%s" expected.', $actual, $expected));
    }

    /**
     * Checks that current session address is not equals to provided one.
     *
     * @param string $page
     *
     * @throws ExpectationException
     */
    public function addressNotEquals($page)
    {
        $expected = $this->cleanUrl($page);
        $actual = $this->getCurrentUrlPath();

        $this->assert($actual !== $expected, sprintf('Current page is "%s", but should not be.', $actual));
    }

    /**
     * Checks that current session address matches regex.
     *
     * @param string $regex
     *
     * @throws ExpectationException
     */
    public function addressMatches($regex)
    {
        $actual = $this->getCurrentUrlPath();
        $message = sprintf('Current page "%s" does not match the regex "%s".', $actual, $regex);

        $this->assert((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that specified cookie exists and its value equals to a given one.
     *
     * @param string $name  cookie name
     * @param string $value cookie value
     *
     * @throws ExpectationException
     */
    public function cookieEquals($name, $value)
    {
        $this->cookieExists($name);

        $actualValue = $this->session->getCookie($name);
        $message = sprintf('Cookie "%s" value is "%s", but should be "%s".', $name, $actualValue, $value);

        $this->assert($actualValue == $value, $message);
    }

    /**
     * Checks that specified cookie exists.
     *
     * @param string $name cookie name
     *
     * @throws ExpectationException
     */
    public function cookieExists($name)
    {
        $message = sprintf('Cookie "%s" is not set, but should be.', $name);
        $this->assert($this->session->getCookie($name) !== null, $message);
    }

    /**
     * Checks that current response code equals to provided one.
     *
     * @param int $code
     *
     * @throws ExpectationException
     */
    public function statusCodeEquals($code)
    {
        $actual = $this->session->getStatusCode();
        $message = sprintf('Current response status code is %d, but %d expected.', $actual, $code);

        $this->assert(intval($code) === intval($actual), $message);
    }

    /**
     * Checks that current response code not equals to provided one.
     *
     * @param int $code
     *
     * @throws ExpectationException
     */
    public function statusCodeNotEquals($code)
    {
        $actual = $this->session->getStatusCode();
        $message = sprintf('Current response status code is %d, but should not be.', $actual);

        $this->assert(intval($code) !== intval($actual), $message);
    }

    /**
     * Checks that current response header equals value.
     *
     * @param string $name
     * @param string $value
     *
     * @throws ExpectationException
     */
    public function responseHeaderEquals($name, $value)
    {
        $actual = $this->session->getResponseHeader($name);
        $message = sprintf('Current response header "%s" is "%s", but "%s" expected.', $name, $actual, $value);

        $this->assert($value === $actual, $message);
    }

    /**
     * Checks that current response header does not equal value.
     *
     * @param string $name
     * @param string $value
     *
     * @throws ExpectationException
     */
    public function responseHeaderNotEquals($name, $value)
    {
        $actual = $this->session->getResponseHeader($name);
        $message = sprintf('Current response header "%s" is "%s", but should not be.', $name, $actual, $value);

        $this->assert($value !== $actual, $message);
    }

    /**
     * Checks that current response header contains value.
     *
     * @param string $name
     * @param string $value
     *
     * @throws ExpectationException
     */
    public function responseHeaderContains($name, $value)
    {
        $actual = (string) $this->session->getResponseHeader($name);
        $message = sprintf('The text "%s" was not found anywhere in the "%s" response header.', $value, $name);

        $this->assert(false !== stripos($actual, (string) $value), $message);
    }

    /**
     * Checks that current response header does not contain value.
     *
     * @param string $name
     * @param string $value
     *
     * @throws ExpectationException
     */
    public function responseHeaderNotContains($name, $value)
    {
        $actual = (string) $this->session->getResponseHeader($name);
        $message = sprintf('The text "%s" was found in the "%s" response header, but it should not.', $value, $name);

        $this->assert(false === stripos($actual, (string) $value), $message);
    }

    /**
     * Checks that current response header matches regex.
     *
     * @param string $name
     * @param string $regex
     *
     * @throws ExpectationException
     */
    public function responseHeaderMatches($name, $regex)
    {
        $actual = (string) $this->session->getResponseHeader($name);
        $message = sprintf('The pattern "%s" was not found anywhere in the "%s" response header.', $regex, $name);

        $this->assert((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that current response header does not match regex.
     *
     * @param string $name
     * @param string $regex
     *
     * @throws ExpectationException
     */
    public function responseHeaderNotMatches($name, $regex)
    {
        $actual = (string) $this->session->getResponseHeader($name);
        $message = sprintf(
            'The pattern "%s" was found in the text of the "%s" response header, but it should not.',
            $regex,
            $name
        );

        $this->assert(!preg_match($regex, $actual), $message);
    }

    /**
     * Checks that current page contains text.
     *
     * @param string $text
     *
     * @throws ResponseTextException
     */
    public function pageTextContains($text)
    {
        $actual = $this->session->getPage()->getText();
        $actual = preg_replace('/\s+/u', ' ', $actual);
        $regex = '/'.preg_quote($text, '/').'/ui';
        $message = sprintf('The text "%s" was not found anywhere in the text of the current page.', $text);

        $this->assertResponseText((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that current page does not contains text.
     *
     * @param string $text
     *
     * @throws ResponseTextException
     */
    public function pageTextNotContains($text)
    {
        $actual = $this->session->getPage()->getText();
        $actual = preg_replace('/\s+/u', ' ', $actual);
        $regex = '/'.preg_quote($text, '/').'/ui';
        $message = sprintf('The text "%s" appears in the text of this page, but it should not.', $text);

        $this->assertResponseText(!preg_match($regex, $actual), $message);
    }

    /**
     * Checks that current page text matches regex.
     *
     * @param string $regex
     *
     * @throws ResponseTextException
     */
    public function pageTextMatches($regex)
    {
        $actual = $this->session->getPage()->getText();
        $message = sprintf('The pattern %s was not found anywhere in the text of the current page.', $regex);

        $this->assertResponseText((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that current page text does not matches regex.
     *
     * @param string $regex
     *
     * @throws ResponseTextException
     */
    public function pageTextNotMatches($regex)
    {
        $actual = $this->session->getPage()->getText();
        $message = sprintf('The pattern %s was found in the text of the current page, but it should not.', $regex);

        $this->assertResponseText(!preg_match($regex, $actual), $message);
    }

    /**
     * Checks that page HTML (response content) contains text.
     *
     * @param string $text
     *
     * @throws ExpectationException
     */
    public function responseContains($text)
    {
        $actual = $this->session->getPage()->getContent();
        $message = sprintf('The string "%s" was not found anywhere in the HTML response of the current page.', $text);

        $this->assert(stripos($actual, (string) $text) !== false, $message);
    }

    /**
     * Checks that page HTML (response content) does not contains text.
     *
     * @param string $text
     *
     * @throws ExpectationException
     */
    public function responseNotContains($text)
    {
        $actual = $this->session->getPage()->getContent();
        $message = sprintf('The string "%s" appears in the HTML response of this page, but it should not.', $text);

        $this->assert(stripos($actual, (string) $text) === false, $message);
    }

    /**
     * Checks that page HTML (response content) matches regex.
     *
     * @param string $regex
     *
     * @throws ExpectationException
     */
    public function responseMatches($regex)
    {
        $actual = $this->session->getPage()->getContent();
        $message = sprintf('The pattern %s was not found anywhere in the HTML response of the page.', $regex);

        $this->assert((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that page HTML (response content) does not matches regex.
     *
     * @param $regex
     *
     * @throws ExpectationException
     */
    public function responseNotMatches($regex)
    {
        $actual = $this->session->getPage()->getContent();
        $message = sprintf('The pattern %s was found in the HTML response of the page, but it should not.', $regex);

        $this->assert(!preg_match($regex, $actual), $message);
    }

    /**
     * Checks that there is specified number of specific elements on the page.
     *
     * @param string           $selectorType element selector type (css, xpath)
     * @param string|array     $selector     element selector
     * @param int              $count        expected count
     * @param ElementInterface $container    document to check against
     *
     * @throws ExpectationException
     */
    public function elementsCount($selectorType, $selector, $count, ElementInterface $container = null)
    {
        $container = $container ?: $this->session->getPage();
        $nodes = $container->findAll($selectorType, $selector);

        $message = sprintf(
            '%d %s found on the page, but should be %d.',
            count($nodes),
            $this->getMatchingElementRepresentation($selectorType, $selector, count($nodes) !== 1),
            $count
        );

        $this->assert(intval($count) === count($nodes), $message);
    }

    /**
     * Checks that specific element exists on the current page.
     *
     * @param string           $selectorType element selector type (css, xpath)
     * @param string|array     $selector     element selector
     * @param ElementInterface $container    document to check against
     *
     * @return NodeElement
     *
     * @throws ElementNotFoundException
     */
    public function elementExists($selectorType, $selector, ElementInterface $container = null)
    {
        $container = $container ?: $this->session->getPage();
        $node = $container->find($selectorType, $selector);

        if (null === $node) {
            if (is_array($selector)) {
                $selector = implode(' ', $selector);
            }

            throw new ElementNotFoundException($this->session->getDriver(), 'element', $selectorType, $selector);
        }

        return $node;
    }

    /**
     * Checks that specific element does not exists on the current page.
     *
     * @param string           $selectorType element selector type (css, xpath)
     * @param string|array     $selector     element selector
     * @param ElementInterface $container    document to check against
     *
     * @throws ExpectationException
     */
    public function elementNotExists($selectorType, $selector, ElementInterface $container = null)
    {
        $container = $container ?: $this->session->getPage();
        $node = $container->find($selectorType, $selector);

        $message = sprintf(
            'An %s appears on this page, but it should not.',
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assert(null === $node, $message);
    }

    /**
     * Checks that specific element contains text.
     *
     * @param string       $selectorType element selector type (css, xpath)
     * @param string|array $selector     element selector
     * @param string       $text         expected text
     *
     * @throws ElementTextException
     */
    public function elementTextContains($selectorType, $selector, $text)
    {
        $element = $this->elementExists($selectorType, $selector);
        $actual = $element->getText();
        $regex = '/'.preg_quote($text, '/').'/ui';

        $message = sprintf(
            'The text "%s" was not found in the text of the %s.',
            $text,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElementText((bool) preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that specific element does not contains text.
     *
     * @param string       $selectorType element selector type (css, xpath)
     * @param string|array $selector     element selector
     * @param string       $text         expected text
     *
     * @throws ElementTextException
     */
    public function elementTextNotContains($selectorType, $selector, $text)
    {
        $element = $this->elementExists($selectorType, $selector);
        $actual = $element->getText();
        $regex = '/'.preg_quote($text, '/').'/ui';

        $message = sprintf(
            'The text "%s" appears in the text of the %s, but it should not.',
            $text,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElementText(!preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that specific element contains HTML.
     *
     * @param string       $selectorType element selector type (css, xpath)
     * @param string|array $selector     element selector
     * @param string       $html         expected text
     *
     * @throws ElementHtmlException
     */
    public function elementContains($selectorType, $selector, $html)
    {
        $element = $this->elementExists($selectorType, $selector);
        $actual = $element->getHtml();
        $regex = '/'.preg_quote($html, '/').'/ui';

        $message = sprintf(
            'The string "%s" was not found in the HTML of the %s.',
            $html,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement((bool) preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that specific element does not contains HTML.
     *
     * @param string       $selectorType element selector type (css, xpath)
     * @param string|array $selector     element selector
     * @param string       $html         expected text
     *
     * @throws ElementHtmlException
     */
    public function elementNotContains($selectorType, $selector, $html)
    {
        $element = $this->elementExists($selectorType, $selector);
        $actual = $element->getHtml();
        $regex = '/'.preg_quote($html, '/').'/ui';

        $message = sprintf(
            'The string "%s" appears in the HTML of the %s, but it should not.',
            $html,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement(!preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that an attribute exists in an element.
     *
     * @param string       $selectorType
     * @param string|array $selector
     * @param string       $attribute
     *
     * @return NodeElement
     *
     * @throws ElementHtmlException
     */
    public function elementAttributeExists($selectorType, $selector, $attribute)
    {
        $element = $this->elementExists($selectorType, $selector);

        $message = sprintf(
            'The attribute "%s" was not found in the %s.',
            $attribute,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement($element->hasAttribute($attribute), $message, $element);

        return $element;
    }

    /**
     * Checks that an attribute does not exist in an element.
     *
     * @param string       $selectorType
     * @param string|array $selector
     * @param string       $attribute
     *
     * @return NodeElement
     *
     * @throws ElementHtmlException
     */
    public function elementAttributeNotExists($selectorType, $selector, $attribute)
    {
        $element = $this->elementExists($selectorType, $selector);

        $message = sprintf(
            'The attribute "%s" was found in the %s.',
            $attribute,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement(!$element->hasAttribute($attribute), $message, $element);

        return $element;
    }

    /**
     * Checks that an attribute of a specific elements contains text.
     *
     * @param string       $selectorType
     * @param string|array $selector
     * @param string       $attribute
     * @param string       $text
     *
     * @throws ElementHtmlException
     */
    public function elementAttributeContains($selectorType, $selector, $attribute, $text)
    {
        $element = $this->elementAttributeExists($selectorType, $selector, $attribute);
        $actual = (string) $element->getAttribute($attribute);
        $regex = '/'.preg_quote($text, '/').'/ui';

        $message = sprintf(
            'The text "%s" was not found in the attribute "%s" of the %s.',
            $text,
            $attribute,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement((bool) preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that an attribute of a specific elements does not contain text.
     *
     * @param string       $selectorType
     * @param string|array $selector
     * @param string       $attribute
     * @param string       $text
     *
     * @throws ElementHtmlException
     */
    public function elementAttributeNotContains($selectorType, $selector, $attribute, $text)
    {
        $element = $this->elementAttributeExists($selectorType, $selector, $attribute);
        $actual = (string) $element->getAttribute($attribute);
        $regex = '/'.preg_quote($text, '/').'/ui';

        $message = sprintf(
            'The text "%s" was found in the attribute "%s" of the %s.',
            $text,
            $attribute,
            $this->getMatchingElementRepresentation($selectorType, $selector)
        );

        $this->assertElement(!preg_match($regex, $actual), $message, $element);
    }

    /**
     * Checks that specific field exists on the current page.
     *
     * @param string             $field     field id|name|label|value
     * @param TraversableElement $container document to check against
     *
     * @return NodeElement
     *
     * @throws ElementNotFoundException
     */
    public function fieldExists($field, TraversableElement $container = null)
    {
        $container = $container ?: $this->session->getPage();
        $node = $container->findField($field);

        if (null === $node) {
            throw new ElementNotFoundException($this->session->getDriver(), 'form field', 'id|name|label|value', $field);
        }

        return $node;
    }

    /**
     * Checks that specific field does not exists on the current page.
     *
     * @param string             $field     field id|name|label|value
     * @param TraversableElement $container document to check against
     *
     * @throws ExpectationException
     */
    public function fieldNotExists($field, TraversableElement $container = null)
    {
        $container = $container ?: $this->session->getPage();
        $node = $container->findField($field);

        $this->assert(null === $node, sprintf('A field "%s" appears on this page, but it should not.', $field));
    }

    /**
     * Checks that specific field have provided value.
     *
     * @param string             $field     field id|name|label|value
     * @param string             $value     field value
     * @param TraversableElement $container document to check against
     *
     * @throws ExpectationException
     */
    public function fieldValueEquals($field, $value, TraversableElement $container = null)
    {
        $node = $this->fieldExists($field, $container);
        $actual = (string) $node->getValue();
        $regex = '/^'.preg_quote($value, '/').'$/ui';

        $message = sprintf('The field "%s" value is "%s", but "%s" expected.', $field, $actual, $value);

        $this->assert((bool) preg_match($regex, $actual), $message);
    }

    /**
     * Checks that specific field have provided value.
     *
     * @param string             $field     field id|name|label|value
     * @param string             $value     field value
     * @param TraversableElement $container document to check against
     *
     * @throws ExpectationException
     */
    public function fieldValueNotEquals($field, $value, TraversableElement $container = null)
    {
        $node = $this->fieldExists($field, $container);
        $actual = (string) $node->getValue();
        $regex = '/^'.preg_quote($value, '/').'$/ui';

        $message = sprintf('The field "%s" value is "%s", but it should not be.', $field, $actual);

        $this->assert(!preg_match($regex, $actual), $message);
    }

    /**
     * Checks that specific checkbox is checked.
     *
     * @param string             $field     field id|name|label|value
     * @param TraversableElement $container document to check against
     *
     * @throws ExpectationException
     */
    public function checkboxChecked($field, TraversableElement $container = null)
    {
        $node = $this->fieldExists($field, $container);

        $this->assert($node->isChecked(), sprintf('Checkbox "%s" is not checked, but it should be.', $field));
    }

    /**
     * Checks that specific checkbox is unchecked.
     *
     * @param string             $field     field id|name|label|value
     * @param TraversableElement $container document to check against
     *
     * @throws ExpectationException
     */
    public function checkboxNotChecked($field, TraversableElement $container = null)
    {
        $node = $this->fieldExists($field, $container);

        $this->assert(!$node->isChecked(), sprintf('Checkbox "%s" is checked, but it should not be.', $field));
    }

    /**
     * Gets current url of the page.
     *
     * @return string
     */
    protected function getCurrentUrlPath()
    {
        return $this->cleanUrl($this->session->getCurrentUrl());
    }

    /**
     * Trims scriptname from the URL.
     *
     * @param string $url
     *
     * @return string
     */
    protected function cleanUrl($url)
    {
        $parts = parse_url($url);
        $fragment = empty($parts['fragment']) ? '' : '#'.$parts['fragment'];
        $path = empty($parts['path']) ? '/' : $parts['path'];

        return preg_replace('/^\/[^\.\/]+\.php\//', '/', $path).$fragment;
    }

    /**
     * Asserts a condition.
     *
     * @param bool   $condition
     * @param string $message   Failure message
     *
     * @throws ExpectationException when the condition is not fulfilled
     */
    private function assert($condition, $message)
    {
        if ($condition) {
            return;
        }

        throw new ExpectationException($message, $this->session->getDriver());
    }

    /**
     * Asserts a condition involving the response text.
     *
     * @param bool   $condition
     * @param string $message   Failure message
     *
     * @throws ResponseTextException when the condition is not fulfilled
     */
    private function assertResponseText($condition, $message)
    {
        if ($condition) {
            return;
        }

        throw new ResponseTextException($message, $this->session->getDriver());
    }

    /**
     * Asserts a condition on an element.
     *
     * @param bool    $condition
     * @param string  $message   Failure message
     * @param Element $element
     *
     * @throws ElementHtmlException when the condition is not fulfilled
     */
    private function assertElement($condition, $message, Element $element)
    {
        if ($condition) {
            return;
        }

        throw new ElementHtmlException($message, $this->session->getDriver(), $element);
    }

    /**
     * Asserts a condition involving the text of an element.
     *
     * @param bool    $condition
     * @param string  $message   Failure message
     * @param Element $element
     *
     * @throws ElementTextException when the condition is not fulfilled
     */
    private function assertElementText($condition, $message, Element $element)
    {
        if ($condition) {
            return;
        }

        throw new ElementTextException($message, $this->session->getDriver(), $element);
    }

    /**
     * @param string       $selectorType
     * @param string|array $selector
     * @param bool         $plural
     *
     * @return string
     */
    private function getMatchingElementRepresentation($selectorType, $selector, $plural = false)
    {
        $pluralization = $plural ? 's' : '';

        if (in_array($selectorType, array('named', 'named_exact', 'named_partial'))
            && is_array($selector) && 2 === count($selector)
        ) {
            return sprintf('%s%s matching locator "%s"', $selector[0], $pluralization, $selector[1]);
        }

        if (is_array($selector)) {
            $selector = implode(' ', $selector);
        }

        return sprintf('element%s matching %s "%s"', $pluralization, $selectorType, $selector);
    }
}


text:
import saspy

class Utilities:
    def __init__(self, session = None):
        if session is None:
            self.sas = saspy.SASsession(cfgname=saspy.SASsession().sascfg.SAScfg.SAS_config_names[0])
        else:
            self.sas = session

    def procExists(self, plist: list) -> bool:
        """
        Checks to see if the given list of procs exist on the instance.
        :param plist: A list of procs.
        :return:      True if all procs are found, False otherwise
        """
        assert isinstance(plist, list)
        for proc in plist:
            res = self.sas.submit("proc %s; run;" % proc)
            log = res['LOG'].splitlines()
            for line in log:
                if line == 'ERROR: Procedure %s not found.' % proc.upper():
                    return False
        return True

    def procLicensed(self, plist):
        """
        Checks to see if the given list of procs are licensed on the instance.
        :param plist: A list of procs.
        :return:      True if all procs are licensed, false otherwise.
        """
        assert isinstance(plist, list)
        for proc in plist:
            res = self.sas.submit("proc %s; run;" % proc)
            log = res['LOG'].splitlines()
            for line in log:
                if line == 'ERROR: Bad product ID for procedure %s.' % proc.upper():
                    return False
        return True

    def procFound(self, plist):
        """
        Determines if the procs listed are usable on the available sas instance.
        """
        return self.procExists(plist) and self.procLicensed(plist)

redpajama_set_name: RedPajamaGithub


text:
package com.sap.prd.mobile.ios.ota.lib;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestUtils
{

  public static void assertContains(String expected, String value)
  {
    if (!value.contains(expected)) {
      fail(String.format("Expected is contained: '%s' but was '%s'", expected, value));
    }
  }

  public static void assertOtaLink(CharSequence s, String plistURL, String bundleIdentifier)
  {
    Pattern checkOtaLinkPattern = Pattern.compile("href='itms-services:///\\?action=download-manifest&url=([^']+)'>Install Over-The-Air</a>");
    Matcher checkOtaLinkMatcher = checkOtaLinkPattern.matcher(s);
    assertTrue("Ota link not found in "+s, checkOtaLinkMatcher.find());
    assertEquals(plistURL, checkOtaLinkMatcher.group(1));
  }

}


text:
/**
 * @generated SignedSource<<15bdc0c7f2084a4986f965f5c3df540b>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { ConcreteRequest, Query } from 'relay-runtime';
import { FragmentRefs } from "relay-runtime";
export type MarketStatsQuery$variables = {
  artistInternalID: string;
};
export type MarketStatsQuery$data = {
  readonly priceInsightsConnection: {
    readonly " $fragmentSpreads": FragmentRefs<"MarketStats_priceInsightsConnection">;
  } | null;
};
export type MarketStatsQuery = {
  response: MarketStatsQuery$data;
  variables: MarketStatsQuery$variables;
};

const node: ConcreteRequest = (function(){
var v0 = [
  {
    "defaultValue": null,
    "kind": "LocalArgument",
    "name": "artistInternalID"
  }
],
v1 = [
  {
    "kind": "Variable",
    "name": "artistId",
    "variableName": "artistInternalID"
  },
  {
    "kind": "Literal",
    "name": "sort",
    "value": "ANNUAL_VALUE_SOLD_CENTS_DESC"
  }
];
return {
  "fragment": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Fragment",
    "metadata": null,
    "name": "MarketStatsQuery",
    "selections": [
      {
        "alias": "priceInsightsConnection",
        "args": (v1/*: any*/),
        "concreteType": "PriceInsightConnection",
        "kind": "LinkedField",
        "name": "priceInsights",
        "plural": false,
        "selections": [
          {
            "args": null,
            "kind": "FragmentSpread",
            "name": "MarketStats_priceInsightsConnection"
          }
        ],
        "storageKey": null
      }
    ],
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Operation",
    "name": "MarketStatsQuery",
    "selections": [
      {
        "alias": "priceInsightsConnection",
        "args": (v1/*: any*/),
        "concreteType": "PriceInsightConnection",
        "kind": "LinkedField",
        "name": "priceInsights",
        "plural": false,
        "selections": [
          {
            "alias": null,
            "args": null,
            "concreteType": "PriceInsightEdge",
            "kind": "LinkedField",
            "name": "edges",
            "plural": true,
            "selections": [
              {
                "alias": null,
                "args": null,
                "concreteType": "MarketPriceInsights",
                "kind": "LinkedField",
                "name": "node",
                "plural": false,
                "selections": [
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "medium",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "annualLotsSold",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "annualValueSoldCents",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "sellThroughRate",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "medianSaleOverEstimatePercentage",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "id",
                    "storageKey": null
                  }
                ],
                "storageKey": null
              }
            ],
            "storageKey": null
          }
        ],
        "storageKey": null
      }
    ]
  },
  "params": {
    "cacheID": "493670ff35fcfa2c2a856f7060338013",
    "id": null,
    "metadata": {},
    "name": "MarketStatsQuery",
    "operationKind": "query",
    "text": "query MarketStatsQuery(\n  $artistInternalID: ID!\n) {\n  priceInsightsConnection: priceInsights(artistId: $artistInternalID, sort: ANNUAL_VALUE_SOLD_CENTS_DESC) {\n    ...MarketStats_priceInsightsConnection\n  }\n}\n\nfragment MarketStats_priceInsightsConnection on PriceInsightConnection {\n  edges {\n    node {\n      medium\n      annualLotsSold\n      annualValueSoldCents\n      sellThroughRate\n      medianSaleOverEstimatePercentage\n      id\n    }\n  }\n}\n"
  }
};
})();

(node as any).hash = "b8c04641b23e82c0ad5fb0e068f340a0";

export default node;


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.geospatial.serde;

import com.esri.core.geometry.ogc.OGCGeometry;
import com.google.common.base.Joiner;
import io.airlift.slice.Slice;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;

import static com.esri.core.geometry.ogc.OGCGeometry.fromText;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.GEOMETRYCOLLECTION;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.LINESTRING;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.MULTILINESTRING;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.MULTIPOINT;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.MULTIPOLYGON;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.POINT;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.POLYGON;
import static com.facebook.presto.geospatial.serde.BenchmarkGeometrySerializationData.readResource;
import static com.facebook.presto.geospatial.serde.GeometrySerde.deserialize;
import static com.facebook.presto.geospatial.serde.GeometrySerde.deserializeEnvelope;
import static com.facebook.presto.geospatial.serde.GeometrySerde.serialize;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.openjdk.jmh.annotations.Mode.Throughput;

@State(Scope.Thread)
@Fork(2)
@Warmup(iterations = 3, time = 3, timeUnit = SECONDS)
@Measurement(iterations = 5, time = 4, timeUnit = SECONDS)
@OutputTimeUnit(SECONDS)
@BenchmarkMode(Throughput)
public class BenchmarkGeometrySerde
{
    // POINT
    @Benchmark
    public Object serializePoint(BenchmarkData data)
    {
        return serialize(data.point);
    }

    @Benchmark
    public Object deserializePoint(BenchmarkData data)
    {
        return deserialize(data.pointSerialized);
    }

    @Benchmark
    public Object deserializePointEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.pointSerialized);
    }

    // MULTI POINT
    @Benchmark
    public Object serializeSimpleMultipoint(BenchmarkData data)
    {
        return serialize(data.simpleMultipoint);
    }

    @Benchmark
    public Object deserializeSimpleMultipoint(BenchmarkData data)
    {
        return deserialize(data.simpleMultipointSerialized);
    }

    @Benchmark
    public Object deserializeSimpleMultipointEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simpleMultipointSerialized);
    }

    @Benchmark
    public Object serializeComplexMultipoint(BenchmarkData data)
    {
        return serialize(data.complexMultipoint);
    }

    @Benchmark
    public Object deserializeComplexMultipoint(BenchmarkData data)
    {
        return deserialize(data.complexMultipointSerialized);
    }

    @Benchmark
    public Object deserializeComplexMultipointEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexMultipointSerialized);
    }

    // LINE STRING
    @Benchmark
    public Object serializeSimpleLineString(BenchmarkData data)
    {
        return serialize(data.simpleLineString);
    }

    @Benchmark
    public Object deserializeSimpleLineString(BenchmarkData data)
    {
        return deserialize(data.simpleLineStringSerialized);
    }

    @Benchmark
    public Object deserializeSimpleLineStringEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simpleLineStringSerialized);
    }

    @Benchmark
    public Object serializeComplexLineString(BenchmarkData data)
    {
        return serialize(data.complexLineString);
    }

    @Benchmark
    public Object deserializeComplexLineString(BenchmarkData data)
    {
        return deserialize(data.complexLineStringSerialized);
    }

    @Benchmark
    public Object deserializeComplexLineStringEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexLineStringSerialized);
    }

    // MULTILINE STRING
    @Benchmark
    public Object serializeSimpleMultiLineString(BenchmarkData data)
    {
        return serialize(data.simpleMultiLineString);
    }

    @Benchmark
    public Object deserializeSimpleMultiLineString(BenchmarkData data)
    {
        return deserialize(data.simpleMultiLineStringSerialized);
    }

    @Benchmark
    public Object deserializeSimpleMultiLineStringEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simpleMultiLineStringSerialized);
    }

    @Benchmark
    public Object serializeComplexMultiLineString(BenchmarkData data)
    {
        return serialize(data.complexMultiLineString);
    }

    @Benchmark
    public Object deserializeComplexMultiLineString(BenchmarkData data)
    {
        return deserialize(data.complexMultiLineStringSerialized);
    }

    @Benchmark
    public Object deserializeComplexMultiLineStringEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexMultiLineStringSerialized);
    }

    // POLYGON
    @Benchmark
    public Object serializeSimplePolygon(BenchmarkData data)
    {
        return serialize(data.simplePolygon);
    }

    @Benchmark
    public Object deserializeSimplePolygon(BenchmarkData data)
    {
        return deserialize(data.simplePolygonSerialized);
    }

    @Benchmark
    public Object deserializeSimplePolygonEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simplePolygonSerialized);
    }

    @Benchmark
    public Object serializeComplexPolygon(BenchmarkData data)
    {
        return serialize(data.complexPolygon);
    }

    @Benchmark
    public Object deserializeComplexPolygon(BenchmarkData data)
    {
        return deserialize(data.complexPolygonSerialized);
    }

    @Benchmark
    public Object deserializeComplexPolygonEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexPolygonSerialized);
    }

    // MULTI POLYGON
    @Benchmark
    public Object serializeSimpleMultiPolygon(BenchmarkData data)
    {
        return serialize(data.simpleMultiPolygon);
    }

    @Benchmark
    public Object deserializeSimpleMultiPolygon(BenchmarkData data)
    {
        return deserialize(data.simpleMultiPolygonSerialized);
    }

    @Benchmark
    public Object deserializeSimpleMultiPolygonEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simpleMultiPolygonSerialized);
    }

    @Benchmark
    public Object serializeComplexMultiPolygon(BenchmarkData data)
    {
        return serialize(data.complexMultiPolygon);
    }

    @Benchmark
    public Object deserializeComplexMultiPolygon(BenchmarkData data)
    {
        return deserialize(data.complexMultiPolygonSerialized);
    }

    @Benchmark
    public Object deserializeComplexMultiPolygonEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexMultiPolygonSerialized);
    }

    // GEOMETRY COLLECTION
    @Benchmark
    public Object serializeSimpleGeometryCollection(BenchmarkData data)
    {
        return serialize(data.simpleGeometryCollection);
    }

    @Benchmark
    public Object deserializeSimpleGeometryCollection(BenchmarkData data)
    {
        return deserialize(data.simpleGeometryCollectionSerialized);
    }

    @Benchmark
    public Object deserializeSimpleGeometryCollectionEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.simpleGeometryCollectionSerialized);
    }

    @Benchmark
    public Object serializeComplexGeometryCollection(BenchmarkData data)
    {
        return serialize(data.complexGeometryCollection);
    }

    @Benchmark
    public Object deserializeComplexGeometryCollection(BenchmarkData data)
    {
        return deserialize(data.complexGeometryCollectionSerialized);
    }

    @Benchmark
    public Object deserializeComplexGeometryCollectionEnvelope(BenchmarkData data)
    {
        return deserializeEnvelope(data.complexGeometryCollectionSerialized);
    }

    @State(Scope.Thread)
    public static class BenchmarkData
    {
        // POINT
        private OGCGeometry point;
        private Slice pointSerialized;

        // MULTI POINT
        private OGCGeometry simpleMultipoint;
        private Slice simpleMultipointSerialized;
        private OGCGeometry complexMultipoint;
        private Slice complexMultipointSerialized;

        // LINE STRING
        private OGCGeometry simpleLineString;
        private Slice simpleLineStringSerialized;
        private OGCGeometry complexLineString;
        private Slice complexLineStringSerialized;

        // MULTILINE STRING
        private OGCGeometry simpleMultiLineString;
        private Slice simpleMultiLineStringSerialized;
        private OGCGeometry complexMultiLineString;
        private Slice complexMultiLineStringSerialized;

        // POLYGON
        private OGCGeometry simplePolygon;
        private Slice simplePolygonSerialized;
        private OGCGeometry complexPolygon;
        private Slice complexPolygonSerialized;

        // MULTI POLYGON
        private OGCGeometry simpleMultiPolygon;
        private Slice simpleMultiPolygonSerialized;
        private OGCGeometry complexMultiPolygon;
        private Slice complexMultiPolygonSerialized;

        // COLLECTION
        private OGCGeometry simpleGeometryCollection;
        private Slice simpleGeometryCollectionSerialized;
        private OGCGeometry complexGeometryCollection;
        private Slice complexGeometryCollectionSerialized;

        @Setup
        public void setup()
        {
            point = fromText(POINT);
            pointSerialized = serialize(point);

            simpleMultipoint = fromText(MULTIPOINT);
            simpleMultipointSerialized = serialize(simpleMultipoint);
            complexMultipoint = fromText(readResource("complex-multipoint.txt"));
            complexMultipointSerialized = serialize(complexMultipoint);

            simpleLineString = fromText(LINESTRING);
            simpleLineStringSerialized = serialize(simpleLineString);
            complexLineString = fromText(readResource("complex-linestring.txt"));
            complexLineStringSerialized = serialize(complexLineString);

            simpleMultiLineString = fromText(MULTILINESTRING);
            simpleMultiLineStringSerialized = serialize(simpleMultiLineString);
            complexMultiLineString = fromText(readResource("complex-multilinestring.txt"));
            complexMultiLineStringSerialized = serialize(complexMultiLineString);

            simplePolygon = fromText(POLYGON);
            simplePolygonSerialized = serialize(simplePolygon);
            complexPolygon = fromText(readResource("complex-polygon.txt"));
            complexPolygonSerialized = serialize(complexPolygon);

            simpleMultiPolygon = fromText(MULTIPOLYGON);
            simpleMultiPolygonSerialized = serialize(simpleMultiPolygon);
            complexMultiPolygon = fromText(readResource("complex-multipolygon.txt"));
            complexMultiPolygonSerialized = serialize(complexMultiPolygon);

            simpleGeometryCollection = fromText(GEOMETRYCOLLECTION);
            simpleGeometryCollectionSerialized = serialize(simpleGeometryCollection);
            complexGeometryCollection = fromText("GEOMETRYCOLLECTION (" + Joiner.on(", ").join(
                    readResource("complex-multipoint.txt"),
                    readResource("complex-linestring.txt"),
                    readResource("complex-multilinestring.txt"),
                    readResource("complex-polygon.txt"),
                    readResource("complex-multipolygon.txt")) + ")");
            complexGeometryCollectionSerialized = serialize(complexGeometryCollection);
        }
    }

    public static void main(String[] args)
            throws RunnerException
    {
        Options options = new OptionsBuilder()
                .verbosity(VerboseMode.NORMAL)
                .include(".*" + BenchmarkGeometrySerde.class.getSimpleName() + ".*")
                .build();
        new Runner(options).run();
    }
}


text:
"""
StatsFunctions.py

Statistics functions to assess the performance of an estimator

Author: Ashiv Dhondea, RRSG, UCT.

Date: 23 November 2016

Edited:
23 November 2016: added function fnCalcNees and fnChiSquaredTest to calculate the NEES and perform the Chi-Squared test.
13 December 2016: changed the name of fnCalcNees to fnCalc_NEES. Made sure that the NEES is normalized.
09/03/2017: added the function fnCalc_NES
19/03/2017: cleaned up several functions.
20/03/2017: rewrote the 3sigma test
22/09/2017: added a comment to fn3SigmaTest
28/09/2017: added the function fnCalculate_MSEs

Theoretical background:
1. Tracking Filter Engineering, Norman Morrison. 2013.
2. Estimation with applications to tracking and navigation. Bar Shalom.
"""
import numpy as np
import MathsFunctions as MathsFn
# -------------------------------------------------------------------------------------------------- #
## NEES according to Bar Shalom book. 23.11.16
def fnCalc_NEES(errorvec,covmat):
    simul = np.shape(errorvec)[1];
    nVars = float(np.shape(errorvec)[0]);
    nees = np.zeros([simul],dtype=np.float64);
    for index in range(0,simul):
        nees[index] = MathsFn.fn_invSymQuadForm(errorvec[:,index],covmat[:,:,index]); # edited: 09/03/17: used a faster implementation of invsymquadform
    return nees/nVars # edited: 13/12/16: reminder that the NEES is NORMALIZED by the dimensionality of the state vector

## One-shot Chi-squared test according to Tracking Filter Engineering book. 23.11.16
def fnChiSquaredTest(errorvec,covmat):
    nees = fnCalc_NEES(errorvec,covmat);
    #dx = 6; # we already know dx =6 in this project.
    simul = np.shape(errorvec)[1];
    threshold_6 = 16.81;
    chi_metric = np.full([simul],False,dtype=np.bool); # edited: 20/03/17
    for index in range(0,simul):
        if nees[index] < threshold_6:
            chi_metric[index] = True;
    return chi_metric

## One-shot 3-sigma test according to Tracking Filter Engineering book. 23.11.16
def fn3SigmaTest(errorvec,covmat):
    """
    3-sigma test
    Created: 19 March 2017
    Edited:
    20/03/17: rewrote according to the theory in TFE
	22/09/17: added a comment
    """
    dx = np.shape(errorvec)[0];
    simul = np.shape(errorvec)[1];
    three_sigma_metric = np.full([dx,simul],False,dtype=np.bool);
    three_sigma_bounds = np.zeros([dx,simul],dtype=np.float64);
    for index in range(0,simul):
        three_sigma_bounds[:,index] = 3.*np.sqrt(np.diagonal(covmat[0:dx,0:dx,index])); # edited: 20/03/17
        three_sigma_metric[:,index] = np.less_equal(np.absolute(errorvec[:,index]),three_sigma_bounds[:,index]); # edited: 13/11/17
        """
        Comment: 22.09.17
        np.less_equal([4, 2, 1], [2, 2, 2])
        array([False,  True,  True], dtype=bool)

        meaning return False if errorvec[:,index] not less or equal to three_sigma_bounds[:,index]
        """

    return three_sigma_metric, three_sigma_bounds

# --------------------------------------------------------------------------- #
## NES according to Bar Shalom book.
def fnCalc_NES(errorvec,covmat):
    """
    Calculate the Normalized Error Squared

    Created: 09 March 2017
    """
    nVars = np.shape(errorvec)[0];
    nes = MathsFn.fn_invSymQuadForm(errorvec,covmat);
    return nes/float(nVars)
# --------------------------------------------------------------------------- #
def fnCalculate_MSE(x_error):
    """
    Calculate the means squared error in the estimated error vector

    x_error is dx by num_mc by len(timevec)
    Created on: 28/09/17
    """
    dx = np.shape(x_error)[0]; num_MC = np.shape(x_error)[1];l_timevec=np.shape(x_error)[2];
    sqr_error = np.zeros([dx,num_MC,l_timevec],dtype=np.float64);
    means_sqr_error =  np.zeros([dx,l_timevec],dtype=np.float64);

    for i_t in range(0,l_timevec):
        for i_mc in range(0,num_MC):
            # Square the error
            sqr_error[:,i_mc,i_t] = np.square(x_error[:,i_mc,i_t]);
        # add all squared errors to reduce by the number of Monte Carlo runs
        means_sqr_error[:,i_t]= np.sum(sqr_error[:,:,i_t],axis=1)/num_MC;
        #divide by number of Monte Carlo runs to averag

    return means_sqr_error


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Jaxxes\RolBundle\RolBundle(),
            new Jaxxes\ResumeBundle\ResumeBundle(),
            new Jaxxes\VirtualInterviewBundle\VirtualInterviewBundle(),
            new Jaxxes\SeleccionProcesBundle\SeleccionProcesBundle(),
            new Jaxxes\RegisterDefinitionRolBundle\RegisterDefinitionRolBundle(),
            new Jaxxes\CandidateBundle\CandidateBundle(),
            new Jaxxes\EnterpriseBundle\EnterpriseBundle(),
            new Jaxxes\GeneralBundle\GeneralBundle(),
            new Jaxxes\DefinitionTestBundle\DefinitionTestBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Jaxxes\NivelBundle\NivelBundle(),
            new Jaxxes\TestGatbBundle\TestGatbBundle(),
            new Jaxxes\TestGatbSPBundle\TestGatbSPBundle(),
            new Jaxxes\EscudoSPBundle\EscudoSPBundle(),
            new Jaxxes\EscudoBundle\EscudoBundle(),
            new Jaxxes\TestICEBundle\TestICEBundle(),
            new Jaxxes\TestICESPBundle\TestICESPBundle(),
            new Jaxxes\TestPmaBundle\TestPmaBundle(),
            new Jaxxes\TestPmaSPBundle\TestPmaSPBundle(),
            new Jaxxes\RavenBundle\RavenBundle(),
            new Jaxxes\RavenSPBundle\RavenSPBundle(),
            new Knp\Bundle\SnappyBundle\KnpSnappyBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
/*            $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();*/
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
IP='104.236.105.218'
VERSION=$(awk '/version/{gsub(/("|",)/,"",$2);print $2};' package.json)
HASH=$(git rev-parse head)
TODAY=$(date)
USER=$(whoami)
KEY="/Users/$USER/.ssh/id_rsa"

# Now package and move to server
echo "Cleaning distribution folder..."
rm -rf dist
echo "Compiling production build..."
npm run build
echo "Creating log..."
{
  echo "site: space-invaders@www.nathanielinman.com";
  echo "date: $TODAY";
  echo "user: $USER";
  echo "hash: $HASH";
  echo "application: space-invaders";
  echo "version: $VERSION";
} > ./dist/deploy.txt
echo "Packaging files..."
cd ./dist
tar -czvf ../space-invaders.tar.gz .
cd ../
echo "Moving files to server..."
rsync -avhtz -e "ssh -i $KEY" space-invaders.tar.gz nate@$IP:./
echo "Extracting files..."
ssh -i "$KEY" nate@$IP << EOF
  sudo rm -rf /var/www/space-invaders
  sudo mkdir /var/www/space-invaders
  sudo tar -C /var/www/space-invaders -zxvf space-invaders.tar.gz
EOF
echo "Cleaning up deployment files..."
rm ./space-invaders.tar.gz
echo "Verifying successful deploy..."
sleep 5
curl https://space-invaders.nathanielinman.com/deploy.txt


text:
//  This file is part of MOS, the MANTIS Operating System
//  See http://mantis.cs.colorado.edu/
//
//  Copyright (c) 2002 - 2007 University of Colorado, Boulder
//
//   All rights reserved.
//
//   Redistribution and use in source and binary forms, with or without
//   modification, are permitted provided that the following conditions are
//   met:
//
//       * Redistributions of source code must retain the above copyright
//         notice, this list of conditions and the following disclaimer.
//       * Redistributions in binary form must reproduce the above
//         copyright notice, this list of conditions and the following
//         disclaimer in the documentation and/or other materials provided
//         with the distribution.
//       * Neither the name of the MANTIS Project nor the names of its
//         contributors may be used to endorse or promote products derived
//         from this software without specific prior written permission.
//
//   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
//   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//   POSSIBILITY OF SUCH DAMAGE.

/** @file msp430/include/plat_dep.h
 * @brief MSP430 Platform specific functions used in the kernel
 *
 */

#ifndef __PLAT_DEP_H__
#define __PLAT_DEP_H__

#include <sys/types.h>
#include <signal.h>
#include <io.h>

#include "mos.h"

// 10k of RAM
/** @brief Total bytes of memory */
#define MEMORY_SIZE 10240
#define MEMORY_BASE 0x1100
#define ARCH_PROGMEM

#define RAMFUNC __attribute__ ((section (".data")))

#define SETUP_SOFT_INT() do{     \
   P2DIR |=  (1 << 5);           \
   P2SEL |=  (1 << 5);           \
   P2IES &= ~(1 << 5);           \
   P2IE  |=  (1 << 5);           \
}while(0)

#define DISABLE_SOFT_INT() P2IFG &= ~(1 << 5)
#define DO_SOFT_INT()      P2IFG |=  (1 << 5)

// not necessary for msp430
#define WAIT_FOR_ASYNC_UPDATE()

// stack pointer type
typedef uint16_t stackval_t;

//16bit address space
typedef stackval_t memtype_t;

// size of the SR -- used for mos_(enable|disable)_ints();
typedef uint16_t handle_t;

// minimum stack size
#define MIN_STACK_SIZE 128

#define ENABLE_INTS() eint()
#define DISABLE_INTS() dint()

#define PRE_KERNEL_SLEEP()
#define POST_KERNEL_SLEEP()

// turn off TimerA
#define DISABLE_ALARM_TIMER() TACTL &= ~(MC_3)
// start TimerA
#define ENABLE_ALARM_TIMER() TACTL |= MC_UPTO_CCR0

#define ALARM_TIMER_VALUE (TAR)
// make sure the interrupt was triggered
// because of an overflow
#define ALARM_TIMER_EXPIRED (TAIV == 10)

#define SET_ALARM_TIMER_VALUE(value) TAR = value
#define SET_ALARM_OCR_VALUE(value) TACCR0  = value

// turn off TimerB
#define DISABLE_SLEEP_TIMER() TBCTL &= ~(MC_3)
// start TimerB
#define ENABLE_SLEEP_TIMER() TBCTL |= MC_UPTO_CCR0
#define SET_SLEEP_TIMER_VALUE(time) TBR = time
#define SET_SLEEP_OCR_VALUE(value) TBCCR0  = value
// make sure the interrupt was triggered
// because of a capture
#define SLEEP_TIMER_EXPIRED (TBIV == 14)

// msp430 doesn't need to do anything special
// to enable low power modes
#define ENABLE_SLEEP()
#define ENABLE_IDLE()

// set low power mode bits in the SR to sleep
#define SLEEP() _BIS_SR(LPM3_bits)
#define IDLE() _BIS_SR(LPM0_bits)

#define SOFT_INT_HEADER()   interrupt (PORT2_VECTOR) soft_trig_int()
#define SLEEP_INT_HEADER()  interrupt (TIMERB1_VECTOR) sleep_wake_int()
#define ALARM_INT_HEADER() interrupt (TIMERA1_VECTOR) tslice_sig_int()

/** @brief Initialize the hardware timer
 * This timer is used for the kernel time slice.
 */
void kernel_timer_init(void);

/** @brief initialize the timer used for sleeping
 *
 */
void sleep_timer_init(void);

/** @brief enables interrupts
 *
 */
#define mos_enable_ints(int_handle) WRITE_SR(int_handle)

/** @brief disables interrupts
 *
 */
handle_t mos_disable_ints(void);

#define GET_SP(sp) {		\
      asm volatile(		\
	 "mov.w r1, %0\n\t"	\
	 :"=r" (sp) : );	\
	 }

#define srandom(seed) srand(seed)

/** @brief recalibrates the DCO to CLOCK_SPEED from plat_clock.h.
 * this function sources Timer A off of the DCO, then calculates an adjustment to the DCO based on how long it takes Timer A to overflow. */
void mos_recalibrate_dco(void);

/** @brief using the DCO to calculate 1 MS intervals is more accurate than using the 32 Khz timer; unfortunantly the DCO can vary in speed due to change in temperature, humidity, etc.  use mos_recalibrate_dco() to readjust the DCO speed. */
//#define TIMESLICE_USE_DCO

// this value should be 32, but the clock divisor is set to 2 by clock_init().
#define TIMESLICE_20_MS (32)

#endif


text:
<?php

namespace Elasticsearch\Common\Exceptions;

/**
 * NoNodesAvailableException
 *
 * @category Elasticsearch
 * @package  Elasticsearch\Common\Exceptions
 * @author   Zachary Tong <zach@elastic.co>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
 * @link     http://elastic.co
 */
class NoNodesAvailableException extends \Exception implements ElasticsearchException
{
}


text:
/// A ClientContext allows the person implementing a service client to:
///
/// - Add custom metadata key-value pairs that will propagated to the server
/// side.
/// - Control call settings such as compression and authentication.
/// - Initial and trailing metadata coming from the server.
/// - Get performance metrics (ie, census).
///
/// Context settings are only relevant to the call they are invoked with, that
/// is to say, they aren't sticky. Some of these settings, such as the
/// compression options, can be made persistant at channel construction time
/// (see \a grpc::CreateCustomChannel).
///
/// \warning ClientContext instances should \em not be reused across rpcs.

#ifndef GRPCXX_CLIENT_CONTEXT_H
#define GRPCXX_CLIENT_CONTEXT_H

#include <map>
#include <memory>
#include <string>

#include <grpc/compression.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpc++/security/auth_context.h>
#include <grpc++/support/config.h>
#include <grpc++/support/status.h>
#include <grpc++/support/string_ref.h>
#include <grpc++/support/time.h>

struct census_context;

namespace grpc {

class Channel;
class CompletionQueue;
class Credentials;
class RpcMethod;
template <class R>
class ClientReader;
template <class W>
class ClientWriter;
template <class R, class W>
class ClientReaderWriter;
template <class R>
class ClientAsyncReader;
template <class W>
class ClientAsyncWriter;
template <class R, class W>
class ClientAsyncReaderWriter;
template <class R>
class ClientAsyncResponseReader;
class ServerContext;

/// Options for \a ClientContext::FromServerContext specifying which traits from
/// the \a ServerContext to propagate (copy) from it into a new \a
/// ClientContext.
///
/// \see ClientContext::FromServerContext
class PropagationOptions {
 public:
  PropagationOptions() : propagate_(GRPC_PROPAGATE_DEFAULTS) {}

  PropagationOptions& enable_deadline_propagation() {
    propagate_ |= GRPC_PROPAGATE_DEADLINE;
    return *this;
  }

  PropagationOptions& disable_deadline_propagation() {
    propagate_ &= ~GRPC_PROPAGATE_DEADLINE;
    return *this;
  }

  PropagationOptions& enable_census_stats_propagation() {
    propagate_ |= GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
    return *this;
  }

  PropagationOptions& disable_census_stats_propagation() {
    propagate_ &= ~GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
    return *this;
  }

  PropagationOptions& enable_census_tracing_propagation() {
    propagate_ |= GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
    return *this;
  }

  PropagationOptions& disable_census_tracing_propagation() {
    propagate_ &= ~GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
    return *this;
  }

  PropagationOptions& enable_cancellation_propagation() {
    propagate_ |= GRPC_PROPAGATE_CANCELLATION;
    return *this;
  }

  PropagationOptions& disable_cancellation_propagation() {
    propagate_ &= ~GRPC_PROPAGATE_CANCELLATION;
    return *this;
  }

  gpr_uint32 c_bitmask() const { return propagate_; }

 private:
  gpr_uint32 propagate_;
};

namespace testing {
class InteropClientContextInspector;
}  // namespace testing

class ClientContext {
 public:
  ClientContext();
  ~ClientContext();

  /// Create a new \a ClientContext as a child of an incoming server call,
  /// according to \a options (\see PropagationOptions).
  ///
  /// \param server_context The source server context to use as the basis for
  /// constructing the client context.
  /// \param options The options controlling what to copy from the \a
  /// server_context.
  ///
  /// \return A newly constructed \a ClientContext instance based on \a
  /// server_context, with traits propagated (copied) according to \a options.
  static std::unique_ptr<ClientContext> FromServerContext(
      const ServerContext& server_context,
      PropagationOptions options = PropagationOptions());

  /// Add the (\a meta_key, \a meta_value) pair to the metadata associated with
  /// a client call. These are made available at the server side by the \a
  /// grpc::ServerContext::client_metadata() method.
  ///
  /// \warning This method should only be called before invoking the rpc.
  ///
  /// \param meta_key The metadata key. If \a meta_value is binary data, it must
  /// end in "-bin".
  /// \param meta_value The metadata value. If its value is binary, it must be
  /// base64-encoding (see https://tools.ietf.org/html/rfc4648#section-4) and \a
  /// meta_key must end in "-bin".
  void AddMetadata(const grpc::string& meta_key,
                   const grpc::string& meta_value);

  /// Return a collection of initial metadata key-value pairs. Note that keys
  /// may happen more than once (ie, a \a std::multimap is returned).
  ///
  /// \warning This method should only be called after initial metadata has been
  /// received. For streaming calls, see \a
  /// ClientReaderInterface::WaitForInitialMetadata().
  ///
  /// \return A multimap of initial metadata key-value pairs from the server.
  const std::multimap<grpc::string_ref, grpc::string_ref>&
  GetServerInitialMetadata() {
    GPR_ASSERT(initial_metadata_received_);
    return recv_initial_metadata_;
  }

  /// Return a collection of trailing metadata key-value pairs. Note that keys
  /// may happen more than once (ie, a \a std::multimap is returned).
  ///
  /// \warning This method is only callable once the stream has finished.
  ///
  /// \return A multimap of metadata trailing key-value pairs from the server.
  const std::multimap<grpc::string_ref, grpc::string_ref>&
  GetServerTrailingMetadata() {
    // TODO(yangg) check finished
    return trailing_metadata_;
  }

  /// Set the deadline for the client call.
  ///
  /// \warning This method should only be called before invoking the rpc.
  ///
  /// \param deadline the deadline for the client call. Units are determined by
  /// the type used.
  template <typename T>
  void set_deadline(const T& deadline) {
    TimePoint<T> deadline_tp(deadline);
    deadline_ = deadline_tp.raw_time();
  }

#ifndef GRPC_CXX0X_NO_CHRONO
  /// Return the deadline for the client call.
  std::chrono::system_clock::time_point deadline() {
    return Timespec2Timepoint(deadline_);
  }
#endif  // !GRPC_CXX0X_NO_CHRONO

  /// Return a \a gpr_timespec representation of the client call's deadline.
  gpr_timespec raw_deadline() { return deadline_; }

  /// Set the per call authority header (see
  /// https://tools.ietf.org/html/rfc7540#section-8.1.2.3).
  void set_authority(const grpc::string& authority) { authority_ = authority; }

  /// Return the authentication context for this client call.
  ///
  /// \see grpc::AuthContext.
  std::shared_ptr<const AuthContext> auth_context() const;

  /// Set credentials for the client call.
  ///
  /// A credentials object encapsulates all the state needed by a client to
  /// authenticate with a server and make various assertions, e.g., about the
  /// client's identity, role, or whether it is authorized to make a particular
  /// call.
  ///
  /// \see  https://github.com/grpc/grpc/blob/master/doc/grpc-auth-support.md
  void set_credentials(const std::shared_ptr<Credentials>& creds) {
    creds_ = creds;
  }

  /// Return the compression algorithm to be used by the client call.
  grpc_compression_algorithm compression_algorithm() const {
    return compression_algorithm_;
  }

  /// Set \a algorithm to be the compression algorithm used for the client call.
  ///
  /// \param algorith The compression algorithm used for the client call.
  void set_compression_algorithm(grpc_compression_algorithm algorithm);

  /// Return the peer uri in a string.
  ///
  /// \warning This value is never authenticated or subject to any security
  /// related code. It must not be used for any authentication related
  /// functionality. Instead, use auth_context.
  ///
  /// \return The call's peer URI.
  grpc::string peer() const;

  /// Get and set census context
  void set_census_context(struct census_context* ccp) { census_context_ = ccp; }
  struct census_context* census_context() const {
    return census_context_;
  }

  /// Send a best-effort out-of-band cancel. The call could be in any stage.
  /// e.g. if it is already finished, it may still return success.
  ///
  /// There is no guarantee the call will be cancelled.
  void TryCancel();

 private:
  // Disallow copy and assign.
  ClientContext(const ClientContext&);
  ClientContext& operator=(const ClientContext&);

  friend class ::grpc::testing::InteropClientContextInspector;
  friend class CallOpClientRecvStatus;
  friend class CallOpRecvInitialMetadata;
  friend class Channel;
  template <class R>
  friend class ::grpc::ClientReader;
  template <class W>
  friend class ::grpc::ClientWriter;
  template <class R, class W>
  friend class ::grpc::ClientReaderWriter;
  template <class R>
  friend class ::grpc::ClientAsyncReader;
  template <class W>
  friend class ::grpc::ClientAsyncWriter;
  template <class R, class W>
  friend class ::grpc::ClientAsyncReaderWriter;
  template <class R>
  friend class ::grpc::ClientAsyncResponseReader;
  template <class InputMessage, class OutputMessage>
  friend Status BlockingUnaryCall(Channel* channel, const RpcMethod& method,
                                  ClientContext* context,
                                  const InputMessage& request,
                                  OutputMessage* result);

  grpc_call* call() { return call_; }
  void set_call(grpc_call* call, const std::shared_ptr<Channel>& channel);

  grpc::string authority() { return authority_; }

  bool initial_metadata_received_;
  std::shared_ptr<Channel> channel_;
  grpc_call* call_;
  gpr_timespec deadline_;
  grpc::string authority_;
  std::shared_ptr<Credentials> creds_;
  mutable std::shared_ptr<const AuthContext> auth_context_;
  struct census_context* census_context_;
  std::multimap<grpc::string, grpc::string> send_initial_metadata_;
  std::multimap<grpc::string_ref, grpc::string_ref> recv_initial_metadata_;
  std::multimap<grpc::string_ref, grpc::string_ref> trailing_metadata_;

  grpc_call* propagate_from_call_;
  PropagationOptions propagation_options_;

  grpc_compression_algorithm compression_algorithm_;
};

}  // namespace grpc

#endif  // GRPCXX_CLIENT_CONTEXT_H


text:
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview This test attempts to run a simple piece of guest code. It
 * is intended to be invoked in a number of situations under which the version
 * number of some underlying piece of the infrastructure is incorrect (i.e.,
 * does not match the "expected" version number baked into the "caja.js" file).
 *
 * @author ihab.awad@gmail.com
 * @requires caja, jsunitRun, readyToTest
 */

// Alias the console to capture messages for future matching.

var consoleMessages = "";

// Callback for error checking

var checkErrorsInterval = undefined;

var testConsole = {
  log: function(msg) { consoleMessages += msg; },
  toString: function() { return 'fake console for skew'; }
};

// Register the test case.

jsunitRegister('testVersionSkew', function testVersionSkew() {
  caja.initialize({
    server: '/caja',
    resources: '/caja/testing/skew-0000',
    maxAcceptableSeverity: 'NEW_SYMPTOM',
    console: testConsole
  });
  caja.load(undefined, undefined, function (frame) {
    var extraImports = { x: 4, y: 3 };
    frame.code('fixture-guest.js', 'text/javascript')
         .api(extraImports)
         .run(function(result) {
           clearInterval(checkErrorsInterval);
           // If we succeed in running, we fail the test!
           fail('testVersionSkew');
         });
  });
});

// Start the actual testing.

readyToTest();
jsunitRun();

// Check for error strings in the console and pass if the expected error
// is seen.

function checkErrors() {
  // TODO(ihab.awad): If we can pass the expected error message on the URL
  // to the test, we can look for custom errors for each individual case. We
  // would have to URL-encode/decode the expected message.
  if (/Version error/.test(consoleMessages)) {
    clearInterval(checkErrorsInterval);
    jsunitPass('testVersionSkew');
  }
}

checkErrorsInterval = setInterval(checkErrors, 125);


text:
{-# LINE 1 "System.Mem.hs" #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  System.Mem
-- Copyright   :  (c) The University of Glasgow 2001
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  provisional
-- Portability :  portable
--
-- Memory-related system things.
--
-----------------------------------------------------------------------------

{-# LANGUAGE Trustworthy #-}
-- allocation counter stuff is safe, but GHC.Conc.Sync is Unsafe

module System.Mem
       (
       -- * Garbage collection
         performGC
       , performMajorGC
       , performMinorGC

        -- * Allocation counter and limits
        , setAllocationCounter
        , getAllocationCounter
        , enableAllocationLimit
        , disableAllocationLimit
       ) where

import GHC.Conc.Sync

-- | Triggers an immediate major garbage collection.
performGC :: IO ()
performGC = performMajorGC

-- | Triggers an immediate major garbage collection.
--
-- @since 4.7.0.0
foreign import ccall "performMajorGC" performMajorGC :: IO ()

-- | Triggers an immediate minor garbage collection.
--
-- @since 4.7.0.0
foreign import ccall "performGC" performMinorGC :: IO ()


text:
bool LocalFileOps::getattr(const QLatin1String& path, FileInfo* info)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file getattr" << path;
#endif

    struct stat stbuf;
    int rc = ::lstat(path.latin1(), &stbuf);
    if (rc != 0)
        m_error = errno;
    else if (info) {
        info->setSerialNumber(stbuf.st_ino);
        info->setMode(stbuf.st_mode);
        info->setNumberOfHardLinks(stbuf.st_nlink);
        info->setUserId(stbuf.st_uid);
        info->setGroupId(stbuf.st_gid);
        info->setDeviceId(stbuf.st_rdev);
        info->setSize(stbuf.st_size);
        info->setLastAccess(QDateTime::fromTime_t(stbuf.st_atime));
        info->setLastDataModification(QDateTime::fromTime_t(stbuf.st_mtime));
        info->setLastStatusChange(QDateTime::fromTime_t(stbuf.st_ctime));
        info->setNumberOfBlocks(stbuf.st_blocks);
    }

    return rc == 0;
}

static mode_t permissionsToMode(QFile::Permissions p)
{
    mode_t m = 0;
    if (p & QFile::ReadOwner)   m |= S_IRUSR;
    if (p & QFile::WriteOwner)  m |= S_IWUSR;
    if (p & QFile::ExeOwner)    m |= S_IXUSR;
    if (p & QFile::ReadUser)    m |= S_IRUSR;
    if (p & QFile::WriteUser)   m |= S_IWUSR;
    if (p & QFile::ExeUser)     m |= S_IXUSR;
    if (p & QFile::ReadGroup)   m |= S_IRGRP;
    if (p & QFile::WriteGroup)  m |= S_IWGRP;
    if (p & QFile::ExeGroup)    m |= S_IXGRP;
    if (p & QFile::ReadOther)   m |= S_IROTH;
    if (p & QFile::WriteOther)  m |= S_IWOTH;
    if (p & QFile::ExeOther)    m |= S_IXOTH;
    return m;
}

bool LocalFileOps::create(const QLatin1String& path, QFile::Permissions perm, qint32 flags, quint64* fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file create" << path << perm;
#endif

    int rc = ::open(path.latin1(), O_CREAT | flags, permissionsToMode(perm));
    if (rc == -1)
        m_error = errno;
    else if (fh)
        *fh = rc;
    return rc > 0;
}

bool LocalFileOps::unlink(const QLatin1String& path)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file unlink" << path;
#endif

    int rc = ::unlink(path.latin1());
    if (rc != 0)
        m_error = errno;
    return rc == 0;
}

bool LocalFileOps::open(const QLatin1String& path, qint32 flags, quint64* fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file open" << path << flags << fh;
#endif

    int rc = ::open(path.latin1(), flags);
    if (rc == -1)
        m_error = errno;
    else if (fh)
        *fh = rc;
    return rc > 0;
}

bool LocalFileOps::read(const QLatin1String& path, QByteArray *buffer, qint64 size, qint64 offset, quint64 fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file read" << path << size << offset << fh;
#else
    Q_UNUSED(path);
#endif

    Q_ASSERT(buffer);
    int rc = ::pread(fh, buffer->data(), size, offset);
    if (rc == -1)
        m_error = errno;
    return rc > 0;
}

bool LocalFileOps::release(const QLatin1String& path, qint32 flags, quint64 fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file release" << path << flags << fh;
#else
    Q_UNUSED(path);
    Q_UNUSED(flags);
#endif

    int rc = ::close(fh);
    if (rc != 0)
        m_error = errno;
    return rc == 0;
}

bool LocalFileOps::opendir(const QLatin1String& path, quint64* fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file opendir" << path << fh;
#endif
    DIR* dir = ::opendir(path.latin1());
    if (!dir)
        m_error = errno;
    else if (fh)
        *fh = reinterpret_cast<quint64>(dir);
    return dir;
}

bool LocalFileOps::readdir(const QLatin1String& path, quint64 offset, FileInfo* info, quint64 fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file readdir" << path;
#else
    Q_UNUSED(path);
    Q_UNUSED(offset);
#endif

    struct dirent* dir = ::readdir(reinterpret_cast<DIR*>(fh));
    if (!dir)
        m_error = errno;
    else if (info) {
#if _DIRENT_HAVE_D_NAMLEN
        info->setName(QString::fromAscii(dir->d_name, dir->d_namlen));
#else
        info->setName(QString::fromAscii(dir->d_name));
#endif
        info->setSerialNumber(dir->d_ino);
        info->setMode(dir->d_type << 12);
    }
    return dir;
}

bool LocalFileOps::releasedir(const QLatin1String& path, quint64 fh)
{
#if DEBUG_LOCALFILEOPS
    qDebug() << "Local file releasedir" << path << fh;
#else
    Q_UNUSED(path);
#endif
    int rc = ::closedir(reinterpret_cast<DIR*>(fh));
    if (rc != 0)
        m_error = errno;
    return rc == 0;
}


text:
package models.supervision

import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import jto.validation.{Invalid, Path, Valid}
import jto.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, JsSuccess, Json}

class ProfessionalBodyMemberSpec extends PlaySpec with MockitoSugar {

  "ProfessionalBodyMember" must {

    "pass validation" when {
      "more than one check box is selected" in {

        val model = Map("isAMember" -> Seq("true"))

        ProfessionalBodyMember.formRule.validate(model) must be(Valid(ProfessionalBodyMemberYes))

      }

      "'No' is selected" in {

        val model = Map("isAMember" -> Seq("false"))

        ProfessionalBodyMember.formRule.validate(model) must be(Valid(ProfessionalBodyMemberNo))

      }
    }

    "fail validation" when {
      "'isAMember' field field is missing" in {

        val model = Map[String, Seq[String]]()

        ProfessionalBodyMember.formRule.validate(model) must
          be(Invalid(List((Path \ "isAMember", Seq(ValidationError("error.required.supervision.business.a.member"))))))

      }

      "given no data represented by an empty Map" in {

        ProfessionalBodyMember.formRule.validate(Map.empty) must
          be(Invalid(Seq((Path \ "isAMember") -> Seq(ValidationError("error.required.supervision.business.a.member")))))

      }

    }

    "validate form write for option No" in {

      val map = Map("isAMember" -> Seq("false"))

      ProfessionalBodyMember.formWrites.writes(ProfessionalBodyMemberNo) must be (map)
    }

    "validate form write for option Yes" in {

      val map = Map("isAMember" -> Seq("true"))

      ProfessionalBodyMember.formWrites.writes(ProfessionalBodyMemberYes) must be (map)
    }

    "form write test" in {
      val map = Map("isAMember" -> Seq("false"))

      ProfessionalBodyMember.formWrites.writes(ProfessionalBodyMemberNo) must be(map)
    }

    "JSON validation" must {

      "successfully validate given values" in {
        val json =  Json.obj("isAMember" -> true)

        Json.fromJson[ProfessionalBodyMember](json) must be(JsSuccess(ProfessionalBodyMemberYes, JsPath))
      }

      "successfully validate given values with option No" in {
        val json =  Json.obj("isAMember" -> false)

        Json.fromJson[ProfessionalBodyMember](json) must be(JsSuccess(ProfessionalBodyMemberNo, JsPath))
      }

      "fail when on path is missing" in {
        Json.fromJson[ProfessionalBodyMember](Json.obj()) must
          be(JsError((JsPath \"isAMember") -> play.api.libs.json.JsonValidationError("error.path.missing")))
      }

      "fail when on invalid data" in {
        Json.fromJson[ProfessionalBodyMember](Json.obj("isAMember" -> "")) must
          be(JsError((JsPath \ "isAMember") -> play.api.libs.json.JsonValidationError("error.expected.jsboolean")))
      }

      "write valid data in using json write" in {
        Json.toJson[ProfessionalBodyMember](ProfessionalBodyMemberYes) must be (Json.obj("isAMember" -> true))
      }

      "write valid data in using json write with Option No" in {
        Json.toJson[ProfessionalBodyMember](ProfessionalBodyMemberNo) must be (Json.obj("isAMember" -> false))
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "
	default-lazy-init="false">

	<context:annotation-config />

	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:thrall.properties</value>
			</list>
		</property>
	</bean>

	<!-- 指定所上传文件的总大小不能超过20M(1024 * 1024 * 20).注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="20971520" />
	</bean>

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.html</value>
		</property>
	</bean>
	<mvc:annotation-driven />

	<mvc:default-servlet-handler />

	<context:component-scan base-package="org.xmly.thrall.controller" />
</beans>


text:
<?php
namespace Hyperframework\Db;

use Exception;
use Closure;

class DbTransaction {
    private static $connections = [];
    private static $counts = [];

    /**
     * @param Closure $callback
     */
    public static function run(Closure $callback) {
        $connection = DbClient::getConnection();
        $index = array_search($connection, self::$connections, true);
        if ($index === false) {
            self::$connections[] = $connection;
            self::$counts[] = 0;
            end(self::$connections);
            $index = key(self::$connections);
        }
        if (self::$counts[$index] === 0) {
            $connection->beginTransaction();
        }
        try {
            ++self::$counts[$index];
            $callback();
            --self::$counts[$index];
            if (self::$counts[$index] === 0) {
                $connection->commit();
                unset(self::$counts[$index]);
                unset(self::$connections[$index]);
            }
        } catch (Exception $e) {
            --self::$counts[$index];
            if (self::$counts[$index] === 0) {
                $connection->rollback();
                unset(self::$counts[$index]);
                unset(self::$connections[$index]);
            }
            throw $e;
        }
    }
}


text:
BLOCK_W = 16 # pow2
BLOCK_H = 16 # pow2

# To run this demo effectively please mount your OpenMV Cam on a steady
# base and SLOWLY rotate the camera around the lens and move the camera
# forward/backwards to see the numbers change.
# I.e. Z direction changes only.

import sensor, image, time, math

# NOTE!!! You have to use a small power of 2 resolution when using
# find_displacement(). This is because the algorithm is powered by
# something called phase correlation which does the image comparison
# using FFTs. A non-power of 2 resolution requires padding to a power
# of 2 which reduces the usefulness of the algorithm results. Please
# use a resolution like B128X128 or B128X64 (2x faster).

# Your OpenMV Cam supports power of 2 resolutions of 64x32, 64x64,
# 128x64, and 128x128. If you want a resolution of 32x32 you can create
# it by doing "img.pool(2, 2)" on a 64x64 image.

sensor.reset()                         # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to GRAYSCALE (or RGB565)
sensor.set_framesize(sensor.B128X128)  # Set frame size to 128x128... (or 128x64)...
sensor.skip_frames(time = 2000)        # Wait for settings take effect.
clock = time.clock()                   # Create a clock object to track the FPS.

# Take from the main frame buffer's RAM to allocate a second frame buffer.
# There's a lot more RAM in the frame buffer than in the MicroPython heap.
# However, after doing this you have a lot less RAM for some algorithms...
# So, be aware that it's a lot easier to get out of RAM issues now.
extra_fb = sensor.alloc_extra_fb(sensor.width(), sensor.height(), sensor.GRAYSCALE)
extra_fb.replace(sensor.snapshot())

while(True):
    clock.tick() # Track elapsed milliseconds between snapshots().
    img = sensor.snapshot() # Take a picture and return the image.

    for y in range(0, sensor.height(), BLOCK_H):
        for x in range(0, sensor.width(), BLOCK_W):
            # For this example we never update the old image to measure absolute change.
            displacement = extra_fb.find_displacement(img, logpolar=True, \
                roi = (x, y, BLOCK_W, BLOCK_H), template_roi = (x, y, BLOCK_W, BLOCK_H))

            # Below 0.1 or so (YMMV) and the results are just noise.
            if(displacement.response() > 0.1):
                rotation_change = displacement.rotation()
                zoom_amount = displacement.scale()
                pixel_x = x + (BLOCK_W//2) + int(math.sin(rotation_change) * zoom_amount * (BLOCK_W//4))
                pixel_y = y + (BLOCK_H//2) + int(math.cos(rotation_change) * zoom_amount * (BLOCK_H//4))
                img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, pixel_x, pixel_y), \
                    color = 255)
            else:
                img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, x + BLOCK_W//2, y + BLOCK_H//2), \
                    color = 0)

    print(clock.fps())


text:
goog.provide('ol.test.interaction.DragRotateAndZoom');

goog.require('ol.interaction.DragRotateAndZoom');

describe('ol.interaction.DragRotateAndZoom', function() {

  describe('constructor', function() {

    it('can be constructed without arguments', function() {
      var instance = new ol.interaction.DragRotateAndZoom();
      expect(instance).to.be.an(ol.interaction.DragRotateAndZoom);
    });

  });

});


text:
#ifndef BlynkStream_h
#define BlynkStream_h

#ifndef BLYNK_INFO_CONNECTION
#define BLYNK_INFO_CONNECTION "Serial"
#endif

#include <BlynkApiParticle.h>
#include <Blynk/BlynkProtocol.h>

class BlynkTransportStream
{
public:
    BlynkTransportStream()
        : stream(NULL), conn(0)
    {}

    // IP redirect not available
    void begin(char BLYNK_UNUSED *h, uint16_t BLYNK_UNUSED p) {}

    void begin(Stream& s) {
        stream = &s;
    }

    bool connect() {
        BLYNK_LOG1(BLYNK_F("Connecting..."));
        stream->flush();
        return conn = true;
    }
    void disconnect() { conn = false; }

    size_t read(void* buf, size_t len) {
        char* beg = (char*)buf;
        char* end = beg + len;
        millis_time_t startMillis = BlynkMillis();
        while ((beg < end) && (BlynkMillis() - startMillis < BLYNK_TIMEOUT_MS)) {
            int c = stream->read();
            if (c < 0)
                continue;
            *beg++ = (char)c;
        }
        return beg-(char*)buf;
    }
    size_t write(const void* buf, size_t len) {
        stream->write((const uint8_t*)buf, len);
        return len;
    }

    bool connected() { return conn; }
    int available() { return stream->available(); }

protected:
    Stream* stream;
    bool    conn;
};

class BlynkStream
    : public BlynkProtocol<BlynkTransportStream>
{
    typedef BlynkProtocol<BlynkTransportStream> Base;
public:
    BlynkStream(BlynkTransportStream& transp)
        : Base(transp)
    {}

    void config(Stream&     stream,
                const char* auth)
    {
        Base::begin(auth);
        this->conn.begin(stream);
    }

    void begin(Stream& stream, const char* auth) {
        config(stream, auth);
        while(this->connect() != true) {}
    }

    // Please use Blynk.begin(Stream, "auth")
    BLYNK_DEPRECATED
    void begin(const char* auth, Stream& stream) {
        config(stream, auth);
        while(this->connect() != true) {}
    }
};

#endif


text:
namespace NetMsg
{
    struct SVC_EntityMessage
    {
        std::unique_ptr<uint8_t[]> data;
        uint16_t dataLengthInBits;
        uint16_t entIndex;
        uint16_t classID;
    };
}

DECLARE_NET_HANDLERS(SVC_EntityMessage);


text:
package org.jivesoftware.sparkimpl.settings.local;

/**
 * Implement this interface to be notified that the preferences have been changed.
 *
 * @author Derek DeMoro
 */
public interface PreferenceListener {

    /**
     * Notified when preferences are changed.
     *
     * @param preference the new preferences.
     */
    void preferencesChanged(LocalPreferences preference);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>maven-dotnet-plugins</artifactId>
    <groupId>org.apache.npanday.plugins</groupId>
    <version>1.5.0-incubating-SNAPSHOT</version>
  </parent>
  <groupId>org.apache.npanday.plugins</groupId>
  <artifactId>msdeploy-maven-plugin</artifactId>
  <packaging>maven-plugin</packaging>

  <name>NPanday :: MSDeploy Maven Plugin</name>
  <description>Maven Plugin for Microsoft Web Deploy</description>
</project>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Dashboard">
    <meta name="keyword" content="Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">

    <title>Istri Bijak | Daftar</title>

    <link href="<?php echo base_url();?>assets/css/bootstrap.css" rel="stylesheet">

    <link href="<?php echo base_url();?>assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="<?php echo base_url();?>source/img/favicon/favicon.png" rel="shortcut icon" type="image/png"/>

    <link href="<?php echo base_url();?>assets/css/style2.css" rel="stylesheet">
    <link href="<?php echo base_url();?>assets/css/style-responsive.css" rel="stylesheet">

		      <form id="form-login" class="form-login" action="index.html">
            <input type="hidden" id="base_url" name="base_url" value="<?php echo base_url(); ?>">

Daftar

		            <input type="text" id="nama" name="nama" class="form-control" id="nama" placeholder="Nama" autofocus>

                <input type="text" id="username" name="username" class="form-control" id="username" placeholder="Username" autofocus>

		            <input type="password" id="password" name="password" class="form-control" id="" placeholder="Kata Sandi">

		            <input type="password"  id="ulangi_password" name="ulangi_password" class="form-control" placeholder="Ketik Ulang Kata Sandi">

		            <input type="text" class="form-control" name="email" id="email" placeholder="Email">

		            <button id="btn" class="btn btn-theme btn-block" href="#" type="submit"> Daftar Sekarang</button>

		      </form>

    <?php echo $js; ?>


text:
module StripeClerk
  class ApplicationController < ActionController::Base
  end
end


text:
@implementation Parachute

@synthesize position, velocity, angle, alive, cargoOffset;

-(id)initAt:(Vector2D)p withTexture:(eTexture)tx forGame:(Game*)g {
    if (self == [super init]) {
        tex = tx;
        position = p;
        velocity = Vector2DMake(0.0f,-GAME_PARAMETERS.parachuteFallSpeed);
        cargoOffset = 0.65f*GetImageDimensions(tex).y;
        angularVelocity = PARACHUTE_MIN_ANGULAR_VELOCITY;
        alive = true;
        game = g;
    }
    return self;
}

-(Boolean)isInside:(CGPoint)p {
    Vector2D dim = GetImageDimensions(tex);
    return fabsf(p.x-position.x) <= dim.x/2 &&
           fabsf(p.y-position.y) <= dim.y/2;
}

-(void)tick:(float) timeElapsed {
    if (!alive) {
        return;
    }

    angularVelocity -= timeElapsed;
    angularVelocity = fminf( fmaxf(angularVelocity, PARACHUTE_MIN_ANGULAR_VELOCITY), PARACHUTE_MAX_ANGULAR_VELOCITY);
    t += angularVelocity*timeElapsed;
    angle = 0.15f*M_PI*sinf(t)-M_PI;

    if (!cargo) {
        velocity.y += PARACHUTE_RISE_ACCEL * timeElapsed;
        alive = (position.y < 1.1f*GetGLHeight());
    }

    position = Vector2DAdd(position, Vector2DMul(velocity, timeElapsed));
}

-(Boolean)trigger {
    [PARTICLE_MANAGER createHitAt:position];
    [PARTICLE_MANAGER createConfettiAt:position
                                withAmount:15
                                withLayer:kLayer_Game];

    [[SimpleAudioEngine sharedEngine] playEffect:GetSoundName(kSound_BalloonPop)];

    [cargo remove:self];
    alive = false;
    return true;
}

-(void)attatch:(id<ParachuteCargo>)c {
    NSAssert(!cargo,@"Parachute::attatch - cargo already attatched!");
    cargo = c;
}

-(void)releaseCargo {
    cargo = nil;
    velocity.y = 0.0f;
}

-(void)addForce:(Vector2D)force {
    float strength = Vector2DMagnitude(force);
    float torque = 0.3f*strength;
    angularVelocity = torque;
    velocity = Vector2DAdd(velocity, Vector2DMake(force.x,0.0f));
}

-(void)render:(float)timeElapsed {
    if (!alive) {
        return;
    }

    Texture2D* texture = GetTexture(tex);

    if (IsGameShadowsEnabled()) {
        Vector2D shadowOffset = [ES1Renderer shadowOffset];
        Color3D shadowColor = [game shadowColor];

        // render shadow
        glLoadIdentity();
        glTranslatef(   ToScreenScaleX(position.x+shadowOffset.x),
                        ToScreenScaleY(position.y+shadowOffset.y), 0.0f);
        glColor4f(shadowColor.red, shadowColor.green, shadowColor.blue, shadowColor.alpha);
        [texture draw];
    }

    if (IsGameMotionBlurEnabled()) {
        // motion blur
        glLoadIdentity();
        glTranslatef(   ToScreenScaleX(position.x-2.0f*timeElapsed*velocity.x),
                        ToScreenScaleY(position.y-2.0f*timeElapsed*velocity.y), 0.0f);
        glColor4f(1.0f, 1.0f, 1.0f, 0.75f*Vector2DMagnitude(velocity)/GAME_PARAMETERS.maxPinataSpeed);
        [texture draw];
    }

    glLoadIdentity();
    glTranslatef(ToScreenScaleX(position.x), ToScreenScaleY(position.y), 0.0f);
    glColor4f(1.0f,1.0f,1.0f,1.0f);
    [texture draw];
}

@end