text:
<?php

namespace Test\Integration;

require_once dirname(__DIR__) . '/Setup.php';

use Test\Setup;
use Braintree;

class AddressTest extends Setup
{
    public function testCreate()
    {
        $customer = Braintree\Customer::createNoValidate();
        $result = Braintree\Address::create([
            'customerId' => $customer->id,
            'firstName' => 'Dan',
            'lastName' => 'Smith',
            'company' => 'Braintree',
            'streetAddress' => '1 E Main St',
            'extendedAddress' => 'Apt 1F',
            'locality' => 'Chicago',
            'region' => 'IL',
            'postalCode' => '60622',
            'countryName' => 'Vatican City',
            'countryCodeAlpha2' => 'VA',
            'countryCodeAlpha3' => 'VAT',
            'countryCodeNumeric' => '336'
        ]);
        $this->assertTrue($result->success);
        $address = $result->address;
        $this->assertEquals('Dan', $address->firstName);
        $this->assertEquals('Smith', $address->lastName);
        $this->assertEquals('Braintree', $address->company);
        $this->assertEquals('1 E Main St', $address->streetAddress);
        $this->assertEquals('Apt 1F', $address->extendedAddress);
        $this->assertEquals('Chicago', $address->locality);
        $this->assertEquals('IL', $address->region);
        $this->assertEquals('60622', $address->postalCode);
        $this->assertEquals('Vatican City', $address->countryName);
        $this->assertEquals('VA', $address->countryCodeAlpha2);
        $this->assertEquals('VAT', $address->countryCodeAlpha3);
        $this->assertEquals('336', $address->countryCodeNumeric);
    }

    public function testGatewayCreate()
    {
        $customer = Braintree\Customer::createNoValidate();

        $gateway = new Braintree\Gateway([
            'environment' => 'development',
            'merchantId' => 'integration_merchant_id',
            'publicKey' => 'integration_public_key',
            'privateKey' => 'integration_private_key'
        ]);
        $result = $gateway->address()->create([
            'customerId' => $customer->id,
            'streetAddress' => '1 E Main St',
            'locality' => 'Chicago',
            'region' => 'IL',
            'postalCode' => '60622',
        ]);

        $this->assertTrue($result->success);
        $address = $result->address;
        $this->assertEquals('1 E Main St', $address->streetAddress);
        $this->assertEquals('Chicago', $address->locality);
        $this->assertEquals('IL', $address->region);
        $this->assertEquals('60622', $address->postalCode);
    }

    public function testCreate_withValidationErrors()
    {
        $customer = Braintree\Customer::createNoValidate();
        $result = Braintree\Address::create([
            'customerId' => $customer->id,
            'countryName' => 'Invalid States of America'
        ]);
        $this->assertFalse($result->success);
        $countryErrors = $result->errors->forKey('address')->onAttribute('countryName');
        $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, $countryErrors[0]->code);
    }

    public function testCreate_withValidationErrors_onCountryCodes()
    {
        $customer = Braintree\Customer::createNoValidate();
        $result = Braintree\Address::create([
            'customerId' => $customer->id,
            'countryCodeAlpha2' => 'ZZ'
        ]);
        $this->assertFalse($result->success);
        $countryErrors = $result->errors->forKey('address')->onAttribute('countryCodeAlpha2');
        $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED, $countryErrors[0]->code);
    }

    public function testCreate_withNotFoundErrors()
    {
        $this->expectException('Braintree\Exception\NotFound', 'Customer nonExistentCustomerId not found.');
        $result = Braintree\Address::create([
            'customerId' => 'nonExistentCustomerId',
        ]);
    }

    public function testCreateNoValidate()
    {
        $customer = Braintree\Customer::createNoValidate();
        $address = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'firstName' => 'Dan',
            'lastName' => 'Smith',
            'company' => 'Braintree',
            'streetAddress' => '1 E Main St',
            'extendedAddress' => 'Apt 1F',
            'locality' => 'Chicago',
            'region' => 'IL',
            'postalCode' => '60622',
            'countryName' => 'United States of America'
        ]);
        $this->assertEquals('Dan', $address->firstName);
        $this->assertEquals('Smith', $address->lastName);
        $this->assertEquals('Braintree', $address->company);
        $this->assertEquals('1 E Main St', $address->streetAddress);
        $this->assertEquals('Apt 1F', $address->extendedAddress);
        $this->assertEquals('Chicago', $address->locality);
        $this->assertEquals('IL', $address->region);
        $this->assertEquals('60622', $address->postalCode);
        $this->assertEquals('United States of America', $address->countryName);
    }

    public function testCreateNoValidate_withValidationErrors()
    {
        $customer = Braintree\Customer::createNoValidate();
        $this->expectException('Braintree\Exception\ValidationsFailed');
        Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'countryName' => 'Invalid States of America'
        ]);
    }

    public function testDelete()
    {
        $customer = Braintree\Customer::createNoValidate();
        $address = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'streetAddress' => '1 E Main St'
        ]);
        Braintree\Address::find($customer->id, $address->id);
        Braintree\Address::delete($customer->id, $address->id);
        $this->expectException('Braintree\Exception\NotFound');
        Braintree\Address::find($customer->id, $address->id);
    }

    public function testFind()
    {
        $customer = Braintree\Customer::createNoValidate();
        $result = Braintree\Address::create([
            'customerId' => $customer->id,
            'firstName' => 'Dan',
            'lastName' => 'Smith',
            'company' => 'Braintree',
            'streetAddress' => '1 E Main St',
            'extendedAddress' => 'Apt 1F',
            'locality' => 'Chicago',
            'region' => 'IL',
            'postalCode' => '60622',
            'countryName' => 'United States of America'
        ]);
        $this->assertTrue($result->success);
        $address = Braintree\Address::find($customer->id, $result->address->id);
        $this->assertEquals('Dan', $address->firstName);
        $this->assertEquals('Smith', $address->lastName);
        $this->assertEquals('Braintree', $address->company);
        $this->assertEquals('1 E Main St', $address->streetAddress);
        $this->assertEquals('Apt 1F', $address->extendedAddress);
        $this->assertEquals('Chicago', $address->locality);
        $this->assertEquals('IL', $address->region);
        $this->assertEquals('60622', $address->postalCode);
        $this->assertEquals('United States of America', $address->countryName);
    }

    public function testFind_whenNotFound()
    {
        $customer = Braintree\Customer::createNoValidate();
        $this->expectException('Braintree\Exception\NotFound');
        Braintree\Address::find($customer->id, 'does-not-exist');
    }

    public function testUpdate()
    {
        $customer = Braintree\Customer::createNoValidate();
        $address = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'firstName' => 'Old First',
            'lastName' => 'Old Last',
            'company' => 'Old Company',
            'streetAddress' => '1 E Old St',
            'extendedAddress' => 'Apt Old',
            'locality' => 'Old Chicago',
            'region' => 'Old Region',
            'postalCode' => 'Old Postal',
            'countryName' => 'United States of America',
            'countryCodeAlpha2' => 'US',
            'countryCodeAlpha3' => 'USA',
            'countryCodeNumeric' => '840'
        ]);
        $result = Braintree\Address::update($customer->id, $address->id, [
            'firstName' => 'New First',
            'lastName' => 'New Last',
            'company' => 'New Company',
            'streetAddress' => '1 E New St',
            'extendedAddress' => 'Apt New',
            'locality' => 'New Chicago',
            'region' => 'New Region',
            'postalCode' => 'New Postal',
            'countryName' => 'Mexico',
            'countryCodeAlpha2' => 'MX',
            'countryCodeAlpha3' => 'MEX',
            'countryCodeNumeric' => '484'
        ]);
        $this->assertTrue($result->success);
        $address = $result->address;
        $this->assertEquals('New First', $address->firstName);
        $this->assertEquals('New Last', $address->lastName);
        $this->assertEquals('New Company', $address->company);
        $this->assertEquals('1 E New St', $address->streetAddress);
        $this->assertEquals('Apt New', $address->extendedAddress);
        $this->assertEquals('New Chicago', $address->locality);
        $this->assertEquals('New Region', $address->region);
        $this->assertEquals('New Postal', $address->postalCode);
        $this->assertEquals('Mexico', $address->countryName);
        $this->assertEquals('MX', $address->countryCodeAlpha2);
        $this->assertEquals('MEX', $address->countryCodeAlpha3);
        $this->assertEquals('484', $address->countryCodeNumeric);
    }

    public function testUpdate_withValidationErrors()
    {
        $customer = Braintree\Customer::createNoValidate();
        $address = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'streetAddress' => '1 E Main St'
        ]);
        $result = Braintree\Address::update(
            $customer->id,
            $address->id,
            [
                'countryName' => 'Invalid States of America'
            ]
        );
        $this->assertFalse($result->success);
        $countryErrors = $result->errors->forKey('address')->onAttribute('countryName');
        $this->assertEquals(Braintree\Error\Codes::ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED, $countryErrors[0]->code);
    }

    public function testUpdate_withValidationErrors_onCountry()
    {
        $customer = Braintree\Customer::createNoValidate();
        $address = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'streetAddress' => '1 E Main St'
        ]);
        $result = Braintree\Address::update(
            $customer->id,
            $address->id,
            [
                'countryCodeAlpha2' => 'MU',
                'countryCodeAlpha3' => 'MYT'
            ]
        );
        $this->assertFalse($result->success);
        $countryErrors = $result->errors->forKey('address')->onAttribute('base');
        $this->assertEquals(Braintree\Error\Codes::ADDRESS_INCONSISTENT_COUNTRY, $countryErrors[0]->code);
    }

    public function testUpdateNoValidate()
    {
        $customer = Braintree\Customer::createNoValidate();
        $createdAddress = Braintree\Address::createNoValidate([
            'customerId' => $customer->id,
            'firstName' => 'Old First',
            'lastName' => 'Old Last',
            'company' => 'Old Company',
            'streetAddress' => '1 E Old St',
            'extendedAddress' => 'Apt Old',
            'locality' => 'Old Chicago',
            'region' => 'Old Region',
            'postalCode' => 'Old Postal',
            'countryName' => 'United States of America'
        ]);
        $address = Braintree\Address::updateNoValidate($customer->id, $createdAddress->id, [
            'firstName' => 'New First',
            'lastName' => 'New Last',
            'company' => 'New Company',
            'streetAddress' => '1 E New St',
            'extendedAddress' => 'Apt New',
            'locality' => 'New Chicago',
            'region' => 'New Region',
            'postalCode' => 'New Postal',
            'countryName' => 'Mexico'
        ]);
        $this->assertEquals('New First', $address->firstName);
        $this->assertEquals('New Last', $address->lastName);
        $this->assertEquals('New Company', $address->company);
        $this->assertEquals('1 E New St', $address->streetAddress);
        $this->assertEquals('Apt New', $address->extendedAddress);
        $this->assertEquals('New Chicago', $address->locality);
        $this->assertEquals('New Region', $address->region);
        $this->assertEquals('New Postal', $address->postalCode);
        $this->assertEquals('Mexico', $address->countryName);
    }
}


