sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function addRouteFromArray($name, array $routeArray)
{
$route = \Parable\Routing\Route::createFromDataArray($routeArray);
$route->setName($name);
$this->addRoute($name, $route);
return $this;
} | Add a route to the routes list from array data.
@param string $name
@param array $routeArray
@return $this | entailment |
public function addRoutesFromArray(array $routes)
{
foreach ($routes as $name => $route) {
$this->addRouteFromArray($name, $route);
}
return $this;
} | Add an array of routes defined by array data to the router.
@param array $routes
@return $this | entailment |
public function getRouteByName($name)
{
if (!isset($this->routes[$name])) {
return null;
}
return $this->routes[$name];
} | Return a route by its name.
@param string $name
@return \Parable\Routing\Route|null | entailment |
public function matchUrl($url)
{
$url = '/' . ltrim($url, '/');
$url = $this->sanitizeUrl($url);
if ($url && $route = $this->matchUrlDirectly($url)) {
return $route;
}
if ($url && $route = $this->matchUrlWithParameters($url)) {
return $route;
... | Try to find a match in all available routes.
@param string $url
@return \Parable\Routing\Route|null | entailment |
protected function matchUrlDirectly($url)
{
foreach ($this->routes as $route) {
if ($route->matchDirectly($url)) {
return $route;
}
}
return null;
} | Loop through routes and try to match directly.
@param string $url
@return \Parable\Routing\Route|null | entailment |
protected function matchUrlWithParameters($url)
{
foreach ($this->routes as $route) {
if ($route->matchWithParameters($url)) {
return $route;
}
}
return null;
} | Loop through routes and try to match with parameters.
@param string $url
@return \Parable\Routing\Route|null | entailment |
public function getRouteUrlByName($name, array $parameters = [])
{
$route = $this->getRouteByName($name);
if (!$route) {
return null;
}
return $route->buildUrlWithParameters($parameters);
} | Return a url based on the $name provided, with $parameters passed (as [key => value]).
@param string $name
@param array $parameters
@return string | entailment |
public function leaves(\WP_Query $query)
{
$post = $query->get_queried_object();
$leaves = [];
if ($post instanceof \WP_Post) {
$post_format = get_post_format($post);
$post_format and $leaves[] = "embed-{$post->post_type}-{$post_format}";
$leaves[] = "emb... | {@inheritdoc} | entailment |
public function getData4CodeType($code, $type)
{
$query = $this->createQueryBuilder('p')
->select('p')
->where('p.code = :code')
->setParameter('code', $code)
->andWhere('p.expire >= :expire')
->setParameter('expire', new \DateTime())
-... | @param $code
@param $type
@return null|\PServerCore\Entity\UserCodes | entailment |
public function deleteCodes4User($userId, $type)
{
$query = $this->createQueryBuilder('p')
->delete($this->getEntityName(), 'p')
->where('p.user = :user_id')
->setParameter('user_id', $userId)
->andWhere('p.type = :type')
->setParameter('type', $ty... | @param $userId
@param $type
@return mixed | entailment |
public function getExpiredCodes($limit = 100)
{
$query = $this->createQueryBuilder('p')
->select('p')
->andWhere('p.expire < :expire')
->setParameter('expire', new \DateTime())
->orderBy('p.expire', 'asc')
->setMaxResults($limit)
->getQ... | @param int $limit
@return \PServerCore\Entity\UserCodes[] | entailment |
public function call()
{
$this->app->get('/api-docs', array($this, 'apiDocs'))->name('apiDocs');
$this->app->get('/api-docs/:resource', array($this, 'apiDocsForResource'))->name('apiDocsForResource');
$this->app->get('/docs/', array($this, 'docsView'))->name('apiView');
$this->next->... | Call | entailment |
public function getPage4Type($type)
{
$cachingKey = Caching::PAGE_INFO . '_' . $type;
$pageInfo = $this->cachingHelperService->getItem($cachingKey, function () use ($type) {
/** @var \PServerCore\Entity\Repository\PageInfo $repository */
$repository = $this->entityManager->g... | @param $type
@return \PServerCore\Entity\PageInfo|null | entailment |
public function run()
{
$homedir = $this->parameter->getOption('homedir');
$homedir = ltrim($homedir, DS);
$homedir_actual = $this->path->getDir($homedir);
$this->output->writeln([
"Parable initialization script",
"-----------------------------------",
... | Run the init structure command.
@return $this | entailment |
public function setMailSender(\Parable\Mail\Sender\SenderInterface $mailSender)
{
$this->mailSender = $mailSender;
return $this;
} | Set the mail sender implementation to use.
@param Sender\SenderInterface $mailSender
@return $this | entailment |
public function setFrom($email, $name = null)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \Parable\Mail\Exception("Email provided is invalid: {$email}");
}
$this->addresses['from'] = [
[
'email' => $email,
'name' => $... | Set the from address.
@param string $email
@param null|string $name
@return $this
@throws \Parable\Mail\Exception | entailment |
protected function addAddress($type, $email, $name = null)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \Parable\Mail\Exception("Email provided is invalid: {$email}");
}
$this->addresses[$type][] = [
'email' => $email,
'name' => $name,
... | Add an address to the $type stack.
@param string $type
@param string $email
@param null|string $name
@return $this
@throws \Parable\Mail\Exception | entailment |
public function getAddressesForType($type)
{
if (!isset($this->addresses[$type])) {
throw new \Parable\Mail\Exception('Only to, cc, bcc addresses are allowed.');
}
$addresses = [];
foreach ($this->addresses[$type] as $address) {
if (!empty($address['name'])) ... | Return all addresses for type.
@param string $type
@return string
@throws \Parable\Mail\Exception | entailment |
public function send()
{
if (!$this->mailSender) {
throw new \Parable\Mail\Exception('No mail sender implementation set.');
}
// Check the basics
if (count($this->addresses['to']) === 0) {
throw new \Parable\Mail\Exception('No to addresses provided.');
... | Send the email.
@return bool
@throws \Parable\Mail\Exception | entailment |
protected function sendMail($to, $subject, $body, $headers)
{
return mail(
$to,
$subject,
$body,
$headers
);
} | Actually send the email, using PHPs built-in mail() command.
@param string $to
@param string $subject
@param string $body
@param string $headers
@return bool
@codeCoverageIgnore | entailment |
public function resetMailData()
{
// Reset the mail values
$this->subject = null;
$this->body = null;
$this->headers = [];
return $this;
} | Reset just the subject, body, headers
@return $this | entailment |
private function isFunctionCall(Tokens $tokens, int $index): bool
{
$previousIndex = $tokens->getPrevMeaningfulToken($index);
return $previousIndex !== null
&& ($tokens[$previousIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)
|| $tokens[$previousIndex]->isGivenKind(T_FUNCTION... | Detect if this is most probably function call (and not function import or function definition). | entailment |
public function trigger($event, &$payload = null)
{
// Disallow calling a trigger on global hooks
if ($event === '*') {
return $this;
}
// Get all global hooks
$globalHooks = [];
if (isset($this->hooks['*']) && count($this->hooks['*']) > 0) {
... | Trigger $event and run through all hooks referenced, passing along $payload to all $callables.
@param string $event
@param null|mixed $payload
@return $this | entailment |
public function setAction($action)
{
if (!in_array($action, $this->acceptedValues)) {
$acceptedValuesString = implode(', ', $this->acceptedValues);
throw new \Parable\ORM\Exception("Invalid action set, only {$acceptedValuesString} are allowed.");
}
$this->action = $ac... | Set the type of query we're going to do.
@param string $action
@return $this
@throws \Parable\ORM\Exception | entailment |
public function where(\Parable\ORM\Query\ConditionSet $set)
{
$this->where[] = $set;
return $this;
} | Add a where condition set.
@param \Parable\ORM\Query\ConditionSet $set
@return $this | entailment |
public function whereCondition($key, $comparator, $value = null, $tableName = null)
{
return $this->where($this->buildAndSet([
[$key, $comparator, $value, $tableName]
]));
} | Add a condition based on key/comparator/value, with an optional $tableName.
@param string $key
@param string $comparator
@param string|null $value
@param string|null $tableName
@return $this | entailment |
public function having(\Parable\ORM\Query\ConditionSet $set)
{
$this->having[] = $set;
return $this;
} | Add a having condition set.
@param \Parable\ORM\Query\ConditionSet $set
@return $this | entailment |
protected function join(
$type,
$joinTableName,
$key,
$comparator,
$value = null,
$shouldCompareFields = true,
$tableName = null
) {
if (!$tableName) {
$tableName = $this->getTableName();
}
$condition = new \Parable\ORM\Que... | Add a join to the query.
@param int $type
@param string $joinTableName
@param string $key
@param string $comparator
@param mixed $value
@param bool $shouldCompareFields
@param string|null $tableName
@return $this | entailment |
public function innerJoin(
$joinTableName,
$key,
$comparator,
$value = null,
$shouldCompareFields = true,
$tableName = null
) {
return $this->join(
self::JOIN_INNER,
$joinTableName,
$key,
$comparator,
... | Add an inner join to the query.
@param string $joinTableName
@param string $key
@param string $comparator
@param mixed $value
@param bool $shouldCompareFields
@param string|null $tableName
@return $this | entailment |
public function leftJoin(
$joinTableName,
$key,
$comparator,
$value = null,
$shouldCompareFields = true,
$tableName = null
) {
return $this->join(
self::JOIN_LEFT,
$joinTableName,
$key,
$comparator,
$... | Add a left join to the query.
@param string $joinTableName
@param string $key
@param string $comparator
@param mixed $value
@param bool $shouldCompareFields
@param string|null $tableName
@return $this | entailment |
public function rightJoin(
$joinTableName,
$key,
$comparator,
$value = null,
$shouldCompareFields = true,
$tableName = null
) {
return $this->join(
self::JOIN_RIGHT,
$joinTableName,
$key,
$comparator,
... | Add a right join to the query.
@param string $joinTableName
@param string $key
@param string $comparator
@param mixed $value
@param bool $shouldCompareFields
@param string|null $tableName
@return $this | entailment |
public function fullJoin(
$joinTableName,
$key,
$comparator,
$value = null,
$shouldCompareFields = true,
$tableName = null
) {
return $this->join(
self::JOIN_FULL,
$joinTableName,
$key,
$comparator,
$... | Add a full join to the query.
@param string $joinTableName
@param string $key
@param string $comparator
@param mixed $value
@param bool $shouldCompareFields
@param string|null $tableName
@return $this | entailment |
public function addValues(array $values)
{
foreach ($values as $key => $value) {
$this->addValue($key, $value);
}
return $this;
} | Adds an array of values to update/insert queries.
@param array $values
@return $this | entailment |
public function orderBy($key, $direction = self::ORDER_ASC, $tableName = null)
{
if (!$tableName) {
$tableName = $this->getTableName();
}
$this->orderBy[] = ['key' => $key, 'direction' => $direction, 'tableName' => $tableName];
return $this;
} | Sets the order for select queries.
@param string $key
@param string $direction
@param null|string $tableName
@return $this | entailment |
public function groupBy($key, $tableName = null)
{
if (!$tableName) {
$tableName = $this->getTableName();
}
$this->groupBy[] = ['key' => $key, 'tableName' => $tableName];
return $this;
} | Sets the group by for select queries.
@param string $key
@param null|string $tableName
@return $this | entailment |
protected function buildSelect()
{
$selects = [];
foreach ($this->select as $select) {
$shouldBeQuoted = true;
// Check our list of nonQuoteStrings to see if we should quote or not.
foreach ($this->nonQuoteStrings as $nonQuoteString) {
if (strpos(... | Build and return the select string.
@return string | entailment |
protected function buildJoins()
{
$builtJoins = [];
foreach ($this->joins as $type => $joins) {
if (count($joins) > 0) {
foreach ($joins as $join) {
if ($type === self::JOIN_INNER) {
$builtJoins[] = 'INNER JOIN';
... | Build and return the join strings.
@return string | entailment |
protected function buildWheres()
{
if (count($this->where) === 0) {
return '';
}
// Use a ConditionSet to build the wheres
$conditionSet = new Query\Condition\AndSet($this, $this->where);
return "WHERE {$conditionSet->buildWithoutParentheses()}";
} | Build and return the where string.
@return string | entailment |
protected function buildHaving()
{
if (count($this->having) === 0) {
return '';
}
// Use a ConditionSet to build the having clause
$conditionSet = new Query\Condition\AndSet($this, $this->having);
return "HAVING {$conditionSet->buildWithoutParentheses()}";
} | Build and return the having string.
@return string | entailment |
protected function buildOrderBy()
{
if (count($this->orderBy) === 0) {
return '';
}
$orders = [];
foreach ($this->orderBy as $orderBy) {
$key = $this->quoteIdentifier($orderBy['tableName']) . '.' . $this->quoteIdentifier($orderBy['key']);
$orders[... | Build and return the order by string.
@return string | entailment |
protected function buildGroupBy()
{
if (count($this->groupBy) === 0) {
return '';
}
$groups = [];
foreach ($this->groupBy as $groupBy) {
$groupBy = $this->quoteIdentifier($groupBy['tableName']) . '.' . $this->quoteIdentifier($groupBy['key']);
$gro... | Build and return the group by string.
@return string | entailment |
protected function buildLimitOffset()
{
if (empty($this->limitOffset)) {
return '';
}
$limitOffset = '';
if ($this->limitOffset['limit'] && $this->limitOffset['offset']) {
$limitOffset = $this->limitOffset['offset'] . ',' . $this->limitOffset['limit'];
... | Build and return the limit/offset string.
@return string | entailment |
public function createQuery()
{
$query = \Parable\ORM\Query::createInstance();
$query->setTableName($this->getModel()->getTableName());
if ($this->onlyCount) {
$query->select(['count(*)']);
}
if (!empty($this->orderBy)) {
$query->orderBy($this->orderB... | Generate a query set to use the current Model's table name & key.
@return \Parable\ORM\Query | entailment |
public function getAll()
{
$query = $this->createQuery();
$result = $this->database->query($query);
$entities = [];
if ($result) {
$result = $result->fetchAll(\PDO::FETCH_ASSOC);
$entities = $this->handleResult($result);
}
if ($this->returnOne... | Returns all rows for this model type.
@return \Parable\ORM\Model[]|\Parable\ORM\Model | entailment |
public function getById($id)
{
$query = $this->createQuery();
$query->where(
$query->buildAndSet([$this->getModel()->getTableKey(), '=', $id])
);
$result = $this->database->query($query);
$model = null;
if ($result) {
$result = $result->fetchA... | Returns a single model, based on $id.
@param int $id
@return null|\Parable\ORM\Model | entailment |
public function getByCondition($key, $comparator, $value = null)
{
$query = $this->createQuery();
$conditionSet = $query->buildAndSet([$key, $comparator, $value]);
return $this->getByConditionSet($conditionSet);
} | Returns all rows matching specific condition parameters given.
@param string $key
@param string $comparator
@param mixed|null $value
@return \Parable\ORM\Model[]|\Parable\ORM\Model | entailment |
public function getByConditionSets(array $conditionSets)
{
$query = $this->createQuery();
$query->whereMany($conditionSets);
$result = $this->database->query($query);
$entities = [];
if ($result) {
$result = $result->fetchAll(\PDO::FETCH_ASSOC);
$enti... | Returns all rows matching all conditions passed.
@param array $conditionSets
@return \Parable\ORM\Model[]|\Parable\ORM\Model | entailment |
public function orderBy($key, $direction = \Parable\ORM\Query::ORDER_ASC)
{
$this->orderBy = ['key' => $key, 'direction' => $direction];
return $this;
} | Allow multiple orders by $key in $direction.
@param string $key
@param string $direction ASC by default
@return $this | entailment |
public function setModel(\Parable\ORM\Model $model)
{
$this->model = $model->reset();
return $this;
} | Set a model on the repository. Reset it so there's no unwanted values stored on it.
@param \Parable\ORM\Model $model
@return $this | entailment |
protected function handleResult(array $result)
{
if ($this->onlyCount && isset($result[0]) && is_array($result[0])) {
return (int)current($result[0]);
}
$entities = [];
foreach ($result as $row) {
$model = clone $this->getModel();
$model->populate... | Handle the result of one of the get functions. This attempts to create a new model
with the values returned properly set.
@param array $result
@return \Parable\ORM\Model[]|int | entailment |
public function reset()
{
$this->orderBy = [];
$this->limitOffset = [];
$this->setOnlyCount(false);
$this->returnAll();
} | Resets everything but the query and model class to their default values. | entailment |
public static function createForModelName($modelName)
{
if (!class_exists($modelName)) {
throw new \Parable\ORM\Exception("Model '{$modelName}' does not exist.");
}
return self::createForModel($modelName::create());
} | Create an instance of the repository class for given $modelName.
@param string $modelName
@return \Parable\ORM\Repository
@throws \Parable\ORM\Exception | entailment |
public static function createForModel(\Parable\ORM\Model $model)
{
$repository = \Parable\DI\Container::create(static::class);
$repository->setModel($model);
return $repository;
} | Create an instance of the repository class for given $model.
@param \Parable\ORM\Model $model
@return \Parable\ORM\Repository | entailment |
public function initialize()
{
if ($this->checkAuthentication()) {
$data = $this->getAuthenticationData();
if (!isset($data['user_id'])) {
return false;
}
$user = $this->toolkit->getRepository($this->userClassName)->getById($data['user_id']);
... | Initialize the authentication, picking up on session data if possible.
@return bool | entailment |
protected function checkAuthentication()
{
$authSession = $this->readFromSession();
if ($authSession) {
if (isset($authSession['authenticated'])) {
$this->setAuthenticated($authSession['authenticated']);
} else {
$this->setAuthenticated(false);... | Checks whether there's an auth session active at this point.
@return bool | entailment |
public function setUserClassName($className)
{
try {
\Parable\DI\Container::create($className);
} catch (\Exception $e) {
throw new \Parable\Framework\Exception("Class '{$className}' could not be instantiated.");
}
$this->userClassName = $className;
r... | Set the class name to use for the user.
@param string $className
@return $this
@throws \Parable\Framework\Exception | entailment |
public function setUser($user)
{
if (!($user instanceof $this->userClassName)) {
throw new \Parable\Framework\Exception("Invalid object provided, type {$this->userClassName} required.");
}
$this->user = $user;
return $this;
} | Set the user and check whether it's of the right type.
@param $user
@return $this
@throws \Parable\Framework\Exception | entailment |
public function authenticate($passwordProvided, $passwordHash)
{
if (password_verify($passwordProvided, $passwordHash)) {
$this->setAuthenticated(true);
if ($this->getUser() && property_exists($this->getUser(), $this->getUserIdProperty())) {
$userId = $this->getUser(... | Check whether the provided password matches the password hash.
@param string $passwordProvided
@param string $passwordHash
@return bool | entailment |
protected function isJsonString($data)
{
if (!is_string($data) && !is_null($data)) {
return false;
}
// We json_encode here to see if there might be a json_last_error
json_decode($data, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false;... | Attempt to check whether the provided string is json or not.
@param string $data
@return bool | entailment |
public function getNextTimeDay(array $dayList, $hour, $minute)
{
$nextTime = PHP_INT_MAX;
$currentTimeStamp = $this->getCurrentTimeStamp();
$nDate = date("n", $currentTimeStamp);
$yDate = date("Y", $currentTimeStamp);
$jDate = date("j", $currentTimeStamp);
foreach (... | @param array $dayList
@param integer $hour
@param integer $minute
@return int | entailment |
protected function nextFight(array $hourList, $minute)
{
sort($hourList);
$result = 0;
$timeStamp = $this->getCurrentTimeStamp();
$nDate = date("n", $timeStamp);
$yDate = date("Y", $timeStamp);
$jDate = date("j", $timeStamp);
$mDate = date("m", $timeStamp);
... | @param array $hourList
@param $minute
@return int | entailment |
protected function setValuesFromConfig()
{
if ($this->config->get('parable.mail.sender')) {
try {
$sender = \Parable\DI\Container::create($this->config->get('parable.mail.sender'));
$this->setMailSender($sender);
} catch (\Exception $e) {
... | Set the following values from config if available:
parable.mail.sender - the Mail sender implementation to use (default: PhpMail)
parable.mail.from.email - the email to set the from to by default
parable.mail.from.name - the name to set the from to by default, optional, only used if from.email is present
@return... | entailment |
public function loadTemplate($path)
{
$path = $this->path->getDir($path);
if (!file_exists($path)) {
throw new \Parable\Framework\Exception("Email template '{$path}' does not exist.");
}
$content = $this->view->partial($path);
$this->setBody(trim($content));
... | Load template for this mail. Returns the interpreted output as string.
@param string $path
@return $this
@throws \Parable\Framework\Exception | entailment |
public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken)
{
if (strlen($srcToken->getTermText()) < $this->length) {
return null;
} else {
return $srcToken;
}
} | Normalize Token or remove it (if null is returned)
@param Zend_Search_Lucene_Analysis_Token $srcToken
@return Zend_Search_Lucene_Analysis_Token | entailment |
protected function query(string $sql): ResultSet
{
$sql = preg_replace('/_\?\w{13}\?_/', '?', $sql);
if ($sql === null) {
throw new \UnexpectedValueException;
}
return $this->connection->query(...$this->addParams($sql));
} | Call Context::query() with current sql + params | entailment |
public function filter(array $filters): void
{
foreach ($filters as $filter) {
if ($filter->isValueSet()) {
if ($filter->getConditionCallback() !== null) {
$this->sql = call_user_func_array(
$filter->getConditionCallback(),
[$this->sql, $filter->getValue(), & $this->queryParameters]
);
... | {@inheritDoc} | entailment |
public function filterOne(array $condition): IDataSource
{
foreach ($condition as $column => $value) {
$this->applyWhere($column, $value);
}
return $this;
} | {@inheritDoc} | entailment |
public function setupEntities()
{
if ($this->registeredEntities->Count() > 0) {
return;
}
if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
$this->populateEntitiesFromInstall();
}
$registered = Config::inst()->get('Documen... | Sets up the top level entities.
Either manually registered through the YAML syntax or automatically
loaded through investigating the file system for `docs` folder. | entailment |
public function populateEntitiesFromInstall()
{
if ($this->automaticallyPopulated) {
// already run
return;
}
foreach (scandir(BASE_PATH) as $key => $entity) {
if ($key == "themes") {
continue;
}
$dir = Documentati... | Scans the current installation and picks up all the SilverStripe modules
that contain a `docs` folder.
@return void | entailment |
public function getPage($url)
{
$pages = $this->getPages();
$url = $this->normalizeUrl($url);
if (!isset($pages[$url])) {
return null;
}
$record = $pages[$url];
foreach ($this->getEntities() as $entity) {
if (strpos($record['filepath'], $en... | Returns a particular page for the requested URL.
@return DocumentationPage | entailment |
public function getRedirect($url)
{
$pages = $this->getRedirects();
$url = $this->normalizeUrl($url);
if (isset($pages[$url])) {
return $pages[$url];
}
} | Get any redirect for the given url
@param type $url
@return string | entailment |
public function regenerate($cache = true)
{
$finder = new DocumentationManifestFileFinder();
$finder->setOptions(
array(
'dir_callback' => array($this, 'handleFolder'),
'file_callback' => array($this, 'handleFile')
)
);
$this->redirec... | Regenerates the manifest by scanning the base path.
@param bool $cache | entailment |
protected function stripLinkBase($link)
{
// Trim baseURL
$link = preg_replace('/^' . preg_quote(Director::baseURL(), '/') .'/', '', $link);
// Trim link_base
if ($linkBase = Config::inst()->get('DocumentationViewer', 'link_base')) {
$link = preg_replace('/^' . preg_quot... | Remove the link_base from the start of a link
@param string $link
@return string | entailment |
protected function addRedirect($from, $to)
{
$fromLink = $this->stripLinkBase($from);
$toLink = $this->stripLinkBase($to);
// If the redirect "from" is already registered with a "to", don't override it. This ensures
// that the first version processed is treated as the canonical ver... | Add a redirect
@param string $from
@param string $to | entailment |
public function handleFile($basename, $path, $depth)
{
$page = Injector::inst()->create(
'DocumentationPage',
$this->entity,
$basename,
$path
);
// populate any meta data
$page->getMarkdown();
// Add main link
$fullLin... | Individual files can optionally provide a nice title and a better URL
through the use of markdown meta data. This creates a new
{@link DocumentationPage} instance for the file.
If the markdown does not specify the title in the meta data it falls back
to using the file name.
@param string $basename
@param string $path... | entailment |
public function generateBreadcrumbs($record, $base)
{
$output = new ArrayList();
$parts = explode('/', trim($record->getRelativeLink(), '/'));
// Add the base link.
$output->push(
new ArrayData(
array(
'Link' => $base->Link(),
... | Generate an {@link ArrayList} of the pages to the given page.
@param DocumentationPage
@param DocumentationEntityLanguage
@return ArrayList | entailment |
protected function buildUrl($url)
{
return Controller::join_links(
Director::baseURL(),
Config::inst()->get('DocumentationViewer', 'link_base'),
$url,
'/'
);
} | Create a clean domain-relative URL form a docuetn URL | entailment |
public function getNextPage($filepath, $entityBase)
{
$grabNext = false;
$fallback = null;
foreach ($this->getPages() as $url => $page) {
if ($grabNext && strpos($page['filepath'], $entityBase) !== false) {
return new ArrayData(
array(
... | Determine the next page from the given page.
Relies on the fact when the manifest was built, it was generated in
order.
@param string $filepath
@param string $entityBase
@return ArrayData | entailment |
public function getPreviousPage($filepath, $entityPath)
{
$previousUrl = $previousPage = null;
foreach ($this->getPages() as $url => $page) {
if ($filepath == $page['filepath']) {
if ($previousUrl) {
return new ArrayData(
array... | Determine the previous page from the given page.
Relies on the fact when the manifest was built, it was generated in
order.
@param string $filepath
@param string $entityBase
@return ArrayData | entailment |
public function normalizeUrl($url)
{
$url = trim($url, '/') .'/';
// if the page is the index page then hide it from the menu
if (strpos(strtolower($url), '/index.md/')) {
$url = substr($url, 0, strpos($url, "index.md/"));
}
return $url;
} | @param string
@return string | entailment |
public function getChildrenFor($entityPath, $recordPath = null)
{
if (!$recordPath) {
$recordPath = $entityPath;
}
$output = new ArrayList();
$entityPath = $this->normalizeUrl($entityPath);
$recordPath = $this->normalizeUrl($recordPath);
$recordParts = ex... | Return the children of the provided record path.
Looks for any pages in the manifest which have one more slash attached.
@param string $path
@return ArrayList | entailment |
public function getAllVersionsOfEntity(DocumentationEntity $entity)
{
$all = new ArrayList();
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
$all->push($ch... | @param DocumentationEntity
@return ArrayList | entailment |
public function getStableVersion(DocumentationEntity $entity)
{
foreach ($this->getEntities() as $check) {
if ($check->getKey() == $entity->getKey()) {
if ($check->getLanguage() == $entity->getLanguage()) {
if ($check->getIsStable()) {
... | @param DocumentationEntity
@return DocumentationEntity | entailment |
public function getAllVersions()
{
$versions = array();
foreach ($this->getEntities() as $entity) {
if ($entity->getVersion()) {
$versions[$entity->getVersion()] = $entity->getVersion();
} else {
$versions['0.0'] = _t('DocumentationManifest.MA... | Returns a sorted array of all the unique versions registered | entailment |
public static function fromInteger(int $vat = null): Tax
{
$mapping = [
0 => self::VAT0,
10 => self::VAT110,
18 => self::VAT118,
];
if (null === $vat) {
return new self(self::NONE);
}
if (!isset($mapping[$vat])) {
... | Get tax by integer value.
@param int|null $vat
@return Tax | entailment |
public static function clean_page_name($name)
{
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
$name = str_replace(array('-', '_'), ' ', $name);
return ucfirst(trim($name));
} | String helper for cleaning a file name to a readable version.
@param string $name to convert
@return string $name output | entailment |
public static function clean_page_url($name)
{
$name = str_replace(array(' '), '_', $name);
$name = self::trim_extension_off($name);
$name = self::trim_sort_number($name);
if (preg_match('/^[\/]?index[\/]?/', $name)) {
return '';
}
return strtolower($na... | String helper for cleaning a file name to a URL safe version.
@param string $name to convert
@return string $name output | entailment |
public static function trim_extension_off($name)
{
if (strrpos($name, '.') !== false) {
return substr($name, 0, strrpos($name, '.'));
}
return $name;
} | Helper function to strip the extension off and return the name without
the extension.
@param string
@return string | entailment |
public static function relativePath($path)
{
$base = self::normalizePath(Director::baseFolder());
return substr($path, strlen($base));
} | Helper function to make normalized paths relative
@param string
@return string | entailment |
private static function _getPrefix($word)
{
$questionMarkPosition = strpos($word, '?');
$astrericPosition = strpos($word, '*');
if ($questionMarkPosition !== false) {
if ($astrericPosition !== false) {
return substr($word, 0, min($questionMarkPosition, $astre... | Get terms prefix
@param string $word
@return string | entailment |
public function rewrite(Zend_Search_Lucene_Interface $index)
{
$this->_matches = array();
if ($this->_pattern->field === null) {
// Search through all fields
$fields = $index->getFieldNames(true /* indexed fields list */);
} else {
$fields = array($this->... | Re-write query into primitive queries in the context of specified index
@param Zend_Search_Lucene_Interface $index
@return Zend_Search_Lucene_Search_Query
@throws Zend_Search_Lucene_Exception | entailment |
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
{
$words = array();
$matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*'), preg_quote($this->_pattern->text, '/')) . '$/';
if (@preg_match('/\pL/u', 'a') == 1) {
... | Query specific matches highlighting
@param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) | entailment |
public function send($recipient, $body, $originator = '')
{
$result = $this->getSmsSender()->send($this->recipient, $body, $originator);
$result['recipient'] = $recipient;
return $result;
} | {@inheritdoc} | entailment |
public function rewrite(Zend_Search_Lucene_Interface $index)
{
$this->_matches = array();
if ($this->_field === null) {
// Search through all fields
$fields = $index->getFieldNames(true /* indexed fields list */);
} else {
$fields = array($this->_field);
... | Re-write query into primitive queries in the context of specified index
@param Zend_Search_Lucene_Interface $index
@return Zend_Search_Lucene_Search_Query | entailment |
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
{
$words = array();
$docBody = $highlighter->getDocument()->getFieldUtf8Value('body');
include_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
$tokens = Zend_Search_Lucene_Analysis_An... | Query specific matches highlighting
@param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) | entailment |
public function outerProduct(Vector $other): Matrix
{
$literal = [];
for ($i = 0; $i < $this->getSize(); $i++) {
for ($j = 0; $j < $other->getSize(); $j++) {
$literal[$i][$j] = $this->toArray()[$i] * $other->toArray()[$j];
}
}
return new Matr... | | a₀ | | a₀b₀ a₀b₁ a₀b₂ |
A ⨂ B = | a₁ | ⨂ |b₀ b₁b₂| = | a₁b₀ a₁b₁ a₁b₂|
| a₂ | | a₂b₀ a₂b₁ a₂b₂|
@param Vector $other
@return Matrix
@link https://en.wikipedia.org/wiki/Outer_product | entailment |
public function projection(self $other): self
{
return self::fromMatrix($other->multiplyScalar($this->dotProduct($other) / ($other->l2norm() ** 2)));
} | A⋅B
projᵇA = --- B
|B|²
@param self $other
@return self
@link https://en.wikipedia.org/wiki/Vector_projection#Vector_projection | entailment |
public function l1Norm(): float
{
return array_reduce($this->toArray(), function (float $carry, float $value) {
return $carry + abs($value);
}, 0);
} | |x|₁ = ∑|xᵢ|
@return float
@link https://en.wikipedia.org/wiki/Norm_(mathematics)#Taxicab_norm_or_Manhattan_norm | entailment |
public function l2Norm(): float
{
return sqrt(array_reduce($this->toArray(), function (float $carry, float $value) {
return $carry + pow($value, 2);
}, 0));
} | ______
|x|₂ = √∑|xᵢ|²
Also known as Euclidean norm, Euclidean length, L² distance, ℓ² distance
Used to normalize a vector.
@return float
@link http://mathworld.wolfram.com/L2-Norm.html
@link https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm | entailment |
public function maxNorm(): float
{
return array_reduce($this->toArray(), function (float $carry, float $value) {
$value = abs($value);
return $carry > $value ? $carry : $value;
}, -INF);
} | |x|∞ = max |x|
Max norm (infinity norm) (|x|∞)
@return float | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.