<?php

namespace Alcalyn\NeuralNetwork;

class Network
{
    /**
     * @var int
     */
    public $id;

    /**
     * @var string
     */
    public $name;

    /**
     * @var float
     */
    public $e = 0.5;

    /**
     * @var array
     */
    public $structure;

    /**
     * @var Layer[]
     */
    public $layers;

    /**
     * @param array $structure
     */
    public function __construct(array $structure)
    {
        $this->structure = $structure;
        $this->layers = [];

        foreach ($structure as $size) {
            $this->layers []= new Layer($size);
        }

        $this->linkLayers();
    }

    /**
     * @param float[] $in
     *
     * @return float[]
     */
    public function pulseInput(array $in)
    {
        $this->setInput($in);
        $this->pulse();

        return $this->getOutput();
    }

    /**
     * Pulse.
     */
    public function pulse()
    {
        for ($i = 1; $i < count($this->structure); $i++) {
            $this->layers[$i]->pulse();
        }
    }

    /**
     * @param float[] $in
     * @param float[] $expected
     *
     * @return float[]
     */
    public function trainInput(array $in, array $expected)
    {
        if ($this->getInputLayer()->size !== count($in)) {
            throw new RuntimeException('Input array length must be the same as input length.');
        }

        if ($this->getOutputLayer()->size !== count($expected)) {
            throw new RuntimeException('Expected array length must be the same as output length.');
        }

        $out = $this->pulseInput($in);

        $layer = $this->getOutputLayer();

        for ($i = 0; $i < $layer->size; $i++) {
            $neuron = $layer->neurons[$i];
            $neuron->gradiant = $neuron->axion * (1 - $neuron->axion) * ($expected[$i] - $neuron->axion);
        }

        for ($j = count($this->structure) - 2; $j >= 1; $j--) {
            $layer = $this->layers[$j];

            foreach ($layer->neurons as $neuron) {
                $sum = 0;

                foreach ($neuron->succ as $succ) {
                    $sum += $succ->neuronFrom->gradiant * $succ->w;
                }

                $neuron->gradiant = $neuron->axion * (1 - $neuron->axion) * $sum;
            }
        }

        for ($j = 1; $j < count($this->structure); $j++) {
            foreach ($this->layers[$j]->neurons as $neuron) {
                foreach ($neuron->dendrites as $dendrite) {
                    $dendrite->w += $this->e * $neuron->gradiant * $dendrite->neuron->axion;
                }
            }
        }

        return $out;
    }

    /**
     * Link layers together.
     */
    public function linkLayers()
    {
        for ($i = 1; $i < count($this->structure); $i++) {
            $this->layers[$i]->bind($this->layers[$i - 1]);
        }
    }

    /**
     * @param float[] $in
     *
     * @throws RuntimeException
     */
    public function setInput(array $in)
    {
        if ($this->getInputLayer()->size !== count($in)) {
            throw new RuntimeException('Input array length must be the same as input length.');
        }

        for ($i = 0; $i < $this->structure[0]; $i++) {
            $this->getInputLayer()->neurons[$i]->axion = $in[$i];
        }
    }

    /**
     * @return float[]
     */
    public function getOutput()
    {
        $output = [];

        foreach ($this->getOutputLayer()->neurons as $neuron) {
            $output []= $neuron->axion;
        }

        return $output;
    }

    /**
     * @return Layer
     */
    public function getInputLayer()
    {
        return $this->layers[0];
    }

    /**
     * @return Layer
     */
    public function getOutputLayer()
    {
        return $this->layers[count($this->layers) - 1];
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $output = '';
        $layerCount = 0;

        foreach ($this->layers as $layer) {
            $output .= PHP_EOL.'   Layer '.$layerCount.PHP_EOL.PHP_EOL;

            foreach ($layer->neurons as $neuron) {
                $output .= 'Neuron'.PHP_EOL;

                if ($layerCount > 0) {
                    foreach ($neuron->dendrites as $dendrite) {
                        $output .= 'x ='.self::f($dendrite->neuron->axion).'   ';
                    }

                    $output .= PHP_EOL;

                    foreach ($neuron->dendrites as $dendrite) {
                        $output .= 'w ='.self::f($dendrite->w).'   ';
                    }

                    $output .= PHP_EOL;
                }

                $output .= 'Axion ='.self::f($neuron->axion).PHP_EOL.PHP_EOL;
            }

            $layerCount++;
        }

        return $output.PHP_EOL;
    }

    private static function f($float)
    {
        return ($float >= 0 ? ' ' : '').number_format($float, 3, '.', '');
    }
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Menu;

class MainMenuBuilder
{
    /**
     * @var ContainerProvider
     */
    protected $provider;

    /**
     * @param ContainerProvider $provider
     */
    public function __construct(ContainerProvider $provider)
    {
        $this->provider = $provider;
    }

    /**
     * @param Factory $factory
     * @param Helper  $helper
     *
     * @return \Knp\Menu\ItemInterface
     */
    public function getMenu($factory, $helper)
    {
        $menu = $factory->createItem('root');

        return $menu;
    }

    /**
     * @param Factory $factory
     * @param Helper  $helper
     *
     * @return \Knp\Menu\ItemInterface
     */
    public function getSideMenu($factory, $helper)
    {
        $menu = $factory->createItem('root');

        if ($helper->isUserLogged()) {
            // Admin menu
            if ($this->provider->has('imatic.admin')) {
                $menu->addChild($this->provider->get('imatic.admin'));
            }
            // User menu - user functions
            if ($this->provider->has('imatic.user')) {
                $helper->addDivider($menu, true);
                $menu->addChild($this->provider->get('imatic.user'));
            }
        } else {
            // User menu - login link
            if ($this->provider->has('imatic.user_anon')) {
                $helper->addDivider($menu, true);
                $menu->addChild($this->provider->get('imatic.user_anon'));
            }
        }

        return $menu;
    }
}


<?php

namespace Addons\Core\Middleware;

use Closure;
use Illuminate\Http\Response;
use Addons\Core\Tools\OutputEncrypt;

class Encrypt
{
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if (strtoupper($request->method()) == 'OPTIONS')
		{
			$response = new Response();

			$e = new OutputEncrypt();
			$response->headers->set('X-RSA', $e->getRsaPublicKey());
			$response->headers->set('X-KEY', $e->getServerEncryptedKey());

			return $response;
		}
		else
			return $next($request);
	}
}


<?php
/**
 * PX Commands "ssi"
 */
namespace picklesFramework2\processors\ssi;

/**
 * PX Commands "ssi"
 */
class ssi{

	/**
	 * Picklesオブジェクト
	 */
	private $px;

	/**
	 * Starting function
	 * @param object $px Picklesオブジェクト
	 */
	public static function exec( $px ){
		$me = new self( $px );
		$px->bowl()->each( array($me, 'apply') );
	}

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 */
	public function __construct( $px ){
		$this->px = $px;
	}

	/**
	 * apply output filter
	 * @param string $src HTML, CSS, JavaScriptなどの出力コード
	 * @param string $current_path コンテンツのカレントディレクトリパス
	 * @return string 加工後の出力コード
	 */
	public function apply($src, $current_path = null){
		if( is_null($current_path) ){
			$current_path = $this->px->req()->get_request_file_path();
		}

		if( !$this->px->is_publish_tool() ){

			// SSI命令の解決
			$tmp_src = $src;
			$src = '';
			while(1){
				$tmp_preg_pattern = '/^(.*?)'.preg_quote('<!--#include','/').'\s+virtual\=\"(.*?)\"\s*'.preg_quote('-->','/').'(.*)$/s';
				if( !preg_match($tmp_preg_pattern, $tmp_src, $tmp_matched) ){
					$src .= $tmp_src;
					break;
				}
				$src .= $tmp_matched[1];

				// SSI先のファイルを読み込む
				$href_incfile = $this->px->fs()->normalize_path( trim($tmp_matched[2]) );
				$realpath_incfile = null;
				$path_incfile = null;
				if( preg_match( '/^\//s', $href_incfile ) ){
					$realpath_incfile = $this->px->fs()->get_realpath( $this->px->get_realpath_docroot().$href_incfile );
					$path_incfile = $href_incfile;
				}else{
					$realpath_incfile = $this->px->fs()->get_realpath( $this->px->get_realpath_docroot().dirname($current_path).'/'.$href_incfile );
					$path_incfile = $this->px->fs()->get_realpath( $href_incfile, dirname($current_path) );
				}
				$ssi_content = $this->px->fs()->read_file( $realpath_incfile );
				$ssi_content = $this->apply( $ssi_content, $path_incfile );
				$src .= $ssi_content;

				$tmp_src = $tmp_matched[3];
				continue;
			}

		}

		return $src;
	}

}


<?php

namespace Phile\Plugin\Siezi\PhileMarkdownEditor;

/**
 * Class Request
 *
 * @author Schlaefer <openmail+sourcecode@siezi.com>
 * @link https://github.com/Schlaefer/phileMarkdownEditor
 * @license http://opensource.org/licenses/MIT
 * @package Phile\Plugin\Siezi\PhileMarkdownEditor
 */
class Request
{

    protected $_base;

    protected $_request;

    protected $_uri;

    public function __construct($request)
    {
        $this->_request = $request;
    }

    public function param($key)
    {
        if (isset($this->_request[$key])) {
            $value = $this->_request[$key];
        } else {
            $value = $this->_paramBackbone($key);
        }

        return $value;
    }

    /**
     * Extract request param from backbone model request
     *
     * @param string $key
     * @return string|null
     */
    protected function _paramBackbone($key)
    {
        if (isset($this->_request['model'])) {
            $model = json_decode($this->_request['model'], true);

            return $model[$key];
        }

        return null;
    }

    public function setUri($uri)
    {
        $this->_uri = $uri;
    }

    public function setBase($base)
    {
        $this->_base = $base;
    }

    public function isEditor()
    {
        return !empty($this->_uri) && $this->getAction();
    }

    public function getAction()
    {
        $uri = rtrim($this->_uri, '/');
        $base = rtrim($this->_base, '/');

        if ($uri === $base) {
            return '/';
        }

        preg_match("/$base\/(?P<action>.*)(\/)?$/", $uri, $matches);
        if (!empty($matches['action'])) {
            return $matches['action'];
        }

        return false;
    }

}


<?php

namespace Zeeml\Algorithms\Formulas;

use Zeeml\Algorithms\Exceptions\MissingResultException;
use Zeeml\Algorithms\Exceptions\WrongUsageException;
use Zeeml\DataSet\DataSet;

class SimpleLinearCoefficients extends Formulas
{
    /**
     * Calculating the slope of the dataSet following the formula:
     *
     *               Σ(x - mean(x)) * (y - mean(y))
     *   slope =     ---------------------------
     *                     Σ(x - mean(x))²
     *
     * and the intercept following the formula:
     *
     *  intercept = mean(y) - slope * mean(x)
     *
     * the result returned is an array(intercept, slope)
     *
     * @return FormulasInterface
     * @throws MissingResultException
     * @throws WrongUsageException
     */
    public function calculate(): FormulasInterface
    {
        if (! $this->dataSet instanceof DataSet) {
            throw new WrongUsageException('DataSet was not provided for slope calculus');
        }

        try {
            $means = $this->previousResults->of(Mean::class);
        } catch (\Throwable $exception) {
            throw new MissingResultException('Can not calculate the linear slope without knowing the mean');
        }

        $slope = 0;
        $denominator = 0;

        foreach ($this->dataSet as $instance) {
            $slope += ($instance->getDimension(0) - $means[0][0]) * ($instance->getOutput(0) - $means[1][0]);
            $denominator += pow(($instance->getDimension(0) - $means[0][0]), 2);
        }

        if ($denominator === 0) {
            $slope = 0;
        } else {
            $slope /= $denominator;
        }

        $intercept = $means[1][0] - ($slope * $means[0][0]);

        $this->result = [$intercept, $slope];

        return $this;
    }
}


<?php

namespace DDDominio\EventSourcing\EventStore\Vendor;

use DDDominio\EventSourcing\Common\EventStream;
use DDDominio\EventSourcing\Common\EventStreamInterface;
use DDDominio\EventSourcing\EventStore\AbstractEventStore;
use DDDominio\EventSourcing\EventStore\ConcurrencyException;
use DDDominio\EventSourcing\EventStore\EventStreamDoesNotExistException;
use DDDominio\EventSourcing\EventStore\StoredEvent;
use Doctrine\DBAL\Connection;
use DDDominio\EventSourcing\Serialization\SerializerInterface;
use DDDominio\EventSourcing\Versioning\EventUpgrader;
use DDDominio\EventSourcing\Versioning\Version;
use Doctrine\DBAL\Schema\Schema;
use DDDominio\EventSourcing\EventStore\InitializableInterface;