text:
title: Paul D. Ryan, Wisconsin Congressperson
name: Paul D. Ryan
avatar: /ui/img/avatars/Paul_Ryan.png
party: republican
state: wisconsin
type: congressperson
lasthall: 2014-03-18
phone: 202-225-3031
never:
twitter: RepPaulRyan
---

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.facebook.fresco.samples.showcase"
    >

  <uses-permission android:name="android.permission.INTERNET" />

  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  <!-- Keyframes requires API level 15 and without this the build will fail,
       version checking is performed in runtime instead.-->
  <uses-sdk tools:overrideLibrary="com.facebook.keyframes" />

  <application
      android:name=".ShowcaseApplication"
      android:allowBackup="false"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme"
      >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"
        >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <activity
        android:name=".drawee.transition.ImageDetailsActivity"
        android:label="@string/drawee_transition_details_title"
        android:parentActivityName=".MainActivity"
        android:theme="@style/AppTheme.ImageDetails"
        >
      <meta-data
          android:name="android.support.PARENT_ACTIVITY"
          android:value=".MainActivity"
          />
    </activity>
  </application>
</manifest>


text:
<?php

/**
 * Class to work with HTTP protocol using sockets
 *
 * @category    Mage
 * @package     Mage_Connect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_HTTP_Client_Socket
    implements Mage_HTTP_IClient
{
    /**
     * Hostname
     * @var string
     */
    private $_host = 'localhost';

    /**
     * Port
     * @var int
     */
    private $_port = 80;

    /**
     * Stream resource
     * @var object
     */
    private $_sock = null;

    /**
     * Request headers
     * @var array
     */
    private $_headers = array();

    /**
     * Fields for POST method - hash
     * @var array
     */
    private $_postFields = array();

    /**
     * Request cookies
     * @var array
     */
    private $_cookies = array();

    /**
     * Response headers
     * @var array
     */
    private $_responseHeaders = array();

    /**
     * Response body
     * @var string
     */
    private $_responseBody = '';

    /**
     * Response status
     * @var int
     */
    private $_responseStatus = 0;

    /**
     * Request timeout
     * @var int
     */
    private $_timeout = 300;

    /**
     * TODO
     * @var int
     */
    private $_redirectCount = 0;

    /**
     * Set request timeout, msec
     *
     * @param int $value
     */
    public function setTimeout($value)
    {
        $this->_timeout = (int) $value;
    }

    /**
     * Constructor
     * @param string $host
     * @param int $port
     */
    public function __construct($host = null, $port = 80)
    {
        if($host) {
            $this->connect($host, (int) $port);
        }
    }

    /**
     * Set connection params
     *
     * @param string $host
     * @param int $port
     */
    public function connect($host, $port = 80)
    {
        $this->_host = $host;
        $this->_port = (int) $port;

    }

    /**
     * Disconnect
     */
    public function disconnect()
    {
        @fclose($this->_sock);
    }

    /**
     * Set headers from hash

     * @param array $headers
     */
    public function setHeaders($headers)
    {
        $this->_headers = $headers;

    }

    /**
     * Add header
     *
     * @param $name name, ex. "Location"
     * @param $value value ex. "http://google.com"
     */
    public function addHeader($name, $value)
    {
        $this->_headers[$name] = $value;

    }

    /**
     * Remove specified header
     *
     * @param string $name
     */
    public function removeHeader($name)
    {
        unset($this->_headers[$name]);

    }

    /**
     * Authorization: Basic header
     * Login credentials support
     *
     * @param string $login username
     * @param string $pass password
     */
    public function setCredentials($login, $pass)
    {
        $val= base64_encode( "$login:$pass" );
        $this->addHeader( "Authorization", "Basic $val" );
    }

    /**
     * Add cookie
     *
     * @param string $name
     * @param string $value
     */
    public function addCookie($name, $value)
    {
        $this->_cookies[$name] = $value;
    }

    /**
     * Remove cookie
     *
     * @param string $name
     */
    public function removeCookie($name)
    {
        unset($this->_cookies[$name]);
    }

    /**
     * Set cookies array
     *
     * @param array $cookies
     */
    public function setCookies($cookies)
    {
        $this->_cookies = $cookies;
    }

    /**
     * Clear cookies
     */
    public function removeCookies()
    {
        $this->setCookies(array());
    }

    /**
     * Make GET request
     *
     * @param string $uri full uri path
     */
    public function get($uri)
    {
        $this->makeRequest("GET",$this->parseUrl($uri));
    }

    /**
     * Set host, port from full url
     * and return relative url
     *
     * @param string $uri ex. http://google.com/index.php?a=b
     * @return string ex. /index.php?a=b
     */
    protected function parseUrl($uri)
    {
        $parts = parse_url($uri);
        if(!empty($parts['user']) && !empty($parts['pass'])) {
            $this->setCredentials($parts['user'], $parts['pass']);
        }
        if(!empty($parts['port'])) {
            $this->_port = (int) $parts['port'];
        }

        if(!empty($parts['host'])) {
            $this->_host = $parts['host'];
        } else {
            throw new InvalidArgumentException("Uri doesn't contain host part");
        }

        if(!empty($parts['path'])) {
            $requestUri = $parts['path'];
        } else {
            throw new InvalidArgumentException("Uri doesn't contain path part");
        }
        if(!empty($parts['query'])) {
            $requestUri .= "?".$parts['query'];
        }
        return $requestUri;
    }

    /**
     * Make POST request
     */
    public function post($uri, $params)
    {
        $this->makeRequest("POST", $this->parseUrl($uri), $params);
    }

    /**
     * Get response headers
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->_responseHeaders;
    }

    /**
     * Get response body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->_responseBody;
    }

    /**
     * Get cookies response hash
     *
     * @return array
     */
    public function getCookies()
    {
        if(empty($this->_responseHeaders['Set-Cookie'])) {
            return array();
        }
        $out = array();
        foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
            $values = explode("; ", $row);
            $c = count($values);
            if(!$c) {
                continue;
            }
            list($key, $val) = explode("=", $values[0]);
            if(is_null($val)) {
                continue;
            }
            $out[trim($key)] = trim($val);
        }
        return $out;
    }

    /**
     * Get cookies array with details
     * (domain, expire time etc)
     * @return array
     */
    public function getCookiesFull()
    {
        if(empty($this->_responseHeaders['Set-Cookie'])) {
            return array();
        }
        $out = array();
        foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
            $values = explode("; ", $row);
            $c = count($values);
            if(!$c) {
                continue;
            }
            list($key, $val) = explode("=", $values[0]);
            if(is_null($val)) {
                continue;
            }
            $out[trim($key)] = array('value'=>trim($val));
            array_shift($values);
            $c--;
            if(!$c) {
                continue;
            }
            for($i = 0; $i<$c; $i++) {
                list($subkey, $val) = explode("=", $values[$i]);
                $out[trim($key)][trim($subkey)] = trim($val);
            }
        }
        return $out;
    }

    /**
     * Process response headers
     */
    protected function processResponseHeaders()
    {
        $crlf = "\r\n";
        $this->_responseHeaders = array();
        while (!feof($this->_sock)) {
            $line = fgets($this->_sock, 1024);
            if($line === $crlf) {
                return;
            }
            $name = $value = '';
            $out = explode(": ", trim($line), 2);
            if(count($out) == 2) {
                $name = $out[0];
                $value = $out[1];
            }
            if(!empty($value)) {
                if($name == "Set-Cookie") {
                    if(!isset($this->_responseHeaders[$name])) {
                        $this->_responseHeaders[$name] = array();
                    }
                    $this->_responseHeaders[$name][] = $value;
                } else {
                    $this->_responseHeaders[$name] = $value;
                }
            }
        }
    }

    /**
     * Process response body
     */
    protected function processResponseBody()
    {
        $this->_responseBody = '';

        while (!feof($this->_sock)) {
            $this->_responseBody .= @fread($this->_sock, 1024);
        }
    }

    /**
     * Process response
     */
    protected function processResponse()
    {
        $response = '';
        $responseLine = trim(fgets($this->_sock, 1024));

        $line = explode(" ", $responseLine, 3);
        if(count($line) != 3) {
            return $this->doError("Invalid response line returned from server: ".$responseLine);
        }
        $this->_responseStatus = intval($line[1]);
        $this->processResponseHeaders();

        $this->processRedirect();

        $this->processResponseBody();
    }

    /**
     * Process redirect
     */
    protected function processRedirect()
    {
        // TODO: implement redircets support
    }

    /**
     * Get response status code
     * @see lib/Mage/HTTP/Mage_HTTP_Client#getStatus()
     */
    public function getStatus()
    {
        return $this->_responseStatus;
    }

    /**
     * Make request
     * @param string $method
     * @param string $uri
     * @param array $params
     * @return null
     */
    protected function makeRequest($method, $uri, $params = array())
    {
        $errno = $errstr = '';
        $this->_sock = @fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout);
        if(!$this->_sock) {
            return $this->doError(sprintf("[errno: %d] %s", $errno, $errstr));
        }

        $crlf = "\r\n";
        $isPost = $method == "POST";

        $appendHeaders = array();
        $paramsStr = false;
        if($isPost && count($params)) {
            $paramsStr = http_build_query($params);
            $appendHeaders['Content-type'] = 'application/x-www-form-urlencoded';
            $appendHeaders['Content-length'] = strlen($paramsStr);
        }

        $out = "{$method} {$uri} HTTP/1.1{$crlf}";
        $out .= $this->headersToString($appendHeaders);
        $out .= $crlf;
        if($paramsStr) {
            $out .= $paramsStr.$crlf;
        }

        fwrite($this->_sock, $out);
        $this->processResponse();
    }

    /**
     * Throw error excpetion
     * @param $string
     * @throws Exception
     */
    public function doError($string)
    {
        throw new Exception($string);
    }

    /**
     * Convert headers hash to string
     * @param $delimiter
     * @param $append
     * @return string
     */
    protected function headersToString($append = array())
    {
        $headers = array();
        $headers["Host"] = $this->_host;
        $headers['Connection'] = "close";
        $headers = array_merge($headers, $this->_headers, $append);
        $str = array();
        foreach ($headers as $k=>$v) {
            $str []= "$k: $v\r\n";
        }
        return implode($str);
    }

    /**
     * TODO
     */
    public function setOptions($arr)
    {
        // Stub
    }

    /**
     * TODO
     */
    public function setOption($name, $value)
    {
        // Stub
    }

}


