text:
<?php

namespace BackBee\CoreDomain\NestedNode\Repository;

use BackBee\CoreDomain\Site\Layout;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;

use BackBee\CoreDomain\ClassContent\AbstractClassContent;
use BackBee\CoreDomain\ClassContent\ContentSet;
use BackBee\CoreDomain\NestedNode\Page;
use BackBee\CoreDomain\NestedNode\Section;
use BackBee\Security\Token\BBUserToken;
use BackBee\CoreDomain\Site\Site;
use InvalidArgumentException;

/**
 * Page repository.
 *
 * @category    BackBee
 *
 * @copyright   Lp digital system
 * @author      c.rouillon <charles.rouillon@lp-digital.fr>
 */
class PageRepository extends EntityRepository
{
    /**
     * Creates a new Page QueryBuilder instance that is prepopulated for this entity name.
     *
     * @param string                $alias              The alias to use.
     * @param string                $indexBy            Optional, the index to use for the query.
     *
     * @return PageQueryBuilder                         The page query builder for this repository.
     */
    public function createQueryBuilder($alias, $indexBy = null)
    {
        $qb = new PageQueryBuilder($this->_em);

        return $qb->select($alias)->from($this->_entityName, $alias, $indexBy);
    }

    /**
     * Finds entities by a set of criteria with automatic join on section if need due to retro-compatibility.
     *
     * @param  array                $criteria           An array of criteria ( field => value ).
     * @param  array|null           $orderBy            Optional, an array of ordering criteria ( [field => direction] ).
     * @param  integer|null         $limit              Optional, the max number of results.
     * @param  integer|null         $offset             Optional, The starting index of results.
     *
     * @return Page[]                                   An array of matching pages.
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if (
                false === PageQueryBuilder::hasJoinCriteria($criteria) &&
                false === PageQueryBuilder::hasJoinCriteria($orderBy)
        ) {
            return parent::findBy($criteria, $orderBy, $limit, $offset);
        }

        $query = $this->createQueryBuilder('p')
                        ->addSearchCriteria($criteria);

        if (false === empty($orderBy)) {
            $query->addMultipleOrderBy($orderBy);
        }

        return $query->setMaxResults($limit)
                        ->setFirstResult($offset)
                        ->getQuery()
                        ->getResult();
    }

    /**
     * Finds a single entity by a set of criteria with automatic join on section if need due to retro-compatibility.
     *
     * @param  array                $criteria           An array of criteria.
     * @param  array|null           $orderBy            Optional, an array of ordering criteria.
     *
     * @return object|null                              The page instance or null if the entity can not be found.
     */
    public function findOneBy(array $criteria, array $orderBy = null)
    {
        if (
                false === PageQueryBuilder::hasJoinCriteria($criteria) &&
                false === PageQueryBuilder::hasJoinCriteria($orderBy)
        ) {
            return parent::findOneBy($criteria, $orderBy);
        }

        $query = $this->createQueryBuilder('p')
                ->addSearchCriteria($criteria);

        if (false === empty($orderBy)) {
            $query->addMultipleOrderBy($orderBy);
        }

        return $query->getQuery()
                        ->getOneOrNullResult();
    }

    /**
     * Returns the ancestor at level $level of the provided page.
     *
     * @param  Page                 $page               The page to look for ancestor.
     * @param  integer              $level              Optional, the level of the ancestor (0 by default, ie root).
     *
     * @return Page|null                                The page instance or null if the entity can not be found.
     */
    public function getAncestor(Page $page, $level = 0)
    {
        if ($page->getLevel() < $level) {
            return;
        }

        if ($page->getLevel() === $level) {
            return $page;
        }

        return $this->createQueryBuilder('p')
                        ->andIsAncestorOf($page, false, $level)
                        ->getQuery()
                        ->getOneOrNullResult();
    }

    /**
     * Returns the ancestors of the provided page.
     *
     * @param  Page                 $page               The page to look for ancestors.
     * @param  integer|null         $depth              Optional, limits results to ancestors from $depth number of generation.
     * @param  boolean              $includeNode        Optional, include the node itsef to results if true (false by default).
     *
     * @return Page[]                                   An array of matching ancestors.
     */
    public function getAncestors(Page $page, $depth = null, $includeNode = false)
    {
        $q = $this->createQueryBuilder('p')
                ->andIsAncestorOf($page, !$includeNode, null === $depth ? null : $page->getLevel() - $depth);

        $results = $q->orderBy($q->getSectionAlias().'._leftnode', 'asc')
                ->getQuery()
                ->getResult();

        if (true === $includeNode && false === $page->hasMainSection()) {
            $results[] = $page;
        }

        return $results;
    }

    /**
     * Returns the previous online sibling of $page.
     *
     * @param  Page                 $page               The page to look for previous sibling
     *
     * @return Page|null                                The previous page or null if the entity can not be found.
     */
    public function getOnlinePrevSibling(Page $page)
    {
        $query = $this->createQueryBuilder('p')
                ->andIsSiblingsOf($page, true, ['_leftnode' => 'DESC', '_position' => 'DESC'], 1, 0)
                ->andIsOnline();

        if (true === $page->hasMainSection()) {
            $query->andIsSection()
                    ->andWhere($query->getSectionAlias().'._leftnode < :leftnode')
                    ->setParameter('leftnode', $page->getLeftnode());
        } else {
            $qOR = $query->expr()->orX();
            $qOR->add('p._section != p')
                    ->add($query->getSectionAlias().'._parent = :parent');

            $query->andWhere('p._position < :position')
                    ->andWhere($qOR)
                    ->setParameter('position', $page->getPosition())
                    ->setParameter('parent', $page->getParent()->getSection());
        }

        return $query->getQuery()
                        ->getOneOrNullResult();
    }

    /**
     * Returns the online siblings having layout $layout of the provided page.
     *
     * @param  Page                 $page               The page to look for siblings having $layout.
     * @param  Layout               $layout             The layout to look for.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array|null           $order              Optional, the ordering criteria ( [field => $sort] ).
     * @param  integer|null         $limit              Optional, the maximum number of results.
     * @param  integer              $start              Optional, the first result index (0 by default).
     *
     * @return Page[]                                   An array of matching siblings.
     */
    public function getOnlineSiblingsByLayout(Page $page, Layout $layout, $includeNode = false, $order = null, $limit = null, $start = 0)
    {
        return $this->createQueryBuilder('p')
                        ->andIsSiblingsOf($page, !$includeNode, $order, $limit, $start)
                        ->andIsOnline()
                        ->andWhere('p._layout = :layout')
                        ->setParameter('layout', $layout)
                        ->andWhere('p._level = :level')
                        ->setParameter('level', $page->getLevel())
                        ->getQuery()
                        ->getResult();
    }

    /**
     * Returns the next online sibling of $page.
     *
     * @param  Page                 $page               The page to look for next sibling.
     *
     * @return Page|null                                The next page or null if the entity can not be found.
     */
    public function getOnlineNextSibling(Page $page)
    {
        $query = $this->createQueryBuilder('p');

        if (true === $page->hasMainSection()) {
            $query->andWhere($query->getSectionAlias().'._leftnode >= :leftnode')
                    ->orWhere('p._section IN (:sections)')
                    ->setParameter('leftnode', $page->getLeftnode())
                    ->setParameter('sections', [$page->getSection(), $page->getSection()->getParent()]);
        } else {
            $query->andWhere('p._position > :position')
                    ->setParameter('position', $page->getPosition());
        }

        return $query->andIsSiblingsOf($page, true, ['_position' => 'ASC', '_leftnode' => 'ASC'], 1, 0)
                        ->andIsOnline()
                        ->getQuery()
                        ->getOneOrNullResult();
    }

    /**
     * Inserts a page in a tree at first position.
     *
     * @param  Page                 $page               The page to be inserted.
     * @param  Page                 $parent             The parent node.
     * @param  boolean              $section            If true, the page is inserted with a section (false by default).
     *
     * @return Page                                     The inserted page.
     */
    public function insertNodeAsFirstChildOf(Page $page, Page $parent, $section = false)
    {
        return $this->insertNode($page, $parent, 1, $section);
    }

    /**
     * Inserts a page in a tree at last position.
     *
     * @param  Page                 $page               The page to be inserted.
     * @param  Page                 $parent             The parent node.
     * @param  boolean              $section            If true, the page is inserted with a section (false by default).
     *
     * @return Page                                     The inserted page.
     */
    public function insertNodeAsLastChildOf(Page $page, Page $parent, $section = false)
    {
        return $this->insertNode($page, $parent, $this->getMaxPosition($parent) + 1, $section);
    }

    /**
     * Inserts a page in a tree.
     *
     * @param  Page                 $page               The page to be inserted.
     * @param  Page                 $parent             The parent node.
     * @param  integer              $position           The position of the inserted page
     * @param  boolean              $section            If true, the page is inserted with a section (false by default).
     *
     * @return Page                                     The inserted page.
     *
     * @throws InvalidArgumentException                 Raises if parent page is not a section.
     */
    public function insertNode(Page $page, Page $parent, $position, $section = false)
    {
        if (!$parent->hasMainSection()) {
            throw new InvalidArgumentException('Parent page is not a section.');
        }

        $current_parent = $page->getSection();
        $page->setParent($parent)
                ->setPosition($position)
                ->setLevel($parent->getSection()->getLevel() + 1);

        if (true === $section) {
            $page = $this->saveWithSection($page, $current_parent);
        } else {
            $this->shiftPosition($page, 1, true);
        }

        $parent->getSection()->setHasChildren(true);

        return $page;
    }