class DoctrineDbalEventStore extends AbstractEventStore implements InitializableInterface
{
    const STREAMS_TABLE = 'streams';
    const EVENTS_TABLE = 'events';

    /**
     * @var Connection
     */
    private $connection;

    /**
     * @param Connection $connection
     * @param SerializerInterface $serializer
     * @param EventUpgrader $eventUpgrader
     */
    public function __construct($connection, $serializer, $eventUpgrader)
    {
        parent::__construct($serializer, $eventUpgrader);
        $this->connection = $connection;
    }

    /**
     * @param string $streamId
     * @param int $start
     * @param int $count
     * @return EventStreamInterface
     */
    public function readStreamEvents($streamId, $start = 1, $count = null)
    {
        if (!isset($count)) {
            $count = PHP_INT_MAX;
        }
        $stmt = $this->connection->prepare(
            'SELECT *
             FROM events
             WHERE stream_id = :streamId
             LIMIT :limit
             OFFSET :offset'
        );
        $stmt->bindValue(':streamId', $streamId);
        $stmt->bindValue(':offset', (int) $start - 1, \PDO::PARAM_INT);
        $stmt->bindValue(':limit', $count, \PDO::PARAM_INT);
        $stmt->execute();
        $results = $stmt->fetchAll();

        $storedEvents = array_map(function($result) {
            return new StoredEvent(
                $result['id'],
                $result['stream_id'],
                $result['type'],
                $result['event'],
                $result['metadata'],
                new \DateTimeImmutable($result['occurred_on']),
                Version::fromString($result['version'])
            );
        }, $results);

        return $this->domainEventStreamFromStoredEvents(new EventStream($storedEvents));
    }

    /**
     * @param string $streamId
     * @return EventStreamInterface
     */
    public function readFullStream($streamId)
    {
        $stmt = $this->connection->prepare(
            'SELECT *
             FROM events
             WHERE stream_id = :streamId'
        );
        $stmt->bindValue(':streamId', $streamId);
        $stmt->execute();
        $results = $stmt->fetchAll();

        $storedEvents = array_map(function($result) {
            return new StoredEvent(
                $result['id'],
                $result['stream_id'],
                $result['type'],
                $result['event'],
                $result['metadata'],
                new \DateTimeImmutable($result['occurred_on']),
                Version::fromString($result['version'])
            );
        }, $results);

        return $this->domainEventStreamFromStoredEvents(new EventStream($storedEvents));
    }

    /**
     * @return EventStreamInterface[]
     */
    public function readAllStreams()
    {
        $stmt = $this->connection->prepare(
            'SELECT *
             FROM streams'
        );
        $stmt->execute();

        $streams = [];
        foreach ($stmt->fetchAll() as $result) {
            $streams[] = $this->readFullStream($result['id']);
        }
        return $streams;
    }

    /**
     * @return EventStreamInterface
     */
    public function readAllEvents()
    {
        $stmt = $this->connection->prepare(
            'SELECT *
             FROM events'
        );
        $stmt->execute();
        $results = $stmt->fetchAll();

        $storedEvents = array_map(function($result) {
            return new StoredEvent(
                $result['id'],
                $result['stream_id'],
                $result['type'],
                $result['event'],
                $result['metadata'],
                new \DateTimeImmutable($result['occurred_on']),
                Version::fromString($result['version'])
            );
        }, $results);

        return $this->domainEventStreamFromStoredEvents(new EventStream($storedEvents));
    }

    /**
     * @param string $type
     * @param Version $version
     * @return EventStreamInterface
     */
    protected function readStoredEventsOfTypeAndVersion($type, $version)
    {
        $stmt = $this->connection->prepare(
            'SELECT *
             FROM events
             WHERE type = :type
             AND version = :version'
        );
        $stmt->bindValue(':type', $type);
        $stmt->bindValue(':version', $version);
        $stmt->execute();
        $results = $stmt->fetchAll();

        $storedEvents = array_map(function($result) {
            return new StoredEvent(
                $result['id'],
                $result['stream_id'],
                $result['type'],
                $result['event'],
                $result['metadata'],
                new \DateTimeImmutable($result['occurred_on']),
                Version::fromString($result['version'])
            );
        }, $results);

        return new EventStream($storedEvents);
    }

    /**
     * @param string $streamId
     * @param StoredEvent[] $storedEvents
     * @param int $expectedVersion
     */
    protected function appendStoredEvents($streamId, $storedEvents, $expectedVersion)
    {
        $this->connection->transactional(function() use ($streamId, $storedEvents, $expectedVersion) {
            if (!$this->streamExists($streamId)) {
                $stmt = $this->connection
                    ->prepare('INSERT INTO streams (id) VALUES (:streamId)');
                $stmt->bindValue(':streamId', $streamId);
                $stmt->execute();
            }
            $stmt = $this->connection->prepare(
                'INSERT INTO events (stream_id, type, event, metadata, occurred_on, version)
                 VALUES (:streamId, :type, :event, :metadata, :occurredOn, :version)'
            );
            foreach ($storedEvents as $storedEvent) {
                $stmt->bindValue(':streamId', $streamId);
                $stmt->bindValue(':type', $storedEvent->type());
                $stmt->bindValue(':event', $storedEvent->data());
                $stmt->bindValue(':metadata', $storedEvent->metadata());
                $stmt->bindValue(':occurredOn', $storedEvent->occurredOn()->format('Y-m-d H:i:s'));
                $stmt->bindValue(':version', $storedEvent->version());
                $stmt->execute();
            }

            if ($expectedVersion !== self::EXPECTED_VERSION_ANY) {
                $streamFinalVersion = $this->streamVersion($streamId);
                if (count($storedEvents) !== $streamFinalVersion - $expectedVersion) {
                    throw ConcurrencyException::fromVersions(
                        $this->streamVersion($streamId),
                        $expectedVersion
                    );
                }
            }
        });
    }
    /**
     * @param string $streamId
     * @return int
     */
    protected function streamVersion($streamId)
    {
        $stmt = $this->connection
            ->prepare('SELECT COUNT(*) FROM events WHERE stream_id = :streamId');
        $stmt->bindValue(':streamId', $streamId);
        $stmt->execute();
        return intval($stmt->fetchColumn());
    }

    /**
     * @param string $streamId
     * @param \DateTimeImmutable $datetime
     * @return int
     * @throws EventStreamDoesNotExistException
     */
    public function getStreamVersionAt($streamId, \DateTimeImmutable $datetime)
    {
        if (!$this->streamExists($streamId)) {
            throw EventStreamDoesNotExistException::fromStreamId($streamId);
        }
        $stmt = $this->connection->prepare(
            'SELECT COUNT(*)
             FROM events
             WHERE stream_id = :streamId
             AND occurred_on <= :occurred_on'
        );
        $stmt->bindValue(':streamId', $streamId);
        $stmt->bindValue(':occurred_on', $datetime->format('Y-m-d H:i:s'));
        $stmt->execute();
        return intval($stmt->fetchColumn());
    }

    /**
     * @param string $streamId
     * @return bool
     */
    protected function streamExists($streamId)
    {
        $stmt = $this->connection
            ->prepare('SELECT COUNT(*) FROM streams WHERE id = :streamId');
        $stmt->bindValue(':streamId', $streamId);
        $stmt->execute();
        return boolval($stmt->fetchColumn());
    }

    /**
     * Initialize the Event Store
     */
    public function initialize()
    {
        $schema = new Schema();

        $streamTable = $schema->createTable(self::STREAMS_TABLE);
        $streamTable->addColumn('id', 'string');
        $streamTable->setPrimaryKey(array("id"));

        $eventsTable = $schema->createTable(self::EVENTS_TABLE);
        $eventsTable->addColumn('id', 'integer', ['autoincrement' => true]);
        $eventsTable->addColumn('stream_id', 'string');
        $eventsTable->addColumn('type', 'string');
        $eventsTable->addColumn('event', 'text');
        $eventsTable->addColumn('metadata', 'text');
        $eventsTable->addColumn('occurred_on', 'datetime');
        $eventsTable->addColumn('version', 'string');
        $eventsTable->setPrimaryKey(['id']);
        $eventsTable->addForeignKeyConstraint($streamTable, ['stream_id'], ['id']);

        $queries = $schema->toSql($this->connection->getDatabasePlatform());
        $this->connection->transactional(function(Connection $connection) use ($queries) {
            foreach ($queries as $query) {
                $connection->exec($query);
            }
        });
    }

    /**
     * Check if the Event Store has been initialized
     *
     * @return bool
     */
    public function initialized()
    {
        return $this->connection->getSchemaManager()->tablesExist([self::STREAMS_TABLE]);
    }
}


<?php
/**
 * PX Commands "publish"
 */
namespace picklesFramework2\commands;

/**
 * PX Commands "publish"
 *
 *

 *
PX=publish

 *
パブリッシュのホーム画面を表示します。

 *
PX=publish.run

 *
パブリッシュを実行します。

 *
PX=publish.version

 *
Pickles Framework のバージョン番号を JSON 形式の文字列で返します。

 *

 */
class publish{

	/** Picklesオブジェクト */
	private $px;

	/** プラグイン設定 */
	private $plugin_conf;

	/** パス設定 */
	private $path_tmp_publish, $path_publish_dir, $path_docroot;

	/** ドメイン設定 */
	private $domain;

	/** パブリッシュ範囲設定 */
	private $paths_region = array();

	/** パブリッシュ対象外範囲設定 */
	private $paths_ignore = array();

	/** キャッシュを消去しないフラグ */
	private $flg_keep_cache = false;

	/** ロックファイルの格納パス */
	private $path_lockfile;

	/** 処理待ちのパス一覧 */
	private $paths_queue = array();

	/** 処理済みのパス一覧 */
	private $paths_done = array();

	/** Extension をマッチさせる正規表現 */
	private $preg_exts;

	/**
	 * Before content function
	 * @param object $px Picklesオブジェクト
	 * @param object $json プラグイン設定
	 * ```
	 * {
	 * 	"paths_ignore": [
	 * 		// パブリッシュ対象から常に除外するパスを設定する。
	 * 		// (ここに設定されたパスは、動的なプレビューは可能)
	 * 		"/sample_pages/no_publish/*"
	 * 	]
	 * }
	 * ```
	 */
	public static function register( $px, $json ){

		// プラグイン設定の初期化
		if( !is_object(@$json) ){
			$json = json_decode('{}');
		}
		if( !is_array(@$json->paths_ignore) ){
			$json->paths_ignore = array();
		}
		// var_dump($json);

		$self = new self( $px, $json );

		$px->pxcmd()->register('publish', array($self, 'exec_home'));
	}

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 * @param object $json プラグイン設定
	 */
	public function __construct( $px, $json ){
		$this->px = $px;
		$this->plugin_conf = $json;

		$this->path_tmp_publish = $px->fs()->get_realpath( $px->get_realpath_homedir().'_sys/ram/publish/' );
		$this->path_lockfile = $this->path_tmp_publish.'applock.txt';
		if( $this->get_path_publish_dir() !== false ){
			$this->path_publish_dir = $this->get_path_publish_dir();
		}
		$this->domain = $px->conf()->domain;
		$this->path_docroot = $px->conf()->path_controot;

		// Extensionをマッチさせる正規表現
		$process = array_keys( get_object_vars( $this->px->conf()->funcs->processor ) );
		foreach( $process as $key=>$val ){
			$process[$key] = preg_quote($val);
		}
		$this->preg_exts = '('.implode( '|', $process ).')';

		// パブリッシュ対象範囲
		$path_region = $this->px->req()->get_request_file_path();
		$path_region = preg_replace('/^\/+/s','/',$path_region);
		$path_region = preg_replace('/\/'.$this->px->get_directory_index_preg_pattern().'$/s','/',$path_region);
		$func_check_param_path = function($path){
			if( !preg_match('/^\//', $path) ){
				return false;
			}
			$path = preg_replace('/(?:\/|\\\\)/', '/', $path);
			if( preg_match('/(?:^|\/)\.{1,2}(?:$|\/)/', $path) ){
				return false;
			}
			return true;
		};
		$param_path_region = $this->px->req()->get_param('path_region');
		if( strlen( $param_path_region ) && $param_path_region != $path_region && $func_check_param_path( $param_path_region ) ){
			$path_region = $param_path_region;
		}
		$this->paths_region = array( $path_region );
		unset( $path_region, $param_path_region );

		// パブリッシュ対象範囲(複数指定する場合)
		$paths_region = $this->px->req()->get_param('paths_region');
		if( is_array($paths_region) ){
			$this->paths_region = array_merge( $this->paths_region, $paths_region );
		}

		// パブリッシュ範囲の指定から、2重拡張子の2つ目を削除
		foreach( $this->paths_region as $tmp_key=>$tmp_localpath_region ){
			if( !is_dir('./'.$tmp_localpath_region) && preg_match( '/\.'.$this->preg_exts.'\.'.$this->preg_exts.'$/is', $tmp_localpath_region ) ){
				$this->paths_region[$tmp_key] = preg_replace( '/\.'.$this->preg_exts.'$/is', '', $tmp_localpath_region );
			}
		}
		unset($tmp_localpath_region, $tmp_key);

		// キャッシュを消去しないフラグ
		$this->flg_keep_cache = !!$this->px->req()->get_param('keep_cache');

		// パブリッシュ対象外の範囲
		$this->paths_ignore = $this->px->req()->get_param('paths_ignore');
		if( is_string($this->paths_ignore) ){
			$this->paths_ignore = array( $this->paths_ignore );
		}
		if( !is_array($this->paths_ignore) ){
			$this->paths_ignore = array();
		}
	}

