text:
<?php

namespace Concrete\Core\Page\Collection;

use Concrete\Core\Area\Area;

use CacheLocal;
use CollectionVersion;
use Concrete\Core\Block\Block;
use Concrete\Core\Area\CustomStyle as AreaCustomStyle;
use Concrete\Core\Area\GlobalArea;
use Concrete\Core\Attribute\Key\CollectionKey;
use Concrete\Core\Block\CustomStyle as BlockCustomStyle;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Database\Driver\PDOStatement;
use Concrete\Core\Entity\Attribute\Value\PageValue;
use Concrete\Core\Foundation\ConcreteObject;
use Concrete\Core\Page\Cloner;
use Concrete\Core\Page\ClonerOptions;
use Concrete\Core\Page\Collection\Version\VersionList;
use Concrete\Core\Page\Command\ReindexPageCommand;
use Concrete\Core\Page\Search\IndexedSearch;
use Concrete\Core\Page\Summary\Template\Populator;
use Concrete\Core\Search\Index\IndexManagerInterface;
use Concrete\Core\Statistics\UsageTracker\TrackableInterface;
use Concrete\Core\StyleCustomizer\Inline\StyleSet;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\Support\Facade\Facade;
use Config;
use Doctrine\DBAL\FetchMode;
use Loader;
use Page;
use PageCache;
use Permissions;
use Stack;

class Collection extends ConcreteObject implements TrackableInterface
{
    /**
     * The collection ID.
     *
     * @deprecated Use getCollectionID (what's deprecated is the public part)
     *
     * @var int|null
     */
    public $cID;

    /**
     * The collection version object.
     *
     * @var \Concrete\Core\Page\Collection\Version\Version|null
     */
    protected $vObj;

    /**
     * The collection handle.
     *
     * @var string|null
     */
    protected $cHandle;

    /**
     * The date/time when the collection has been created.
     *
     * @var string|null
     *
     * @example 2017-12-31 23:59:59
     */
    protected $cDateAdded;

    /**
     * The date/time when the collection was last modified.
     *
     * @var string|null
     *
     * @example 2017-12-31 23:59:59
     */
    protected $cDateModified;

    /**
     * @var array
     */
    protected $attributes = [];

    /**
     * Destruct the class instance.
     */
    public function __destruct()
    {
        unset($this->attributes);
        unset($this->vObj);
    }

    /**
     * Get a collection by ID.
     *
     * @param int $cID The collection ID
     * @param string|int|false $version the collection version ('RECENT' for the most recent version, 'ACTIVE' for the currently published version, 'SCHEDULED' for the currently scheduled version, a falsy value to not load the collection version, or an integer to retrieve a specific version ID)
     *
     * @return \Concrete\Core\Page\Collection\Collection If the collection is not found, you'll get an empty Collection instance
     */
    public static function getByID($cID, $version = 'RECENT')
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $qb->select('c.cDateAdded', 'c.cDateModified', 'c.cID')
            ->from('Collections', 'c')
            ->where('c.cID = :cID')
            ->setParameter('cID', $cID);
        $row = $qb->execute()->fetch();

        $c = new self();
        if ($row !== false) {
            $c->setPropertiesFromArray($row);

            if ($version != false) {
                // we don't do this on the front page
                $c->loadVersionObject($version);
            }
        }

