sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function setMask(int $mask): ZipManager {
try {
foreach ( $this->zip_archives as $archive ) {
$archive->setMask($mask);
}
return $this;
} catch (ZipException $ze) {
throw $ze;
}
} | Set default file mask for all Zips
@param int $mask
@return ZipManager
@throws ZipException | entailment |
public function getMask(): array {
return array_column(
array_map(function($key, $archive) {
return [ "key" => $key, "mask" => $archive->getMask() ];
}, array_keys($this->zip_archives), $this->zip_archives),
"mask", "key");
} | Get a list of masks from Zips
@return array | entailment |
public function listFiles(): array {
try {
return array_column(
array_map(function($key, $archive) {
return [ "key" => $key, "files" => $archive->listFiles() ];
}, array_keys($this->zip_archives), $this->zip_archives),
"files", "key");... | Get a list of files in Zips
@return array
@throws ZipException | entailment |
public function extract(
string $destination,
bool $separate = true,
$files = null
): bool {
try {
foreach ( $this->zip_archives as $archive ) {
$local_path = substr($destination, -1) == '/' ? $destination : $destination.'/';
$local_file ... | Extract Zips to common destination
@param string $destination Destination path
@param bool $separate (optional) If true (default), files will be placed in different directories
@param mixed $files (optional) a filename or an array of filenames
@return bool
@throws ZipException | entailment |
public function merge(string $output_zip_file, bool $separate = true): bool {
$pathinfo = pathinfo($output_zip_file);
$temporary_folder = $pathinfo['dirname']."/".ManagerTools::getTemporaryFolder();
try {
$this->extract($temporary_folder, $separate);
$zip = Zip::create... | Merge multiple Zips into one
@param string $output_zip_file
Destination zip
@param bool $separate (optional)
If true (default), files will be placed in different directories
@return bool
@throws ZipException | entailment |
public function add($file_name_or_array, bool $flatten_root_folder = false): ZipManager {
try {
foreach ( $this->zip_archives as $archive ) {
$archive->add($file_name_or_array, $flatten_root_folder);
}
return $this;
} catch (ZipException $ze) {
... | Add a file to all registered Zips
@param mixed $file_name_or_array
The filename to add or an array of filenames
@param bool $flatten_root_folder
(optional) If true, the Zip root folder will be flattened (default: false)
@return ZipManager
@throws ZipException | entailment |
public function delete($file_name_or_array): ZipManager {
try {
foreach ( $this->zip_archives as $archive ) {
$archive->delete($file_name_or_array);
}
return $this;
} catch (ZipException $ze) {
throw $ze;
}
} | Delete a file from any registered Zip
@param mixed $file_name_or_array
The filename to add or an array of filenames
@return ZipManager
@throws ZipException | entailment |
public function close(): bool {
try {
foreach ( $this->zip_archives as $archive ) {
$archive->close();
}
return true;
} catch (ZipException $ze) {
throw $ze;
}
} | Close all Zips
@return bool
@throws ZipException | entailment |
public static function getFormat($type, array $options = array())
{
// Sanitize format type.
$type = strtolower(preg_replace('/[^A-Z0-9_]/i', '', $type));
/*
* Only instantiate the object if it doesn't already exist.
* @deprecated 2.0 Object caching will no longer be supported, a new instance will be retu... | Returns an AbstractRegistryFormat object, only creating it if it doesn't already exist.
@param string $type The format to load
@param array $options Additional options to configure the object
@return FormatInterface Registry format handler
@since 1.5.0
@throws \InvalidArgumentException | entailment |
public function search($name, $type = null, $deepSearch = true)
{
/** @var TokenInterface[] $array */
$array = $this->getArrayCopy();
foreach ($array as $token) {
if (fnmatch($name, $token->getName())) {
if ($type === null) {
return $token;
... | Search this object for a Token with a specific name and return the first match
@param string $name [required] Name of the token
@param int $type [optional] TOKEN_DIRECTIVE | TOKEN_BLOCK
@param bool $deepSearch [optional] If the search should be multidimensional. Default is true
@return null|TokenInterface Returns the ... | entailment |
public function getIndex($name, $type = null)
{
/** @var TokenInterface[] $array */
$array = $this->getArrayCopy();
foreach ($array as $index => $token) {
if ($token->getName() === $name) {
if ($type === null) {
return $index;
... | Search this object for a Token with specific name and return the index(key) of the first match
@param string $name [required] Name of the token
@param int $type [optional] TOKEN_DIRECTIVE | TOKEN_BLOCK
@return int|null Returns the index or null if Token is not found | entailment |
public function jsonSerialize()
{
/** @var \Tivie\HtaccessParser\Token\TokenInterface[] $array */
$array = $this->getArrayCopy();
$otp = array();
foreach ($array as $arr) {
if (!$arr instanceof WhiteLine & !$arr instanceof Comment) {
$otp[$arr->getName()] ... | Get a representation ready to be encoded with json_encoded.
Note: Whitelines and Comments are ignored and will not be included in the serialization
@api
@link http://php.net/manual/en/jsonserializable.jsonserialize.php
@return mixed data which can be serialized by <b>json_encode</b>,
which is a value of any type other... | entailment |
public function txtSerialize($indentation = null, $ignoreWhiteLines = null, $ignoreComments = false)
{
/** @var \Tivie\HtaccessParser\Token\TokenInterface[] $array */
$array = $this->getArrayCopy();
$otp = '';
$this->indentation = (is_null($indentation)) ? $this->indentation : $inde... | Returns a representation of the htaccess, ready for inclusion in a file
@api
@param int $indentation [optional] Defaults to null
@param bool $ignoreWhiteLines [optional] Defaults to null
@param bool $ignoreComments [optional] Defaults to null
@return string | entailment |
public function slice($offset, $length = null, $preserveKeys = false, $asArray = false)
{
if (!is_int($offset)) {
throw new InvalidArgumentException('integer', 0);
}
if (!is_null($length) && !is_int($length)) {
throw new InvalidArgumentException('integer', 1);
... | Returns the sequence of elements as specified by the offset and length parameters.
@param int $offset [required] If offset is non-negative, the sequence will start at that offset.
If offset is negative, the sequence will start that far from the end of the
array.
@param int $length [optional] If length is given and is ... | entailment |
public function insertAt($offset, TokenInterface $token)
{
if (!is_int($offset)) {
throw new InvalidArgumentException('integer', 0);
}
$this->splice($offset, 0, array($token));
return $this;
} | @param int $offset [required] If offset is positive then the token will be inserted at that offset from the
beginning. If offset is negative then it starts that far from the end of the input
array.
@param TokenInterface $token [required] The token to insert
@return $this
@throws InvalidArgumentException | entailment |
public function splice($offset, $length = null, $replacement = array())
{
if (!is_int($offset)) {
throw new InvalidArgumentException('integer', 0);
}
if (!is_null($length) && !is_int($length)) {
throw new InvalidArgumentException('integer', 1);
}
if (!... | Removes the elements designated by offset and length, and replaces them with the elements of the replacement
array, if supplied.
@param int $offset [required] If offset is positive then the start of removed portion is at that offset
from the beginning. If offset is negative then it starts that far from the
end of the ... | entailment |
public function findConcept($query, $options)
{
$query->where([
$this->config('field') => $this->config('states.concept'),
]);
return $query;
} | findConcept
Finder for the state 'concepts'.
@param \Cake\ORM\Query $query The current Query object.
@param array $options Optional options.
@return \Cake\ORM\Query The modified Query object. | entailment |
public function findActive($query, $options)
{
$query->where([
$this->config('field') => $this->config('states.active'),
]);
return $query;
} | findActive
Finder for the state 'active'.
@param \Cake\ORM\Query $query The current Query object.
@param array $options Optional options.
@return \Cake\ORM\Query The modified Query object. | entailment |
public function findDeleted($query, $options)
{
$query->where([
$this->config('field') => $this->config('states.deleted'),
]);
return $query;
} | findDeleted
Finder for the state 'deleted'.
@param \Cake\ORM\Query $query The current Query object.
@param array $options Optional options.
@return \Cake\ORM\Query The modified Query object. | entailment |
public function getAnchor()
{
$linkedElement = $this->LinkedElement();
if ($linkedElement && $linkedElement->exists()) {
return $linkedElement->getAnchor();
}
return 'e' . $this->ID;
} | Get a unique anchor name.
@return string | entailment |
public function forTemplate($holder = true)
{
if ($linked = $this->LinkedElement()) {
return $linked->forTemplate($holder);
}
return null;
} | Override to render template based on LinkedElement
@return string|null HTML | entailment |
private static function doReduce($reducedMetrics, $metric)
{
$metricLength = strlen($metric);
$lastReducedMetric = count($reducedMetrics) > 0 ? end($reducedMetrics) : null;
if ($metricLength >= self::MAX_UDP_SIZE_STR
|| null === $lastReducedMetric
|| strlen($newMetri... | This function reduces the number of packets,the reduced has the maximum dimension of self::MAX_UDP_SIZE_STR
Reference:
https://github.com/etsy/statsd/blob/master/README.md
All metrics can also be batch send in a single UDP packet, separated by a newline character.
@param array $reducedMetrics
@param array $metric
@re... | entailment |
public function appendSampleRate($data, $sampleRate = 1)
{
if ($sampleRate < 1) {
array_walk($data, function(&$message, $key) use ($sampleRate) {
$message = sprintf('%s|@%s', $message, $sampleRate);
});
}
return $data;
} | Reference: https://github.com/etsy/statsd/blob/master/README.md
Sampling 0.1
Tells StatsD that this counter is being sent sampled every 1/10th of the time.
@param mixed $data
@param int $sampleRate
@return mixed $data | entailment |
public function send($data, $sampleRate = 1)
{
// check format
if ($data instanceof StatsdDataInterface || is_string($data)) {
$data = array($data);
}
if (!is_array($data) || empty($data)) {
return;
}
// add sampling
if ($sampleRate < 1... | /*
Send the metrics over UDP
{@inheritDoc} | entailment |
public function setMask(int $mask): ZipInterface {
$mask = filter_var($mask, FILTER_VALIDATE_INT, [
"options" => [
"max_range" => 0777,
"default" => 0777
],
'flags' => FILTER_FLAG_ALLOW_OCTAL
]);
$this->mask = $mask;
r... | Set the mask of the extraction folder
@param int $mask Integer representation of the file mask
@return Zip | entailment |
public function setPassword(string $password): ZipInterface {
$this->password = $password;
$this->getArchive()->setPassword($password);
return $this;
} | Set zip password
@param string $password
@return Zip | entailment |
public function getManipulatedData(GridField $gridField, SS_List $dataList)
{
if (!$gridField->State->GridFieldAddRelation) {
return $dataList;
}
$objectID = Convert::raw2sql($gridField->State->GridFieldAddRelation);
if ($objectID) {
$object = DataObject::g... | If an object ID is set, add the object to the list
@param GridField $gridField
@param SS_List $dataList
@return SS_List | entailment |
public function setCol($col = null)
{
if ($col !== null) {
$this->otherOptions['col'] = $col;
} else {
unset($this->otherOptions['col']);
}
return $this;
} | Name of the collection (Crawlbot or Bulk API job name) to search.
By default the search will operate on all of your token's collections.
@param null|string $col
@return $this | entailment |
public function setNum($num = 20)
{
if (!is_numeric($num) && $num !== self::SEARCH_ALL) {
throw new \InvalidArgumentException(
'Argument can only be numeric or "all" to return all results.'
);
}
$this->otherOptions['num'] = $num;
return $this;... | Number of results to return. Default is 20. To return all results in
the search, pass num=all.
@param int $num
@return $this | entailment |
public function buildUrl()
{
$url = rtrim($this->apiUrl, '/') . '?';
// Add token
$url .= 'token=' . $this->diffbot->getToken();
// Add query
$url .= '&query=' . urlencode($this->query);
// Add other options
foreach ($this->otherOptions as $option => $valu... | Builds out the URL string that gets requested once `call()` is called
@return string | entailment |
public function call($info = false)
{
if (!$info) {
$ei = parent::call();
set_error_handler(function() { /* ignore errors */ });
$arr = json_decode((string)$ei->getResponse()->getBody(), true, 512, 1);
restore_error_handler();
unset($arr['request... | If you pass in `true`, you get back a SearchInfo object related to the
last call. Keep in mind that passing in true before calling a default
call() will implicitly call the call(), and then get the SearchInfo.
So:
$searchApi->call() // gets entities
$searchApi->call(true) // gets SearchInfo about the executed query
... | entailment |
public function isOwnedBy($item, $user = [])
{
if (!is_array($item)) {
$item = $item->toArray();
}
if (empty($user)) {
return false;
}
$itemUserId = $item[$this->config('column')];
$userId = $user['id'];
if ($itemUserId === $userId) ... | isOwnedBy
@param array|\Cake\ORM\Entity $item Entity or array with the object to check on.
@param array $user The user who is owner (or not).
@return bool | entailment |
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer)
{
// ensure statement has a ParameterContainer
$parameterContainer = $statementContainer->getParameterContainer();
if (!$parameterContainer instanceof ParameterContainer) {
... | Prepare statement
@param AdapterInterface $adapter
@param StatementContainerInterface $statementContainer
@return void | entailment |
public function getSqlString(PlatformInterface $adapterPlatform = null)
{
// get platform, or create default
$adapterPlatform = ($adapterPlatform) ? : new SphinxQL();
$sqls = [];
$sqls[self::SHOW] = sprintf($this->specifications[static::SHOW], $this->show);
$likePart = $th... | Get SQL string for statement
@param null|PlatformInterface $adapterPlatform If null, defaults to SphinxQL
@return string | entailment |
public function objectToString($object, $options = array())
{
$array = json_decode(json_encode($object), true);
return $this->dumper->dump($array, 2, 0);
} | Converts an object into a YAML formatted string.
We use json_* to convert the passed object to an array.
@param object $object Data source object.
@param array $options Options used by the formatter.
@return string YAML formatted string.
@since 1.0 | entailment |
public function updateCMSFields(FieldList $fields)
{
$global = $fields->dataFieldByName('AvailableGlobally');
if ($global) {
$fields->removeByName('AvailableGlobally');
$fields->addFieldToTab('Root.Settings', $global);
}
if ($virtual = $fields->dataFieldByNa... | @param FieldList $fields
@return FieldList | entailment |
public function onBeforeDelete()
{
if (Versioned::get_reading_mode() == 'Stage.Stage') {
$firstVirtual = false;
$allVirtual = $this->getVirtualElements();
if ($this->getPublishedVirtualElements()->Count() > 0) {
// choose the first one
$fi... | Ensure that if there are elements that are virtualised from this element
that we move the original element to replace one of the virtual elements
But only if it's a delete not an unpublish | entailment |
public function getUsage()
{
$usage = new ArrayList();
if ($page = $this->getPage()) {
$usage->push($page);
if ($this->virtualOwner) {
$page->setField('ElementType', 'Linked');
} else {
$page->setField('ElementType', 'Master');
... | get all pages where this element is used
@return ArrayList | entailment |
public function search($params)
{
$query = Model::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'menu_... | Creates data provider instance with search query applied
@param array $params
@return ActiveDataProvider | entailment |
public function initialize(array $config)
{
parent::initialize($config);
$this->Controller = $this->_registry->getController();
$this->_addFromConfigure();
// set up the default helper
$this->Controller->helpers['Utils.Menu'] = [];
} | initialize
Initialize callback for Components.
@param array $config Configurations.
@return void | entailment |
public function beforeFilter($event)
{
$this->setController($event->subject());
if (method_exists($this->Controller, 'initMenuItems')) {
$this->Controller->initMenuItems($event);
}
} | BeforeFilter Event
This method will check if the `initMenuItems`-method exists in the
`AppController`. That method contains menu-items to add.
@param \Cake\Event\Event $event Event.
@return void | entailment |
public function area($area = null)
{
if ($area !== null) {
$this->area = $area;
}
return $this->area;
} | area
Method to set or get the current area.
Leave empty to get the current area.
Set with a string to set a new area.
@param string|void $area The area where the item should be stored.
@return string | entailment |
public function active($id)
{
$menu = $this->getMenu($this->area());
foreach ($menu as $key => $item) {
if ($menu[$key]['id'] == $id) {
$menu[$key]['active'] = true;
}
}
$data = self::$data;
$data[$this->area] = $menu;
self::$da... | active
Makes a menu item default active.
### Example:
$this->Menu->active('bookmarks');
In this example the menu-item with the id `bookmarks` will be set to active.
@param string $id The id of the menu-item
@return void | entailment |
public function getMenu($area = null)
{
if (!key_exists($area, self::$data)) {
return self::$data;
} else {
return self::$data[$area];
}
} | getMenu
Returns the menu-data of a specific area, or full data if area is not set.
@param string $area The area where the item should be stored.
@return array The menu-items of the area. | entailment |
public function add($title, $item = [])
{
$list = self::$data;
$_item = [
'id' => $title,
'parent' => false,
'url' => '#',
'title' => $title,
'icon' => '',
'area' => $this->area(),
'active' => false,
'we... | add
Adds a new menu-item.
### OPTIONS
- id
- parent
- url
- title
- icon
- area
- weight
@param string $title The title or id of the item.
@param array $item Options for the item.
@return void | entailment |
public function remove($id, $options = [])
{
$_options = [
'area' => false,
];
$options = array_merge($_options, $options);
if ($options['area']) {
$this->area = $item['area'];
}
unset(self::$data[$this->area][$id]);
} | remove
Removes a menu-item.
### OPTIONS
- area The area to remove from.
@param string $id Identifier of the item.
@param array $options Options.
@return void | entailment |
protected function _addFromConfigure()
{
$configure = Configure::read('Menu.Register');
if (!is_array($configure)) {
$configure = [];
}
foreach ($configure as $key => $item) {
$this->add($key, $item);
}
} | _registerFromConfigure
This method gets the menuitems from the Configure: `PostTypes.register.*`.
### Adding menuitems via the `Configure`-class
You can add a menuitem by:
`Configure::write('Menu.Register.MyName', [*settings*]);`
@return void | entailment |
public function produceStatsdData($key, $value = 1, $metric = StatsdDataInterface::STATSD_METRIC_COUNT)
{
$statsdData = $this->produceStatsdDataEntity();
if (null !== $key) {
$statsdData->setKey($key);
}
if (null !== $value) {
$statsdData->setValue($value);
... | {@inheritDoc} | entailment |
protected function bindParametersFromContainer()
{
if ($this->parametersBound) {
return;
}
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
// if param has no errata, PDO will detect the right type
... | Bind parameters from container | entailment |
public function release( $version = 'dev-master' ) {
$package = "youzanyun/open-sdk";
list( $vendor, $name ) = explode( '/', $package );
if ( empty( $vendor ) || empty( $name ) ) {
return;
}
$this->_mkdir( 'release' );
$this->taskExec( "composer create-project {$package} {$name} {$version}" )
... | Creates release zip
@param string $version Version to build. | entailment |
public static function get(int $code): string {
if ( array_key_exists($code, self::ZIP_STATUS_CODES) ) return self::ZIP_STATUS_CODES[$code];
else return sprintf('Unknown status %s', $code);
} | Get status from zip status code
@param int $code ZIP status code
@return string | entailment |
public function getDate()
{
if (!isset($this->data['date'])) {
return null;
}
try {
return (class_exists('\Carbon\Carbon')) ?
new \Carbon\Carbon($this->data['date'], 'GMT') :
$this->data['date'];
} catch (\Exception $e) {
... | Returns date as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
Example date: "Wed, 18 Dec 2013 00:00:00 GMT"
This will be a Carbon (https://github.com/briannesbitt/Carbon) instance if Carbon is installed.
@return \Carbon\Carbon | string | entailment |
public function getEstimatedDate()
{
$date = $this->getOrDefault('estimatedDate', $this->getDate());
return (class_exists('\Carbon\Carbon')) ?
new \Carbon\Carbon($date, 'GMT') :
$date;
} | If an article's date is ambiguous, Diffbot will attempt to estimate a
more specific timestamp using various factors. This will not be
generated for articles older than two days, or articles without an identified date.
@see Article::getDate() - used when estimatedDate isn't defined
This will be a Carbon (https://githu... | entailment |
public function from($table)
{
if ($table instanceof TableIdentifier) {
$table = $table->getTable(); // Ignore schema because it is not supported by SphinxQL
}
$this->table = $table;
return $this;
} | Create from statement
@param string|TableIdentifier $table
@return Delete | entailment |
public function getDownloadUrl($type = "json")
{
switch ($type) {
case "json":
return $this->data['downloadJson'];
case "debug":
return $this->data['downloadUrls'];
case "csv":
return rtrim($this->data['downloadJson'... | Returns the link to the dataset the job produced.
Accepted arguments are: "json", "csv" and "debug".
It is important to be aware of the difference between the types.
See "Retrieving Bulk Data" in link.
@see https://www.diffbot.com/dev/docs/crawl/api.jsp
@param string $type
@return string
@throws DiffbotException | entailment |
public function setPath(?string $path = null): ZipInterface {
if ( $path === null ) {
$this->path = null;
} else if ( !file_exists($path) ) {
throw new ZipException("Not existent path: $path");
} else {
$this->path = $path;
}
return $this;
... | Set current base path (to add relative files to zip archive)
@param string|null $path
@return Zip
@throws ZipException | entailment |
public function setText($text)
{
if (!is_string($text)) {
throw new InvalidArgumentException('string', 0);
}
$text = trim($text);
if (strpos($text, '#') !== 0) {
$text = '# ' . $text;
}
$this->text = $text;
return $this;
} | Set the Comment Text
@param string $text The comment new text. A # will be prepended automatically if it isn't found at the beginning
of the string.
@return $this
@throws InvalidArgumentException | entailment |
public function setSeeds(array $seeds)
{
$invalidSeeds = [];
foreach ($seeds as $seed) {
if (!filter_var($seed, FILTER_VALIDATE_URL)) {
$invalidSeeds[] = $seed;
}
}
if (!empty($invalidSeeds)) {
throw new \InvalidArgumentException(
... | An array of URLs (seeds) which to crawl for matching links
By default Crawlbot will restrict spidering to the entire domain
("http://blog.diffbot.com" will include URLs at "http://www.diffbot.com").
@param array $seeds
@return $this | entailment |
public function setUrlCrawlPatterns(array $pattern = null)
{
$this->otherOptions['urlCrawlPattern'] = ($pattern === null) ? null
: implode("||", array_map(function ($item) {
return urlencode($item);
}, $pattern));
return $this;
} | Array of strings to limit pages crawled to those whose URLs
contain any of the content strings.
You can use the exclamation point to specify a negative string, e.g.
!product to exclude URLs containing the string "product," and the ^ and
$ characters to limit matches to the beginning or end of the URL.
The use of a ur... | entailment |
public function setPageProcessPatterns(array $pattern)
{
$this->otherOptions['pageProcessPattern'] = implode("||",
array_map(function ($item) {
return urlencode($item);
}, $pattern));
return $this;
} | Specify ||-separated strings to limit pages processed to those whose
HTML contains any of the content strings.
@param array $pattern
@return $this | entailment |
public function setMaxHops($input = -1)
{
if ((int)$input < -1) {
$input = -1;
}
$this->otherOptions['maxHops'] = (int)$input;
return $this;
} | Specify the depth of your crawl. A maxHops=0 will limit processing to
the seed URL(s) only -- no other links will be processed; maxHops=1 will
process all (otherwise matching) pages whose links appear on seed URL(s);
maxHops=2 will process pages whose links appear on those pages; and so on
By default, Crawlbot will cr... | entailment |
public function setMaxToCrawl($input = 100000)
{
if ((int)$input < 1) {
$input = 1;
}
$this->otherOptions['maxToCrawl'] = (int)$input;
return $this;
} | Specify max pages to spider. Default: 100,000.
@param int $input
@return $this | entailment |
public function setMaxToProcess($input = 100000)
{
if ((int)$input < 1) {
$input = 1;
}
$this->otherOptions['maxToProcess'] = (int)$input;
return $this;
} | Specify max pages to process through Diffbot APIs. Default: 100,000.
@param int $input
@return $this | entailment |
public function notify($string)
{
if (filter_var($string, FILTER_VALIDATE_EMAIL)) {
$this->otherOptions['notifyEmail'] = $string;
return $this;
}
if (filter_var($string, FILTER_VALIDATE_URL)) {
$this->otherOptions['notifyWebhook'] = urlencode($string);
... | If input is email address, end a message to this email address when the
crawl hits the maxToCrawl or maxToProcess limit, or when the crawl
completes.
If input is URL, you will receive a POST with X-Crawl-Name and
X-Crawl-Status in the headers, and the full JSON response in the
POST body.
@param string $string
@return... | entailment |
public function setCrawlDelay($input = 0.25)
{
if (!is_numeric($input)) {
throw new InvalidArgumentException('Input must be numeric.');
}
$input = ($input < 0) ? 0.25 : $input;
$this->otherOptions['crawlDelay'] = (float)$input;
return $this;
} | Wait this many seconds between each URL crawled from a single IP address.
Specify the number of seconds as an integer or floating-point number.
@param float $input
@return $this
@throws InvalidArgumentException | entailment |
public function setRepeat($input)
{
if (!is_numeric($input) || !$input) {
throw new \InvalidArgumentException('Only positive numbers allowed.');
}
$this->otherOptions['repeat'] = (float)$input;
return $this;
} | Specify the number of days as a floating-point (e.g. repeat=7.0) to
repeat this crawl. By default crawls will not be repeated.
@param int|float $input
@return $this
@throws \InvalidArgumentException | entailment |
public function setMaxRounds($input = 0)
{
if ((int)$input < -1) {
$input = -1;
}
$this->otherOptions['maxRounds'] = (int)$input;
return $this;
} | Specify the maximum number of crawl repeats. By default (maxRounds=0)
repeating crawls will continue indefinitely.
@param int $input
@return $this | entailment |
public function buildUrl()
{
if (isset($this->otherOptions['urlProcessRegEx'])
&& !empty($this->otherOptions['urlProcessRegEx'])
) {
unset($this->otherOptions['urlProcessPattern']);
}
if (isset($this->otherOptions['urlCrawlRegEx'])
&& !empty($thi... | Builds out the URL string that gets requested once `call()` is called
@return string | entailment |
public function getUrlReportUrl($num = null)
{
$this->otherOptions['type'] = 'urls';
if (!empty($num) && is_numeric($num)) {
$this->otherOptions['num'] = $num;
}
// Setup data endpoint
$url = $this->apiUrl . '/data';
// Add token
$url .= '?token... | Sets the request type to "urls" to retrieve the URL Report
URL for understanding diagnostic data of URLs
@return $this | entailment |
public function setHttpClient(Client $client = null)
{
if ($client === null) {
$client = new Client(
HttpClientDiscovery::find(),
MessageFactoryDiscovery::find()
);
}
$this->client = $client;
return $this;
} | Sets the client to be used for querying the API endpoints
@param Client $client
@see http://php-http.readthedocs.org/en/latest/utils/#httpmethodsclient
@return $this | entailment |
public function setEntityFactory(EntityFactory $factory = null)
{
if ($factory === null) {
$factory = new Entity();
}
$this->factory = $factory;
return $this;
} | Sets the Entity Factory which will create the Entities from Responses
@param EntityFactory $factory
@return $this | entailment |
public function createProductAPI($url)
{
$api = new Product($url);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
} | Creates a Product API interface
@param string $url Url to analyze
@return Product | entailment |
public function createArticleAPI($url)
{
$api = new Article($url);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
} | Creates an Article API interface
@param string $url Url to analyze
@return Article | entailment |
public function createImageAPI($url)
{
$api = new Image($url);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
} | Creates an Image API interface
@param string $url Url to analyze
@return Image | entailment |
public function createAnalyzeAPI($url)
{
$api = new Analyze($url);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
} | Creates an Analyze API interface
@param string $url Url to analyze
@return Analyze | entailment |
public function createDiscussionAPI($url)
{
$api = new Discussion($url);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
... | Creates an Discussion API interface
@param string $url Url to analyze
@return Discussion | entailment |
public function createCustomAPI($url, $name)
{
$api = new Custom($url, $name);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);... | Creates a generic Custom API
Does not have predefined Entity, so by default returns Wildcards
@param string $url Url to analyze
@param string $name Name of the custom API, required to finalize URL
@return Custom | entailment |
public function crawl($name = null, Api $api = null)
{
$api = new Crawl($name, $api);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot(... | Creates a new Crawljob with the given name.
@see https://www.diffbot.com/dev/docs/crawl/
@param string $name Name of the crawljob. Needs to be unique.
@param Api $api Optional instance of an API - if omitted, must be set
later manually
@return Crawl | entailment |
public function search($q)
{
$api = new Search($q);
if (!$this->getHttpClient()) {
$this->setHttpClient();
}
if (!$this->getEntityFactory()) {
$this->setEntityFactory();
}
return $api->registerDiffbot($this);
} | Search query.
@see https://www.diffbot.com/dev/docs/search/#query
@param string $q
@return Search | entailment |
public static function open(string $zip_file): ZipInterface {
try {
$zip = new Zip($zip_file);
$zip->setArchive(self::openZipFile($zip_file));
} catch (ZipException $ze) {
throw $ze;
}
return $zip;
} | {@inheritdoc} | entailment |
public static function check(string $zip_file): bool {
try {
$zip = self::openZipFile($zip_file, ZipArchive::CHECKCONS);
$zip->close();
} catch (ZipException $ze) {
throw $ze;
}
return true;
} | {@inheritdoc} | entailment |
public static function create(string $zip_file, bool $overwrite = false): ZipInterface {
$overwrite = DataFilter::filterBoolean($overwrite);
try {
$zip = new Zip($zip_file);
if ( $overwrite ) {
$zip->setArchive(
self::openZipFile(
... | {@inheritdoc} | entailment |
public function listFiles(): array {
$list = [];
for ( $i = 0; $i < $this->getArchive()->numFiles; $i++ ) {
$name = $this->getArchive()->getNameIndex($i);
if ( $name === false ) {
throw new ZipException(StatusCodes::get($this->getArchive()->status));
... | {@inheritdoc} | entailment |
public function extract(string $destination, $files = null): bool {
if ( empty($destination) ) {
throw new ZipException("Invalid destination path: $destination");
}
if ( !file_exists($destination) ) {
$omask = umask(0);
$action = mkdir($destination, $this->... | {@inheritdoc} | entailment |
public function add(
$file_name_or_array,
bool $flatten_root_folder = false,
int $compression = self::CM_DEFAULT,
int $encryption = self::EM_NONE
): ZipInterface {
if ( empty($file_name_or_array) ) {
throw new ZipException(StatusCodes::get(ZipArchive::ER_NOENT));... | {@inheritdoc} | entailment |
public function delete($file_name_or_array): ZipInterface {
if ( empty($file_name_or_array) ) {
throw new ZipException(StatusCodes::get(ZipArchive::ER_NOENT));
}
try {
if ( is_array($file_name_or_array) ) {
foreach ( $file_name_or_array as $file_name ) ... | {@inheritdoc} | entailment |
public function close(): bool {
if ( $this->getArchive()->close() === false ) {
throw new ZipException(StatusCodes::get($this->getArchive()->status));
}
return true;
} | {@inheritdoc} | entailment |
private function getArchiveFiles(): array {
$list = [];
for ( $i = 0; $i < $this->getArchive()->numFiles; $i++ ) {
$file = $this->getArchive()->statIndex($i);
if ( $file === false ) {
continue;
}
$name = str_replace('\\', '/', $file['na... | Get a list of file contained in zip archive before extraction
@return array | entailment |
private function addItem(
string $file,
bool $flatroot = false,
int $compression = self::CM_DEFAULT,
int $encryption = self::EM_NONE,
?string $base = null
): void {
$file = is_null($this->getPath()) ? $file : $this->getPath()."/$file";
$real_file = str_replac... | Add item to zip archive
@param string $file File to add (realpath)
@param bool $flatroot (optional) If true, source directory will be not included
@param string $base (optional) Base to record in zip file
@return void
@throws ZipException | entailment |
private function deleteItem(string $file): void {
if ( $this->getArchive()->deleteName($file) === false ) {
throw new ZipException(StatusCodes::get($this->getArchive()->status));
}
} | Delete item from zip archive
@param string $file File to delete (zippath)
@return void
@throws ZipException | entailment |
private static function openZipFile(string $zip_file, int $flags = null): ZipArchive {
$zip = new ZipArchive();
$open = $zip->open($zip_file, $flags);
if ( $open !== true ) {
throw new ZipException(StatusCodes::get($open));
}
return $zip;
} | Open a zip file
@param string $zip_file ZIP file name
@param int $flags ZipArchive::open flags
@return ZipArchive
@throws ZipException | entailment |
protected function _processAssociation(Event $event, EntityInterface $entity, Association $assoc, array $settings)
{
$foreignKeys = (array)$assoc->foreignKey();
$primaryKeys = (array)$assoc->bindingKey();
$countConditions = $entity->extract($foreignKeys);
$updateConditions = array_co... | Updates sum cache for a single association
@param \Cake\Event\Event $event Event instance.
@param \Cake\Datasource\EntityInterface $entity Entity
@param Association $assoc The association object
@param array $settings The settings for sum cache for this association
@return void | entailment |
public function beforeSave(Event $event, Entity $entity)
{
$config = $this->_config;
foreach ($config['fields'] as $field => $fieldOption) {
$data = $entity->toArray();
$virtualField = $field . $config['suffix'];
if (!isset($data[$virtualField]) || !is_array($da... | Check if there is some files to upload and modify the entity before
it is saved.
At the end, for each files to upload, unset their "virtual" property.
@param Event $event The beforeSave event that was fired.
@param Entity $entity The entity that is going to be saved.
@throws \LogicException When the path configura... | entailment |
protected function _triggerErrors($file)
{
if (!empty($file['error'])) {
switch ((int)$file['error']) {
case UPLOAD_ERR_INI_SIZE:
$message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini : {0}', ini_get('upload_max_filesize'));
... | Trigger upload errors.
@param array $file The file to check.
@return string|int|void | entailment |
protected function _moveFile(Entity $entity, $source = false, $destination = false, $field = false, array $options = [])
{
if ($source === false || $destination === false || $field === false) {
return false;
}
if (isset($options['overwrite']) && is_bool($options['overwrite'])) {... | Move the temporary source file to the destination file.
@param \Cake\ORM\Entity $entity The entity that is going to be saved.
@param bool|string $source The temporary source file to copy.
@param bool|string $destination The destination file to copy.
@param bool|string $field The current ... | entailment |
protected function _deleteOldUpload(Entity $entity, $field = false, $newFile = false, array $options = [])
{
if ($field === false || $newFile === false) {
return true;
}
$fileInfo = pathinfo($entity->$field);
$newFileInfo = pathinfo($newFile);
if (isset($options... | Delete the old upload file before to save the new file.
We can not just rely on the copy file with the overwrite, because if you use
an identifier like :md5 (Who use a different name for each file), the copy
function will not delete the old file.
@param \Cake\ORM\Entity $entity The entity that is going to be saved.
... | entailment |
protected function _getUploadPath(Entity $entity, $path = false, $extension = false)
{
if ($extension === false || $path === false) {
return false;
}
$path = trim($path, DS);
$identifiers = [
':id' => $entity->id,
':md5' => md5(rand() . uniqid() ... | Get the path formatted without its identifiers to upload the file.
Identifiers :
:id : Id of the Entity.
:md5 : A random and unique identifier with 32 characters.
:y : Based on the current year.
:m : Based on the current month.
i.e : upload/:id/:md5 -> upload/2/5e3e0d0f163196cb9526d97be1b2ce26.jpg
@param \Cake\... | entailment |
public function beforeFind($event, $query, $options, $primary)
{
if ($this->config('contain')) {
if ($this->config('created_by')) {
$query->contain(['CreatedBy' => ['fields' => $this->config('fields')]]);
}
if ($this->config('modified_by')) {
... | BeforeFind callback
Used to add CreatedBy and ModifiedBy to the contain of the query.
@param \Cake\Event\Event $event Event.
@param \Cake\ORM\Query $query The Query object.
@param array $options Options.
@param bool $primary Root Query or not.
@return void | entailment |
public function beforeSave($event, $entity, $options)
{
$auth = Configure::read('GlobalAuth');
$id = $auth['id'];
if ($entity->isNew()) {
if ($this->config('created_by')) {
$entity->set($this->config('created_by'), $id);
}
}
if ($this... | BeforeSave callback
Used to add the user to the `created_by` and `modified_by` fields.
@param \Cake\Event\Event $event Event.
@param \Cake\ORM\Entity $entity The Entity to save on.
@param array $options Options.
@return void | entailment |
public function getMessage($withMetric = true)
{
if (!$withMetric) {
$result = sprintf('%s:%s', $this->getKey(), $this->getValue());
} else {
$result = sprintf('%s:%s|%s', $this->getKey(), $this->getValue(), $this->getMetric());
}
$sampleRate = $this->getSamp... | @param bool $withMetric
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.