text:
namespace blink {

// This file contains two scope classes for catching cases where paint
// properties needed an update but were not marked as such. If paint properties
// will change, the object must be marked as needing a paint property update
// using {FrameView, LayoutObject}::setNeedsPaintPropertyUpdate() or by forcing
// a subtree update (see: PaintPropertyTreeBuilderContext::forceSubtreeUpdate).
//
// Both scope classes work by recording the paint property state of an object
// before rebuilding properties, forcing the properties to get updated, then
// checking that the updated properties match the original properties.

#define DUMP_PROPERTIES(original, updated)                           \
  "\nOriginal:\n"                                                    \
      << (original ? (original)->toString().ascii().data() : "null") \
      << "\nUpdated:\n"                                              \
      << (updated ? (updated)->toString().ascii().data() : "null")

#define CHECK_PROPERTY_EQ(thing, original, updated)                        \
  do {                                                                     \
    DCHECK(!!original == !!updated) << "Property was created or deleted "  \
                                    << "without " << thing                 \
                                    << " needing a paint property update." \
                                    << DUMP_PROPERTIES(original, updated); \
    if (!!original && !!updated) {                                         \
      DCHECK(*original == *updated) << "Property was updated without "     \
                                    << thing                               \
                                    << " needing a paint property update." \
                                    << DUMP_PROPERTIES(original, updated); \
    }                                                                      \
  } while (0)

#define DCHECK_FRAMEVIEW_PROPERTY_EQ(original, updated) \
  CHECK_PROPERTY_EQ("the FrameView", original, updated)

class FindFrameViewPropertiesNeedingUpdateScope {
 public:
  FindFrameViewPropertiesNeedingUpdateScope(
      FrameView* frameView,
      PaintPropertyTreeBuilderContext& context)
      : m_frameView(frameView),
        m_neededPaintPropertyUpdate(frameView->needsPaintPropertyUpdate()),
        m_neededForcedSubtreeUpdate(context.forceSubtreeUpdate) {
    // No need to check if an update was already needed.
    if (m_neededPaintPropertyUpdate || m_neededForcedSubtreeUpdate)
      return;

    // Mark the properties as needing an update to ensure they are rebuilt.
    m_frameView->setOnlyThisNeedsPaintPropertyUpdateForTesting();

    if (auto* preTranslation = m_frameView->preTranslation())
      m_originalPreTranslation = preTranslation->clone();
    if (auto* contentClip = m_frameView->contentClip())
      m_originalContentClip = contentClip->clone();
    if (auto* scrollTranslation = m_frameView->scrollTranslation())
      m_originalScrollTranslation = scrollTranslation->clone();
    if (auto* scroll = m_frameView->scroll())
      m_originalScroll = scroll->clone();
  }

  ~FindFrameViewPropertiesNeedingUpdateScope() {
    // No need to check if an update was already needed.
    if (m_neededPaintPropertyUpdate || m_neededForcedSubtreeUpdate)
      return;

    // If these checks fail, the paint properties changed unexpectedly. This is
    // due to missing one of these paint property invalidations:
    // 1) The FrameView should have been marked as needing an update with
    //    FrameView::setNeedsPaintPropertyUpdate().
    // 2) The PrePaintTreeWalk should have had a forced subtree update (see:
    //    PaintPropertyTreeBuilderContext::forceSubtreeUpdate).
    DCHECK_FRAMEVIEW_PROPERTY_EQ(m_originalPreTranslation,
                                 m_frameView->preTranslation());
    DCHECK_FRAMEVIEW_PROPERTY_EQ(m_originalContentClip,
                                 m_frameView->contentClip());
    DCHECK_FRAMEVIEW_PROPERTY_EQ(m_originalScrollTranslation,
                                 m_frameView->scrollTranslation());
    DCHECK_FRAMEVIEW_PROPERTY_EQ(m_originalScroll, m_frameView->scroll());

    // Restore original clean bit.
    m_frameView->clearNeedsPaintPropertyUpdate();
  }

 private:
  Persistent<FrameView> m_frameView;
  bool m_neededPaintPropertyUpdate;
  bool m_neededForcedSubtreeUpdate;
  RefPtr<TransformPaintPropertyNode> m_originalPreTranslation;
  RefPtr<ClipPaintPropertyNode> m_originalContentClip;
  RefPtr<TransformPaintPropertyNode> m_originalScrollTranslation;
  RefPtr<ScrollPaintPropertyNode> m_originalScroll;
};

#define DCHECK_OBJECT_PROPERTY_EQ(object, original, updated)            \
  CHECK_PROPERTY_EQ("the layout object (" << object.debugName() << ")", \
                    original, updated)

class FindObjectPropertiesNeedingUpdateScope {
 public:
  FindObjectPropertiesNeedingUpdateScope(
      const LayoutObject& object,
      PaintPropertyTreeBuilderContext& context)
      : m_object(object),
        m_neededPaintPropertyUpdate(object.needsPaintPropertyUpdate()),
        m_neededForcedSubtreeUpdate(context.forceSubtreeUpdate),
        m_originalPaintOffset(object.paintOffset()) {
    // No need to check if an update was already needed.
    if (m_neededPaintPropertyUpdate || m_neededForcedSubtreeUpdate)
      return;

    // Mark the properties as needing an update to ensure they are rebuilt.
    m_object.getMutableForPainting()
        .setOnlyThisNeedsPaintPropertyUpdateForTesting();

    if (const auto* properties = m_object.paintProperties())
      m_originalProperties = properties->clone();
  }

  ~FindObjectPropertiesNeedingUpdateScope() {
    // No need to check if an update was already needed.
    if (m_neededPaintPropertyUpdate || m_neededForcedSubtreeUpdate)
      return;

    // If these checks fail, the paint properties changed unexpectedly. This is
    // due to missing one of these paint property invalidations:
    // 1) The LayoutObject should have been marked as needing an update with
    //    LayoutObject::setNeedsPaintPropertyUpdate().
    // 2) The PrePaintTreeWalk should have had a forced subtree update (see:
    //    PaintPropertyTreeBuilderContext::forceSubtreeUpdate).
    DCHECK_OBJECT_PROPERTY_EQ(m_object, &m_originalPaintOffset,
                              &m_object.paintOffset());
    const auto* objectProperties = m_object.paintProperties();
    if (m_originalProperties && objectProperties) {
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->paintOffsetTranslation(),
                                objectProperties->paintOffsetTranslation());
      DCHECK_OBJECT_PROPERTY_EQ(m_object, m_originalProperties->transform(),
                                objectProperties->transform());
      DCHECK_OBJECT_PROPERTY_EQ(m_object, m_originalProperties->effect(),
                                objectProperties->effect());
      DCHECK_OBJECT_PROPERTY_EQ(m_object, m_originalProperties->cssClip(),
                                objectProperties->cssClip());
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->cssClipFixedPosition(),
                                objectProperties->cssClipFixedPosition());
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->innerBorderRadiusClip(),
                                objectProperties->innerBorderRadiusClip());
      DCHECK_OBJECT_PROPERTY_EQ(m_object, m_originalProperties->overflowClip(),
                                objectProperties->overflowClip());
      DCHECK_OBJECT_PROPERTY_EQ(m_object, m_originalProperties->perspective(),
                                objectProperties->perspective());
      DCHECK_OBJECT_PROPERTY_EQ(
          m_object, m_originalProperties->svgLocalToBorderBoxTransform(),
          objectProperties->svgLocalToBorderBoxTransform());
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->scrollTranslation(),
                                objectProperties->scrollTranslation());
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->scrollTranslation(),
                                objectProperties->scrollTranslation());
      DCHECK_OBJECT_PROPERTY_EQ(m_object,
                                m_originalProperties->scrollbarPaintOffset(),
                                objectProperties->scrollbarPaintOffset());
      const auto* originalBorderBox =
          m_originalProperties->localBorderBoxProperties();
      const auto* objectBorderBox =
          objectProperties->localBorderBoxProperties();
      if (originalBorderBox && objectBorderBox) {
        DCHECK_OBJECT_PROPERTY_EQ(m_object, originalBorderBox->transform(),
                                  objectBorderBox->transform());
        DCHECK_OBJECT_PROPERTY_EQ(m_object, originalBorderBox->clip(),
                                  objectBorderBox->clip());
        DCHECK_OBJECT_PROPERTY_EQ(m_object, originalBorderBox->effect(),
                                  objectBorderBox->effect());
        DCHECK_OBJECT_PROPERTY_EQ(m_object, originalBorderBox->scroll(),
                                  objectBorderBox->scroll());
      } else {
        DCHECK_EQ(!!originalBorderBox, !!objectBorderBox)
            << " Object: " << m_object.debugName();
      }
    } else {
      DCHECK_EQ(!!m_originalProperties, !!objectProperties)
          << " Object: " << m_object.debugName();
    }
    // Restore original clean bit.
    m_object.getMutableForPainting().clearNeedsPaintPropertyUpdateForTesting();
  }

 private:
  const LayoutObject& m_object;
  bool m_neededPaintPropertyUpdate;
  bool m_neededForcedSubtreeUpdate;
  LayoutPoint m_originalPaintOffset;
  std::unique_ptr<const ObjectPaintProperties> m_originalProperties;
};

}  // namespace blink
#endif  // DCHECK_IS_ON()

#endif  // FindPropertiesNeedingUpdate_h


text:
package org.teavm.classlib.java.util.function;

@FunctionalInterface
public interface TIntConsumer {
    void accept(int value);

    default TIntConsumer andThen(TIntConsumer after) {
        return v -> {
            accept(v);
            after.accept(v);
        };
    }
}


text:
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            new SharedCode(); // Should print Hello World
        }
    }
}


text:
layout: search
title: Search
site_root:  ../
description: To help you navigate our documentation, we've added this nifty search box.
---

Try searching for "large-top-space" or "grid gutters" or anything else you want to know about:

  <form class="ink-form docsearch">

          <input type="search" class="search-field main" placeholder="Search" name="search" tabindex="1">
          <button class="ink-button black">Search</button>

  </form>

Results


text:
struct ParserTest : public testing::Test,
                    public ManifestParser::FileReader {
  void AssertParse(const char* input) {
    ManifestParser parser(&state, this);
    string err;
    ASSERT_TRUE(parser.Parse(input, &err)) << err;
    ASSERT_EQ("", err);
  }

  virtual bool ReadFile(const string& path, string* content, string* err) {
    files_read_.push_back(path);
    map<string, string>::iterator i = files_.find(path);
    if (i == files_.end()) {
      *err = "No such file or directory";  // Match strerror() for ENOENT.
      return false;
    }
    *content = i->second;
    return true;
  }

  State state;
  map<string, string> files_;
  vector<string> files_read_;
};

TEST_F(ParserTest, Empty) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(""));
}

TEST_F(ParserTest, Rules) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n"
"  command = cat $in > $out\n"
"\n"
"rule date\n"
"  command = date > $out\n"
"\n"
"build result: cat in_1.cc in-2.O\n"));

  ASSERT_EQ(3u, state.rules_.size());
  const Rule* rule = state.rules_.begin()->second;
  EXPECT_EQ("cat", rule->name_);
  EXPECT_EQ("cat $in > $out", rule->command_.unparsed());
}

