_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q13000
DeviceInfo.toProtobuf
train
public function toProtobuf() : SignatureDeviceInfo { $deviceInfo = new SignatureDeviceInfo(); if ($this->deviceId !== null) { $deviceInfo->setDeviceId($this->deviceId); } $deviceInfo->setDeviceBrand($this->deviceBrand); $deviceInfo->setDeviceModel($this->deviceModel); $deviceInfo->setDeviceModelBoot($this->deviceModelBoot); $deviceInfo->setFirmwareType($this->firmwareType); $deviceInfo->setFirmwareBrand($this->firmwareBrand); $deviceInfo->setHardwareModel($this->hardwareModel); $deviceInfo->setHardwareManufacturer($this->hardwareManufacturer); return $deviceInfo; }
php
{ "resource": "" }
q13001
WindowsAzureDistributionExtension.loadKeyValueStore
train
protected function loadKeyValueStore($config, $container, $loader) { if (empty($config['key_value_store']['connection_name'])) { return; } $loader->load('keyvaluestore.xml'); $container->setAlias('windows_azure_distribution.key_value_store.storage_client', 'windows_azure.table.' . $config['key_value_store']['connection_name']); }
php
{ "resource": "" }
q13002
Router.getNamedUrl
train
public function getNamedUrl($name, $params = array(), $version = null, $locale = null) { if ($version == null) { $version = Registry::get('version'); } if ($locale == null) { $locale = Registry::get('locale'); } $foundRoute = false; if (isset($this->allRoutesByVersionAndLocale[$version][$locale][$name])) { $url = $this->allRoutesByVersionAndLocale[$version][$locale][$name]['regexp']; $foundRoute = true; } elseif (isset($this->allRoutesByVersionAndLocale[$version]['*'][$name])) { $url = $this->allRoutesByVersionAndLocale[$version]['*'][$name]['regexp']; $foundRoute = true; } elseif (isset($this->allRoutesByVersionAndLocale['*']['*'][$name])) { $url = $this->allRoutesByVersionAndLocale['*']['*'][$name]['regexp']; $foundRoute = true; } if ($foundRoute) { preg_match_all('/\(([\w_]+):([^)]+)\)/im', $url, $result, PREG_SET_ORDER); for ($matchi = 0; $matchi < count($result); $matchi ++) { if (isset($params[$result[$matchi][1]])) { $url = str_replace($result[$matchi][0], $params[$result[$matchi][1]], $url); } } return $url; } else { throw new \Exception('Cannot find route named "' . $name . '" (version=' . $version . ', locale=' . $locale . ')'); } }
php
{ "resource": "" }
q13003
NodeElement.appendChildWithText
train
public function appendChildWithText(NodeElement $nodeElement, $text, $append = true) { $content = $nodeElement->render(); if ($append === true) { $content = $content.$text; } else { $content = $text.$content; } $this->setText($content); return $this; }
php
{ "resource": "" }
q13004
NodeElement.setText
train
public function setText($text, $finalize = true) { if ($finalize && !$this->isFinalized()) { $this->finalize(); } $this->append($text); return $this; }
php
{ "resource": "" }
q13005
NodeElement.finalize
train
public function finalize($singular = false) { $this->finalized = true; if ($singular === true) { $text = ' />'; } else { $text = '>'; } $this->append($text); return $this; }
php
{ "resource": "" }
q13006
NodeElement.openTag
train
public function openTag($tagName) { $this->append(sprintf('<%s', $tagName)); $this->tag = $tagName; return $this; }
php
{ "resource": "" }
q13007
NodeElement.closeTag
train
public function closeTag($tag = null) { if ($tag === null) { $tag = $this->tag; } $this->append(sprintf('</%s>', $tag)); return $this; }
php
{ "resource": "" }
q13008
NodeElement.addPropertyOnDemand
train
public function addPropertyOnDemand($property, $value) { if ((bool) $value === true) { $this->addProperty($property); } return $this; }
php
{ "resource": "" }
q13009
NodeElement.addAttribute
train
public function addAttribute($attribute, $value) { // Escape special characters $value = Filter::filterAttribute($value); if ($this->isProperty($attribute)) { $this->addPropertyOnDemand($attribute, $value); } else { if ($this->hasAttribute($attribute)) { throw new LogicException(sprintf('The element already has "%s" attribute', $attribute)); } $this->append(sprintf(' %s="%s"', $attribute, $value)); $this->attributes[$attribute] = $value; } return $this; }
php
{ "resource": "" }
q13010
NodeElement.addAttributes
train
public function addAttributes(array $attributes) { foreach ($attributes as $attribute => $value) { $this->addAttribute($attribute, $value); } return $this; }
php
{ "resource": "" }
q13011
NodeElement.hasClass
train
public function hasClass($class = null) { if ($class !== null) { $classes = explode(' ', $this->getClass()); return in_array($class, $classes); } else { return $this->hasAttribute('class'); } }
php
{ "resource": "" }
q13012
Data.isActiveDefaultPayment
train
public function isActiveDefaultPayment() { return $this->scopeConfig->isSetFlag( self::XML_PAYMENT_DEFAULT_ACTIVE_DEFAULT_PAYMENT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); }
php
{ "resource": "" }
q13013
Data.getDefaultMethod
train
public function getDefaultMethod() { return $this->scopeConfig->getValue( self::XML_PAYMENT_DEFAULT_METHOD, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); }
php
{ "resource": "" }
q13014
Data.isActiveGoogleAddress
train
public function isActiveGoogleAddress() { $flag = $this->scopeConfig->isSetFlag( self::XML_GOOGLE_MAP_ADDRESS_ACTIVE_GOOGLE_ADDRESS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); return $flag && $this->getGoogleMapApiKey(); }
php
{ "resource": "" }
q13015
Data.isActiveBillingGoogleAddress
train
public function isActiveBillingGoogleAddress() { $flag = $this->scopeConfig->isSetFlag( self::XML_GOOGLE_MAP_ADDRESS_ACTIVE_GOOGLE_ADDRESS_BILLING, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); return $flag && $this->getGoogleMapApiKey(); }
php
{ "resource": "" }
q13016
Data.getGoogleMapApiKey
train
public function getGoogleMapApiKey() { $str = $this->scopeConfig->getValue( self::XML_GOOGLE_MAP_API_KEY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); $str = trim($str); return $str; }
php
{ "resource": "" }
q13017
Data.getGoogleMapAddressLibraries
train
public function getGoogleMapAddressLibraries() { return $this->scopeConfig->getValue( self::XML_GOOGLE_MAP_ADDRESS_LIBRARIES, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); }
php
{ "resource": "" }
q13018
Data.getGoogleMapAddressCountries
train
public function getGoogleMapAddressCountries() { return explode( ',', (string) $this->scopeConfig->getValue( self::XML_GOOGLE_MAP_ADDRESS_COUNTRY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ) ); }
php
{ "resource": "" }
q13019
Data.getGoogleMapAddressLanguage
train
public function getGoogleMapAddressLanguage() { return $this->scopeConfig->getValue( self::XML_GOOGLE_MAP_ADDRESS_LANGUAGE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); }
php
{ "resource": "" }
q13020
API.checkChallenge
train
public function checkChallenge() { $request = new CheckChallenge(); /** @var CheckChallengeResponse $response */ $response = $this->service->execute($request, $this->position); $challengeUrl = trim($response->getChallengeUrl()); if ($response->getShowChallenge() || !empty($challengeUrl)) { if (!$this->captchaSolver instanceof Solver) { $this->getLogger()->alert("Account has been flagged for CAPTCHA. No CAPTCHA-solver defined, returning challenge."); return $challengeUrl; } $this->getLogger()->alert("Account has been flagged for CAPTCHA. Attempting to solve CAPTCHA with defined resolver."); /* Attempt to solve CAPTCHA */ $token = $this->captchaSolver->solve($challengeUrl); $this->getLogger()->info("Received CAPTCHA solution. Verifying..."); /* Wait 1 second before firing verification request. */ sleep(1); $verify = $this->verifyChallenge($token); if ($verify->hasSuccess()) { $this->getLogger()->info("Successfully solved CAPTCHA."); return true; } throw new FailedCaptchaException("Failed to resolve CAPTCHA."); } return false; }
php
{ "resource": "" }
q13021
API.acceptTerms
train
public function acceptTerms() : MarkTutorialCompleteResponse { $request = new MarkTutorialComplete(); return $this->service->execute($request, $this->position); }
php
{ "resource": "" }
q13022
API.getPlayerData
train
public function getPlayerData() : GetPlayerResponse { $request = new GetPlayer(); return $this->service->execute($request, $this->position); }
php
{ "resource": "" }
q13023
API.getInventory
train
public function getInventory() : GetInventoryResponse { $request = new GetInventory(); return $this->service->execute($request, $this->position); }
php
{ "resource": "" }
q13024
API.getMapObjects
train
public function getMapObjects() : GetMapObjectsResponse { $request = new GetMapObjects($this->position); return $this->service->execute($request, $this->position); }
php
{ "resource": "" }
q13025
PluginBag.appendInternal
train
private function appendInternal($unit, array &$stack) { $unit = $this->normalizeAssetPath($unit); array_push($stack, $unit); return $this; }
php
{ "resource": "" }
q13026
PluginBag.normalizeAssetPath
train
private function normalizeAssetPath($path) { $pattern = '~@(\w+)~'; $replacement = sprintf('/%s/$1/%s', ViewManager::TEMPLATE_PARAM_MODULES_DIR, ViewManager::TEMPLATE_PARAM_ASSETS_DIR); return preg_replace($pattern, $replacement, $path); }
php
{ "resource": "" }
q13027
PluginBag.register
train
public function register(array $collection) { foreach ($collection as $name => $data) { $this->plugins[$name] = $data; } return $this; }
php
{ "resource": "" }
q13028
PluginBag.load
train
public function load($plugins) { if (!is_array($plugins)) { $plugins = (array) $plugins; } foreach ($plugins as $plugin) { if (!isset($this->plugins[$plugin])) { trigger_error(sprintf('Attempted to load non-existing plugin %s', $plugin)); return false; } if (isset($this->plugins[$plugin]['scripts'])) { $this->appendScripts($this->plugins[$plugin]['scripts']); } if (isset($this->plugins[$plugin]['stylesheets'])) { $this->appendStylesheets($this->plugins[$plugin]['stylesheets']); } } return $this; }
php
{ "resource": "" }
q13029
ReportTasks.reportLighthouse
train
public function reportLighthouse($opts = [ 'hostname' => null, 'protocol' => 'http' ]) { $host = ProjectX::getProjectConfig() ->getHost(); $protocol = $opts['protocol']; $hostname = isset($opts['hostname']) ? $opts['hostname'] : (isset($host['name']) ? $host['name'] : 'localhost'); $path = $this->getReportsPath() . "/lighthouse-report-$hostname.html"; $this->taskGoogleLighthouse() ->setUrl("$protocol://$hostname") ->setOutputPath($path) ->run(); }
php
{ "resource": "" }
q13030
ReportTasks.getReportsPath
train
protected function getReportsPath() { $project_root = ProjectX::projectRoot(); $reports_path = "$project_root/reports"; if (!file_exists($reports_path)) { mkdir($reports_path); } return $reports_path; }
php
{ "resource": "" }
q13031
EngineTasks.engineUp
train
public function engineUp($opts = ['no-hostname' => false, 'no-browser' => false]) { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:up'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13032
EngineTasks.engineRebuild
train
public function engineRebuild() { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:rebuild'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13033
EngineTasks.engineDown
train
public function engineDown($opts = [ 'include-network' => false ]) { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:down'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13034
EngineTasks.engineResume
train
public function engineResume() { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:resume'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13035
EngineTasks.engineRestart
train
public function engineRestart() { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:restart'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13036
EngineTasks.engineReboot
train
public function engineReboot() { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:reboot'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13037
EngineTasks.engineInstall
train
public function engineInstall() { $this->executeCommandHook(__FUNCTION__, 'before'); $this->executeExistingCommand('env:install'); $this->executeCommandHook(__FUNCTION__, 'after'); return $this; }
php
{ "resource": "" }
q13038
EngineTasks.executeExistingCommand
train
protected function executeExistingCommand( $command_name, InputInterface $input = null, OutputInterface $output = null ) { if (!isset($command_name)) { return 1; } $input = isset($input) ? $input : $this->input(); $output = isset($output) ? $output : $this->output(); return $this->getApplication() ->find($command_name) ->run($input, $output); }
php
{ "resource": "" }
q13039
StatusGenerator.getDescriptionByStatusCode
train
public function getDescriptionByStatusCode($code) { // Make sure the expected type supplied $code = (int) $code; if (isset($this->statuses[$code])) { return $this->statuses[$code]; } else { throw new OutOfRangeException( sprintf('The status code "%s" is out of allowed range', $code) ); } }
php
{ "resource": "" }
q13040
StatusGenerator.generate
train
public function generate($code) { if ($this->isValid($code)) { return sprintf('HTTP/%s %s %s', $this->version, $code, $this->getDescriptionByStatusCode($code)); } else { return false; } }
php
{ "resource": "" }
q13041
ProjectX.discoverCommands
train
public function discoverCommands() { $commands = (new PhpClassDiscovery()) ->addSearchLocation(APP_ROOT . '/src/Command') ->matchExtend('Symfony\Component\Console\Command\Command') ->discover(); foreach ($commands as $classname) { $this->add(new $classname()); } return $this; }
php
{ "resource": "" }
q13042
ProjectX.setEnvVariables
train
public static function setEnvVariables() { $env_variables = []; if (file_exists(static::projectRoot() . '/.env')) { $env_variables = (new Dotenv(static::projectRoot())) ->load(); } self::$projectEnv = $env_variables; }
php
{ "resource": "" }
q13043
ProjectX.setDefaultServices
train
public static function setDefaultServices($container) { $project_root = self::projectRoot(); $container ->share('projectXTemplate', \Droath\ProjectX\Template\TemplateManager::class); $container ->share('projectXGitHubUserAuth', \Droath\ProjectX\Service\GitHubUserAuthStore::class); $container ->share('projectXHostChecker', \Droath\ProjectX\Service\HostChecker::class); $container ->add('projectXEngine', function () use ($container) { return (new \Droath\ProjectX\Engine\EngineTypeFactory( $container->get('projectXEngineResolver') ))->createInstance(); }); $container ->share('projectXEngineResolver', \Droath\ProjectX\Engine\EngineTypeResolver::class) ->withArgument('projectXFilesystemCache'); $container ->add('projectXProject', function () use ($container) { return (new \Droath\ProjectX\Project\ProjectTypeFactory( $container->get('projectXProjectResolver') ))->createInstance(); }); $container ->share('projectXProjectResolver', \Droath\ProjectX\Project\ProjectTypeResolver::class) ->withArgument('projectXFilesystemCache'); $container ->add('projectXPlatform', function () use ($container) { return (new PlatformTypeFactory( $container->get('projectXPlatformResolver') ))->createInstance(); }); $container ->share('projectXPlatformResolver', PlatformTypeResolver::class) ->withArgument('projectXFilesystemCache'); $container ->share('projectXFilesystemCache', \Symfony\Component\Cache\Adapter\FilesystemAdapter::class) ->withArguments(['', 0, "$project_root/.project-x/cache"]); }
php
{ "resource": "" }
q13044
ProjectX.taskLocations
train
public static function taskLocations() { $locations = array_merge( [self::projectRoot()], self::getEngineType()->taskDirectories(), self::getProjectType()->taskDirectories(), self::getPlatformType()->taskDirectories() ); if (self::hasProjectConfig()) { $locations[] = APP_ROOT . '/src/Task'; } return array_filter($locations); }
php
{ "resource": "" }
q13045
ProjectX.getPlatformType
train
public static function getPlatformType() { $container = self::getContainer(); $builder = CollectionBuilder::create($container, false); return $container->get('projectXPlatform') ->setBuilder($builder); }
php
{ "resource": "" }
q13046
ProjectX.getProjectType
train
public static function getProjectType() { $container = self::getContainer(); $builder = CollectionBuilder::create($container, new ProjectTasks()); return $container->get('projectXProject') ->setBuilder($builder); }
php
{ "resource": "" }
q13047
ProjectX.getEngineType
train
public static function getEngineType() { $container = self::getContainer(); $builder = CollectionBuilder::create($container, new EngineTasks()); return $container->get('projectXEngine') ->setBuilder($builder); }
php
{ "resource": "" }
q13048
ProjectX.getProjectConfig
train
public static function getProjectConfig() { if (!isset(self::$projectConfig)) { $config = self::getConfigInstance(); $values = self::getLocalConfigValues(); self::$projectConfig = empty($values) ? $config : $config->update($values); } return self::$projectConfig; }
php
{ "resource": "" }
q13049
ProjectX.getRemoteEnvironments
train
public static function getRemoteEnvironments() { $environments = []; foreach (self::getProjectConfig()->getRemote() as $remote) { foreach ($remote as $environment) { if (!isset($environment['realm'])) { continue; } $realm = $environment['realm']; unset($environment['realm']); $environments[$realm][] = $environment; } } return $environments; }
php
{ "resource": "" }
q13050
ProjectX.getLocalConfigValues
train
protected static function getLocalConfigValues() { $root = self::projectRoot(); $path = "{$root}/project-x.local.yml"; if (!file_exists($path)) { return []; } $instance = ProjectXConfig::createFromFile( new \SplFileInfo($path) ); return array_filter($instance->toArray()); }
php
{ "resource": "" }
q13051
AttemptLimit.getCurrentFailAttemptCount
train
public function getCurrentFailAttemptCount() { if (!$this->sessionBag->has(self::PARAM_ATTEMPT_NS)) { $this->reset(); } return $this->sessionBag->get(self::PARAM_ATTEMPT_NS); }
php
{ "resource": "" }
q13052
AttemptLimit.getLastLogin
train
public function getLastLogin() { if ($this->sessionBag->has(self::PARAM_LAST_LOGIN_NS)) { return $this->sessionBag->get(self::PARAM_LAST_LOGIN_NS); } else { return null; } }
php
{ "resource": "" }
q13053
Filter.fromList
train
public function fromList($value): self { $value = collect($value)->implode(self::SEPARATOR); $this->has("list:{$value}"); return $this; }
php
{ "resource": "" }
q13054
FileManager.humanSize
train
public static function humanSize($bytes) { // Make sure we can't divide by zero if ($bytes == 0) { return '0 B'; } $value = floor(log($bytes, 1024)); $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); $unit = $units[$value]; // Chosen unit return sprintf('%.02F', $bytes / pow(1024, $value)) * 1 . ' ' . $unit; }
php
{ "resource": "" }
q13055
FileManager.hasExtension
train
public static function hasExtension($baseName, array $extensions) { // Lowercase names $baseName = strtolower($baseName); $extensions = array_map(function($key){ return strtolower($key); }, $extensions); return in_array(self::getExtension($baseName), $extensions); }
php
{ "resource": "" }
q13056
FileManager.getMimeType
train
public static function getMimeType($file) { $mimeType = new MimeTypeGuesser(); $extension = self::getExtension($file); return $mimeType->getTypeByExtension($file); }
php
{ "resource": "" }
q13057
FileManager.rmfile
train
public static function rmfile($file) { if (is_file($file)) { return chmod($file, 0777) && unlink($file); } else { throw new RuntimeException(sprintf( 'Invalid file path supplied "%s"', $file )); } }
php
{ "resource": "" }
q13058
FileManager.getDirTree
train
public static function getDirTree($dir, $self = false) { if (!is_dir($dir)) { throw new RuntimeException(sprintf( 'Can not build directory tree because of invalid path "%s"', $dir )); } $target = array(); $tree = array(); $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); if ($self !== false) { array_push($target, $dir); } foreach ($iterator as $file) { array_push ($target, $file); } foreach ($target as $index => $file) { array_push($tree, (string) $file); } return $tree; }
php
{ "resource": "" }
q13059
FileManager.getDirSizeCount
train
public static function getDirSizeCount($dir) { if (!is_dir($dir)) { throw new RuntimeException(sprintf('Invalid directory path supplied "%s"', $dir)); } $count = 0.00; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); foreach ($iterator as $file) { $count += $file->getSize(); } return $count; }
php
{ "resource": "" }
q13060
FileManager.chmod
train
public static function chmod($file, $mode, array &$ignored = array()) { if (is_file($file)) { if (!chmod($file, $mode)) { array_push($ignored, $file); return false; } } else if (is_dir($file)) { $items = self::getDirTree($file, true); foreach ($items as $item) { if (!chmod($item, $mode)) { array_push($ignored, $item); } } } else { throw new UnexpectedValueException(sprintf( '%s expects a path to be a directory or a file as first argument', __METHOD__ )); } return true; }
php
{ "resource": "" }
q13061
FileManager.copy
train
public static function copy($src, $dst) { if (!is_dir($src)) { throw new RuntimeException(sprintf('Invalid directory path supplied "%s"', $src)); } $dir = opendir($src); if (!is_dir($dst)) { mkdir($dst, 0777); } while (false !== ($file = readdir($dir))) { // We must ensure a file isn't a dot if (($file != '.' ) && ($file != '..' )) { if (is_dir($src . '/' . $file)) { // Recursive call call_user_func(__METHOD__, $src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir); return true; }
php
{ "resource": "" }
q13062
FileManager.move
train
public static function move($from, $to) { return self::copy($from, $to) && self::delete($from); }
php
{ "resource": "" }
q13063
FileManager.isFileEmpty
train
public static function isFileEmpty($file) { if (!is_file($file)) { throw new RuntimeException(sprintf('Invalid file path supplied')); } return mb_strlen(file_get_contents($file, 2), 'UTF-8') > 0 ? false : true; }
php
{ "resource": "" }
q13064
FileManager.getFirstLevelDirs
train
public static function getFirstLevelDirs($dir) { $iterator = new DirectoryIterator($dir); $result = array(); foreach ($iterator as $item) { if (!$item->isDot() && $item->isDir()) { array_push($result, $item->getFileName()); } } return $result; }
php
{ "resource": "" }
q13065
News.summaryFields
train
public function summaryFields() { $summaryFields = parent::summaryFields(); $summaryFields = array_merge( $summaryFields, array( 'Title' => _t('News.TITLE', 'Title'), 'Author' => _t('News.AUTHOR', 'Author'), 'PublishFrom' => _t('News.PUBLISH', 'Publish from'), 'Status' => _t('News.STATUS', 'Status'), ) ); return $summaryFields; }
php
{ "resource": "" }
q13066
News.searchableFields
train
public function searchableFields() { $searchableFields = parent::searchableFields(); unset($searchableFields['PublishFrom']); $searchableFields['Title'] = array( 'field' => 'TextField', 'filter' => 'PartialMatchFilter', 'title' => _t('News.TITLE', 'Title') ); $searchableFields['Author'] = array( 'field' => 'TextField', 'filter' => 'PartialMatchFilter', 'title' => _t('News.AUTHOR', 'Author') ); return $searchableFields; }
php
{ "resource": "" }
q13067
News.fieldLabels
train
public function fieldLabels($includerelations = true) { $labels = parent::fieldLabels($includerelations); $newsLabels = array( 'Title' => _t('News.TITLE', 'Title'), 'Author' => _t('News.AUTHOR', 'Author'), 'Synopsis' => _t('News.SUMMARY', 'Summary/Abstract'), 'Content' => _t('News.CONTENT', 'Content'), 'PublishFrom' => _t('News.PUBDATE', 'Publish from'), 'Live' => _t('News.PUSHLIVE', 'Published'), 'Commenting' => _t('News.COMMENTING', 'Allow comments on this item'), 'Type' => _t('News.NEWSTYPE', 'Type of item'), 'External' => _t('News.EXTERNAL', 'External link'), 'Download' => _t('News.DOWNLOAD', 'Downloadable file'), 'Impression' => _t('News.IMPRESSION', 'Impression image'), 'Comments' => _t('News.COMMENTS', 'Comments'), 'SlideshowImages' => _t('News.SLIDE', 'Slideshow'), 'Tags' => _t('News.TAGS', 'Tags'), 'NewsHolderPages' => _t('News.LINKEDPAGES', 'Linked pages'), 'Help' => _t('News.BASEHELPLABEL', 'Help') ); return array_merge($newsLabels, $labels); }
php
{ "resource": "" }
q13068
News.onBeforeWrite
train
public function onBeforeWrite() { parent::onBeforeWrite(); /** Check if we have translatable and a NewsHolderPage. If no HolderPage available, skip (Create an orphan) */ if (!$this->NewsHolderPages()->count()) { if (!class_exists('Translatable') && $page = NewsHolderPage::get()->first()) { $this->NewsHolderPages()->add($page); } elseif (class_exists('Translatable')) { Translatable::disable_locale_filter(); $page = NewsHolderPage::get()->first(); $this->NewsHolderPages()->add($page); Translatable::enable_locale_filter(); } } if (!$this->Type || $this->Type === '') { $this->Type = 'news'; } /** Set PublishFrom to today to prevent errors with sorting. New since 2.0, backward compatible. */ if (!$this->PublishFrom) { $this->PublishFrom = SS_Datetime::now()->Rfc2822(); } /** * Make sure the link is valid. */ if (substr($this->External, 0, 4) !== 'http' && $this->External != '') { $this->External = 'http://' . $this->External; } $this->setURLValue(); $this->setAuthorData(); }
php
{ "resource": "" }
q13069
News.setURLValue
train
private function setURLValue() { if (!$this->URLSegment || ($this->isChanged('Title') && !$this->isChanged('URLSegment'))) { if ($this->ID > 0) { $Renamed = new Renamed(); $Renamed->OldLink = $this->URLSegment; $Renamed->NewsID = $this->ID; $Renamed->write(); $this->URLSegment = singleton('SiteTree')->generateURLSegment($this->Title); if (strpos($this->URLSegment, 'page-') === false) { $URLSegment = $this->URLSegment; if ($this->LookForExistingURLSegment($URLSegment)) { $URLSegment = $this->URLSegment . '-' . $this->ID; } $this->URLSegment = $URLSegment; } } } }
php
{ "resource": "" }
q13070
News.LookForExistingURLSegment
train
private function LookForExistingURLSegment($URLSegment) { return (News::get() ->filter(array('URLSegment' => $URLSegment)) ->exclude(array('ID' => $this->ID)) ->count() !== 0); }
php
{ "resource": "" }
q13071
News.LinkingMode
train
public function LinkingMode() { /** @var Page_Controller $controller */ $controller = Controller::curr(); $params = $controller->getURLParams(); return $params['ID'] === $this->URLSegment ? 'current' : 'link'; }
php
{ "resource": "" }
q13072
News.getStatus
train
public function getStatus() { $published = $this->isPublished() ? _t('News.IsPublished', 'published') : _t('News.IsUnpublished', 'not published'); if ($this->isPublished() && $this->PublishFrom > SS_Datetime::now()->Rfc2822()) { $published = _t('News.InQueue', 'Awaiting publishdate'); } return $published; }
php
{ "resource": "" }
q13073
News.doPublish
train
public function doPublish() { if (!$this->canEdit()) { throw new ValidationException(_t('News.PublishPermissionFailure', 'No permission to publish or unpublish news item')); } $this->Live = true; $this->write(); }
php
{ "resource": "" }
q13074
News.doUnpublish
train
public function doUnpublish() { if (!$this->canEdit()) { throw new ValidationException(_t('News.PublishPermissionFailure', 'No permission to publish or unpublish news item')); } $this->Live = false; $this->write(); }
php
{ "resource": "" }
q13075
Checkout.CreateFreePostageObject
train
public static function CreateFreePostageObject() { $postage = new PostageArea(); $postage->ID = -1; $postage->Title = _t("Checkout.FreeShipping", "Free Shipping"); $postage->Country = "*"; $postage->ZipCode = "*"; return $postage; }
php
{ "resource": "" }
q13076
Application.create
train
public static function create(string $basePath): Application { self::$instance = new Application($basePath); return self::$instance; }
php
{ "resource": "" }
q13077
Application.basePath
train
public function basePath(?string $basePath = null) { if ($basePath != null) { $this->basePath = $basePath; } return $this->basePath; }
php
{ "resource": "" }
q13078
Application.storagePath
train
public function storagePath(?string $storagePath = null) { if ($storagePath != null) { $this->storagePath = $storagePath; } else if (!isset($this->storagePath)) { $this->storagePath = get_property("app.storage_path", $this->basePath . DIRECTORY_SEPARATOR . "storage"); } return $this->storagePath; }
php
{ "resource": "" }
q13079
Application.resourcesPath
train
public function resourcesPath(?string $resourcesPath = null) { if ($resourcesPath != null) { $this->resourcesPath = $resourcesPath; } else if (!isset($this->resourcesPath)) { $this->resourcesPath = get_property("app.resources_path", $this->basePath . DIRECTORY_SEPARATOR . "resources"); } return $this->resourcesPath; }
php
{ "resource": "" }
q13080
Application.configPath
train
public function configPath(?string $configPath = null) { if ($configPath != null) { $this->configPath = $configPath; } else { if (!isset($this->configPath)) { $this->configPath = $this->basePath() . DIRECTORY_SEPARATOR . "config"; } } return $this->configPath; }
php
{ "resource": "" }
q13081
Application.localConfigPath
train
public function localConfigPath(?string $localConfigPath = null) { if ($localConfigPath != null) { $this->localConfigPath = $localConfigPath; } else { if (!isset($this->localConfigPath)) { $this->localConfigPath = $this->basePath() . DIRECTORY_SEPARATOR . "config.local"; } } return $this->localConfigPath; }
php
{ "resource": "" }
q13082
Application.start
train
public function start() { foreach ($this->modules as $module) { $module->start(); } if (php_sapi_name() == "cli") { Commands::handleCommand(); } else { Routes::handleRequest(); } }
php
{ "resource": "" }
q13083
Application.getParameterValues
train
private function getParameterValues ($function, array $parameters = []) { $functionParams = []; $parameterIndex = 0; foreach ($function->getParameters() as $parameter) { $parameterName = $parameter->getName(); $parameterValue = null; if (array_key_exists($parameterName, $parameters)) { $parameterValue = $parameters[$parameterName]; } else if ($parameter->hasType()) { $type = $parameter->getType(); if (!$type->isBuiltin()) { $typeName = (string)$type; if (array_key_exists($typeName, $parameters)) { $parameterValue = $parameters[$typeName]; } else if (!$parameter->isDefaultValueAvailable()) { $typeClass = new ReflectionClass($typeName); foreach ($typeClass->getMethods(ReflectionMethod::IS_STATIC) as $staticMethod) { if ($staticMethod->getReturnType() != null && ((string)$staticMethod->getReturnType() == $typeName) && $staticMethod->getNumberOfParameters() == 0) { $parameterValue = $staticMethod->invoke(null); break; } } } } } if ($parameterValue == null) { if (array_key_exists($parameterIndex, $parameters)) { $parameterValue = $parameters[$parameterIndex]; $parameterIndex++; } else if ($parameter->isDefaultValueAvailable()) { $parameterValue = $parameter->getDefaultValue(); } } $functionParams[] = $parameterValue; } return $functionParams; }
php
{ "resource": "" }
q13084
Application.handleError
train
public function handleError($errno, $errstr, $errfile, $errline, $errcontext) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }
php
{ "resource": "" }
q13085
Translator.translate
train
public function translate($text, $autoDetect = true) { if (! $this->getTargetLang()) { throw new TranslateException('No target language was set.'); } if (! $this->getSourceLang() && $autoDetect) { // Detect language if source language was not provided and auto detect is turned on $this->setSourceLang($this->detect($text)); } else { if (! $this->getSourceLang()) { throw new TranslateException('No source language was set with autodetect turned off.'); } } $requestUrl = $this->buildRequestUrl($this->getTranslateUrl(), [ 'q' => $text, 'source' => $this->getSourceLang(), 'target' => $this->getTargetLang() ]); $response = $this->getResponse($requestUrl); if (isset($response['data']['translations']) && count($response['data']['translations']) > 0) { return $response['data']['translations'][0]['translatedText']; } return null; }
php
{ "resource": "" }
q13086
Translator.detect
train
public function detect($text) { $requestUrl = $this->buildRequestUrl($this->getDetectUrl(), [ 'q' => $text ]); $response = $this->getResponse($requestUrl); if (isset($response['data']['detections'])) { return $response['data']['detections'][0][0]['language']; } throw new TranslateException('Could not detect provided text language.'); }
php
{ "resource": "" }
q13087
Translator.getResponse
train
protected function getResponse($requestUrl) { $response = $this->getHttpClient()->get($requestUrl); return json_decode($response->getBody()->getContents(), true); }
php
{ "resource": "" }
q13088
DoctrineOrmDataSource.setQuery
train
public function setQuery($query) { $this->cacheRows = null; $this->size = null; $this->paginator = new Paginator($query); return $this; }
php
{ "resource": "" }
q13089
AbstractConstraint.violate
train
public function violate($message) { if (!empty($this->messages)){ $message = $this->messages[0]; } else { $this->setMessage($message); } }
php
{ "resource": "" }
q13090
TreeBuilder.applyToChildNodes
train
public function applyToChildNodes($parentId, Closure $callback) { $ids = $this->findChildNodeIds($parentId); // If there's at least one child id, then start working next if (!empty($ids)) { foreach ($ids as $id) { // Invoke a callback supplying a child's id $callback($id); } } return true; }
php
{ "resource": "" }
q13091
TreeBuilder.findParentNodesByChildId
train
public function findParentNodesByChildId($id) { // To be returned $result = array(); $rl = $this->getRelations(); $data = $rl[RelationBuilder::TREE_PARAM_ITEMS]; // If can't find, then return empty array if (!isset($data[$id])) { return array(); } $current = $data[$id]; $parentId = $current[RelationBuilder::TREE_PARAM_PARENT_ID]; while (isset($data[$parentId])) { $current = $data[$parentId]; $parentId = $current[RelationBuilder::TREE_PARAM_PARENT_ID]; array_push($result, $current); } return $result; }
php
{ "resource": "" }
q13092
TreeBuilder.findAll
train
public function findAll($id) { $result = array(); $root = $this->findById($id); if ($root !== false) { $result = array_merge($result, array($root)); } return array_merge($result, $this->findParentNodesByChildId($id)); }
php
{ "resource": "" }
q13093
TreeBuilder.findById
train
public function findById($id) { $result = array(); $relations = $this->getRelations(); $items = $relations[RelationBuilder::TREE_PARAM_ITEMS]; if (isset($items[$id])) { return $items[$id]; } else { return false; } }
php
{ "resource": "" }
q13094
TreeBuilder.render
train
public function render(AbstractRenderer $renderer = null, $active = null) { if (is_null($renderer)) { $renderer = $this->getRenderer(); } return $renderer->render($this->getRelations(), $active); }
php
{ "resource": "" }
q13095
TreeBuilder.getRelations
train
private function getRelations() { if (is_null($this->relations)) { $builder = new RelationBuilder(); $this->relations = $builder->build($this->data); } return $this->relations; }
php
{ "resource": "" }
q13096
TreeBuilder.findChildNodeWithKey
train
private function findChildNodeWithKey($parentId, $key) { $result = array(); $relations = $this->getRelations(); if (isset($relations[RelationBuilder::TREE_PARAM_PARENTS][$parentId])) { foreach ($relations[RelationBuilder::TREE_PARAM_PARENTS][$parentId] as $id) { // Current found node $node = $relations[RelationBuilder::TREE_PARAM_ITEMS][$id][$key]; $result = array_merge($result, $this->findChildNodeWithKey($id, $key)); $result[] = $node; } } return $result; }
php
{ "resource": "" }
q13097
Request.toProtobufRequest
train
public function toProtobufRequest() { $request = new \POGOProtos\Networking\Requests\Request(); $request->setRequestType($this->getType()); if (($message = $this->getMessage()) !== null) { $request->setRequestMessage($message->toStream()); } return $request; }
php
{ "resource": "" }
q13098
AbstractModule.loadArray
train
final protected function loadArray($file) { if (is_file($file)) { $array = include($file); if (is_array($array)) { return $array; } else { trigger_error(sprintf('Included file "%s" should return an array not %s', $file, gettype($array))); } } else { return array(); } }
php
{ "resource": "" }
q13099
AbstractModule.getConfig
train
final public function getConfig($key = null) { if (method_exists($this, 'getConfigData')) { if ($this->config === null) { $this->config = $this->getConfigData(); if (!is_array($this->config)) { throw new LogicException('Configuration provider should return an array'); } } if (!is_null($key)) { if (isset($this->config[$key])) { return $this->config[$key]; } else { trigger_error('Attempted to read non-existing configuration key'); } } else { return $this->config; } } else { throw new RuntimeException(sprintf( 'If you want to read configuration from modules, you should implement provideConfig() method that returns an array in %s', null )); } }
php
{ "resource": "" }