	/**
	 * print CLI header
	 */
	private function cli_header(){
		ob_start();
		print $this->px->pxcmd()->get_cli_header();
		print 'publish directory(tmp): '.$this->path_tmp_publish."\n";
		print 'lockfile: '.$this->path_lockfile."\n";
		print 'publish directory: '.$this->path_publish_dir."\n";
		print 'domain: '.$this->domain."\n";
		print 'docroot directory: '.$this->path_docroot."\n";
		print 'ignore: '.join(', ', $this->plugin_conf->paths_ignore)."\n";
		print 'region: '.join(', ', $this->paths_region)."\n";
		print 'ignore (tmp): '.join(', ', $this->paths_ignore)."\n";
		print 'keep cache: '.($this->flg_keep_cache ? 'true' : 'false')."\n";
		print '------------'."\n";
		flush();
		return ob_get_clean();
	}

	/**
	 * print CLI footer
	 */
	private function cli_footer(){
		ob_start();
		print $this->px->pxcmd()->get_cli_footer();
		return ob_get_clean();
	}

	/**
	 * report
	 */
	private function cli_report(){
		$cnt_queue = count( $this->paths_queue );
		$cnt_done = count( $this->paths_done );
		ob_start();
		print $cnt_done.'/'.($cnt_queue+$cnt_done)."\n";
		print 'queue: '.$cnt_queue.' / done: '.$cnt_done."\n";
		return ob_get_clean();
	}

	/**
	 * execute home
	 * @param object $px Picklesオブジェクト
	 */
	public function exec_home( $px ){
		$pxcmd = $this->px->get_px_command();

		if( @$pxcmd[1] == 'version' ){
			// 命令が publish.version の場合、バージョン番号を返す。
			$val = $this->px->get_version();
			@header('Content-type: application/json; charset=UTF-8');
			print json_encode($val);
			exit;
		}
		if( @$pxcmd[1] == 'run' ){
			// 命令が publish.run の場合、実行する。
			$this->exec_publish( $px );
			exit;
		}
		if( @strlen($pxcmd[1]) ){
			// 命令が不明の場合、エラーを表示する。
			if( $this->px->req()->is_cmd() ){
				header('Content-type: text/plain;');
				print $this->cli_header();
				print 'execute PX command => "?PX=publish.run"'."\n";
				print $this->cli_footer();
			}else{
				$html = '
Go to PX=publish to execute publish.
'."\n";
				print $this->px->pxcmd()->wrap_gui_frame($html);
			}
			exit;
		}

		if( $this->px->req()->is_cmd() ){
			header('Content-type: text/plain;');
			print $this->cli_header();
			print 'execute PX command => "?PX=publish.run"'."\n";
			print $this->cli_footer();
		}else{
			$html = '';

			if(!is_dir($this->path_tmp_publish)){
				$html .= '
'."\n";
				$html .= '
パブリッシュ先一時ディレクトリが存在しません。
'."\n";
				$html .= '

'.htmlspecialchars( $this->path_tmp_publish ).'

'."\n";
				$html .= '
'."\n";
			}elseif(!is_writable($this->path_tmp_publish)){
				$html .= '
'."\n";
				$html .= '
パブリッシュ先一時ディレクトリに書き込み許可がありません。
'."\n";
				$html .= '

'.htmlspecialchars( $this->path_tmp_publish ).'

'."\n";
				$html .= '
'."\n";
			}elseif( strlen($this->path_publish_dir) && !is_dir($this->path_publish_dir) ){
				$html .= '
'."\n";
				$html .= '
パブリッシュ先ディレクトリが存在しません。
'."\n";
				$html .= '

'.htmlspecialchars( $this->px->dbh()->get_realpath( $this->path_publish_dir ).'/' ).'

'."\n";
				$html .= '
'."\n";
			}elseif( strlen($this->path_publish_dir) && !is_writable($this->path_publish_dir) ){
				$html .= '
'."\n";
				$html .= '
パブリッシュ先ディレクトリに書き込み許可がありません。
'."\n";
				$html .= '

'.htmlspecialchars( $this->px->dbh()->get_realpath( $this->path_publish_dir ).'/' ).'

'."\n";
				$html .= '
'."\n";
			}elseif( $this->is_locked() ){
				$html .= '
'."\n";
				$html .= '
パブリッシュはロックされています。
'."\n";
				$html .= '
'."\n";
				$html .= '		現在、他のプロセスでパブリッシュが実行中である可能性があります。
'."\n";
				$html .= '		しばらく待ってから、リロードしてください。
'."\n";
				$html .= '
'."\n";
				$html .= '
'."\n";
				$html .= '		ロックファイルの内容を下記に示します。
'."\n";
				$html .= '
'."\n";
				$html .= '

'.htmlspecialchars( $this->px->fs()->read_file( $this->path_lockfile ) ).'

'."\n";
				$html .= '
'."\n";
				$html .= '		ロックファイルは下記の時刻に更新されました。
'."\n";
				$html .= '
'."\n";
				$html .= '

'.htmlspecialchars( date( 'Y-m-d H:i:s', filemtime( $this->path_lockfile ) ) ).'

'."\n";
				$html .= '
'."\n";
				$html .= '		ロックファイルは、次のパスに存在します。
'."\n";
				$html .= '
'."\n";
				$html .= '

'.htmlspecialchars( realpath( $this->path_lockfile ) ).'

'."\n";
				$html .= '
'."\n";
			}else{
				ob_start(); ?>

プロジェクト『<?= htmlspecialchars($this->px->conf()->name) ?>』をパブリッシュします。

		<colgroup><col width="30%" /><col width="70%" /></colgroup>

			publish directory(tmp)
			<?= htmlspecialchars($this->path_tmp_publish) ?>

			publish directory
			<?= htmlspecialchars($this->path_publish_dir) ?>

			domain
			<?= htmlspecialchars($this->domain) ?>

			docroot directory
			<?= htmlspecialchars($this->path_docroot) ?>

			region

<?= htmlspecialchars($this->paths_region[0]) ?>

変更する

					<form action="?" method="get" onsubmit="cont_EditPublishTargetPathApply(this); return false;" class="inline">
						<input type="text" name="path" size="25" style="max-width:70%;" value="<?= htmlspecialchars($this->paths_region[0]) ?>" />
						<input type="submit" style="width:20%;" value="変更する" />
					</form>

次のボタンをクリックしてパブリッシュを実行してください。

	<form action="?" method="get" target="_blank">

<button class="xlarge">パブリッシュを実行する</button>

<input type="hidden" name="PX" value="publish.run" /><input type="hidden" name="path_region" value="<?= htmlspecialchars($this->px->req()->get_param('path_region')) ?>" />

	</form>

<?php
				$html .= ob_get_clean();
			}

			print $this->px->pxcmd()->wrap_gui_frame($html);
		}
		exit;
	}

	/**
	 * execute publish
	 * @param object $px Picklesオブジェクト
	 */
	private function exec_publish( $px ){
		header('Content-type: text/plain;');
		$total_time = time();
		print $this->cli_header();

		$validate = $this->validate();
		if( !$validate['status'] ){
			print $validate['message']."\n";
			print $this->cli_footer();
			exit;
		}
		flush();
		if( !$this->lock() ){//ロック
			print '------'."\n";
			print 'publish is now locked.'."\n";
			print '  (lockfile updated: '.@date('Y-m-d H:i:s', filemtime($this->path_lockfile)).')'."\n";
			print 'Try again later...'."\n";
			print 'exit.'."\n";
			print $this->cli_footer();
			exit;
		}
		print "\n";
		print "\n";

		print '============'."\n";
		print '## Clearing caches'."\n";
		print "\n";
		$this->clearcache();
		print "\n";

		// make instance $site
		$this->px->set_site( new \picklesFramework2\site($this->px) );

		print '============'."\n";
		print '## Making list'."\n";
		print "\n";
		print '-- making list by Sitemap'."\n";
		$this->make_list_by_sitemap();
		print "\n";
		print '-- making list by Directory Scan'."\n";
		foreach( $this->get_region_root_path() as $path_region ){
			$this->make_list_by_dir_scan( $path_region );
		}
		print "\n";
		print '============'."\n";
		print '## Start publishing'."\n";
		print "\n";
		print $this->cli_report();
		print "\n";

		while(1){
			set_time_limit(5*60);
			flush();
			if( !count( $this->paths_queue ) ){
				break;
			}
			foreach( $this->paths_queue as $path=>$val ){break;}
			print '------------'."\n";
			print $path."\n";
			$path_type = $this->px->get_path_type( $path );
			if( $path_type != 'normal' && $path_type !== false ){
				// 物理ファイルではないものはスキップ
				print ' -> Non file URL.'."\n";

			}elseif( $this->px->fs()->is_dir(dirname($_SERVER['SCRIPT_FILENAME']).$path) ){
				// ディレクトリを処理
				$this->px->fs()->mkdir( $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path );
				print ' -> A directory.'."\n";

			}else{
				// ファイルを処理
				$ext = strtolower( pathinfo( $path , PATHINFO_EXTENSION ) );
				$proc_type = $this->px->get_path_proc_type( $path );
				$status_code = null;
				$status_message = null;
				$errors = array();
				$microtime = microtime(true);
				switch( $proc_type ){
					case 'pass':
						// pass
						print $ext.' -> '.$proc_type."\n";
						if( !$this->px->fs()->mkdir_r( dirname( $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path ) ) ){
							$status_code = 500;
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'FAILED to making parent directory.' ));
							break;
						}
						if( !$this->px->fs()->copy( dirname($_SERVER['SCRIPT_FILENAME']).$path , $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path ) ){
							$status_code = 500;
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'FAILED to copying file.' ));
							break;
						}
						$status_code = 200;
						break;

					case 'direct':
					default:
						// pickles execute
						print $ext.' -> '.$proc_type."\n";

