text:
/**
 * Provides the templatized data type of single dimensional Array.
 *
 * @file include/GExL/Core/templates/TArray.hpp
 * @author Ryan Lindeman
 * @date 20140912 - Initial Release
 */
#ifndef   CORE_TARRAY_HPP_INCLUDED
#define   CORE_TARRAY_HPP_INCLUDED

#include <GExL/GExL_types.hpp>
#include <GExL/logger/Log_macros.hpp>
#include <new>

namespace GExL
{
  /**
   * @brief Provides the fundamental Array data structure in a templatized format.
   * @details Provides a robust single dimensional Array implementation for the
   * TYPE specified.
   * Example usage:
   *   GExL::TArray<int> integers(10);
   *   for(GExL::Uint32 i=0; i<integers.size(); ++i)
   *     integers[i] = i;
   *
   *   int rawData[20];
   *   // Create Array wrapper around rawData starting at index 5 with size 10.
   *   // This means index 0 of Array wrapper maps to index 5 of rawData and
   *   // index 9 of Array wrapper maps to index 14 of rawData
   *   GExL::TArray<int> integers(rawData, 5, 10);
   *   for(GExL::Uint32 i=0; i<integers.size(); ++i)
   *     integers[i] = i;
   *
   *   for(GExL::Uint32 i=0; i<20; ++i)
   *     printf("[%u] = %d\n", i, rawData[i]);
   */
  template <class TYPE>
  class TArray
  {
  public:
    /** Default constructor creates a TArray of 0 elements in size
     */
    TArray();

    /** Alternative constructor creates a TArray of size elements in size
     * @param[in] size of array to create
     */
    explicit TArray(Uint32 size);

    /** Alternative constructor creates a reference array to another data
     * source of size and at offset specified.
     * @param[in] data pointer to original source
     * @param[in] size of reference array
     * @param[in] offset into reference array that maps to index 0 (default 0)
     */
    TArray(TYPE* data, Uint32 size, Uint32 offset = 0);

    /** Destructor for array will delete the array if not a reference array.
     */
    virtual ~TArray();

    /** Copy constructor for array
     * @param[in] copy to construct new array from
     */
    TArray(TArray const& copy);

    /** Assignment operator
     * @param[in] right side of assignment operator
     * @return TArray address reference to left side of assignment operator
     */
    TArray& operator=(TArray const& right);

    /** Retrieve reference to internal raw data array. Typically used to create
     * sub reference arrays of original array (see @ref TArray2D or @ref TArray3D).
     * @return TYPE const*
     *   pointer to internal raw data array
     */
    TYPE* data() const;

    /** Retrieve the size of the array. Typically used when iterating over the array
     * bounds.
     * @return Uint32
     *   size of array.
     */
    Uint32 size() const;

    /** Retrieve the offset of the array. Typically used when creating a reference
     * array from another reference array (see @ref TArray2D)
     * @return Uint32
     *   offset of reference array
     */
    Uint32 offset() const;

    /** Retrieve the reference to the position specified in the array with bounds
     * checking. If position exceeds the size of the array then the last element in
     * the array will be returned.
     * @param[in] position in array to return reference to
     * @return TYPE&
     *   reference to the element at position specified.
     */
    TYPE& indexOf(Uint32 position);

    /** Retrieve a constant reference to the position specified in the array with
     * bounds checking. If position exceeds the size of the array then the last
     * element in the array will be returned.
     * @param[in] position in array to return reference to
     * @return TYPE const&
     *   constant reference to the element at position specified.
     */
    TYPE const& operator[] (Uint32 position) const;

    /** Retrieve the reference to the position specified in the array with bounds
     * checking. If position exceeds the size of the array then the last element in
     * the array will be returned.
     * @param[in] position in array to return reference to
     * @return TYPE&
     *   reference to the element at position specified.
     */
    TYPE& operator[] (Uint32 position);

  protected:
    /** Single dimensional array of elements
     */
    TYPE* mData;

    /** Size of single dimensional array of elements
     */
    Uint32 mSize;

    /** Offset into data for position 0. Often used for reference arrays.
     */
    Uint32 mOffset;

    /** Indicates this is a reference array and should not be deleted on destruction
     */
    bool mReference;

  private:
    /** Helper function used by assignment operator to swap between a copy of
     * the array and this array.
     * @param[inout] reference to copy to swap with this array
     */
    void transfer(TArray<TYPE>& copy);

  }; // class TArray

  /////////////////////////////////////////////////////////////////////////////
  // Template implementation details
  /////////////////////////////////////////////////////////////////////////////
  template <class TYPE>
  TArray<TYPE>::TArray() :
    mData(new (std::nothrow) TYPE[0]),
    mSize(0U),
    mOffset(0U),
    mReference(false)
  {
  }

  template <class TYPE>
  TArray<TYPE>::TArray(Uint32 size) :
    mData(new (std::nothrow) TYPE[size]),
    mSize(size),
    mOffset(0U),
    mReference(false)
  {
  }

  template <class TYPE>
  TArray<TYPE>::TArray(TYPE* data, Uint32 size, Uint32 offset) :
    mData(data),
    mSize(size),
    mOffset(offset),
    mReference(true)
  {
  }

  template <class TYPE>
  TArray<TYPE>::~TArray()
  {
    if (!mReference)
    {
      delete[] mData;
    }
    // Don't keep data address around
    mData = 0;
    mSize = 0U;
  }

  template <class TYPE>
  TArray<TYPE>::TArray(TArray<TYPE> const& copy) :
    mData(new (std::nothrow) TYPE[copy.mSize]),
    mSize(copy.mSize),
    mOffset(copy.mOffset),
    mReference(false)
  {
    for (Uint32 i = 0; i < mSize; ++i)
    {
      mData[i] = copy.mData[i];
    }
  }

  template <class TYPE>
  TArray<TYPE>& TArray<TYPE>::operator=(TArray<TYPE> const& right)
  {
    // If not self reference then copy new array into existing array
    if (this != &right)
    {
      // Transfer copy of array to this array
      transfer(TArray<TYPE>(right));
    }
    return *this;
  }

  template <class TYPE>
  TYPE* TArray<TYPE>::data() const
  {
    return mData;
  }

  template <class TYPE>
  Uint32 TArray<TYPE>::size() const
  {
    return mSize;
  }

  template <class TYPE>
  Uint32 TArray<TYPE>::offset() const
  {
    return mOffset;
  }

  template <class TYPE>
  TYPE const& TArray<TYPE>::operator[](Uint32 position) const
  {
    return indexOf(position);
  }

  template <class TYPE>
  TYPE& TArray<TYPE>::indexOf(Uint32 position)
  {
    if (position < mSize)
    {
      return mData[position + mOffset];
    }
    else if (mSize > 0)
    {
      /*WLOG() << "TArray:indexOf(" << position
        << ") position provided exceeds size of "
        << mSize << std::endl;
      */
      return mData[(mSize - 1) + mOffset];
    }
    else
    {/*
      ELOG() << "TArray:indexOf(" << position
        << ") array is empty (size is 0)" << std::endl;
       */
      return mData[mOffset];
    }
  }

  template <class TYPE>
  TYPE& TArray<TYPE>::operator[](Uint32 position)
  {
    return indexOf(position);
  }

  template <class TYPE>
  void TArray<TYPE>::transfer(TArray<TYPE>& copy)
  {
    using std::swap;
    swap(mData, copy.mData);
    swap(mSize, copy.mSize);
    swap(mOffset, copy.mOffset);
    swap(mReference, copy.mReference);
  }
} // namespace GExL

#endif // CORE_TARRAY_HPP_INCLUDED

/**
 * @class GExL::TArray
 * @ingroup Core
 * The TArray template class is the template used to create an array of the
 * type provided.
 *
 * Copyright (c) 2014 Ryan Lindeman
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */


