_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q10000
AlgoliaManager.clearIndices
train
public function clearIndices($className) { $this->checkImplementsSearchableInterface($className); /** @var SearchableInterface $activeRecord */ $activeRecord = $this->activeRecordFactory->make($className); $indices = $indices = $this->initIndices($activeRecord); return $this->processIndices($indices, function (Index $index) { return $index->clearIndex(); }); }
php
{ "resource": "" }
q10001
AlgoliaManager.initIndices
train
private function initIndices(SearchableInterface $searchableModel) { $indexNames = $searchableModel->getIndices(); return \array_map(function ($indexName) { if ($this->env !== null) { $indexName = $this->env . '_' . $indexName; } return $this->initIndex($indexName); }, $indexNames); }
php
{ "resource": "" }
q10002
AlgoliaManager.getAlgoliaRecordsFromSearchableModelArray
train
private function getAlgoliaRecordsFromSearchableModelArray(array $searchableModels) { if (empty($searchableModels)) { throw new \InvalidArgumentException('The given array should not be empty'); } // Use the first element of the array to define what kind of models we are indexing. $arrayType = \get_class($searchableModels[0]); $this->checkImplementsSearchableInterface($arrayType); return \array_map(function (SearchableInterface $searchableModel) use ($arrayType) { if (! $searchableModel instanceof $arrayType) { throw new \InvalidArgumentException('The given array should not contain multiple different classes'); } $algoliaRecord = $searchableModel->getAlgoliaRecord(); $algoliaRecord['objectID'] = $searchableModel->getObjectID(); return $algoliaRecord; }, $searchableModels); }
php
{ "resource": "" }
q10003
AlgoliaManager.reindexAtomically
train
private function reindexAtomically(Index $index, array $algoliaRecords) { $temporaryIndexName = 'tmp_' . $index->indexName; $temporaryIndex = $this->initIndex($temporaryIndexName); $temporaryIndex->addObjects($algoliaRecords); $settings = $index->getSettings(); // Temporary index overrides all the settings on the main one. // So we need to set the original settings on the temporary one before atomically moving the index. $temporaryIndex->setSettings($settings); return $this->moveIndex($temporaryIndexName, $index->indexName); }
php
{ "resource": "" }
q10004
AlgoliaManager.processIndices
train
private function processIndices($indices, callable $callback) { $response = []; foreach ($indices as $index) { $response[$index->indexName] = \call_user_func($callback, $index); } return $response; }
php
{ "resource": "" }
q10005
ProcessBuilder.withDir
train
public function withDir(string $dir): self { $builder = clone $this; $builder->dir = $dir; return $builder; }
php
{ "resource": "" }
q10006
ProcessBuilder.withEnv
train
public function withEnv(string $name, string $value): self { $builder = clone $this; $builder->env[$name] = $value; return $builder; }
php
{ "resource": "" }
q10007
ProcessBuilder.start
train
public function start(Context $context, array $args = []): Promise { $factory = $context->lookup(ProcessFactory::class); if ($factory === null) { throw new \RuntimeException('Cannot launch an async process without a process factory'); } $options = []; foreach ($this->options as $k => $v) { if (\strlen($k) === 1) { $name = '-' . $k; } else { $name = '--' . $k; } if ($v === null) { $options[] = $name; } else { foreach ($v as $val) { $options[] = $name; $options[] = $val; } } } return $context->task($factory->createProcess($context, $this->command, \array_merge($options, $args), $this->dir, $this->env)); }
php
{ "resource": "" }
q10008
ProcessBuilder.run
train
public function run(Context $context, array $args, ?callable $stdin = null, ?callable $stdout = null, ?callable $stderr = null): Promise { static $discard; static $closer; if ($discard === null) { $discard = static function (Context $context, ReadableStream $stream) { yield $stream->discard($context); }; } if ($closer === null) { $closer = static function (Context $context, ?callable $callback, $pipe) { $result = null; try { if ($callback) { $result = yield from Coroutine::generate($callback, $context, $pipe); } } finally { $pipe->close(); } return $result; }; } return $context->task(function (Context $context) use ($args, $stdin, $stdout, $stderr, $closer, $discard) { $process = yield $this->start($context, $args); try { $context = $context->cancellable($cancel = $context->cancellationHandler()); yield $context->all([ $closer($context, $stdin, $process->getStdin()), $closer($context, $stdout ?? $discard, $process->getStdout()), $closer($context, $stderr ?? $discard, $process->getStderr()) ], $cancel); $code = yield $process->exitCode($context); } finally { $process->close(); } return $code; }); }
php
{ "resource": "" }
q10009
Character.charCount
train
public static function charCount($char): int { self::handleIncomingChar($char); $stringChar = (string) $char; return mb_ord($stringChar, mb_detect_encoding($stringChar)) > 0xFFFF ? 2 : 1; }
php
{ "resource": "" }
q10010
Character.codePointBefore
train
public static function codePointBefore($chars, int $index, int $start = null): int { if ($start !== null && ($start < 0 || $index <= $start)) { throw new InvalidArgumentException('Start cannot be negative and index must be greater than start!'); } return static::codePointAt($chars, $index - 1); }
php
{ "resource": "" }
q10011
Character.compare
train
public static function compare($charA, $charB): int { self::handleIncomingChar($charA, $charB); return (string) $charA <=> (string) $charB; }
php
{ "resource": "" }
q10012
Character.handleIncomingChar
train
private static function handleIncomingChar(...$chars): void { foreach ($chars as $char) { Assert::typeOf(['string', __CLASS__], $char); if (mb_strlen((string) $char) !== 1) { throw new InvalidArgumentException('Only one character can be represented!'); } } }
php
{ "resource": "" }
q10013
Character.isLowerCase
train
public static function isLowerCase($char): bool { self::handleIncomingChar($char); return static::compare($char, static::toLowerCase($char)) === 0; }
php
{ "resource": "" }
q10014
Character.isUpperCase
train
public static function isUpperCase($char): bool { self::handleIncomingChar($char); return static::compare($char, static::toUpperCase($char)) === 0; }
php
{ "resource": "" }
q10015
Character.valueOf
train
public static function valueOf($char): self { if (\is_string($char) || $char instanceof self) { return new static((string) $char); } throw new InvalidArgumentException('Unsupported character type!'); }
php
{ "resource": "" }
q10016
Size.createBySizeName
train
public static function createBySizeName(string $name): self { $registeredImageSizes = get_intermediate_image_sizes(); $additionalImageSizes = wp_get_additional_image_sizes(); Assert::oneOf( $name, $registeredImageSizes, "{$name} size not found on WordPress registered sizes." ); if ($additionalImageSizes[$name] ?? false) { return new self( (int)$additionalImageSizes[$name]['width'], (int)$additionalImageSizes[$name]['height'] ); } return new self( (int)get_option("{$name}_size_w", null), (int)get_option("{$name}_size_h", null) ); }
php
{ "resource": "" }
q10017
ProfileController.update
train
public function update(UpdateUserRequest $request) { $this->dispatch(new UpdateUser($this->auth->user()->id, $request->get('name'), $request->get('email'))); return redirect()->route('authentication::profile.show'); }
php
{ "resource": "" }
q10018
AnnotationsReader.target
train
public function target($target, $keyName = null) { $this->target = $target; $this->keyName = $keyName; return $this; }
php
{ "resource": "" }
q10019
AnnotationsReader.read
train
public function read($argument) { // Get Reflection. $reflection = $this->getReflectionFrom($argument); // We have some specific annotations to be read. if ($this->wantsSpecificAnnotation()) { return $this->readSpecificAnnotationFor($reflection); } // We require to read all annotations. return $this->readAllAnnotationsFor($reflection); }
php
{ "resource": "" }
q10020
AnnotationsReader.addFilesToRegistry
train
public function addFilesToRegistry($filePaths) { collect((array) $filePaths)->each(function ($filePath) { if (file_exists($filePath)) { AnnotationRegistry::registerFile($filePath); } }); return $this; }
php
{ "resource": "" }
q10021
AnnotationsReader.addNamespacesToRegistry
train
public function addNamespacesToRegistry($namespaces) { collect((array) $namespaces)->each(function ($namespace) { // Get path from namespace. $path = $this->getPathFromNamespace($namespace); if (file_exists($path)) { // Register each annotations file found in the namespace. foreach (Finder::create()->files()->name('*.php')->in($path) as $file) { $this->addFilesToRegistry($file->getRealPath()); } } }); return $this; }
php
{ "resource": "" }
q10022
AnnotationsReader.readAllAnnotationsFor
train
protected function readAllAnnotationsFor($reflection) { // Construct Method to be used for reading. $methodName = $this->constructReadMethod(); // Read, Collect and return annotations. return collect($this->reader->{$methodName}($reflection)); }
php
{ "resource": "" }
q10023
AnnotationsReader.readSpecificAnnotationFor
train
protected function readSpecificAnnotationFor($reflection) { // Construct Method to be used for reading. $methodName = $this->constructReadMethod(); // Read, Collect and return annotations. return collect($this->reader->{$methodName}($reflection, $this->annotationName)); }
php
{ "resource": "" }
q10024
AnnotationsReader.getReflectionFrom
train
protected function getReflectionFrom($argument) { // Method name to use. $reflectionMethodName = Str::camel('getreflection'.$this->target.'from'); // Return Reflection return $this->{$reflectionMethodName}($argument); }
php
{ "resource": "" }
q10025
AnnotationsReader.getReflectionPropertyFrom
train
protected function getReflectionPropertyFrom($argument) { // No property name is given for targetting. if (is_null($this->keyName)) { throw new InvalidArgumentException('Property name to target is required'); } // Argument is an Object. if (is_object($argument)) { $argument = get_class($argument); } // Get Reflected property of the object. return new ReflectionProperty($argument, $this->keyName); }
php
{ "resource": "" }
q10026
AnnotationsReader.getReflectionMethodFrom
train
protected function getReflectionMethodFrom($argument) { // No method name is given for targetting. if (is_null($this->keyName)) { throw new InvalidArgumentException('Method name to target is required'); } // Argument is an Object. if (is_object($argument)) { $argument = get_class($argument); } // Get Reflected method of the object. return new ReflectionMethod($argument, $this->keyName); }
php
{ "resource": "" }
q10027
AnnotationsReader.constructReadMethod
train
protected function constructReadMethod() { // Reader methods ends with this. $endsWith = 'annotations'; // We have an annotation name which means // we have to target a specific one. if ($this->wantsSpecificAnnotation()) { $endsWith = 'annotation'; } return Str::camel('get'.$this->target.$endsWith); }
php
{ "resource": "" }
q10028
SortableBehavior.restoreSorting
train
public function restoreSorting(array $scope = []): void { $records = $this->_table->find() ->select([$this->_table->getPrimaryKey(), $this->getConfig('sortField')]) ->select($this->getConfig('columnScope')) ->order($this->getConfig('defaultOrder')); if (!empty($scope)) { $records->where($scope); } $sorts = []; foreach ($records as $entity) { $individualScope = ''; foreach ($this->getConfig('columnScope') as $column) { $individualScope .= $entity->get($column); } if (!isset($sorts[$individualScope])) { $sorts[$individualScope] = 0; } $sort = ++$sorts[$individualScope]; $this->_table->updateAll([ $this->getConfig('sortField') => $sort, ], [ $this->_table->getPrimaryKey() => $entity->get($this->_table->getPrimaryKey()), ]); } }
php
{ "resource": "" }
q10029
SortableBehavior.getNextSortValue
train
public function getNextSortValue(array $scope = []): int { $query = $this->_table->query(); $scope = Hash::merge($this->getConfig('scope'), $scope); if (!empty($scope)) { $query->where($scope); } $query->select([ 'maxSort' => $query->func()->max($this->getConfig('sortField')), ]); $res = $query->enableHydration(false)->first(); if (empty($res)) { return 1; } return ($res['maxSort'] + 1); }
php
{ "resource": "" }
q10030
ConfigInspection.makeArraySerializable
train
private function makeArraySerializable(array $data) { $serializable = []; foreach ($data as $key => $value) { if (is_object($value)) { $serializable[$key] = new ObjectStub($value); continue; } $serializable[$key] = is_array($value) ? $this->makeArraySerializable($value) : $value; } return $serializable; }
php
{ "resource": "" }
q10031
SearchEndpointTrait.createElasticSearchQuery
train
private function createElasticSearchQuery(array $params, $operator = 'AND') { $filteredParams = []; foreach ($params as $name => $value) { if (empty($name) || empty($value)) { continue; } $filteredParams[] = "$name:$value"; } return implode(" $operator ", $filteredParams); }
php
{ "resource": "" }
q10032
SearchEndpointTrait.normalizeSearchChannelsResponse
train
private function normalizeSearchChannelsResponse($response) { $response = json_decode($response, true); if (!is_array($response) || !array_key_exists('result', $response) || !array_key_exists('total', $response)) { throw new Exception('Invalid response from search endpoint'); } $response['totalCount'] = $response['total']; $response['channels'] = $response['result']; unset($response['result'], $response['total']); return json_encode($response); }
php
{ "resource": "" }
q10033
UrlService.createFetch
train
public function createFetch($params, $optParams = []) { if (is_string($params)) { $params = ['url' => $params]; } $params = $this->client->fillParams(['cloudId', 'url'], $params); return $this->build('/f/'.$params['url'], $params, $optParams); }
php
{ "resource": "" }
q10034
UrlService.createFacebook
train
public function createFacebook($params, $optParams = []) { if (is_string($params)) { $params = ['facebookId' => $params]; } $params = $this->client->fillParams(['cloudId', 'facebookId'], $params); return $this->build('/r/facebook/'.$params['facebookId'], $params, $optParams); }
php
{ "resource": "" }
q10035
UrlService.createTwitter
train
public function createTwitter($params, $optParams = []) { if (is_string($params)) { $params = ['twitterId' => $params]; } $params = $this->client->fillParams(['cloudId', 'twitterId'], $params); return $this->build('/r/twitter/'.$params['twitterId'], $params, $optParams); }
php
{ "resource": "" }
q10036
UrlService.createYoutube
train
public function createYoutube($params, $optParams = []) { if (is_string($params)) { $params = ['youtubeId' => $params]; } $params = $this->client->fillParams(['cloudId', 'youtubeId'], $params); return $this->build('/r/youtube/'.$params['youtubeId'], $params, $optParams); }
php
{ "resource": "" }
q10037
UrlService.createCloudinary
train
public function createCloudinary($params, $optParams = []) { $params = $this->client->fillParams(['cloudId', 'cloudinaryCloud', 'cloudinaryImage'], $params); return $this->build('/r/cloudinary/'.urlencode($params['cloudinaryCloud'].'/'.$params['cloudinaryImage']), $params, $optParams); }
php
{ "resource": "" }
q10038
UrlService.createWikimedia
train
public function createWikimedia($params, $optParams = []) { if (is_string($params)) { $params = ['wikimediaImage' => $params]; } $params = $this->client->fillParams(['cloudId', 'wikimediaImage'], $params); return $this->build('/r/commons/'.urlencode($params['wikimediaImage']), $params, $optParams); }
php
{ "resource": "" }
q10039
UrlService.build
train
private function build($resource, $params, $optParams) { $url = ''; if (isset($optParams['option'])) { $option = (string) $optParams['option']; if (!empty($option)) { $url .= '/o-'.$option; } } if (isset($optParams['transformation'])) { $transformation = (string) $optParams['transformation']; if (!empty($transformation)) { $url .= '/' . trim($transformation, '/'); } } if (isset($optParams['version'])) { $url .= '/v/'.$optParams['version']; } $url .= $resource; if (isset($optParams['format'])) { $url .= '.'.$optParams['format']; } if (isset($optParams['seo'])) { $url .= '/seo/'.$optParams['seo']; } $security = ''; if (isset($optParams['security'])) { switch ($optParams['security']) { case 'basic': if (!$this->client->apiKey || !$this->client->imageSecret) { throw new InvalidConfigException('The apiKey and imageSecret must be specified!'); } $security = '/s-b3:'.SecurityHelper::generateImageSecretSignature($this->client->imageHostname, ltrim($url, '/'), $this->client->apiKey, $this->client->imageSecret); break; case 'token': if (!$this->client->apiAccessTokenSecret){ throw new InvalidConfigException('The apiAccessTokenSecret must be specified!'); } $security = '/s-token:'.$this->client->apiAccessToken.','.SecurityHelper::generateTokenHash($this->client->imageHostname, ltrim($url, '/'), $this->client->apiAccessToken, $this->client->apiAccessTokenSecret); break; } } return $this->client->imageHost.'/'.$params['cloudId'].$security.$url; }
php
{ "resource": "" }
q10040
Environment.find
train
function find($logicalPath, $options = array()) { $path = new FileUtils\PathInfo($logicalPath); if ($path->isAbsolute()) { $realPath = $logicalPath; } else { $realPath = $this->loadPaths->find($logicalPath); } if (!is_file($realPath)) { return; } if (null === $realPath) { return; } if (@$options["bundled"]) { $asset = new BundledAsset($this, $realPath, $logicalPath); } else { $asset = new ProcessedAsset($this, $realPath, $logicalPath); } return $asset; }
php
{ "resource": "" }
q10041
Environment.logicalPath
train
function logicalPath($absolutePath) { foreach ($this->loadPaths->paths() as $lp) { $absoluteLoadPath = realpath($lp); if (strpos($absolutePath, $absoluteLoadPath) === 0) { return ltrim(substr($absolutePath, strlen($absoluteLoadPath)), '/'); } } }
php
{ "resource": "" }
q10042
Environment.setJsCompressor
train
function setJsCompressor($compressor) { if (!isset($this->compressors[$compressor])) { throw new \InvalidArgumentException(sprintf('Undefined compressor "%s"', $compressor)); } $js = $this->contentType('.js'); if ($this->jsCompressor !== null) { $this->bundleProcessors->unregister($js, $this->compressors[$this->jsCompressor]); } $this->jsCompressor = $compressor; $this->bundleProcessors->register($js, $this->compressors[$compressor]); }
php
{ "resource": "" }
q10043
Environment.setCssCompressor
train
function setCssCompressor($compressor) { if (!isset($this->compressors[$compressor])) { throw new \InvalidArgumentException(sprintf('Undefined compressor "%s"', $compressor)); } $css = $this->contentType('.css'); if ($this->cssCompressor !== null) { $this->bundleProcessors->unregister($css, $this->compressors[$this->cssCompressor]); } $this->cssCompressor = $compressor; $this->bundleProcessors->register($css, $this->compressors[$compressor]); }
php
{ "resource": "" }
q10044
ActiveQueryChunker.chunk
train
public function chunk(ActiveQueryInterface $query, $size, callable $callback) { $pageNumber = 1; $records = $this->paginateRecords($query, $pageNumber, $size)->all(); $results = []; while (count($records) > 0) { // On each chunk, pass the records to the callback and then let the // developer take care of everything within the callback. This allows to // keep the memory low when looping through large result sets. $callableResults = $callback($records); if ($callableResults === false) { break; } // If the results of the given callable function were an array // merge them into the result array which is returned at the end of the chunking. if (\is_array($callableResults)) { $results = \array_merge($results, $callableResults); } $pageNumber++; $records = $this->paginateRecords($query, $pageNumber, $size)->all(); } return $results; }
php
{ "resource": "" }
q10045
ActiveQueryChunker.paginateRecords
train
private function paginateRecords(ActiveQueryInterface $query, $pageNumber, $count) { $offset = ($pageNumber - 1) * $count; $limit = $count; return $query->offset($offset)->limit($limit); }
php
{ "resource": "" }
q10046
PasswordResetController.store
train
public function store(SendPasswordResetLinkRequest $request) { $this->dispatch(new SendPasswordResetLink($request->get('email'))); return redirect()->route('authentication::password-reset.create')->withErrors([ 'authentication::password-reset.created' => trans('authentication::password-reset.created'), ]); }
php
{ "resource": "" }
q10047
PasswordResetController.edit
train
public function edit($token, PasswordResetRepository $resets) { if ($resets->exists($token)) { return view('authentication::password-reset.edit')->with('token', $token); } else { return redirect()->route('authentication::password-reset.create')->withErrors([ 'authentication::password-reset.expired' => trans('authentication::password-reset.expired'), ]); } }
php
{ "resource": "" }
q10048
PasswordResetController.update
train
public function update(ResetPasswordRequest $request) { try { $this->dispatch(new ResetPassword($request->get('token'), $request->get('email'), $request->get('password'))); return redirect()->route('authentication::session.create')->withErrors([ 'authentication::password-reset.updated' => trans('authentication::password-reset.updated'), ]); } catch (TokenIsExpired $e) { return redirect()->route('authentication::password-reset.create')->withErrors([ 'authentication::password-reset.expired' => trans('authentication::password-reset.expired'), ]); } }
php
{ "resource": "" }
q10049
ApplicationService.getVersion
train
private function getVersion(): ?Version { // Oops, unknown/empty path of a file who contains version if (empty($this->versionFilePath)) { throw EmptyVersionFilePathException::create(); } // Oops, not readable/accessible file who contains version if (!is_readable($this->versionFilePath)) { throw UnreadableVersionFileException::create($this->versionFilePath); } $contents = file_get_contents($this->versionFilePath); return Version::fromString($contents); }
php
{ "resource": "" }
q10050
ApplicationService.createDescriptor
train
private function createDescriptor(string $name, string $description): void { $version = $this->getVersion(); $this->descriptor = new Descriptor($name, $description, $version); }
php
{ "resource": "" }
q10051
RobotsFileController.indexAction
train
public function indexAction(Request $request) { $hosts = $this->getParameter('jantao_dev_sitemap.hosts'); $webDir = rtrim($this->getParameter('jantao_dev_sitemap.web_dir'), '/'); if (!empty($hosts)) { $host = $request->getHttpHost(); if (strpos($host, ':') !== false) { $host = substr($host, 0, strpos($host, ':')); } if (in_array($host, $hosts) && file_exists("$webDir/robots.$host.txt")) { return new BinaryFileResponse("$webDir/robots.$host.txt"); } } if (file_exists("$webDir/robots.txt")) { return new BinaryFileResponse("$webDir/robots.txt"); } else { throw $this->createNotFoundException('robots.txt not found'); } }
php
{ "resource": "" }
q10052
SecurityContextConfiguration.setPrefix
train
public function setPrefix($prefix) { if ($prefix != '') { $prefix = rtrim($prefix, '_').'_'; } $this->prefix = $prefix; return $this; }
php
{ "resource": "" }
q10053
SectionTwigExtension.section
train
public function section(string $section): SectionTwigExtension { $this->options[ReadOptions::SECTION] = $section; return $this; }
php
{ "resource": "" }
q10054
SectionTwigExtension.limit
train
public function limit(int $limit): SectionTwigExtension { $this->options[ReadOptions::LIMIT] = $limit; return $this; }
php
{ "resource": "" }
q10055
SectionTwigExtension.offset
train
public function offset(int $offset): SectionTwigExtension { $this->options[ReadOptions::OFFSET] = $offset; return $this; }
php
{ "resource": "" }
q10056
SectionTwigExtension.sort
train
public function sort(string $sort): SectionTwigExtension { $this->options[ReadOptions::SORT] = $sort; return $this; }
php
{ "resource": "" }
q10057
SectionTwigExtension.before
train
public function before(string $before): SectionTwigExtension { $this->options[ReadOptions::BEFORE] = new \DateTime($before); return $this; }
php
{ "resource": "" }
q10058
SectionTwigExtension.after
train
public function after(string $after): SectionTwigExtension { $this->options[ReadOptions::AFTER] = new \DateTime($after); return $this; }
php
{ "resource": "" }
q10059
SectionTwigExtension.locale
train
public function locale(string $locale): SectionTwigExtension { $this->options[ReadOptions::LOCALE] = $locale; return $this; }
php
{ "resource": "" }
q10060
SectionTwigExtension.id
train
public function id(int $id): SectionTwigExtension { $this->throwNotFound = true; $this->options[ReadOptions::ID] = $id; return $this; }
php
{ "resource": "" }
q10061
SectionTwigExtension.slug
train
public function slug(string $slug): SectionTwigExtension { $this->throwNotFound = true; $this->options[ReadOptions::SLUG] = $slug; return $this; }
php
{ "resource": "" }
q10062
SectionTwigExtension.search
train
public function search(string $searchQuery): SectionTwigExtension { $this->options[ReadOptions::SEARCH] = $searchQuery; return $this; }
php
{ "resource": "" }
q10063
FilesystemLocation.getURI
train
public function getURI(array $criteria) { $uris = $this->getURIs($criteria); return $uris->count() > 0 ? $uris->first() : false; }
php
{ "resource": "" }
q10064
FilesystemLocation.getURIs
train
public function getURIs(array $criteria): URIs { $uris = new URIs(); foreach ($this->extensions as $extension) { $finder = new Finder(); try { $finder->files() ->name($this->getNamePattern($criteria, $extension)) ->in($this->getPathPattern($this->getRelativePath($criteria))); foreach ($finder as $file) { /** @var SplFileInfo $file */ $uris->add($file->getPathname()); } } catch (Exception $exception) { // Fail silently; } } return $uris; }
php
{ "resource": "" }
q10065
FilesystemLocation.getNamePattern
train
protected function getNamePattern(array $criteria, string $extension): string { $names = []; $names[] = array_map(function ($criterion) use ($extension) { $uriExtension = URIHelper::containsExtension($criterion); if (! empty($extension)) { $extension = ltrim($extension, '.'); if ($uriExtension === $extension) { $criterion = substr($criterion,0,-strlen(".{$extension}")); } } else { $extension = URIHelper::containsExtension($criterion); if (!empty($extension)) { $criterion = substr($criterion,0,-strlen(".{$extension}")); } } $criterion = preg_quote(URIHelper::getFilename($criterion), chr(1)); return (empty($extension) || URIHelper::hasExtension($criterion, $extension)) ? "{$criterion}(?:\..*?)$" : "{$criterion}\.{$extension}$"; }, $criteria)[0]; return chr(1) . implode('|', array_unique($names)) . chr(1); }
php
{ "resource": "" }
q10066
FilesystemLocation.getPathPattern
train
protected function getPathPattern(string $relativePath): string { if (empty($relativePath)) { return $this->path; } return rtrim($this->path,'/') . '/' . ltrim($relativePath, '/'); }
php
{ "resource": "" }
q10067
FilesystemLocation.getRelativePath
train
protected function getRelativePath($criteria): string { $criterion = current($criteria); $components = explode('/', $criterion); if (count($components) < 2) { return ''; } return implode('/', array_slice($components, 0, -1)); }
php
{ "resource": "" }
q10068
FilesystemLocation.validateExtensions
train
protected function validateExtensions($extensions): Extensions { if (empty($extensions)) { $extensions = new Extensions(['']); } if (! $extensions instanceof Extensions) { $extensions = new Extensions((array)$extensions); } return $extensions; }
php
{ "resource": "" }
q10069
Resize.resizeImagick
train
private function resizeImagick(Imagick $imagick, Picture $picture) { if(!$this->resizeSmaller && $this->height > $imagick->getImageHeight() && $this->width > $imagick->getImageWidth()) { return; } if($this->resizeMode === $this::MODE_CROP) { $imagick->cropThumbnailImage($this->width, $this->height); } elseif($this->resizeMode === $this::MODE_FILL) { $ratioH = $this->height / $imagick->getImageHeight(); $ratioW = $this->width / $imagick->getImageWidth(); $width = max($imagick->getImageWidth() * $ratioH, $imagick->getImageWidth() * $ratioW); $height = max($imagick->getImageHeight() * $ratioH, $imagick->getImageHeight() * $ratioW); $ratio = max($width / $imagick->getImageWidth(), $height / $imagick->getImageHeight()); $imagick->scaleImage(round($imagick->getImageWidth() * $ratio), round($imagick->getImageHeight() * $ratio), TRUE); } elseif($this->resizeMode === $this::MODE_STRETCH) { $imagick->scaleImage($this->width, $this->height, FALSE); } elseif($this->resizeMode === $this::MODE_EXACT) { $imagick->scaleImage($this->width, $this->height, TRUE); $rectangle = $picture->createImagick(); $rectangle->setFormat('png'); $rectangle->newImage($this->width, $this->height, new \ImagickPixel($this->color ?: 'transparent')); $rectangle->compositeImage($imagick, $imagick->getImageCompose(), ($rectangle->getImageWidth() - $imagick->getImageWidth()) / 2, ($rectangle->getImageHeight() - $imagick->getImageHeight()) / 2 ); $picture->setResource($rectangle); } else { $imagick->scaleImage($this->width, $this->height, TRUE); } }
php
{ "resource": "" }
q10070
PromiseResolution.resolve
train
protected function resolve($value = null): void { if (~$this->state & AbstractPromise::PENDING) { return; } if ($value instanceof Promise) { $value->when(function (?\Throwable $e, $v = null): void { if ($e === null) { $this->resolve($v); } else { $this->fail($e); } }); return; } $callbacks = $this->result; $this->state ^= AbstractPromise::PENDING | AbstractPromise::SUCCEEDED; $this->result = $value; if ($this instanceof Cancellable) { $this->context->unregisterCancellation($this); } if ($callbacks) { if (\is_array($callbacks)) { foreach ($callbacks as $callback) { try { $callback(null, $value); } catch (\Throwable $e) { $this->context->handleError($e); } } } else { try { $callbacks(null, $value); } catch (\Throwable $e) { $this->context->handleError($e); } } } }
php
{ "resource": "" }
q10071
PromiseResolution.fail
train
protected function fail(\Throwable $error): void { if (~$this->state & AbstractPromise::PENDING) { return; } $callbacks = $this->result; $this->state ^= AbstractPromise::PENDING | AbstractPromise::FAILED; $this->result = $error; if ($this instanceof Cancellable) { $this->context->unregisterCancellation($this); } if ($callbacks) { if (\is_array($callbacks)) { foreach ($callbacks as $callback) { try { $callback($error); } catch (\Throwable $e) { $this->context->handleError($e); } } } else { try { $callbacks($error); } catch (\Throwable $e) { $this->context->handleError($e); } } } }
php
{ "resource": "" }
q10072
WaitConditionLoop.popAndRunBusyCallback
train
private function popAndRunBusyCallback() { if ( $this->busyCallbacks ) { reset( $this->busyCallbacks ); $key = key( $this->busyCallbacks ); /** @var callable $workCallback */ $workCallback =& $this->busyCallbacks[$key]; try { $workCallback(); } catch ( \Exception $e ) { $workCallback = function () use ( $e ) { throw $e; }; } unset( $this->busyCallbacks[$key] ); // consume return true; } return false; }
php
{ "resource": "" }
q10073
GithubMarkdownRenderer.getRenderedHTML
train
public function getRenderedHTML($value) { //Build object to send $sendObj=new stdClass(); $sendObj->text=$value; $sendObj->mode=(self::$useGFM ? 'gmf':'markdown'); $content=json_encode($sendObj); //Build headers $headers=array("Content-type: application/json", "User-Agent: curl"); if(self::$useBasicAuth) { $encoded=base64_encode(self::$username.':'.self::$password); $headers[]="Authorization: Basic $encoded"; } //Build curl request to github's api $curl=curl_init('https://api.github.com/markdown'); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $content); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //Send request and verify response $response=curl_exec($curl); $status=curl_getinfo($curl, CURLINFO_HTTP_CODE); if($status!=200) { user_error("Error: Call to api.github.com failed with status $status, response $response, curl_error ".curl_error($curl).", curl_errno ".curl_errno($curl), E_USER_WARNING); } //Close curl connection curl_close($curl); return $response; }
php
{ "resource": "" }
q10074
GithubMarkdownRenderer.useBasicAuth
train
public function useBasicAuth($username=false, $password=false) { self::$useBasicAuth=($username!==false && $password!==false); self::$username=$username; self::$password=$password; }
php
{ "resource": "" }
q10075
PromiseTrait.doReject
train
public static function doReject($promiseOrValue = null) { if (!$promiseOrValue instanceof PromiseInterface) { return new PromiseRejected($promiseOrValue); } return self::doResolve($promiseOrValue)->then(function($value) { return new PromiseRejected($value); }); }
php
{ "resource": "" }
q10076
PromiseTrait.doCancel
train
public static function doCancel($promiseOrValue = null) { if (!$promiseOrValue instanceof PromiseInterface) { return new PromiseCancelled($promiseOrValue); } return self::doResolve($promiseOrValue) ->then( function($value) { return new PromiseCancelled($value); }, function($value) { return new PromiseCancelled($value); } ); }
php
{ "resource": "" }
q10077
PromiseTrait.race
train
public static function race($promisesOrValues) { $cancellationQueue = new CancellationQueue(); return new Promise(function($resolve, $reject, $cancel) use($promisesOrValues, $cancellationQueue) { self::doResolve($promisesOrValues) ->done(function($array) use($resolve, $reject, $cancel, $cancellationQueue) { if (!is_array($array) || !$array) { $resolve(); return; } $fulfiller = function($value) use($resolve, $cancellationQueue) { $resolve($value); $cancellationQueue(); }; $rejecter = function($reason) use($reject, $cancellationQueue) { $reject($reason); $cancellationQueue(); }; foreach ($array as $promiseOrValue) { $cancellationQueue->enqueue($promiseOrValue); self::doResolve($promiseOrValue) ->done($fulfiller, $rejecter, $cancel); } }, $reject, $cancel); }, $cancellationQueue); }
php
{ "resource": "" }
q10078
PasswordReset.generate
train
public static function generate(Authenticatable $user) { return new static([ 'email' => $user->email, 'token' => hash_hmac('sha256', Str::random(40), config('app.key')), 'created_at' => Carbon::now(), ]); }
php
{ "resource": "" }
q10079
EngineResolver.register
train
public function register(callable $factory, $priority = 0): self { array_unshift($this->engines, [$factory, $priority]); $this->cache = null; $sorted = false; while (!$sorted) { $sorted = true; for ($i = 0, $l = count($this->engines) - 1; $i < $l; $i++) { if ($this->engines[$i][1] < $this->engines[$i + 1][1]) { $tmp = $this->engines[$i]; $this->engines[$i] = $this->engines[$i + 1]; $this->engines[$i + 1] = $tmp; $sorted = false; } } } return $this; }
php
{ "resource": "" }
q10080
EngineResolver.resolve
train
public function resolve(string $path): IEngine { if ($this->cache === null) { $this->cache = []; foreach ($this->engines as $engine) { $this->cache[] = $engine[0]($this->renderer); } } foreach ($this->cache as $engine) { if ($engine->canHandle($path)) { return $engine; } } return $this->renderer->getDefaultEngine(); }
php
{ "resource": "" }
q10081
FeatureTypeQuery.filterByHasFeatureAvValue
train
public function filterByHasFeatureAvValue($hasFeatureAvValue = null, $comparison = null) { if (is_array($hasFeatureAvValue)) { $useMinMax = false; if (isset($hasFeatureAvValue['min'])) { $this->addUsingAlias(FeatureTypeTableMap::HAS_FEATURE_AV_VALUE, $hasFeatureAvValue['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($hasFeatureAvValue['max'])) { $this->addUsingAlias(FeatureTypeTableMap::HAS_FEATURE_AV_VALUE, $hasFeatureAvValue['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::HAS_FEATURE_AV_VALUE, $hasFeatureAvValue, $comparison); }
php
{ "resource": "" }
q10082
FeatureTypeQuery.filterByIsMultilingualFeatureAvValue
train
public function filterByIsMultilingualFeatureAvValue($isMultilingualFeatureAvValue = null, $comparison = null) { if (is_array($isMultilingualFeatureAvValue)) { $useMinMax = false; if (isset($isMultilingualFeatureAvValue['min'])) { $this->addUsingAlias(FeatureTypeTableMap::IS_MULTILINGUAL_FEATURE_AV_VALUE, $isMultilingualFeatureAvValue['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($isMultilingualFeatureAvValue['max'])) { $this->addUsingAlias(FeatureTypeTableMap::IS_MULTILINGUAL_FEATURE_AV_VALUE, $isMultilingualFeatureAvValue['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::IS_MULTILINGUAL_FEATURE_AV_VALUE, $isMultilingualFeatureAvValue, $comparison); }
php
{ "resource": "" }
q10083
FeatureTypeQuery.filterByCssClass
train
public function filterByCssClass($cssClass = null, $comparison = null) { if (null === $comparison) { if (is_array($cssClass)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $cssClass)) { $cssClass = str_replace('*', '%', $cssClass); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(FeatureTypeTableMap::CSS_CLASS, $cssClass, $comparison); }
php
{ "resource": "" }
q10084
FeatureTypeQuery.filterByInputType
train
public function filterByInputType($inputType = null, $comparison = null) { if (null === $comparison) { if (is_array($inputType)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $inputType)) { $inputType = str_replace('*', '%', $inputType); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(FeatureTypeTableMap::INPUT_TYPE, $inputType, $comparison); }
php
{ "resource": "" }
q10085
FeatureTypeQuery.filterByMax
train
public function filterByMax($max = null, $comparison = null) { if (is_array($max)) { $useMinMax = false; if (isset($max['min'])) { $this->addUsingAlias(FeatureTypeTableMap::MAX, $max['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($max['max'])) { $this->addUsingAlias(FeatureTypeTableMap::MAX, $max['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::MAX, $max, $comparison); }
php
{ "resource": "" }
q10086
FeatureTypeQuery.filterByMin
train
public function filterByMin($min = null, $comparison = null) { if (is_array($min)) { $useMinMax = false; if (isset($min['min'])) { $this->addUsingAlias(FeatureTypeTableMap::MIN, $min['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($min['max'])) { $this->addUsingAlias(FeatureTypeTableMap::MIN, $min['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::MIN, $min, $comparison); }
php
{ "resource": "" }
q10087
FeatureTypeQuery.filterByStep
train
public function filterByStep($step = null, $comparison = null) { if (is_array($step)) { $useMinMax = false; if (isset($step['min'])) { $this->addUsingAlias(FeatureTypeTableMap::STEP, $step['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($step['max'])) { $this->addUsingAlias(FeatureTypeTableMap::STEP, $step['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::STEP, $step, $comparison); }
php
{ "resource": "" }
q10088
FeatureTypeQuery.filterByImageMaxWidth
train
public function filterByImageMaxWidth($imageMaxWidth = null, $comparison = null) { if (is_array($imageMaxWidth)) { $useMinMax = false; if (isset($imageMaxWidth['min'])) { $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_WIDTH, $imageMaxWidth['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($imageMaxWidth['max'])) { $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_WIDTH, $imageMaxWidth['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_WIDTH, $imageMaxWidth, $comparison); }
php
{ "resource": "" }
q10089
FeatureTypeQuery.filterByImageMaxHeight
train
public function filterByImageMaxHeight($imageMaxHeight = null, $comparison = null) { if (is_array($imageMaxHeight)) { $useMinMax = false; if (isset($imageMaxHeight['min'])) { $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_HEIGHT, $imageMaxHeight['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($imageMaxHeight['max'])) { $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_HEIGHT, $imageMaxHeight['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(FeatureTypeTableMap::IMAGE_MAX_HEIGHT, $imageMaxHeight, $comparison); }
php
{ "resource": "" }
q10090
FeatureTypeQuery.filterByFeatureTypeI18n
train
public function filterByFeatureTypeI18n($featureTypeI18n, $comparison = null) { if ($featureTypeI18n instanceof \FeatureType\Model\FeatureTypeI18n) { return $this ->addUsingAlias(FeatureTypeTableMap::ID, $featureTypeI18n->getId(), $comparison); } elseif ($featureTypeI18n instanceof ObjectCollection) { return $this ->useFeatureTypeI18nQuery() ->filterByPrimaryKeys($featureTypeI18n->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByFeatureTypeI18n() only accepts arguments of type \FeatureType\Model\FeatureTypeI18n or Collection'); } }
php
{ "resource": "" }
q10091
FeatureTypeQuery.useFeatureTypeI18nQuery
train
public function useFeatureTypeI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') { return $this ->joinFeatureTypeI18n($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'FeatureTypeI18n', '\FeatureType\Model\FeatureTypeI18nQuery'); }
php
{ "resource": "" }
q10092
Arrays.fill
train
public function fill($newValue): self { foreach ($this->values as $index => $value) { $this->values[$index] = $newValue; } return $this; }
php
{ "resource": "" }
q10093
Picture.loadImageResource
train
protected function loadImageResource() { if(empty($this->resource)) { if((is_null($this->worker) || $this->worker === $this::WORKER_IMAGICK) && $this->imagickAvailable()) { $this->resource = $this->createImagick($this->image); } elseif((is_null($this->worker) || $this->worker === $this::WORKER_GD) && $this->gdAvailable()) { $this->resource = $this->getGdResource($this->image); } else { throw new Exception('Required extensions missing, extension GD or Imagick is required'); } } }
php
{ "resource": "" }
q10094
Picture.convertResource
train
protected function convertResource($convertTo) { $this->tmpImage[] = $tmpImage = tempnam(sys_get_temp_dir(), 'picture'); if($this->isGd()) { imagepng($this->resource, $tmpImage, 0); } else { $this->resource->writeImage($tmpImage); } if($convertTo === $this::WORKER_GD) { return $this->getGdResource($tmpImage); } else { return $this->createImagick($tmpImage); } }
php
{ "resource": "" }
q10095
Picture.setResource
train
public function setResource($resource) { if($this->getWorker($resource) === $this->getWorker($this->resource)) { $this->resource = $resource; } $this->tmpImage[] = $tmpImage = tempnam(sys_get_temp_dir(), 'picture'); if($this->getWorker($resource) === $this::WORKER_GD) { imagepng($resource, $tmpImage, 0); } else { $resource->writeImage($tmpImage); } if($this->isGd()) { $this->resource = $this->getGdResource($tmpImage); } else { $this->resource = $this->createImagick($tmpImage); } }
php
{ "resource": "" }
q10096
Picture.normalizeGdResource
train
protected function normalizeGdResource($resource) { if(imageistruecolor($resource)) { imagesavealpha($resource, TRUE); return $resource; } $width = imagesx($resource); $height = imagesy($resource); $trueColor = imagecreatetruecolor($width, $height); imagealphablending($trueColor, FALSE); $transparent = imagecolorallocatealpha($trueColor, 255, 255, 255, 127); imagefilledrectangle($trueColor, 0, 0, $width, $height, $transparent); imagealphablending($trueColor, TRUE); imagecopy($trueColor, $resource, 0, 0, 0, 0, $width, $height); imagedestroy($resource); imagesavealpha($trueColor, TRUE); return $trueColor; }
php
{ "resource": "" }
q10097
Picture.getGdResource
train
protected function getGdResource($imageFile) { $imageInfo = getimagesize($imageFile); switch($imageInfo['mime']) { case 'image/jpg': case 'image/jpeg': return $this->normalizeGdResource(imagecreatefromjpeg($imageFile)); case 'image/gif': return $this->normalizeGdResource(imagecreatefromgif($imageFile)); case 'image/png': return $this->normalizeGdResource(imagecreatefrompng($imageFile)); } throw new Exception('GD resource not supported image extension'); }
php
{ "resource": "" }
q10098
Picture.getImageQuery
train
public function getImageQuery() { $command = ''; foreach($this->effect as $effect) { if($effect instanceof PictureEffect) { $command .= $effect->__toString() . '&'; } } $command .= 'Quality;' . $this->quality . '&'; if($this->progressive) { $command .= 'Progressive&'; } return substr($command, 0, strlen($command) - 1); }
php
{ "resource": "" }
q10099
Picture.effect
train
public function effect($effect) { $args = array_slice(func_get_args(), 1); if($effect instanceof PictureEffect) { $this->effect[] = $effect; } else { $effectClass = "Palette\\Effect\\" . $effect; if(class_exists($effectClass)) { $reflection = new ReflectionClass($effectClass); $this->effect[] = $reflection->newInstanceArgs($args); } else { throw new Exception('Unknown Palette effect instance'); } } }
php
{ "resource": "" }