						$bin = $this->px->internal_sub_request( $path, array('output'=>'json'), $return_var );
						if( !is_object($bin) ){
							$bin = new \stdClass;
							$bin->status = 500;
							$tmp_err_msg = 'Unknown server error';
							$tmp_err_msg .= "\n".'PHP returned status code "'.$return_var.'" on exit. There is a possibility of "Parse Error" or "Fatal Error" was occured.';
							$tmp_err_msg .= "\n".'Hint: Normally, "Pickles 2" content files are parsed as PHP scripts. If you are using "<'.'?", "<'.'?php", "<'.'%", or "<'.'?=" unintentionally in contents, might be the cause.';
							$bin->message = $tmp_err_msg;
							$bin->errors = array();
							// $bin->errors = array($tmp_err_msg);
							$bin->relatedlinks = array();
							$bin->body_base64 = base64_encode('');
							// $bin->body_base64 = base64_encode($tmp_err_msg);
							unset($tmp_err_msg);
						}
						$status_code = @$bin->status;
						$status_message = @$bin->message;
						$errors = @$bin->errors;
						if( $bin->status >= 500 ){
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'status: '.$bin->status.' '.$bin->message ));
						}elseif( $bin->status >= 400 ){
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'status: '.$bin->status.' '.$bin->message ));
						}elseif( $bin->status >= 300 ){
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'status: '.$bin->status.' '.$bin->message ));
						}elseif( $bin->status >= 200 ){
							// 200 番台は正常
						}elseif( $bin->status >= 100 ){
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'status: '.$bin->status.' '.$bin->message ));
						}else{
							$this->alert_log(array( @date('Y-m-d H:i:s'), $path, 'Unknown status code.' ));
						}

						// コンテンツの書き出し処理
						// エラーが含まれている場合でも、得られたコンテンツを出力する。
						$this->px->fs()->mkdir_r( dirname( $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path ) );
						$this->px->fs()->save_file( $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path, base64_decode( @$bin->body_base64 ) );
						foreach( $bin->relatedlinks as $link ){
							$link = $this->px->fs()->get_realpath( $link, dirname($this->path_docroot.$path).'/' );
							$link = $this->px->fs()->normalize_path( $link );
							$tmp_link = preg_replace( '/^'.preg_quote($this->px->get_path_controot(), '/').'/s', '/', $link );
							if( $this->px->fs()->is_dir( $this->px->get_realpath_docroot().'/'.$link ) ){
								$this->make_list_by_dir_scan( $tmp_link.'/' );
							}else{
								$this->add_queue( $tmp_link );
							}
						}

						// エラーメッセージを alert_log に追記
						if( is_array( $bin->errors ) && count( $bin->errors ) ){
							foreach( $bin->errors as $tmp_error_row ){
								$this->alert_log(array( @date('Y-m-d H:i:s'), $path, $tmp_error_row ));
							}
						}

						break;
				}

				$str_errors = '';
				if( is_array($errors) && count($errors) ){
					$str_errors .= count($errors).' errors: ';
					$str_errors .= implode(', ', $errors).';';
				}
				$this->log(array(
					@date('Y-m-d H:i:s') ,
					$path ,
					$proc_type ,
					$status_code ,
					$status_message ,
					$str_errors,
					@filesize($this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path),
					microtime(true)-$microtime
				));

			}

			if( !empty( $this->path_publish_dir ) ){
				// パブリッシュ先ディレクトリに都度コピー
				if( $this->px->fs()->is_file( $this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path ) ){
					$this->px->fs()->mkdir_r( dirname( $this->path_publish_dir.$this->path_docroot.$path ) );
					$this->px->fs()->copy(
						$this->path_tmp_publish.'/htdocs'.$this->path_docroot.$path ,
						$this->path_publish_dir.$this->path_docroot.$path
					);
					print ' -> copied to publish dir'."\n";
				}
			}

			unset($this->paths_queue[$path]);
			$this->paths_done[$path] = true;
			print $this->cli_report();

			$this->touch_lockfile();

			if( !count( $this->paths_queue ) ){
				break;
			}
		}

		print "\n";

		if( !empty( $this->path_publish_dir ) ){
			// パブリッシュ先ディレクトリを同期
			print '============'."\n";
			print '## Sync to publish directory.'."\n";
			print "\n";
			set_time_limit(30*60);
			foreach( $this->paths_region as $path_region ){
				$this->sync_dir(
					$this->path_tmp_publish.'/htdocs'.$this->path_docroot ,
					$this->path_publish_dir.$this->path_docroot ,
					$path_region
				);
			}
		}
		print "\n";
		print '============'."\n";
		print '## done.'."\n";
		print "\n";

		$path_logfile = $this->path_tmp_publish.'alert_log.csv';
		clearstatcache();
		if( @is_file( $path_logfile ) ){
			sleep(1);
			$alert_log = $this->px->fs()->read_csv( $path_logfile );
			array_shift( $alert_log );
			$alert_total_count = count($alert_log);
			$max_preview_count = 20;
			$alert_header = '************************* '.$alert_total_count.' ALERTS ******';
			print $alert_header."\n";
			print "\n";
			$counter = 0;
			foreach( $alert_log as $key=>$row ){
				$counter ++;
				// var_dump($row);
				$tmp_number = '  ['.($key+1).'] ';
				print $tmp_number;
				print preg_replace('/(\r\n|\r|\n)/s', '$1'.str_pad('', strlen($tmp_number), ' '), $row[2])."\n";
				print str_pad('', strlen($tmp_number), ' ').'  in '.$row[1]."\n";
				if( $counter >= $max_preview_count ){ break; }
			}
			if( $alert_total_count > $max_preview_count ){
				print '  [etc...]'."\n";
			}
			print "\n";
			print '    You got total '.$alert_total_count.' alerts.'."\n";
			print '    see more: '.realpath($path_logfile)."\n";
			print str_pad('', strlen($alert_header), '*')."\n";
			print "\n";
		}

		print 'Total Time: '.(time() - $total_time).' sec.'."\n";
		print "\n";

		$this->unlock();//ロック解除

		print $this->cli_footer();
		exit;
	}

	/**
	 * ディレクトリを同期する。
	 *
	 * @param string $path_sync_from 同期元のルートディレクトリ
	 * @param string $path_sync_to 同期先のルートディレクトリ
	 * @param string $path_region ルート以下のパス
	 * @return bool 常に `true` を返します。
	 */
	private function sync_dir( $path_sync_from , $path_sync_to, $path_region ){
		print 'Copying files and directories...';
		$this->sync_dir_copy_r( $path_sync_from , $path_sync_to, $path_region );
		print "\n";
		print 'Deleting removed files and directories...';
		$this->sync_dir_compare_and_cleanup( $path_sync_to , $path_sync_from, $path_region );
		print "\n";
		return true;
	}//sync_dir()

	/**
	 * ディレクトリを複製する(下層ディレクトリも全てコピー)
	 *
	 * ただし、ignore指定されているパスに対しては操作を行わない。
	 *
	 * @param string $from コピー元ファイルのパス
	 * @param string $to コピー先のパス
	 * @param string $path_region ルート以下のパス
	 * @param int $perm 保存するファイルに与えるパーミッション
	 * @return bool 成功時に `true`、失敗時に `false` を返します。
	 */
	private function sync_dir_copy_r( $from, $to, $path_region, $perm = null ){
		static $count = 0;
		if( $count%100 == 0 ){print '.';}
		$count ++;

		$from = $this->px->fs()->localize_path($from);
		$to   = $this->px->fs()->localize_path($to  );
		$path_region = $this->px->fs()->localize_path($path_region);

		$result = true;

		if( @is_file( $from.$path_region ) ){
			if( $this->px->fs()->mkdir_r( dirname( $to.$path_region ) ) ){
				if( $this->px->is_ignore_path( $path_region ) ){
					// ignore指定されているパスには、操作しない。
				}elseif( !$this->is_region_path( $path_region ) ){
					// 範囲外のパスには、操作しない。
				}else{
					if( !$this->px->fs()->copy( $from.$path_region , $to.$path_region , $perm ) ){
						$result = false;
					}
				}
			}else{
				$result = false;
			}
		}elseif( @is_dir( $from.$path_region ) ){
			if( !@is_dir( $to.$path_region ) ){
				if( $this->px->is_ignore_path( $path_region ) ){
					// ignore指定されているパスには、操作しない。
				}elseif( !$this->is_region_path( $path_region ) ){
					// 範囲外のパスには、操作しない。
				}else{
					if( !$this->px->fs()->mkdir_r( $to.$path_region ) ){
						$result = false;
					}
				}
			}
			$itemlist = $this->px->fs()->ls( $from.$path_region );
			foreach( $itemlist as $Line ){
				if( $Line == '.' || $Line == '..' ){ continue; }
				if( @is_dir( $from.$path_region.DIRECTORY_SEPARATOR.$Line ) ){
					if( @is_file( $to.$path_region.DIRECTORY_SEPARATOR.$Line ) ){
						continue;
					}elseif( !@is_dir( $to.$path_region.DIRECTORY_SEPARATOR.$Line ) ){
						if( $this->px->is_ignore_path( $path_region.DIRECTORY_SEPARATOR.$Line ) ){
							// ignore指定されているパスには、操作しない。
						}elseif( !$this->is_region_path( $path_region.DIRECTORY_SEPARATOR.$Line ) ){
							// 範囲外のパスには、操作しない。
						}else{
							if( !$this->px->fs()->mkdir_r( $to.$path_region.DIRECTORY_SEPARATOR.$Line ) ){
								$result = false;
							}
						}
					}
					if( !$this->sync_dir_copy_r( $from , $to, $path_region.DIRECTORY_SEPARATOR.$Line , $perm ) ){
						$result = false;
					}
					continue;
				}elseif( @is_file( $from.$path_region.DIRECTORY_SEPARATOR.$Line ) ){
					if( !$this->sync_dir_copy_r( $from, $to, $path_region.DIRECTORY_SEPARATOR.$Line , $perm ) ){
						$result = false;
					}
					continue;
				}
			}
		}

		return $result;
	}//sync_dir_copy_r()

	/**
	 * ディレクトリの内部を比較し、$comparisonに含まれない要素を$targetから削除する。
	 *
	 * ただし、ignore指定されているパスに対しては操作を行わない。
	 *
	 * @param string $target クリーニング対象のディレクトリパス
	 * @param string $comparison 比較するディレクトリのパス
	 * @param string $path_region ルート以下のパス
	 * @return bool 成功時 `true`、失敗時 `false` を返します。
	 */
	private function sync_dir_compare_and_cleanup( $target , $comparison, $path_region ){
		static $count = 0;
		if( $count%100 == 0 ){print '.';}
		$count ++;

		if( is_null( $comparison ) || is_null( $target ) ){ return false; }

		$target = $this->px->fs()->localize_path($target);
		$comparison = $this->px->fs()->localize_path($comparison);
		$path_region = $this->px->fs()->localize_path($path_region);
		$flist = array();

		// 先に、ディレクトリ内をスキャンする
		if( @is_dir( $target.$path_region ) ){
			$flist = $this->px->fs()->ls( $target.$path_region );
			foreach ( $flist as $Line ){
				if( $Line == '.' || $Line == '..' ){ continue; }
				$this->sync_dir_compare_and_cleanup( $target , $comparison, $path_region.DIRECTORY_SEPARATOR.$Line );
			}
			$flist = $this->px->fs()->ls( $target.$path_region );
		}

		if( !@file_exists( $comparison.$path_region ) && @file_exists( $target.$path_region ) ){
			if( $this->px->is_ignore_path( $path_region ) ){
				// ignore指定されているパスには、操作しない。
				return true;
			}elseif( !$this->is_region_path( $path_region ) ){
				// 範囲外のパスには、操作しない。
				return true;
			}
			if( @is_dir( $target.$path_region ) ){
				if( !count($flist) ){
					// ディレクトリの場合は、内容が空でなければ削除しない。
					$this->px->fs()->rm( $target.$path_region );
				}
			}else{
				$this->px->fs()->rm( $target.$path_region );
			}

			return true;
		}

		return true;
	}//sync_dir_compare_and_cleanup()

	/**
	 * パブリッシュログ
	 * @param array $row ログデータ
	 * @return bool ログ書き込みの成否
	 */
	private function log( $row ){
		$path_logfile = $this->path_tmp_publish.'publish_log.csv';
		if( !is_file( $path_logfile ) ){
			error_log( $this->px->fs()->mk_csv( array(array(
				'datetime' ,
				'path' ,
				'proc_type' ,
				'status_code' ,
				'status_message' ,
				'errors' ,
				'filesize',
				'proc_microtime'
			)) ), 3, $path_logfile );
			clearstatcache();
		}
		return error_log( $this->px->fs()->mk_csv( array($row) ), 3, $path_logfile );
	}

	/**
	 * パブリッシュアラートログ
	 * @param array $row ログデータ
	 * @return bool ログ書き込みの成否
	 */
	private function alert_log( $row ){
		$path_logfile = $this->path_tmp_publish.'alert_log.csv';
		if( !is_file( $path_logfile ) ){
			error_log( $this->px->fs()->mk_csv( array(array(
				'datetime' ,
				'path' ,
				'error_message'
			)) ), 3, $path_logfile );
			clearstatcache();
		}
		return error_log( $this->px->fs()->mk_csv( array($row) ), 3, $path_logfile );
	}

	/**
	 * validate
	 */
	private function validate(){
		$rtn = array('status'=>true, 'message'=>'');
		return $rtn;
	}

	/**
	 * clearcache
	 */
	private function clearcache(){

		// キャッシュを消去
		if( !$this->flg_keep_cache ){
			(new \picklesFramework2\commands\clearcache( $this->px ))->exec();
		}else{
			// 一時パブリッシュディレクトリをクリーニング
			echo '-- cleaning "publish"'."\n";
			$this->cleanup_tmp_publish_dir( $this->path_tmp_publish );
		}

		return true;
	}

	/**
	 * 一時パブリッシュディレクトリをクリーニング
	 * @param string $path クリーニング対象のパス
	 * @param string $localpath $pathの仮想のパス (再帰処理のために使用)
	 */
	private function cleanup_tmp_publish_dir( $path, $localpath = null ){
		$count = 0;
		$ls = $this->px->fs()->ls($path.$localpath);
		foreach( $ls as $basename ){
			if( $localpath.$basename == '.gitkeep' ){
				continue;
			}
			if( $this->px->fs()->is_dir($path.$localpath.$basename) ){
				$count += $this->cleanup_tmp_publish_dir( $path, $localpath.$basename.DIRECTORY_SEPARATOR );

				$i = 0;
				print 'rmdir '.$this->px->fs()->get_realpath( $path.$localpath.$basename );
				while(1){
					$i ++;
					if( $this->px->fs()->rmdir($path.$localpath.$basename) ){
						break;
					}
					if($i > 5){
						print ' [FAILED]';
						break;
					}
					sleep(1);
				}
				print "\n";
				$count ++;

			}else{
				clearstatcache();
				if( $this->px->fs()->get_realpath($path.$localpath.$basename) == $this->path_lockfile ){
					// パブリッシュロックファイルは消さない
				}else{
					$i = 0;
					print 'rm '.$this->px->fs()->get_realpath( $path.$localpath.$basename );
					while(1){
						$i ++;
						if( $this->px->fs()->rm($path.$localpath.$basename) ){
							break;
						}
						if($i > 5){
							print ' [FAILED]';
							break;
						}
						sleep(1);
					}
					print "\n";
					$count ++;
				}
			}
		}

		if( is_null($localpath) ){
			$this->px->fs()->save_file( $path.$localpath.'.gitkeep', '' );
		}
		return $count;
	}

	/**
	 * make list by sitemap
	 * @return bool 常に `true` を返します。
	 */
	private function make_list_by_sitemap(){
		$sitemap = $this->px->site()->get_sitemap();
		foreach( $sitemap as $page_info ){
			set_time_limit(30);
			$href = $this->px->href( $page_info['path'] );
			if( preg_match('/^(?:[a-zA-Z0-9]+\:)?\/\//', $href) ){
				// プロトコル名、またはドメイン名から始まるリンク先はスキップ
				continue;
			}
			$href = preg_replace( '/\/$/s', '/'.$this->px->get_directory_index_primary(), $href );
			$href = preg_replace( '/^'.preg_quote($this->px->get_path_controot(), '/').'/s', '/', $href );
			$this->add_queue( $href );
		}
		return true;
	}

	/**
	 * make list by directory scan
	 *
	 * @param string $path ファイル または ディレクトリ のパス
	 * @return bool 常に真
	 */
	private function make_list_by_dir_scan( $path = null ){

		$realpath = $this->px->fs()->get_realpath('./'.$path);

		if( !file_exists( $realpath ) ){
			// 直にファイルが存在しない場合、2重拡張子のファイルを検索
			$tmp_process = array_keys( get_object_vars( $this->px->conf()->funcs->processor ) );
			foreach( $tmp_process as $tmp_ext ){
				if( $this->px->fs()->is_file( $realpath.'.'.$tmp_ext ) ){
					$realpath = $realpath.'.'.$tmp_ext;
					break;
				}
			}
			unset($tmp_process, $tmp_ext);
		}

		if( $this->px->fs()->is_file( $realpath ) ){
			$tmp_localpath = $this->px->fs()->get_realpath('/'.$path);
			if( preg_match( '/\.'.$this->preg_exts.'\.'.$this->preg_exts.'$/is', $tmp_localpath ) ){
				$tmp_localpath = preg_replace( '/\.'.$this->preg_exts.'$/is', '', $tmp_localpath );
			}
			if( $this->px->get_path_proc_type( $tmp_localpath ) == 'ignore' || $this->px->get_path_proc_type( $tmp_localpath ) == 'pass' ){
				$tmp_localpath = $this->px->fs()->get_realpath('/'.$path);
			}
			$tmp_localpath = $this->px->fs()->normalize_path( $tmp_localpath );
			$this->add_queue( $tmp_localpath );
			return true;
		}

		$ls = $this->px->fs()->ls( $realpath );
		if( !is_array($ls) ){
			$ls = array();
		}
		// ↓ `/index.html` がignoreされている場合に、
		// 　ディレクトリスキャンがキャンセルされてしまう問題があり、
		// 　ここでの評価はしないことにした。
		// 　※add_queue()で評価しているので、結果問題なし。
		// if( $this->px->is_ignore_path( './'.$path ) ){
		// 	return true;
		// }

		foreach( $this->px->conf()->paths_proc_type as $row => $type ){
			// $conf->paths_proc_type の設定から、
			// 明らかに除外できると判断できるディレクトリは再帰処理をキャンセルする。
			// 設定値の末尾が `/*` で終わっている ignore 指定の行は、 "ディレクトリ以下すべて除外" と断定し、
			// これにマッチしたディレクトリをキャンセルの対象とする。
			if(!is_string($row)){continue;}
			if( $type != 'ignore' ){
				continue;
			}
			if( strrpos($row, '/*') !== strlen($row)-2 ){
				continue;
			}
			// var_dump($row);
			$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)), '/');
			$realpath_controot = $this->px->fs()->normalize_path( $this->px->fs()->get_realpath( $this->px->get_path_docroot().$this->px->get_path_controot() ) );
			if( preg_match('/\*/',$preg_pattern) ){
				// ワイルドカードが使用されている場合
				$preg_pattern = preg_quote($row,'/');
				$preg_pattern = preg_replace('/'.preg_quote('\*','/').'/','(?:.*?)',$preg_pattern);//ワイルドカードをパターンに反映
			}elseif(is_dir($realpath_controot.$row)){
				$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)).'/','/');
			}elseif(is_file($realpath_controot.$row)){
				$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)),'/');
			}
			$path_child = $this->px->fs()->normalize_path( $this->px->fs()->get_realpath( $path ).'/' );
			// var_dump($preg_pattern);
			if( preg_match( '/^'.$preg_pattern.'$/s' , $path_child ) ){
				// var_dump($path_child);
				return true;
			}
		}

		foreach( $ls as $basename ){
			set_time_limit(30);
			$this->make_list_by_dir_scan( $path.DIRECTORY_SEPARATOR.$basename );
		}
		return true;
	}

	/**
	 * add queue
	 * @param string $path 対象のパス
	 * @return bool 真偽
	 */
	private function add_queue( $path ){
		$path_type = $this->px->get_path_type( $path );
		if($path_type != 'normal'){
			// `normal` ではないもの(`data`, `javascript`, `anchor`, `full_url` など)は、
			// 物理ファイルを出力するものではないので、キューに送らない。
			return false;
		}

		$path = $this->px->fs()->normalize_path( $this->px->fs()->get_realpath( $path, $this->path_docroot ) );
		$path = preg_replace('/\#.*$/', '', $path);
		$path = preg_replace('/\?.*$/', '', $path);
		if( preg_match( '/\/$/', $path ) ){
			$path .= $this->px->get_directory_index_primary();
		}

		if( $this->px->is_ignore_path( $path ) || $this->is_ignore_path( $path ) || !$this->is_region_path( $path ) ){
			// 対象外, パブリッシュ対象外, 範囲外
			// 対象外パスの親ディレクトリが対象パスの場合は、ディレクトリ単体でキューに登録を試みる。
			// 　　ディレクトリの内容がすべて一時対象外に指定された場合に、
			// 　　一時パブリッシュディレクトリにフォルダが作られないため、
			// 　　同期時にディレクトリごと削除されてしまうことを防止するため。
			$dirname = $this->px->fs()->normalize_path(dirname($path));
			if($dirname != '/'){ $this->add_queue( $dirname ); }
			return false;
		}
		if( array_key_exists($path, $this->paths_queue) ){
			// 登録済み
			return false;
		}
		if( array_key_exists($path, $this->paths_done) ){
			// 処理済み
			return false;
		}
		$this->paths_queue[$path] = true;
		print 'added queue - "'.$path.'"'."\n";
		return true;
	}

	/**
	 * パブリッシュ対象か調べる
	 * @param string $path 対象のパス
	 * @return bool 真偽
	 */
	private function is_ignore_path( $path ){
		static $rtn = array();
		if( is_null($path) ){
			return true;
		}
		$path = $this->px->fs()->get_realpath( '/'.$path );
		if( is_dir('./'.$path) ){
			$path .= '/'.$this->px->get_directory_index_primary();
		}
		if( preg_match('/(?:\/|\\\\)$/', $path) ){
			$path .= $this->px->get_directory_index_primary();
		}
		$path = $this->px->fs()->normalize_path($path);

		if( @is_bool($rtn[$path]) ){
			return $rtn[$path];
		}

		foreach( $this->plugin_conf->paths_ignore as $row ){
			if(!is_string($row)){continue;}
			$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)), '/');
			if( preg_match('/\*/',$preg_pattern) ){
				// ワイルドカードが使用されている場合
				$preg_pattern = preg_quote($row,'/');
				$preg_pattern = preg_replace('/'.preg_quote('\*','/').'/','(?:.*?)',$preg_pattern);//ワイルドカードをパターンに反映
			}elseif(is_dir($row)){
				$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)).'/','/');
			}elseif(is_file($row)){
				$preg_pattern = preg_quote($this->px->fs()->normalize_path($this->px->fs()->get_realpath($row)),'/');
			}
			if( preg_match( '/^'.$preg_pattern.'$/s' , $path ) ){
				$rtn[$path] = true;
				return $rtn[$path];
			}
		}
		foreach( $this->paths_ignore as $path_ignore ){
			$preg_pattern = preg_quote( $path_ignore, '/' );
			if( preg_match('/'.preg_quote('\*','/').'/',$preg_pattern) ){
				// ワイルドカードが使用されている場合
				$preg_pattern = preg_replace('/'.preg_quote('\*','/').'/','(?:.*?)',$preg_pattern);//ワイルドカードをパターンに反映
				$preg_pattern = $preg_pattern.'$';//前方・後方一致
			}
			if( preg_match( '/^'.$preg_pattern.'/s' , $path ) ){
				$rtn[$path] = true;
				return $rtn[$path];
			}
		}
		$rtn[$path] = false;// <- default
		return $rtn[$path];
	}// is_ignore_path()

	/**
	 * パブリッシュ範囲内か調べる
	 * @param string $path 対象のパス
	 * @return bool 真偽
	 */
	private function is_region_path( $path ){
		$path = $this->px->fs()->get_realpath( '/'.$path );
		if( $this->px->fs()->is_dir('./'.$path) ){
			$path .= '/';
		}
		$path = $this->px->fs()->normalize_path($path);
		$is_region = false;
		foreach( $this->paths_region as $path_region ){
			if( preg_match( '/^'.preg_quote( $path_region, '/' ).'/s' , $path ) ){
				$is_region = true;
				break;
			}
		}
		if( !$is_region ){
			return false;
		}
		foreach( $this->paths_ignore as $path_ignore ){
			$preg_pattern = preg_quote( $path_ignore, '/' );
			if( preg_match('/'.preg_quote('\*','/').'/',$preg_pattern) ){
				// ワイルドカードが使用されている場合
				$preg_pattern = preg_replace('/'.preg_quote('\*','/').'/','(?:.*?)',$preg_pattern);//ワイルドカードをパターンに反映
				$preg_pattern = $preg_pattern.'$';//前方・後方一致
			}
			if( preg_match( '/^'.$preg_pattern.'/s' , $path ) ){
				return false;
			}
		}
		return true;
	}// is_region_path()

	/**
	 * パブリッシュ範囲のルートパスを得る
	 * @return string パブリッシュ範囲のルートパス
	 */
	private function get_region_root_path(){
		$rtn = array();
		foreach( $this->paths_region as $path_region ){
			$path = $this->px->fs()->get_realpath( '/'.$path_region );
			$path = $this->px->fs()->normalize_path($path);
			// ↓スキャンする対象が実在するディレクトリである必要はないので削除。
			// 　実在しない場合は無視されるだけなので問題ない。
			// 　この処理が有効だった場合、ファイル名名指しでパブリッシュしようとした場合にも、
			// 　実在する親ディレクトリに遡ってスキャンしてしまうため、無駄に処理に時間がかかってしまっていた。
			// while( !$this->px->fs()->is_dir('./'.$path) ){
			// 	$path = $this->px->fs()->normalize_path(dirname($path).'/');
			// }
			// var_dump($path);
			array_push($rtn, $path);
		}
		return $rtn;
	}// get_region_root_path()

	/**
	 * パブリッシュ先ディレクトリを取得
	 */
	private function get_path_publish_dir(){
		if( @!strlen( $this->px->conf()->path_publish_dir ) ){
			return false;
		}
		$tmp_path = $this->px->fs()->get_realpath( $this->px->conf()->path_publish_dir.'/' );
		if( !$this->px->fs()->is_dir( $tmp_path ) ){
			return false;
		}
		if( !$this->px->fs()->is_writable( $tmp_path ) ){
			return false;
		}
		return $tmp_path;
	}// get_path_publish_dir()

	/**
	 * パブリッシュをロックする。
	 *
	 * @return bool ロック成功時に `true`、失敗時に `false` を返します。
	 */
	private function lock(){
		$lockfilepath = $this->path_lockfile;
		$timeout_limit = 5;

		if( !@is_dir( dirname( $lockfilepath ) ) ){
			$this->px->fs()->mkdir_r( dirname( $lockfilepath ) );
		}

		#	PHPのFileStatusCacheをクリア
		clearstatcache();

		$i = 0;
		while( $this->is_locked() ){
			$i ++;
			if( $i >= $timeout_limit ){
				return false;
				break;
			}
			sleep(1);

			#	PHPのFileStatusCacheをクリア
			clearstatcache();
		}
		$src = '';
		$src .= 'ProcessID='.getmypid()."\r\n";
		$src .= @date( 'Y-m-d H:i:s' , time() )."\r\n";
		$RTN = $this->px->fs()->save_file( $lockfilepath , $src );
		return	$RTN;
	}//lock()

	/**
	 * パブリッシュがロックされているか確認する。
	 *
	 * @return bool ロック中の場合に `true`、それ以外の場合に `false` を返します。
	 */
	private function is_locked(){
		$lockfilepath = $this->path_lockfile;
		$lockfile_expire = 60*30;//有効期限は30分

		#	PHPのFileStatusCacheをクリア
		clearstatcache();

		if( $this->px->fs()->is_file($lockfilepath) ){
			if( ( time() - filemtime($lockfilepath) ) > $lockfile_expire ){
				#	有効期限を過ぎていたら、ロックは成立する。
				return false;
			}
			return true;
		}
		return false;
	}//is_locked()

	/**
	 * パブリッシュロックを解除する。
	 *
	 * @return bool ロック解除成功時に `true`、失敗時に `false` を返します。
	 */
	private function unlock(){
		$lockfilepath = $this->path_lockfile;

		#	PHPのFileStatusCacheをクリア
		clearstatcache();

		return @unlink( $lockfilepath );
	}//unlock()

	/**
	 * パブリッシュロックファイルの更新日を更新する。
	 *
	 * @return bool 成功時に `true`、失敗時に `false` を返します。
	 */
	private function touch_lockfile(){
		$lockfilepath = $this->path_lockfile;

		#	PHPのFileStatusCacheをクリア
		clearstatcache();
		if( !is_file( $lockfilepath ) ){
			return false;
		}

		return touch( $lockfilepath );
	}//touch_lockfile()

}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Twig\TokenParser;