text:
letsencrypt container (see [docker-compose live deployment](https://github.com/researchstudio-sat/webofneeds/blob/master/webofneeds/won-docker/deploy/live_satvm01/docker-compose.yml)) that helps renew the matchat.org (including match.org and node.matchat.org) certificate.
It is used by the nginx (external matchat representation of owner) and the wonnode.
Certificate renewal happens automatically via a cronjob.

# Certificate Renewal

To renew the certificate note the following things:

- all involved containers (letsencrypt, nginx, wonnode) are configured to mount the right folders
- the certificate folder on the host is configured to be `$base_folder/letsencrypt/certs/live/matchat.org"`
- nginx must be running so that the acme challenge can be executed (for a new creation of the certificate you can start nginx with the nginx-http-only.conf which doesn't need a certificate file for startup)
- execute `docker start livesatvm01_letsencrypt_1` for certificate renewal on host satvm01 (this should happen once a day via cronjob)
- to manually renew the certificates, execute `docker exec livesatvm01_letsencrypt_1 bash /usr/local/bin/certificate-request-and-renew.sh`
- this script can be changed for testing e.g. by adding parameters like `--dry-run or --test-cert` to the certbot commands
- this should renew the letsencrypt certificate in `$base_folder/letsencrypt/certs/live/matchat.org` on the host
- check if the .pem files and the java key store files (.jks and .pfx) in the same folder have also been updated. These are symlinks into `../../archive/<domainname>/`, you might want to follow those symlinks and check that they are pointing to new files
- delete all (trust store) files in directory `$base_folder/won-client-certs/` on all hosts (satvm01)
- redeploy all live containers (with jenkins job)
- check if everything works (HTTPS, websocket and JMS communication)

# Troubleshooting

Updating the certificates sometimes fails. If things have stopped working for you after a certificate renewal, this [troubleshooting tip](/documentation/building.md#exception-in-owner-webapp-log-pkix-path-building-failed) may help.

redpajama_set_name: RedPajamaGithub


text:
<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

            new Sonata\CoreBundle\SonataCoreBundle(),
            new Sonata\IntlBundle\SonataIntlBundle(),
            new Sonata\BlockBundle\SonataBlockBundle(),
            new Sonata\AdminBundle\SonataAdminBundle(),
            new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
            new Sonata\FormatterBundle\SonataFormatterBundle(),
            new Sonata\MediaBundle\SonataMediaBundle(),
            new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
            new Sonata\ClassificationBundle\SonataClassificationBundle(),

            new Sonata\SeoBundle\SonataSeoBundle(),
            new Sonata\CacheBundle\SonataCacheBundle(),

            new Sonata\NotificationBundle\SonataNotificationBundle(),
            new Sonata\PageBundle\SonataPageBundle(),

            new SimpleThings\EntityAudit\SimpleThingsEntityAuditBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),

            new JMS\SerializerBundle\JMSSerializerBundle($this),
            new JMS\AopBundle\JMSAopBundle(),
            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            new Bmatzner\FontAwesomeBundle\BmatznerFontAwesomeBundle(),
            new Liip\ImagineBundle\LiipImagineBundle(),
            new Cocur\Slugify\Bridge\Symfony\CocurSlugifyBundle(),

            new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(),
            new Ivory\CKEditorBundle\IvoryCKEditorBundle(),

            new Snc\RedisBundle\SncRedisBundle(),
            new \Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle(),
            new Eko\FeedBundle\EkoFeedBundle(),
            new FOS\HttpCacheBundle\FOSHttpCacheBundle(),

            new Nelmio\SecurityBundle\NelmioSecurityBundle(),
            new Liuggio\StatsDClientBundle\LiuggioStatsDClientBundle(),

            new Webfactory\Bundle\ExceptionsBundle\WebfactoryExceptionsBundle(),
            new SunCat\MobileDetectBundle\MobileDetectBundle(),
            new Socloz\MonitoringBundle\SoclozMonitoringBundle(),
            new FOS\ElasticaBundle\FOSElasticaBundle(),
            new Happyr\CloudFlareBundle\HappyrCloudFlareBundle(),
            new Leezy\PheanstalkBundle\LeezyPheanstalkBundle(),

            new FOS\RestBundle\FOSRestBundle(),

            new Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(),
            // new Symfony\Cmf\Bundle\CoreBundle\CmfCoreBundle(),
            // new Symfony\Cmf\Bundle\MenuBundle\CmfMenuBundle(),
            // new Symfony\Cmf\Bundle\ContentBundle\CmfContentBundle(),
            // new Symfony\Cmf\Bundle\TreeBrowserBundle\CmfTreeBrowserBundle(),
            // new Symfony\Cmf\Bundle\BlockBundle\CmfBlockBundle(),
            new Application\Sonata\NotificationBundle\ApplicationSonataNotificationBundle(),
            new Application\Sonata\PageBundle\ApplicationSonataPageBundle(),
            new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
            new Application\Sonata\MediaBundle\ApplicationSonataMediaBundle(),
            new Application\Sonata\ClassificationBundle\ApplicationSonataClassificationBundle(),
            new Aldor\InftechBundle\AldorInftechBundle(),
            new Aldor\BlogBundle\AldorBlogBundle(),
            new Aldor\GalleryBundle\AldorGalleryBundle(),
            new Aldor\PortfolioBundle\AldorPortfolioBundle(),
            new Aldor\BackendBundle\AldorBackendBundle(),
            new Aldor\ApiBundle\AldorApiBundle(),
        );

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

            if (in_array($this->getEnvironment(), array('dev')))
                 $bundles[] = new JMS\DebuggingBundle\JMSDebuggingBundle($this);

        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
    protected function getContainerBaseClass()
    {
        if (in_array($this->getEnvironment(), array('dev'))) {
                return '\JMS\DebuggingBundle\DependencyInjection\TraceableContainer';
            }

        return parent::getContainerBaseClass();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace mvlSite.CompressionMiddleware
{
    internal static class EnumerableExtension
    {
        public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var element in source)
                action(element);
            return source;
        }

        public static string ToStringExt<T>(this IEnumerable<T> enumerable, Func<T, string> value, string delimiter = ", ")
        {
            var sb = new StringBuilder();
            foreach (var item in enumerable)
            {
                sb.Append(value(item));
                sb.Append(delimiter);
            }
            return sb.ToString().TrimEnd(delimiter.ToCharArray());
        }

        public static string ToStringExt<T>(this IEnumerable<T> enumerable, string delimiter = ", ")
        {
            return ToStringExt(enumerable, m => m.ToString(), delimiter);
        }
    }
}


text:
With version 2 of `bpk-component-banner-alert` we overhauled and simplified the external interface of the component by splitting it in several components for each use case. In version 2 there are 3 components:

+ `BpkBannerAlert`
+ `BpkBannerAlertDismissable`
+ `BpkBannerAlertExpandable`

`BpkBannerAlert` is the default version that does not feature the ability to dismiss or expand. `BpkBannerAlertDismissable` is the variant that can be dismissed by the user. `BpkBannerAlertExpandable` is a variant that can show more detailed content by expanding an initially hidden section of content.

## Migrating

Let us walk through migrating the 3 different cases.

### The default case

No `dismissable` prop and no children.

**V1:**

```javascript
import BpkBannerAlert, { ALERT_TYPES } from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlert type={ALERT_TYPES.SUCCESS} message="Everything went well" />
);
```

This migration is really simple as you have to make no changes unless you are using `ariaLive` which has been removed.

**V2:**

```javascript
import BpkBannerAlert, { ALERT_TYPES } from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlert type={ALERT_TYPES.SUCCESS} message="Everything went well" />
);
```

## The dismissable case

In the dismissable case the component needs to be changed to `BpkBannerAlertDismissable`. Also verify that you are not passing props that `BpkBannerAlertDismissable` does not use.

**V1:**

```javascript
import BpkBannerAlert, { ALERT_TYPES } from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlert
    dismissable
    dismissButtonLabel="Dismiss"
    type={ALERT_TYPES.SUCCESS}
    message="Everything went well"
    onDismiss={() => undefined}
  />
);
```

**V2:**

```javascript
import {
  ALERT_TYPES,
  BpkBannerAlertDismissable
} from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlertDismissable
    dismissButtonLabel="Dismiss"
    type={ALERT_TYPES.SUCCESS}
    message="Everything went well"
    onDismiss={() => undefined}
  />
);
```

## The expandable case

In version 1 the expandable behaviour was enabled if the component had any children. With version 2 there is now a dedicated component, `BpkBannerAlertExpandable`, for this behaviour.

**V1:**

```javascript
import BpkBannerAlert, { ALERT_TYPES } from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlert
    type={ALERT_TYPES.SUCCESS}
    message="Everything went horribly wrong"
    toggleButtonLabel="Toggle details"
    onExpandToggle={() => undefined}
  >
    An even longer more detailed message
  </BpkBannerAlert>
);
```

**V2:**

```javascript
import { ALERT_TYPES, BpkBannerAlertExpandable } from "bpk-component-banner-alert";

const render = () => (
  <BpkBannerAlertExpandable
    type={ALERT_TYPES.SUCCESS}
    message="Everything went horribly wrong"
    toggleButtonLabel="Toggle details"
    onExpandToggle={() => undefined}
  >
    An even longer more detailed message
  </BpkBannerAlertExpandable>
);
```

## `withBannerAlertState`

`withBannerAlertState` continues to work with both `BpkBannerAlertDismissable` and `BpkBannerAlertExpandable` as before. However when using `hideAfter` `onDimiss` is no longer called when the banner alert is removed, instead a new prop `onHide` has been introduced for this purpose. `hideAfter` is no longer a valid option for expandable banner alerts.


text:
<?php

/* AppBundle::Default/header.html.twig */
class __TwigTemplate_47a465bbf0b3050172f5c167e965a1b53af4ee3d2733be747779b36745d8f219 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_06629905fff625f79f2ce542fcf7014de72b9fc839da80bee5d33ce34e994bea = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_06629905fff625f79f2ce542fcf7014de72b9fc839da80bee5d33ce34e994bea->enter($__internal_06629905fff625f79f2ce542fcf7014de72b9fc839da80bee5d33ce34e994bea_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "AppBundle::Default/header.html.twig"));

        $__internal_01ca1b2fb1772c7c1ef681ed45000eb5634b94673d97d76c66def6f7a24c003a = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_01ca1b2fb1772c7c1ef681ed45000eb5634b94673d97d76c66def6f7a24c003a->enter($__internal_01ca1b2fb1772c7c1ef681ed45000eb5634b94673d97d76c66def6f7a24c003a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "AppBundle::Default/header.html.twig"));

        // line 1
        echo "

        ";
        // line 5
        echo "            ";
        // line 6
        echo "                ";
        // line 7
        echo "                ";
        // line 8
        echo "                ";
        // line 9
        echo "                ";
        // line 10
        echo "            ";
        // line 11
        echo "            ";
        // line 12
        echo "        ";
        // line 13
        echo "

env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getUrl("accueilpage");
        echo "\">Accueil

env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getUrl("predictionpage");
        echo "\">Prédiction

env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getUrl("horoscopepage");
        echo "\">Horoscope

                        ";
        // line 21
        if ($this->env->getExtension('Symfony\Bridge\Twig\Extension\SecurityExtension')->isGranted("IS_AUTHENTICATED_REMEMBERED")) {
            // line 22
            echo "                            ";
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("layout.logged_in_as", array("%username%" => $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "username", array())), "FOSUserBundle"), "html", null, true);
            echo "
                        ";
        } else {
            // line 24
            echo "                            Mon compte
                        ";
        }
        // line 26
        echo "

                        ";
        // line 29
        if ($this->env->getExtension('Symfony\Bridge\Twig\Extension\SecurityExtension')->isGranted("IS_AUTHENTICATED_REMEMBERED")) {
            // line 30
            echo "
                                ";
            // line 31
            if ($this->env->getExtension('Symfony\Bridge\Twig\Extension\SecurityExtension')->isGranted("ROLE_ADMIN")) {
                // line 32
                echo "

                                        env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("admin");
                echo "\" target=\"_blank\"> Admin

                                ";
            }
            // line 36
            echo "

 env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("fos_user_profile_show");
            echo "\"> Mon profil

 env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("fos_user_security_logout");
            echo "\">
                                ";
            // line 39
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("layout.logout", array(), "FOSUserBundle"), "html", null, true);
            echo "

                        ";
        } else {
            // line 43
            echo "
env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("fos_user_security_login");
            echo "\">";
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("layout.login", array(), "FOSUserBundle"), "html", null, true);
            echo "

env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("fos_user_registration_register");
            echo "\">";
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("layout.register", array(), "FOSUserBundle"), "html", null, true);
            echo "

                        ";
        }
        // line 46
        echo "