TEST_F(ParserTest, Variables) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"l = one-letter-test\n"
"rule link\n"
"  command = ld $l $extra $with_under -o $out $in\n"
"\n"
"extra = -pthread\n"
"with_under = -under\n"
"build a: link b c\n"
"nested1 = 1\n"
"nested2 = $nested1/2\n"
"build supernested: link x\n"
"  extra = $nested2/3\n"));

  ASSERT_EQ(2u, state.edges_.size());
  Edge* edge = state.edges_[0];
  EXPECT_EQ("ld one-letter-test -pthread -under -o a b c",
            edge->EvaluateCommand());
  EXPECT_EQ("1/2", state.bindings_.LookupVariable("nested2"));

  edge = state.edges_[1];
  EXPECT_EQ("ld one-letter-test 1/2/3 -under -o supernested x",
            edge->EvaluateCommand());
}

TEST_F(ParserTest, VariableScope) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"foo = bar\n"
"rule cmd\n"
"  command = cmd $foo $in $out\n"
"\n"
"build inner: cmd a\n"
"  foo = baz\n"
"build outer: cmd b\n"
"\n"  // Extra newline after build line tickles a regression.
));

  ASSERT_EQ(2u, state.edges_.size());
  EXPECT_EQ("cmd baz a inner", state.edges_[0]->EvaluateCommand());
  EXPECT_EQ("cmd bar b outer", state.edges_[1]->EvaluateCommand());
}

TEST_F(ParserTest, Continuation) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule link\n"
"  command = foo bar $\n"
"    baz\n"
"\n"
"build a: link c $\n"
" d e f\n"));

  ASSERT_EQ(2u, state.rules_.size());
  const Rule* rule = state.rules_.begin()->second;
  EXPECT_EQ("link", rule->name_);
  EXPECT_EQ("foo bar baz", rule->command_.unparsed());
}

TEST_F(ParserTest, Backslash) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"foo = bar\\baz\n"
"foo2 = bar\\ baz\n"
));
  EXPECT_EQ("bar\\baz", state.bindings_.LookupVariable("foo"));
  EXPECT_EQ("bar\\ baz", state.bindings_.LookupVariable("foo2"));
}

TEST_F(ParserTest, Comment) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"# this is a comment\n"
"foo = not # a comment\n"));
  EXPECT_EQ("not # a comment", state.bindings_.LookupVariable("foo"));
}

TEST_F(ParserTest, Dollars) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule foo\n"
"  command = ${out}bar$$baz$$$\n"
"blah\n"
"x = $$dollar\n"
"build $x: foo y\n"
));
  EXPECT_EQ("$dollar", state.bindings_.LookupVariable("x"));
  EXPECT_EQ("$dollarbar$baz$blah", state.edges_[0]->EvaluateCommand());
}

TEST_F(ParserTest, CanonicalizeFile) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n"
"  command = cat $in > $out\n"
"build out: cat in/1 in//2\n"
"build in/1: cat\n"
"build in/2: cat\n"));

  EXPECT_TRUE(state.LookupNode("in/1"));
  EXPECT_TRUE(state.LookupNode("in/2"));
  EXPECT_FALSE(state.LookupNode("in//1"));
  EXPECT_FALSE(state.LookupNode("in//2"));
}

TEST_F(ParserTest, PathVariables) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n"
"  command = cat $in > $out\n"
"dir = out\n"
"build $dir/exe: cat src\n"));

  EXPECT_FALSE(state.LookupNode("$dir/exe"));
  EXPECT_TRUE(state.LookupNode("out/exe"));
}

TEST_F(ParserTest, CanonicalizePaths) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n"
"  command = cat $in > $out\n"
"build ./out.o: cat ./bar/baz/../foo.cc\n"));

  EXPECT_FALSE(state.LookupNode("./out.o"));
  EXPECT_TRUE(state.LookupNode("out.o"));
  EXPECT_FALSE(state.LookupNode("./bar/baz/../foo.cc"));
  EXPECT_TRUE(state.LookupNode("bar/foo.cc"));
}

TEST_F(ParserTest, ReservedWords) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule build\n"
"  command = rule run $out\n"
"build subninja: build include default foo.cc\n"
"default subninja\n"));
}

TEST_F(ParserTest, Errors) {
  {
    ManifestParser parser(NULL, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("foobar", &err));
    EXPECT_EQ("line 1, col 7: expected '=', got eof", err);
  }

  {
    ManifestParser parser(NULL, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x 3", &err));
    EXPECT_EQ("line 1, col 3: expected '=', got '3'", err);
  }

  {
    ManifestParser parser(NULL, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x = 3", &err));
    EXPECT_EQ("line 1, col 6: expected newline, got eof", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x = 3\ny 2", &err));
    EXPECT_EQ("line 2, col 3: expected '=', got '2'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x = $", &err));
    EXPECT_EQ("line 1, col 3: unexpected eof", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x = $\n $[\n", &err));
    EXPECT_EQ("line 2, col 3: expected variable after $", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("x = a$\n b$\n $\n", &err));
    EXPECT_EQ("line 4, col 1: expected newline, got eof", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("build x: y z\n", &err));
    EXPECT_EQ("line 1, col 10: unknown build rule 'y'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("build x:: y z\n", &err));
    EXPECT_EQ("line 1, col 9: expected build command name, got ':'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cat\n  command = cat ok\n"
                              "build x: cat $\n :\n",
                              &err));
    EXPECT_EQ("line 4, col 2: expected newline, got ':'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cat\n",
                              &err));
    EXPECT_EQ("line 2, col 1: expected 'command =' line", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cat\n  command = ${fafsd\n  foo = bar\n",
                              &err));
    EXPECT_EQ("line 2, col 20: expected closing curly after ${", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cat\n  command = cat\nbuild $: cat foo\n",
                              &err));
    // XXX EXPECT_EQ("line 3, col 7: expected variable after $", err);
    EXPECT_EQ("line 4, col 1: expected variable after $", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule %foo\n",
                              &err));
    EXPECT_EQ("line 1, col 6: expected rule name, got unknown '%'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cc\n  command = foo\n  othervar = bar\n",
                              &err));
    EXPECT_EQ("line 3, col 3: unexpected variable 'othervar'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule cc\n  command = foo\n"
                              "build $: cc bar.cc\n",
                              &err));
    EXPECT_EQ("line 4, col 1: expected variable after $", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("default\n",
                              &err));
    EXPECT_EQ("line 1, col 8: expected target name, got newline", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("default nonexistent\n",
                              &err));
    EXPECT_EQ("line 1, col 9: unknown target 'nonexistent'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule r\n  command = r\n"
                              "build b: r\n"
                              "default b:\n",
                              &err));
    EXPECT_EQ("line 4, col 10: expected newline, got ':'", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("default $a\n", &err));
    EXPECT_EQ("line 1, col 9: empty path", err);
  }

  {
    State state;
    ManifestParser parser(&state, NULL);
    string err;
    EXPECT_FALSE(parser.Parse("rule r\n"
                              "  command = r\n"
                              "build $a: r $c\n", &err));
    // XXX the line number is wrong; we should evaluate paths in ParseEdge
    // as we see them, not after we've read them all!
    EXPECT_EQ("line 4, col 1: empty path", err);
  }
}

TEST_F(ParserTest, MultipleOutputs)
{
  State state;
  ManifestParser parser(&state, NULL);
  string err;
  EXPECT_TRUE(parser.Parse("rule cc\n  command = foo\n  depfile = bar\n"
                            "build a.o b.o: cc c.cc\n",
                            &err));
  EXPECT_EQ("", err);
}

TEST_F(ParserTest, SubNinja) {
  files_["test.ninja"] =
    "var = inner\n"
    "build $builddir/inner: varref\n";
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"builddir = some_dir/\n"
"rule varref\n"
"  command = varref $var\n"
"var = outer\n"
"build $builddir/outer: varref\n"
"subninja test.ninja\n"
"build $builddir/outer2: varref\n"));
  ASSERT_EQ(1u, files_read_.size());

  EXPECT_EQ("test.ninja", files_read_[0]);
  EXPECT_TRUE(state.LookupNode("some_dir/outer"));
  // Verify our builddir setting is inherited.
  EXPECT_TRUE(state.LookupNode("some_dir/inner"));

  ASSERT_EQ(3u, state.edges_.size());
  EXPECT_EQ("varref outer", state.edges_[0]->EvaluateCommand());
  EXPECT_EQ("varref inner", state.edges_[1]->EvaluateCommand());
  EXPECT_EQ("varref outer", state.edges_[2]->EvaluateCommand());
}

TEST_F(ParserTest, MissingSubNinja) {
  ManifestParser parser(&state, this);
  string err;
  EXPECT_FALSE(parser.Parse("subninja foo.ninja\n", &err));
  EXPECT_EQ("line 1, col 10: loading foo.ninja: No such file or directory",
            err);
}

TEST_F(ParserTest, Include) {
  files_["include.ninja"] = "var = inner\n";
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"var = outer\n"
"include include.ninja\n"));

  ASSERT_EQ(1u, files_read_.size());
  EXPECT_EQ("include.ninja", files_read_[0]);
  EXPECT_EQ("inner", state.bindings_.LookupVariable("var"));
}

TEST_F(ParserTest, Implicit) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n  command = cat $in > $out\n"
"build foo: cat bar | baz\n"));

  Edge* edge = state.LookupNode("foo")->in_edge_;
  ASSERT_TRUE(edge->is_implicit(1));
}

TEST_F(ParserTest, OrderOnly) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n  command = cat $in > $out\n"
"build foo: cat bar || baz\n"));

  Edge* edge = state.LookupNode("foo")->in_edge_;
  ASSERT_TRUE(edge->is_order_only(1));
}

TEST_F(ParserTest, DefaultDefault) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n  command = cat $in > $out\n"
"build a: cat foo\n"
"build b: cat foo\n"
"build c: cat foo\n"
"build d: cat foo\n"));

  string err;
  EXPECT_EQ(4u, state.DefaultNodes(&err).size());
  EXPECT_EQ("", err);
}

TEST_F(ParserTest, DefaultStatements) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(
"rule cat\n  command = cat $in > $out\n"
"build a: cat foo\n"
"build b: cat foo\n"
"build c: cat foo\n"
"build d: cat foo\n"
"third = c\n"
"default a b\n"
"default $third\n"));

  string err;
  std::vector<Node*> nodes = state.DefaultNodes(&err);
  EXPECT_EQ("", err);
  ASSERT_EQ(3u, nodes.size());
  EXPECT_EQ("a", nodes[0]->file_->path_);
  EXPECT_EQ("b", nodes[1]->file_->path_);
  EXPECT_EQ("c", nodes[2]->file_->path_);
}