use Imatic\Bundle\ViewBundle\Twig\Node\ExampleNode;
use Twig_Token;
use Twig_TokenParser;

/**
 * Generate an example.
 *
 * {% example %}
 *      An example
 * {% endexample %}
 *
 * @author Pavel Batecko <pavel.batecko@imatic.cz>
 */
class ExampleTokenParser extends Twig_TokenParser
{
    public function getTag()
    {
        return 'example';
    }

    public function parse(Twig_Token $token)
    {
        $lineno = $token->getLine();

        $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse(function (Twig_Token $token) {
            return $token->test('endexample');
        }, true);
        $rawBody = $this->parseRawBody($lineno);
        $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);

        return new ExampleNode($body, $rawBody, $lineno, $this->getTag());
    }

    /**
     * Parse raw template body.
     *
     * @param int $startLine
     *
     * @return string
     */
    private function parseRawBody($startLine)
    {
        $templateSource = \file_get_contents($this->parser->getStream()->getSourceContext()->getPath());

        // parse tag contents
        \preg_match(
            '/\\s*\\{%\s*example\\s*%\\}(.*?)\\s*\\{%\\s*endexample\\s*%\\}/s',
            \implode(
                "\n",
                \array_slice(
                    \preg_split('/\\n|\\r\\n?/', $templateSource),
                    $startLine - 1,
                    $this->parser->getCurrentToken()->getLine() - $startLine + 1
                )
            ),
            $match
        );

        if (isset($match[1])) {
            return $this->removeExtraIndentation($match[1]);
        }

        return '';
    }

    /**
     * Remove extra indentation from a string.
     *
     * @param string $string
     *
     * @return string
     */
    private function removeExtraIndentation($string)
    {
        $lines = \preg_split('/\\n|\\r\\n?/', $string);

        // determine indentation length
        $indentLen = null;
        for ($i = 0; isset($lines[$i]); ++$i) {
            if ('' !== \trim($lines[$i])) {
                \preg_match('/^\\s*/', $lines[$i], $match);
                $indentLen = \strlen($match[0]);
                break;
            }
        }

        if (null !== $indentLen) {
            // cut each line
            $out = '';
            for (; isset($lines[$i]); ++$i) {
                if (\substr($lines[$i], 0, $indentLen) === $match[0]) {
                    $out .= \substr($lines[$i], $indentLen);
                } else {
                    $out .= $lines[$i];
                }
                $out .= "\n";
            }

            return $out;
        }

        return $string;
    }
}