    /**
     * Returns default ordering criteria for descendants if none provided.
     *
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     *
     * @return array                                    If none ordering criteria provided and only one descendant generation is requested
     *                                                  the result will be array['_position' => 'ASC', '_leftnode' => 'ASC']
     *                                                  If none ordering criteria provided and several generations requested the result
     *                                                  will be array['_leftnode' => 'ASC', '_level' => 'ASC', '_position' => 'ASC']
     *                                                  elsewhere $order.
     */
    private function getOrderingDescendants($depth = null, $order = [])
    {
        if (1 === $depth && true === empty($order)) {
            $order = [
                '_position' => 'ASC',
                '_leftnode' => 'ASC',
            ];
        } elseif (true === empty($order)) {
            $order = [
                '_leftnode' => 'ASC',
                '_level' => 'ASC',
                '_position' => 'ASC',
            ];
        }

        return $order;
    }

    /**
     * Returns the descendants of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     * @param  boolean              $paginate           Optional, if true return a paginator rather than an array (false by default).
     * @param  integer              $start              Optional, if paginated set the first result index (0 by default).
     * @param  integer              $limit              Optional, if paginated set the maxmum number of results (25 by default).
     * @param  boolean              $limitToSection     Optional, limit to descendants having child (false by default).
     * @param  string|null          $state              Optional, either 'visible', 'online', 'not-deleted' or empty.
     *
     * @return Page[]|Paginator                         The matching pages if $paginate is false, a Paginator elsewhere.
     */
    private function getDescendantsWithState(Page $page, $depth = null, $includeNode = false, $order = [], $paginate = false, $start = 0, $limit = 25, $limitToSection = false, $state = null)
    {
        if (true === $page->isLeaf()) {
            return [];
        }

        $query = $this->createQueryBuilder('p')
                ->andIsDescendantOf($page, !$includeNode, $depth, $this->getOrderingDescendants($depth, $order), (true === $paginate) ? $limit : null, $start, $limitToSection);

        switch ($state) {
            case 'onine':
                $query->andIsOnline();
                break;
            case 'visible':
                $query->andIsVisible();
                break;
            case 'not-deleted':
                $query->andIsNotDeleted();
                break;
        }

        if (true === $paginate) {
            return new Paginator($query);
        }

        return $query->getQuery()->getResult();
    }

    /**
     * Returns the descendants of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     * @param  boolean              $paginate           Optional, if true return a paginator rather than an array (false by default).
     * @param  integer              $start              Optional, if paginated set the first result index (0 by default).
     * @param  integer              $limit              Optional, if paginated set the maxmum number of results (25 by default).
     * @param  boolean              $limitToSection     Optional, limit to descendants having child (false by default).
     *
     * @return Page[]|Paginator                         The matching pages if $paginate is false, a Paginator elsewhere.
     */
    public function getDescendants(Page $page, $depth = null, $includeNode = false, $order = [], $paginate = false, $start = 0, $limit = 25, $limitToSection = false)
    {
        return $this->getDescendantsWithState($page, $depth, $includeNode, $order, $paginate, $start, $limit, $limitToSection);
    }

    /**
     * Returns the online descendants of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     * @param  boolean              $paginate           Optional, if true return a paginator rather than an array (false by default).
     * @param  integer              $start              Optional, if paginated set the first result index (0 by default).
     * @param  integer              $limit              Optional, if paginated set the maxmum number of results (25 by default).
     * @param  boolean              $limitToSection     Optional, limit to descendants having child (false by default).
     *
     * @return Page[]|Paginator                         The matching pages if $paginate is false, a Paginator elsewhere.
     */
    public function getOnlineDescendants(Page $page, $depth = null, $includeNode = false, $order = [], $paginate = false, $start = 0, $limit = 25, $limitToSection = false)
    {
        return $this->getDescendantsWithState($page, $depth, $includeNode, $order, $paginate, $start, $limit, $limitToSection, 'online');
    }

    /**
     * Returns the visible (ie online and not hidden) descendants of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     * @param  boolean              $paginate           Optional, if true return a paginator rather than an array (false by default).
     * @param  integer              $start              Optional, if paginated set the first result index (0 by default).
     * @param  integer              $limit              Optional, if paginated set the maxmum number of results (25 by default).
     * @param  boolean              $limitToSection     Optional, limit to descendants having child (false by default).
     *
     * @return Page[]|Paginator                         The matching pages if $paginate is false, a Paginator elsewhere.
     */
    public function getVisibleDescendants(Page $page, $depth = null, $includeNode = false, $order = [], $paginate = false, $start = 0, $limit = 25, $limitToSection = false)
    {
        return $this->getDescendantsWithState($page, $depth, $includeNode, $order, $paginate, $start, $limit, $limitToSection, 'visible');
    }

    /**
     * Returns the visible (ie online and not hidden) children of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     *
     * @return Page[]                                   The matching pages if $paginate is false, a Paginator elsewhere.
     *
     * @deprecated
     */
    public function getVisibleDescendantsFromParent(Page $page, $depth = null, $includeNode = false)
    {
        return $this->getVisibleDescendants($page, 1, $includeNode);
    }

    /**
     * Returns the not deleted descendants of $page.
     *
     * @param  Page                 $page               The page to look for descendants.
     * @param  integer|null         $depth              Optional, limit to $depth number of generation.
     * @param  boolean              $includeNode        Optional, include $page in results if true (false by default).
     * @param  array                $order              Optional, the ordering criteria ( [] by default ).
     * @param  boolean              $paginate           Optional, if true return a paginator rather than an array (false by default).
     * @param  integer              $start              Optional, if paginated set the first result index (0 by default).
     * @param  integer              $limit              Optional, if paginated set the maxmum number of results (25 by default).
     * @param  boolean              $limitToSection     Optional, limit to descendants having child (false by default).
     *
     * @return Page[]|Paginator                         The matching pages if $paginate is false, a Paginator elsewhere.
     */
    public function getNotDeletedDescendants(Page $page, $depth = null, $includeNode = false, $order = [], $paginate = false, $start = 0, $limit = 25, $limitToSection = false)
    {
        return $this->getDescendantsWithState($page, $depth, $includeNode, $order, $paginate, $start, $limit, $limitToSection, 'not-deleted');
    }

    /**
     * Move page as first child of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     *
     * @return Page                                     The moved page.
     */
    public function moveAsFirstChildOf(Page $page, Page $target)
    {
        return $this->moveAsChildOf($page, $target, true);
    }

    /**
     * Move page as last child of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     *
     * @return Page                                     The moved page.
     */
    public function moveAsLastChildOf(Page $page, Page $target)
    {
        return $this->moveAsChildOf($page, $target, false);
    }

    /**
     * Move page as child of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asFirst            Move page as first child of $target if true (default), last child elsewhere.
     *
     * @return Page                                     The moved page.
     *
     * @throws InvalidArgumentException                 Raises if target page is not a section.
     */
    private function moveAsChildOf(Page $page, Page $target, $asFirst = true)
    {
        if (false === $target->hasMainSection()) {
            throw new InvalidArgumentException('Cannot move page into a non-section page.');
        }

        if (false === $page->hasMainSection()) {
            $this->movePageAsChildOf($page, $target, $asFirst);
        } else {
            $this->moveSectionAsChildOf($page, $target, $asFirst);
        }

        $target->getSection()->setHasChildren(true);

        return $page->setParent($target)
                        ->setLevel($target->getLevel() + 1);
    }

    /**
     * Move a non-section page as child of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asFirst            Move page as first child of $target if true (default), last child elsewhere.
     *
     * @return Page                                     The moved page.
     */
    private function movePageAsChildOf(Page $page, Page $target, $asFirst = true)
    {
        if (true === $asFirst) {
            return $this->shiftPosition($page, -1, true)
                            ->insertNodeAsFirstChildOf($page, $target);
        } else {
            return $this->shiftPosition($page, -1, true)
                            ->insertNodeAsLastChildOf($page, $target);
        }
    }

    /**
     * Move a section page as child of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asFirst            Move page as first child of $target if true (default), last child elsewhere.
     *
     * @return Page                                     The moved page.
     */
    private function moveSectionAsChildOf(Page $page, Page $target, $asFirst = true)
    {
        $delta = $target->getLevel() - $page->getLevel() + 1;
        $this->shiftLevel($page, $delta);

        $this->getEntityManager()
                ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                ->moveNode($page->getSection(), $target->getSection(), $asFirst ? 'firstin' : 'lastin');

        return $page;
    }

    /**
     * Move a page as previous sibling of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     *
     * @return Page                                     The moved page.
     */
    public function moveAsPrevSiblingOf(Page $page, Page $target)
    {
        return $this->moveAsSiblingOf($page, $target, true);
    }

    /**
     * Move a page as next sibling of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     *
     * @return Page                                     The moved page.
     */
    public function moveAsNextSiblingOf(Page $page, Page $target)
    {
        return $this->moveAsSiblingOf($page, $target, false);
    }

    /**
     * Move a page as sibling of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asPrevious         Move page as previous sibling of $target if true (default), next sibling elsewhere.
     *
     * @return Page                                     The moved page.
     *
     * @throws InvalidArgumentException                 Raises if $target is a root.
     */
    private function moveAsSiblingOf(Page $page, Page $target, $asPrevious = true)
    {
        if (null === $target->getParent()) {
            throw new InvalidArgumentException('Cannot move a page as sibling of a root.');
        }

        if (!$page->hasMainSection() && $target->hasMainSection()) {
            $this->moveAsFirstChildOf($page, $target->getParent());
        } elseif (!$page->hasMainSection() && !$target->hasMainSection()) {
            $this->movePageAsSiblingOf($page, $target, $asPrevious);
        } elseif ($page->hasMainSection() && !$target->hasMainSection()) {
            $this->moveAsLastChildOf($page, $target->getParent());
        } else {
            $this->moveSectionAsSiblingOf($page, $target, $asPrevious);
        }

        return $page->setParent($target->getParent());
    }