TEST(MakefileParser, Basic) {
  MakefileParser parser;
  string err;
  EXPECT_TRUE(parser.Parse(
"build/ninja.o: ninja.cc ninja.h eval_env.h manifest_parser.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("build/ninja.o", parser.out_.AsString());
  EXPECT_EQ(4u, parser.ins_.size());
}

TEST(MakefileParser, EarlyNewlineAndWhitespace) {
  MakefileParser parser;
  string err;
  EXPECT_TRUE(parser.Parse(
" \\\n"
"  out: in\n",
      &err));
  ASSERT_EQ("", err);
}

TEST(MakefileParser, Continuation) {
  MakefileParser parser;
  string err;
  EXPECT_TRUE(parser.Parse(
"foo.o: \\\n"
"  bar.h baz.h\n",
      &err));
  ASSERT_EQ("", err);
  EXPECT_EQ("foo.o", parser.out_.AsString());
  EXPECT_EQ(2u, parser.ins_.size());
}


text:
FactoryGirl.define do
  factory :summary,:class => BasicoOctokit::Models::Summary do |f|
    f.date_start Date.today - 1
    f.date_end Date.today
    f.state 'opened'
    f.repository 'lojabasico/tickets_ti'
    f.total 10
    f.summary_labels nil
    f.summary_users nil
  end
end


text:
//
//  KTSearchengineResult.h
//  keytechKit
//
//  Created by Thorsten Claus on 06.11.14.
//  Copyright (c) 2017 Claus-Software. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "KTElement.h"

/**
 Represents a manager object to retrive search results within files
 */
@interface KTSearchengineResult : NSObject
+(RKObjectMapping*)mappingWithManager:(RKObjectManager*)manager;

/**
 The underlying element that contains the searched value
 */
@property (nonatomic) KTElement *element;

/**
 The internal Solr ID to uniquely identify the element in the search index.
 */
@property (nonatomic) NSString *solrIndexID;

@end


text:
.file-manager-bar {
  list-style: none;
  display: inline-block;
  float:left;
  padding: 0;
}
.file-manager-bar:after {
  content: '';
  display: block;
  clear: both;
}
.file-manager-bar > li {
  float: left;
}

[hidden] {
  display: none !important;
}


text:
package org.auraframework.integration.test.root.application;

import org.auraframework.Aura;
import org.auraframework.def.*;
import org.auraframework.impl.root.application.ApplicationDefImpl;
import org.auraframework.impl.root.application.ApplicationDefImpl.Builder;
import org.auraframework.impl.root.component.BaseComponentDefImplUnitTest;
import org.mockito.Mock;
import org.mockito.Mockito;

public class ApplicationDefImplUnitTest extends
        BaseComponentDefImplUnitTest<ApplicationDefImpl, ApplicationDef, Builder> {

    @Mock
    DefDescriptor<EventDef> locationChangeEventDescriptor;
    DefinitionAccess access;
    Boolean isAppcacheEnabled;
    String additionalAppCacheURLs;
    Boolean isOnePageApp;

    public ApplicationDefImplUnitTest(String name) {
        super(name);
        qualifiedDescriptorName = "test:application";
    }

    @Override
    protected Builder getBuilder() {
        return new Builder();
    }

    @Override
    protected ApplicationDef buildDefinition(Builder builder) throws Exception {
        builder.locationChangeEventDescriptor = this.locationChangeEventDescriptor;
        builder.setAccess(this.access);
        builder.isAppcacheEnabled = this.isAppcacheEnabled;
        builder.additionalAppCacheURLs = this.additionalAppCacheURLs;
        builder.isOnePageApp = this.isOnePageApp;
        return super.buildDefinition(builder);
    }

    @Override
    protected void setupValidateReferences() throws Exception {
        super.setupValidateReferences();
        DefDescriptor<EventDef> superDesc = Aura.getDefinitionService().getDefDescriptor("aura:locationChange",
                EventDef.class);
        EventDef locationChangeEventDef = Mockito.mock(EventDef.class);
        Mockito.doReturn(true).when(locationChangeEventDef).isInstanceOf(superDesc);
        Mockito.doReturn(locationChangeEventDef).when(this.locationChangeEventDescriptor).getDef();
    }
}


text:
namespace base {
class DictionaryValue;
class ListValue;
class Value;
}

// Base class for unit tests for JSONSchemaValidator. There is currently only
// one implementation, JSONSchemaValidatorCPPTest.
//
// TODO(aa): Refactor chrome/test/data/json_schema_test.js into
// JSONSchemaValidatorJSTest that inherits from this.
class JSONSchemaValidatorTestBase : public testing::Test {
 public:
  JSONSchemaValidatorTestBase();

  void RunTests();

 protected:
  virtual void ExpectValid(const std::string& test_source,
                           base::Value* instance,
                           base::DictionaryValue* schema,
                           base::ListValue* types) = 0;

  virtual void ExpectNotValid(const std::string& test_source,
                              base::Value* instance,
                              base::DictionaryValue* schema,
                              base::ListValue* types,
                              const std::string& expected_error_path,
                              const std::string& expected_error_message) = 0;

 private:
  void TestComplex();
  void TestStringPattern();
  void TestEnum();
  void TestChoices();
  void TestExtends();
  void TestObject();
  void TestTypeReference();
  void TestArrayTuple();
  void TestArrayNonTuple();
  void TestString();
  void TestNumber();
  void TestTypeClassifier();
  void TestTypes();
};

#endif  // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_


text:
/**
 *
 */
package gov.nih.nci.cagrid.portal.portlet.browse;

import gov.nih.nci.cagrid.portal.domain.catalog.CatalogEntry;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Joshua Phillips
 *
 */
public class CatalogEntryFactory {

	private Map<String,String> entryTypeMap = new HashMap<String,String>();

	/**
	 *
	 */
	public CatalogEntryFactory() {

	}

	public CatalogEntry newCatalogEntry(String logicalTypeName){
		CatalogEntry ce = null;
		String classname = getEntryTypeMap().get(logicalTypeName);
		if(classname == null){
			throw new RuntimeException("Unknown catalog entry type: " + logicalTypeName);
		}
		try{
			ce = (CatalogEntry)Class.forName(classname).newInstance();
		}catch(Exception ex){
			throw new RuntimeException("Error creating catalog entry: " + ex.getMessage(), ex);
		}

		return ce;
	}

	public Map<String, String> getEntryTypeMap() {
		return entryTypeMap;
	}

	public void setEntryTypeMap(Map<String, String> entryTypeMap) {
		this.entryTypeMap = entryTypeMap;
	}

}


text:
<!--
  Copyright (C) FuseSource, Inc.
  http://fusesource.com

  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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.fusesource.insight</groupId>
    <artifactId>insight-project</artifactId>
    <version>1.0.0.redhat-379</version>
  </parent>

  <artifactId>insight-jetty</artifactId>
  <name>${project.artifactId}</name>
  <description>Fuse Insight :: Jetty</description>
  <packaging>bundle</packaging>

  <properties>
    <fuse.osgi.export>
    </fuse.osgi.export>
    <fuse.osgi.private.pkg>
        org.fusesource.insight.jetty*;version=${fabric.version}
    </fuse.osgi.private.pkg>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.core</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.compendium</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.fusesource.insight</groupId>
        <artifactId>insight-storage</artifactId>
        <scope>provided</scope>
    </dependency>

      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
      </dependency>

      <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-server</artifactId>
      </dependency>
      <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-jmx</artifactId>
      </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <scope>provided</scope>
    </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <excludeDependencies>${fuse.osgi.exclude.dependencies}</excludeDependencies>
                    <instructions combine.self="override">
                        <Bundle-Name>${fuse.osgi.bundle.name}</Bundle-Name>
                        <Bundle-SymbolicName>${fuse.osgi.symbolic.name}</Bundle-SymbolicName>
                        <Bundle-DocURL>http://fabric.fusesource.org/</Bundle-DocURL>
                        <Export-Package></Export-Package>
                        <Private-Package>org.fusesource.insight.jetty*,org.eclipse.jetty.jmx</Private-Package>
                        <Import-Package>*</Import-Package>
                        <Embed-Dependency></Embed-Dependency>
                        <Fragment-Host>org.ops4j.pax.web.pax-web-jetty</Fragment-Host>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package org.apache.camel.util;

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

/**
 * Helper for Camel OGNL (Object-Graph Navigation Language) expressions.
 */
public final class OgnlHelper {

    private static final Pattern INDEX_PATTERN = Pattern.compile("^(.*)\\[(.*)\\]$");

    private OgnlHelper() {
    }

    /**
     * Tests whether or not the given String is a Camel OGNL expression.
     *

     * An expression is considered an OGNL expression when it contains either one of the following chars: . or [
     *
     * @param expression  the String
     * @return <tt>true</tt> if a Camel OGNL expression, otherwise <tt>false</tt>.
     */
    public static boolean isValidOgnlExpression(String expression) {
        if (ObjectHelper.isEmpty(expression)) {
            return false;
        }

        // the brackets should come in a pair
        int bracketBegin = StringHelper.countChar(expression, '[');
        int bracketEnd = StringHelper.countChar(expression, ']');
        if (bracketBegin > 0 && bracketEnd > 0) {
            return bracketBegin == bracketEnd;
        }

        return expression.contains(".");
    }

    public static boolean isInvalidValidOgnlExpression(String expression) {
        if (ObjectHelper.isEmpty(expression)) {
            return false;
        }

        if (!expression.contains(".") && !expression.contains("[") && !expression.contains("]")) {
            return false;
        }

        // the brackets should come in pair
        int bracketBegin = StringHelper.countChar(expression, '[');
        int bracketEnd = StringHelper.countChar(expression, ']');
        if (bracketBegin > 0 || bracketEnd > 0) {
            return bracketBegin != bracketEnd;
        }

        // check for double dots
        if (expression.contains("..")) {
            return true;
        }

        return false;
    }

    /**
     * Validates whether the method name is using valid java identifiers in the name
     * Will throw {@link IllegalArgumentException} if the method name is invalid.
     */
    public static void validateMethodName(String method) {
        if (ObjectHelper.isEmpty(method)) {
            return;
        }
        for (int i = 0; i < method.length(); i++) {
            char ch = method.charAt(i);
            if (i == 0 && '.' == ch) {
                // its a dot before a method name
                continue;
            }
            if (ch == '(' || ch == '[' || ch == '.' || ch == '?') {
                // break when method name ends and sub method or arguments begin
                break;
            }
            if (i == 0 && !Character.isJavaIdentifierStart(ch)) {
                throw new IllegalArgumentException("Method name must start with a valid java identifier at position: 0 in method: " + method);
            } else if (!Character.isJavaIdentifierPart(ch)) {
                throw new IllegalArgumentException("Method name must be valid java identifier at position: " + i + " in method: " + method);
            }
        }
    }

    /**
     * Tests whether or not the given Camel OGNL expression is using the null safe operator or not.
     *
     * @param ognlExpression the Camel OGNL expression
     * @return <tt>true</tt> if the null safe operator is used, otherwise <tt>false</tt>.
     */
    public static boolean isNullSafeOperator(String ognlExpression) {
        if (ObjectHelper.isEmpty(ognlExpression)) {
            return false;
        }

        return ognlExpression.startsWith("?");
    }

    /**
     * Removes any leading operators from the Camel OGNL expression.
     *

     * Will remove any leading of the following chars: ? or .
     *
     * @param ognlExpression  the Camel OGNL expression
     * @return the Camel OGNL expression without any leading operators.
     */
    public static String removeLeadingOperators(String ognlExpression) {
        if (ObjectHelper.isEmpty(ognlExpression)) {
            return ognlExpression;
        }

        if (ognlExpression.startsWith("?")) {
            ognlExpression = ognlExpression.substring(1);
        }
        if (ognlExpression.startsWith(".")) {
            ognlExpression = ognlExpression.substring(1);
        }

        return ognlExpression;
    }

    /**
     * Removes any trailing operators from the Camel OGNL expression.
     *
     * @param ognlExpression  the Camel OGNL expression
     * @return the Camel OGNL expression without any trailing operators.
     */
    public static String removeTrailingOperators(String ognlExpression) {
        if (ObjectHelper.isEmpty(ognlExpression)) {
            return ognlExpression;
        }

        if (ognlExpression.contains("[")) {
            return StringHelper.before(ognlExpression, "[");
        }
        return ognlExpression;
    }

    public static String removeOperators(String ognlExpression) {
        return removeLeadingOperators(removeTrailingOperators(ognlExpression));
    }

    public static KeyValueHolder<String, String> isOgnlIndex(String ognlExpression) {
        Matcher matcher = INDEX_PATTERN.matcher(ognlExpression);
        if (matcher.matches()) {

            // to avoid empty strings as we want key/value to be null in such cases
            String key = matcher.group(1);
            if (ObjectHelper.isEmpty(key)) {
                key = null;
            }

            // to avoid empty strings as we want key/value to be null in such cases
            String value = matcher.group(2);
            if (ObjectHelper.isEmpty(value)) {
                value = null;
            }

            return new KeyValueHolder<>(key, value);
        }

        return null;
    }

    /**
     * Regular expression with repeating groups is a pain to get right
     * and then nobody understands the reg exp afterwards.
     * So we use a bit ugly/low-level Java code to split the OGNL into methods.
     *
     * @param ognl the ognl expression
     * @return a list of methods, will return an empty list, if ognl expression has no methods
     * @throws IllegalArgumentException if the last method has a missing ending parenthesis
     */
    public static List<String> splitOgnl(String ognl) {
        List<String> methods = new ArrayList<>();

        // return an empty list if ognl is empty
        if (ObjectHelper.isEmpty(ognl)) {
            return methods;
        }

        StringBuilder sb = new StringBuilder();

        int j = 0; // j is used as counter per method
        boolean squareBracket = false; // special to keep track if we are inside a square bracket block, eg: [foo]
        boolean parenthesisBracket = false; // special to keep track if we are inside a parenthesis block, eg: bar(${body}, ${header.foo})
        for (int i = 0; i < ognl.length(); i++) {
            char ch = ognl.charAt(i);
            // special for starting a new method
            if (j == 0 || (j == 1 && ognl.charAt(i - 1) == '?')
                    || (ch != '.' && ch != '?' && ch != ']')) {
                sb.append(ch);
                // special if we are doing square bracket
                if (ch == '[' && !parenthesisBracket) {
                    squareBracket = true;
                } else if (ch == '(') {
                    parenthesisBracket = true;
                } else if (ch == ')') {
                    parenthesisBracket = false;
                }
                j++; // advance
            } else {
                if (ch == '.' && !squareBracket && !parenthesisBracket) {
                    // only treat dot as a method separator if not inside a square bracket block
                    // as dots can be used in key names when accessing maps

                    // a dit denotes end of this method and a new method is to be invoked
                    String s = sb.toString();

                    // reset sb
                    sb.setLength(0);

                    // pass over ? to the new method
                    if (s.endsWith("?")) {
                        sb.append("?");
                        s = s.substring(0, s.length() - 1);
                    }

                    // add the method
                    methods.add(s);

                    // reset j to begin a new method
                    j = 0;
                } else if (ch == ']' && !parenthesisBracket) {
                    // append ending ] to method name
                    sb.append(ch);
                    String s = sb.toString();

                    // reset sb
                    sb.setLength(0);

                    // add the method
                    methods.add(s);

                    // reset j to begin a new method
                    j = 0;

                    // no more square bracket
                    squareBracket = false;
                }

                // and don't lose the char if its not an ] end marker (as we already added that)
                if (ch != ']' || parenthesisBracket) {
                    sb.append(ch);
                }

                // only advance if already begun on the new method
                if (j > 0) {
                    j++;
                }
            }
        }

        // add remainder in buffer when reached end of data
        if (sb.length() > 0) {
            methods.add(sb.toString());
        }

        String last = methods.isEmpty() ? null : methods.get(methods.size() - 1);
        if (parenthesisBracket && last != null) {
            // there is an unclosed parenthesis bracket on the last method, so it should end with a parenthesis
            if (last.contains("(") && !last.endsWith(")")) {
                throw new IllegalArgumentException("Method should end with parenthesis, was " + last);
            }
        }

        return methods;
    }

}


text:
package com.pie.tlatoani.Skin;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;

/**
 * Created by Tlatoani on 1/20/18.
 */
public class ExprTabName extends SimpleExpression<String> {
    @Override
    protected String[] get(Event event) {
        return new String[0];
    }

    @Override
    public boolean isSingle() {
        return false;
    }

    @Override
    public Class<? extends String> getReturnType() {
        return null;
    }

    @Override
    public String toString(Event event, boolean b) {
        return null;
    }

    @Override
    public boolean init(Expression<?>[] expressions, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) {
        Skript.error("The 'mundosk tablist name of %player%' expression was removed in MundoSK 1.8.3. "
                + "Please use the Displayed Name of Player Tab expression using 'all players' instead (do '/mundosk doc displayed name of player tab' for more info)");
        return false;
    }
}


text:
@interface MDCFlatButtonsTests : XCTestCase
@end

@implementation MDCFlatButtonsTests

- (void)testDefaultElevationsForState {
  // Given
  MDCFlatButton *button = [MDCFlatButton appearance];

  // Then
  XCTAssertEqual([button elevationForState:UIControlStateNormal], MDCShadowElevationNone);
  XCTAssertEqual([button elevationForState:UIControlStateHighlighted], MDCShadowElevationNone);
  XCTAssertEqual([button elevationForState:UIControlStateDisabled], MDCShadowElevationNone);
  XCTAssertEqual([button elevationForState:UIControlStateSelected], MDCShadowElevationNone);
}

// TODO(#2782): Remove this test and replace it with default checks once UIAppearance is no longer
//              used for overriding MDCButton
- (void)testMDCFlatButtonDoesNotModifyInkColorInInit {
  // Given
  MDCButton *button = [[MDCButton alloc] init];
  MDCFlatButton *flatButton = [[MDCFlatButton alloc] init];

  // Then
  XCTAssertEqualObjects(flatButton.inkColor, button.inkColor);
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<inset android:insetLeft="0.0dip" android:insetRight="0.0dip" android:insetTop="0.0dip" android:insetBottom="0.0dip"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <shape android:shape="rectangle">
        <corners android:radius="1.0dip" />
        <solid android:color="#19000000" />
    </shape>
</inset>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Management;
using Kooboo.CMS.Sites.Services;
using System.ComponentModel.DataAnnotations;

namespace Kooboo.CMS.Web.Areas.Sites.Models
{
    public class DiagnosisResult_Metadata
    {
        public WebApplicationInformation WebApplicationInformation { get; set; }
        [Display(Name = "Content provider")]
        public string ContentProvider { get; set; }
        public DiagnosisItem[] DiagnosisItems { get; set; }
    }

    public class WebApplicationInformation_Metadata
    {
        [Display(Name = "Application virtual path")]
        public string ApplicationVirtualPath { get; set; }
        [Display(Name = "Machine name")]
        public string MachineName { get; set; }
        [Display(Name = "Trust level")]
        public string TrustLevel { get; set; }
    }
}


text:
class ChangeTypeToInteger < ActiveRecord::Migration
  def change
    change_column :clients, :hourly_rate_cents, :integer
    change_column :worklogs, :hourly_rate_cents, :integer
    change_column :worklogs, :total_cents, :integer
    change_column :invoices, :total_cents, :integer
  end
end


text:
/* ================== IE.css ==================== *\
|*        Rules here apply to all versions        *|
|*        of Internet Explorer for Windows        *|
|*        prior to and including version 6        *|
\* ============================================== */

/* Setting position:relative on anything containing
   floated elements, as well as floated elements
   themselves helps floated elements behave. */
#wrapper, #nav, #primary {
	position: relative;
}
/* Setting height:1% makes elements
  stretch vertically to enclose floated elements. */
#main, #primary {
  height: 1%;
}
/* Setting display:inline helps fix margins of
   floated elements */
#secondary {
  display: inline;
}

