sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function getRuntimeContexts(array $unqualified_context_ids) {
$context_definition = new ContextDefinition('entity:node', NULL, FALSE);
$context = new Context($context_definition, $this->node);
return ['@node.node_route_context:node' => $context];
} | {@inheritdoc} | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$schemes = $this->utils->getFilesystemSchemes();
$options = array_combine($schemes, $schemes);
$form['filesystems'] = [
'#title' => $this->t('Filesystems'),
'#type' => 'checkboxes',
'#options' => $option... | {@inheritdoc} | entailment |
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['filesystems'] = array_filter($form_state->getValue('filesystems'));
parent::submitConfigurationForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['filesystems']) && !$this->isNegated()) {
return TRUE;
}
$file = $this->getContextValue('file');
return $this->evaluateFile($file);
} | {@inheritdoc} | entailment |
protected function evaluateFile(FileInterface $file) {
$uri = $file->getFileUri();
$scheme = $this->fileSystem->uriScheme($uri);
return !empty($this->configuration['filesystems'][$scheme]);
} | The actual evaluate function.
@param \Drupal\file\FileInterface $file
File.
@return bool
TRUE on success. | entailment |
public function index()
{
$currentUserId = Auth::user()->id;
// All threads, ignore deleted/archived participants
$threads = Thread::getAllLatest()->get();
// All threads that user is participating in
// $threads = Thread::forUser($currentUserId)->latest('updated_at')->get(... | Show all of the message threads to the user
@return mixed | entailment |
public function show($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('message');
}
// show current user in li... | Shows a message thread
@param $id
@return mixed | entailment |
public function store()
{
$input = Input::all();
$thread = Thread::create(
[
'subject' => $input['subject'],
]
);
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Aut... | Stores a new message thread
@return mixed | entailment |
public function getRuntimeContexts(array $unqualified_context_ids) {
$result = [];
$context_definition = new ContextDefinition('entity:media', NULL, FALSE);
$value = NULL;
// Hack the media out of the route.
$route_object = $this->routeMatch->getRouteObject();
if ($route_object) {
$route_... | {@inheritdoc} | entailment |
public function participantsUserIds($userId = null)
{
$users = $this->participants()->lists('user_id');
if ($userId) {
$users[] = $userId;
}
return $users;
} | Returns an array of user ids that are associated with the thread
@param null $userId
@return array | entailment |
public function scopeForUserWithNewMessages($query, $userId)
{
return $query->join('participants', 'threads.id', '=', 'participants.thread_id')
->where('participants.user_id', $userId)
->where(function ($query) {
$query->where('threads.updated_at', '>', $this->getConn... | Returns threads with new messages that the user is associated with
@param $query
@param $userId
@return mixed | entailment |
public function scopeBetween($query, array $participants)
{
$query->whereHas('participants', function ($query) use ($participants) {
$query->whereIn('user_id', $participants)
->groupBy('thread_id')
->havingRaw('COUNT(thread_id)='.count($participants));
... | Returns threads between given user ids
@param $query
@param $participants
@return mixed | entailment |
public function addParticipants(array $participants)
{
if (count($participants)) {
foreach ($participants as $user_id) {
Participant::firstOrCreate([
'user_id' => $user_id,
'thread_id' => $this->id,
]);
}
... | Adds users to this thread
@param array $participants list of all participants
@return void | entailment |
public function markAsRead($userId)
{
try {
$participant = $this->getParticipantFromUser($userId);
$participant->last_read = new Carbon;
$participant->save();
} catch (ModelNotFoundException $e) {
// do nothing
}
} | Mark a thread as read for a user
@param integer $userId | entailment |
public function isUnread($userId)
{
try {
$participant = $this->getParticipantFromUser($userId);
if ($this->updated_at > $participant->last_read) {
return true;
}
} catch (ModelNotFoundException $e) {
// do nothing
}
re... | See if the current thread is unread by the user
@param integer $userId
@return bool | entailment |
public function participantsString($userId=null, $columns=['first_name'])
{
$selectString = $this->createSelectString($columns);
$participantNames = $this->getConnection()->table($this->getUsersTable())
->join('participants', $this->getUsersTable() . '.id', '=', 'participants.user_id')
... | Generates a string of participant information
@param null $userId
@param array $columns
@return string | entailment |
protected function createSelectString($columns)
{
$dbDriver = $this->getConnection()->getDriverName();
switch ($dbDriver) {
case 'pgsql':
case 'sqlite':
$columnString = implode(" || ' ' || " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() ... | Generates a select string used in participantsString()
@param $columns
@return string | entailment |
private function getUsersTable()
{
if ($this->usersTable !== null) {
return $this->usersTable;
}
$userModel = Config::get('chat.user_model');
return $this->usersTable = (new $userModel)->getTable();
} | Returns the "users" table name to use in manual queries
@return string | entailment |
public function addSynonyms($list) {
$this->data = array_unique(array_merge($this->data, (array)$list));
return $this;
} | Add synonyms
@param string/array $list One array entry for each group of synonyms. The synonyms within a group are separated by commas.
Example: couch,sofa,divan | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['types'] = [
'#title' => $this->t('Content Entity Types'),
'#type' => 'checkboxes',
'#options' => [
'node' => $this->t('Node'),
'media' => $this->t('Media'),
'file' => $this->t('File... | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['types']) && !$this->isNegated()) {
return TRUE;
}
foreach ($this->configuration['types'] as $type) {
if ($this->getContext($type)->hasContextValue()) {
$entity = $this->getContextValue($type);
if ($entity && $entity->g... | {@inheritdoc} | entailment |
public function summary() {
if (count($this->configuration['types']) > 1) {
$types = $this->configuration['types'];
$last = array_pop($types);
$types = implode(', ', $types);
return $this->t(
'The content entity is a @types or @last',
[
'@types' => $types,
... | {@inheritdoc} | entailment |
public function relativeDateFilter($field, $fromUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $fromInterval, $toUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $toInterval = 0, $dateFormat = self::RELATIVE_DATE_FILTER_DATEFORMAT, $isNegative = false) {
$parameters = array(
'fromUnit' => $fromUnit,
... | Add a RelativeDateFilter on request
@return OpenSearchServer\Search | entailment |
public function negativeRelativeDateFilter($field, $fromUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $fromInterval, $toUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $toInterval = 0, $dateFormat = self::RELATIVE_DATE_FILTER_DATEFORMAT, $isNegative = false) {
return $this->relativeDateFilter($field, $fromUni... | Add a negative RelativeDateFilter on request
@return OpenSearchServer\Search | entailment |
public function geoFilter($shape = self::GEO_FILTER_SQUARED, $unit = self::GEO_FILTER_KILOMETERS, $distance, $isNegative = false) {
$parameters = array(
'shape' => $shape,
'unit' => $unit,
'distance' => $distance
);
$this->addFilter(null, self::GEO_FILTER, $isNegative, $parameters... | Add a GeoFilter on request
@return OpenSearchServer\Search | entailment |
public function negativeGeoFilter($shape = self::GEO_FILTER_SQUARED, $unit = self::GEO_FILTER_KILOMETERS, $distance) {
return $this->geoFilter(null, $shape, $unit, $distance, true);
} | Add a negative GeoFilter on request
@return OpenSearchServer\Search | entailment |
public function returnedFields($fields) {
if(empty($this->data['returnedFields'])) {
$this->data['returnedFields'] = array();
}
$this->data['returnedFields'] = array_unique(array_merge($this->data['returnedFields'], (array)$fields));
return $this;
} | Configure fields to return
@param array or string $fields
@return OpenSearchServer\Search | entailment |
function filterField($field, $filter, $join = self::OPERATOR_OR, $addQuotes = false) {
$quotes = ($addQuotes) ? '"' : '';
if(is_array($filter)) {
$filterString = $field . ':'.$quotes.'' . implode(''.$quotes.' '.$join.' '.$field.':'.$quotes.'', $filter ) .''.$quotes.'';
}
else {
$filterString = $field . ':... | Helper method: set a QueryFilter by specifying field and value.
Value can be an array of values, that will be joined with $join
@param string $field Field on which filter.
@param string $filter Value of the filter.
@param string $join Type of join. Default is OR.
@param string $addQuotes Whether or not add quotes aroun... | entailment |
private function addFilter($value = null, $type, $isNegative, $parameters = array()) {
if(empty($this->data['filters'])) {
$this->data['filters'] = array();
}
$newFilter = array(
'type' => $type,
'negative' => (boolean)$isNegative,
);
//add options depending on type of filter
switch($type) {
... | ****************************
PRIVATE METHODS
**************************** | entailment |
static public function fetch( $tagID, $locale, $includeDrafts = false )
{
$fetchParams = array( 'keyword_id' => $tagID, 'locale' => $locale );
if ( !$includeDrafts )
$fetchParams['status'] = self::STATUS_PUBLISHED;
return parent::fetchObject( self::definition(), null, $fetchPara... | Returns eZTagsKeyword object for given tag ID and locale
@static
@param int $tagID
@param string $locale
@param bool $includeDrafts
@return eZTagsKeyword | entailment |
static public function fetchByTagID( $tagID )
{
$tagKeywordList = parent::fetchObjectList( self::definition(), null, array( 'keyword_id' => $tagID ) );
if ( is_array( $tagKeywordList ) )
return $tagKeywordList;
return array();
} | Returns eZTagsKeyword list for given tag ID
@static
@param int $tagID
@return eZTagsKeyword[] | entailment |
public function languageName()
{
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetchByLocale( $this->attribute( 'locale' ) );
if ( $language instanceof eZContentLanguage )
return array( 'locale' => $language->attribute( 'locale' ), 'name' => $language->a... | Returns array with language name and locale for this instance
@return array | entailment |
public function searchField($field, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 1) {
if(empty($this->data['searchFields'])) {
$this->data['searchFields'] = array();
}
$this->data['searchFields'][] = array(
'field' => $field,
'mode' => $mode,
'boost' => $boost,
'phraseBoost' => $ph... | Add a field to search into
@return OpenSearchServer\Search\Search | entailment |
public function searchFields(array $fields, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 2) {
foreach($fields as $field) {
$this->searchField($field, $mode, $boost, $phraseBoost);
}
return $this;
} | Helper method: add several searchFields with same parameters | entailment |
public function getFilenames(array $fileOrDirectoryNames, array $filePatterns = [], FinderObserver $observer = null): array
{
$finder = clone $this->finder;
$finder->files();
$observer = $observer ?: new CallbackFinderObserver(function() {});
if (count($filePatterns) > 0) {
... | Generates a list of file names from a list of file and directory names.
@param string[] $fileOrDirectoryNames A list of file and directory names.
@param string[] $filePatterns Glob patterns that filenames should match
@param FinderObserver|null $observer
@return string[] A list of file na... | entailment |
public function getPath()
{
$this->checkPathIndexNeeded();
$path = rawurlencode($this->options['index']).'/morelikethis';
return (!empty($this->options['template'])) ? $path.'/template/'.rawurlencode($this->options['template']) : $path;
} | {@inheritdoc} | entailment |
public function getField($fieldName, $returnFirstValueOnly = true) {
if(!empty($this->fields[$fieldName]) && count($this->fields[$fieldName] > 0)) {
return ($returnFirstValueOnly) ? $this->fields[$fieldName][0] : $this->fields[$fieldName];
}
} | Return value of a field
@param string $fieldName
@param boolean $returnFirstValueOnly Return every values (useful for a multivalued field), or only
first value (useful for most of the cases when there is only one value).
Default value: true. | entailment |
public function getSnippet($fieldName, $returnFirstValueOnly = true) {
if(!empty($this->snippets[$fieldName]) && count($this->snippets[$fieldName] > 0)) {
return ($returnFirstValueOnly) ? $this->snippets[$fieldName][0] : $this->snippets[$fieldName];
}
} | Return value of a snippet
@param string $fieldName
@param boolean $returnFirstValueOnly Return every values (useful for a multivalued snippets), or only
first value (useful for most of the cases when there is only one value).
Default value: true. | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
// Build up options array.
$entity_types = $this->entityTypeManager->getDefinitions();
$view_modes = $this->entityTypeManager->getStorage('entity_view_mode')->loadMultiple();
$options = [];
foreach ($view_modes a... | {@inheritdoc} | entailment |
public function initialize(array $config)
{
if ($this->_config['referenceName'] == null) {
$this->_config['referenceName'] = $this->_referenceName();
}
$this->setupFieldAssociations($this->_config['versionTable']);
} | Constructor hook method.
Implement this method to avoid having to overwrite
the constructor and call parent.
@param array $config The configuration settings provided to this behavior.
@return void | entailment |
public function setupFieldAssociations($table)
{
$options = [
'table' => $table
];
foreach ($this->_fields() as $field) {
$this->versionAssociation($field, $options);
}
$this->versionAssociation(null, $options);
} | Creates the associations between the bound table and every field passed to
this method.
Additionally it creates a `version` HasMany association that will be
used for fetching all versions for each record in the bound table
@param string $table the table name to use for storing each field version
@return void | entailment |
public function versionAssociation($field = null, $options = [])
{
$name = $this->_associationName($field);
if (!$this->_table->associations()->has($name)) {
$model = $this->_config['referenceName'];
$options += [
'className' => $this->_config['versionTable'... | Returns association object for all versions or single field version.
@param string|null $field Field name for per-field association.
@param array $options Association options.
@return \Cake\ORM\Association | entailment |
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
$association = $this->versionAssociation();
$name = $association->getName();
$newOptions = [$name => ['validate' => false]];
$options['associated'] = $newOptions + $options['associated'];
... | Modifies the entity before it is saved so that versioned fields are persisted
in the database too.
@param \Cake\Event\Event $event The beforeSave event that was fired
@param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
@param \ArrayObject $options the options passed to the save method
... | entailment |
public function afterSave(Event $event, EntityInterface $entity)
{
$property = $this->versionAssociation()->getProperty();
$entity->unsetProperty($property);
} | Unsets the temporary `__version` property after the entity has been saved
@param \Cake\Event\Event $event The beforeSave event that was fired
@param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
@return void | entailment |
public function getVersionId(EntityInterface $entity)
{
$table = TableRegistry::get($this->_config['versionTable']);
$preexistent = $table->find()
->select(['version_id'])
->where([
'model' => $this->_config['referenceName']
] + $this->_ext... | return the last version id
@param \Cake\Datasource\EntityInterface $entity Entity.
@return int | entailment |
public function findVersions(Query $query, array $options)
{
$association = $this->versionAssociation();
$name = $association->getName();
return $query
->contain([$name => function (Query $q) use ($name, $options, $query) {
if (!empty($options['primaryKey'])) {
... | Custom finder method used to retrieve all versions for the found records.
Versioned values will be found for each entity under the property `_versions`.
### Example:
{{{
$article = $articles->find('versions')->first();
$firstVersion = $article->get('_versions')[1];
}}}
@param \Cake\ORM\Query $query The original que... | entailment |
public function groupVersions($results)
{
$property = $this->versionAssociation()->getProperty();
return $results->map(function (EntityInterface $row) use ($property) {
$versionField = $this->_config['versionField'];
$versions = (array)$row->get($property);
$grou... | Modifies the results from a table find in order to merge full version records
into each entity under the `_versions` key
@param \Cake\Datasource\ResultSetInterface $results Results to modify.
@return \Cake\Collection\CollectionInterface | entailment |
public function getVersions(EntityInterface $entity)
{
$primaryKey = (array)$this->_table->getPrimaryKey();
$query = $this->_table->find('versions');
$pkValue = $entity->extract($primaryKey);
$conditions = [];
foreach ($pkValue as $key => $value) {
$field = curre... | Returns the versions of a specific entity.
@param \Cake\Datasource\EntityInterface $entity Entity.
@return \Cake\Collection\CollectionInterface | entailment |
protected function _fields()
{
$schema = $this->_table->getSchema();
$fields = $schema->columns();
if ($this->_config['fields'] !== null) {
$fields = array_intersect($fields, (array)$this->_config['fields']);
}
return $fields;
} | Returns an array of fields to be versioned.
@return array | entailment |
protected function _extractForeignKey($entity)
{
$foreignKey = (array)$this->_config['foreignKey'];
$primaryKey = (array)$this->_table->getPrimaryKey();
$pkValue = $entity->extract($primaryKey);
return array_combine($foreignKey, $pkValue);
} | Returns an array with foreignKey value.
@param \Cake\Datasource\EntityInterface $entity Entity.
@return array | entailment |
protected function _associationName($field = null)
{
$alias = Inflector::singularize($this->_table->getAlias());
if ($field) {
$field = Inflector::camelize($field);
}
return $alias . $field . 'Version';
} | Returns default version association name.
@param string $field Field name.
@return string | entailment |
protected function _referenceName()
{
$table = $this->_table;
$name = namespaceSplit(get_class($table));
$name = substr(end($name), 0, -5);
if (empty($name)) {
$name = $table->getTable() ?: $table->getAlias();
$name = Inflector::camelize($name);
}
... | Returns reference name for identifying this model's records in version table.
@return string | entailment |
protected function _convertFieldsToType(array $fields, $direction)
{
if (!in_array($direction, ['toPHP', 'toDatabase'])) {
throw new InvalidArgumentException(sprintf('Cannot convert type, Cake\Database\Type::%s does not exist', $direction));
}
$driver = $this->_table->getConnect... | Converts fields to the appropriate type to be stored in the version, and
to be converted from the version record to the entity
@param array $fields Fields to convert
@param string $direction Direction (toPHP or toDatabase)
@return array | entailment |
public function indexed($indexed) {
if($indexed === true or $indexed === false) {
$this->data['indexed'] = ($indexed) ? 'YES' : 'NO';
} else {
$this->data['indexed'] = $indexed;
}
return $this;
} | Tell whether this field must be indexed or not
@param boolean $indexed
@return OpenSearchServer\Field\Create | entailment |
public function stored($stored) {
if($stored === true or $stored === false) {
$this->data['stored'] = ($stored) ? 'YES' : 'NO';
} else {
$this->data['stored'] = $stored;
}
return $this;
} | Tell whether this field must be stored or not
@param string $stored
@return OpenSearchServer\Field\Create | entailment |
public function onResponse(FilterResponseEvent $event) {
$response = $event->getResponse();
$media = $this->getObject($response, 'media');
if ($media === FALSE) {
return;
}
$links = array_merge(
$this->generateEntityReferenceLinks($media),
$this->generateRestLinks($media),
... | {@inheritdoc} | entailment |
protected function generateMediaLinks(MediaInterface $media) {
$media_type = $this->entityTypeManager->getStorage('media_type')->load($media->bundle());
$type_configuration = $media_type->get('source_configuration');
$links = [];
$update_route_name = 'islandora.media_source_update';
$update_route... | Generates link headers for the described file and source update routes.
@param \Drupal\media\MediaInterface $media
Media to generate link headers.
@return string[]
Array of link headers | entailment |
public function evaluateContexts(array $provided = []) {
$this->activeContexts = [];
/** @var \Drupal\context\ContextInterface $context */
foreach ($this->getContexts() as $context) {
if ($this->evaluateContextConditions($context, $provided) && !$context->disabled()) {
$this->activeContexts[... | Evaluate all context conditions.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions. | entailment |
public function evaluateContextConditions(ContextInterface $context, array $provided = []) {
$conditions = $context->getConditions();
// Apply context to any context aware conditions.
$this->applyContexts($conditions, $provided);
// Set the logic to use when validating the conditions.
$logic = $co... | Evaluate a contexts conditions.
@param \Drupal\context\ContextInterface $context
The context to evaluate conditions for.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions.
@return bool
TRUE if conditions pass | entailment |
protected function applyContexts(ConditionPluginCollection &$conditions, array $provided = []) {
foreach ($conditions as $condition) {
if ($condition instanceof ContextAwarePluginInterface) {
try {
if (empty($provided)) {
$contexts = $this->contextRepository->getRuntimeContexts(a... | Apply context to all the context aware conditions in the collection.
@param \Drupal\Core\Condition\ConditionPluginCollection $conditions
A collection of conditions to apply context to.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions.
@return bool
TRUE ... | entailment |
public function variables(array $variables) {
foreach($variables as $name => $value) {
$this->variable($name, $value);
}
return $this;
} | ****************************
HELPER METHOD
**************************** | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
// Build up options array.
$entity_types = $this->entityTypeManager->getDefinitions();
$form_displays = $this->entityTypeManager->getStorage('entity_form_display')->loadMultiple();
$options = [];
foreach ($form_d... | {@inheritdoc} | entailment |
public function writeStream($path, $resource, Config $config)
{
$path = pathinfo($path)['filename'];
$resource_metadata = stream_get_meta_data($resource);
$uploaded_metadata = Uploader::upload($resource_metadata['uri'], ['public_id' => $path, 'resource_type' => 'auto']);
re... | Write a new file using a stream.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function write($path, $resource, Config $config)
{
$path = pathinfo($path)['filename'];
return parent::write($path, $resource, $config);
} | Write a new file.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
protected function getObject(Response $response, $object_type) {
if ($object_type != 'node'
&& $object_type != 'media'
) {
return FALSE;
}
// Exit early if the response is already cached.
if ($response->headers->get('X-Drupal-Dynamic-Cache') == 'HIT') {
return FALSE;
}
if... | Get the Node | Media | File.
@param \Symfony\Component\HttpFoundation\Response $response
The current response object.
@param string $object_type
The type of entity to look for.
@return Drupal\Core\Entity\ContentEntityBase|bool
A node or media entity or FALSE if we should skip out. | entailment |
protected function generateEntityReferenceLinks(EntityInterface $entity) {
// Use the node to add link headers for each entity reference.
$entity_type = $entity->getEntityType()->id();
$bundle = $entity->bundle();
// Get all fields for the entity.
$fields = $this->entityFieldManager->getFieldDefini... | Generates link headers for each referenced entity.
@param \Drupal\Core\Entity\EntityInterface $entity
Entity that has reference fields.
@return string[]
Array of link headers | entailment |
protected function generateRestLinks(EntityInterface $entity) {
$rest_resource_config_storage = $this->entityTypeManager->getStorage('rest_resource_config');
$entity_type = $entity->getEntityType()->id();
$rest_resource_config = $rest_resource_config_storage->load("entity.$entity_type");
$current_forma... | Generates link headers for REST endpoints.
@param \Drupal\Core\Entity\EntityInterface $entity
Entity that has reference fields.
@return string[]
Array of link headers | entailment |
public function threadsWithNewMessages()
{
$threadsWithNewMessages = [];
$participants = Participant::where('user_id', $this->id)->lists('last_read', 'thread_id');
/**
* @todo: see if we can fix this more in the future.
* Illuminate\Foundation is not available through comp... | Returns all threads with new messages
@return array | entailment |
public function getConfigTreeBuilder(): TreeBuilder
{
if (method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('typoscript-lint');
$root = $treeBuilder->getRootNode();
} else {
$treeBuilder = new TreeBuilder();
$root = $tr... | Generates the configuration tree builder.
@return TreeBuilder The tree builder
@codeCoverageIgnore FU, I'm not going to test this one!
@suppress PhanParamTooMany, PhanUndeclaredMethod | entailment |
public function execute($entity = NULL) {
if (!$entity) {
return;
}
$transaction = $this->connection->startTransaction();
try {
// Delete all the source files and then the media.
$source_field = $this->mediaSourceService->getSourceFieldName($entity->bundle());
foreach ($entity-... | {@inheritdoc} | entailment |
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $object->access('delete', $account, $return_as_object);
} | {@inheritdoc} | entailment |
public function summary() {
if (count($this->configuration['filesystems']) > 1) {
$filesystems = $this->configuration['filesystems'];
$last = array_pop($filesystems);
$filesystems = implode(', ', $filesystems);
return $this->t(
'The media uses @filesystems or @last',
[
... | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['filesystems']) && !$this->isNegated()) {
return TRUE;
}
$media = $this->getContextValue('media');
$file = $this->mediaSource->getSourceFile($media);
if (!$file) {
return FALSE;
}
return $this->evaluateFile($file);
} | {@inheritdoc} | entailment |
private function buildFacetsArray($facetsJson) {
foreach($facetsJson as $facetObj) {
//build array of term with <term> => <number of occurences>
$terms = array();
foreach($facetObj->terms as $termObj) {
$terms[$termObj->term] = $termObj->count;
}
... | Build array of facets based on JSON results
@param array $facetsJson Array of JSON values for facets | entailment |
public function addStopWords($list) {
$this->data = array_unique(array_merge($this->data, (array)$list));
return $this;
} | Add synonyms
@param string/array $list One array entry for each stop word | entailment |
public function validateUser(CommandData $commandData) {
$userid = $commandData->input()->getOption('userid');
if ($userid) {
$account = User::load($userid);
if (!$account) {
throw new \Exception("User ID does not match an existing user.");
}
}
} | Validate the provided userid.
@hook validate migrate:import | entailment |
public function preImport(CommandData $commandData) {
$userid = $commandData->input()->getOption('userid');
if ($userid) {
$account = User::load($userid);
$accountSwitcher = \Drupal::service('account_switcher');
$userSession = new UserSession([
'uid' => $account->id(),
'name'... | Switch the active user account to perform the import.
@hook pre-command migrate:import | entailment |
public function postImport($result, CommandData $commandData) {
if ($commandData->input()->getOption('userid')) {
$accountSwitcher = \Drupal::service('account_switcher');
$this->logger()->notice(dt(
'Switching back from user @uid.',
['@... | Switch the user back once the migration is complete.
@hook post-command migrate:import | entailment |
protected function getSpecialOffset(\Imagick $original, $targetWidth, $targetHeight)
{
return $this->getEntropyOffsets($original, $targetWidth, $targetHeight);
} | get special offset for class
@param \Imagick $original
@param int $targetWidth
@param int $targetHeight
@return array | entailment |
protected function getEntropyOffsets(\Imagick $original, $targetWidth, $targetHeight)
{
$measureImage = clone($original);
// Enhance edges
$measureImage->edgeimage(1);
// Turn image into a grayscale
$measureImage->modulateImage(100, 0, 100);
// Turn everything darker ... | Get the topleftX and topleftY that will can be passed to a cropping method.
@param \Imagick $original
@param int $targetWidth
@param int $targetHeight
@return array | entailment |
protected function getOffsetFromEntropy(\Imagick $originalImage, $targetWidth, $targetHeight)
{
// The entropy works better on a blured image
$image = clone $originalImage;
$image->blurImage(3, 2);
$size = $image->getImageGeometry();
$originalWidth = $size['width'];
... | Get the offset of where the crop should start
@param \Imagick $image
@param int $targetHeight
@param int $targetHeight
@param int $sliceSize
@return array | entailment |
protected function slice($image, $originalSize, $targetSize, $axis)
{
$aSlice = null;
$bSlice = null;
// Just an arbitrary size of slice size
$sliceSize = ceil(($originalSize - $targetSize) / 25);
$aBottom = $originalSize;
$aTop = 0;
// while there still ar... | slice
@param mixed $image
@param mixed $originalSize
@param mixed $targetSize
@param mixed $axis h=horizontal, v = vertical
@access protected
@return void | entailment |
protected function getPotential($position, $top, $sliceSize)
{
$safeZoneList = $this->getSafeZoneList();
$safeRatio = 0;
if ($position == 'top' || $position == 'left') {
$start = $top;
$end = $top + $sliceSize;
} else {
$start = $top - $sliceSize... | getPotential
@param mixed $position
@param mixed $top
@param mixed $sliceSize
@access protected
@return void | entailment |
protected function grayscaleEntropy(\Imagick $image)
{
// The histogram consists of a list of 0-254 and the number of pixels that has that value
$histogram = $image->getImageHistogram();
return $this->getEntropy($histogram, $this->area($image));
} | Calculate the entropy for this image.
A higher value of entropy means more noise / liveliness / color / business
@param \Imagick $image
@return float
@see http://brainacle.com/calculating-image-entropy-with-python-how-and-why.html
@see http://www.mathworks.com/help/toolbox/images/ref/entropy.html | entailment |
protected function colorEntropy(\Imagick $image)
{
$histogram = $image->getImageHistogram();
$newHistogram = array();
// Translates a color histogram into a bw histogram
$colors = count($histogram);
for ($idx = 0; $idx < $colors; $idx++) {
$colors = $histogram[$i... | Find out the entropy for a color image
If the source image is in color we need to transform RGB into a grayscale image
so we can calculate the entropy more performant.
@param \Imagick $image
@return float | entailment |
public static function createFromParseError(ParseError $parseError): self
{
return new self(
$parseError->getSourceLine(),
0,
"Parse error: " . $parseError->getMessage(),
self::SEVERITY_ERROR,
get_class($parseError)
);
} | Creates a new warning from a parse error.
@param ParseError $parseError The parse error to convert into a warning.
@return Issue The converted warning. | entailment |
public static function createFromTokenizerError(TokenizerException $tokenizerException): self
{
return new self(
$tokenizerException->getSourceLine(),
0,
"Tokenization error: " . $tokenizerException->getMessage(),
self::SEVERITY_ERROR,
get_class($t... | Creates a new warning from a tokenizer error.
@param TokenizerException $tokenizerException The tokenizer error to convert into a warning.
@return Issue The converted warning. | entailment |
public function getPath()
{
$this->checkPathIndexNeeded();
if(empty($this->parameters['name'])) {
throw new \Exception('Method "name($name)" must be called before submitting request.');
}
return rawurlencode($this->options['index']).'/replication/run';
} | {@inheritdoc} | entailment |
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/lastfm.php', 'lastfm');
$this->app->bind(Lastfm::class, function () {
return new Lastfm(new \GuzzleHttp\Client(), config('lastfm.api_key'));
});
} | Register any package services. | entailment |
public function getConfig()
{
$config = [];
foreach ($this->providers as $key => $provider) {
$config[$key] = $provider->getConfig();
}
return $config;
} | Aggregates the config from the providers, and returns a hash with the namespace as the key, and the config
as the value.
@return array | entailment |
public function createCommand($name)
{
$startTimestamp = time();
#######################
# Build Paths #
#######################
$basePath = $this->getStashEntryPath($name);
$databaseDestination = $basePath . '/database.sql';
$persistentDestination ... | Creates a new stash entry with the given name.
@param string $name The name for the new stash entry
@return void | entailment |
public function listCommand()
{
$head = ['Name', 'Stashed At', 'From Preset', 'Cloned At'];
$rows = [];
$basePath = sprintf(FLOW_PATH_ROOT . 'Data/MagicWandStash');
if (!is_dir($basePath)) {
$this->renderLine('Stash is empty.');
$this->quit(1);
}
... | Lists all entries
@return void | entailment |
public function clearCommand()
{
$startTimestamp = time();
$path = FLOW_PATH_ROOT . 'Data/MagicWandStash';
FileUtils::removeDirectoryRecursively($path);
#################
# Final Message #
#################
$endTimestamp = time();
$duration = $endTi... | Clear the whole stash
@return void | entailment |
public function restoreCommand($name, $yes = false, $keepDb = false)
{
$basePath = $this->getStashEntryPath($name);
$this->restoreStashEntry($basePath, $name, $yes, true, $keepDb);
} | Restores stash entries
@param string $name The name of the stash entry that will be restored
@param boolean $yes confirm execution without further input
@param boolean $keepDb skip dropping of database during sync
@return void | entailment |
public function removeCommand($name, $yes = false)
{
$directory = FLOW_PATH_ROOT . 'Data/MagicWandStash/' . $name;
if (!is_dir($directory)) {
$this->renderLine('<error>%s does not exist</error>', [$name]);
$this->quit(1);
}
if (!$yes) {
$this->re... | Remove a named stash entry
@param string $name The name of the stash entry that will be removed
@param boolean $yes confirm execution without further input
@return void | entailment |
protected function restoreStashEntry($source, $name, $force = false, $preserve = true, $keepDb = false)
{
if (!is_dir($source)) {
$this->renderLine('<error>%s does not exist</error>', [$name]);
$this->quit(1);
}
#################
# Are you sure? #
###... | Actual restore logic
@param string $source
@param string $name
@param boolean $force
@param boolean $keepDb
@return void | entailment |
public function fillFieldWithValue($field, $value = '')
{
$fieldNode = $this->spin(
function () use ($field) {
$fieldNode = $this->getSession()->getPage()->findField($field);
if ($fieldNode == null) {
throw new \Exception('Field not found');
... | @When I fill in :field with :value
@When I set :field as empty
Spin function make it possible to retry in case of failure | entailment |
public function clickEditActionBar($button)
{
$actionBarElements = $this->findAllWithWait('.ez-editactionbar-container .ez-action .action-label');
foreach ($actionBarElements as $element) {
if ($element->isVisible() && $element->getText() === $button) {
$element->click();... | @Given I click (on) the edit action bar button :button
Click on a PlatformUI edit action bar
@param string $button Text of the element to click | entailment |
public function goToContentWithPath($path)
{
$this->clickNavigationZone('Content');
$this->clickNavigationItem('Content structure');
$this->clickOnBrowsePath($path);
$this->confirmSelection();
} | Opens a content in PlatformUi. | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$container->getD... | {@inheritdoc} | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.