    /**
     * Move a non-section page as sibling of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asPrevious         Move page as previous sibling of $target if true (default), next sibling elsewhere.
     *
     * @return Page                                     The moved page.
     */
    private function movePageAsSiblingOf(Page $page, Page $target, $asPrevious = true)
    {
        $this->shiftPosition($page, -1, true);
        $this->_em->refresh($target);

        if (true === $asPrevious) {
            $page->setPosition($target->getPosition());
            $this->shiftPosition($target, 1);
        } else {
            $page->setPosition($target->getPosition() + 1);
            $this->shiftPosition($target, 1, true);
        }

        return $page;
    }

    /**
     * Move a section page as sibling of $target.
     *
     * @param  Page                 $page               The page to be moved.
     * @param  Page                 $target             The target page.
     * @param  boolean              $asPrevious         Move page as previous sibling of $target if true (default), next sibling elsewhere.
     *
     * @return Page                                     The moved page.
     */
    private function moveSectionAsSiblingOf(Page $page, Page $target, $asPrevious = true)
    {
        $delta = $page->getLevel() - $target->getLevel();
        $this->shiftLevel($page, $delta);

        $this->getEntityManager()
                ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                ->moveNode($page->getSection(), $target->getSection(), $asPrevious ? 'before' : 'after');

        return $page;
    }

    /**
     * Returns the root page for $site.
     *
     * @param  Site                 $site               The site to test.
     * @param  integer[]            $restrictedStates   Optional, limit to pages having provided states ( [] by default ).
     *
     * @return Page|null                                The root instance or null if the entity can not be found.
     */
    public function getRoot(Site $site, array $restrictedStates = [])
    {
        $q = $this->createQueryBuilder('p')
                ->andSiteIs($site)
                ->andParentIs(null)
                ->orderby('p._position', 'asc')
                ->setMaxResults(1);

        if (0 < count($restrictedStates)) {
            $q->andStateIsIn($restrictedStates);
        }

        return $q->getQuery()->getOneOrNullResult();
    }

    /**
     * Returns an array of online children of $page.
     *
     * @param  Page                 $page               The parent page.
     * @param  integer|null         $maxResults         Optional, the maximum number of results.
     * @param  array                $order              Optional, the ordering criteria ( ['_leftnode', 'asc'] by default).
     *
     * @return Page[]                                   An array of matching pages.
     *
     * @deprecated
     */
    public function getOnlineChildren(Page $page, $maxResults = null, array $order = ['_leftnode', 'asc'])
    {
        if (true === $page->isLeaf()) {
            return [];
        }

        $query = $this->createQueryBuilder('p')
                ->andIsOnline()
                ->andIsDescendantOf($page, true, 1, $this->getOrderingDescendants(1, null), $maxResults, 0, false);

        return $query->getQuery()->getResult();
    }

    /**
     * Returns an array of children of $page.
     *
     * @param  Page                 $page               The parent page.
     * @param  string               $orderSort          Optional, the sort field, title by default.
     * @param  string               $orderDir           Optional, the sort direction, asc by default.
     * @param  string               $paging             Optional, the paging criteria: ['start' => xx, 'limit' => xx], empty by default.
     * @param  integer[]            $restrictedStates   Optional, limit to pages having provided states, empty by default.
     * @param  string[]             $options            Optional, the search criteria:
     *                                                      * 'beforePubdateField'  => timestamp against page._modified,
     *                                                      * 'afterPubdateField'   => timestamp against page._modified,
     *                                                      * 'searchField'         => string to search for title
     *
     * @return Page[]|Paginator                         Returns Paginaor is $paging criteria provided, array otherwise.
     *
     * @deprecated
     */
    public function getChildren(Page $page, $orderSort = '_title', $orderDir = 'asc', $paging = [], $restrictedStates = [], $options = [])
    {
        if (true === $page->isLeaf()) {
            return [];
        }

        $paginate = (is_array($paging) && array_key_exists('start', $paging) && array_key_exists('limit', $paging));

        $query = $this->createQueryBuilder('p')
                ->andIsDescendantOf($page, true, 1, [$orderSort => $orderDir], $paginate ? $paging['limit'] : null, $paginate ? $paging['start'] : 0, false)
                ->andSearchCriteria($restrictedStates, $options);

        if (true === $paginate) {
            return new Paginator($query);
        }

        return $query->getQuery()->getResult();
    }

    /**
     * Returns count of children of $page.
     *
     * @param  Page                 $page               The parent page.
     * @param  string               $orderSort          Optional, the sort field, title by default.
     * @param  string               $orderDir           Optional, the sort direction, asc by default.
     * @param  integer[]            $restrictedStates   Optional, limit to pages having provided states, empty by default.
     * @param  string[]             $options            Optional, the search criteria:
     *                                                      * 'beforePubdateField'  => timestamp against page._modified,
     *                                                      * 'afterPubdateField'   => timestamp against page._modified,
     *                                                      * 'searchField'         => string to search for title
     *
     * @return integer                                  The children count.
     *
     * @deprecated
     */
    public function countChildren(Page $page, $orderSort = '_title', $orderDir = 'asc', $restrictedStates = [], $options = [])
    {
        if (true === $page->isLeaf()) {
            return 0;
        }

        return $this->createQueryBuilder('p')
                        ->select("COUNT(p)")
                        ->andIsDescendantOf($page, true, 1, [$orderSort => $orderDir], null, 0, false)
                        ->andSearchCriteria($restrictedStates, $options)
                        ->getQuery()
                        ->getSingleScalarResult();
    }

    /**
     * Sets state of $page and is descendant to STATE_DELETED.
     *
     * @param  Page                 $page               The page to delete.
     *
     * @return integer                                  The number of page having their state changed.
     */
    public function toTrash(Page $page)
    {
        if (true === $page->isLeaf()) {
            $page->setState(Page::STATE_DELETED);
            $this->getEntityManager()->flush($page);

            return 1;
        }

        $subquery = $this->getEntityManager()
                ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                ->createQueryBuilder('n')
                ->select('n._uid')
                ->andIsDescendantOf($page->getSection());

        return $this->createQueryBuilder('p')
                        ->update()
                        ->set('p._state', Page::STATE_DELETED)
                        ->andWhere('p._section IN ('.$subquery->getDQL().')')
                        ->setParameters($subquery->getParameters())
                        ->getQuery()
                        ->execute();
    }

    /**
     * Copy a page to a new one.
     *
     * @param  Page                 $page               The page to be copied.
     * @param  string|null          $title              Optional, the title of the copy, if null (default) the title of the copied page.
     * @param  Page|null            $parent             Optional, the parent of the copy, if null (default) the parent of the copied page.
     *
     * @return Page                                     The copy of the page.
     *
     * @throws InvalidArgumentException                 Raises if the page is deleted.
     */
    private function copy(Page $page, $title = null, Page $parent = null)
    {
        if (Page::STATE_DELETED & $page->getState()) {
            throw new InvalidArgumentException('Cannot duplicate a deleted page.');
        }

        // Cloning the page
        $new_page = clone $page;
        $new_page->setTitle((null === $title) ? $page->getTitle() : $title)
                ->setLayout($page->getLayout());

        // Setting the clone as first child of the parent
        if (null !== $parent) {
            $new_page = $this->insertNodeAsFirstChildOf($new_page, $parent, $new_page->hasMainSection());
        }

        // Persisting entities
        $this->_em->persist($new_page);

        return $new_page;
    }

    /**
     * Replace subcontent of ContentSet by their clone if exist.
     *
     * @param  AbstractClassContent $content            The cloned content.
     * @param  array                $cloningData        The cloned data array.
     * @param  BBUserToken|null     $token              Optional, the BBuser token to allow the update of revisions if set.
     *
     * @return PageRepository
     */
    private function updateRelatedPostCloning(AbstractClassContent $content, array $cloningData, BBUserToken $token = null)
    {
        if (
                $content instanceof ContentSet &&
                true === array_key_exists('pages', $cloningData) &&
                true === array_key_exists('contents', $cloningData) &&
                0 < count($cloningData['pages']) &&
                0 < count($cloningData['contents'])
        ) {
            // reading copied elements
            $copied_pages = array_keys($cloningData['pages']);
            $copied_contents = array_keys($cloningData['contents']);

            // Updating subcontent if needed
            foreach ($content as $subcontent) {
                if (false === $this->_em->contains($subcontent)) {
                    $subcontent = $this->_em->find(get_class($subcontent), $subcontent->getUid());
                }

                if (
                        $subcontent instanceof AbstractClassContent &&
                        null !== $subcontent->getMainNode() &&
                        true === in_array($subcontent->getMainNode()->getUid(), $copied_pages) &&
                        true === in_array($subcontent->getUid(), $copied_contents)
                ) {
                    // Loading draft for content
                    if (
                            null !== $token &&
                            (null !== $draft = $this->_em->getRepository('BackBee\CoreDomain\ClassContent\Revision')->getDraft($content, $token, true))
                        ) {
                        $content->setDraft($draft);
                    }
                    $content->replaceChildBy($subcontent, $cloningData['contents'][$subcontent->getUid()]);
                }
            }
        }

        return $this;
    }

    /**
     * Update mainnode of the content if need during clonage.
     *
     * @param  AbstractClassContent $content            The cloned content.
     * @param  array                $cloningPages       The cloned pages array.
     * @param  BBUserToken|null     $token              Optional, the BBuser token to allow the update of revisions if set.
     *
     * @return PageRepository
     */
    private function updateMainNodePostCloning(AbstractClassContent $content, array $cloningPages, BBUserToken $token = null)
    {
        $mainnode = $content->getMainNode();

        if (
                null !== $mainnode &&
                0 < count($cloningPages) &&
                true === in_array($mainnode->getUid(), array_keys($cloningPages))
            ) {
            // Loading draft for content
            if (
                    null !== $token &&
                    (null !== $draft = $this->_em->getRepository('BackBee\CoreDomain\ClassContent\Revision')->getDraft($content, $token, true))
                ) {
                $content->setDraft($draft);
            }
            $content->setMainNode($cloningPages[$mainnode->getUid()]);
        }

        return $this;
    }