/* For the nav */
#nav li {
  float: left;
}
#nav li, #nav a {
  display: inline;
}
#nav {
  height: 1%;
}

/* For the contact form */
.formrow, div.send {
  height: 1%;
}
#contact-form, #contact-info, label, texarea, input, button, #flash-notice img {
  display: inline;
  position: relative;
}


text:
<?php
class Solicitud_model extends CI_Model {
  public function __construct(){
    $this->load->database();
  }

  public function buscar_todos(){
    $query = $this->db->query('SELECT s.id, s.estado, s.fecha_creacion as fecha, c.nombre as cliente, r1.numero_de_facturas, r1.total, s.cupones
        FROM eugene.solicitudes as s
        INNER JOIN eugene.clientes as c on c.id = s.cliente_id
        LEFT JOIN (
          SELECT f.solicitud_id, count(*) as numero_de_facturas, sum(total) as total
          FROM eugene.facturas as f
          group by f.solicitud_id
        ) as r1 on r1.solicitud_id = s.id
        ORDER BY s.fecha_creacion DESC');

    return $query->result_array();
  }

  public function buscar_10_ultimas(){
    $query = $this->db->query('SELECT s.id, s.estado, s.fecha_creacion as fecha, c.nombre as cliente, r1.numero_de_facturas, r1.total
                  FROM eugene.solicitudes as s
                  INNER JOIN eugene.clientes as c on c.id = s.cliente_id
                  LEFT JOIN (
                    SELECT f.solicitud_id, count(*) as numero_de_facturas, sum(total) as total
                    FROM eugene.facturas as f
                    group by f.solicitud_id
                  ) as r1 on r1.solicitud_id = s.id
          ORDER BY s.fecha_creacion DESC
          LIMIT 10');

    return $query->result_array();
  }

  public function buscar_por_id($id){
    $query = $this->db->query('SELECT s.id, s.estado, s.cupones, s.fecha_creacion as fecha, c.nombre as cliente, r1.numero_de_facturas, r1.total, p.nombre as promocion, s.promocion_id
        FROM eugene.solicitudes as s
        INNER JOIN eugene.clientes as c on c.id = s.cliente_id
        INNER JOIN eugene.promociones as p on p.id = s.promocion_id
        LEFT JOIN (
          SELECT f.solicitud_id, count(*) as numero_de_facturas, sum(total) as total
          FROM eugene.facturas as f
          group by f.solicitud_id
        ) as r1 on r1.solicitud_id = s.id
        WHERE s.id = '.$id);
    return $query->row(0);
  }

  public function buscar_por_cliente_id($id){
    $query = $this->db->query('SELECT s.id, s.estado, s.cupones, s.fecha_creacion as fecha, c.nombre as cliente, r1.numero_de_facturas, r1.total, p.nombre as promocion
        FROM eugene.solicitudes as s
        INNER JOIN eugene.clientes as c on c.id = s.cliente_id
        INNER JOIN eugene.promociones as p on p.id = s.promocion_id
        LEFT JOIN (
          SELECT f.solicitud_id, count(*) as numero_de_facturas, sum(total) as total
          FROM eugene.facturas as f
          group by f.solicitud_id
        ) as r1 on r1.solicitud_id = s.id
        WHERE s.cliente_id = '.$id);
    return $query->result_array();
  }

  public function guardar($data){
    date_default_timezone_set('America/Guayaquil');
    $fecha_creacion = date("Y-m-d H:i:s");
    $respuesta = $this->db->insert('solicitudes', array(
      'cliente_id' => $data['cliente_id'],
      'promocion_id' => $data['promocion_id'],
      'estado' => 'pendiente',
      'creado_por_id' => $this->auth_user_id,
      'fecha_creacion' => $fecha_creacion,
      'fecha_modificacion' => $fecha_creacion
    ));

    if(!$respuesta) return false;

    $solicitud_id = $this->db->insert_id();
    $facturas = $data['facturas'];

    $data_comun = array(
      'solicitud_id' => $solicitud_id,
      'fecha_creacion' => $fecha_creacion,
      'fecha_modificacion' => $fecha_creacion
    );
    array_walk($facturas, function(&$factura, $index, $data){
      $factura['solicitud_id'] = $data['solicitud_id'];
      $factura['fecha_creacion'] = $data['fecha_creacion'];
      $factura['fecha_modificacion'] = $data['fecha_creacion'];
    }, $data_comun);

    $respuesta = $this->db->insert_batch('facturas', $facturas);

    if($respuesta > 0){
      return $solicitud_id;
    }
    return NULL;
  }

  public function calcularCupones($solicitud_id){
    $this->load->model('Promocion_model');
    $solicitud = $this->buscar_por_id($solicitud_id);
    $promocion = $this->Promocion_model->buscar_por_id($solicitud->promocion_id);

    $n = intval($solicitud->total / $promocion->valor_cupon);
    return $n;
  }

  public function aprobar($solicitud_id){
    $numero_cupones = $this->calcularCupones($solicitud_id, 10);
    $data = array(
      'estado' => 'aprobado',
      'cupones' => $numero_cupones
    );

    $this->db->where('id', $solicitud_id);
    return $this->db->update('solicitudes', $data);
  }
}


text:
#ifndef FIRESTORE_CORE_SRC_MODEL_OBJECT_VALUE_H_
#define FIRESTORE_CORE_SRC_MODEL_OBJECT_VALUE_H_

#include <map>
#include <ostream>
#include <set>
#include <string>
#include <utility>

#include "Firestore/Protos/nanopb/google/firestore/v1/document.nanopb.h"
#include "Firestore/core/src/model/field_mask.h"
#include "Firestore/core/src/model/field_path.h"
#include "Firestore/core/src/model/model_fwd.h"
#include "Firestore/core/src/model/value_util.h"
#include "Firestore/core/src/nanopb/message.h"
#include "Firestore/core/src/util/hard_assert.h"
#include "absl/types/optional.h"

namespace firebase {
namespace firestore {

namespace model {

/** A structured object value stored in Firestore. */
class ObjectValue {
 public:
  ObjectValue();

  /** Creates a new ObjectValue */
  explicit ObjectValue(nanopb::Message<google_firestore_v1_Value> value);

  ObjectValue(ObjectValue&& other) noexcept = default;
  ObjectValue& operator=(ObjectValue&& other) noexcept = default;
  ObjectValue(const ObjectValue& other);

  ObjectValue& operator=(const ObjectValue&) = delete;

  /**
   * Creates a new ObjectValue that is backed by the given `map_value`.
   * ObjectValue takes on ownership of the data.
   */
  static ObjectValue FromMapValue(
      nanopb::Message<google_firestore_v1_MapValue> map_value);

  /**
   * Creates a new ObjectValue that is backed by the provided document fields.
   * ObjectValue takes on ownership of the data and zeroes out the pointers in
   * `fields_entry`. This allows the callsite to destruct the Document proto
   * without affecting the fields data.
   */
  static ObjectValue FromFieldsEntry(
      google_firestore_v1_Document_FieldsEntry* fields_entry, pb_size_t count);

  /** Recursively extracts the FieldPaths that are set in this ObjectValue. */
  FieldMask ToFieldMask() const;

  /**
   * Returns the value at the given path or null.
   *
   * @param path the path to search
   * @return The value at the path or null if it doesn't exist.
   */
  absl::optional<google_firestore_v1_Value> Get(const FieldPath& path) const;

  /**
   * Returns the ObjectValue in its Protobuf representation.
   */
  google_firestore_v1_Value Get() const;

  /**
   * Sets the field to the provided value.
   *
   * @param path The field path to set. The path must not be empty.
   * @param value The value to set.
   */
  void Set(const FieldPath& path,
           nanopb::Message<google_firestore_v1_Value> value);

  /**
   * Sets the provided fields to the provided values. Fields set to `nullopt`
   * are deleted.
   *
   * Takes ownership of data.
   *
   * @param data A map of fields to values (or nullopt for deletes)
   */
  void SetAll(TransformMap data);

  /**
   * Removes the field at the specified path. If there is no field at the
   * specified path, nothing is changed.
   *
   * @param path The field path to remove. The path must not be empty.
   */
  void Delete(const FieldPath& path);

  std::string ToString() const;

  size_t Hash() const;

  friend bool operator==(const ObjectValue& lhs, const ObjectValue& rhs);
  friend std::ostream& operator<<(std::ostream& out,
                                  const ObjectValue& object_value);

 private:
  /** Returns the field mask for the provided map value. */
  FieldMask ExtractFieldMask(const google_firestore_v1_MapValue& value) const;

  /**
   * Returns the map that contains the leaf element of `path`. If the parent
   * entry does not yet exist, or if it is not a map, a new map will be created.
   */
  google_firestore_v1_MapValue* ParentMap(const FieldPath& path);

  nanopb::Message<google_firestore_v1_Value> value_;
};

inline bool operator==(const ObjectValue& lhs, const ObjectValue& rhs) {
  return *lhs.value_ == *rhs.value_;
}

inline bool operator!=(const ObjectValue& lhs, const ObjectValue& rhs) {
  return !(lhs == rhs);
}

inline std::ostream& operator<<(std::ostream& out,
                                const ObjectValue& object_value) {
  return out << "ObjectValue(" << *object_value.value_ << ")";
}

}  // namespace model
}  // namespace firestore
}  // namespace firebase

#endif  // FIRESTORE_CORE_SRC_MODEL_OBJECT_VALUE_H_


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 io.trino.execution;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.trino.FeaturesConfig;
import io.trino.connector.CatalogName;
import io.trino.connector.MockConnectorFactory;
import io.trino.connector.system.StaticSystemTablesProvider;
import io.trino.connector.system.SystemTablesMetadata;
import io.trino.execution.warnings.WarningCollector;
import io.trino.metadata.Catalog;
import io.trino.metadata.Catalog.SecurityManagement;
import io.trino.metadata.CatalogManager;
import io.trino.metadata.Metadata;
import io.trino.security.AccessControl;
import io.trino.security.AllowAllAccessControl;
import io.trino.spi.connector.Connector;
import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorTransactionHandle;
import io.trino.spi.resourcegroups.ResourceGroupId;
import io.trino.spi.security.Identity;
import io.trino.spi.security.RoleGrant;
import io.trino.spi.security.SelectedRole;
import io.trino.spi.security.TrinoPrincipal;
import io.trino.spi.transaction.IsolationLevel;
import io.trino.sql.parser.ParsingOptions;
import io.trino.sql.parser.SqlParser;
import io.trino.sql.tree.SetRole;
import io.trino.testing.TestingConnectorContext;
import io.trino.transaction.TransactionManager;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.URI;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;

import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.trino.connector.CatalogName.createInformationSchemaCatalogName;
import static io.trino.connector.CatalogName.createSystemTablesCatalogName;
import static io.trino.metadata.MetadataManager.createTestMetadataManager;
import static io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND;
import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.StandardErrorCode.ROLE_NOT_FOUND;
import static io.trino.spi.security.PrincipalType.USER;
import static io.trino.testing.TestingSession.testSessionBuilder;
import static io.trino.testing.assertions.TrinoExceptionAssert.assertTrinoExceptionThrownBy;
import static io.trino.transaction.InMemoryTransactionManager.createTestTransactionManager;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.testng.Assert.assertEquals;

public class TestSetRoleTask
{
    private static final String CATALOG_NAME = "foo";
    private static final String SYSTEM_ROLE_CATALOG_NAME = "system_role";
    private static final String USER_NAME = "user";
    private static final String ROLE_NAME = "bar";

    private TransactionManager transactionManager;
    private AccessControl accessControl;
    private Metadata metadata;
    private ExecutorService executor;
    private SqlParser parser;

    @BeforeClass
    public void setUp()
    {
        CatalogManager catalogManager = new CatalogManager();
        transactionManager = createTestTransactionManager(catalogManager);
        accessControl = new AllowAllAccessControl();

        metadata = createTestMetadataManager(transactionManager, new FeaturesConfig());

        MockConnectorFactory mockConnectorFactory = MockConnectorFactory.builder()
                .withListRoleGrants((connectorSession, roles, grantees, limit) -> ImmutableSet.of(new RoleGrant(new TrinoPrincipal(USER, USER_NAME), ROLE_NAME, false)))
                .build();
        Connector testConnector = mockConnectorFactory.create(CATALOG_NAME, ImmutableMap.of(), new TestingConnectorContext());
        CatalogName catalogName = new CatalogName(CATALOG_NAME);
        catalogManager.registerCatalog(new Catalog(
                CATALOG_NAME,
                catalogName,
                "test",
                testConnector,
                SecurityManagement.CONNECTOR,
                createInformationSchemaCatalogName(catalogName),
                testConnector,
                createSystemTablesCatalogName(catalogName),
                testConnector));

        CatalogName systemRoleCatalog = new CatalogName(SYSTEM_ROLE_CATALOG_NAME);
        Connector systemRoleConnector = new Connector()
        {
            @Override
            public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly, boolean autoCommit)
            {
                return new ConnectorTransactionHandle() {};
            }

            @Override
            public ConnectorMetadata getMetadata(ConnectorTransactionHandle transaction)
            {
                return new SystemTablesMetadata(new StaticSystemTablesProvider(ImmutableSet.of()));
            }
        };
        catalogManager.registerCatalog(new Catalog(
                SYSTEM_ROLE_CATALOG_NAME,
                systemRoleCatalog,
                "test",
                systemRoleConnector,
                SecurityManagement.SYSTEM,
                createInformationSchemaCatalogName(systemRoleCatalog),
                systemRoleConnector,
                createSystemTablesCatalogName(systemRoleCatalog),
                systemRoleConnector));

        executor = newCachedThreadPool(daemonThreadsNamed("test-set-role-task-executor-%s"));
        parser = new SqlParser();
    }

    @AfterClass(alwaysRun = true)
    public void tearDown()
    {
        executor.shutdownNow();
        executor = null;
        metadata = null;
        accessControl = null;
        transactionManager = null;
        parser = null;
    }

    @Test
    public void testSetRole()
    {
        assertSetRole("SET ROLE ALL IN " + CATALOG_NAME, ImmutableMap.of(CATALOG_NAME, new SelectedRole(SelectedRole.Type.ALL, Optional.empty())));
        assertSetRole("SET ROLE NONE IN " + CATALOG_NAME, ImmutableMap.of(CATALOG_NAME, new SelectedRole(SelectedRole.Type.NONE, Optional.empty())));
        assertSetRole("SET ROLE " + ROLE_NAME + " IN " + CATALOG_NAME, ImmutableMap.of(CATALOG_NAME, new SelectedRole(SelectedRole.Type.ROLE, Optional.of(ROLE_NAME))));

        assertSetRole("SET ROLE ALL", ImmutableMap.of("system", new SelectedRole(SelectedRole.Type.ALL, Optional.empty())));
        assertSetRole("SET ROLE NONE", ImmutableMap.of("system", new SelectedRole(SelectedRole.Type.NONE, Optional.empty())));
    }

    @Test
    public void testSetRoleInvalidRole()
    {
        assertTrinoExceptionThrownBy(() -> executeSetRole("SET ROLE unknown IN " + CATALOG_NAME))
                .hasErrorCode(ROLE_NOT_FOUND)
                .hasMessage("line 1:1: Role 'unknown' does not exist");
    }

    @Test
    public void testSetRoleInvalidCatalog()
    {
        assertTrinoExceptionThrownBy(() -> executeSetRole("SET ROLE foo IN invalid"))
                .hasErrorCode(CATALOG_NOT_FOUND)
                .hasMessage("line 1:1: Catalog 'invalid' does not exist");
    }

    @Test
    public void testSetCatalogRoleInCatalogWithSystemSecurity()
    {
        assertTrinoExceptionThrownBy(() -> executeSetRole("SET ROLE foo IN " + SYSTEM_ROLE_CATALOG_NAME))
                .hasErrorCode(NOT_SUPPORTED)
                .hasMessage("line 1:1: Catalog '" + SYSTEM_ROLE_CATALOG_NAME + "' does not support role management");
    }

    private void assertSetRole(String statement, Map<String, SelectedRole> expected)
    {
        QueryStateMachine stateMachine = executeSetRole(statement);
        QueryInfo queryInfo = stateMachine.getQueryInfo(Optional.empty());
        assertEquals(queryInfo.getSetRoles(), expected);
    }

    private QueryStateMachine executeSetRole(String statement)
    {
        SetRole setRole = (SetRole) parser.createStatement(statement, new ParsingOptions());
        QueryStateMachine stateMachine = QueryStateMachine.begin(
                statement,
                Optional.empty(),
                testSessionBuilder()
                        .setIdentity(Identity.ofUser(USER_NAME))
                        .build(),
                URI.create("fake://uri"),
                new ResourceGroupId("test"),
                false,
                transactionManager,
                accessControl,
                executor,
                metadata,
                WarningCollector.NOOP,
                Optional.empty());
        new SetRoleTask(metadata, accessControl).execute(setRole, stateMachine, ImmutableList.of(), WarningCollector.NOOP);
        return stateMachine;
    }
}


text:
package com.mysuite.commons.utility;

import com.mysuite.commons.utility.format.DateTimeFormatHelper;
import junit.framework.TestCase;
import org.junit.Test;

import java.util.Date;

/**
 * Created by jianl on 6/04/2017.
 */
public class FormatHelperTest extends TestCase {

    @Test
    public void testGetDateFromDateString() throws Exception {
        String string = "2017-01-01";
        Date date = DateTimeFormatHelper.getDateFromDateString(string);
        assertEquals(string, DateTimeFormatHelper.getDateString(date));
    }

    @Test
    public void testGetTImeFromTimeString() throws Exception {
        String string = "16:16:16";
        Date date = DateTimeFormatHelper.getTimeFromTimeString(string);
        assertEquals("16:16:16", DateTimeFormatHelper.getTimeString(date));
    }

    @Test
    public void testGetDateTImeFromDateTimeString() throws Exception {
        String string = "2017-01-01 16:16:16";
        Date date = DateTimeFormatHelper.getDateFromDateTimeString(string);
        assertEquals("2017-01-01 16:16:16", DateTimeFormatHelper.getDateTimeString(date));
    }

    @Test
    public void testGetDateFromDateTimeString() throws Exception{
        String string = "20170419105609";
        Date date = DateTimeFormatHelper.getDateFromDateTimeSimpleString(string);
        System.out.println(date);
    }

    @Test
    public void testGetTimeStringFromDateTime() throws Exception{
        String string = "20170419105609";
        Date date = DateTimeFormatHelper.getDateFromDateTimeSimpleString(string);
        assertEquals("10:56:09", DateTimeFormatHelper.getTimeString(date));
    }

    @Test
    public void testGetDateStringFromDateTime() throws Exception{
        String string = "20170419105609";
        Date date = DateTimeFormatHelper.getDateFromDateTimeSimpleString(string);
        assertEquals("2017-04-19", DateTimeFormatHelper.getDateString(date));
    }
}


text:
package me.dpohvar.powernbt.completer;

import me.dpohvar.powernbt.utils.NBTQuery;
import me.dpohvar.powernbt.nbt.NBTType;
import org.bukkit.Bukkit;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileReader;
import java.util.*;
import java.util.logging.Level;

public class TypeCompleter {

    private HashMap<String, Object> templates = new HashMap<String, Object>();

    public TypeCompleter(File ymlFolder) {
        try {
            Yaml yaml = new Yaml();
            File file = new File(ymlFolder, "templates.yml");
            if (!file.exists()) return;
            FileReader reader = new FileReader(file);
            Object ymlRoot = yaml.load(reader);
            reader.close();
            if (!(ymlRoot instanceof Map)) throw new RuntimeException("invalid yml format in file " + file);
            for (Map.Entry<String, Object> el : ((Map<String, Object>) ymlRoot).entrySet()) {
                String name = el.getKey();
                String filename = el.getValue().toString();
                file = new File(ymlFolder, filename);
                addToTemplates(name, file);
            }
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.ALL, "can not autocomplete tml "+ymlFolder, e);
        }
    }

    private void addToTemplates(String name, File file) throws Exception {
        FileReader reader = new FileReader(file);
        Object ymlRoot = new Yaml().load(reader);
        reader.close();
        templates.put(name, ymlRoot);
    }

    public List<String> getNextKeys(String key, NBTQuery query) {
        List<String> res = new ArrayList<String>();
        Object x = getObjectByQueue(key, query.getQueue());
        if (x instanceof List) res.add("[]");
        else if (x instanceof Map) {
            for (String s : ((Map<String, Object>) x).keySet()) {
                res.add(s);
            }
        }
        return res;
    }

    public NBTType getType(String key, NBTQuery query) {
        Object x = getObjectByQueue(key, query.getQueue());
        if (x instanceof String) {
            return NBTType.fromString((String) x);
        }
        return null;
    }

    private Object getObjectByQueue(String key, Queue<Object> queue) {
        Object current = templates.get(key);
        if (key != null) while (true) {
            Object t = queue.poll();
            if (current == null) return null;
            if (current instanceof Map && t instanceof String) {
                current = ((Map) current).get(t);
                continue;
            }
            if (current instanceof List && t instanceof Integer) {
                current = ((List) current).get(0);
                continue;
            }
            if (current instanceof String) {
                String s = (String) current;
                if (s.endsWith("[]")) {
                    if (t == null) return s;
                    if (queue.isEmpty()) return s.substring(0, s.length() - 2);
                    return null;
                }
                if (templates.containsKey(current)) {
                    LinkedList<Object> l = new LinkedList<Object>(queue);
                    l.addFirst(t);
                    return getObjectByQueue((String) current, l);
                }
                return queue.isEmpty() ? current : null;
            }
            return current;
        }
        else {
            Object r = null;
            for (String subKey : templates.keySet()) {
                r = getObjectByQueue(subKey, new LinkedList<Object>(queue));
                if (r != null) break;
            }
            return r;
        }
    }

}


text:
import rasterio
import numpy
import os
import unittest

from shapely.geometry import mapping
from shapely.wkt import loads
from winston.stats import summary, Summary

class TestSummaryStats(unittest.TestCase):
    def setUp(self):
        # world.tif looks like this:
        #
        # [   0,   90,  180,  270,  360]
        # [  45,  135,  225,  315,  405]
        # [  90,  180,  270,  360,  450]
        # [ 135,  225,  315,  405,  495]
        # [ 180,  270,  360,  450,  540]
        #
        # Each pixel is 72x36 degrees and the origin is in the center of a
        # pixel.
        path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'data',
            'world.tif',
        )
        self.origin = loads('POINT(0 0)')
        self.src = rasterio.open(path)