<?php

namespace Skillberto\SonataPageMenuBundle\Util;

class PositionHandler
{
    protected
        $positions = array(),
        $lastPositions = array()
    ;

    /**
     * @param  array $positions
     *
     * @return $this
     */
    public function setPositions(array $positions)
    {
        $this->positions = $positions;

        return $this;
    }

    /**
     * @param int $id
     * @param $value
     *
     * @return $this
     */
    public function setPosition($id, $value)
    {
        $this->positions[$id] = $value;

        return $this;
    }

    /**
     * @param  array $lastPositions
     *
     * @return $this
     */
    public function setLastPositions(array $lastPositions)
    {
        $this->lastPositions = $lastPositions;

        return $this;
    }

    /**
     * @return int
     */
    public function getPositions()
    {
        return $this->positions;
    }

    /**
     * @param  int $id
     *
     * @return int
     */
    public function getPosition($id)
    {
        return isset($this->positions[$id]) ? $this->positions[$id] : 0;
    }

    /**
     * @return array
     */
    public function getLastPositions()
    {
        return $this->lastPositions;
    }

    /**
     * @param  int $id
     *
     * @return int
     */
    public function getLastPosition($id)
    {
        return isset($this->lastPositions[$id]) ? $this->lastPositions[$id] : 0;
    }

    /**
     * @param  int $id
     *
     * @return $this
     */
    public function incrementPosition($id)
    {
        $value = $this->getPosition($id);

        $this->setPosition($id, $value + 1);

        return $this;
    }
}


<?php
/**
 * @author Andrey Samusev <Andrey.Samusev@exigenservices.com>
 * @copyright andrey 9/12/13
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FDevs\Photatoes;

class Gallery implements \Serializable
{
    /**
     * @var string
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @var int
     */
    private $count = 0;

    /**
     * @var \DateTime
     */
    private $updatedAt = null;

    /**
     * @var Meta[]
     */
    private $cover = array();

    /**
     * @var Image[]
     */
    private $images = array();

    /**
     * @var Manager
     */
    private $manager = null;

    /**
     * init
     *
     * @param string       $id
     * @param Manager|null $manager
     */
    public function __construct($id, Manager $manager = null)
    {
        $this->id = $id;
        if ($manager) {
            $this->setManager($manager);
            $this->reload();
        }
    }

    /**
     * set Manager
     *
     * @param Manager $manager
     * @return $this
     */
    public function setManager(Manager $manager)
    {
        $this->manager = $manager;

        return $this;
    }

    /**
     * reload Gallery
     *
     * @param bool $all
     * @return $this
     * @throws Exception\RuntimeException
     */
    public function reload($all = false)
    {
        if ($this->manager) {
            $this->manager->getAdapter()->getGallery($this);
            if ($all) {
                $this->getCover(true);
                $this->getImages(true);
            }
        }

        return $this;
    }

    /**
     * get Id
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * set Images
     *
     * @param \FDevs\Photatoes\Image[] $images
     * @return $this
     */
    public function setImages(array $images)
    {
        $this->images = array();
        foreach ($images as $image) {
            $this->addImage($image);
        }
        $this->count = count($this->images);

        return $this;
    }

    /**
     * get Images
     *
     * @param  bool                     $reload
     * @return \FDevs\Photatoes\Image[]
     */
    public function getImages($reload = false)
    {
        if ((!count($this->images) || $reload) && $this->manager) {
            $this->manager->getAdapter()->getImagesGallery($this);
        }

        return $this->images;
    }

    /**
     * add Image
     *
     * @param Image $image
     * @return $this
     */
    public function addImage(Image $image)
    {
        if (!isset($this->images[$image->getId()])) {
            $this->count++;
        }
        $this->images[$image->getId()] = $image;

        return $this;
    }

    /**
     * set Name
     *
     * @param string $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * get Name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * set Count
     *
     * @param int $count
     * @return $this
     */
    public function setCount($count)
    {
        $this->count = $count;

        return $this;
    }

    /**
     * get Count
     *
     * @return int
     */
    public function getCount()
    {
        return $this->count;
    }

    /**
     * add Cover
     *
     * @param Meta $meta
     * @return $this
     */
    public function addCover(Meta $meta)
    {
        $this->cover[$meta->getSize()] = $meta;

        return $this;
    }

    /**
     * get Cover
     *
     * @param  bool                    $reload
     * @return \FDevs\Photatoes\Meta[]
     */
    public function getCover($reload = false)
    {
        if ((!count($this->cover) || $reload) && $this->manager) {
            $this->manager->getAdapter()->getCover($this);
        }

        return $this->cover;
    }

    /**
     * @param \DateTime $updatedAt
     * @return $this
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * save Gallery
     *
     * @return bool
     */
    public function save()
    {
        return $this->manager ? $this->manager->getAdapter()->saveGallery($this) : false;
    }

    /**
     * {@inheritDoc}
     */
    public function serialize()
    {
        $this->reload(true);
        $data = array(
            $this->id,
            $this->count,
            $this->updatedAt,
            $this->name,
            $this->cover,
            $this->images
        );

        return serialize($data);
    }

    /**
     * {@inheritDoc}
     */
    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        list(
            $this->id,
            $this->count,
            $this->updatedAt,
            $this->name,
            $this->cover,
            $this->images
            ) = $data;
    }

}


<?php
/**
 * processor "*.scss"
 */
namespace picklesFramework2\processors\scss;

/**
 * processor "*.scss" class
 */
class ext{

	/**
	 * 変換処理の実行
	 * @param object $px Picklesオブジェクト
	 */
	public static function exec( $px ){
		foreach( $px->bowl()->get_keys() as $key ){
			$src = $px->bowl()->pull( $key );

			$tmp_current_dir = realpath('./');
			chdir( dirname( $_SERVER['SCRIPT_FILENAME'] ) );
			$scss = new \Leafo\ScssPhp\Compiler();
			$src = $scss->compile( $src );
			chdir( $tmp_current_dir );

			$px->bowl()->replace( $src, $key );
		}

		return true;
	}
}


<?php

declare(strict_types=1);

namespace ManoManoTech\CorrelationIdHTTPlug;

use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use ManoManoTech\CorrelationId\CorrelationEntryName;
use ManoManoTech\CorrelationId\CorrelationEntryNameInterface;
use ManoManoTech\CorrelationId\CorrelationIdContainerInterface;
use Psr\Http\Message\RequestInterface;

final class CorrelationIdHTTPlug implements Plugin
{
    /** @var CorrelationEntryNameInterface */
    private $correlationEntryName;
    /** @var CorrelationIdContainerInterface */
    private $requestIdentifier;

    public function __construct(
        CorrelationIdContainerInterface $requestIdentifier,
        CorrelationEntryNameInterface $correlationEntryName = null
    ) {
        $this->requestIdentifier = $requestIdentifier;
        $this->correlationEntryName = $correlationEntryName ?? CorrelationEntryName::suffixed();
    }