    /**
     * Duplicate a page and its descendants.
     *
     * @param  Page                 $page               The page to be duplicated.
     * @param  string|null          $title              Optional, the title of the copy, if null (default) the title of the copied page.
     * @param  Page|null            $parent             Optional, the parent of the copy, if null (default) the parent of the copied page.
     *
     * @return Page                                     The copy of the page.
     *
     * @throws InvalidArgumentException                 Raises if the page is recursively duplicated in itself.
     */
    private function duplicateRecursively(Page $page, $title = null, Page $parent = null)
    {
        if (null !== $parent && true === $parent->isDescendantOf($page)) {
            throw new InvalidArgumentException('Cannot recursively duplicate a page in itself');
        }

        // Storing current children before clonage
        $children = $this->getDescendants($page, 1);

        // Cloning the page
        $new_page = $this->copy($page, $title, $parent);
        $this->_em->flush($new_page);

        // Cloning children
        foreach (array_reverse($children) as $child) {
            if (!(Page::STATE_DELETED & $child->getState())) {
                $new_child = $this->duplicateRecursively($child, null, $new_page);
                $new_page->cloningData = array_merge_recursive($new_page->cloningData, $new_child->cloningData);
            }
        }

        return $new_page;
    }

    /**
     * Duplicate a page and optionnaly its descendants.
     *
     * @param  Page                 $page               The page to be duplicated.
     * @param  string|null          $title              Optional, the title of the copy, if null (default) the title of the copied page.
     * @param  Page|null            $parent             Optional, the parent of the copy, if null (default) the parent of the copied page.
     * @param  boolean              $recursive          Optional, if true (by default) duplicates recursively the descendants of the page.
     * @param  BBUserToken|null     $token              Optional, the BBuser token to allow the update of revisions if set.
     *
     * @return Page                                     The copy of the page.
     *
     * @throws InvalidArgumentException                 Raises if the page is recursively duplicated in itself.
     */
    public function duplicate(Page $page, $title = null, Page $parent = null, $recursive = true, BBUserToken $token = null)
    {
        if (false === $recursive || false === $page->hasMainSection()) {
            $new_page = $this->copy($page, $title, $parent);
        } else {
            // Recursive cloning
            $new_page = $this->duplicateRecursively($page, $title, $parent);
        }

        // Finally updating contentset and mainnode
        foreach ($new_page->cloningData['contents'] as $content) {
            $this->updateRelatedPostCloning($content, $new_page->cloningData, $token)
                 ->updateMainNodePostCloning($content, $new_page->cloningData['pages'], $token)
            ;
        }

        return $new_page;
    }

    /**
     * Removes page with no contentset for $site.
     *
     * @param Site                  $site
     *
     * @deprecated
     */
    public function removeEmptyPages(Site $site)
    {
        $q = $this->createQueryBuilder('p')
            ->select()
            ->andWhere('p._contentset IS NULL')
            ->andWhere('p._site = :site')
            ->orderBy('p._leftnode', 'desc')
            ->setParameter('site', $site);

        foreach ($q->getQuery()->execute() as $page) {
            $this->deletePage($page);
        }
    }

    public function deletePage(Page $page)
    {
        if ($page->hasMainSection()) {
            $this->getEntityManager()
                    ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                    ->deleteSection($page->getSection());
        }

        if ($page->getContentSet() !== null) {
            $this->getEntityManager()->getRepository('BackBee\CoreDomain\ClassContent\AbstractClassContent')->deleteContent($page->getContentSet());
        }

        $this->getEntityManager()->remove($page);
    }

    /**
     * Saves a page with a section and returns it.
     *
     * @param  Page                 $page               The page to be saved with section.
     * @param  Section|null         $currentParent      Optional, if provided the parent section of the new one.
     *
     * @return Page                                     The newly page with section.
     */
    public function saveWithSection(Page $page, Section $currentParent = null)
    {
        if ($page->hasMainSection()) {
            return $page;
        }

        if (false === $this->_em->contains($page)) {
            $this->_em->persist($page);
        }

        $parent = $page->getSection();
        if (null !== $currentParent && $this->_em->getUnitOfWork()->isScheduledForInsert($currentParent)) {
            $this->_em->detach($currentParent);
        }

        $section = new Section($page->getUid(), ['page' => $page, 'site' => $page->getSite()]);

        $this->getEntityManager()
                ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                ->insertNodeAsFirstChildOf($section, $parent);

        return $page->setPosition(0)
                    ->setLevel($section->getLevel());
    }

    /**
     * Shift position values for pages siblings of and after $page by $delta.
     *
     * @param  Page                 $page               The page for which to shift position.
     * @param  integer              $delta              The shift value of position.
     * @param  boolean              $strict             Does $page is include (true) or not (false, by default).
     *
     * @return PageRepository
     */
    private function shiftPosition(Page $page, $delta, $strict = false)
    {
        if (true === $page->hasMainSection()) {
            return $this;
        }

        $query = $this->createQueryBuilder('p')
                ->set('p._position', 'p._position + :delta_node')
                ->andWhere('p._section = :section')
                ->andWhere('p._position >= :position')
                ->setParameters([
                    'delta_node' => $delta,
                    'section' => $page->getSection(),
                    'position' => $page->getPosition(),
                ]);

        if (true === $strict) {
            $query->andWhere('p != :page')
                    ->setParameter('page', $page);
        } else {
            $page->setPosition($page->getPosition() + $delta);
        }

        $query->update()
                ->getQuery()
                ->execute();

        return $this;
    }

    /**
     * Shift level values for pages descendants of $page by $delta.
     *
     * @param  Page                 $page               The page for which to shift level.
     * @param  integer              $delta              The shift value of position.
     * @param  boolean              $strict             Does $page is include (true) or not (false, by default).
     *
     * @return PageRepository
     */
    private function shiftLevel(Page $page, $delta, $strict = false)
    {
        if (false === $page->hasMainSection() && true === $strict) {
            return $this;
        }

        $query = $this->createQueryBuilder('p')
                ->update()
                ->set('p._level', 'p._level + :delta');

        if (true === $page->hasMainSection()) {
            $subquery = $this->getEntityManager()
                    ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                    ->createQueryBuilder('n')
                    ->select('n._uid')
                    ->andIsDescendantOf($page->getSection());

            $query->andWhere('p._section IN ('.$subquery->getDQL().')')
                    ->setParameters($subquery->getParameters());

            if (true === $strict) {
                $query->andWhere('p <> :page')
                        ->setParameter('page', $page);
            }
        } else {
            $query->andWhere('p = :page')
                    ->setParameter('page', $page);
        }

        $query->setParameter('delta', $delta)->getQuery()
                ->execute();

        return $this;
    }

    /**
     * Returns the maximum position of children of $page.
     *
     * @param  Page                 $page
     *
     * @return integer
     */
    private function getMaxPosition(Page $page)
    {
        if (false === $page->hasMainSection()) {
            return 0;
        }

        $query = $this->createQueryBuilder('p');
        $max = $query->select($query->expr()->max('p._position'))
                ->andParentIs($page)
                ->getQuery()
                ->getResult(\Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);

        return (null === $max) ? 0 : $max;
    }

    /**
     * Updates nodes information of a tree.
     *
     * @param  string               $nodeUid            The starting point in the tree.
     * @param  integer              $leftNode           Optional, the first value of left node (1 by default).
     * @param  integer              $level              Optional, the first value of level (0 by default).
     *
     * @return \StdClass
     *
     * @deprecated since version 1.1
     */
    public function updateTreeNatively($nodeUid, $leftNode = 1, $level = 0)
    {
        return $this->_em
                        ->getRepository('BackBee\CoreDomain\NestedNode\Section')
                        ->updateTreeNatively($nodeUid, $leftNode, $level);
    }
}


text:
package org.jetbrains.sbt.project.template.activator

import java.io.{File, IOException}
import java.net.{URLClassLoader, HttpURLConnection}

import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.progress.{ProgressIndicator, ProgressManager}
import com.intellij.openapi.util.io.{FileUtil, StreamUtil}
import com.intellij.util.io.ZipUtil
import com.intellij.util.net.HttpConfigurable
import org.apache.lucene.document.Document
import org.apache.lucene.index.{DirectoryReader, IndexReader}
import org.apache.lucene.store.FSDirectory
import org.jetbrains.plugins.scala.project.template

/**
 * User: Dmitry.Naydanov
 * Date: 20.01.15.
 *
 *
 */
class ActivatorRepoProcessor {
  import org.jetbrains.sbt.project.template.activator.ActivatorRepoProcessor._

  private var extractedHash: Option[String] = None
  private var indexFile: Option[(String, File)] = None

  private def error(msg: String, ex: Throwable = null) {
    ActivatorRepoProcessor.log.error(msg, ex)
    throw new ConfigurationException(msg)
  }

  private def errorStr(msg: String) = error(msg, null)

  private def urlString = s"$REPO_URI/$INDEX_DIR/$VERSION"

  private def extractHash(): Option[String] = {
    if (extractedHash.isEmpty) extractedHash = {
      var downloaded: Option[String] = None

      try {
        downloaded = ActivatorRepoProcessor.downloadStringFromRepo(s"$urlString/$PROPERTIES")
      } catch {
        case io: IOException => error("Can't download index", io)
      }

      downloaded flatMap {
        case str => str.split('\n').find {
          case s => s.trim startsWith CACHE_HASH
        } map {
          case hashStr => hashStr.trim.stripPrefix(CACHE_HASH)
        }
      }
    }

    extractedHash
  }

