_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q13200
Stream.dir_readdir
train
public function dir_readdir() { $object = current($this->blobs); if ($object !== false) { next($this->blobs); return $object->getName(); } return false; }
php
{ "resource": "" }
q13201
CpAssetBundle.init
train
final public function init() { $this->sourcePath = $this->getSourcePath(); $this->depends = [CpAsset::class]; $this->js = $this->getScripts(); $this->css = $this->getStylesheets(); parent::init(); }
php
{ "resource": "" }
q13202
ServiceConfiguration.addRole
train
public function addRole($name) { $namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI); $roleNode = $this->dom->createElementNS($namespaceUri, 'Role'); $roleNode->setAttribute('name', $name); $instancesNode = $this->dom->createElementNS($namespaceUri, 'Instances'); $instancesNode->setAttribute('count', '2'); $configurationSettings = $this->dom->createElementNS($namespaceUri, 'ConfigurationSettings'); $roleNode->appendChild($instancesNode); $roleNode->appendChild($configurationSettings); $this->dom->documentElement->appendChild($roleNode); $this->save(); }
php
{ "resource": "" }
q13203
ServiceConfiguration.copyForDeployment
train
public function copyForDeployment($targetPath, $development = true) { $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->loadXML($this->dom->saveXML()); $xpath = new \DOMXpath($dom); $xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI)); $settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]'); foreach ($settings as $setting) { if ($development) { $setting->setAttribute('value', 'UseDevelopmentStorage=true'); } else if (strlen($setting->getAttribute('value')) === 0) { if ($this->storage) { $setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey'])); } else { throw new \RuntimeException(<<<EXC ServiceConfiguration.csdef: Missing value for 'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'. You have to modify the app/azure/ServiceConfiguration.csdef to contain a value for the diagnostics connection string or better configure 'windows_azure_distribution.diagnostics.accountName' and 'windows_azure_distribution.diagnostics.accountKey' in your app/config/config.yml If you don't want to enable diagnostics you should delete the connection string elements from ServiceConfiguration.csdef file. EXC ); } } } $dom->save($targetPath . '/ServiceConfiguration.cscfg'); }
php
{ "resource": "" }
q13204
ServiceConfiguration.setConfigurationSetting
train
public function setConfigurationSetting($roleName, $name, $value) { $namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI); $xpath = new \DOMXpath($this->dom); $xpath->registerNamespace('sc', $namespaceUri); $xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:ConfigurationSettings//sc:Setting[@name="' . $name . '"]'; $settingList = $xpath->evaluate($xpathExpression); if ($settingList->length == 1) { $settingNode = $settingList->item(0); } else { $settingNode = $this->dom->createElementNS($namespaceUri, 'Setting'); $settingNode->setAttribute('name', $name); $configSettingList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]/sc:ConfigurationSettings'); if ($configSettingList->length == 0) { throw new \RuntimeException("Cannot find <ConfigurationSettings /> in Role '" . $roleName . "'."); } $configSettings = $configSettingList->item(0); $configSettings->appendChild($settingNode); } $settingNode->setAttribute('value', $value); $this->save(); }
php
{ "resource": "" }
q13205
ServiceConfiguration.addCertificate
train
public function addCertificate($roleName, RemoteDesktopCertificate $certificate) { $namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI); $xpath = new \DOMXpath($this->dom); $xpath->registerNamespace('sc', $namespaceUri); $xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:Certificates'; $certificateList = $xpath->evaluate($xpathExpression); if ($certificateList->length == 1) { $certificatesNode = $certificateList->item(0); $certificateNodeToDelete = null; foreach ($certificatesNode->childNodes as $certificateNode) { if (!$certificateNode instanceof \DOMElement) { continue; } if ('Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption' == $certificateNode->getAttribute('name')) { $certificateNodeToDelete = $certificateNode; } } if (!is_null($certificateNodeToDelete)) { $certificatesNode->removeChild($certificateNodeToDelete); } } else { $certificatesNode = $this->dom->createElementNS($namespaceUri, 'Certificates'); $roleNodeList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]'); if ($roleNodeList->length == 0) { throw new \RuntimeException("No Role found with name '" . $roleName . "'."); } $roleNode = $roleNodeList->item(0); $roleNode->appendChild($certificatesNode); } $certificateNode = $this->dom->createElementNS($namespaceUri, 'Certificate'); $certificateNode->setAttribute('name', 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption'); $certificateNode->setAttribute('thumbprint', $certificate->getThumbprint()); $certificateNode->setAttribute('thumbprintAlgorithm', 'sha1'); $certificatesNode->appendChild($certificateNode); $this->save(); }
php
{ "resource": "" }
q13206
CApacheHTTPManagerApp.prepareStandaloneMode
train
private function prepareStandaloneMode() { $param_path = nbCLICheckOption('p', 'path', ':', false); if ($param_path && is_dir($param_path)) { $this->mode = CNabuEngine::ENGINE_MODE_STANDALONE; $this->host_path = $param_path; } else { echo "Invalid host path provided for Standalone Engine Mode.\n"; echo "Please revise your params and try again.\n"; } }
php
{ "resource": "" }
q13207
CApacheHTTPManagerApp.prepareHostedMode
train
private function prepareHostedMode() { $param_server = nbCLICheckOption('s', 'server', ':', false); if (strlen($param_server) === 0) { $param_server = self::DEFAULT_HOSTED_KEY; $this->mode = CNabuEngine::ENGINE_MODE_HOSTED; $this->server_key = $param_server; } else { echo "Invalid server key provided for Hosted Engine Mode.\n"; echo "Please revise your options and try again.\n"; } }
php
{ "resource": "" }
q13208
CApacheHTTPManagerApp.prepareClusteredMode
train
private function prepareClusteredMode() { $param_server = nbCLICheckOption('s', 'server', ':', false); if (strlen($param_server) === 0) { echo "Missed --server or -s option.\n"; echo "Please revise your options and try again.\n"; } else { $this->mode = CNabuEngine::ENGINE_MODE_CLUSTERED; $this->server_key = $param_server; } }
php
{ "resource": "" }
q13209
CApacheHTTPManagerApp.runStandalone
train
private function runStandalone() { $nb_server = new CNabuBuiltInServer(); $nb_server->setVirtualHostsPath($this->host_path); $nb_site = new CNabuBuiltInSite(); $nb_site->setBasePath(''); $nb_site->setUseFramework('T'); $apache_server = new CApacheHTTPServer($nb_server, $nb_site); if ($apache_server->locateApacheServer()) { $this->displayServerConfig($apache_server); if ($this->checkHostFolders($this->host_path)) { $apache_server->createStandaloneConfiguration(); } } }
php
{ "resource": "" }
q13210
CApacheHTTPManagerApp.runHosted
train
private function runHosted() { $nb_server = CNabuServer::findByKey($this->server_key); $apache_server = new CApacheHTTPServer($nb_server); if ($apache_server->locateApacheServer()) { $this->displayServerConfig($apache_server); $apache_server->createHostedConfiguration(); } }
php
{ "resource": "" }
q13211
CApacheHTTPManagerApp.runClustered
train
private function runClustered() { $nb_server = CNabuServer::findByKey($this->server_key); if (!is_object($nb_server)) { throw new ENabuCoreException(ENabuCoreException::ERROR_SERVER_NOT_FOUND, array($this->server_key, '*', '*')); } $apache_server = new CApacheHTTPServer($nb_server); if ($apache_server->locateApacheServer()) { $this->displayServerConfig($apache_server); $apache_server->createClusteredConfiguration(); } }
php
{ "resource": "" }
q13212
CApacheHTTPManagerApp.checkHostFolders
train
private function checkHostFolders(string $path) : bool { echo "Checking folders of host...\n"; $retval = $this->checkFolder($path, 'private') || $this->checkFolder($path, 'httpdocs') || $this->checkFolder($path, 'httpsdocs') || $this->checkFolder($path, 'phputils') || $this->checkFolder($path, 'templates'); echo "OK\n"; return $retval; }
php
{ "resource": "" }
q13213
CApacheHTTPManagerApp.checkFolder
train
private function checkFolder(string $path, string $folder, bool $create = false) : bool { $retval = false; $target = $path . (is_string($folder) && strlen($folder) > 0 ? DIRECTORY_SEPARATOR . $folder : ''); echo " ... checking folder $target ..."; if (is_dir($target)) { echo "EXISTS\n"; $retval = true; } elseif ($create) { if ($retval = mkdir($target)) { echo "CREATED\n"; } else { echo "ERROR\n"; } } else { echo "NOT PRESENT\n"; } return $retval; }
php
{ "resource": "" }
q13214
DockerFrontendServiceTrait.alterService
train
protected function alterService(DockerService $service) { if ($this->internal) { $links = []; $name = $this->getName(); $host = ProjectX::getProjectConfig() ->getHost(); if (isset($host['name'])) { $links[] = "traefik.{$name}.frontend.rule=Host:{$host['name']}"; } $service->setNetworks([ 'internal', DockerEngineType::TRAEFIK_NETWORK ])->setLabels(array_merge([ 'traefik.enable=true', "traefik.{$name}.frontend.backend={$name}", "traefik.{$name}.port={$this->ports()[0]}", 'traefik.docker.network=' . DockerEngineType::TRAEFIK_NETWORK, ], $links)); } else { $service->setPorts($this->getPorts()); } return $service; }
php
{ "resource": "" }
q13215
CheckAuthor.createSourceExtractors
train
protected function createSourceExtractors( InputInterface $input, OutputInterface $output, $config, CacheInterface $cachePool ) { // Remark: a plugin system would be really nice here, so others could simply hook themselves into the checking. $extractors = []; foreach ([ 'bower' => AuthorExtractor\BowerAuthorExtractor::class, 'composer' => AuthorExtractor\ComposerAuthorExtractor::class, 'packages' => AuthorExtractor\NodeAuthorExtractor::class, 'php-files' => AuthorExtractor\PhpDocAuthorExtractor::class, ] as $option => $class) { if ($input->getOption($option)) { $extractors[$option] = new $class($config, $output, $cachePool); } } return $extractors; }
php
{ "resource": "" }
q13216
CheckAuthor.handleExtractors
train
private function handleExtractors($extractors, AuthorExtractor $reference, AuthorListComparator $comparator) { $failed = false; foreach ($extractors as $extractor) { $failed = !$comparator->compare($extractor, $reference) || $failed; } return $failed; }
php
{ "resource": "" }
q13217
CheckAuthor.enableDeprecatedNoProgressBar
train
private function enableDeprecatedNoProgressBar(InputInterface $input) { if (!$input->getOption('no-progress-bar')) { return; } // @codingStandardsIgnoreStart @trigger_error( 'The command option --no-progress-bar is deprecated since 1.4 and where removed in 2.0. Use --no-progress instead.', E_USER_DEPRECATED ); // @codingStandardsIgnoreEnd $input->setOption('no-progress', true); }
php
{ "resource": "" }
q13218
CheckAuthor.createGitAuthorExtractor
train
private function createGitAuthorExtractor($scope, Config $config, $error, $cache, GitRepository $git) { if ($scope === 'project') { return new GitProjectAuthorExtractor($config, $error, $cache); } else { $extractor = new GitAuthorExtractor($config, $error, $cache); $extractor->collectFilesWithCommits($git); return $extractor; } }
php
{ "resource": "" }
q13219
Discount.generateRandomString
train
private static function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $string = ''; for ($i = 0; $i < $length; $i++) { $string .= $characters[rand(0, strlen($characters) - 1)]; } return $string; }
php
{ "resource": "" }
q13220
Discount.AddLink
train
public function AddLink() { $link = Controller::join_links( Director::absoluteBaseURL(), ShoppingCart::config()->url_segment, "usediscount", $this->Code ); return $link; }
php
{ "resource": "" }
q13221
AbstractController.addFlashMessage
train
protected function addFlashMessage($type, $transKey, $transOpts = array(), $domain = 'messages') { $this->get('session') ->getFlashBag() ->add( $type, $this->get('translator')->trans($transKey, $transOpts, $domain) ); }
php
{ "resource": "" }
q13222
Extension.hasValidExtension
train
private function hasValidExtension($filename) { // Current extension $extension = mb_strtolower(pathinfo($filename, \PATHINFO_EXTENSION), 'UTF-8'); // Make sure all extensions are in lowercase foreach ($this->extensions as &$expected) { $expected = mb_strtolower($expected, 'UTF-8'); } return in_array($extension, $this->extensions); }
php
{ "resource": "" }
q13223
LoaderUtil.paginateChoices
train
public static function paginateChoices(AjaxChoiceLoaderInterface $choiceLoader, array $choices) { list($startTo, $endTo) = static::getRangeValues($choiceLoader); // group if (\is_array(current($choices))) { return static::paginateGroupChoices($choices, $startTo, $endTo); } return static::paginateSimpleChoices($choices, $startTo, $endTo); }
php
{ "resource": "" }
q13224
LoaderUtil.getRangeValues
train
protected static function getRangeValues(AjaxChoiceLoaderInterface $choiceLoader) { $startTo = ($choiceLoader->getPageNumber() - 1) * $choiceLoader->getPageSize(); $startTo = $startTo < 0 ? 0 : $startTo; $endTo = $startTo + $choiceLoader->getPageSize(); if (0 >= $choiceLoader->getPageSize()) { $endTo = $choiceLoader->getSize(); } if ($endTo > $choiceLoader->getSize()) { $endTo = $choiceLoader->getSize(); } return [$startTo, $endTo]; }
php
{ "resource": "" }
q13225
LoaderUtil.paginateSimpleChoices
train
protected static function paginateSimpleChoices(array $choices, $startTo, $endTo) { $paginatedChoices = []; $index = 0; foreach ($choices as $key => $choice) { if ($index >= $startTo && $index < $endTo) { $paginatedChoices[$key] = $choice; } ++$index; } return $paginatedChoices; }
php
{ "resource": "" }
q13226
LoaderUtil.paginateGroupChoices
train
protected static function paginateGroupChoices(array $choices, $startTo, $endTo) { $paginatedChoices = []; $index = 0; foreach ($choices as $groupName => $groupChoices) { foreach ($groupChoices as $key => $choice) { if ($index >= $startTo && $index < $endTo) { $paginatedChoices[$groupName][$key] = $choice; } ++$index; } } return $paginatedChoices; }
php
{ "resource": "" }
q13227
EncodingContext.isCircularReference
train
public function isCircularReference(object $object): bool { $objectHashId = spl_object_hash($object); if (isset($this->circularReferenceHashTable[$objectHashId])) { return true; } $this->circularReferenceHashTable[$objectHashId] = true; return false; }
php
{ "resource": "" }
q13228
ImportCommand.ensureFileExists
train
protected function ensureFileExists($path) { if (file_exists($path) === false) { // Create directory @mkdir(dirname($path), 0777, true); // Make the language file touch($path); } }
php
{ "resource": "" }
q13229
Review.getByBookId
train
public static function getByBookId(Bookboon $bookboon, string $bookId) : BookboonResponse { if (Entity::isValidUUID($bookId) === false) { throw new BadUUIDException(); } $bResponse = $bookboon->rawRequest("/books/$bookId/review"); $bResponse->setEntityStore( new EntityStore(Review::getEntitiesFromArray($bResponse->getReturnArray())) ); return $bResponse; }
php
{ "resource": "" }
q13230
Review.submit
train
public function submit(Bookboon $bookboon, string $bookId) : void { if (Entity::isValidUUID($bookId)) { $bookboon->rawRequest("/books/$bookId/review", $this->getData(), ClientInterface::HTTP_POST); } }
php
{ "resource": "" }
q13231
Resolver.initialize
train
public function initialize(stdClass $schema, Uri $uri) { $this->registerSchema($schema, $uri); $this->stack = [[$uri, $schema]]; }
php
{ "resource": "" }
q13232
Resolver.resolve
train
public function resolve(stdClass $reference) { $baseUri = $this->getCurrentUri(); $uri = new Uri($reference->{'$ref'}); if (!$uri->isAbsolute()) { $uri->resolveAgainst($baseUri); } $identifier = $uri->getPrimaryResourceIdentifier(); if (!isset($this->schemas[$identifier])) { $schema = $this->fetchSchemaAt($identifier); $this->registerSchema($schema, $uri); } else { $schema = $this->schemas[$identifier]; } $resolved = $this->resolvePointer($schema, $uri); if ($resolved === $reference) { throw new SelfReferencingPointerException(); } if (!is_object($resolved)) { throw new InvalidPointerTargetException([$uri->getRawUri()]); } return [$uri, $resolved]; }
php
{ "resource": "" }
q13233
Resolver.registerSchema
train
private function registerSchema(stdClass $schema, Uri $uri) { if (!isset($this->schemas[$uri->getPrimaryResourceIdentifier()])) { $this->schemas[$uri->getPrimaryResourceIdentifier()] = $schema; } }
php
{ "resource": "" }
q13234
Resolver.fetchSchemaAt
train
private function fetchSchemaAt($uri) { if ($hook = $this->preFetchHook) { $uri = $hook($uri); } set_error_handler(function ($severity, $error) use ($uri) { restore_error_handler(); throw new UnfetchableUriException([$uri, $error, $severity]); }); $content = file_get_contents($uri); restore_error_handler(); $schema = json_decode($content); if (json_last_error() !== JSON_ERROR_NONE) { throw new JsonDecodeException(sprintf( 'Cannot decode JSON from URI "%s" (error: %s)', $uri, Utils::lastJsonErrorMessage() )); } if (!is_object($schema)) { throw new InvalidRemoteSchemaException([$uri]); } return $schema; }
php
{ "resource": "" }
q13235
Resolver.resolvePointer
train
private function resolvePointer(stdClass $schema, Uri $pointerUri) { $segments = $pointerUri->getPointerSegments(); $pointer = $pointerUri->getRawPointer(); $currentNode = $schema; for ($i = 0, $max = count($segments); $i < $max; ++$i) { if (is_object($currentNode)) { if (property_exists($currentNode, $segments[$i])) { $currentNode = $currentNode->{$segments[$i]}; continue; } throw new UnresolvedPointerPropertyException([$segments[$i], $i, $pointer]); } if (is_array($currentNode)) { if (!preg_match('/^\d+$/', $segments[$i])) { throw new InvalidPointerIndexException([$segments[$i], $i, $pointer]); } if (!isset($currentNode[$index = (int) $segments[$i]])) { throw new UnresolvedPointerIndexException([$segments[$i], $i, $pointer]); } $currentNode = $currentNode[$index]; continue; } throw new InvalidSegmentTypeException([$i, $pointer]); } return $currentNode; }
php
{ "resource": "" }
q13236
QueryBuilder.guessCountQuery
train
public function guessCountQuery($column, $alias) { return str_replace($this->selected, $this->createFunction('COUNT', array($column), $alias), $this->getQueryString()); }
php
{ "resource": "" }
q13237
QueryBuilder.isFilterable
train
public function isFilterable($state, $target) { // Empty string if ($state === true && empty($target) && $target !== '0') { return false; } // Pure wildcards must be treated as empty values if ($state == true && ($target == '%%' || $target == '%')) { return false; } // Start checking from very common usage case if ($state == true && $target == '0') { return true; } // If empty array supplied if (is_array($target) && empty($target)) { return false; } $result = false; if ($state === false) { $result = true; } else { if (is_string($target) && $target != '0' && !empty($target)) { $result = true; } if (is_array($target)) { // If empty array is passed, that means it's time to stop right here if (empty($target)) { $result = false; } else { // Otherwise go on $count = 0; foreach ($target as $value) { if (!empty($value)) { $count++; } } // All values must not be empty if ($count == count($target)) { $result = true; } } } } return $result; }
php
{ "resource": "" }
q13238
QueryBuilder.createFunction
train
private function createFunction($func, array $arguments = array(), $alias = null) { // Prepare function arguments foreach ($arguments as $index => $argument) { if ($argument instanceof RawSqlFragmentInterface) { $item = $argument->getFragment(); } else { $item = $this->quote($argument); } // Update item collection $arguments[$index] = $item; } $fragment = sprintf(' %s(%s) ', $func, implode(', ', $arguments)); // Generate alias if provided if (!is_null($alias)) { $fragment .= sprintf(' AS %s ', $this->quote($alias)); } // Append a comma if there was a function call before if ($this->hasFunctionCall === true) { $this->append(', '); } $this->hasFunctionCall = true; return $fragment; }
php
{ "resource": "" }
q13239
QueryBuilder.needsQuoting
train
private function needsQuoting($target) { $isSqlFunction = strpos($target, '(') !== false || strpos($target, ')') !== false; $isColumn = strpos($target, '.') !== false; $hasQuotes = strpos($target, '`') !== false; // Whether already has quotes return !(is_numeric($target) || $isColumn || $isSqlFunction || $hasQuotes); }
php
{ "resource": "" }
q13240
QueryBuilder.quote
train
private function quote($target) { $wrapper = function($column) { return sprintf('`%s`', $column); }; if (is_array($target)) { foreach($target as &$column) { $column = $this->needsQuoting($column) ? $wrapper($column) : $column; } } else if (is_scalar($target)) { $target = $this->needsQuoting($target) ? $wrapper($target) : $target; } else { throw new InvalidArgumentException(sprintf( 'Unknown type for wrapping supplied "%s"', gettype($target) )); } return $target; }
php
{ "resource": "" }
q13241
QueryBuilder.insert
train
public function insert($table, array $data, $ignore = false) { if (empty($data)) { throw new LogicException('You have not provided a data to be inserted'); } $keys = array(); $values = array_values($data); foreach (array_keys($data) as $key) { $keys[] = $this->quote($key); } // Handle ignore case if ($ignore === true) { $ignore = 'IGNORE'; } else { $ignore = ''; } // Build and append query we made $this->append(sprintf('INSERT %s INTO %s (%s) VALUES (%s)', $ignore, $this->quote($table), implode(', ', $keys), implode(', ', $values))); return $this; }
php
{ "resource": "" }
q13242
QueryBuilder.update
train
public function update($table, array $data) { $conditions = array(); foreach ($data as $key => $value) { // Wrap column names into back-ticks $conditions[] = sprintf('%s = %s', $this->quote($key), $value); } $query = sprintf('UPDATE %s SET %s', $this->quote($table), implode(', ', $conditions)); $this->append($query); return $this; }
php
{ "resource": "" }
q13243
QueryBuilder.recountColumn
train
private function recountColumn($table, $column, $operator, $step = 1) { // Make sure expected value is going to be updated $step = (int) $step; $step = (string) $step; return $this->update($table, array($column => $column . sprintf(' %s ', $operator) . $step)); }
php
{ "resource": "" }
q13244
QueryBuilder.createSelectData
train
private function createSelectData($type) { // * is a special keyword, which doesn't need to be wrapped if ($type !== '*' && $type !== null && !is_array($type)) { $type = $this->quote($type); } // Special case when $type is array if (is_array($type)) { $collection = array(); foreach ($type as $column => $alias) { // Did we receive an alias? if (!is_numeric($column)) { $push = sprintf('%s AS %s', $this->quote($column), $this->quote($alias)); } else if ($alias instanceof RawSqlFragmentInterface) { // Is raw SQL fragment needs to selected? $push = $alias->getFragment(); } else { // In case received a regular column name $push = $this->quote($alias); } array_push($collection, $push); } // And finally, separate via commas $type = implode(', ', $collection); } return $type; }
php
{ "resource": "" }
q13245
QueryBuilder.limit
train
public function limit($offset, $amount = null) { if (is_null($amount)) { $this->append(' LIMIT ' . $offset); } else { $this->append(sprintf(' LIMIT %s, %s', $offset, $amount)); } return $this; }
php
{ "resource": "" }
q13246
QueryBuilder.from
train
public function from($table = null) { if ($table !== null) { $this->table = $table; $table = $this->quote($table); } $this->append(' FROM ' . $table); return $this; }
php
{ "resource": "" }
q13247
QueryBuilder.compare
train
public function compare($column, $operator, $value, $filter = false) { if (!$this->isFilterable($filter, $value)) { return $this; } if ($value instanceof RawSqlFragmentInterface) { $value = $value->getFragment(); } if ($value instanceof RawBindingInterface) { $value = $value->getTarget(); } $this->append(sprintf(' %s %s %s ', $this->quote($column), $operator, $value)); return $this; }
php
{ "resource": "" }
q13248
QueryBuilder.createConstraint
train
private function createConstraint($token, $column, $operator, $value, $filter) { if (!$this->isFilterable($filter, $value)) { return $this; } $this->append(sprintf('%s %s %s %s ', $token, $this->quote($column), $operator, $value)); return $this; }
php
{ "resource": "" }
q13249
QueryBuilder.where
train
public function where($column, $operator, $value, $filter = false) { return $this->createConstraint(' WHERE', $column, $operator, $value, $filter); }
php
{ "resource": "" }
q13250
QueryBuilder.whereEqualsOrGreaterThan
train
public function whereEqualsOrGreaterThan($column, $value, $filter = false) { return $this->where($column, '>=', $value, $filter); }
php
{ "resource": "" }
q13251
QueryBuilder.whereEqualsOrLessThan
train
public function whereEqualsOrLessThan($column, $value, $filter = false) { return $this->where($column, '<=', $value, $filter); }
php
{ "resource": "" }
q13252
QueryBuilder.join
train
public function join($type, $table, array $relations = array()) { $this->append(sprintf(' %s JOIN %s ', $type, $table)); // Append relations if provided if (!empty($relations)) { // First on $this->on(); $i = 0; // Iteration counter $count = count($relations); foreach ($relations as $column => $value) { // Increment iteration count $i++; $this->equals($column, $value); // If last iteration if ($i != $count) { $this->rawAnd(); } } } return $this; }
php
{ "resource": "" }
q13253
QueryBuilder.groupBy
train
public function groupBy($target) { $columns = null; if (is_string($target)) { $columns = $target; } elseif (is_array($target)) { $columns = implode(', ', $target); } else { throw new InvalidArgumentException(sprintf( 'groupBy() accepts only an array of columns or a plain column name. You supplied "%s"', gettype($target) )); } $this->append(sprintf(' GROUP BY %s ', $columns)); return $this; }
php
{ "resource": "" }
q13254
QueryBuilder.orderBy
train
public function orderBy($type = null) { if ($type === null) { $target = null; } elseif ($type instanceof RawSqlFragmentInterface) { $target = $type->getFragment(); } elseif (is_array($type)) { // Special case for non-associative array if (!ArrayUtils::isAssoc($type)) { // Check if at least one value represents a raw fragment foreach ($type as &$option) { // If raw, then do nothing but get it if ($option instanceof RawSqlFragmentInterface) { $option = $option->getFragment(); } else { // Not raw - OK, then just quote it $option = $this->quote($option); } } } else { // If associative array supplied then assume that values represent sort orders $result = array(); foreach ($type as $column => $sortOrder) { // Force sorting method to be in upper case $sortOrder = strtoupper($sortOrder); // Ensure that only valid sorting methods provided if (!in_array($sortOrder, array('ASC', 'DESC'))) { throw new LogicException(sprintf( 'Only ASC and DESC methods are supported. You provided "%s"', $sortOrder )); } // Only column names should be wrapped around backticks array_push($result, sprintf('%s %s', $this->quote($column), $sortOrder)); } $type = $result; } $target = implode(', ', $type); } else { $target = $this->quote($type); } $this->append(' ORDER BY '.$target); return $this; }
php
{ "resource": "" }
q13255
QueryBuilder.between
train
private function between($column, $a, $b, $prefix, $not = false, $operator = null, $filter = false) { if (!$this->isFilterable($filter, array($a, $b))) { return $this; } if ($operator !== null) { // A space before the operator is preferred $operator = sprintf(' %s', $operator); } // Handle NOT prefix if ($not === true) { $not = 'NOT'; } else { $not = ''; } $this->append($operator.sprintf(' %s %s %s BETWEEN %s AND %s ', $prefix, $this->quote($column), $not, $a, $b)); return $this; }
php
{ "resource": "" }
q13256
QueryBuilder.andWhereNotBetween
train
public function andWhereNotBetween($column, $a, $b, $filter = false) { return $this->between($column, $a, $b, null, true, 'AND', $filter); }
php
{ "resource": "" }
q13257
QueryBuilder.delete
train
public function delete(array $tables = array()) { $this->append(' DELETE '); if (!empty($tables)) { $tablesSequence = implode(', ', $tables); $this->append($tablesSequence); } return $this; }
php
{ "resource": "" }
q13258
QueryBuilder.renameTable
train
public function renameTable($old, $new) { $this->append(sprintf('RENAME TABLE %s TO %s ', $this->quote($old), $this->quote($new))); return $this; }
php
{ "resource": "" }
q13259
QueryBuilder.dropTable
train
public function dropTable($target, $ifExists = true) { $query = 'DROP TABLE '; if ($ifExists === true) { $query .= 'IF EXISTS '; } if (!is_array($target)) { $target = array($target); } $target = $this->quote($target); $query .= sprintf('%s;', implode(', ', $target)); $this->append($query); return $this; }
php
{ "resource": "" }
q13260
QueryBuilder.renameColumn
train
public function renameColumn($old, $new) { $this->append(sprintf(' RENAME COLUMN %s TO %s ', $this->quote($old), $this->quote($new))); return $this; }
php
{ "resource": "" }
q13261
QueryBuilder.alterColumn
train
public function alterColumn($column, $type) { $column = $this->quote($column); $this->append(sprintf(' CHANGE %s %s %s ', $column, $column, $type)); return $this; }
php
{ "resource": "" }
q13262
QueryBuilder.dropIndex
train
public function dropIndex($table, $name) { $query = sprintf('DROP INDEX %s ON %s ;', $this->quote($name), $this->quote($table)); $this->append($query); return $this; }
php
{ "resource": "" }
q13263
CSS_Block.get_inline_css
train
public function get_inline_css() { if ( $this->get_pre_selectors() ) { $inline_css = sprintf( '%1$s { %2$s }', implode( ',', $this->get_selectors() ), $this->get_properties() ); foreach ( $this->get_pre_selectors() as $pre_selector ) { $inline_css = sprintf( '%1$s { %2$s }', $pre_selector, $inline_css ); } return $inline_css; } return sprintf( '%1$s { %2$s }', implode( ',', $this->get_selectors() ), $this->get_properties() ); }
php
{ "resource": "" }
q13264
ChainModel.getModel
train
public function getModel($name) { if(!isset($this->models[$name])){ throw new RuntimeException(sprintf("The model document name '%s' is not added in chain model '%s'",$name,$this->id)); } $this->models[$name]->setContainer($this->container); return $this->models[$name]; }
php
{ "resource": "" }
q13265
ChainModel.getDirOutput
train
public function getDirOutput() { $ds = DIRECTORY_SEPARATOR; $id = $this->getId(); $documentsPath = $this->exporterManager->getOption("documents_path"); $env = $this->exporterManager->getOption("env"); if($this->basePath === null){ $fullPath = $documentsPath.$ds.$env.$ds.$id; }else{ $fullPath = $this->basePath; } if($this->subPath !== null){ $fullPath .= $ds.$this->subPath; } if(!$this->exporterManager->getFs()->exists($fullPath)){ $this->exporterManager->getFs()->mkdir($fullPath); } return $fullPath; }
php
{ "resource": "" }
q13266
ChainModel.getFiles
train
public function getFiles() { $dir = $this->getDirOutput(); $finder = new \Symfony\Component\Finder\Finder(); $finder->files()->in($dir); return $finder; }
php
{ "resource": "" }
q13267
ChainModel.deleteFile
train
public function deleteFile($fileName) { $files = $this->getFiles(); $success = false; foreach ($files as $file) { if($file->getRelativePathname() === $fileName){ if(!$file->isWritable()){ throw new RuntimeException(sprintf("The file '%s' is not writable and can not be deleted.",$fileName)); } unlink($file->getRealPath()); if($file->isReadable()){ throw new RuntimeException(sprintf("The file '%s' could not be deleted",$fileName)); } $success = true; } } return $success; }
php
{ "resource": "" }
q13268
ChainModel.getFile
train
public function getFile($fileName) { $files = $this->getFiles(); $found = null; foreach ($files as $file) { if($file->getRelativePathname() === $fileName){ if(!$file->isReadable()){ throw new RuntimeException(sprintf("The file '%s' could not be read.",$fileName)); } $found = $file; break; } } return $found; }
php
{ "resource": "" }
q13269
ConfigBase.createFromFile
train
public static function createFromFile(\SplFileInfo $file_info) { $contents = file_get_contents($file_info); if (!$contents) { throw new \RuntimeException( sprintf( 'Unable to retrieve contents from file (%s).', $file_info->getRealPath() ) ); } return self::createFromString($contents); }
php
{ "resource": "" }
q13270
UploaderFactory.build
train
public static function build($dir, array $plugins) { if (count($plugins) === 0) { throw new InvalidArgumentException('There must be at least one provided plugin for image uploader'); } // Default image's quality $quality = 75; $collection = array(); foreach ($plugins as $plugin => $options) { switch ($plugin) { case 'thumb': $thumb = new ThumbFactory(); $collection[] = $thumb->build($dir, $quality, $options); break; case 'original': $original = new OriginalSizeFactory(); $collection[] = $original->build($dir, $quality, $options); break; } } return new UploadChain($collection); }
php
{ "resource": "" }
q13271
PermissionHelper.checkPermission
train
public static function checkPermission(string $permissionName, bool $checkForNested = false): bool { if (self::isAdmin()) { return true; } $user = \Craft::$app->getUser(); $permissionName = strtolower($permissionName); if (self::permissionsEnabled()) { if ($checkForNested) { if (!$user->getId()) { return false; } $permissionList = \Craft::$app->userPermissions->getPermissionsByUserId($user->getId()); foreach ($permissionList as $permission) { if (strpos($permission, $permissionName) === 0) { return true; } } } return $user->checkPermission($permissionName); } return false; }
php
{ "resource": "" }
q13272
PermissionHelper.getNestedPermissionIds
train
public static function getNestedPermissionIds(string $permissionName) { if (self::isAdmin()) { return true; } $user = \Craft::$app->getUser(); $permissionName = strtolower($permissionName); $idList = []; if (self::permissionsEnabled()) { if (!$user->getId()) { return []; } $permissionList = \Craft::$app->userPermissions->getPermissionsByUserId($user->getId()); foreach ($permissionList as $permission) { if (strpos($permission, $permissionName) === 0) { if (strpos($permission, ':') === false) { continue; } list($name, $id) = explode(':', $permission); $idList[] = $id; } } return $idList; } return self::isAdmin(); }
php
{ "resource": "" }
q13273
TemplateManager.loadTemplate
train
public function loadTemplate($filename, $format = null) { $contents = $this->getTemplateContent($filename); switch ($format) { case 'json': $contents = json_decode($contents, true); break; } return $contents; }
php
{ "resource": "" }
q13274
TemplateManager.getTemplateFilePath
train
public function getTemplateFilePath($filename) { $filepath = $this->locateTemplateFilePath($filename); if (!file_exists($filepath)) { return false; } return $filepath; }
php
{ "resource": "" }
q13275
TemplateManager.locateTemplateFilePath
train
protected function locateTemplateFilePath($filename) { // Search project root template directory if defined. if ($this->hasProjectTemplateDirectory()) { $filepath = $this->templateProjectPath() . "/{$filename}"; if (file_exists($filepath)) { return $filepath; } } // Search defined directories for template files. foreach ($this->searchDirectories as $directory) { if (!file_exists($directory)) { continue; } $filepath = "{$directory}/{$filename}"; if (file_exists($filepath)) { return $filepath; } } return null; }
php
{ "resource": "" }
q13276
CoreBag.getMissingCoreModules
train
public function getMissingCoreModules() { $modules = array(); foreach ($this->coreModules as $module) { if (!$this->isLoadedModule($module)) { array_push($modules, $module); } } return $modules; }
php
{ "resource": "" }
q13277
CoreBag.isCoreModule
train
public function isCoreModule($module) { if (!is_string($module)) { throw new InvalidArgumentException(sprintf( 'Module name must be a string, not "%s"', gettype($module) )); } return in_array($module, $this->coreModules); }
php
{ "resource": "" }
q13278
CoreBag.isCoreModules
train
public function isCoreModules(array $modules) { foreach ($modules as $module) { if (!$this->isCoreModule($module)) { return false; } } return true; }
php
{ "resource": "" }
q13279
PlatformTypeFactory.createInstance
train
public function createInstance() { $classname = $this->getPlatformClassname(); if (!class_exists($classname)) { throw new \Exception( sprintf('Unable to locate class %s', $classname) ); } return new $classname(); }
php
{ "resource": "" }
q13280
AjaxORMFilter.filter
train
public function filter(QueryBuilder $qb, $alias, $identifier, $search) { $qb->andWhere("LOWER({$alias}.{$identifier}) LIKE LOWER(:{$identifier})"); $qb->setParameter($identifier, "%{$search}%"); }
php
{ "resource": "" }
q13281
Acknowledgement.setAcknowledgement
train
public function setAcknowledgement(string $acknowledgement): SecurityTxt { if (filter_var($acknowledgement, FILTER_VALIDATE_URL) === false) { throw new Exception('Acknowledgement must be a well-formed URL.'); } $this->acknowledgement = $acknowledgement; return $this; }
php
{ "resource": "" }
q13282
Handler.handle
train
public function handle($exception) { $file = $exception->getFile(); $line = $exception->getLine(); $message = $exception->getMessage(); $trace = $exception->getTrace(); // Reverse and reset default order $trace = array_reverse($trace); // The name of thrown exception $class = get_class($exception); // Above variables will be available in the template require($this->templateFile); }
php
{ "resource": "" }
q13283
TelegramBotCore.webhook
train
public function webhook(): void { //$log = new Logger('botlog'); //$log->pushHandler(new StreamHandler(__DIR__ . "/../log/botlog.log", Logger::DEBUG)); if ($data = BotApi::jsonValidate(file_get_contents('php://input'), true)) { //$log->debug(file_get_contents('php://input')); $update = Update::fromResponse($data); $this->processUpdate($update); } }
php
{ "resource": "" }
q13284
TelegramBotCore.addCommand
train
protected function addCommand(Command $handler): void { $handler->setBot($this); $command = $handler->getName(); $this->commands[strtoupper($command)] = $handler; }
php
{ "resource": "" }
q13285
TelegramBotCore.setCallbackQueryHandler
train
protected function setCallbackQueryHandler(CallbackQueryHandler $handler): void { $handler->setBot($this); $this->cqHandler = $handler; }
php
{ "resource": "" }
q13286
TelegramBotCore.setGenericMessageHandler
train
protected function setGenericMessageHandler(GenericMessageHandler $handler): void { $handler->setBot($this); $this->genericMessageHandler = $handler; }
php
{ "resource": "" }
q13287
MemoryCache.increment
train
public function increment($key, $step = 1) { $value = $this->get($key); $this->set($key, $value + $step); }
php
{ "resource": "" }
q13288
MemoryCache.decrement
train
public function decrement($key, $step = 1) { $value = $this->get($key); $this->set($key, $value - $step); }
php
{ "resource": "" }
q13289
MemoryCache.get
train
public function get($key, $default = false) { if ($this->has($key) !== false) { return $this->cache[$key]; } else { return $default; } }
php
{ "resource": "" }
q13290
MemoryCache.remove
train
public function remove($key) { if ($this->has($key)) { unset($this->cache[$key]); return true; } else { return false; } }
php
{ "resource": "" }
q13291
DataTableData.buildColumns
train
private function buildColumns(array $columns) { $this->columns = []; foreach ($columns as $key => $column) { $column = new DataTableColumn($column); $this->columns[$key] = $column; if($column->getName() != ""){ $this->columns[$column->getName()] = $column; } if($column->getData() != ""){ $this->columns[$column->getData()] = $column; } } }
php
{ "resource": "" }
q13292
DataTableData.getColumnByIndex
train
public function getColumnByIndex($index) { if(!isset($this->columns[$index])){ throw new Exception(sprintf("Column index %s is not valid",$index)); } return $this->columns[$index]; }
php
{ "resource": "" }
q13293
EngineTypeFactory.createInstance
train
public function createInstance() { $classname = $this->getEngineClassname(); if (!class_exists($classname)) { throw new \Exception( sprintf('Unable to locate class %s', $classname) ); } return new $classname(); }
php
{ "resource": "" }
q13294
Pogodev.supportsVersion
train
public function supportsVersion(Version $version) : bool { try { $this->getVersionUrl($version); } catch (UnsupportedVersionException $e) { return false; } return true; }
php
{ "resource": "" }
q13295
PayPalHandler.callback
train
public function callback($request) { $this->extend('onBeforeCallback'); $data = $this->request->postVars(); $status = "error"; $order_id = 0; $payment_id = 0; $error_url = Controller::join_links( Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error' ); // Check if CallBack data exists and install id matches the saved ID if (isset($data) && isset($data['custom']) && isset($data['payment_status'])) { $order_id = $data['custom']; $paypal_request = 'cmd=_notify-validate'; $final_response = ""; // If the transaction ID is set, keep it if (array_key_exists("txn_id", $data)) { $payment_id = $data["txn_id"]; } $listener = new PaypalIPN(); if (Director::isDev()) { $listener->useSandbox(); } try { $verified = $listener->verifyIPN(); } catch (Exception $e) { error_log("Unable to verify IPN: " . $e->getMessage()); return $this->httpError(500); } if ($verified) { // IPN response was "VERIFIED" switch ($data['payment_status']) { case 'Canceled_Reversal': $status = "canceled"; break; case 'Completed': $status = "paid"; break; case 'Denied': $status = "failed"; break; case 'Expired': $status = "failed"; break; case 'Failed': $status = "failed"; break; case 'Pending': $status = "pending"; break; case 'Processed': $status = "pending"; break; case 'Refunded': $status = "refunded"; break; case 'Reversed': $status = "canceled"; break; case 'Voided': $status = "canceled"; break; } } else { error_log("Invalid payment status"); return $this->httpError(500); } } else { error_log("No payment details set"); return $this->httpError(500); } $payment_data = ArrayData::array_to_object(array( "OrderID" => $order_id, "PaymentProvider" => "PayPal", "PaymentID" => $payment_id, "Status" => $status, "GatewayData" => $data )); $this->setPaymentData($payment_data); $this->extend('onAfterCallback'); return $this->httpError(200); }
php
{ "resource": "" }
q13296
CreditCardValidator.setContext
train
public function setContext($context) { $contexts = array(self::CONTEXT_CREDITCARD, self::CONTEXT_TOKEN); if (!in_array($context, $contexts)) { throw new RuntimeException( sprintf("Invalid validation context '%s'", $context) ); } $this->context = $context; }
php
{ "resource": "" }
q13297
CreditCardValidator.validate
train
public function validate(CreditCard $creditCard) { $this->errors = array(); $this->creditCard = $creditCard; if ($this->context == self::CONTEXT_CREDITCARD) { $this->validateNumber(); $this->validateExpiration(); $this->validateVerificationValue(); $this->validateBrand(); $this->validateCardHolder(); } elseif ($this->context == self::CONTEXT_TOKEN) { $this->validateToken(); } return $this->errors; }
php
{ "resource": "" }
q13298
Paginator.tweak
train
public function tweak($totalAmount, $itemsPerPage, $page) { $this->totalAmount = (int) $totalAmount; $this->itemsPerPage = (int) $itemsPerPage; $this->setCurrentPage($page); return $this; }
php
{ "resource": "" }
q13299
Paginator.getUrl
train
public function getUrl($page) { if (is_null($this->url)) { throw new RuntimeException('URL template must be defined'); } if (strpos($this->url, $this->placeholder) !== false) { return str_replace($this->placeholder, $page, $this->url); } else { // Without placeholder, no substitution is done, therefore pagination links won't work throw new LogicException('The URL string must contain at least one placeholder to make pagination links work'); } }
php
{ "resource": "" }