    /**
     * Handle the request and return the response coming from the next callable.
     *
     * @see http://docs.php-http.org/en/latest/plugins/build-your-own.html
     *
     * @param callable $next  Next middleware in the chain, the request is passed as the first argument
     * @param callable $first First middleware in the chain, used to to restart a request
     *
     * @return Promise resolves a PSR-7 Response or fails with an Http\Client\Exception (The same as HttpAsyncClient)
     */
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
    {
        $headers = [
            $this->correlationEntryName->parent() => $this->requestIdentifier->current(),
            $this->correlationEntryName->root() => $this->selectBestRootHeaderValue(),
        ];

        foreach ($headers as $headerName => $headerValue) {
            $request = $request->withHeader($headerName, $headerValue);
        }

        return $next($request);
    }

    private function selectBestRootHeaderValue(): string
    {
        // Best value is, in the following order:
        // - root value if set or else
        // - parent value if set or else
        // - current value
        $rootPossibleValues = array_filter(
            [
                $this->requestIdentifier->root(),
                $this->requestIdentifier->parent(),
                $this->requestIdentifier->current(),
            ]
        );

        return array_shift($rootPossibleValues) ?? '';
    }
}


<?php

namespace Zeeml\Algorithms\Formulas;
use Zeeml\Algorithms\Exceptions\WrongUsageException;
use Zeeml\DataSet\DataSet;

/**
 * class that contains the functions used to calculate the accuracy of an algorithm
 * @package Zeeml\Algorithms\Traits
 */
class Benchmark extends Formulas
{
    protected $algorithmName;
    const ACCURACY = 'accuracy';
    const RMSE = 'rmse';

    public function __construct(string $algorithmName)
    {
        $this->algorithmName = $algorithmName;
    }

    /**
     * calculates the accuracy and the RMSE for a dataSet after the fit and test are done :
     *
     *
     *                         NumberOfCorrectGuesses
     *          accuracy =   -------------------------
     *                            NumberOfOutputs
     *
     *  and
     *                        Σ (prediction - output)^2
     *          Rmse =        -------------------------
     *                             NumberOfOutputs
     *
     *
     * @return FormulasInterface
     * @throws WrongUsageException
     */
    public function calculate(): FormulasInterface
    {
        if (! $this->dataSet instanceof DataSet) {
            throw new WrongUsageException('DataSet was not provided for Accuracy calculus');
        }

        $correctGuesses = 0;
        $rmse = 0;

        foreach ($this->dataSet as $instance) {
            $result = $instance->getResult($this->algorithmName);

            if (! isset($result['result'])) {
                throw new WrongUsageException('Can not calculate accuracy before testing the dataSet');
            }

            if (abs($result['result'] - $instance->getOutput(0)) <= self::EPSILON ) {
                $correctGuesses ++;
            }

            $rmse += pow($result['result'] - $instance->getOutput(0), 2);
        }

        $accuracy = $correctGuesses / $this->dataSet->getSize();
        $rmse = sqrt($rmse / $this->dataSet->getSize());

        $this->result = [self::ACCURACY => $accuracy, self::RMSE => $rmse];

        return $this;
    }
}


<?php

namespace Alcalyn\NeuralNetwork;

class Neuron
{
    /**
     * @var int
     */
    public $id;

    /**
     * @var Dendrite[]
     */
    public $dendrites;

    /**
     * @var float
     */
    public $axion;

    /**
     * @var float
     */
    public $gradiant;

    /**
     * @var Dendrite[]
     */
    public $succ;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->dendrites = [];
        $this->axion = 0;
        $this->succ = [];
    }

    /**
     * Pulse.
     */
    public function pulse()
    {
        $sum = 0;

        foreach ($this->dendrites as $dendrite) {
            $sum += $dendrite->neuron->axion * $dendrite->w;
        }

        $this->axion = self::sig($sum);
    }

    /**
     * @param Neuron $neuron
     */
    public function bind(Neuron $neuron)
    {
        $dendrite = new Dendrite();

        $dendrite->neuronFrom = $this;
        $dendrite->neuron = $neuron;
        $dendrite->w = rand(-5, 5) / 10;

        $this->dendrites []= $dendrite;

        $neuron->succ []= $dendrite;
    }

    /**
     * @param float $n
     *
     * @return float
     */
    public static function sig($n)
    {
        return 1 / (1 + exp(-$n));
    }
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Templating\Helper\Format;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;

class FormatHelper implements FormatterInterface
{
    /**
     * @var FormatterInterface[]
     */
    private $formatters;

    /**
     * @var array[]
     */
    private $formatterOptions;

    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var PropertyAccessor
     */
    private $accessor;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container; // need a container instance because of a circular dependency
        $this->accessor = PropertyAccess::createPropertyAccessor();
    }

    /**
     * @param string             $format
     * @param FormatterInterface $formatter
     * @param array              $options
     */
    public function addFormatter($format, FormatterInterface $formatter, array $options = [])
    {
        $this->formatters[$format] = $formatter;
        $this->formatterOptions[$format] = $options;
    }

    /**
     * @param string $format
     * @param string $context templating context (e.g. "html")
     *
     * @return bool
     */
    public function isSafe($format, $context)
    {
        if (!isset($this->formatterOptions[$format])) {
            return false;
        }

        return $context === $this->formatterOptions[$format]['is_safe'];
    }

    /**
     * @param mixed  $value
     * @param string $format
     * @param array  $options
     *
     * @throws \InvalidArgumentException if the formatter doesn't exist
     *
     * @return string|null
     */
    public function format($value, $format = null, array $options = [])
    {
        if (null === $format) {
            $format = $this->guessFormat($value);
        }

        if (!empty($options['template'])) {
            return $this->container->get('templating')->render(
                $options['template'],
                ['value' => $value, 'options' => $options, 'format' => $format] + $options
            );
        }

        if (!isset($this->formatters[$format])) {
            throw new \InvalidArgumentException(\sprintf('Formatter "%s" not found', $format));
        }

        return $this->formatters[$format]->format($value, $format, $options);
    }

    /**
     * @param array|object $objectOrArray
     * @param string|null  $propertyPath
     * @param string       $format
     * @param array        $options
     *
     * @return string|null
     */
    public function renderValue($objectOrArray, $propertyPath, $format = null, array $options = [])
    {
        if (\is_array($objectOrArray) && $propertyPath && $propertyPath[0] !== '[') {
            $propertyPath = \sprintf('[%s]', $propertyPath);
        }

        if (null === $propertyPath) {
            $value = $objectOrArray;
        } else {
            try {
                $value = $this->accessor->getValue($objectOrArray, $propertyPath);
                $options['object'] = $objectOrArray;
            } catch (UnexpectedTypeException $e) {
                // the property path could not be reached
                $value = null;
            }
        }

        if (!empty($options['collection']) && true === $options['collection']) {
            unset($options['collection']);
            $propertyPath = null;
            if (!empty($options['propertyPath'])) {
                $propertyPath = $options['propertyPath'];
            }

            return $this->container->get('templating')->render('ImaticViewBundle:Field:collection.html.twig', [
                'value' => $value,
                'options' => $options,
                'format' => $format,
                'propertyPath' => $propertyPath,
            ]);
        }

        return $this->format($value, $format, $options);
    }

    /**
     * @param mixed $value
     *
     * @throws \RuntimeException if the format could not be determined
     *
     * @return string
     */
    protected function guessFormat($value)
    {
        $format = null;
        $type = \gettype($value);

        switch ($type) {
            case 'boolean':
                $format = 'boolean';
                break;
            case 'integer':
            case 'double':
                $format = 'number';
                break;
            case 'string':
            case 'NULL':
            case 'resource':
                $format = 'text';
                break;
            case 'object':
                if ($value instanceof \DateTime) {
                    $format = 'datetime';
                } else {
                    $format = 'text';
                }
                break;
        }

        if (null === $format) {
            throw new \RuntimeException(\sprintf(
                'Could not guess format for a value of type "%s". Please provide a format.',
                $type
            ));
        }

        return $format;
    }
}


<?php
/**
 * @author Andrey Samusev <Andrey.Samusev@exigenservices.com>
 * @copyright andrey 9/10/13
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FDevs\Photatoes;

class Image implements \Serializable
{
    /**
     * @var string
     */
    private $id;

    /**
     * @var string
     */
    private $title = null;

    /**
     * @var string
     */
    private $description = null;

    /**
     * @var \DateTime
     */
    private $publishAt = null;

    /**
     * @var \DateTime
     */
    private $updateAt = null;

    /**
     * @var array
     */
    private $tags = array();

    /**
     * @var Meta[]
     */
    private $img = array();

    /**
     * @var Manager
     */
    private $manager = null;

    /**
     * init
     *
     * @param string  $id      id image
     * @param Manager $manager
     */
    public function __construct($id, Manager $manager = null)
    {
        $this->id = $id;
        if ($manager) {
            $this->setManager($manager);
            $this->manager->getAdapter()->getImage($this);
        }
    }

    /**
     * set Manager
     *
     * @param Manager $manager
     * @return $this
     */
    public function setManager(Manager $manager)
    {
        $this->manager = $manager;

        return $this;
    }

    /**
     * save Image to the server
     *
     * @return bool
     */
    public function save()
    {
        return $this->manager ? $this->manager->getAdapter()->saveImage($this) : false;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $description
     * @return $this
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * add Image
     *
     * @param Meta $file
     * @return $this
     */
    public function addMeta(Meta $file)
    {
        $this->img[$file->getSize()] = $file;

        return $this;
    }

    /**
     * get Img
     * @param  string    $size
     * @return Meta|null
     */
    public function get($size)
    {
        $size = ImageSize::get($size);
        if (isset($this->img[$size])) {
            return $this->img[$size];
        }

        return null;
    }

    /**
     * @return \FDevs\Photatoes\Meta[]
     */
    public function all()
    {
        return $this->img;
    }

    /**
     * @param \DateTime $publishAt
     * @return $this
     */
    public function setPublishAt(\DateTime $publishAt)
    {
        $this->publishAt = $publishAt;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getPublishAt()
    {
        return $this->publishAt;
    }

    /**
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * set Update At
     *
     * @param \DateTime $updateAt
     * @return $this
     */
    public function setUpdateAt(\DateTime $updateAt)
    {
        $this->updateAt = $updateAt;

        return $this;
    }

    /**
     * get Update At
     *
     * @return \DateTime
     */
    public function getUpdateAt()
    {
        return $this->updateAt;
    }

    /**
     * @param array $tags
     * @return $this
     */
    public function setTags(array $tags)
    {
        $this->tags = $tags;

        return $this;
    }

    /**
     * add Tag
     *
     * @param string $tag
     * @return $this
     */
    public function addTag($tag)
    {
        $this->tags[] = $tag;

        return $this;
    }

    /**
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * has Image in Server
     *
     * @return bool
     */
    public function has()
    {
        return !empty($this->publishAt);
    }

    /**
     * {@inheritDoc}
     */
    public function serialize()
    {
        $data = array(
            $this->id,
            $this->title,
            $this->description,
            $this->tags,
            $this->publishAt,
            $this->updateAt,
            $this->img
        );

        return serialize($data);
    }

    /**
     * {@inheritDoc}
     */
    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        list(
            $this->id,
            $this->title,
            $this->description,
            $this->tags,
            $this->publishAt,
            $this->updateAt,
            $this->img
            ) = $data;
    }
}


<?php

namespace Mingalevme\Utils;

use Mingalevme\HttpBuildUrl\HttpBuildUrl;

class Url
{
    const SCHEME    = 'scheme';
    const HOST      = 'host';
    const PORT      = 'port';
    const USER      = 'user';
    const PASS      = 'pass';
    const PATH      = 'path';
    const QUERY     = 'query';
    const FRAGMENT  = 'fragment';

    static protected $mapping = [
        self::SCHEME    => \PHP_URL_SCHEME,
        self::HOST      => \PHP_URL_HOST,
        self::PORT      => \PHP_URL_PORT,
        self::USER      => \PHP_URL_USER,
        self::PASS      => \PHP_URL_PASS,
        self::PATH      => \PHP_URL_PATH,
        self::QUERY     => \PHP_URL_QUERY,
        self::FRAGMENT  => \PHP_URL_FRAGMENT,
    ];