  private def downloadIndex(): Option[File] = {
    if (extractedHash.flatMap(a => indexFile.map(b => (a, b._1))).exists(a => a._1 == a._2)) indexFile.map(_._2) else {
      extractHash() flatMap {
        case hash =>
          val tmpFile = FileUtil.createTempFile(s"index-$hash", ".zip", true)
          val downloaded = ActivatorRepoProcessor.downloadFile(s"$urlString/${indexName(hash)}",
            tmpFile.getCanonicalPath, errorStr, ProgressManager.getInstance().getProgressIndicator)

          if (downloaded) {
            indexFile = Some((hash, tmpFile))
            Some(tmpFile)
          } else None
      }
    }
  }

  private def processIndex(location: File): Map[String, DocData] = {
    if (!location.exists()) return Map.empty

    var reader: IndexReader = null

    try {
      template.usingTempDirectoryWithHandler("index-activator", None)(
      {case io: IOException => error("Can't process templates list", io); Map.empty[String, ActivatorRepoProcessor.DocData]}, {case io: IOException => }) {
        extracted =>

          ZipUtil.extract(location, extracted, null)

          import org.apache.lucene
          import org.apache.lucene.search.IndexSearcher

          val loader = getClass.getClassLoader match { //hack to avoid lucene 2.4.1 from bundled maven plugin
            case urlLoader: URLClassLoader =>
              new URLClassLoader(urlLoader.getURLs, null)
            case other => other
          }
          loader.loadClass("org.apache.lucene.store.FSDirectory")

          reader = DirectoryReader.open(FSDirectory.open(extracted))
          val searcher = new IndexSearcher(reader)
          val docs = searcher.search(new lucene.search.MatchAllDocsQuery, reader.maxDoc())
          val data = docs.scoreDocs.map { case doc => reader document doc.doc }

          data.map {
            case docData => Keys.from(docData)
          }.toMap
      }
    } catch {
      case io: IOException =>
        error("Can't process templates list", io)
        Map.empty
    } finally {
      if (reader != null) reader.close()
    }
  }

  def extractRepoData(): Map[String, DocData] = downloadIndex() match {
    case None => error("No index file"); Map.empty
    case Some(file) => processIndex(file)
  }
}

object ActivatorRepoProcessor {
  val REPO_URI = "http://downloads.typesafe.com/typesafe-activator"
  private val INDEX_DIR = "index"
  private val TEMPLATES_DIR = "templates"
  private val VERSION = "v2"
  private val PROPERTIES = "current.properties"
  private val CACHE_HASH = "cache.hash="

  private def indexName(hash: String) = s"index-$hash.zip"
  private def templateFileName(id: String) = s"$id.zip"
  private def calculateHash(id: String): String = id.take(2) + "/" + id.take(6) + "/"

  private val log = Logger.getInstance(classOf[ActivatorRepoProcessor])

  case class DocData(id: String, title: String, author: String, src: String, category: String, desc: String, tags: String)

  object Keys {
    class Key(val keyName: String) {
      def getValue(doc: Document): String = doc.get(keyName)
    }

    val TEMPLATE_ID = new Key("id")
    val NAME = new Key("name")
    val TITLE = new Key("title")
    val TAGS = new Key("tags")
    val AUTHOR_NAME = new Key("authorName")
    val SOURCE_LINK = new Key("sourceLink")
    val CATEGORY = new Key("category")
    val DESCRIPTION = new Key("description")

    def from(doc: Document) =
      (NAME getValue doc, DocData(TEMPLATE_ID getValue doc, TITLE getValue doc, AUTHOR_NAME getValue doc,
        SOURCE_LINK getValue doc, CATEGORY getValue doc, DESCRIPTION getValue doc, TAGS getValue doc))
  }

  def downloadStringFromRepo(url: String): Option[String] = {
    val conf = HttpConfigurable.getInstance()
    var connection: HttpURLConnection = null

    try {
      connection = conf openHttpConnection url
      connection.connect()

      val status = connection.getResponseMessage
      if (status != null && status.trim.startsWith("OK")) {
        val text = StreamUtil.readText(connection.getInputStream, "utf-8" /*connection.getContentEncoding*/)
        Some(text)
      } else None
    } catch {
      case _: Exception => None
    } finally {
      if (connection != null) connection.disconnect()
    }
  }

  def downloadFile(url: String, toFile: String, onError: String => Unit, indicator: ProgressIndicator = null): Boolean = {
    try {
      val file = new File(toFile)
      if (!file.exists()) return false

      ActivatorDownloadUtil.downloadContentToFile(indicator, url, file)
      true
    } catch {
      case io: IOException =>
        onError(io.getMessage)
        log.error(s"Can't download $url", io)
        false
    }
  }

  def downloadTemplateFromRepo(id: String, pathTo: File, onError: String => Unit, indicator: ProgressIndicator = null) {
    try {
      val url = s"$REPO_URI/$TEMPLATES_DIR/${calculateHash(id)}${templateFileName(id)}"
      ActivatorDownloadUtil.downloadContentToFile(indicator, url, pathTo)
    } catch {
      case io: IOException =>
        log.error(s"Can't download template $id", io)
        onError(io.getMessage)
    }

  }
}

redpajama_set_name: RedPajamaGithub


text:
Install and trust a CA at the operating system level, making it available for use by
OpenStack services and other network clients authenticating SSL-secured connections.

Configuration
-------------

    ssl:
      ca_certificate: certdata

The CA certificate will be written to /etc/ssl/from-heat-ca.crt and installed using
update-ca-certificates (apt-based distros) or update-ca-trusts (yum-based distros).

This may be used in conjunction with openstack-ssl to enable SSL-secure connections
between OpenStack services, or independently to enable secure integration with
external resources such as Keystone -> LDAP server or Cinder -> external backend.

If multiple CA certificates are to be trusted, they should be concatenated in PEM
format within the single ca_certificate property defining the trust store.


text:
class Solution:
    # @param {integer[]} nums
    # @param {integer} k
    # @return {boolean}
    def containsNearbyDuplicate(self, nums, k):
        if not self.containsDuplicate(nums):
            return False
        for i in range(len(nums) - 1):
            end = i + k
            if end >= len(nums):
                end = len(nums) - 1
            for j in range(end, i, -1):
                if nums[i] == nums[j]:
                    return True
        return False

    def containsDuplicate(self, nums):
        nums = sorted(nums)
        for idx in range(len(nums) - 1):
            if nums[idx] == nums[idx+1]:
                return True
        return False


text:
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

namespace Microsoft.HBase.Client.Filters
{
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Text;

    /// <summary>
    /// This comparator is for use with CompareFilter implementations, such as RowFilter, QualifierFilter, and
    /// ValueFilter, for filtering based on the value of a given column.
    /// </summary>
    public class RegexStringComparator : ByteArrayComparable
    {
        // note:  could not get "flags" to stringify, so it has been removed.

        /// <summary>
        /// Initializes a new instance of the <see cref="RegexStringComparator"/> class.
        /// </summary>
        /// <param name="expr">The regular expression as a string.</param>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "expr")]
        public RegexStringComparator(string expr) : base(expr == null ? null : Encoding.UTF8.GetBytes(expr))
        {
        }

        /// <inheritdoc/>
        public override string ToEncodedString()
        {
            const string pattern = @"""type"":""RegexStringComparator"", ""value"":""{0}""";
            return string.Format(CultureInfo.InvariantCulture, pattern, Encoding.UTF8.GetString(Value));
        }
    }
}


text:
using System.Collections.Generic;

using Newtonsoft.Json;

namespace Todoist.Net.Models
{
    internal class IdToOrderArgument : ICommandArgument
    {
        public IdToOrderArgument(IEnumerable<OrderEntry> orderEntries)
        {
            Ids = new Dictionary<ComplexId, int>();
            foreach (var entry in orderEntries)
            {
                Ids.Add(entry.Id, entry.Order);
            }
        }

        [JsonProperty("ids_to_orders")]
        public IDictionary<ComplexId, int> Ids { get; set; }
    }
}


text:
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['core'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('./core'));
  }
}(this, function (core) {
  'use strict';

  var module = {};

  var PATH_WIDTH = 4;

  module.BACKGROUND_COLOUR = '#F5F5F5';
  module.OBSTACLE_COLOUR = '#212121';
  module.PATH_COLOUR = '#12c700';
  module.CLOSED_LIST_COLOUR = '#01579b';
  module.OPEN_LIST_COLOUR = '#29b6f6';

  var canvas;
  var context;

  module.setCanvas = function (canvasElement) {
    canvas = canvasElement;
    if (canvas && canvas.getContext) {
      context = canvas.getContext('2d');
    }
  };

  module.drawObstacles = function (map) {
    for (var x = 0; x < core.MAP_WIDTH; x++) {
      for (var y = 0; y < core.MAP_HEIGHT; y++) {
        if (!map[x][y]) {
          module.drawObstacle(x, y);
        }
      }
    }
  };

  module.drawObstacle = function (x, y) {
    module.drawNode(x, y, module.OBSTACLE_COLOUR);
  };

  module.clearObstacle = function (x, y) {
    module.drawNode(x, y, module.BACKGROUND_COLOUR);
  };

  module.drawVisited = function (x, y) {
    module.drawNode(x, y, module.CLOSED_LIST_COLOUR);
  };

  module.drawOpenListNode = function (x, y) {
    module.drawNode(x, y, module.OPEN_LIST_COLOUR);
  };

  module.drawStartGoal = function (x, y) {
    module.drawNode(x, y, module.PATH_COLOUR);
  };

  module.drawNode = function (x, y, COLOUR) {
    context.fillStyle = COLOUR;
    context.fillRect(x * core.MAP_SCALE, y * core.MAP_SCALE, core.MAP_SCALE, core.MAP_SCALE);
  };

  module.clearCanvas = function () {
    context.fillStyle = module.BACKGROUND_COLOUR;
    context.fillRect(0, 0, core.CANVAS_WIDTH, core.CANVAS_HEIGHT);
  };

  module.draw = function (closedList, openList, startNode, goalNode) {
    module.drawStartGoal(goalNode.x, goalNode.y);
    module.drawStartGoal(startNode.x, startNode.y);

    context.beginPath();
    context.moveTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);

    for (var i = 0; i < openList.length; i++) {
      module.drawOpenListNode(openList[i].x, openList[i].y);
    }

    while (goalNode.parent) {
      goalNode = goalNode.parent;
      context.lineTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);
    }

    context.strokeStyle = module.PATH_COLOUR;
    context.lineWidth = PATH_WIDTH;
    context.stroke();
    context.closePath();
  };

  module.drawPath = function (goalNode) {
    context.beginPath();
    context.moveTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);

    while (goalNode.parent) {
      goalNode = goalNode.parent;
      context.lineTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);
    }

    context.strokeStyle = module.PATH_COLOUR;
    context.lineWidth = PATH_WIDTH;
    context.stroke();
    context.closePath();
  };

  module.getCanvasWidth = function () {
    canvas.setAttribute('width', canvas.clientWidth);
    return canvas.clientWidth;
  };

  module.getCanvasHeight = function () {
    canvas.setAttribute('height', canvas.clientHeight);
    return canvas.clientHeight;
  };

  return module;
}));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
The fungi of Manitoba 74 (1929)