    def test_point_wkt(self):
        result = summary(self.src, self.origin.wkt)
        expected = Summary(1, 270, 270, 270, 270, 0)
        self.assertEqual(result, expected)

    def test_point_geometry(self):
        result = summary(self.src, self.origin.wkt)
        expected = Summary(1, 270, 270, 270, 270, 0)
        self.assertEqual(result, expected)

    def test_point_geojson(self):
        result = summary(self.src, mapping(self.origin))
        expected = Summary(1, 270, 270, 270, 270, 0)
        self.assertEqual(result, expected)

    def test_out_of_bounds(self):
        top_left = loads('POINT(-181 91)')
        result = summary(self.src, top_left)
        expected = Summary(None, None, None, None, None, None)
        self.assertEqual(result, expected)

    def test_range(self):
        result = summary(self.src, self.origin, bounds=(0, 1))
        expected = Summary(None, None, None, None, None, None)
        self.assertEqual(result, expected)

    def test_origin_buffer(self):
        # A 45 degree buffer around the origin should be the nine pixels from
        # (1, 1) to (3, 3) in that matrix.

        expected = numpy.array([
            135, 225, 315,
            180, 270, 360,
            225, 315, 405,
        ])

        result = summary(self.src, self.origin.buffer(45), all_touched=True)
        self.assertEqual(result.count, expected.size)
        self.assertEqual(result.sum, expected.sum())
        self.assertEqual(result.mean, expected.mean())
        self.assertEqual(result.min, expected.min())
        self.assertEqual(result.max, expected.max())
        self.assertEqual(result.std, expected.std())