    /**
     * Build an URL
     *
     * @param string|array $url Base url or parts of the url (aliases is not supported), to build from scratch use any falsy value, e.g. [], null or ''
     * @param array $replacement [optional] Associative array like parse_url() returns
     * @param array &$newUrlParts [optional] If set, it will be filled with the parts of the composed url like parse_url() would return
     * @return string The new URL string
     */
    public static function build($url, $replacement=[], &$newUrlParts=null)
    {
        return HttpBuildUrl::build($url, $replacement, $newUrlParts);
    }

    /**
     * Almost the same as parse_url, except $component is expected local consts
     *
     * @param string $url The URL to parse. Invalid characters are replaced by _.
     * @param int $component Optional. Specify one of
     * self::SCHEME,
     * self::HOST,
     * self::PORT,
     * self::USER,
     * self::PASS,
     * self::PATH,
     * self::QUERY,
     * self::FRAGMENT
     * to retrieve just a specific URL component as a string (except
     * when self::PORT is given, in which case the return value will be an integer).
     * @throws \Exception If $component is unknown.
     * @return array|string|int|bool If the component parameter is omitted,
     * an associative array is returned. At least one element will be present
     * within the array. If the component parameter is specified, self::parse()
     * returns a string (or an integer, in the case of self::PORT) instead of
     * an array. If the requested component doesn't exist within the given URL,
     * NULL will be returned.
     *
     * @deprecated
     */
    public static function parse($url, $component = null)
    {
        if ($component && isset(self::$mapping[$component]) === false) {
            throw new \Exception("Unknown component: {$component}");
        }

        return \parse_url($url, $component ? self::$mapping[$component] : -1);
    }

    /**
     * (PHP 5)

     * Generate URL-encoded query string
     * @link http://php.net/manual/en/function.http-build-query.php
     * @param mixed $query_data

     * May be an array or object containing properties.
     *

     *

     * If query_data is an array, it may be a simple
     * one-dimensional structure, or an array of arrays (which in
     * turn may contain other arrays).
     *

     *

     * If query_data is an object, then only public
     * properties will be incorporated into the result.
     *

     * @param string $numeric_prefix [optional]

     * If numeric indices are used in the base array and this parameter is
     * provided, it will be prepended to the numeric index for elements in
     * the base array only.
     *

     *

     * This is meant to allow for legal variable names when the data is
     * decoded by PHP or another CGI application later on.
     *

     * @param string $arg_separator [optional]

     * arg_separator.output
     * is used to separate arguments, unless this parameter is specified,
     * and is then used.
     *

     * @param int $enc_type [optional]

     * By default, PHP_QUERY_RFC1738.
     *

     *

     * If enc_type is
     * PHP_QUERY_RFC1738, then encoding is performed per
     * RFC 1738 and the
     * application/x-www-form-urlencoded media type, which
     * implies that spaces are encoded as plus (+) signs.
     *

     *

     * If enc_type is
     * PHP_QUERY_RFC3986, then encoding is performed
     * according to RFC 3986, and
     * spaces will be percent encoded (%20).
     *

     * @return string a URL-encoded string.
     *
     * @deprecated
     */
    public static function buildQueryString(array $params, $prefix = null, $separator = '&', $enctype = null)
    {
        if ($enctype) {
            return http_build_query($params, $prefix, $separator, $enctype);
        } else {
            return http_build_query($params, $prefix, $separator);
        }
    }

    /**
     * Convenient way to call parse_str
     *
     * @param string $query
     * @return array
     */
    public static function parseQueryString($query)
    {
        parse_str($query, $result);
        return $result;
    }

    /**
     * Parse URL and return query string as assoc array
     *
     * @param string $url
     * @return array
     */
    public static function parseQueryStringFromUrl($url)
    {
        $query = (string) parse_url($url, \PHP_URL_QUERY);
        parse_str($query, $result);
        return $result;
    }

    /**
     * Set (if not specified) scheme and host to $url based on $baseUrl
     *
     * @param string $url
     * @param string $baseUrl
     * @return string absolutized version of $url
     */
    public static function absolutizeUrl($url, $baseUrl)
    {
        $components = parse_url($baseUrl);

        if (empty($components[self::SCHEME]) || empty($components[self::HOST])) {
            throw new \InvalidArgumentException("Malformed baseUrl: {$baseUrl}");
        }

        return static::build($url, [
            's' => $components[self::SCHEME],
            'h' => $components[self::HOST],
        ]);
    }

    /**
     * Check if url is absolute (based on scheme and host components)
     *
     * @param string $url
     * @return bool
     */
    public static function isAbsolute($url)
    {
        $components = parse_url($url);

        return isset($components[self::SCHEME]) && isset($components[self::HOST]);
    }

    /**
     * Check if url is related (based on host component)
     *
     * @param string $url
     * @return bool
     */
    public static function isRelative($url)
    {
        return !self::isAbsolute($url);
    }

    /**
     * Check if $url is a local file path
     *
     * @param $url
     * @return bool
     * @throws \Exception
     */
    public static function isLocal($url)
    {
        $components = self::parse($url);

        if (isset($components[self::SCHEME]) && $components[self::SCHEME] !== 'file') {
            return false;
        }

        if (isset($components[self::HOST])) {
            return false;
        }

        return true;
    }
}


<?php
/**
 * PX Commands "phpinfo"
 */
namespace picklesFramework2\commands;

/**
 * PX Commands "phpinfo"
 *
 *

 *
PX=phpinfo

 *
`phpinfo()` の実行結果を表示します。

 *

 */
class phpinfo{

	/**
	 * Picklesオブジェクト
	 */
	private $px;

	/**
	 * Starting function
	 * @param object $px Picklesオブジェクト
	 */
	public static function register( $px ){
		$px->pxcmd()->register('phpinfo', function($px){
			(new self( $px ))->kick();
			exit;
		});
	}

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 */
	public function __construct( $px ){
		$this->px = $px;
	}

	/**
	 * kick
	 * @return void
	 */
	private function kick(){
		phpinfo();
		exit;
	}
}


<?php
/**
 * theme "pickles"
 */
namespace picklesFramework2\theme;

/**
 * theme "pickles" class
 */
class theme{
	/**
	 * objects
	 */
	private $px;

	/**
	 * テーマテンプレートの格納先パス
	 */
	private $path_tpl;

	/**
	 * current_page_info
	 */
	private $page;

	/**
	 * constructor
	 * @param object $px $px object
	 */
	public function __construct($px){
		$this->px = $px;
		$this->path_tpl = $px->fs()->get_realpath(__DIR__.'/../').DIRECTORY_SEPARATOR;
		$this->page = $this->px->site()->get_current_page_info();
		if( @!strlen( $this->page['layout'] ) ){
			$this->page['layout'] = 'default';
		}
		if( !$px->fs()->is_file( $this->path_tpl.$this->page['layout'].'.html' ) ){
			$this->page['layout'] = 'default';
		}
		// $this->px->realpath_plugin_private_cache('/test/abc/test.inc');
		$this->px->fs()->copy_r( __DIR__.'/../theme_files/', $this->px->realpath_plugin_files('/') );
	}

	/**
	 * entry method
	 * @param object $px $px object
	 * @return bool true
	 */
	public static function exec( $px ){
		$theme = new self($px);
		$src = $theme->bind($px);
		$px->bowl()->replace($src, '');
		return true;
	}

	/**
	 * bind content to theme
	 * @param object $px $px object
	 * @return string HTML Source code
	 */
	private function bind( $px ){
		$theme = $this;
		ob_start();
		include( $this->path_tpl.$this->page['layout'].'.html' );
		$src = ob_get_clean();
		return $src;
	}

	/**
	 * グローバルナビを自動生成する
	 * @return string HTML Source code
	 */
	public function mk_global_menu(){
		$global_menu = $this->px->site()->get_global_menu();
		if( !count($global_menu) ){
			return '';
		}

		$rtn = '';
		$rtn .= '
'."\n";
		foreach( $global_menu as $global_menu_page_id ){
			$rtn .= '
'.$this->px->mk_link( $global_menu_page_id );
			$rtn .= $this->mk_sub_menu( $global_menu_page_id );
			$rtn .= '
'."\n";
		}
		$rtn .= '
'."\n";
		return $rtn;
	}
	/**
	 * ショルダーナビを自動生成する
	 * @return string HTML Source code
	 */
	public function mk_shoulder_menu(){
		$shoulder_menu = $this->px->site()->get_shoulder_menu();
		if( !count($shoulder_menu) ){
			return '';
		}

		$rtn = '';
		$rtn .= '
'."\n";
		foreach( $shoulder_menu as $shoulder_menu_page_id ){
			$rtn .= '
'.$this->px->mk_link( $shoulder_menu_page_id );
			$rtn .= $this->mk_sub_menu( $shoulder_menu_page_id );
			$rtn .= '
'."\n";
		}
		$rtn .= '
'."\n";
		return $rtn;
	}
	/**
	 * 指定されたページの小階層のメニューを展開する
	 *
	 * @param string $parent_page_id 親ページのページID
	 * @return string ページリストのHTMLソース
	 */
	public function mk_sub_menu( $parent_page_id ){
		$rtn = '';
		$children = $this->px->site()->get_children( $parent_page_id );
		if( count($children) ){
			$rtn .= '
'."\n";
			foreach( $children as $child ){
				$rtn .= '
'.$this->px->mk_link( $child );
				if( $this->px->site()->is_page_in_breadcrumb($child) ){//←カレントページ以外の下層は辿らない
					$rtn .= $this->mk_sub_menu( $child );//←再帰的呼び出し
				}
				$rtn .= '
'."\n";
			}
			$rtn .= '
'."\n";
		}
		return $rtn;
	}

	/**
	 * グローバルナビを自動生成する
	 * @return string HTML Source code
	 */
	public function mk_megafooter_menu(){
		$global_menu = $this->px->site()->get_global_menu();
		if( !count($global_menu) ){
			return '';
		}

		$rtn = '';
		$rtn .= '
'."\n";
		foreach( $global_menu as $global_menu_page_id ){
			$rtn .= '
'.$this->px->mk_link( $global_menu_page_id );
			$children = $this->px->site()->get_children( $global_menu_page_id );
			if( count( $children ) ){
				$rtn .= '
'."\n";
				foreach( $children as $child_page_id ){
					$rtn .= '
'.$this->px->mk_link( $child_page_id );
					$rtn .= '
'."\n";
				}
				$rtn .= '
'."\n";
			}
			$rtn .= '
'."\n";
		}
		$rtn .= '
'."\n";
		return $rtn;
	}

	/**
	 * パンくずを自動生成する
	 * @return string HTML Source code
	 */
	public function mk_breadcrumb(){
		$breadcrumb = $this->px->site()->get_breadcrumb_array();
		$rtn = '';
		$rtn .= '
';
		foreach( $breadcrumb as $pid ){
			$rtn .= '
'.$this->px->mk_link( $pid, array('label'=>htmlspecialchars($this->px->site()->get_page_info($pid, 'title_breadcrumb')), 'current'=>false) ).'
';
		}
		$rtn .= '
'.htmlspecialchars( $this->px->site()->get_current_page_info('title_breadcrumb') ).'
';
		$rtn .= '
';
		return $rtn;
	}

}


<?php

namespace Zeeml\Algorithms\Formulas;

use Zeeml\Algorithms\Exceptions\MissingResultException;
use Zeeml\Algorithms\Exceptions\WrongUsageException;

class LinearPrediction extends Formulas
{
    protected $inputs;
    protected $coefficients;

    public function __construct(array $inputs, array $coefficients)
    {
        $this->inputs = $inputs;
        $this->coefficients = $coefficients;
    }

    /**
     * the linear prediction is calculated for each input of the dataSet at a specific index using a slope and an intercept :
     *
     *    prediction = B0 + B1 * X1 + B2 * X2 ....
     *
     * @return FormulasInterface
     * @throws MissingResultException
     * @throws WrongUsageException
     */
    public function calculate(): FormulasInterface
    {
        $countInputs = count($this->inputs);

        if (count(array_filter($this->inputs, 'is_numeric')) !== $countInputs) {
            throw new WrongUsageException('Inputs provided are not usable');

        }

        $trainingInputsCounts = count($this->coefficients) - 1;
        if ($trainingInputsCounts != count($this->inputs)) {
            throw new WrongUsageException('Linear regression was calculated for ' . $trainingInputsCounts . ' inputs');
        }

        array_unshift($this->inputs, 1);

        foreach ($this->coefficients as $index => $coefficient) {
            $this->result = $this->result ?? 0;
            $this->result += $coefficient * $this->inputs[$index];
        }

        return $this;
    }
}