#### Original name
Metasphaeria querna Dearn. & Bisby

### Remarks
null


text:
class RenderAsyncsController < ApplicationController
  layout "no_jquery", only: :show_no_jquery

  # actions for rendering pages

  # GET /render_async
  def show
  end

  # GET /render_async/show_no_jquery
  def show_no_jquery
  end

  # actions for rendering using render_async

  # GET /render_async/wave
  def wave
    render layout: false
  end

  # POST /render_async/bump
  def bump
    @body = request.body.read
    render layout: false
  end

  # GET /render_async/error
  def error
    head :not_found, layout: false
  end

  # GET /render_async/nested
  def nested
    render layout: false
  end
end


text:
import Ember from "ember";

export default Ember.Component.extend({
  content: null,
  selectedValue: null,

  didInitAttrs() {
    this._super(...arguments);
    var content = this.get('content');

    if (!content) {
      this.set('content', []);
    }
  }
});


text:
package org.workcraft.serialisation.xml;

import static org.workcraft.serialisation.xml.BeanInfoCache.getBeanInfo;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Element;
import org.workcraft.dom.visual.Dependent;
import org.workcraft.exceptions.DeserialisationException;
import org.workcraft.serialisation.ReferenceResolver;
import org.workcraft.util.ConstructorParametersMatcher;
import org.workcraft.util.XmlUtils;

class DefaultNodeDeserialiser {
    private final DeserialiserFactory fac;
    private final NodeInitialiser initialiser;
    private final NodeFinaliser finaliser;

    DefaultNodeDeserialiser(DeserialiserFactory factory, NodeInitialiser initialiser, NodeFinaliser finaliser) {
        this.fac = factory;
        this.initialiser = initialiser;
        this.finaliser = finaliser;
    }

    private void autoDeserialiseProperties(Element currentLevelElement,
            Object instance, Class<?> currentLevel,
            ReferenceResolver externalReferenceResolver)
            throws DeserialisationException {
        if (currentLevel.getAnnotation(NoAutoSerialisation.class) != null) {
            return;
        }

        try {
            List<Element> propertyElements = XmlUtils.getChildElements("property", currentLevelElement);
            HashMap<String, Element> nameMap = new HashMap<>();

            for (Element e : propertyElements) {
                nameMap.put(e.getAttribute("name"), e);
            }

            BeanInfo info = getBeanInfo(currentLevel);

            for (PropertyDescriptor desc : info.getPropertyDescriptors()) {
                if (!nameMap.containsKey(desc.getName())) {
                    continue;
                }

                if (desc.getPropertyType() == null) {
                    continue;
                }

                if (desc.getWriteMethod() == null || desc.getReadMethod() == null) {
                    continue;
                }

                // property explicitly requested to be excluded from auto serialisation
                if (
                        desc.getReadMethod().getAnnotation(NoAutoSerialisation.class) != null ||
                        desc.getWriteMethod().getAnnotation(NoAutoSerialisation.class) != null
                ) {
                    continue;
                }

                // the property is writable and is not of array type, try to get a deserialiser
                XMLDeserialiser deserialiser = fac.getDeserialiserFor(desc.getPropertyType().getName());

                if (!(deserialiser instanceof BasicXMLDeserialiser)) {
                    // no deserialiser, try to use the special case enum deserialiser
                    if (desc.getPropertyType().isEnum()) {
                        deserialiser = fac.getDeserialiserFor(Enum.class.getName());
                        if (deserialiser == null) {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }

                Element element = nameMap.get(desc.getName());
                Object value = ((BasicXMLDeserialiser) deserialiser).deserialise(element);

                desc.getWriteMethod().invoke(instance, value);
            }
        } catch (IllegalArgumentException | IllegalAccessException | InstantiationException |
                IntrospectionException e) {
            throw new DeserialisationException(e);
        } catch (InvocationTargetException e) {
            throw new DeserialisationException(instance.getClass().getName() + " " + currentLevel.getName() + " " + e.getMessage(), e);
        }
    }

    public Object initInstance(Element element, ReferenceResolver externalReferenceResolver, Object ... constructorParameters) throws DeserialisationException {
        String className = element.getAttribute("class");

        if (className == null || className.isEmpty()) {
            throw new DeserialisationException("Class name attribute is not set\n" + element.toString());
        }

        //System.out.println("Initialising " + className);

        try {
            Class<?> cls = Class.forName(className);
            String shortClassName = cls.getSimpleName();

            Element currentLevelElement = XmlUtils.getChildElement(shortClassName, element);

            Object instance;

            // Check for a custom deserialiser first
            XMLDeserialiser deserialiser = fac.getDeserialiserFor(className);

            if (deserialiser instanceof CustomXMLDeserialiser) {
                //System.out.println("Using custom deserialiser " + deserialiser);
                instance = ((CustomXMLDeserialiser) deserialiser).createInstance(currentLevelElement, externalReferenceResolver, constructorParameters);
            } else if (deserialiser instanceof BasicXMLDeserialiser) {
                //System.out.println("Using basic deserialiser " + deserialiser);
                instance = ((BasicXMLDeserialiser) deserialiser).deserialise(currentLevelElement);
            } else {
                //System.out.println("Using default deserialiser " + deserialiser);

                // Check for incoming parameters - these may be supplied when a custom deserialiser requests
                // a sub-node to be deserialised which should know how to construct this class and pass
                // the proper constructor arguments

                if (constructorParameters.length != 0) {
                    Class<?>[] parameterTypes = new Class<?>[constructorParameters.length];
                    for (int i = 0; i < constructorParameters.length; i++) {
                        parameterTypes[i] = constructorParameters[i].getClass();
                    }
                    Constructor<?> ctor = new ConstructorParametersMatcher().match(Class.forName(className), parameterTypes);
                    instance = ctor.newInstance(constructorParameters);
                } else {
                    // Still don't know how to deserialise the class.
                    // Let's see if it is a dependent node.

                    if (Dependent.class.isAssignableFrom(cls)) {
                        // Check for the simple case when there is only one reference to the underlying model.
                        String ref = currentLevelElement.getAttribute("ref");
                        if (ref.isEmpty()) {
                            // Bad luck, we probably can't do anything.
                            // But let's try a default constructor just in case.
                            instance = cls.newInstance();
                        } else {
                            // Hooray, we've got a reference, so there is likely an appropriate constructor.
                            Object refObject = externalReferenceResolver.getObject(ref);
                            Constructor<?> ctor = new ConstructorParametersMatcher().match(cls, refObject.getClass());
                            instance = ctor.newInstance(refObject);
                        }
                    } else {
                        // It is not a dependent node, so there should be a default constructor.
                        instance = cls.newInstance();
                    }
                }
            }

            //System.out.println("Result = " + instance);

            doInitialisation(element, instance, instance.getClass(), externalReferenceResolver);

            return instance;
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException |
                NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
            throw new DeserialisationException(e);
        }
    }

    void doInitialisation(Element element, Object instance, Class<?> currentLevel, ReferenceResolver externalReferenceResolver) throws DeserialisationException {
        Element currentLevelElement = XmlUtils.getChildElement(currentLevel.getSimpleName(), element);
        if (currentLevelElement != null) {
            autoDeserialiseProperties(currentLevelElement, instance, currentLevel, externalReferenceResolver);
        }

        try {
            XMLDeserialiser deserialiser = fac.getDeserialiserFor(currentLevel.getName());

            if (deserialiser instanceof CustomXMLDeserialiser) {
                ((CustomXMLDeserialiser) deserialiser).initInstance(currentLevelElement, instance, externalReferenceResolver, initialiser);
            }
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DeserialisationException(e);
        }

        if (currentLevel.getSuperclass() != Object.class) {
            doInitialisation(element, instance, currentLevel.getSuperclass(), externalReferenceResolver);
        }
    }

    void doFinalisation(Element element, Object instance,
            ReferenceResolver internalReferenceResolver,
            ReferenceResolver externalReferenceResolver,
            Class<?> currentLevel)
            throws DeserialisationException {
        Element currentLevelElement = XmlUtils.getChildElement(currentLevel.getSimpleName(), element);
        if (currentLevelElement != null) {
            try {
                XMLDeserialiser deserialiser = fac.getDeserialiserFor(currentLevel.getName());
                if (deserialiser instanceof CustomXMLDeserialiser) {
                    CustomXMLDeserialiser customDeserialiser = (CustomXMLDeserialiser) deserialiser;
                    customDeserialiser.finaliseInstance(currentLevelElement, instance,
                            internalReferenceResolver, externalReferenceResolver, finaliser);
                }
            } catch (InstantiationException e) {
                throw new DeserialisationException(e);
            } catch (IllegalAccessException e) {
                throw new DeserialisationException(e);
            }
        }
        if (currentLevel.getSuperclass() != Object.class) {
            doFinalisation(element, instance, internalReferenceResolver, externalReferenceResolver, currentLevel.getSuperclass());
        }
    }

    public void finaliseInstance(Element element, Object instance, ReferenceResolver internalReferenceResolver,
            ReferenceResolver externalReferenceResolver) throws DeserialisationException {
        doFinalisation(element, instance, internalReferenceResolver, externalReferenceResolver, instance.getClass());
    }

}


text:
import pytest
import tensorflow as tf
import numpy as np
from tfs.models import LeNet

from tfs.dataset.predefined import Mnist
import tfs.g

@pytest.fixture
def data():
  mnist=Mnist().to_one_hot()
  return mnist

@pytest.fixture
def net():
  n = LeNet()
  n.build()
  return n

class TestOptimizer:
  def test_fit(self,data,net,capsys):
    if tfs.g.config['test']['optimizer']:
      with capsys.disabled():
        net.monitor['default'].interval=1
        net.fit(data,batch_size=300,n_epoch=1,max_step=20)


text:
layout: post
title: Screamland Farms - You Should Probably Start Screaming
tags:
 - texture
 - zombies
 - dark
 - blood

exhibit: 2017-04-06-screamlandfarms.com.png
link: http://web.archive.org/web/20120917000415/http://www.screamlandfarms.com/
founder: woodylama
---


text:
#include "caffe2/operators/reverse_packed_segs_op.h"

namespace caffe2 {
REGISTER_CPU_OPERATOR(ReversePackedSegs, ReversePackedSegsOp<CPUContext>);

OPERATOR_SCHEMA(ReversePackedSegs)
    .NumInputs(2)
    .NumOutputs(1)
    .SetDoc(R"DOC(
Reverse segments in a 3-D tensor (lengths, segments, embeddings,), leaving
paddings unchanged. This operator is used to reverse input of a recurrent neural
network to make it a BRNN.
  )DOC")
    .Input(0, "data", "a 3-D (lengths, segments, embeddings,) tensor.")
    .Input(1, "lengths", "length of each segment.")
    .Output(
        0,
        "reversed data",
        "a (lengths, segments, embeddings,) tensor with each segment reversed"
        "and paddings unchanged.");

class GetReversePackedSegsGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    return SingleGradientDef(
        "ReversePackedSegs",
        "",
        vector<string>{GO(0), I(1)},
        vector<string>{GI(0)});
  }
};
REGISTER_GRADIENT(ReversePackedSegs, GetReversePackedSegsGradient);
} // namespace caffe2


text:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from feedback.models import Feedback
from feedback.feeds import FeedbackFeed

info_dict = {
    'queryset': Feedback.objects.all(),
}

urlpatterns = patterns('feedback.views',
    url(r'^$', 'index', name='feedback_index'),
    url(r'^submit-feedback$', 'index', name='submit_feedback'),
    url(r'^(?P<filter_by>\w+)/(?P<page>\d+/)?$', 'show_list', name='show_list'),
)
urlpatterns += patterns('',
    url(r'show/(?P<object_id>\d+)$',
    'django.views.generic.list_detail.object_detail', info_dict, name='show_message'),
    url(r'^rss$', FeedbackFeed(), name="feedback_rss"),
 )


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/joint.css">

WOW Logger - Data Structures Overview

Download specification file: wow-logging-spec.json

Show class list

Show class diagram


text:
module ActiveMerchant #:nodoc:
  module RequiresParameters #:nodoc:
    def requires!(hash, *params)
      keys = hash.keys
      params.each do |param|
        if param.is_a?(Array)
          raise ArgumentError.new("Missing required parameter: #{param.first}") unless keys.include?(param.first)

          valid_options = param[1..-1]
          raise ArgumentError.new("Parameter: #{param.first} must be one of #{valid_options.to_sentence(:connector => 'or')}") unless valid_options.include?(hash[param.first])
        else
          raise ArgumentError.new("Missing required parameter: #{param}") unless keys.include?(param)
        end
      end
    end
  end
end


text:
import {DataPoint, DataProto, DataSet, SpriteAndMetadataInfo, PointMetadata, State} from './data';
import {analyzeMetadata, ProjectorConfig, DataProvider} from './data-provider';

export class ProtoDataProvider implements DataProvider {
  private dataProto: DataProto;

  constructor(dataProto: DataProto) {
    this.dataProto = dataProto;
  }

  retrieveRuns(callback: (runs: string[]) => void): void {
    callback(['proto']);
  }

  retrieveProjectorConfig(run: string, callback: (d: ProjectorConfig) => void) {
    callback({
      modelCheckpointPath: 'proto',
      embeddings: [{
        tensorName: 'proto',
        tensorShape: this.dataProto.shape,
        metadataPath: 'proto'
      }]
    });
  }

  retrieveTensor(run: string, tensorName: string,
      callback: (ds: DataSet) => void) {
    callback(this.flatArrayToDataset(this.dataProto.tensor));
  }

  retrieveSpriteAndMetadata(run: string, tensorName: string,
      callback: (r: SpriteAndMetadataInfo) => void): void {
    let columnNames = this.dataProto.metadata.columns.map(c => c.name);
    let n = this.dataProto.shape[0];
    let pointsMetadata: PointMetadata[] = new Array(n);
    this.dataProto.metadata.columns.forEach(c => {
      let values = c.numericValues || c.stringValues;
      for (let i = 0; i < n; i++) {
        pointsMetadata[i] = pointsMetadata[i] || {};
        pointsMetadata[i][c.name] = values[i];
      }
    });
    callback({
      stats: analyzeMetadata(columnNames, pointsMetadata),
      pointsInfo: pointsMetadata
    });
  }

  getDefaultTensor(run: string, callback: (tensorName: string) => void): void {
    callback('proto');
  }

  getBookmarks(run: string, tensorName: string,
      callback: (r: State[]) => void): void {
    return callback([]);
  }

  private flatArrayToDataset(tensor: number[]): DataSet {
    let points: DataPoint[] = [];
    let n = this.dataProto.shape[0];
    let d = this.dataProto.shape[1];
    if (n * d !== tensor.length) {
      throw 'The shape doesn\'t match the length of the flattened array';
    }
    for (let i = 0; i < n; i++) {
      let offset = i * d;
      points.push({
        vector: new Float32Array(tensor.slice(offset, offset + d)),
        metadata: {},
        projections: null,
        index: i
      });
    }
    return new DataSet(points);
  }
}


text:
using CsvHelper.Configuration;
using NoBeerNoParty.Common.Model;

namespace NoBeerNoParty.Simulation.Services
{
    /// <summary>
    /// Mapper for currency csv file configuration
    /// </summary>
    public sealed class BeersCsvMapper: CsvClassMap<Beer>, ICsvMapper<Beer>
    {
        /// <summary>
        /// CurrencyCsvMapper Constructor
        /// </summary>
        public BeersCsvMapper()
        {
            Map(m => m.ExternalId).Index(0);
            Map(m => m.Name).Index(3);
            Map(m => m.BreweryId).Index(1);
            Map(m => m.Price).Index(2);
            Map(m => m.Style).Index(4).TypeConverter(new BeerTypeConverter());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/rounded_button_shape_hover" android:state_pressed="true"></item>
    <item android:drawable="@drawable/rounded_button_shape_hover" android:state_focused="true"></item>
    <item android:drawable="@drawable/rounded_button_shape_hover" android:state_enabled="false"></item>
    <item android:drawable="@drawable/rounded_button_shape" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>

</selector>


text:
@interface PodsDummy_Pods_RBSQLite_Example : NSObject
@end
@implementation PodsDummy_Pods_RBSQLite_Example
@end


text:
Puppet::Type.newtype(:ec2_security_group) do
  @doc = "Ensure the current EC2 instance is part of a given SG."

  ensurable
  newparam(:group_id) do
    isnamevar
    desc "The AWS security group ID."
    validate do |value|
      unless value =~ /^sg-\w+/
        raise ArgumentError, "%s is not a valid security group ID." % value
      end
    end
  end
end


text:
/* http://keith-wood.name/calendars.html
   Spanish/Perú localisation for Gregorian/Julian calendars for jQuery.
   Written by Fischer Tirado (fishdev@globant.com) of ASIX (http://www.asixonline.com). */
(function($) {
	$.calendars.calendars.gregorian.prototype.regionalOptions['es-PE'] = {
		name: 'Gregorian',
		epochs: ['BCE', 'CE'],
		monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
		'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
		monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
		'Jul','Ago','Sep','Oct','Nov','Dic'],
		dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
		dayNamesShort: ['Dom','Lun','Mar','Mié','Jue','Vie','Sab'],
		dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sa'],
		dateFormat: 'dd/mm/yyyy',
		firstDay: 0,
		isRTL: false
	};
	if ($.calendars.calendars.julian) {
		$.calendars.calendars.julian.prototype.regionalOptions['es-PE'] =
			$.calendars.calendars.gregorian.prototype.regionalOptions['es-PE'];
	}
})(jQuery);


text:
<?php

declare(strict_types=1);

namespace Xtreamwayz\HTMLFormValidator\FormElement;

use Laminas\Filter\StringToLower as StringToLowerFilter;
use Laminas\Validator\Regex as RegexValidator;

class Color extends BaseFormElement
{
    protected function getFilters(): array
    {
        return [
            ['name' => StringToLowerFilter::class],
        ];
    }