        return $c;
    }

    /**
     * Get a Collection by handle (provided that it's not a Page handle).
     * If there's there's no collection with the specified handle, a new Collection will be created.
     *
     * @param string $handle the collection handle
     *
     * @return \Concrete\Core\Page\Collection\Collection|null return NULL if $handle is the handle of an existing page
     */
    public static function getByHandle($handle)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $qb->select('c.cID', 'p.cID')
            ->from('Collections', 'c')
            ->leftJoin('c', 'Pages', 'p', 'c.cID = p.cID')
            ->where('c.cHandle = :cHandle')
            ->setParameter('cHandle', $handle);

        // first we ensure that this does NOT appear in the Pages table. This is not a page. It is more basic than that
        /** @var PDOStatement $r */
        $r = $qb->execute();
        if ($r->rowCount() === 0) {
            // there is nothing in the collections table for this page, so we create and grab

            $data = [
                'handle' => $handle,
            ];
            $cObj = self::createCollection($data);
        } else {
            $row = $r->fetch();
            if ($row['cID'] > 0 && $row['pcID'] === null) {
                // there is a collection, but it is not a page. so we grab it
                $cObj = self::getByID($row['cID']);
            }
        }

        return $cObj ?? null;
    }

    /**
     * (Re)Index all the collections that are marked as to be (re)indexed.
     *
     * @return int returns the number of reindexed pages
     */
    public static function reindexPendingPages()
    {
        $app = Application::getFacadeApplication();

        $indexStack = $app->make(IndexManagerInterface::class);

        $num = 0;
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $r = $qb->select('cID')
            ->from('PageSearchIndex')
            ->where('cRequiresReindex = 1')
            ->execute();
        while ($id = $r->fetchColumn()) {
            $indexStack->index(\Concrete\Core\Page\Page::class, $id);
            $num++;
        }
        Config::save('concrete.misc.do_page_reindex_check', false);

        return $num;
    }

    /**
     * Create a new Collection instance.
     *
     * @param array $data {
     *
     *     @var int|null $cID The ID of the collection to create (if unspecified or NULL: database autoincrement value)
     *     @var string $handle The collection handle (default: NULL)
     *     @var string $name The collection name (default: empty string)
     *     @var string $cDescription The collection description (default: NULL)
     *     @var string $cDatePublic The collection publish date/time in format 'YYYY-MM-DD hh:mm:ss' (default: now)
     *     @var bool $cvIsApproved Is the collection version approved (default: true)
     *     @var bool $cvIsNew Is the collection to be considered "new"? (default: true if $cvIsApproved is false, false if $cvIsApproved is true)
     *     @var int|null $pThemeID The collection theme ID (default: NULL)
     *     @var int|null $pTemplateID The collection template ID (default: NULL)
     *     @var int|null $uID The ID of the collection author (default: NULL)
     * }
     *
     * @return \Concrete\Core\Page\Collection\Collection
     */
    public static function createCollection($data)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $dh = Loader::helper('date');
        $cDate = $dh->getOverridableNow();

        $data = array_merge(
            [
                'name' => '',
                'pTemplateID' => 0,
                'handle' => null,
                'uID' => null,
                'cDatePublic' => $cDate,
                'cDescription' => null,
            ],
            $data
            );

        $cDatePublic = ($data['cDatePublic']) ? $data['cDatePublic'] : $cDate;

        if (isset($data['cID'])) {
            $res = $db->insert('Collections', [
                'cID' => $data['cID'],
                'cHandle' => $data['handle'],
                'cDateAdded' => $cDate,
                'cDateModified' => $cDate
            ]);
            $newCID = $data['cID'];
        } else {
            $res = $db->insert('Collections', [
                'cHandle' => $data['handle'],
                'cDateAdded' => $cDate,
                'cDateModified' => $cDate
            ]);
            $newCID = $db->lastInsertId();
        }

        $cvIsApproved = (isset($data['cvIsApproved']) && $data['cvIsApproved'] == 0) ? 0 : 1;
        $cvIsNew = 1;
        if ($cvIsApproved) {
            $cvIsNew = 0;
        }
        if (isset($data['cvIsNew'])) {
            $cvIsNew = $data['cvIsNew'];
        }
        $data['name'] = Loader::helper('text')->sanitize($data['name']);
        $pThemeID = 0;
        if (isset($data['pThemeID']) && $data['pThemeID']) {
            $pThemeID = $data['pThemeID'];
        }

        $pTemplateID = 0;
        if ($data['pTemplateID']) {
            $pTemplateID = $data['pTemplateID'];
        }

        if ($res) {
            // now we add a pending version to the collectionversions table
            $db->insert('CollectionVersions', [
                'cID' => $newCID,
                'cvID' => 1,
                'pTemplateID' => $pTemplateID,
                'cvName' => $data['name'],
                'cvHandle' => $data['handle'],
                'cvDescription' => $data['cDescription'],
                'cvDatePublic' => $cDatePublic,
                'cvDateCreated' => $cDate,
                'cvComments' => t(VERSION_INITIAL_COMMENT),
                'cvAuthorUID' => $data['uID'],
                'cvIsApproved' => $cvIsApproved,
                'cvIsNew' => $cvIsNew,
                'pThemeID' => $pThemeID,
            ]);
        }

        return self::getByID($newCID);
    }

    /**
     * Get the collection ID.
     *
     * @return int|null
     */
    public function getCollectionID()
    {
        return $this->cID ? (int) $this->cID : null;
    }

    /**
     * Get the collection handle.
     *
     * @return string|null
     */
    public function getCollectionHandle()
    {
        return $this->cHandle;
    }

    /**
     * Get the date/time when the collection was last modified.
     *
     * @return string|null
     *
     * @example 2017-12-31 23:59:59
     */
    public function getCollectionDateLastModified()
    {
        return $this->cDateModified;
    }

    /**
     * Get the date/time when the collection has been created.
     *
     * @return string|null
     *
     * @example 2017-12-31 23:59:59
     */
    public function getCollectionDateAdded()
    {
        return $this->cDateAdded;
    }

    /**
     * Get the ID of the currently loaded version.
     *
     * @return int
     */
    public function getVersionID()
    {
        return $this->vObj->cvID;
    }

    /**
     * Get the currently loaded version object.
     *
     * @return \Concrete\Core\Page\Collection\Version\Version|null
     */
    public function getVersionObject()
    {
        return $this->vObj;
    }

    /**
     * Create a new Collection instance, using the same theme as this instance (if it's a Page instance).
     *
     * @param array $data {
     *
     *     @var int|null $cID The ID of the collection to create (if unspecified or NULL: database autoincrement value)
     *     @var string $handle The collection handle (default: NULL)
     *     @var string $name The collection name (default: empty string)
     *     @var string $cDescription The collection description (default: NULL)
     *     @var string $cDatePublic The collection publish date/time in format 'YYYY-MM-DD hh:mm:ss' (default: now)
     *     @var bool $cvIsApproved Is the collection version approved (default: true)
     *     @var bool $cvIsNew Is the collection to be considered "new"? (default: true if $cvIsApproved is false, false if $cvIsApproved is true)
     *     @var int|null $pTemplateID The collection template ID (default: NULL)
     *     @var int|null $uID The ID of the collection author (default: NULL)
     * }
     *
     * @return \Concrete\Core\Page\Collection\Collection
     */
    public function addCollection($data)
    {
        $data['pThemeID'] = 0;
        if (isset($this) && $this instanceof Page) {
            $data['pThemeID'] = $this->getCollectionThemeID();
        }

        return static::createCollection($data);
    }

    /**
     * Load a specific collection version (you can retrieve it with the getVersionObject() method).
     *
     * @param string|int $cvID the collection version ('RECENT' for the most recent version, 'ACTIVE' for the currently published version, 'SCHEDULED' for the currently scheduled version, or an integer to retrieve a specific version ID)
     */
    public function loadVersionObject($cvID = 'ACTIVE')
    {
        $this->vObj = CollectionVersion::get($this, $cvID);
    }

    /**
     * Get the Collection instance to be modified (this instance if it's a new or master Collection, a clone otherwise).
     *
     * @return $this|\Concrete\Core\Page\Page
     */
    public function getVersionToModify()
    {
        $vObj = $this->getVersionObject();
        if ($this->isMasterCollection() || ($vObj->isNew())) {
            return $this;
        } else {
            $nc = $this->cloneVersion(null);

            return $nc;
        }
    }

    /**
     * Get the automatic comment for the next collection version.
     *
     * @return string Example: 'Version 2'
     */
    public function getNextVersionComments()
    {
        $c = Page::getByID($this->getCollectionID(), 'ACTIVE');
        $cvID = $c->getVersionID();

        return t('Version %d', $cvID + 1);
    }

    public function reindex()
    {
        if ($this->isAlias() && !$this->isExternalLink()) {
            return false;
        }

        $command = new ReindexPageCommand($this->getCollectionID());
        $app = Facade::getFacadeApplication();
        $app->executeCommand($command);
    }

    /**
     * Set the attribute value for the currently loaded collection version.
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $ak the attribute key (or its handle)
     * @param \Concrete\Core\Entity\Attribute\Value\Value\AbstractValue|mixed $value an attribute value object, or the data needed by the attribute controller to create the attribute value object
     * @param bool $doReindexImmediately
     * @return \Concrete\Core\Entity\Attribute\Value\PageValue
     */
    public function setAttribute($ak, $value, $doReindexImmediately = true)
    {
        return $this->vObj->setAttribute($ak, $value, $doReindexImmediately);
    }

    /**
     * Return the value of the attribute with the handle $akHandle of the currently loaded version (if it's loaded).
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $akHandle the attribute key (or its handle)
     * @param string|false $displayMode makes The format of the attribute value
     *
     * @return mixed|null
     *
     * @example When you need the raw attribute value or object, use this:
     *
     * $c = Page::getCurrentPage();
     * $attributeValue = $c->getAttribute('attribute_handle');
     *
     * @example If you need the formatted output supported by some attribute, use this:
     *
     * $c = Page::getCurrentPage();
     * $attributeValue = $c->getAttribute('attribute_handle', 'display');
     *
     * @example An attribute type like "date" will then return the date in the correct format just like other attributes will show you a nicely formatted output and not just a simple value or object.
     */
    public function getAttribute($akHandle, $displayMode = false)
    {
        if (is_object($this->vObj)) {
            return $this->vObj->getAttribute($akHandle, $displayMode);
        }
    }

    /**
     * Return the attribute value object with the handle $akHandle of the currently loaded version (if it's loaded).
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $akHandle the attribute key (or its handle)
     * @param bool $createIfNotExists
     *
     * @return \Concrete\Core\Entity\Attribute\Value\PageValue|null
     */
    public function getAttributeValueObject($akHandle, $createIfNotExists = false)
    {
        if (is_object($this->vObj)) {
            return $this->vObj->getAttributeValueObject($akHandle, $createIfNotExists);
        }
    }

    /**
     * Delete the values of the attributes associated to the currently loaded collection version.
     *
     * @param int[] $retainAKIDs a list of attribute key IDs to keep (their values won't be deleted)
     */
    public function clearCollectionAttributes($retainAKIDs = [])
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        if (count($retainAKIDs) > 0) {
            $cleanAKIDs = [];
            foreach ($retainAKIDs as $akID) {
                $cleanAKIDs[] = (int) $akID;
            }
            $qb->delete('CollectionAttributeValues')
                ->where('cID = :cID')
                ->andWhere('cvID = :cvID')
                ->andWhere($qb->expr()->notIn('akID', $cleanAKIDs))
                ->setParameter('cID', $this->getCollectionID())
                ->setParameter('cvID', $this->getVersionID())
                ->execute();
        } else {
            $qb->delete('CollectionAttributeValues')
                ->where('cID = :cID')
                ->andWhere('cvID = :cvID')
                ->setParameter('cID', $this->getCollectionID())
                ->setParameter('cvID', $this->getVersionID())
                ->execute();
        }
        $this->reindex();
    }

    /**
     * Delete the value of a specific attribute key associated to the currently loaded collection version.
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $ak the attribute key (or its handle)
     * @param bool $doReindexImmediately
     */
    public function clearAttribute($ak, bool $doReindexImmediately = true)
    {
        $this->vObj->clearAttribute($ak, $doReindexImmediately);
    }

    /**
     * Get the list of attribute keys for which the currently loaded collection version has values.
     *
     * @return \Concrete\Core\Entity\Attribute\Key\PageKey[]
     */
    public function getSetCollectionAttributes()
    {
        $category = $this->vObj->getObjectAttributeCategory();
        $values = $category->getAttributeValues($this->vObj);
        $attribs = [];
        foreach ($values as $value) {
            $attribs[] = $value->getAttributeKey();
        }

        return $attribs;
    }

    /**
     * Get an existing area associated to this collection.
     *
     * @param string $arHandle the handle of the area
     *
     * @return \Concrete\Core\Area\Area|null
     */
    public function getArea($arHandle)
    {
        return Area::get($this, $arHandle);
    }

    /**
     * Does this collection contain blocks that are aliased in other pages?
     *
     * @return bool
     */
    public function hasAliasedContent()
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        // aliased content is content on the particular page that is being
        // used elsewhere - but the content on the PAGE is the original version
        $r = $qb->select('bID')
            ->from('CollectionVersionBlocks')
            ->where('cID = :cID')
            ->andWhere('isOriginal = 1')
            ->setParameter('cID', $this->getCollectionID())
            ->execute();
        $bIDArray = [];
        if ($r) {
            while ($row = $r->fetch()) {
                $bIDArray[] = $row['bID'];
            }
            if (count($bIDArray) > 0) {
                $qb2 = $db->createQueryBuilder();
                $qb2->select('cID')
                    ->from('CollectionVersionBlocks')
                    ->where($qb2->expr()->in('bID', $bIDArray))
                    ->andWhere($qb2->expr()->neq('cID', ':cID'))
                    ->setParameter('cID', $this->getCollectionID())
                    ->setMaxResults(1);
                $aliasedCID = $qb2->execute()->fetchColumn();
                if ($aliasedCID > 0) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get the custom style of an area in the currently loaded collection version.
     *
     * @param \Concrete\Core\Area\Area $area the area for which you want the custom styles
     * @param bool $force Set to true to retrieve a CustomStyle even if the area does not define any custom style
     *
     * @return \Concrete\Core\Area\CustomStyle|null return NULL if the area does not have any custom style and $force is false, a CustomStyle instance otherwise
     */
    public function getAreaCustomStyle($area, $force = false)
    {
        $areac = $area->getAreaCollectionObject();
        if ($areac instanceof Stack) {
            // this fixes the problem of users applying design to the main area on the page, and then that trickling into any
            // stacks that have been added to other areas of the page.
            return null;
        }
        $result = null;
        $styles = $this->vObj->getCustomAreaStyles();
        $areaHandle = $area->getAreaHandle();
        if ($force || isset($styles[$areaHandle])) {
            $pss = isset($styles[$areaHandle]) ? StyleSet::getByID($styles[$areaHandle]) : null;
            $result = new AreaCustomStyle($pss, $area, $this->getCollectionThemeObject());
        }

        return $result;
    }

    /**
     * Set the custom style of an area in the currently loaded collection version.
     *
     * @param \Concrete\Core\Area\Area $area
     * @param \Concrete\Core\Entity\StyleCustomizer\Inline\StyleSet $set
     */
    public function setCustomStyleSet($area, $set)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $r = $qb->select('cID')
            ->from('CollectionVersionAreaStyles')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('arHandle = :arHandle')
            ->setParameter('cID', $this->getCollectionID())
            ->setParameter('cvID', $this->getVersionID())
            ->setParameter('arHandle', $area->getAreaHandle())
            ->execute()->fetch();

        $qb2 = $db->createQueryBuilder();
        if ($r !== false) {
            $qb2->update('CollectionVersionAreaStyles')
                ->set('issID', ':issID')
                ->where('cID = :cID')
                ->andWhere('cvID = :cvID')
                ->andWhere('arHandle = :arHandle');
        } else {
            $qb2->insert('CollectionVersionAreaStyles')
                ->setValue('cID', ':cID')
                ->setValue('cvID', ':cvID')
                ->setValue('arHandle', ':arHandle')
                ->setValue('issID', ':issID');
        }
        $qb2->setParameter('cID', $this->getCollectionID())
            ->setParameter('cvID', $this->getVersionID())
            ->setParameter('arHandle', $area->getAreaHandle())
            ->setParameter('issID', $set->getID())
            ->execute();
    }

    /**
     * Delete all the custom styles of an area of the currently loaded collection version.
     *
     * @param \Concrete\Core\Area\Area $area
     */
    public function resetAreaCustomStyle($area)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $qb->delete('CollectionVersionAreaStyles')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('arHandle = :arHandle')
            ->setParameter('cID', $this->getCollectionID())
            ->setParameter('cvID', $this->getVersionID())
            ->setParameter('arHandle', $area->getAreaHandle())
            ->execute();
    }

    /**
     * Retrieve all custom style rules that should be inserted into the header on a page, whether they are defined in areas or blocks.
     *
     * @param bool $return set to true to return the HTML that defines the styles, false to add it to the current View instance
     *
     * @return string|null
     */
    public function outputCustomStyleHeaderItems($return = false)
    {
        if (!Config::get('concrete.design.enable_custom')) {
            return '';
        }

        $psss = [];
        $txt = Loader::helper('text');
        CacheLocal::set('pssCheck', $this->getCollectionID() . ':' . $this->getVersionID(), true);

        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb1 = $db->createQueryBuilder();
        $r1 = $qb1->select('bID', 'arHandle', 'issID')
            ->from('CollectionVersionBlockStyles')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('issID > 0')
            ->setParameter(':cID', $this->getCollectionID())
            ->setParameter(':cvID', $this->getVersionID())
            ->execute()->fetchAll();
        $qb2 = $db->createQueryBuilder();
        $r2 = $qb2->select('arHandle', 'issID')
            ->from('CollectionVersionAreaStyles')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('issID > 0')
            ->setParameter(':cID', $this->getCollectionID())
            ->setParameter(':cvID', $this->getVersionID())
            ->execute()->fetchAll();
        foreach ($r1 as $r) {
            $issID = $r['issID'];
            $arHandle = $txt->filterNonAlphaNum($r['arHandle']);
            $bID = $r['bID'];
            $obj = StyleSet::getByID($issID);
            if (is_object($obj)) {
                $b = new Block();
                $b->bID = $bID;
                $a = new Area($arHandle);
                $b->setBlockAreaObject($a);
                $obj = new BlockCustomStyle($obj, $b, $this->getCollectionThemeObject());
                $psss[] = $obj;
                CacheLocal::set(
                          'pssObject',
                          $this->getCollectionID() . ':' . $this->getVersionID() . ':' . $r['arHandle'] . ':' . $r['bID'],
                          $obj
                );
            }
        }

        foreach ($r2 as $r) {
            $issID = $r['issID'];
            $obj = StyleSet::getByID($issID);
            if (is_object($obj)) {
                $a = new Area($r['arHandle']);
                $obj = new AreaCustomStyle($obj, $a, $this->getCollectionThemeObject());
                $psss[] = $obj;
                CacheLocal::set(
                          'pssObject',
                          $this->getCollectionID() . ':' . $this->getVersionID() . ':' . $r['arHandle'],
                          $obj
                );
            }
        }

        // grab all the header block style rules for items in global areas on this page
        $qb3 = $db->createQueryBuilder();
        $rs = $qb3->select('arHandle')
            ->from('Areas')
            ->where('arIsGlobal = 1')
            ->andWhere('cID = :cID')
            ->setParameter('cID', $this->getCollectionID())
            ->execute()->fetchAll(FetchMode::COLUMN);
        if (count($rs) > 0) {
            $pcp = new Permissions($this);
            foreach ($rs as $garHandle) {
                if ($pcp->canViewPageVersions()) {
                    $s = Stack::getByName($garHandle, 'RECENT');
                } else {
                    $s = Stack::getByName($garHandle, 'ACTIVE');
                }
                if (is_object($s)) {
                    CacheLocal::set('pssCheck', $s->getCollectionID() . ':' . $s->getVersionID(), true);
                    $qb4 = $db->createQueryBuilder();
                    $rs1 = $qb4->select('bID', 'issID', 'arHandle')
                        ->from('CollectionVersionBlockStyles')
                        ->where('cID = :cID')
                        ->andWhere('cvID = :cvID')
                        ->andWhere('issID > 0')
                        ->setParameter('cID', $s->getCollectionID())
                        ->setParameter('cvID', $s->getVersionID())
                        ->execute()->fetchAll();
                    foreach ($rs1 as $r) {
                        $issID = $r['issID'];
                        $obj = StyleSet::getByID($issID);
                        if (is_object($obj)) {
                            $b = new Block();
                            $b->bID = $r['bID'];
                            $a = new GlobalArea($garHandle);
                            $b->setBlockAreaObject($a);
                            $obj = new BlockCustomStyle($obj, $b, $this->getCollectionThemeObject());
                            $psss[] = $obj;
                            CacheLocal::set(
                                      'pssObject',
                                      $s->getCollectionID() . ':' . $s->getVersionID() . ':' . $r['arHandle'] . ':' . $r['bID'],
                                      $obj
                            );
                        }
                    }
                }
            }
        }

        $styleHeader = '';
        foreach ($psss as $st) {
            $css = $st->getCSS();
            if ($css !== '') {
                $styleHeader .= $st->getStyleWrapper($css);
            }
        }

        if (strlen(trim($styleHeader))) {
            if ($return == true) {
                return $styleHeader;
            } else {
                $v = \View::getInstance();
                $v->addHeaderItem($styleHeader);
            }
        }
    }

    /**
     * Associate the edits of another collection to this collection.
     *
     * @param \Concrete\Core\Page\Collection\Collection $oc the collection that has been modified
     *
     * @return null|false return false if the other collection is already associated to this collection, NULL otherwise
     *
     * @example If a global area is modified inside this collection, you need to call $page->relateVersionEdits($globalArea)
     */
    public function relateVersionEdits($oc)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $r = (int) $qb = $qb->select('count(*)')
            ->from('CollectionVersionRelatedEdits')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('cRelationID = :cRelationID')
            ->andWhere('cvRelationID = :cvRelationID')
            ->setParameter('cID', $this->getCollectionID())
            ->setParameter('cvID', $this->getVersionID())
            ->setParameter('cRelationID', $oc->getCollectionID())
            ->setParameter('cvRelationID', $oc->getVersionID())
            ->execute()->fetchColumn();
        if ($r > 0) {
            return false;
        } else {
            $qb2 = $db->createQueryBuilder();
            $qb2->insert('CollectionVersionRelatedEdits')
                ->setValue('cID', $this->getCollectionID())
                ->setValue('cvID', $this->getVersionID())
                ->setValue('cRelationID', $oc->getCollectionID())
                ->setValue('cvRelationID', $oc->getVersionID())
                ->execute();
        }
    }

    /**
     * Returns the ID of the page/collection type.
     *
     * @return int|false
     */
    public function getPageTypeID()
    {
        return false;
    }

    /**
     * Empty the collection-related cache.
     */
    public function refreshCache()
    {
        CacheLocal::flush();
    }

    /**
     * Get the blocks contained in the all the global areas.
     *
     * @return \Concrete\Core\Block\Block[]
     */
    public function getGlobalBlocks()
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $rs = $qb->select('stName')
            ->from('Stacks')
            ->where('stType = :stType')
            ->setParameter('stType', Stack::ST_TYPE_GLOBAL_AREA)
            ->execute()->fetchAll(FetchMode::COLUMN);
        $blocks = [];
        if (count($rs) > 0) {
            $pcp = new Permissions($this);
            foreach ($rs as $garHandle) {
                if ($pcp->canViewPageVersions()) {
                    $s = Stack::getByName($garHandle, 'RECENT');
                } else {
                    $s = Stack::getByName($garHandle, 'ACTIVE');
                }
                if (is_object($s)) {
                    $blocksTmp = $s->getBlocks(STACKS_AREA_NAME);
                    $blocks = array_merge($blocks, $blocksTmp);
                }
            }
        }

        return $blocks;
    }

    /**
     * List the blocks in the currently loaded collection version (or in a specific area within it).
     *
     * @param string|false $arHandle The handle if the area (or falsy to get all the blocks in the collection)
     *
     * @return \Concrete\Core\Block\Block[]
     */
    public function getBlocks($arHandle = false)
    {
        $blockIDs = $this->getBlockIDs($arHandle);

        $blocks = [];
        if (is_array($blockIDs)) {
            foreach ($blockIDs as $row) {
                $ab = Block::getByID($row['bID'], $this, $row['arHandle']);
                if (is_object($ab)) {
                    $blocks[] = $ab;
                }
            }
        }

        return $blocks;
    }

    /**
     * List the block IDs and the associated area handles in the currently loaded collection version (or in a specific area within it).
     *
     * @param string|false $arHandle The handle if the area (or falsy to get all the blocks in the collection version)
     *
     * @return array Return a list of arrays, each one is a dictionary like ['bID' => <block ID>, 'arHandle' => <area handle>]
     */
    public function getBlockIDs($arHandle = false)
    {
        $blockIDs = CacheLocal::getEntry(
                              'collection_block_ids',
                              $this->getCollectionID() . ':' . $this->getVersionID()
        );

        if (!is_array($blockIDs)) {
            $app = Application::getFacadeApplication();
            /** @var Connection $db */
            $db = $app->make(Connection::class);
            $qb = $db->createQueryBuilder();
            $r = $qb->select('b.bID', 'cvb.arHandle')
                ->from('CollectionVersionBlocks', 'cvb')
                ->innerJoin('cvb', 'Blocks', 'b', 'cvb.bID = b.bID')
                ->where('cvb.cID = :cID')
                ->andWhere($qb->expr()->orX(
                    'cvb.cvID = :cvID',
                    'cvb.cbIncludeAll = 1'
                ))
                ->orderBy('cvb.cbDisplayOrder', 'asc')
                ->setParameter('cID', $this->getCollectionID())
                ->setParameter('cvID', $this->getVersionID())
                ->execute()->fetchAll();
            $blockIDs = [];
            if (is_array($r)) {
                foreach ($r as $bl) {
                    $blockIDs[strtolower($bl['arHandle'])][] = $bl;
                }
            }
            CacheLocal::set('collection_block_ids', $this->getCollectionID() . ':' . $this->getVersionID(), $blockIDs);
        }

        $result = [];
        if ($arHandle != false) {
            $key = strtolower($arHandle);
            if (isset($blockIDs[$key])) {
                $result = $blockIDs[$key];
            }
        } else {
            foreach ($blockIDs as $arHandle => $row) {
                foreach ($row as $brow) {
                    if (!in_array($brow, $blockIDs)) {
                        $result[] = $brow;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * Add a new block to a specific area of the currently loaded collection version.
     *
     * @param \Concrete\Core\Entity\Block\BlockType\BlockType $bt the type of block to be added
     * @param string|\Concrete\Core\Area\Area $a the area instance (or its handle) to which the block should be added to
     * @param array $data The data of the block. This data depends on the specific block type. Common values are: 'uID' to specify the ID of the author (if not specified: we'll use the current user), 'bName' to specify the block name.
     *
     * @return \Concrete\Core\Block\Block
     */
    public function addBlock($bt, $a, $data)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);

        // first we add the block to the system
        $nb = $bt->add($data, $this, $a);

        // now that we have a block, we add it to the collectionversions table

        $arHandle = (is_object($a)) ? $a->getAreaHandle() : $a;
        $cID = $this->getCollectionID();
        $vObj = $this->getVersionObject();

        if ($bt->includeAll()) {
            // normally, display order is dependant on a per area, per version basis. However, since this block
            // is not aliased across versions, then we want to get display order simply based on area, NOT based
            // on area + version
            $newBlockDisplayOrder = $this->getCollectionAreaDisplayOrder(
                                         $arHandle,
                                         true
            ); // second argument is "ignoreVersions"
        } else {
            $newBlockDisplayOrder = $this->getCollectionAreaDisplayOrder($arHandle);
        }

        $qb = $db->createQueryBuilder();
        $cbRelationID = (int) $qb->select('max(cbRelationID)')->from('CollectionVersionBlocks')
            ->execute()->fetchColumn();
        if (!$cbRelationID) {
            $cbRelationID = 1;
        } else {
            ++$cbRelationID;
        }

        $qb2 = $db->createQueryBuilder();
        $res = $qb2->insert('CollectionVersionBlocks')
            ->setValue('cID', ':cID')
            ->setValue('cvID', ':cvID')
            ->setValue('bID', ':bID')
            ->setValue('arHandle', ':arHandle')
            ->setValue('cbRelationID', ':cbRelationID')
            ->setValue('cbDisplayOrder', ':cbDisplayOrder')
            ->setValue('isOriginal', 1)
            ->setValue('cbIncludeAll', ':cbIncludeAll')
            ->setParameter('cID', $cID)
            ->setParameter('cvID', $vObj->getVersionID())
            ->setParameter('bID', $nb->getBlockID())
            ->setParameter('arHandle', $arHandle)
            ->setParameter('cbRelationID', $cbRelationID)
            ->setParameter('cbDisplayOrder', $newBlockDisplayOrder)
            ->setParameter('cbIncludeAll', (int) ($bt->includeAll()))
            ->execute();

        return Block::getByID($nb->getBlockID(), $this, $a);
    }

    /**
     * Get the next value of the display order (to be used when adding new blocks to an area).
     *
     * @param string $arHandle The handle of the area
     * @param bool $ignoreVersions Set to true to ignore the collection version
     *
     * @return int
     */
    public function getCollectionAreaDisplayOrder($arHandle, $ignoreVersions = false)
    {
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $cID = $this->cID;
        $cvID = $this->vObj->cvID;
        if ($ignoreVersions) {
            $qb->select('max(cbDisplayOrder) as cbdis')
                ->from('CollectionVersionBlocks')
                ->where('cID = :cID')
                ->andWhere('arHandle = :arHandle')
                ->setParameter('cID', $cID)
                ->setParameter('arHandle', $arHandle);
        } else {
            $qb->select('max(cbDisplayOrder) as cbdis')
                ->from('CollectionVersionBlocks')
                ->where('cID = :cID')
                ->andWhere('cvID = :cvID')
                ->andWhere('arHandle = :arHandle')
                ->setParameter('cID', $cID)
                ->setParameter('cvID', $cvID)
                ->setParameter('arHandle', $arHandle);
        }
        /** @var PDOStatement $r */
        $r = $qb->execute();
        if ($r) {
            if ($r->rowCount() > 0) {
                // then we know we got a value; we increment it and return
                $res = $r->fetchAssociative();
                $displayOrder = $res['cbdis'];
                if ($displayOrder === null) {
                    return 0;
                }
                ++$displayOrder;

                return $displayOrder;
            } else {
                // we didn't get anything, so we return a zero
                return 0;
            }
        }
    }

    /**
     * Fix the display order properties for all the blocks within the collection/area.
     *
     * @param string $arHandle the handle of the area to be processed
     */
    public function rescanDisplayOrder($arHandle)
    {
        // this collection function f

        $cID = $this->cID;
        $cvID = $this->vObj->cvID;
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $r = $qb->select('bID')
            ->from('CollectionVersionBlocks')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('arHandle = :arHandle')
            ->orderBy('cbDisplayOrder', 'asc')
            ->setParameter('cID', $cID)
            ->setParameter('cvID', $cvID)
            ->setParameter('arHandle', $arHandle)
            ->execute();

        if ($r) {
            $displayOrder = 0;
            while ($row = $r->fetch()) {
                $qb2 = $db->createQueryBuilder();
                $qb2->update('CollectionVersionBlocks')
                    ->set('cbDisplayOrder', ':cbDisplayOrder')
                    ->where('cID = :cID')
                    ->andWhere('cvID = :cvID')
                    ->andWhere('arHandle = :arHandle')
                    ->andWhere('bID = :bID')
                    ->setParameter('cbDisplayOrder', $displayOrder)
                    ->setParameter('cID', $cID)
                    ->setParameter('cvID', $cvID)
                    ->setParameter('arHandle', $arHandle)
                    ->setParameter('bID', $row['bID'])
                    ->execute();
                ++$displayOrder;
            }
        }
    }

    /**
     * Fix the display order properties for all the blocks after this block in this area.
     * This is useful for forcing a certain block order.
     * @param Block $block the block to begin the display order rescan from
     * @param string $arHandle the handle of the area to be processed
     * @param int|null $fromDisplay an optional integer to override the starting number,
     *                              i.e start from 0 even though our block is 8
     * @return void
     * @throws \Doctrine\DBAL\Driver\Exception|\Doctrine\DBAL\Exception
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function rescanDisplayOrderFromBlock(Block $block, string $arHandle, int $fromDisplay = null)
    {
        /** This block doesnt have a display order */
        if ($block->getBlockDisplayOrder() === null) {
            return $this->rescanDisplayOrder($arHandle);
        }
        $fromDisplay = $fromDisplay ?? $block->getBlockDisplayOrder();
        $cID = $this->cID;
        $cvID = $this->vObj->cvID;
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $qb = $db->createQueryBuilder();
        $r =$qb->select('bID')
            ->from('CollectionVersionBlocks')
            ->where('cID = :cID')
            ->andWhere('cvID = :cvID')
            ->andWhere('bID != :bID')
            ->andWhere('cbDisplayOrder >= :cbDisplay')
            ->andWhere('arHandle = :arHandle')
            ->orderBy('cbDisplayOrder', 'asc')
            ->setParameter('cbDisplay', $fromDisplay)
            ->setParameter('bID', $block->getBlockID())
            ->setParameter('cID', $cID)
            ->setParameter('cvID', $cvID)
            ->setParameter('arHandle', $arHandle)
            ->execute();

        if ($r) {
            $currentDisplayOrder = $block->getBlockDisplayOrder();
            $displayOrder = $fromDisplay;
            while ($row = $r->fetchAssociative()) {
                if ($displayOrder === $currentDisplayOrder) {
                    // Skip our blocks display order
                    $displayOrder++;
                }
                $qb2 = $db->createQueryBuilder();
                $qb2->update('CollectionVersionBlocks')
                    ->set('cbDisplayOrder', ':cbDisplayOrder')
                    ->where('cID = :cID')
                    ->andWhere('cvID = :cvID')
                    ->andWhere('arHandle = :arHandle')
                    ->andWhere('bID = :bID')
                    ->setParameter('cbDisplayOrder', $displayOrder)
                    ->setParameter('cID', $cID)
                    ->setParameter('cvID', $cvID)
                    ->setParameter('arHandle', $arHandle)
                    ->setParameter('bID', $row['bID'])
                    ->execute();
                ++$displayOrder;
            }
        }
    }

    /**
     * Update the last edit date/time.
     */
    public function markModified()
    {
        // marks this collection as newly modified
        $app = Application::getFacadeApplication();
        /** @var Connection $db */
        $db = $app->make(Connection::class);
        $dh = Loader::helper('date');
        $cDateModified = $dh->getOverridableNow();

        $qb = $db->createQueryBuilder();
        $res = $qb->update('Collections')
            ->set('cDateModified', ':cDateModified')
            ->where('cID = :cID')
            ->setParameter('cDateModified', $cDateModified)
            ->setParameter('cID', $this->getCollectionID())
            ->execute();
    }

    /**
     * Delete this collection, and all its versions, contents and attributes.
     */
    public function delete()
    {
        if ($this->cID > 0) {
            $app = Application::getFacadeApplication();
            /** @var Connection $db */
            $db = $app->make(Connection::class);

            // First we delete all versions
            $vl = new VersionList($this);
            $vl->setItemsPerPage(-1);
            $vlArray = $vl->getPage();

            foreach ($vlArray as $v) {
                $v->delete();
            }

            $cID = $this->getCollectionID();

            $qb = $db->createQueryBuilder();
            $qb->delete('CollectionAttributeValues')
                ->where('cID = :cID')
                ->setParameter('cID', $cID)
                ->execute();

            $qb = $db->createQueryBuilder();
            $qb->delete('Collections')
                ->where('cID = :cID')
                ->setParameter('cID', $cID)
                ->execute();

            try {
                $qb = $db->createQueryBuilder();
                $qb->delete('CollectionSearchIndexAttributes')
                    ->where('cID = :cID')
                    ->setParameter('cID', $cID)
                    ->execute();
            } catch (\Exception $e) {
            }
        }
    }

    /**
     * Create a clone of this collection, and all its versions, contents and attributes.
     *
     * @return \Concrete\Core\Page\Collection\Collection
     */
    public function duplicateCollection()
    {
        $app = Application::getFacadeApplication();
        $cloner = $app->make(Cloner::class);
        $clonerOptions = $app->build(ClonerOptions::class)->setKeepOriginalAuthor(true);
        $newCollection = $cloner->cloneCollection($this, $clonerOptions);

        return $newCollection;
    }

    /**
     * Clone the currently loaded version and returns a Page instance containing the new version.
     *
     * @param string|null $versionComments the comments to be associated to the new Version
     * @param bool $createEmpty set to true to create a Version without any blocks/area styles, false to clone them too
     *
     * @return \Concrete\Core\Page\Page
     */
    public function cloneVersion($versionComments, $createEmpty = false)
    {
        $app = Application::getFacadeApplication();
        $cloner = $app->make(Cloner::class);
        $clonerOptions = $app->make(ClonerOptions::class)
            ->setVersionComments($versionComments)
            ->setCopyContents($createEmpty ? false : true)
        ;
        $newVersion = $cloner->cloneCollectionVersion($this->getVersionObject(), $this, $clonerOptions);

        return Page::getByID($newVersion->getCollectionID(), $newVersion->getVersionID());
    }

    /**
     * @deprecated Use of getAttributeValueObject()
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $ak
     *
     * @return \Concrete\Core\Entity\Attribute\Value\PageValue|null
     */
    public function getAttributeValue($ak)
    {
        return $this->getAttributeValueObject($ak);
    }

    /**
     * @deprecated use the getAttribute() method
     *
     * @param string|\Concrete\Core\Attribute\Key\CollectionKey $akHandle
     *
     * @return mixed|null
     */
    public function getCollectionAttributeValue($akHandle)
    {
        return $this->getAttribute($akHandle);
    }

    /**
     * @deprecated use the getPageTypeID() method
     */
    public function getCollectionTypeID()
    {
        return $this->getPageTypeID();
    }
}


text:
<?php
namespace ImageStack\ImageBackend;

use ImageStack\Api\ImageBackendInterface;
use ImageStack\Api\ImagePathInterface;
use ImageStack\OptionnableTrait;
use ImageStack\Api\Exception\ImageNotFoundException;

/**
 * Sequential image backend.
 * Sequentialy fetches images from a queue of image backends and returns the first match.
 */
class SequentialImageBackend implements ImageBackendInterface
{
    use OptionnableTrait;

    /**
     * Sequential image backend constructor.
     *
     * @param ImageBackendInterface[] $imageBackends a queue of image backends
     * @param array $options
     */
    public function __construct(array $imageBackends = [], $options = array())
    {
        foreach ($imageBackends as $imageBackend) {
            $this->addImageBackend($imageBackend);
        }
        $this->setOptions($options);
    }

    public function fetchImage(ImagePathInterface $path)
    {
        foreach ($this->imageBadkends as $imageBackend) {
            try {
                if ($image = $imageBackend->fetchImage($path)) {
                    return $image;
                }
            } catch (ImageNotFoundException $e) {
                //nothing
            }
        }
        throw new ImageNotFoundException(sprintf('Image Not Found : %s', $path->getPath()));
    }

    /**
     * @var ImageBackendInterface[]
     */
    protected $imageBadkends = [];

    /**
     * Append an image backend.
     * @param ImageBackendInterface $imageBackend
     * @throws \InvalidArgumentException
     */
    public function addImageBackend(ImageBackendInterface $imageBackend)
    {
        if ($imageBackend === $this) {
            throw new \InvalidArgumentException('Recursion error');
        }
        $this->imageBadkends[] = $imageBackend;
    }
}

redpajama_set_name: RedPajamaGithub


text:
[jvm]
Content
fun [CodeRepresentation](-code-representation.md)(representation: [KoresPart](../../../../com.github.jonathanxd.kores/-kores-part/index.md))
More info

## Parameters

jvm

|  Name|  Summary|
|---|---|
| representation|

Code representation.


text:
<?php
/*
 * By ptr.nov
 * Load Config CSS/JS
 */
/* YII CLASS */
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\Breadcrumbs;

/* TABLE CLASS DEVELOPE -> |DROPDOWN,PRIMARYKEY-> ATTRIBUTE */
use app\models\hrd\Userlogin;
/*	KARTIK WIDGET -> Penambahan componen dari yii2 dan nampak lebih cantik*/
use kartik\grid\GridView;
use kartik\widgets\ActiveForm;
use kartik\tabs\TabsX;
use kartik\date\DatePicker;
use kartik\builder\Form;

use backend\assets\AppAsset; 	/* CLASS ASSET CSS/JS/THEME Author: -ptr.nov-*/
AppAsset::register($this);		/* INDEPENDENT CSS/JS/THEME FOR PAGE  Author: -ptr.nov-*/

/* add Menu Author: -ptr.nov-*/
$this->sideMenu = 'admin';
/*Title page Modul*/
$this->title = Yii::t('app', 'Department');
$this->params['breadcrumbs'][] = $this->title;
?>

		<?php
			/*DEPARTMENT Author: -ptr.nov */
			//print_r($dataProvider);
			echo GridView::widget([
				'dataProvider' => $dataProvider_Userlogin,
				'filterModel' => $searchModel_Userlogin,
				'columns' => [
					['class' => 'yii\grid\SerialColumn'],
					'id',
					'username',
					'auth_key',
					//'password_hash',
					//'password_reset_token',
					'email',
					'status',
					'created_at',
					'updated_at',
					'EMP_ID',
					'avatar',
					'avatarImage',
					[
						'class' => 'yii\grid\ActionColumn',
						'template' => '{view}',
					],
				],
				'panel'=>[
					'heading' =>false,// $hdr,//
<h8>'. $hdr .'</h8>
',
					'type' =>GridView::TYPE_SUCCESS,//TYPE_WARNING, //TYPE_DANGER, //GridView::TYPE_SUCCESS,//GridView::TYPE_INFO, //TYPE_PRIMARY, TYPE_INFO
					'before'=>Html::a(' '.Yii::t('app', 'Create {modelClass}',
					['modelClass' => 'User Login',]),
					['create'], ['class' => 'btn btn-success']),
				],
				'hover'=>true, //cursor selec
				'responsive'=>true,
				'bordered'=>true,
				'striped'=>true,
			]);
		?>


text:
package com.opengamma.engine.view.worker.cache;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.CacheBuilder;
import com.opengamma.engine.view.compilation.CompiledViewDefinitionWithGraphs;

/**
 * A trivial in-memory cache. This should be used for test infrastructure only; a cache that can spool to disk would probably be better.
 */
public class InMemoryViewExecutionCache implements ViewExecutionCache {

  private static final Logger LOGGER = LoggerFactory.getLogger(InMemoryViewExecutionCache.class);

  /**
   * The buffer to hold compiled view definitions.
   */
  private final Map<ViewExecutionCacheKey, CompiledViewDefinitionWithGraphs> _compiledViewDefinitions = CacheBuilder.newBuilder().softValues()
      .<ViewExecutionCacheKey, CompiledViewDefinitionWithGraphs> build()
      .asMap();

  @Override
  public CompiledViewDefinitionWithGraphs getCompiledViewDefinitionWithGraphs(final ViewExecutionCacheKey key) {
    final CompiledViewDefinitionWithGraphs viewDefinition = _compiledViewDefinitions.get(key);
    if (LOGGER.isDebugEnabled()) {
      if (viewDefinition == null) {
        LOGGER.debug("Cache miss CompiledViewDefinitionWithGraphs for {}", key);
      } else {
        LOGGER.debug("Cache hit CompiledViewDefinitionWithGraphs for {}", key);
      }
    }
    return viewDefinition;
  }

  @Override
  public void setCompiledViewDefinitionWithGraphs(final ViewExecutionCacheKey key, final CompiledViewDefinitionWithGraphs viewDefinition) {
    LOGGER.info("Storing CompiledViewDefinitionWithGraphs for {}", key);
    _compiledViewDefinitions.put(key, viewDefinition);
  }

  @Override
  public void clear() {
    LOGGER.info("Clearing all CompiledViewDefinitionWithGraphs");
    _compiledViewDefinitions.clear();
  }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.databox.models;

import com.azure.resourcemanager.databox.fluent.models.SkuInformationInner;
import java.util.List;

/** An immutable client-side representation of SkuInformation. */
public interface SkuInformation {
    /**
     * Gets the sku property: The Sku.
     *
     * @return the sku value.
     */
    Sku sku();

    /**
     * Gets the enabled property: The sku is enabled or not.
     *
     * @return the enabled value.
     */
    Boolean enabled();

    /**
     * Gets the dataLocationToServiceLocationMap property: The map of data location to service location.
     *
     * @return the dataLocationToServiceLocationMap value.
     */
    List<DataLocationToServiceLocationMap> dataLocationToServiceLocationMap();

    /**
     * Gets the capacity property: Capacity of the Sku.
     *
     * @return the capacity value.
     */
    SkuCapacity capacity();

    /**
     * Gets the costs property: Cost of the Sku.
     *
     * @return the costs value.
     */
    List<SkuCost> costs();

    /**
     * Gets the apiVersions property: Api versions that support this Sku.
     *
     * @return the apiVersions value.
     */
    List<String> apiVersions();

    /**
     * Gets the disabledReason property: Reason why the Sku is disabled.
     *
     * @return the disabledReason value.
     */
    SkuDisabledReason disabledReason();

    /**
     * Gets the disabledReasonMessage property: Message for why the Sku is disabled.
     *
     * @return the disabledReasonMessage value.
     */
    String disabledReasonMessage();

    /**
     * Gets the requiredFeature property: Required feature to access the sku.
     *
     * @return the requiredFeature value.
     */
    String requiredFeature();

    /**
     * Gets the inner com.azure.resourcemanager.databox.fluent.models.SkuInformationInner object.
     *
     * @return the inner object.
     */
    SkuInformationInner innerModel();
}


text:
@extends('layout')

@section('content')
@stop


text:
/*! \file Severity.cpp Definitions for Severity NamedEnum
  *
  */

#include "Severity.h"

DEFINE_ENUMERATION(Severity, SEVERITY_ENUM)

QChar Severity::toChar(void) const
{
    static const QString chars("})|([~+.XXX <>-=!*?$&$$#%%@@@@{");
    return (value() >= 0 && value() < chars.size())
            ? chars.at(value())
            : QChar('?');
}

bool Severity::isFatal(void) const
{
    return value() >= Pointer;
}

bool Severity::isError(void) const
{
    return value() >= Error;
}

bool Severity::isWarning(void) const
{
    return value() >= ToDo;
}


text:
package com.xb.windowandwindowmanager;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see Testing documentation
 */
public class ExampleUnitTest
{
    @Test
    public void addition_isCorrect() throws
                                     Exception
    {
        assertEquals(4, 2 + 2);
    }
}


text:
var config  = require("config");
var http    = require("http");
var logger  = require("logger").get("plugins.pushbullet");
var session = require("bittorrent").session;

// Configuration
var url   = "https://api.pushbullet.com/v2/pushes";
var token = config.getString("extensions.pushbullet.token");

function pushNote(title, body) {
    var data = {
        title: title,
        body: body,
        type: "note"
    };

    var response = http.post(url, JSON.stringify(data), {
        headers: {
            "Authorization": "Bearer " + token,
            "Content-Type":  "application/json"
        }
    });

    if(response.status !== 200) {
        logger.error("Failed to push note to Pushbullet: " + response.reason);
    }
}

function load() {
    var enabled = config.getBoolean("extensions.pushbullet.enabled");

    if(!enabled) {
        return;
    }

    if(!token) {
        logger.warn("No token configured.");
        return;
    }

    var events = config.get("extensions.pushbullet.enabledEvents");
    logger.info("Pushbullet enabled with " + events.length + " enabled events.");

    if(events.indexOf("torrent.added") > -1) {
        session.on("torrent.added", function(args) {
            var status = args.torrent.getStatus();
            pushNote("Torrent added", "Torrent '" + status.name + "' was added.");
        });
    }

    if(events.indexOf("torrent.finished") > -1) {
        session.on("torrent.finished", function(args) {
            var status = args.torrent.getStatus();
            pushNote("Torrent finished", "Torrent '" + status.name + "' finished downloading.");
        });
    }

    if(events.indexOf("hadouken.loaded") > -1) {
        pushNote("Hadouken loaded", "Hadouken just started up.");
    }
}

exports.load = load;


text:
<?php

include_once 'db_con.php';
include_once 'global.php';
include_once 'function.php';

if (is_setup($db)) {
	header("Location: register.php");
}

?>

		<title>ScheDemo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

		<link href="static/components/normalize-css/normalize.css" rel="stylesheet" />

		<link href="static/components/github-fork-ribbon-css/gh-fork-ribbon.css" rel="stylesheet" />

		<link href="static/components/semantic/build/packaged/css/semantic.min.css" rel="stylesheet" />

		<link href="static/css/style.css" rel="stylesheet" />

						Fork me on GitHub

ScheDemo

An application for scheduling.

Start

Powered by ScheDemo.


text:
Seiten Crawler
==============

*(since 1.0.0-alpha13 release)*

Um das Cralwer Module einzufügen gibts du folgende konfiguration an:

```php
'crawler' => [
    'class' => 'crawler\Module',
    'baseUrl' => 'http://luya.io',
],
'crawleradmin' => 'crawleradmin\Module',
```

wobie die `baseUrl` der URL entspricht welche deinen Such-Index aufbauen soll.

Ausführen
---------

Damit deine suche gestartet wird erstellst du am besten einen *Cron-job* der jede Nacht läuft mit dem auszuführenden COmmand:

```sh
php index.php command crawler crawl
```


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc.security;

import com.yahoo.cloud.config.SentinelConfig;
import com.yahoo.concurrent.DaemonThreadFactory;
import com.yahoo.config.FileReference;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.config.provision.security.NodeIdentifierException;
import com.yahoo.config.provision.security.NodeIdentity;
import com.yahoo.jrt.Request;
import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.TransportSecurityUtils;
import com.yahoo.security.tls.ConnectionAuthContext;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
import com.yahoo.vespa.config.server.RequestHandler;
import com.yahoo.vespa.config.server.host.HostRegistry;
import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider;

import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.yahoo.vespa.config.server.rpc.security.AuthorizationException.Type;
import static com.yahoo.yolean.Exceptions.throwUnchecked;

/**
 * A {@link RpcAuthorizer} that perform access control for configserver RPC methods when TLS and multi-tenant mode are enabled.
 *
 * @author bjorncs
 */
public class MultiTenantRpcAuthorizer implements RpcAuthorizer {

    private static final Logger log = Logger.getLogger(MultiTenantRpcAuthorizer.class.getName());

    private final NodeIdentifier nodeIdentifier;
    private final HostRegistry hostRegistry;
    private final RequestHandlerProvider handlerProvider;
    private final Executor executor;

    public MultiTenantRpcAuthorizer(NodeIdentifier nodeIdentifier,
                                    HostRegistry hostRegistry,
                                    RequestHandlerProvider handlerProvider,
                                    int threadPoolSize) {
        this(nodeIdentifier,
             hostRegistry,
             handlerProvider,
             Executors.newFixedThreadPool(threadPoolSize, new DaemonThreadFactory("multi-tenant-rpc-authorizer-")));
    }

    MultiTenantRpcAuthorizer(NodeIdentifier nodeIdentifier,
                             HostRegistry hostRegistry,
                             RequestHandlerProvider handlerProvider,
                             Executor executor) {
        this.nodeIdentifier = nodeIdentifier;
        this.hostRegistry = hostRegistry;
        this.handlerProvider = handlerProvider;
        this.executor = executor;
    }

    @Override
    public CompletableFuture<Void> authorizeConfigRequest(Request request) {
        return doAsyncAuthorization(request, this::doConfigRequestAuthorization);
    }

    @Override
    public CompletableFuture<Void> authorizeFileRequest(Request request) {
        return doAsyncAuthorization(request, this::doFileRequestAuthorization);
    }

    private CompletableFuture<Void> doAsyncAuthorization(Request request, BiConsumer<Request, NodeIdentity> authorizer) {
        return CompletableFuture.runAsync(
                () -> {
                    try {
                        getPeerIdentity(request)
                                .ifPresent(peerIdentity -> authorizer.accept(request, peerIdentity));
                        log.log(Level.FINE, () -> String.format("Authorization succeeded for request '%s' from '%s'",
                                                                   request.methodName(), request.target().toString()));
                    } catch (Throwable t) {
                        handleAuthorizationFailure(request, t);
                    }
                },
                executor);
    }

    private void doConfigRequestAuthorization(Request request, NodeIdentity peerIdentity) {
        switch (peerIdentity.nodeType()) {
            case config:
                return; // configserver is allowed to access all config
            case proxy:
            case tenant:
            case host:
                JRTServerConfigRequestV3 configRequest = JRTServerConfigRequestV3.createFromRequest(request);
                ConfigKey<?> configKey = configRequest.getConfigKey();
                if (isConfigKeyForGlobalConfig(configKey)) {
                    GlobalConfigAuthorizationPolicy.verifyAccessAllowed(configKey, peerIdentity.nodeType());
                    return; // global config access ok
                } else {
                    String hostname = configRequest.getClientHostName();
                    ApplicationId applicationId = hostRegistry.getKeyForHost(hostname);
                    if (applicationId == null) {
                        if (isConfigKeyForSentinelConfig(configKey)) {
                            return; // config processor will return empty sentinel config for unknown nodes
                        }
                        throw new AuthorizationException(Type.SILENT, String.format("Host '%s' not found in host registry for [%s]", hostname, configKey));
                    }
                    RequestHandler tenantHandler = getTenantHandler(applicationId.tenant());
                    ApplicationId resolvedApplication = tenantHandler.resolveApplicationId(hostname);
                    ApplicationId peerOwner = applicationId(peerIdentity);
                    if (peerOwner.equals(resolvedApplication)) {
                        return; // allowed to access
                    }
                    throw new AuthorizationException(
                            String.format(
                                    "Peer is not allowed to access config owned by %s. Peer is owned by %s",
                                    resolvedApplication.toShortString(), peerOwner.toShortString()));
                }
            default:
                throw new AuthorizationException(String.format("'%s' nodes are not allowed to access config", peerIdentity.nodeType()));
        }
    }

    private void doFileRequestAuthorization(Request request, NodeIdentity peerIdentity) {
        switch (peerIdentity.nodeType()) {
            case config:
                return; // configserver is allowed to access all files
            case proxy:
            case tenant:
            case host:
                ApplicationId peerOwner = applicationId(peerIdentity);
                FileReference requestedFile = new FileReference(request.parameters().get(0).asString());
                RequestHandler tenantHandler = getTenantHandler(peerOwner.tenant());
                Set<FileReference> filesOwnedByApplication = tenantHandler.listFileReferences(peerOwner);
                if (filesOwnedByApplication.contains(requestedFile)) {
                    return; // allowed to access
                }
                throw new AuthorizationException(
                        String.format("Peer is not allowed to access file reference %s. Peer is owned by %s. File references owned by this application: %s",
                                      requestedFile.value(), peerOwner.toShortString(), filesOwnedByApplication));
            default:
                throw new AuthorizationException(String.format("'%s' nodes are not allowed to access files", peerIdentity.nodeType()));
        }
    }

    private void handleAuthorizationFailure(Request request, Throwable throwable) {
        boolean isAuthorizationException = throwable instanceof AuthorizationException;
        String errorMessage = String.format("For request '%s' from '%s': %s", request.methodName(), request.target().toString(), throwable.getMessage());
        if (!isAuthorizationException || ((AuthorizationException) throwable).type() != Type.SILENT) {
            log.log(Level.INFO, errorMessage);
        }
        log.log(Level.FINE, throwable, throwable::getMessage);
        JrtErrorCode error = isAuthorizationException ? JrtErrorCode.UNAUTHORIZED : JrtErrorCode.AUTHORIZATION_FAILED;
        request.setError(error.code, errorMessage);
        request.returnRequest();
        throw throwUnchecked(throwable); // rethrow exception to ensure that subsequent completion stages are not executed (don't execute implementation of rpc method).
    }

    // TODO Make peer identity mandatory once TLS mixed mode is removed
    private Optional<NodeIdentity> getPeerIdentity(Request request) {
        ConnectionAuthContext authCtx = request.target().connectionAuthContext();
        if (authCtx.peerCertificate().isEmpty()) {
            if (TransportSecurityUtils.getInsecureMixedMode() == MixedMode.DISABLED) {
                throw new IllegalStateException("Security context missing"); // security context should always be present
            }
            return Optional.empty(); // client choose to communicate over insecure channel
        }
        List<X509Certificate> certChain = authCtx.peerCertificateChain();
        if (certChain.isEmpty()) {
            throw new IllegalStateException("Client authentication is not enforced!"); // clients should be required to authenticate when TLS is enabled
        }
        try {
            NodeIdentity identity = nodeIdentifier.identifyNode(certChain);
            log.log(Level.FINE, () -> String.format("Client '%s' identified as %s", request.target().toString(), identity.toString()));
            return Optional.of(identity);
        } catch (NodeIdentifierException e) {
            throw new AuthorizationException("Failed to identify peer: " + e.getMessage(), e);
        }
    }

    private static boolean isConfigKeyForGlobalConfig(ConfigKey<?> configKey) {
        return "*".equals(configKey.getConfigId());
    }

    private static boolean isConfigKeyForSentinelConfig(ConfigKey<?> configKey) {
        return SentinelConfig.getDefName().equals(configKey.getName())
                && SentinelConfig.getDefNamespace().equals(configKey.getNamespace());
    }

    private static ApplicationId applicationId(NodeIdentity peerIdentity) {
        return peerIdentity.applicationId()
                .orElseThrow(() -> new AuthorizationException("Peer node is not associated with an application: " + peerIdentity.toString()));
    }

    private RequestHandler getTenantHandler(TenantName tenantName) {
        return handlerProvider.getRequestHandler(tenantName)
                .orElseThrow(() -> new AuthorizationException(String.format("No handler exists for tenant '%s'", tenantName.value())));
    }

    private enum JrtErrorCode {
        UNAUTHORIZED(1),
        AUTHORIZATION_FAILED(2);

        final int code;

        JrtErrorCode(int errorOffset) {
            this.code = 0x20000 + errorOffset;
        }
    }

}


text:
@class Invoice;

#define kDefaultFontSize 18
#define kContentFontSize 17
#define kTimeFontSize 12

@interface InvoiceWithFrame : NSObject
@property (nonatomic, strong) Invoice *invoice;
@property (nonatomic, assign) CGRect  containerViewFrame;
@property (nonatomic, assign) CGRect  containerViewFrame_expand;
@property (nonatomic, assign) CGRect  dateLabelFrame;
@property (nonatomic, assign) CGRect  amountLabelFrame;
@property (nonatomic, assign) CGRect  placeLabelFrame;
@property (nonatomic, assign) CGRect  resultLabelFrame;
@property (nonatomic, assign) CGRect  detailsLabelFrame;
@property (nonatomic, assign) CGRect  detailsLabelFrame_expand;
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, assign) CGFloat cellHeight_expand;

- (instancetype)initWithInvoice:(Invoice *)invoice;

@end


text:
require_dependency "inyx_employees_rails/application_controller"

module InyxEmployeesRails
  class EmployeesController < ApplicationController
    # Configuración para autenticación, true autentica todas las acciones, false permite solo las acciones new, create, show_front
    InyxEmployeesRails.authenticate ? before_filter(:authenticate_user!) : before_filter(:authenticate_user!, except: [:new, :create, :show_front])

    before_action :set_employee, only: [:show, :edit, :update]
    layout :resolve_layout
    respond_to :json
    # GET /employees
    def index
    end

    def angular_index
      employees = Employee.all.order('created_at DESC')
      respond_with(employees) do |format|
        format.json { render :json => employees.as_json }
      end
    end

    # GET /employees/1
    def show
    end

    def show_front
      @employee = Employee.find(params[:id])
    end

    # GET /employees/new
    def new
      @employee = Employee.new
      @url = "/employees"
      @method = 'POST'
    end

    # GET /employees/1/edit
    def edit
      @url = "/admin/employees/#{params[:id]}"
      @route = @method = 'PUT'
    end

    # POST /employees
    def create
      @url = "/employees"
      @employee = Employee.new(employee_params)

      if @employee.save
        EmployeeMailer.notification(@employee).deliver
        EmployeeMailer.notification_client(@employee).deliver
        redirect_to employee_front_path(@employee.id), notice: t("notification.create")
      else
        render :new
      end
    end

    # PATCH/PUT /employees/1
    def update
      if @employee.update(employee_params)
        redirect_to @employee, notice: t("notification.update")
      else
        render :edit
      end
    end

    def destroy
      authorize! :index, @user, :message => 'Not authorized as an administrator.'
      Employee.find(params[:id]).destroy
      respond_to do |format|
        format.html { redirect_to employees_url, notice: t("notification.delete") }
        format.json { head :no_content }
      end
    end

    # DELETE /employees/1
    def delete
      Employee.destroy( redefine_destroy params[:ids].split(",") )
      respond_to do |format|
        format.html { redirect_to employees_path, notice: t("notification.delete") }
      end
    end

    private

      #metodo para redefinir el array de los elementos selecionados que se van a eliminar
      def redefine_destroy(params)
        params.sort.each do |id|
          params.delete id unless Employee.exists? id
        end
      end

      # Use callbacks to share common setup or constraints between actions.
      def set_employee
        @employee = Employee.find(params[:id])
      end

      # Only allow a trusted parameter "white list" through.
      def employee_params
        params.require(:employee).permit(:rif, :names, :last_names, :sex, :email, :birth, :phone, :mobile, :adress, :academic_level, :profession, :experience, :summary_aptitudes, :summary_courses, :summary_works)
      end

      def resolve_layout
        case action_name
          when "new", "show_front", "create"
            "application"
          else
            "admin/application"
        end
      end

  end
end


text:
package botservice

import original "github.com/Azure/azure-sdk-for-go/services/preview/botservice/mgmt/2018-07-12/botservices"

type BotConnectionClient = original.BotConnectionClient
type BotsClient = original.BotsClient
type ChannelsClient = original.ChannelsClient

const (
	DefaultBaseURI = original.DefaultBaseURI
)

type BaseClient = original.BaseClient
type EnterpriseChannelsClient = original.EnterpriseChannelsClient
type ChannelName = original.ChannelName

const (
	ChannelNameDirectLineChannel ChannelName = original.ChannelNameDirectLineChannel
	ChannelNameEmailChannel      ChannelName = original.ChannelNameEmailChannel
	ChannelNameFacebookChannel   ChannelName = original.ChannelNameFacebookChannel
	ChannelNameKikChannel        ChannelName = original.ChannelNameKikChannel
	ChannelNameMsTeamsChannel    ChannelName = original.ChannelNameMsTeamsChannel
	ChannelNameSkypeChannel      ChannelName = original.ChannelNameSkypeChannel
	ChannelNameSlackChannel      ChannelName = original.ChannelNameSlackChannel
	ChannelNameSmsChannel        ChannelName = original.ChannelNameSmsChannel
	ChannelNameTelegramChannel   ChannelName = original.ChannelNameTelegramChannel
	ChannelNameWebChatChannel    ChannelName = original.ChannelNameWebChatChannel
)

type ChannelNameBasicChannel = original.ChannelNameBasicChannel

const (
	ChannelNameChannel            ChannelNameBasicChannel = original.ChannelNameChannel
	ChannelNameDirectLineChannel1 ChannelNameBasicChannel = original.ChannelNameDirectLineChannel1
	ChannelNameEmailChannel1      ChannelNameBasicChannel = original.ChannelNameEmailChannel1
	ChannelNameFacebookChannel1   ChannelNameBasicChannel = original.ChannelNameFacebookChannel1
	ChannelNameKikChannel1        ChannelNameBasicChannel = original.ChannelNameKikChannel1
	ChannelNameMsTeamsChannel1    ChannelNameBasicChannel = original.ChannelNameMsTeamsChannel1
	ChannelNameSkypeChannel1      ChannelNameBasicChannel = original.ChannelNameSkypeChannel1
	ChannelNameSlackChannel1      ChannelNameBasicChannel = original.ChannelNameSlackChannel1
	ChannelNameSmsChannel1        ChannelNameBasicChannel = original.ChannelNameSmsChannel1
	ChannelNameTelegramChannel1   ChannelNameBasicChannel = original.ChannelNameTelegramChannel1
	ChannelNameWebChatChannel1    ChannelNameBasicChannel = original.ChannelNameWebChatChannel1
)

type EnterpriseChannelNodeState = original.EnterpriseChannelNodeState

const (
	CreateFailed EnterpriseChannelNodeState = original.CreateFailed
	Creating     EnterpriseChannelNodeState = original.Creating
	DeleteFailed EnterpriseChannelNodeState = original.DeleteFailed
	Deleting     EnterpriseChannelNodeState = original.Deleting
	Started      EnterpriseChannelNodeState = original.Started
	StartFailed  EnterpriseChannelNodeState = original.StartFailed
	Starting     EnterpriseChannelNodeState = original.Starting
	StopFailed   EnterpriseChannelNodeState = original.StopFailed
	Stopped      EnterpriseChannelNodeState = original.Stopped
	Stopping     EnterpriseChannelNodeState = original.Stopping
)

type EnterpriseChannelState = original.EnterpriseChannelState

const (
	EnterpriseChannelStateCreateFailed EnterpriseChannelState = original.EnterpriseChannelStateCreateFailed
	EnterpriseChannelStateCreating     EnterpriseChannelState = original.EnterpriseChannelStateCreating
	EnterpriseChannelStateDeleteFailed EnterpriseChannelState = original.EnterpriseChannelStateDeleteFailed
	EnterpriseChannelStateDeleting     EnterpriseChannelState = original.EnterpriseChannelStateDeleting
	EnterpriseChannelStateStarted      EnterpriseChannelState = original.EnterpriseChannelStateStarted
	EnterpriseChannelStateStartFailed  EnterpriseChannelState = original.EnterpriseChannelStateStartFailed
	EnterpriseChannelStateStarting     EnterpriseChannelState = original.EnterpriseChannelStateStarting
	EnterpriseChannelStateStopFailed   EnterpriseChannelState = original.EnterpriseChannelStateStopFailed
	EnterpriseChannelStateStopped      EnterpriseChannelState = original.EnterpriseChannelStateStopped
	EnterpriseChannelStateStopping     EnterpriseChannelState = original.EnterpriseChannelStateStopping
)

type Kind = original.Kind

const (
	KindBot      Kind = original.KindBot
	KindDesigner Kind = original.KindDesigner
	KindFunction Kind = original.KindFunction
	KindSdk      Kind = original.KindSdk
)

type SkuName = original.SkuName

const (
	F0 SkuName = original.F0
	S1 SkuName = original.S1
)

type SkuTier = original.SkuTier

const (
	Free     SkuTier = original.Free
	Standard SkuTier = original.Standard
)

type Bot = original.Bot
type BotChannel = original.BotChannel
type BotProperties = original.BotProperties
type BotResponseList = original.BotResponseList
type BotResponseListIterator = original.BotResponseListIterator
type BotResponseListPage = original.BotResponseListPage
type BasicChannel = original.BasicChannel
type Channel = original.Channel
type ChannelResponseList = original.ChannelResponseList
type ChannelResponseListIterator = original.ChannelResponseListIterator
type ChannelResponseListPage = original.ChannelResponseListPage
type CheckNameAvailabilityRequestBody = original.CheckNameAvailabilityRequestBody
type CheckNameAvailabilityResponseBody = original.CheckNameAvailabilityResponseBody
type ConnectionItemName = original.ConnectionItemName
type ConnectionSetting = original.ConnectionSetting
type ConnectionSettingParameter = original.ConnectionSettingParameter
type ConnectionSettingProperties = original.ConnectionSettingProperties
type ConnectionSettingResponseList = original.ConnectionSettingResponseList
type ConnectionSettingResponseListIterator = original.ConnectionSettingResponseListIterator
type ConnectionSettingResponseListPage = original.ConnectionSettingResponseListPage
type DirectLineChannel = original.DirectLineChannel
type DirectLineChannelProperties = original.DirectLineChannelProperties
type DirectLineSite = original.DirectLineSite
type EmailChannel = original.EmailChannel
type EmailChannelProperties = original.EmailChannelProperties
type EnterpriseChannel = original.EnterpriseChannel
type EnterpriseChannelCheckNameAvailabilityRequest = original.EnterpriseChannelCheckNameAvailabilityRequest
type EnterpriseChannelCheckNameAvailabilityResponse = original.EnterpriseChannelCheckNameAvailabilityResponse
type EnterpriseChannelNode = original.EnterpriseChannelNode
type EnterpriseChannelProperties = original.EnterpriseChannelProperties
type EnterpriseChannelResponseList = original.EnterpriseChannelResponseList
type EnterpriseChannelResponseListIterator = original.EnterpriseChannelResponseListIterator
type EnterpriseChannelResponseListPage = original.EnterpriseChannelResponseListPage
type EnterpriseChannelsCreateFuture = original.EnterpriseChannelsCreateFuture
type EnterpriseChannelsDeleteFuture = original.EnterpriseChannelsDeleteFuture
type EnterpriseChannelsUpdateFuture = original.EnterpriseChannelsUpdateFuture
type Error = original.Error
type ErrorBody = original.ErrorBody
type FacebookChannel = original.FacebookChannel
type FacebookChannelProperties = original.FacebookChannelProperties
type FacebookPage = original.FacebookPage
type KikChannel = original.KikChannel
type KikChannelProperties = original.KikChannelProperties
type MsTeamsChannel = original.MsTeamsChannel
type MsTeamsChannelProperties = original.MsTeamsChannelProperties
type OperationDisplayInfo = original.OperationDisplayInfo
type OperationEntity = original.OperationEntity
type OperationEntityListResult = original.OperationEntityListResult
type OperationEntityListResultIterator = original.OperationEntityListResultIterator
type OperationEntityListResultPage = original.OperationEntityListResultPage
type Resource = original.Resource
type ServiceProvider = original.ServiceProvider
type ServiceProviderParameter = original.ServiceProviderParameter
type ServiceProviderProperties = original.ServiceProviderProperties
type ServiceProviderResponseList = original.ServiceProviderResponseList
type Sku = original.Sku
type SkypeChannel = original.SkypeChannel
type SkypeChannelProperties = original.SkypeChannelProperties
type SlackChannel = original.SlackChannel
type SlackChannelProperties = original.SlackChannelProperties
type SmsChannel = original.SmsChannel
type SmsChannelProperties = original.SmsChannelProperties
type TelegramChannel = original.TelegramChannel
type TelegramChannelProperties = original.TelegramChannelProperties
type WebChatChannel = original.WebChatChannel
type WebChatChannelProperties = original.WebChatChannelProperties
type WebChatSite = original.WebChatSite
type OperationsClient = original.OperationsClient

func NewBotConnectionClient(subscriptionID string) BotConnectionClient {
	return original.NewBotConnectionClient(subscriptionID)
}
func NewBotConnectionClientWithBaseURI(baseURI string, subscriptionID string) BotConnectionClient {
	return original.NewBotConnectionClientWithBaseURI(baseURI, subscriptionID)
}
func NewBotsClient(subscriptionID string) BotsClient {
	return original.NewBotsClient(subscriptionID)
}
func NewBotsClientWithBaseURI(baseURI string, subscriptionID string) BotsClient {
	return original.NewBotsClientWithBaseURI(baseURI, subscriptionID)
}
func NewChannelsClient(subscriptionID string) ChannelsClient {
	return original.NewChannelsClient(subscriptionID)
}
func NewChannelsClientWithBaseURI(baseURI string, subscriptionID string) ChannelsClient {
	return original.NewChannelsClientWithBaseURI(baseURI, subscriptionID)
}
func New(subscriptionID string) BaseClient {
	return original.New(subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
	return original.NewWithBaseURI(baseURI, subscriptionID)
}
func NewEnterpriseChannelsClient(subscriptionID string) EnterpriseChannelsClient {
	return original.NewEnterpriseChannelsClient(subscriptionID)
}
func NewEnterpriseChannelsClientWithBaseURI(baseURI string, subscriptionID string) EnterpriseChannelsClient {
	return original.NewEnterpriseChannelsClientWithBaseURI(baseURI, subscriptionID)
}
func PossibleChannelNameValues() []ChannelName {
	return original.PossibleChannelNameValues()
}
func PossibleChannelNameBasicChannelValues() []ChannelNameBasicChannel {
	return original.PossibleChannelNameBasicChannelValues()
}
func PossibleEnterpriseChannelNodeStateValues() []EnterpriseChannelNodeState {
	return original.PossibleEnterpriseChannelNodeStateValues()
}
func PossibleEnterpriseChannelStateValues() []EnterpriseChannelState {
	return original.PossibleEnterpriseChannelStateValues()
}
func PossibleKindValues() []Kind {
	return original.PossibleKindValues()
}
func PossibleSkuNameValues() []SkuName {
	return original.PossibleSkuNameValues()
}
func PossibleSkuTierValues() []SkuTier {
	return original.PossibleSkuTierValues()
}
func NewOperationsClient(subscriptionID string) OperationsClient {
	return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
	return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}


text:
package figglewatts.lsdrsdk.SeqCreate.datatypes;

public class Sequence {
	private SequenceData data;

	public void setData(SequenceData _data) {
		this.data = _data;
	}

	@Override
	public String toString() {
		return data.toString();
	}
}


text:
#ifndef HTTP_HEADER_H
#define HTTP_HEADER_H

#include <string>
#include <algorithm>

namespace http
{
struct Header
{
    Header& operator=(const Header& other) = default;
    Header(const std::string & name, const std::string & value) : name(name), value(value) {}
    Header(const Header && other) : name(std::move(other.name)), value(std::move(other.value)) {}

    void Clear()
    {
        name.clear();
        value.clear();
    }

    std::string name;
    std::string value;
};
}

#endif // HTTP_HEADER_H


text:
package org.fishwife.jrugged.examples;

import java.util.Random;

import org.fishwife.jrugged.aspects.PerformanceMonitor;

public class AspectResponseTweaker {

    @PerformanceMonitor("AspectResponseTweaker")
    public int delay() throws Exception {
        Random r = new Random();
        int count = r.nextInt(2001);

        if (count > 1650) {
            throw new Exception("Count was over the limit.");
        }

        try {
            Thread.sleep(count);
        } catch (InterruptedException e) { }

        return count;
    }

}


text:
package edu.wustl.catissuecore.factory;

import edu.wustl.catissuecore.domain.DisposalEventParameters;

public class DisposalEventParametersFactory extends
		AbstractSpecimenEventParametersFactory<DisposalEventParameters>
{

	private static DisposalEventParametersFactory disposalEventParametersFactory;

	private DisposalEventParametersFactory()
	{
		super();
	}

	public static synchronized DisposalEventParametersFactory getInstance()
	{
		if(disposalEventParametersFactory==null){
			disposalEventParametersFactory = new DisposalEventParametersFactory();
		}
		return disposalEventParametersFactory;
	}

	public DisposalEventParameters createClone(DisposalEventParameters obj)
	{
		DisposalEventParameters disposalEventParameters = createObject();
		return disposalEventParameters;
	}

	public DisposalEventParameters createObject()
	{
		DisposalEventParameters disposalEventParameters = new DisposalEventParameters();
		initDefaultValues(disposalEventParameters);
		return disposalEventParameters;
	}

	public void initDefaultValues(DisposalEventParameters obj)
	{
	}

}