";

        $__internal_06629905fff625f79f2ce542fcf7014de72b9fc839da80bee5d33ce34e994bea->leave($__internal_06629905fff625f79f2ce542fcf7014de72b9fc839da80bee5d33ce34e994bea_prof);

        $__internal_01ca1b2fb1772c7c1ef681ed45000eb5634b94673d97d76c66def6f7a24c003a->leave($__internal_01ca1b2fb1772c7c1ef681ed45000eb5634b94673d97d76c66def6f7a24c003a_prof);

    }

    public function getTemplateName()
    {
        return "AppBundle::Default/header.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  130 => 46,  123 => 44,  116 => 43,  109 => 39,  105 => 38,  101 => 37,  98 => 36,  92 => 33,  89 => 32,  87 => 31,  84 => 30,  82 => 29,  77 => 26,  73 => 24,  67 => 22,  65 => 21,  59 => 18,  55 => 17,  51 => 16,  46 => 13,  44 => 12,  42 => 11,  40 => 10,  38 => 9,  36 => 8,  34 => 7,  32 => 6,  30 => 5,  25 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("

        {#
#}
            {#<button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">#}
                {#Toggle navigation#}
                {##}
                {##}
                {##}
            {#</button>#}
            {#Brand#}
        {#
#}

Accueil

Prédiction

Horoscope

                        {% if is_granted(\"IS_AUTHENTICATED_REMEMBERED\") %}
                            {{ 'layout.logged_in_as'|trans({'%username%': app.user.username}, 'FOSUserBundle') }}
                        {% else %}
                            Mon compte
                        {% endif %}

                        {% if is_granted(\"IS_AUTHENTICATED_REMEMBERED\") %}

                                {% if is_granted(\"ROLE_ADMIN\") %}

                                         Admin

                                {% endif %}

  Mon profil

                                {{ 'layout.logout'|trans({}, 'FOSUserBundle') }}

                        {% else %}

{{ 'layout.login'|trans({}, 'FOSUserBundle') }}

{{ 'layout.register'|trans({}, 'FOSUserBundle') }}

                        {% endif %}

", "AppBundle::Default/header.html.twig", "C:\\wamp\\www\\ecv\\voyance_v2\\src\\AppBundle/Resources/views/Default/header.html.twig");
    }
}


text:
<?php

namespace Doctrine\ORM\Cache;

/**
 * Collection cache entry
 */
class CollectionCacheEntry implements CacheEntry
{
    /**
     * READ-ONLY: Public only for performance reasons, it should be considered immutable.
     *
     * @var CacheKey[] The list of entity identifiers hold by the collection
     */
    public $identifiers;

    /**
     * @param CacheKey[] $identifiers List of entity identifiers hold by the collection
     */
    public function __construct(array $identifiers)
    {
        $this->identifiers = $identifiers;
    }

    /**
     * Creates a new CollectionCacheEntry
     *
     * This method allows for Doctrine\Common\Cache\PhpFileCache compatibility
     *
     * @param array<string, mixed> $values array containing property values
     *
     * @return CollectionCacheEntry
     */
    public static function __set_state(array $values)
    {
        return new self($values['identifiers']);
    }
}


text:
#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/print.h>

#include <freerdp/primitives.h>
#include <freerdp/log.h>
#include <freerdp/codec/bitmap.h>
#include <freerdp/codec/planar.h>

#define TAG FREERDP_TAG("codec")

static INLINE BOOL freerdp_bitmap_planar_compress_plane_rle(const BYTE* plane, UINT32 width,
                                                            UINT32 height, BYTE* outPlane,
                                                            UINT32* dstSize);
static INLINE BYTE* freerdp_bitmap_planar_delta_encode_plane(const BYTE* inPlane, UINT32 width,
                                                             UINT32 height, BYTE* outPlane);

static INLINE INT32 planar_skip_plane_rle(const BYTE* pSrcData, UINT32 SrcSize, UINT32 nWidth,
                                          UINT32 nHeight)
{
	UINT32 x, y;
	BYTE controlByte;
	const BYTE* pRLE = pSrcData;
	const BYTE* pEnd = &pSrcData[SrcSize];

	for (y = 0; y < nHeight; y++)
	{
		for (x = 0; x < nWidth;)
		{
			int cRawBytes;
			int nRunLength;

			if (pRLE >= pEnd)
				return -1;

			controlByte = *pRLE++;
			nRunLength = PLANAR_CONTROL_BYTE_RUN_LENGTH(controlByte);
			cRawBytes = PLANAR_CONTROL_BYTE_RAW_BYTES(controlByte);

			if (nRunLength == 1)
			{
				nRunLength = cRawBytes + 16;
				cRawBytes = 0;
			}
			else if (nRunLength == 2)
			{
				nRunLength = cRawBytes + 32;
				cRawBytes = 0;
			}

			pRLE += cRawBytes;
			x += cRawBytes;
			x += nRunLength;

			if (x > nWidth)
				return -1;

			if (pRLE > pEnd)
				return -1;
		}
	}

	return (INT32)(pRLE - pSrcData);
}

static INLINE INT32 planar_decompress_plane_rle(const BYTE* pSrcData, UINT32 SrcSize,
                                                BYTE* pDstData, INT32 nDstStep, UINT32 nXDst,
                                                UINT32 nYDst, UINT32 nWidth, UINT32 nHeight,
                                                UINT32 nChannel, BOOL vFlip)
{
	INT32 x, y;
	UINT32 pixel;
	UINT32 cRawBytes;
	UINT32 nRunLength;
	INT32 deltaValue;
	INT32 beg, end, inc;
	BYTE controlByte;
	BYTE* currentScanline;
	BYTE* previousScanline;
	const BYTE* srcp = pSrcData;

	if ((nHeight > INT32_MAX) || (nWidth > INT32_MAX) || (nDstStep > INT32_MAX))
		return -1;

	previousScanline = NULL;

	if (vFlip)
	{
		beg = (INT32)nHeight - 1;
		end = -1;
		inc = -1;
	}
	else
	{
		beg = 0;
		end = (INT32)nHeight;
		inc = 1;
	}

	for (y = beg; y != end; y += inc)
	{
		BYTE* dstp = &pDstData[((nYDst + y) * (INT32)nDstStep) + (nXDst * 4) + nChannel];
		pixel = 0;
		currentScanline = dstp;

		for (x = 0; x < (INT32)nWidth;)
		{
			controlByte = *srcp;
			srcp++;

			if ((srcp - pSrcData) > SrcSize)
			{
				WLog_ERR(TAG, "error reading input buffer");
				return -1;
			}

			nRunLength = PLANAR_CONTROL_BYTE_RUN_LENGTH(controlByte);
			cRawBytes = PLANAR_CONTROL_BYTE_RAW_BYTES(controlByte);

			if (nRunLength == 1)
			{
				nRunLength = cRawBytes + 16;
				cRawBytes = 0;
			}
			else if (nRunLength == 2)
			{
				nRunLength = cRawBytes + 32;
				cRawBytes = 0;
			}

			if (((dstp + (cRawBytes + nRunLength)) - currentScanline) > nWidth * 4)
			{
				WLog_ERR(TAG, "too many pixels in scanline");
				return -1;
			}

			if (!previousScanline)
			{
				/* first scanline, absolute values */
				while (cRawBytes > 0)
				{
					pixel = *srcp;
					srcp++;
					*dstp = pixel;
					dstp += 4;
					x++;
					cRawBytes--;
				}

				while (nRunLength > 0)
				{
					*dstp = pixel;
					dstp += 4;
					x++;
					nRunLength--;
				}
			}
			else
			{
				/* delta values relative to previous scanline */
				while (cRawBytes > 0)
				{
					deltaValue = *srcp;
					srcp++;

					if (deltaValue & 1)
					{
						deltaValue = deltaValue >> 1;
						deltaValue = deltaValue + 1;
						pixel = -deltaValue;
					}
					else
					{
						deltaValue = deltaValue >> 1;
						pixel = deltaValue;
					}

					deltaValue = previousScanline[x * 4] + pixel;
					*dstp = deltaValue;
					dstp += 4;
					x++;
					cRawBytes--;
				}

				while (nRunLength > 0)
				{
					deltaValue = previousScanline[x * 4] + pixel;
					*dstp = deltaValue;
					dstp += 4;
					x++;
					nRunLength--;
				}
			}
		}

		previousScanline = currentScanline;
	}

	return (INT32)(srcp - pSrcData);
}

static INLINE INT32 planar_set_plane(BYTE bValue, BYTE* pDstData, INT32 nDstStep, UINT32 nXDst,
                                     UINT32 nYDst, UINT32 nWidth, UINT32 nHeight, UINT32 nChannel,
                                     BOOL vFlip)
{
	INT32 x, y;
	INT32 beg, end, inc;

	if ((nHeight > INT32_MAX) || (nWidth > INT32_MAX) || (nDstStep > INT32_MAX))
		return -1;

	if (vFlip)
	{
		beg = (INT32)nHeight - 1;
		end = -1;
		inc = -1;
	}
	else
	{
		beg = 0;
		end = (INT32)nHeight;
		inc = 1;
	}

	for (y = beg; y != end; y += inc)
	{
		BYTE* dstp = &pDstData[((nYDst + y) * (INT32)nDstStep) + (nXDst * 4) + nChannel];

		for (x = 0; x < (INT32)nWidth; ++x)
		{
			*dstp = bValue;
			dstp += 4;
		}
	}

	return 0;
}

static INLINE BOOL writeLine(BYTE** ppRgba, UINT32 DstFormat, UINT32 width, const BYTE** ppR,
                             const BYTE** ppG, const BYTE** ppB, const BYTE** ppA)
{
	UINT32 x;

	if (!ppRgba || !ppR || !ppG || !ppB)
		return FALSE;

	switch (DstFormat)
	{
	case PIXEL_FORMAT_BGRA32:
		for (x = 0; x < width; x++)
		{
			*(*ppRgba)++ = *(*ppB)++;
			*(*ppRgba)++ = *(*ppG)++;
			*(*ppRgba)++ = *(*ppR)++;
			*(*ppRgba)++ = *(*ppA)++;
		}

		return TRUE;

	case PIXEL_FORMAT_BGRX32:
		for (x = 0; x < width; x++)
		{
			*(*ppRgba)++ = *(*ppB)++;
			*(*ppRgba)++ = *(*ppG)++;
			*(*ppRgba)++ = *(*ppR)++;
			*(*ppRgba)++ = 0xFF;
		}

		return TRUE;

	default:
		if (ppA)
		{
			for (x = 0; x < width; x++)
			{
				BYTE alpha = *(*ppA)++;
				UINT32 color = FreeRDPGetColor(DstFormat, *(*ppR)++, *(*ppG)++, *(*ppB)++, alpha);
				WriteColor(*ppRgba, DstFormat, color);
				*ppRgba += GetBytesPerPixel(DstFormat);
			}
		}
		else
		{
			const BYTE alpha = 0xFF;

			for (x = 0; x < width; x++)
			{
				UINT32 color = FreeRDPGetColor(DstFormat, *(*ppR)++, *(*ppG)++, *(*ppB)++, alpha);
				WriteColor(*ppRgba, DstFormat, color);
				*ppRgba += GetBytesPerPixel(DstFormat);
			}
		}

		return TRUE;
	}
}

static INLINE BOOL planar_decompress_planes_raw(const BYTE* pSrcData[4], BYTE* pDstData,
                                                UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDst,
                                                UINT32 nYDst, UINT32 nWidth, UINT32 nHeight,
                                                BOOL vFlip)
{
	INT32 y;
	INT32 beg, end, inc;
	const BYTE* pR = pSrcData[0];
	const BYTE* pG = pSrcData[1];
	const BYTE* pB = pSrcData[2];
	const BYTE* pA = pSrcData[3];

	if (vFlip)
	{
		beg = nHeight - 1;
		end = -1;
		inc = -1;
	}
	else
	{
		beg = 0;
		end = nHeight;
		inc = 1;
	}

	for (y = beg; y != end; y += inc)
	{
		BYTE* pRGB = &pDstData[((nYDst + y) * nDstStep) + (nXDst * GetBytesPerPixel(DstFormat))];

		if (!writeLine(&pRGB, DstFormat, nWidth, &pR, &pG, &pB, &pA))
			return FALSE;
	}

	return TRUE;
}

BOOL planar_decompress(BITMAP_PLANAR_CONTEXT* planar, const BYTE* pSrcData, UINT32 SrcSize,
                       UINT32 nSrcWidth, UINT32 nSrcHeight, BYTE* pDstData, UINT32 DstFormat,
                       UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst, UINT32 nDstWidth,
                       UINT32 nDstHeight, BOOL vFlip)
{
	BOOL cs;
	BOOL rle;
	UINT32 cll;
	BOOL alpha;
	BOOL useAlpha = FALSE;
	INT32 status;
	const BYTE* srcp;
	UINT32 subSize;
	UINT32 subWidth;
	UINT32 subHeight;
	UINT32 planeSize;
	INT32 rleSizes[4] = { 0, 0, 0, 0 };
	UINT32 rawSizes[4];
	UINT32 rawWidths[4];
	UINT32 rawHeights[4];
	BYTE FormatHeader;
	const BYTE* planes[4] = { 0 };
	const UINT32 w = MIN(nSrcWidth, nDstWidth);
	const UINT32 h = MIN(nSrcHeight, nDstHeight);
	const primitives_t* prims = primitives_get();

	if (nDstStep <= 0)
		nDstStep = nDstWidth * GetBytesPerPixel(DstFormat);

	srcp = pSrcData;

	if (!pDstData)
	{
		WLog_ERR(TAG, "Invalid argument pDstData=NULL");
		return FALSE;
	}

	FormatHeader = *srcp++;
	cll = (FormatHeader & PLANAR_FORMAT_HEADER_CLL_MASK);
	cs = (FormatHeader & PLANAR_FORMAT_HEADER_CS) ? TRUE : FALSE;
	rle = (FormatHeader & PLANAR_FORMAT_HEADER_RLE) ? TRUE : FALSE;
	alpha = (FormatHeader & PLANAR_FORMAT_HEADER_NA) ? FALSE : TRUE;

	if (alpha)
		useAlpha = ColorHasAlpha(DstFormat);

	// WLog_INFO(TAG, "CLL: %"PRIu32" CS: %"PRIu8" RLE: %"PRIu8" ALPHA: %"PRIu8"", cll, cs, rle,
	// alpha);

	if (!cll && cs)
		return FALSE; /* Chroma subsampling requires YCoCg */

	subWidth = (nSrcWidth / 2) + (nSrcWidth % 2);
	subHeight = (nSrcHeight / 2) + (nSrcHeight % 2);
	planeSize = nSrcWidth * nSrcHeight;
	subSize = subWidth * subHeight;

	if (!cs)
	{
		rawSizes[0] = planeSize; /* LumaOrRedPlane */
		rawWidths[0] = nSrcWidth;
		rawHeights[0] = nSrcHeight;
		rawSizes[1] = planeSize; /* OrangeChromaOrGreenPlane */
		rawWidths[1] = nSrcWidth;
		rawHeights[1] = nSrcHeight;
		rawSizes[2] = planeSize; /* GreenChromaOrBluePlane */
		rawWidths[2] = nSrcWidth;
		rawHeights[2] = nSrcHeight;
		rawSizes[3] = planeSize; /* AlphaPlane */
		rawWidths[3] = nSrcWidth;
		rawHeights[3] = nSrcHeight;
	}
	else /* Chroma Subsampling */
	{
		rawSizes[0] = planeSize; /* LumaOrRedPlane */
		rawWidths[0] = nSrcWidth;
		rawHeights[0] = nSrcHeight;
		rawSizes[1] = subSize; /* OrangeChromaOrGreenPlane */
		rawWidths[1] = subWidth;
		rawHeights[1] = subHeight;
		rawSizes[2] = subSize; /* GreenChromaOrBluePlane */
		rawWidths[2] = subWidth;
		rawHeights[2] = subHeight;
		rawSizes[3] = planeSize; /* AlphaPlane */
		rawWidths[3] = nSrcWidth;
		rawHeights[3] = nSrcHeight;
	}

	if (!rle) /* RAW */
	{
		if (alpha)
		{
			if ((SrcSize - (srcp - pSrcData)) < (planeSize * 4))
				return FALSE;

			planes[3] = srcp;                    /* AlphaPlane */
			planes[0] = planes[3] + rawSizes[3]; /* LumaOrRedPlane */
			planes[1] = planes[0] + rawSizes[0]; /* OrangeChromaOrGreenPlane */
			planes[2] = planes[1] + rawSizes[1]; /* GreenChromaOrBluePlane */

			if ((planes[2] + rawSizes[2]) > &pSrcData[SrcSize])
				return FALSE;
		}
		else
		{
			if ((SrcSize - (srcp - pSrcData)) < (planeSize * 3))
				return FALSE;

			planes[0] = srcp;                    /* LumaOrRedPlane */
			planes[1] = planes[0] + rawSizes[0]; /* OrangeChromaOrGreenPlane */
			planes[2] = planes[1] + rawSizes[1]; /* GreenChromaOrBluePlane */

			if ((planes[2] + rawSizes[2]) > &pSrcData[SrcSize])
				return FALSE;
		}
	}
	else /* RLE */
	{
		if (alpha)
		{
			planes[3] = srcp;
			rleSizes[3] = planar_skip_plane_rle(planes[3], SrcSize - (planes[3] - pSrcData),
			                                    rawWidths[3], rawHeights[3]); /* AlphaPlane */

			if (rleSizes[3] < 0)
				return FALSE;

			planes[0] = planes[3] + rleSizes[3];
		}
		else
			planes[0] = srcp;

		rleSizes[0] = planar_skip_plane_rle(planes[0], SrcSize - (planes[0] - pSrcData),
		                                    rawWidths[0], rawHeights[0]); /* RedPlane */

		if (rleSizes[0] < 0)
			return FALSE;

		planes[1] = planes[0] + rleSizes[0];
		rleSizes[1] = planar_skip_plane_rle(planes[1], SrcSize - (planes[1] - pSrcData),
		                                    rawWidths[1], rawHeights[1]); /* GreenPlane */

		if (rleSizes[1] < 1)
			return FALSE;

		planes[2] = planes[1] + rleSizes[1];
		rleSizes[2] = planar_skip_plane_rle(planes[2], SrcSize - (planes[2] - pSrcData),
		                                    rawWidths[2], rawHeights[2]); /* BluePlane */

		if (rleSizes[2] < 1)
			return FALSE;
	}

	if (!cll) /* RGB */
	{
		UINT32 TempFormat;
		BYTE* pTempData = pDstData;
		UINT32 nTempStep = nDstStep;

		if (useAlpha)
			TempFormat = PIXEL_FORMAT_BGRA32;
		else
			TempFormat = PIXEL_FORMAT_BGRX32;

		if ((TempFormat != DstFormat) || (nSrcWidth != nDstWidth) || (nSrcHeight != nDstHeight))
		{
			pTempData = planar->pTempData;
			nTempStep = planar->nTempStep;
		}

		if (!rle) /* RAW */
		{
			if (!planar_decompress_planes_raw(planes, pTempData, TempFormat, nTempStep, nXDst,
			                                  nYDst, nSrcWidth, nSrcHeight, vFlip))
				return FALSE;

			if (alpha)
				srcp += rawSizes[0] + rawSizes[1] + rawSizes[2] + rawSizes[3];
			else /* NoAlpha */
				srcp += rawSizes[0] + rawSizes[1] + rawSizes[2];

			if ((SrcSize - (srcp - pSrcData)) == 1)
				srcp++; /* pad */
		}
		else /* RLE */
		{
			status =
			    planar_decompress_plane_rle(planes[0], rleSizes[0], pTempData, nTempStep, nXDst,
			                                nYDst, nSrcWidth, nSrcHeight, 2, vFlip); /* RedPlane */

			if (status < 0)
				return FALSE;

			status = planar_decompress_plane_rle(planes[1], rleSizes[1], pTempData, nTempStep,
			                                     nXDst, nYDst, nSrcWidth, nSrcHeight, 1,
			                                     vFlip); /* GreenPlane */

			if (status < 0)
				return FALSE;

			status =
			    planar_decompress_plane_rle(planes[2], rleSizes[2], pTempData, nTempStep, nXDst,
			                                nYDst, nSrcWidth, nSrcHeight, 0, vFlip); /* BluePlane */

			if (status < 0)
				return FALSE;

			srcp += rleSizes[0] + rleSizes[1] + rleSizes[2];

			if (useAlpha)
			{
				status = planar_decompress_plane_rle(planes[3], rleSizes[3], pTempData, nTempStep,
				                                     nXDst, nYDst, nSrcWidth, nSrcHeight, 3,
				                                     vFlip); /* AlphaPlane */
			}
			else
				status = planar_set_plane(0xFF, pTempData, nTempStep, nXDst, nYDst, nSrcWidth,
				                          nSrcHeight, 3, vFlip);

			if (status < 0)
				return FALSE;

			if (alpha)
				srcp += rleSizes[3];
		}

		if (pTempData != pDstData)
		{
			if (!freerdp_image_copy(pDstData, DstFormat, nDstStep, nXDst, nYDst, w, h, pTempData,
			                        TempFormat, nTempStep, nXDst, nYDst, NULL, FREERDP_FLIP_NONE))
				return FALSE;
		}
	}
	else /* YCoCg */
	{
		UINT32 TempFormat;
		BYTE* pTempData = planar->pTempData;
		UINT32 nTempStep = planar->nTempStep;

		if (useAlpha)
			TempFormat = PIXEL_FORMAT_BGRA32;
		else
			TempFormat = PIXEL_FORMAT_BGRX32;

		if (!pTempData)
			return FALSE;

		if (cs)
		{
			WLog_ERR(TAG, "Chroma subsampling unimplemented");
			return FALSE;
		}

		if (!rle) /* RAW */
		{
			if (!planar_decompress_planes_raw(planes, pTempData, TempFormat, nTempStep, nXDst,
			                                  nYDst, nSrcWidth, nSrcHeight, vFlip))
				return FALSE;

			if (alpha)
				srcp += rawSizes[0] + rawSizes[1] + rawSizes[2] + rawSizes[3];
			else /* NoAlpha */
				srcp += rawSizes[0] + rawSizes[1] + rawSizes[2];

			if ((SrcSize - (srcp - pSrcData)) == 1)
				srcp++; /* pad */
		}
		else /* RLE */
		{
			if (useAlpha)
			{
				status = planar_decompress_plane_rle(planes[3], rleSizes[3], pTempData, nTempStep,
				                                     nXDst, nYDst, nSrcWidth, nSrcHeight, 3,
				                                     vFlip); /* AlphaPlane */

				if (status < 0)
					return FALSE;
			}

			if (alpha)
				srcp += rleSizes[3];

			status =
			    planar_decompress_plane_rle(planes[0], rleSizes[0], pTempData, nTempStep, nXDst,
			                                nYDst, nSrcWidth, nSrcHeight, 2, vFlip); /* LumaPlane */

			if (status < 0)
				return FALSE;

			status = planar_decompress_plane_rle(planes[1], rleSizes[1], pTempData, nTempStep,
			                                     nXDst, nYDst, nSrcWidth, nSrcHeight, 1,
			                                     vFlip); /* OrangeChromaPlane */

			if (status < 0)
				return FALSE;

			status = planar_decompress_plane_rle(planes[2], rleSizes[2], pTempData, nTempStep,
			                                     nXDst, nYDst, nSrcWidth, nSrcHeight, 0,
			                                     vFlip); /* GreenChromaPlane */

			if (status < 0)
				return FALSE;

			srcp += rleSizes[0] + rleSizes[1] + rleSizes[2];
		}

		if (prims->YCoCgToRGB_8u_AC4R(pTempData, nTempStep, pDstData, DstFormat, nDstStep, w, h,
		                              cll, useAlpha) != PRIMITIVES_SUCCESS)
			return FALSE;
	}

	return (SrcSize == (srcp - pSrcData)) ? TRUE : FALSE;
}

static INLINE BOOL freerdp_split_color_planes(const BYTE* data, UINT32 format, UINT32 width,
                                              UINT32 height, UINT32 scanline, BYTE* planes[4])
{
	INT32 i, j, k;
	if ((width > INT32_MAX) || (height > INT32_MAX) || (scanline > INT32_MAX))
		return FALSE;

	k = 0;

	if (scanline == 0)
		scanline = width * GetBytesPerPixel(format);

	for (i = (INT32)height - 1; i >= 0; i--)
	{
		const BYTE* pixel = &data[(INT32)scanline * i];

		for (j = 0; j < (INT32)width; j++)
		{
			const UINT32 color = ReadColor(pixel, format);
			pixel += GetBytesPerPixel(format);
			SplitColor(color, format, &planes[1][k], &planes[2][k], &planes[3][k], &planes[0][k],
			           NULL);
			k++;
		}
	}

	return TRUE;
}

static INLINE UINT32 freerdp_bitmap_planar_write_rle_bytes(const BYTE* pInBuffer, UINT32 cRawBytes,
                                                           UINT32 nRunLength, BYTE* pOutBuffer,
                                                           UINT32 outBufferSize)
{
	const BYTE* pInput;
	BYTE* pOutput;
	BYTE controlByte;
	UINT32 nBytesToWrite;
	pInput = pInBuffer;
	pOutput = pOutBuffer;

	if (!cRawBytes && !nRunLength)
		return 0;

	if (nRunLength < 3)
	{
		cRawBytes += nRunLength;
		nRunLength = 0;
	}

	while (cRawBytes)
	{
		if (cRawBytes < 16)
		{
			if (nRunLength > 15)
			{
				if (nRunLength < 18)
				{
					controlByte = PLANAR_CONTROL_BYTE(13, cRawBytes);
					nRunLength -= 13;
					cRawBytes = 0;
				}
				else
				{
					controlByte = PLANAR_CONTROL_BYTE(15, cRawBytes);
					nRunLength -= 15;
					cRawBytes = 0;
				}
			}
			else
			{
				controlByte = PLANAR_CONTROL_BYTE(nRunLength, cRawBytes);
				nRunLength = 0;
				cRawBytes = 0;
			}
		}
		else
		{
			controlByte = PLANAR_CONTROL_BYTE(0, 15);
			cRawBytes -= 15;
		}

		if (outBufferSize < 1)
			return 0;

		outBufferSize--;
		*pOutput = controlByte;
		pOutput++;
		nBytesToWrite = (int)(controlByte >> 4);

		if (nBytesToWrite)
		{
			if (outBufferSize < nBytesToWrite)
				return 0;

			outBufferSize -= nBytesToWrite;
			CopyMemory(pOutput, pInput, nBytesToWrite);
			pOutput += nBytesToWrite;
			pInput += nBytesToWrite;
		}
	}

	while (nRunLength)
	{
		if (nRunLength > 47)
		{
			if (nRunLength < 50)
			{
				controlByte = PLANAR_CONTROL_BYTE(2, 13);
				nRunLength -= 45;
			}
			else
			{
				controlByte = PLANAR_CONTROL_BYTE(2, 15);
				nRunLength -= 47;
			}
		}
		else if (nRunLength > 31)
		{
			controlByte = PLANAR_CONTROL_BYTE(2, (nRunLength - 32));
			nRunLength = 0;
		}
		else if (nRunLength > 15)
		{
			controlByte = PLANAR_CONTROL_BYTE(1, (nRunLength - 16));
			nRunLength = 0;
		}
		else
		{
			controlByte = PLANAR_CONTROL_BYTE(nRunLength, 0);
			nRunLength = 0;
		}

		if (outBufferSize < 1)
			return 0;

		--outBufferSize;
		*pOutput = controlByte;
		pOutput++;
	}

	return (pOutput - pOutBuffer);
}

static INLINE UINT32 freerdp_bitmap_planar_encode_rle_bytes(const BYTE* pInBuffer,
                                                            UINT32 inBufferSize, BYTE* pOutBuffer,
                                                            UINT32 outBufferSize)
{
	BYTE symbol;
	const BYTE* pInput;
	BYTE* pOutput;
	const BYTE* pBytes;
	UINT32 cRawBytes;
	UINT32 nRunLength;
	UINT32 bSymbolMatch;
	UINT32 nBytesWritten;
	UINT32 nTotalBytesWritten;
	symbol = 0;
	cRawBytes = 0;
	nRunLength = 0;
	pInput = pInBuffer;
	pOutput = pOutBuffer;
	nTotalBytesWritten = 0;

	if (!outBufferSize)
		return 0;

	do
	{
		if (!inBufferSize)
			break;

		bSymbolMatch = (symbol == *pInput) ? TRUE : FALSE;
		symbol = *pInput;
		pInput++;
		inBufferSize--;

		if (nRunLength && !bSymbolMatch)
		{
			if (nRunLength < 3)
			{
				cRawBytes += nRunLength;
				nRunLength = 0;
			}
			else
			{
				pBytes = pInput - (cRawBytes + nRunLength + 1);
				nBytesWritten = freerdp_bitmap_planar_write_rle_bytes(pBytes, cRawBytes, nRunLength,
				                                                      pOutput, outBufferSize);
				nRunLength = 0;

				if (!nBytesWritten || (nBytesWritten > outBufferSize))
					return nRunLength;

				nTotalBytesWritten += nBytesWritten;
				outBufferSize -= nBytesWritten;
				pOutput += nBytesWritten;
				cRawBytes = 0;
			}
		}

		nRunLength += bSymbolMatch;
		cRawBytes += (!bSymbolMatch) ? TRUE : FALSE;
	} while (outBufferSize);

	if (cRawBytes || nRunLength)
	{
		pBytes = pInput - (cRawBytes + nRunLength);
		nBytesWritten = freerdp_bitmap_planar_write_rle_bytes(pBytes, cRawBytes, nRunLength,
		                                                      pOutput, outBufferSize);

		if (!nBytesWritten)
			return 0;

		nTotalBytesWritten += nBytesWritten;
	}

	if (inBufferSize)
		return 0;

	return nTotalBytesWritten;
}

BOOL freerdp_bitmap_planar_compress_plane_rle(const BYTE* inPlane, UINT32 width, UINT32 height,
                                              BYTE* outPlane, UINT32* dstSize)
{
	UINT32 index;
	const BYTE* pInput;
	BYTE* pOutput;
	UINT32 outBufferSize;
	UINT32 nBytesWritten;
	UINT32 nTotalBytesWritten;

	if (!outPlane)
		return FALSE;

	index = 0;
	pInput = inPlane;
	pOutput = outPlane;
	outBufferSize = *dstSize;
	nTotalBytesWritten = 0;

	while (outBufferSize)
	{
		nBytesWritten =
		    freerdp_bitmap_planar_encode_rle_bytes(pInput, width, pOutput, outBufferSize);

		if ((!nBytesWritten) || (nBytesWritten > outBufferSize))
			return FALSE;

		outBufferSize -= nBytesWritten;
		nTotalBytesWritten += nBytesWritten;
		pOutput += nBytesWritten;
		pInput += width;
		index++;

		if (index >= height)
			break;
	}

	*dstSize = nTotalBytesWritten;
	return TRUE;
}

static INLINE BOOL freerdp_bitmap_planar_compress_planes_rle(BYTE* inPlanes[4], UINT32 width,
                                                             UINT32 height, BYTE* outPlanes,
                                                             UINT32* dstSizes, BOOL skipAlpha)
{
	UINT32 outPlanesSize = width * height * 4;

	/* AlphaPlane */
	if (skipAlpha)
	{
		dstSizes[0] = 0;
	}
	else
	{
		dstSizes[0] = outPlanesSize;

		if (!freerdp_bitmap_planar_compress_plane_rle(inPlanes[0], width, height, outPlanes,
		                                              &dstSizes[0]))
			return FALSE;

		outPlanes += dstSizes[0];
		outPlanesSize -= dstSizes[0];
	}

	/* LumaOrRedPlane */
	dstSizes[1] = outPlanesSize;

	if (!freerdp_bitmap_planar_compress_plane_rle(inPlanes[1], width, height, outPlanes,
	                                              &dstSizes[1]))
		return FALSE;

	outPlanes += dstSizes[1];
	outPlanesSize -= dstSizes[1];
	/* OrangeChromaOrGreenPlane */
	dstSizes[2] = outPlanesSize;

	if (!freerdp_bitmap_planar_compress_plane_rle(inPlanes[2], width, height, outPlanes,
	                                              &dstSizes[2]))
		return FALSE;

	outPlanes += dstSizes[2];
	outPlanesSize -= dstSizes[2];
	/* GreenChromeOrBluePlane */
	dstSizes[3] = outPlanesSize;

	if (!freerdp_bitmap_planar_compress_plane_rle(inPlanes[3], width, height, outPlanes,
	                                              &dstSizes[3]))
		return FALSE;

	return TRUE;
}

BYTE* freerdp_bitmap_planar_delta_encode_plane(const BYTE* inPlane, UINT32 width, UINT32 height,
                                               BYTE* outPlane)
{
	char s2c;
	INT32 delta;
	UINT32 y, x;
	BYTE* outPtr;
	const BYTE *srcPtr, *prevLinePtr;

	if (!outPlane)
	{
		if (width * height == 0)
			return NULL;

		if (!(outPlane = (BYTE*)calloc(height, width)))
			return NULL;
	}

	// first line is copied as is
	CopyMemory(outPlane, inPlane, width);
	outPtr = outPlane + width;
	srcPtr = inPlane + width;
	prevLinePtr = inPlane;

	for (y = 1; y < height; y++)
	{
		for (x = 0; x < width; x++, outPtr++, srcPtr++, prevLinePtr++)
		{
			delta = *srcPtr - *prevLinePtr;
			s2c = (delta >= 0) ? (char)delta : (char)(~((BYTE)(-delta)) + 1);
			s2c = (s2c >= 0) ? (s2c << 1) : (char)(((~((BYTE)s2c) + 1) << 1) - 1);
			*outPtr = (BYTE)s2c;
		}
	}

	return outPlane;
}

static INLINE BOOL freerdp_bitmap_planar_delta_encode_planes(BYTE* inPlanes[4], UINT32 width,
                                                             UINT32 height, BYTE* outPlanes[4])
{
	UINT32 i;

	for (i = 0; i < 4; i++)
	{
		outPlanes[i] =
		    freerdp_bitmap_planar_delta_encode_plane(inPlanes[i], width, height, outPlanes[i]);

		if (!outPlanes[i])
			return FALSE;
	}

	return TRUE;
}

BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* context, const BYTE* data,
                                     UINT32 format, UINT32 width, UINT32 height, UINT32 scanline,
                                     BYTE* dstData, UINT32* pDstSize)
{
	UINT32 size;
	BYTE* dstp;
	UINT32 planeSize;
	UINT32 dstSizes[4] = { 0 };
	BYTE FormatHeader = 0;

	if (!context || !context->rlePlanesBuffer)
		return NULL;

	if (context->AllowSkipAlpha)
		FormatHeader |= PLANAR_FORMAT_HEADER_NA;

	planeSize = width * height;

	if (!freerdp_split_color_planes(data, format, width, height, scanline, context->planes))
		return NULL;

	if (context->AllowRunLengthEncoding)
	{
		if (!freerdp_bitmap_planar_delta_encode_planes(context->planes, width, height,
		                                               context->deltaPlanes))
			return NULL;

		if (!freerdp_bitmap_planar_compress_planes_rle(context->deltaPlanes, width, height,
		                                               context->rlePlanesBuffer, dstSizes,
		                                               context->AllowSkipAlpha))
			return NULL;

		{
			int offset = 0;
			FormatHeader |= PLANAR_FORMAT_HEADER_RLE;
			context->rlePlanes[0] = &context->rlePlanesBuffer[offset];
			offset += dstSizes[0];
			context->rlePlanes[1] = &context->rlePlanesBuffer[offset];
			offset += dstSizes[1];
			context->rlePlanes[2] = &context->rlePlanesBuffer[offset];
			offset += dstSizes[2];
			context->rlePlanes[3] = &context->rlePlanesBuffer[offset];
			// WLog_DBG(TAG, "R: [%"PRIu32"/%"PRIu32"] G: [%"PRIu32"/%"PRIu32"] B:
			// [%"PRIu32"/%"PRIu32"]", 		dstSizes[1], planeSize, dstSizes[2], planeSize,
			// dstSizes[3],
			// planeSize);
		}
	}

	if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
	{
		if (!context->AllowRunLengthEncoding)
			return NULL;

		if (context->rlePlanes[0] == NULL)
			return NULL;

		if (context->rlePlanes[1] == NULL)
			return NULL;

		if (context->rlePlanes[2] == NULL)
			return NULL;

		if (context->rlePlanes[3] == NULL)
			return NULL;
	}

	if (!dstData)
	{
		size = 1;

		if (!(FormatHeader & PLANAR_FORMAT_HEADER_NA))
		{
			if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
				size += dstSizes[0];
			else
				size += planeSize;
		}

		if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
			size += (dstSizes[1] + dstSizes[2] + dstSizes[3]);
		else
			size += (planeSize * 3);

		if (!(FormatHeader & PLANAR_FORMAT_HEADER_RLE))
			size++;

		dstData = malloc(size);

		if (!dstData)
			return NULL;

		*pDstSize = size;
	}

	dstp = dstData;
	*dstp = FormatHeader; /* FormatHeader */
	dstp++;

	/* AlphaPlane */

	if (!(FormatHeader & PLANAR_FORMAT_HEADER_NA))
	{
		if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
		{
			CopyMemory(dstp, context->rlePlanes[0], dstSizes[0]); /* Alpha */
			dstp += dstSizes[0];
		}
		else
		{
			CopyMemory(dstp, context->planes[0], planeSize); /* Alpha */
			dstp += planeSize;
		}
	}

	/* LumaOrRedPlane */

	if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
	{
		CopyMemory(dstp, context->rlePlanes[1], dstSizes[1]); /* Red */
		dstp += dstSizes[1];
	}
	else
	{
		CopyMemory(dstp, context->planes[1], planeSize); /* Red */
		dstp += planeSize;
	}

	/* OrangeChromaOrGreenPlane */

	if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
	{
		CopyMemory(dstp, context->rlePlanes[2], dstSizes[2]); /* Green */
		dstp += dstSizes[2];
	}
	else
	{
		CopyMemory(dstp, context->planes[2], planeSize); /* Green */
		dstp += planeSize;
	}

	/* GreenChromeOrBluePlane */

	if (FormatHeader & PLANAR_FORMAT_HEADER_RLE)
	{
		CopyMemory(dstp, context->rlePlanes[3], dstSizes[3]); /* Blue */
		dstp += dstSizes[3];
	}
	else
	{
		CopyMemory(dstp, context->planes[3], planeSize); /* Blue */
		dstp += planeSize;
	}

	/* Pad1 (1 byte) */

	if (!(FormatHeader & PLANAR_FORMAT_HEADER_RLE))
	{
		*dstp = 0;
		dstp++;
	}

	size = (dstp - dstData);
	*pDstSize = size;
	return dstData;
}

BOOL freerdp_bitmap_planar_context_reset(BITMAP_PLANAR_CONTEXT* context, UINT32 width,
                                         UINT32 height)
{
	if (!context)
		return FALSE;

	context->maxWidth = width;
	context->maxHeight = height;
	context->maxPlaneSize = context->maxWidth * context->maxHeight;
	context->nTempStep = context->maxWidth * 4;
	free(context->planesBuffer);
	free(context->pTempData);
	free(context->deltaPlanesBuffer);
	free(context->rlePlanesBuffer);
	context->planesBuffer = calloc(context->maxPlaneSize, 4);
	context->pTempData = calloc(context->maxPlaneSize, 4);
	context->deltaPlanesBuffer = calloc(context->maxPlaneSize, 4);
	context->rlePlanesBuffer = calloc(context->maxPlaneSize, 4);

	if (!context->planesBuffer || !context->pTempData || !context->deltaPlanesBuffer ||
	    !context->rlePlanesBuffer)
		return FALSE;

	context->planes[0] = &context->planesBuffer[context->maxPlaneSize * 0];
	context->planes[1] = &context->planesBuffer[context->maxPlaneSize * 1];
	context->planes[2] = &context->planesBuffer[context->maxPlaneSize * 2];
	context->planes[3] = &context->planesBuffer[context->maxPlaneSize * 3];
	context->deltaPlanes[0] = &context->deltaPlanesBuffer[context->maxPlaneSize * 0];
	context->deltaPlanes[1] = &context->deltaPlanesBuffer[context->maxPlaneSize * 1];
	context->deltaPlanes[2] = &context->deltaPlanesBuffer[context->maxPlaneSize * 2];
	context->deltaPlanes[3] = &context->deltaPlanesBuffer[context->maxPlaneSize * 3];
	return TRUE;
}

BITMAP_PLANAR_CONTEXT* freerdp_bitmap_planar_context_new(DWORD flags, UINT32 maxWidth,
                                                         UINT32 maxHeight)
{
	BITMAP_PLANAR_CONTEXT* context;
	context = (BITMAP_PLANAR_CONTEXT*)calloc(1, sizeof(BITMAP_PLANAR_CONTEXT));

	if (!context)
		return NULL;

	if (flags & PLANAR_FORMAT_HEADER_NA)
		context->AllowSkipAlpha = TRUE;

	if (flags & PLANAR_FORMAT_HEADER_RLE)
		context->AllowRunLengthEncoding = TRUE;

	if (flags & PLANAR_FORMAT_HEADER_CS)
		context->AllowColorSubsampling = TRUE;

	context->ColorLossLevel = flags & PLANAR_FORMAT_HEADER_CLL_MASK;

	if (context->ColorLossLevel)
		context->AllowDynamicColorFidelity = TRUE;

	if (!freerdp_bitmap_planar_context_reset(context, maxWidth, maxHeight))
	{
		freerdp_bitmap_planar_context_free(context);
		return NULL;
	}

	return context;
}

void freerdp_bitmap_planar_context_free(BITMAP_PLANAR_CONTEXT* context)
{
	if (!context)
		return;

	free(context->pTempData);
	free(context->planesBuffer);
	free(context->deltaPlanesBuffer);
	free(context->rlePlanesBuffer);
	free(context);
}


text:
// Copyright (c) 2018-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>

#include <test/gen/crypto_gen.h>
#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

#include <rapidcheck/Gen.h>
#include <rapidcheck/boost_test.h>
#include <rapidcheck/gen/Arbitrary.h>

#include <cstdint>
#include <vector>

BOOST_FIXTURE_TEST_SUITE(key_properties, BasicTestingSetup)

/** Check CKey uniqueness */
RC_BOOST_PROP(key_uniqueness, (const CKey &key1, const CKey &key2)) {
    RC_ASSERT(!(key1 == key2));
}

/** Verify that a private key generates the correct public key */
RC_BOOST_PROP(key_generates_correct_pubkey, (const CKey &key)) {
    CPubKey pubKey = key.GetPubKey();
    RC_ASSERT(key.VerifyPubKey(pubKey));
}

/** Create a CKey using the 'Set' function must give us the same key */
RC_BOOST_PROP(key_set_symmetry, (const CKey &key)) {
    CKey key1;
    key1.Set(key.begin(), key.end(), key.IsCompressed());
    RC_ASSERT(key1 == key);
}

/**
 *  Create a CKey, sign a piece of data with ECDSA algorithm, then verify it
 *  with the public key.
 */
RC_BOOST_PROP(key_sign_symmetry_ecdsa, (const CKey &key, const uint256 &hash)) {
    std::vector<uint8_t> vchSig;
    key.SignECDSA(hash, vchSig, 0);
    const CPubKey &pubKey = key.GetPubKey();
    RC_ASSERT(pubKey.VerifyECDSA(hash, vchSig));
}

/**
 *  Create a CKey, sign a piece of data with Schnorr algorithm, then verify it
 *  with the public key.
 */
RC_BOOST_PROP(key_sign_symmetry_schnorr,
              (const CKey &key, const uint256 &hash)) {
    std::vector<uint8_t> vchSig;
    key.SignSchnorr(hash, vchSig, 0);
    const CPubKey &pubKey = key.GetPubKey();
    RC_ASSERT(pubKey.VerifySchnorr(hash, vchSig));
}
BOOST_AUTO_TEST_SUITE_END()


text:
require("test_helper")
require("textile")

class Textile
  def send_private(method, *args, &block)
    send(method, *args, &block)
  end
end

class TextileTest < UnitTestCase
  def assert_name_link_matches(str, label = nil, name = nil)
    obj = Textile.new(str)
    obj.send_private(:check_name_links!)
    assert_equal("x{NAME __#{label}__ }{ #{name} }x", obj.to_s)
  end

  def assert_name_link_fails(str)
    obj = Textile.new(str)
    obj.send_private(:check_name_links!)
    assert_equal(str, obj.to_s)
  end

  def do_other_links(str)
    obj = Textile.new(str)
    obj.send_private(:check_other_links!)
    obj.to_s
  end

  def assert_href_equal(url, str)
    result = str.tl
    assert_match(/href=.([^"']*)/, result,
                 "Expected an  tag for #{str.inspect}.\n" \
                 "Got: #{result.inspect}\n")
    result =~ /href=.([^"']*)/
    actual = Regexp.last_match(1)
    assert_equal(url, actual,
                 "URL for #{str.inspect} is wrong:\n" \
                 "url: #{url.inspect}\n" \
                 "actual: #{actual}\n")
  end

  def test_name_lookup
    Textile.clear_textile_cache
    assert_equal({}, Textile.name_lookup)

    assert_name_link_matches("_Agaricus_", "Agaricus", "Agaricus")
    assert_equal({ "A" => "Agaricus" }, Textile.name_lookup)
    assert_nil(Textile.last_species)

    assert_name_link_matches(
      "_A. campestris_", "A. campestris", "Agaricus campestris"
    )
    assert_equal({ "A" => "Agaricus" }, Textile.name_lookup)
    assert_equal("Agaricus campestris", Textile.last_species)

    assert_name_link_matches("_Amanita_", "Amanita", "Amanita")
    assert_name_link_matches(
      "_A. campestris_", "A. campestris", "Amanita campestris"
    )
    assert_equal({ "A" => "Amanita" }, Textile.name_lookup)
    assert_equal("Amanita campestris", Textile.last_species)
    assert_nil(Textile.last_subspecies)
    assert_nil(Textile.last_variety)

    assert_name_link_matches(
      "_v. farrea_", "v. farrea", "Amanita campestris var. farrea"
    )
    assert_equal("Amanita campestris", Textile.last_species)
    assert_equal("Amanita campestris", Textile.last_subspecies)
    assert_equal("Amanita campestris var. farrea", Textile.last_variety)

    assert_name_link_matches("_A. baccata sensu Borealis_",
                             "A. baccata sensu Borealis",
                             "Amanita baccata sensu Borealis")
    assert_equal({ "A" => "Amanita" }, Textile.name_lookup)
    assert_equal("Amanita baccata", Textile.last_species)
    assert_nil(Textile.last_subspecies)
    assert_nil(Textile.last_variety)

    assert_name_link_matches('_A. "fakename"_',
                             'A. "fakename"',
                             'Amanita "fakename"')
    assert_name_link_matches("_A. newname in ed._",
                             "A. newname in ed.",
                             "Amanita newname in ed.")
    assert_name_link_matches("_A. something sensu stricto_",
                             "A. something sensu stricto",
                             "Amanita something")
    assert_name_link_matches("_A. another van den Boom_",
                             "A. another van den Boom",
                             "Amanita another van den Boom")
    assert_name_link_matches("_A. another (Th.) Fr._",
                             "A. another (Th.) Fr.",
                             "Amanita another (Th.) Fr.")
    assert_name_link_matches("_A. another Culb. & Culb._",
                             "A. another Culb. & Culb.",
                             "Amanita another Culb. & Culb.")
    assert_name_link_matches("_A.   ignore    (Extra)   Space!_",
                             "A. ignore (Extra) Space!",
                             "Amanita ignore (Extra) Space!")

    assert_name_link_matches("_Fungi sp._", "Fungi sp.", "Fungi")
    assert_equal({ "A" => "Amanita", "F" => "Fungi" }, Textile.name_lookup)
  end

  def test_expand_infra_specific_names
    # Expand subspecies after Textile is told about species
    assert_name_link_matches("_Hydnum album_", "Hydnum album", "Hydnum album")
    assert_name_link_matches(
      "_subsp. alpha_", "subsp. alpha", "Hydnum album subsp. alpha"
    )

    # Expand variety
    # after Textile is told about species
    assert_name_link_matches("_Hydnum ikeni_", "Hydnum ikeni", "Hydnum ikeni")
    assert_name_link_matches(
      "_var. beta_", "var. beta", "Hydnum ikeni var. beta"
    )
    # after Textile is told about subspecies
    assert_name_link_matches(
      "_subsp. alpha_", "subsp. alpha", "Hydnum ikeni subsp. alpha"
    )
    assert_name_link_matches(
      "_var. beta_", "var. beta", "Hydnum ikeni subsp. alpha var. beta"
    )

    # Expand form
    # after Textile is told about species
    assert_name_link_matches("_Hydnum album_", "Hydnum album", "Hydnum album")
    assert_name_link_matches(
      "_f. gamma_", "f. gamma", "Hydnum album f. gamma"
    )
    # after Textile is  told about subspecies
    assert_name_link_matches(
      "_subsp. alpha_", "subsp. alpha", "Hydnum album subsp. alpha"
    )
    assert_name_link_matches(
      "_f. gamma_", "f. gamma", "Hydnum album subsp. alpha f. gamma"
    )
    # after Textile is told about variety
    assert_name_link_matches(
      "_var. delta_", "var. delta", "Hydnum album subsp. alpha var. delta"
    )
    assert_name_link_matches(
      "_f. gamma_", "f. gamma", "Hydnum album subsp. alpha var. delta f. gamma"
    )
  end

  # These should not be interpreted as names.
  def test_name_lookup_failures
    assert_name_link_fails("__arriba!__")
    assert_name_link_fails("__blah blah blah__")
    assert_name_link_fails("__A 5-6 inch__")
    assert_name_link_fails("__This should be close__")
    assert_name_link_fails("__Sonoran Flora__")
    assert_name_link_fails("__A. H. Smith__")
  end

  def test_other_links
    assert_equal("", do_other_links(""))
    assert_equal("x{OBSERVATION __obs 123__ }{ 123 }x",
                 do_other_links("_obs 123_"))
    assert_equal("x{IMAGE __iMg 765__ }{ 765 }x",
                 do_other_links("_iMg 765_"))
    assert_equal("x{USER __phooey__ }{ phooey }x x{NAME __gar__ }{ gar }x",
                 do_other_links("_user phooey_ _name gar_"))
  end

  def test_location_lookup
    # This loc has 2 all-caps words to insure we're stripping
    # some tags added by Redcloth
    loc = "OSU, Corvallis, Oregon, USA"
    textile = "_location #{loc}_".tpl
    assert_match(
      "#{MO.http_domain}/observer/lookup_location/#{CGI.escape(loc)}", # href
      textile
    )
    assert_match("#{loc}", textile) # anchor text
  end

  def test_url_formatting
    assert_href_equal(
      "#{MO.http_domain}/observer/lookup_name/Amanita+%22sp-O01%22",
      '_Amanita "sp-O01"_'
    )
    assert_href_equal("http://www.amanitaceae.org?Amanita+sp-O01",
                      "http://www.amanitaceae.org?Amanita+sp-O01")
  end

  def test_link_text_truncation
    url = "http://www.#{"x" * Textile::URL_TRUNCATION_LENGTH}abc/truncated"
    result = url.tl
    link_text = Nokogiri::HTML.parse(result).text
    assert(link_text.end_with?("abc/..."),
           "Link text should be truncated with 'x/...'")
  end

  def test_textile_div_safe
    str = "Xyz"
    assert_match(
      %r{
.*#{str}.*
},
      Textile.textile_div_safe { Textile.textilize(str) },
      %("#{str}" should be within a
")
    )
  end
end


text:
@interface BlazeDateFieldProcessor : BlazeFieldProcessor
{

}

@end


text:
"""
img2py.py  --  Convert an image to PNG format and embed it in a Python
               module with appropriate code so it can be loaded into
               a program at runtime.  The benefit is that since it is
               Python source code it can be delivered as a .pyc or
               'compiled' into the program using freeze, py2exe, etc.

Usage:

    img2py.py [options] image_file python_file

Options:

    -m <#rrggbb>   If the original image has a mask or transparency defined
                   it will be used by default.  You can use this option to
                   override the default or provide a new mask by specifying
                   a colour in the image to mark as transparent.

    -n <name>      Normally generic names (getBitmap, etc.) are used for the
                   image access functions.  If you use this option you can
                   specify a name that should be used to customize the access
                   fucntions, (getNameBitmap, etc.)

    -c             Maintain a catalog of names that can be used to reference
                   images.  Catalog can be accessed via catalog and
                   index attributes of the module.
                   If the -n <name> option is specified then <name>
                   is used for the catalog key and index value, otherwise
                   the filename without any path or extension is used
                   as the key.

    -a             This flag specifies that the python_file should be appended
                   to instead of overwritten.  This in combination with -n will
                   allow you to put multiple images in one Python source file.

    -u             Don't use compression.  Leaves the data uncompressed.

    -i             Also output a function to return the image as a wxIcon.

You can also import this module from your Python scripts, and use its img2py()
function. See its docstring for more info.
"""

#
# Changes:
#    - Cliff Wells <LogiplexSoftware@earthlink.net>
#      20021206: Added catalog (-c) option.
#
# 12/21/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
#
# 2/25/2007 - Gianluca Costa (archimede86@katamail.com)
#        -Refactorization of the script-creation code in a specific "img2py()" function
#        -Added regex parsing instead of module importing
#        -Added some "try/finally" statements
#        -Added default values as named constants
#        -Made some parts of code a bit easier to read
#        -Updated the module docstring
#        -Corrected a bug with EmptyIcon
#
# o V2.5 compatibility update
#
import  cPickle
import  cStringIO
import  getopt
import  glob
import  os
import  os.path
import  sys
import  tempfile
import  zlib
import  re

import  wx
import  img2img

def crunch_data(data, compressed):
    # compress it?
    if compressed:
        data = zlib.compress(data, 9)

    # convert to a printable format, so it can be in a Python source file
    data = repr(data)

    # This next bit is borrowed from PIL.  It is used to wrap the text intelligently.
    fp = cStringIO.StringIO()
    data += " "  # buffer for the +1 test
    c = i = 0
    word = ""
    octdigits = "01234567"
    hexdigits = "0123456789abcdef"
    while i < len(data):
        if data[i] != "\\":
            word = data[i]
            i += 1
        else:
            if data[i+1] in octdigits:
                for n in xrange(2, 5):
                    if data[i+n] not in octdigits:
                        break
                word = data[i:i+n]
                i += n
            elif data[i+1] == 'x':
                for n in xrange(2, 5):
                    if data[i+n] not in hexdigits:
                        break
                word = data[i:i+n]
                i += n
            else:
                word = data[i:i+2]
                i += 2

        l = len(word)
        if c + l >= 78-1:
            fp.write("\\\n")
            c = 0
        fp.write(word)
        c += l

    # return the formatted compressed data
    return fp.getvalue()

app = None
DEFAULT_APPEND = False
DEFAULT_COMPRESSED = True
DEFAULT_MASKCLR = None
DEFAULT_IMGNAME = ""
DEFAULT_ICON = False
DEFAULT_CATALOG = False

#THIS IS USED TO IDENTIFY, IN THE GENERATED SCRIPT, LINES IN THE FORM "index.append('Image name')"
indexPattern = re.compile(r"\s*index.append\('(.+)'\)\s*")

def img2py(image_file, python_file, append=DEFAULT_APPEND, compressed=DEFAULT_COMPRESSED, maskClr=DEFAULT_MASKCLR, imgName=DEFAULT_IMGNAME, icon=DEFAULT_ICON, catalog=DEFAULT_CATALOG):
    """
    Converts an image file to a data structure written in a Python file
    --image_file: string; the path of the source image file
    --python_file: string; the path of the destination python file
    --other arguments: they are equivalent to the command-line arguments
    """
    global app
    if not wx.GetApp():
        app = wx.PySimpleApp()

    # convert the image file to a temporary file
    tfname = tempfile.mktemp()
    try:
        ok, msg = img2img.convert(image_file, maskClr, None, tfname, wx.BITMAP_TYPE_PNG, ".png")
        if not ok:
            print msg
            return

        data = open(tfname, "rb").read()
        data = crunch_data(data, compressed)
    finally:
        if os.path.exists(tfname):
            os.remove(tfname)

    old_index = []
    if catalog and append:
        # check to see if catalog exists already (file may have been created
        # with an earlier version of img2py or without -c option)
        pyPath, pyFile = os.path.split(python_file)

        append_catalog = True

        sourcePy = open(python_file, "r")
        try:
            for line in sourcePy:

                if line == "catalog = {}\n":
                    append_catalog = False
                else:
                    lineMatcher = indexPattern.match(line)
                    if lineMatcher:
                        old_index.append(lineMatcher.groups()[0])
        finally:
            sourcePy.close()

        if append_catalog:
            out = open(python_file, "a")
            try:
                out.write("\n# ***************** Catalog starts here *******************")
                out.write("\n\ncatalog = {}\n")
                out.write("index = []\n\n")
                out.write("class ImageClass: pass\n\n")
            finally:
                out.close()

    if append:
        out = open(python_file, "a")
    else:
        out = open(python_file, "w")

    try:
        if catalog:
            imgPath, imgFile = os.path.split(image_file)

            if not imgName:
                imgName = os.path.splitext(imgFile)[0]
                print "\nWarning: -n not specified. Using filename (%s) for catalog entry." % imgName

        out.write("#" + "-" * 70 + "\n")
        if not append:
            out.write("# This file was generated by %s\n#\n" % sys.argv[0])
            out.write("from wx import ImageFromStream, BitmapFromImage, EmptyIcon\n")
            if compressed:
                out.write("import cStringIO, zlib\n\n\n")
            else:
                out.write("import cStringIO\n\n\n")

            if catalog:
                out.write("catalog = {}\n")
                out.write("index = []\n\n")
                out.write("class ImageClass: pass\n\n")

        if compressed:
            out.write("def get%sData():\n"
                      "    return zlib.decompress(\n%s)\n\n"
                      % (imgName, data))
        else:
            out.write("def get%sData():\n"
                      "    return \\\n%s\n\n"
                      % (imgName, data))

        out.write("def get%sBitmap():\n"
                  "    return BitmapFromImage(get%sImage())\n\n"
                  "def get%sImage():\n"
                  "    stream = cStringIO.StringIO(get%sData())\n"
                  "    return ImageFromStream(stream)\n\n"
                  % tuple([imgName] * 4))
        if icon:
            out.write("def get%sIcon():\n"
                      "    icon = EmptyIcon()\n"
                      "    icon.CopyFromBitmap(get%sBitmap())\n"
                      "    return icon\n\n"
                      % tuple([imgName] * 2))

        if catalog:
            if imgName in old_index:
                print "Warning: %s already in catalog." % imgName
                print "         Only the last entry will be accessible.\n"
            old_index.append(imgName)
            out.write("index.append('%s')\n" % imgName)
            out.write("catalog['%s'] = ImageClass()\n" % imgName)
            out.write("catalog['%s'].getData = get%sData\n" % tuple([imgName] * 2))
            out.write("catalog['%s'].getImage = get%sImage\n" % tuple([imgName] * 2))
            out.write("catalog['%s'].getBitmap = get%sBitmap\n" % tuple([imgName] * 2))
            if icon:
                out.write("catalog['%s'].getIcon = get%sIcon\n" % tuple([imgName] * 2))
            out.write("\n\n")

        if imgName:
            n_msg = ' using "%s"' % imgName
        else:
            n_msg = ""

        if maskClr:
            m_msg = " with mask %s" % maskClr
        else:
            m_msg = ""

        print "Embedded %s%s into %s%s" % (image_file, n_msg, python_file, m_msg)
    finally:
        out.close()

def main(args):
    if not args or ("-h" in args):
        print __doc__
        return

    append = DEFAULT_APPEND
    compressed = DEFAULT_COMPRESSED
    maskClr = DEFAULT_MASKCLR
    imgName = DEFAULT_IMGNAME
    icon = DEFAULT_ICON
    catalog = DEFAULT_CATALOG

    try:
        opts, fileArgs = getopt.getopt(args, "auicn:m:")
    except getopt.GetoptError:
        print __doc__
        return

    for opt, val in opts:
        if opt == "-a":
            append = True
        elif opt == "-u":
            compressed = False
        elif opt == "-n":
            imgName = val
        elif opt == "-m":
            maskClr = val
        elif opt == "-i":
            icon = True
        elif opt == "-c":
            catalog = True

    if len(fileArgs) != 2:
        print __doc__
        return

    image_file, python_file = fileArgs
    img2py(image_file, python_file, append, compressed, maskClr, imgName, icon, catalog)

if __name__ == "__main__":
    main(sys.argv[1:])