    protected function getValidators(): array
    {
        return [
            [
                'name'    => RegexValidator::class,
                'options' => ['pattern' => '/^#[0-9a-fA-F]{6}$/'],
            ],
        ];
    }
}


text:
package io.jumpon.api.library.encryption;
import java.io.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {

    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}


text:
'''
Run a pipeline stage either locally or on the cluster,
taking into account the configuration settings,
and command line options of the pipeline.
'''

from ruffus.drmaa_wrapper import run_job, error_drmaa_job

# slurm memory is requested in MB, but the config file specifies in GB
MEGABYTES_IN_GIGABYTE = 1024

'''
SLURM options:

--account=name          Charge job to specified accounts
--exclusive             Allocate nodenumber of tasks to invoke on each nodes
                        in exclusive mode when cpu consumable resource is
                        enabled
--mem=MB                Minimum amount of real memory
--mem-per-cpu=MB        Maximum amount of real memory per allocated cpu
                        required by a job
--mincpus=n             Minimum number of logical processors (threads)
                        per node
--nodes=N               Number of nodes on which to run (N = min[-max])
--ntasks-per-node=n     Number of tasks to invoke on each node
--partition=partition   Partition requested
--reservation=name      Allocate resources from named reservation
--time=hours:minutes    Set a maximum job wallclock time
--ntasks=n              Number of tasks
--mail-type             Notify user by email when certain event types
                        occur. Valid type values are BEGIN, END, FAIL,
                        REQUEUE, and ALL (any state change)
'''

def run_stage(state, stage, command):
    '''Run a pipeline stage, either locally or on the cluster'''

    # Grab the configuration options for this stage
    config = state.config
    modules = config.get_stage_option(stage, 'modules')
    mem = config.get_stage_option(stage, 'mem') * MEGABYTES_IN_GIGABYTE
    account = config.get_stage_option(stage, 'account')
    queue = config.get_stage_option(stage, 'queue')
    walltime = config.get_stage_option(stage, 'walltime')
    run_local = config.get_stage_option(stage, 'local')
    cores = config.get_stage_option(stage, 'cores')
    pipeline_id = config.get_option('pipeline_id')
    job_name = pipeline_id + '_' + stage

    # Generate a "module load" command for each required module
    if modules is not None:
        module_loads = '\n'.join(['module load ' + module for module in modules])
    else:
        module_loads = '\n'
    cluster_command = '\n'.join([module_loads, command])

    # Specify job-specific options for SLURM
    job_options = '--nodes=1 --ntasks-per-node={cores} --ntasks={cores} --time={time} --mem={mem} --partition={queue} --account={account}' \
                      .format(cores=cores, time=walltime, mem=mem, queue=queue, account=account)

    # Log a message about the job we are about to run
    log_messages = ['Running stage: {}'.format(stage),
                    'Command: {}'.format(command)]
    if not run_local:
        log_messages.append('Job options: {}'.format(job_options))
    state.logger.info('\n'.join(log_messages))

    # Run the job, capturing stdout and stderr
    stdout_res, stderr_res = None, None
    try:
        stdout_res, stderr_res = \
            run_job(cmd_str=cluster_command,
                job_name = job_name,
                logger = state.logger.proxy,
                drmaa_session = state.drmaa_session,
                # Determines whether to run the command on the local
                # machine or run it on the cluster
                run_locally = run_local,
                # Keep a copy of the job script for diagnostic purposes
                retain_job_scripts = True,
                retain_stdout = True,
                retain_stderr = True,
                job_script_directory = state.options.jobscripts,
                job_other_options = job_options)
    except error_drmaa_job as err:
        raise Exception("\n".join(map(str, ["Failed to run:", command, err, stdout_res, stderr_res])))


text:
network_interface 'eth0' unless node['os'] == 'windows'

case node['platform_family']
when 'rhel', 'fedora'
  rhel_network_interface 'eth1' do
    bootproto 'none'
    bridge_device 'br0'
  end

  rhel_network_interface 'br0' do
    bootproto 'static'
    address '13.13.13.10'
    netmask '255.255.255.0'
  end
when 'debian'
  debian_network_interface 'br0' do
    bootproto 'static'
    address '13.13.13.11'
    netmask '255.255.255.0'
    bridge_ports ['eth1']
    bridge_stp false
  end

  network_interface 'eth1' do
    bootproto 'manual'
  end
end


text:
package ch.epfl.bbp.uima.ae;

import static ch.epfl.bbp.uima.typesystem.TypeSystem.MULTIPLE_PROTEINS;
import static org.apache.uima.fit.util.JCasUtil.select;

import java.util.Collection;

import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.TypeCapability;
import org.apache.uima.jcas.JCas;

import ch.epfl.bbp.uima.types.MultipleProteins;
import ch.epfl.bbp.uima.types.Protein;

/**
 * Adds a {@link MultipleProteins} annotations if there is more that one
 * {@link Protein} in this document
 *
 * @author renaud.richardet@epfl.ch
 */
@TypeCapability(outputs = { MULTIPLE_PROTEINS })
public class MultipleProteinsAnnotator extends JCasAnnotator_ImplBase {

    @Override
    public void process(JCas jcas) throws AnalysisEngineProcessException {

        Collection<Protein> select = select(jcas, Protein.class);
        if (select.size() > 1) {
            MultipleProteins mp = new MultipleProteins(jcas);
            mp.setPresent(1);
            mp.addToIndexes();
        }
    }
}


text:
namespace g{namespace Android{namespace android{namespace view{struct ViewGroupOverlay;}}}}

namespace g{
namespace Android{
namespace android{
namespace view{

// public sealed extern class ViewGroupOverlay :22929
// {
::g::Android::java::lang::Object_type* ViewGroupOverlay_typeof();

struct ViewGroupOverlay : ::g::Android::android::view::ViewOverlay
{
};
// }

}}}} // ::g::Android::android::view


text:
package org.apache.commons.math3.geometry.partitioning;

import org.apache.commons.math3.geometry.Point;
import org.apache.commons.math3.geometry.Space;

/** Class holding the result of point projection on region boundary.
 *
This class is a simple placeholder, it does not provide any
 * processing methods.

 *
Instances of this class are guaranteed to be immutable

 * @param <S> Type of the space.
 * @version $Id: BoundaryProjection.java 1560335 2014-01-22 12:39:06Z luc $
 * @since 3.3
 * @see AbstractRegion#projectToBoundary(Point)
 */
public class BoundaryProjection<S extends Space> {

    /** Original point. */
    private final Point<S> original;

    /** Projected point. */
    private final Point<S> projected;

    /** Offset of the point with respect to the boundary it is projected on. */
    private final double offset;

    /** Constructor from raw elements.
     * @param original original point
     * @param projected projected point
     * @param offset offset of the point with respect to the boundary it is projected on
     */
    public BoundaryProjection(final Point<S> original, final Point<S> projected, final double offset) {
        this.original  = original;
        this.projected = projected;
        this.offset    = offset;
    }

    /** Get the original point.
     * @return original point
     */
    public Point<S> getOriginal() {
        return original;
    }

    /** Projected point.
     * @return projected point, or null if there are no boundary
     */
    public Point<S> getProjected() {
        return projected;
    }

    /** Offset of the point with respect to the boundary it is projected on.
     *

     * The offset with respect to the boundary is negative if the {@link
     * #getOriginal() original point} is inside the region, and positive otherwise.
     *

     *

     * If there are no boundary, the value is set to either {@code
     * Double.POSITIVE_INFINITY} if the region is empty (i.e. all points are
     * outside of the region) or {@code Double.NEGATIVE_INFINITY} if the region
     * covers the whole space (i.e. all points are inside of the region).
     *

     * @return offset of the point with respect to the boundary it is projected on
     */
    public double getOffset() {
        return offset;
    }

}


text:
'use strict';

var vistaLib = require('./VistALib');

exports.resolveBoilerplates = function(params, session, ewd) {
    var result = ewd.mumps.function('BOILPLTS^ZZTDP', params.patientId, params.text);
    return result;
};


text:
layout: post
title: "Xonro 'Beefy' Skullcrusher"
date: 2016-02-29
tags: [medium, humanoid, cr4]
---
1
**Medium humanoid (tiefling), neutral evil**

**Armor Class** 21 (unarmored, shield)

**Hit Points** 67 (5d12+1d8+30)

**Speed** 40 ft

|   STR   |   DEX   |   CON   |   INT   |   WIS   |   CHA   |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 20 (+5) | 18 (+4) | 20 (+5) | 10 (+0) | 12 (+1) | 10 (+0) |

**Saving Throws** Dexterity +7, Intelligence +2

**Skills** Acrobatics +7, Athletics +9, Deception +1, Investigation +2, Sleight of Hand +7, Stealth +9

**Senses** Passive Perception 11

**Languages** Imperial, Orc, Elf

**Challenge** 3

**Sneak Attack:** 1d6 extra damage when have advantage or an ally within 5 ft once per turn.

**Rage** Twice per day +3 damage, resistance to all damage but psychic, advantage on strength checks for 1 minute.

**Reckless Attack** Get advantage on attacks and give opponents advantage until next turn.

**Actions**

**Multiattack** Skullcrusher makes 2 attacks when he takes the attack action on his turn.

**+1 Gauntlet Claws** +8 to hit (1d6 + 6 (+9 if raging). If the attack hits, the opponent must make a DC 17 Strength Save or be grappled.

**Skullcrush** If Skullcrusher has an opponent grappled, he can attempt to crush their skull.  They must make a DC 17 Constitution save or take 5d8 damage, or half as much on a success. Any opponent reduced to 0 by this effect has their skull crushed and is instantly dead.

**Throwing Knives** +7 to hit range 20/60 (1d4+5)

**Reactions**