_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q6900
ConfigurationReader.createRepository
train
protected function createRepository(ObjectAccess $repository) { if ($repository->exists('packagist')) { return new PackagistRepository( $repository->get('packagist'), $repository->data() ); } $type = $repository->get('type'); if ('package' === $type) { $repository = new PackageRepository( $this->objectToArray($repository->get('package')), $this->objectToArray($repository->getDefault('options')), $repository->data() ); } else { $repository = new Repository( $type, $repository->getDefault('url'), $this->objectToArray($repository->getDefault('options')), $repository->data() ); } return $repository; }
php
{ "resource": "" }
q6901
ConfigurationReader.createProjectConfiguration
train
protected function createProjectConfiguration(stdClass $config = null) { if (null === $config) { return new ProjectConfiguration( null, null, null, null, null, null, null, $this->defaultCacheDir() ); } $configData = new ObjectAccess($config); $cacheDir = $configData->getDefault('cache-dir'); if (null === $cacheDir) { $cacheDir = $this->defaultCacheDir(); } return new ProjectConfiguration( $configData->getDefault('process-timeout'), $configData->getDefault('use-include-path'), $this->createInstallationMethod( $configData->getDefault('preferred-install') ), $configData->getDefault('github-protocols'), $this->objectToArray($configData->getDefault('github-oauth')), $configData->getDefault('vendor-dir'), $configData->getDefault('bin-dir'), $cacheDir, $configData->getDefault('cache-files-dir'), $configData->getDefault('cache-repo-dir'), $configData->getDefault('cache-vcs-dir'), $configData->getDefault('cache-files-ttl'), $configData->getDefault('cache-files-maxsize'), $configData->getDefault('prepend-autoloader'), $configData->getDefault('autoloader-suffix'), $configData->getDefault('optimize-autoloader'), $configData->getDefault('github-domains'), $configData->getDefault('notify-on-install'), $this->createVcsChangePolicy( $configData->getDefault('discard-changes') ), $configData->data() ); }
php
{ "resource": "" }
q6902
ConfigurationReader.defaultCacheDir
train
protected function defaultCacheDir() { $cacheDir = getenv('COMPOSER_CACHE_DIR'); if ($cacheDir) { return $cacheDir; } $home = getenv('COMPOSER_HOME'); $isWindows = defined('PHP_WINDOWS_VERSION_MAJOR'); if (!$home) { if ($isWindows) { if ($envAppData = getenv('APPDATA')) { $home = strtr($envAppData, '\\', '/') . '/Composer'; } } elseif ($envHome = getenv('HOME')) { $home = rtrim($envHome, '/') . '/.composer'; } } if ($home && !$cacheDir) { if ($isWindows) { if ($cacheDir = getenv('LOCALAPPDATA')) { $cacheDir .= '/Composer'; } else { $cacheDir = $home . '/cache'; } $cacheDir = strtr($cacheDir, '\\', '/'); } else { $cacheDir = $home . '/cache'; } } if (!$cacheDir) { return null; } return $cacheDir; }
php
{ "resource": "" }
q6903
ConfigurationReader.createInstallationMethod
train
protected function createInstallationMethod($method) { if (is_string($method)) { return InstallationMethod::memberByValue($method, false); } if (is_object($method)) { $methods = array(); foreach ($method as $project => $projectMethod) { $methods[$project] = InstallationMethod::memberByValue($projectMethod, false); } return $methods; } return null; }
php
{ "resource": "" }
q6904
ConfigurationReader.createVcsChangePolicy
train
protected function createVcsChangePolicy($policy) { if (null !== $policy) { $policy = VcsChangePolicy::memberByValue($policy, false); } return $policy; }
php
{ "resource": "" }
q6905
ConfigurationReader.createScripts
train
protected function createScripts(stdClass $scripts = null) { if (null !== $scripts) { $scriptsData = new ObjectAccess($scripts); $scripts = new ScriptConfiguration( $this->arrayize($scriptsData->getDefault('pre-install-cmd')), $this->arrayize($scriptsData->getDefault('post-install-cmd')), $this->arrayize($scriptsData->getDefault('pre-update-cmd')), $this->arrayize($scriptsData->getDefault('post-update-cmd')), $this->arrayize($scriptsData->getDefault('pre-status-cmd')), $this->arrayize($scriptsData->getDefault('post-status-cmd')), $this->arrayize($scriptsData->getDefault('pre-package-install')), $this->arrayize($scriptsData->getDefault('post-package-install')), $this->arrayize($scriptsData->getDefault('pre-package-update')), $this->arrayize($scriptsData->getDefault('post-package-update')), $this->arrayize($scriptsData->getDefault('pre-package-uninstall')), $this->arrayize($scriptsData->getDefault('post-package-uninstall')), $this->arrayize($scriptsData->getDefault('pre-autoload-dump')), $this->arrayize($scriptsData->getDefault('post-autoload-dump')), $this->arrayize($scriptsData->getDefault('post-root-package-install')), $this->arrayize($scriptsData->getDefault('post-create-project-cmd')), $scriptsData->data() ); } return $scripts; }
php
{ "resource": "" }
q6906
ConfigurationReader.createArchiveConfiguration
train
protected function createArchiveConfiguration(stdClass $archive = null) { if (null !== $archive) { $archiveData = new ObjectAccess($archive); $archive = new ArchiveConfiguration( $archiveData->getDefault('exclude'), $archiveData->data() ); } return $archive; }
php
{ "resource": "" }
q6907
ConfigurationReader.objectToArray
train
protected function objectToArray(stdClass $data = null) { if (null !== $data) { $data = (array) $data; foreach ($data as $key => $value) { if ($value instanceof stdClass) { $data[$key] = $this->objectToArray($value); } } } return $data; }
php
{ "resource": "" }
q6908
Template.execute
train
final function execute() { //parse content first, to allow for any ADDTEMPLATE items $content = $this->parseContent($this->data['bodycontent']); if( !$this->getLayoutClass() ){ throw new \Exception('No layout class defined.'); } $layoutClass = $this->getLayoutClass(); $layout = new $layoutClass($this->getSkin(), $this); //set up standard content zones //head element (including opening body tag) $layout->addHTMLTo('head', $this->html('headelement') ); //the logo image defined in LocalSettings $layout->addHTMLTo('logo', $this->data['logopath']); $layout->addHTMLTo('prepend:body', $this->html( 'prebodyhtml' )); //the article title if($this->showTitle){ $layout->addHTMLTo('content-container.class', 'has-title'); $layout->addHTMLTo('title-html', $this->data['title']); } //article content $layout->addHTMLTo('content-html', $content); //the site notice if( !empty($this->data['sitenotice'])){ $layout->addHTMLTo('site-notice', $this->data['sitenotice']); } //the site tagline, if there is one if($this->showTagline){ $layout->addHTMLTo('content-container.class', 'has-tagline'); $layout->addHTMLTo('tagline', $this->getMsg('tagline') ); } $breadcrumbTrees = $this->breadcrumbs(); $layout->addTemplateTo('breadcrumbs', 'breadcrumbs', array('trees' => $breadcrumbTrees) ); // if(\Skinny::hasContent('toc')){ // $layout->addHTMLTo('toc', (\Skinny::getContent('toc')[0]['html'])); // } // if ( $this->data['dataAfterContent'] ) { // $layout->addHTMLTo('append:content', $this->data['dataAfterContent']); // } //the contents of Mediawiki:Sidebar // $layout->addTemplate('classic-sidebar', 'classic-sidebar', array( // 'sections'=>$this->data['sidebar'] // )); // //list of language variants // $layout->addTemplate('language-variants', 'language-variants', array( // 'variants'=>$this->data['language_urls'] // )); //page footer $layout->addHookTo('footer-links', array($this,'getFooterLinks')); $layout->addHookTo('footer-icons', array($this,'getFooterIcons')); //mediawiki needs this to inject script tags after the footer $layout->addHookTo('append:body', array($this,'afterFooter')); $this->data['pageLanguage'] = $this->getSkin()->getTitle()->getPageViewLanguage()->getCode(); //allow skins to set up before render $this->initialize(); echo $layout->render(); // $this->printTrail(); }
php
{ "resource": "" }
q6909
Template.transclude
train
function transclude($string){ echo $GLOBALS['wgParser']->parse('{{'.$string.'}}', $this->getSkin()->getRelevantTitle(), new ParserOptions)->getText(); }
php
{ "resource": "" }
q6910
Template.parseContent
train
public function parseContent( $html ){ $pattern = '~<p>ADDTEMPLATE\(([\w_:-]*)\):([\w_-]+):ETALPMETDDA<\/p>~m'; if( preg_match_all($pattern, $html, $matches, PREG_SET_ORDER) ){ foreach($matches as $match){ //if a zone is specified, attach the template if(!empty($match[1])){ $this->getLayout()->addTemplateTo($match[1], $match[2]); $html = str_replace($match[0], '', $html); }else{ //otherwise inject the template inline into the wikitext $html = str_replace($match[0], $this->getLayout()->renderTemplate($match[2]), $html); } } } return $html; }
php
{ "resource": "" }
q6911
ResolverExecutor.arrayToObject
train
private function arrayToObject(array $data, FieldsAwareDefinitionInterface $definition) { $class = null; if ($definition instanceof ClassAwareDefinitionInterface) { $class = $definition->getClass(); } //normalize data foreach ($data as $fieldName => &$value) { if (!$definition->hasField($fieldName)) { continue; } $fieldDefinition = $definition->getField($fieldName); $value = $this->normalizeValue($value, $fieldDefinition->getType()); } unset($value); //instantiate object if (class_exists($class)) { $object = new $class(); } else { $object = $data; } //populate object foreach ($data as $key => $value) { if (!$definition->hasField($key)) { continue; } $fieldDefinition = $definition->getField($key); if (\is_array($value) && $this->endpoint->hasType($fieldDefinition->getType())) { $childType = $this->endpoint->getType($fieldDefinition->getType()); if ($childType instanceof FieldsAwareDefinitionInterface) { $value = $this->arrayToObject($value, $childType); } } $this->setObjectValue($object, $fieldDefinition, $value); } return $object; }
php
{ "resource": "" }
q6912
AfricasTalkingGateway.getUserData
train
public function getUserData() { $username = $this->_username; $this->_requestUrl = self::USER_DATA_URL.'?username='.$username; $this->executeGet(); if ( $this->_responseInfo['http_code'] == self::HTTP_CODE_OK ) { $responseObject = json_decode($this->_responseBody); return $responseObject->UserData; } throw new AfricasTalkingGatewayException($this->_responseBody); }
php
{ "resource": "" }
q6913
MGP25.processAllMessages
train
private function processAllMessages() { $processed = []; $receivers = $this->receivers(); $messages = $this->manager->getMessages(); foreach ($receivers as $receiver) { foreach ($messages as $index => $message) { $this->composition($receiver, $message); $id = $this->sendMessage($receiver, $message); $copy = new stdClass(); $copy->id = $id; $copy->type = $message->type; $copy->sender = $this->account['number']; $copy->nickname = $this->account['nickname']; $copy->to = implode(', ', (array) $receiver); $copy->message = $message; if(isset($message->file) && !$message->hash) { $copy->message->hash = $messages[$index]->hash = base64_encode(hash_file("sha256", $message->file, true)); } foreach ($this->manager->getInjectedVars() as $key => $value) { $copy->$key = $value; } $processed[] = $copy; } } $this->broadcast = false; $this->manager->clear(); return $processed; }
php
{ "resource": "" }
q6914
MGP25.sendMessage
train
private function sendMessage($receiver, $message) { $id = null; switch ($message->type) { case 'text': $id = $this->broadcast ? $this->gateway()->sendBroadcastMessage($receiver, $message->message) : $this->gateway()->sendMessage($receiver, $message->message); break; case 'image': $id = $this->broadcast ? $this->gateway()->sendBroadcastImage($receiver, $message->file, false, $message->filesize, $message->hash, $message->caption) : $this->gateway()->sendMessageImage($receiver, $message->file, false, $message->filesize, $message->hash, $message->caption); break; case 'audio': $id = $this->broadcast ? $this->gateway()->sendBroadcastAudio($receiver, $message->file, false, $message->filesize, $message->hash) : $this->gateway()->sendMessageAudio($receiver, $message->file, false, $message->filesize, $message->hash); break; case 'video': $id = $this->broadcast ? $this->gateway()->sendBroadcastVideo($receiver, $message->file, false, $message->filesize, $message->hash, $message->caption) : $this->gateway()->sendMessageVideo($receiver, $message->file, false, $message->filesize, $message->hash, $message->caption); break; case 'location': $id = $this->broadcast ? $this->gateway()->sendBroadcastLocation($receiver, $message->longitude, $message->latitude, $message->caption, $message->url) : $this->gateway()->sendMessageLocation($receiver, $message->longitude, $message->latitude, $message->caption, $message->url); break; case 'vcard': $id = $this->broadcast ? $this->gateway()->sendBroadcastVcard($receiver, $message->name, $message->vcard->show()) : $this->gateway()->sendVcard($receiver, $message->name, $message->vcard->show()); break; default: break; } while ($this->gateway()->pollMessage()); return $id; }
php
{ "resource": "" }
q6915
MGP25.receivers
train
private function receivers() { if(count($this->manager->getReceivers()) <= 10) { return $this->manager->getReceivers(); } $this->broadcast = true; $receivers = []; $allReceivers = $this->manager->getReceivers(); while (count($allReceivers)) { $target = []; $count = 1; while ($count <= $this->config['broadcast-limit'] && count($allReceivers)) { $target[] = array_shift($allReceivers); $count++; } $receivers[] = $target; } return $receivers; }
php
{ "resource": "" }
q6916
MGP25.composition
train
private function composition($receiver, stdClass $message) { if(!$this->broadcast) { $this->typing($receiver); sleep($this->manager->composition($message)); $this->paused($receiver); } }
php
{ "resource": "" }
q6917
MGP25.connectAndLogin
train
public function connectAndLogin() { if(!$this->connected) { $account = $this->config["default"]; $this->whatsProt->connect(); $this->whatsProt->loginWithPassword($this->password); $this->whatsProt->sendGetClientConfig(); $this->whatsProt->sendGetServerProperties(); $this->whatsProt->sendGetGroups(); $this->whatsProt->sendGetBroadcastLists(); $this->whatsProt->sendGetPrivacyBlockedList(); $this->whatsProt->sendAvailableForChat($this->config["accounts"][$account]['nickname']); $this->connected = true; } }
php
{ "resource": "" }
q6918
MGP25.logoutAndDisconnect
train
public function logoutAndDisconnect() { if($this->connected) { // Adds some delay defore disconnect sleep(rand(1, 2)); $this->offline(); $this->whatsProt->disconnect(); $this->connected = false; } }
php
{ "resource": "" }
q6919
NewsHolder.getCMSFields
train
public function getCMSFields() { $fields = parent::getCMSFields(); $modes = array( '' => 'No filing', 'day' => '/Year/Month/Day', 'month' => '/Year/Month', 'year' => '/Year' ); $fields->addFieldToTab('Root.Main', new DropdownField('FilingMode', _t('NewsHolder.FILING_MODE', 'File into'), $modes), 'Content'); $fields->addFieldToTab('Root.Main', new DropdownField('FileBy', _t('NewsHolder.FILE_BY', 'File by'), array('Published' => 'Published', 'Created' => 'Created')), 'Content'); $fields->addFieldToTab('Root.Main', new CheckboxField('PrimaryNewsSection', _t('NewsHolder.PRIMARY_SECTION', 'Is this a primary news section?'), true), 'Content'); $fields->addFieldToTab('Root.Main', new DropdownField('OrderBy', _t('NewsHolder.ORDER_BY', 'Order by'), array('OriginalPublishedDate' => 'Published', 'Created' => 'Created')), 'Content'); $fields->addFieldToTab('Root.Main', new DropdownField('OrderDir', _t('NewsHolder.ORDER_DIR', 'Order direction'), array('DESC' => 'Descending date', 'ASC' => 'Ascending date')), 'Content'); $this->extend('updateNewsHolderCMSFields', $fields); return $fields; }
php
{ "resource": "" }
q6920
NewsHolder.Articles
train
public function Articles($number=null) { if (!$number) { $number = $this->numberToDisplay; } $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0; if ($start < 0) { $start = 0; } $articles = null; $filter = null; if ($this->PrimaryNewsSection) { // get all where the holder = me $filter = array('NewsSectionID' => $this->ID); } else { $subholders = $this->SubSections(); if ($subholders) { $subholders->push($this); } else { $subholders = null; } if ($subholders && $subholders->Count()) { $ids = $subholders->column('ID'); $filter = array('ParentID' => $ids); } else { $filter = array('ParentID' => (int) $this->ID); } } $orderBy = strlen($this->OrderBy) ? $this->OrderBy : 'OriginalPublishedDate'; $dir = strlen($this->OrderDir) ? $this->OrderDir : 'DESC'; if (!in_array($dir, array('ASC', 'DESC'))) { $dir = 'DESC'; } $articles = NewsArticle::get()->filter($filter)->sort(array($orderBy => $dir))->limit($number, $start); $entries = PaginatedList::create($articles); $entries->setPaginationFromQuery($articles->dataQuery()->query()); return $entries; }
php
{ "resource": "" }
q6921
NewsHolder.SubSections
train
public function SubSections($allChildren=true) { $subs = null; $childHolders = NewsHolder::get()->filter('ParentID', $this->ID); if ($childHolders && $childHolders->count()) { $subs = new ArrayList(); foreach ($childHolders as $holder) { $subs->push($holder); if ($allChildren === true) { // see if there's any children to include $subSub = $holder->SubSections(); if ($subSub) { $subs->merge($subSub); } } } } return $subs; }
php
{ "resource": "" }
q6922
NewsHolder.getPartitionedHolderForArticle
train
public function getPartitionedHolderForArticle($article) { if ($this->FileBy == 'Published' && $article->OriginalPublishedDate) { $date = $article->OriginalPublishedDate; } else if ($this->hasField($this->FileBy)) { $field = $this->FileBy; $date = $this->$field; } else { $date = $article->Created; } $year = date('Y', strtotime($date)); $month = date('M', strtotime($date)); $day = date('d', strtotime($date)); $yearFolder = $this->dateFolder($year); if (!$yearFolder) { throw new Exception("Failed retrieving folder"); } if ($this->FilingMode == 'year') { return $yearFolder; } $monthFolder = $yearFolder->dateFolder($month); if (!$monthFolder) { throw new Exception("Failed retrieving folder"); } if ($this->FilingMode == 'month') { return $monthFolder; } $dayFolder = $monthFolder->dateFolder($day); if (!$dayFolder) { throw new Exception("Failed retrieving folder"); } return $dayFolder; }
php
{ "resource": "" }
q6923
NewsHolder.TotalChildArticles
train
public function TotalChildArticles($number = null) { if (!$number) { $number = $this->numberToDisplay; } $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0; if ($start < 0) { $start = 0; } $articles = NewsArticle::get('NewsArticle', '', '"OriginalPublishedDate" DESC, "ID" DESC', '', $start . ',' . $number) ->filter(array('ID' => $this->getDescendantIDList())); $entries = PaginatedList::create($articles); $entries->setPaginationFromQuery($articles->dataQuery()->query()); return $entries; }
php
{ "resource": "" }
q6924
TypeAutoLoader.autoloadTypes
train
public function autoloadTypes() { //loaded and static if (self::$loaded) { return; } if (!$this->kernel->isDebug() && $this->loadFromCacheCache()) { self::$loaded = true; return; } self::$loaded = true; foreach ($this->kernel->getBundles() as $bundle) { $path = $bundle->getPath().'/Type'; if (file_exists($path)) { $this->registerBundleTypes($path, $bundle->getNamespace()); } } if (Kernel::VERSION_ID >= 40000) { $path = $this->kernel->getRootDir().'/Type'; if (file_exists($path)) { $this->registerBundleTypes($path, 'App'); } } $this->saveCache(); }
php
{ "resource": "" }
q6925
TypeAutoLoader.registerBundleTypes
train
protected function registerBundleTypes($path, $namespace) { $finder = new Finder(); foreach ($finder->in($path)->name('/Type.php$/')->getIterator() as $file) { $className = preg_replace('/.php$/', null, $file->getFilename()); if ($file->getRelativePath()) { $subNamespace = str_replace('/', '\\', $file->getRelativePath()); $fullyClassName = $namespace.'\\Type\\'.$subNamespace.'\\'.$className; } else { $fullyClassName = $namespace.'\\Type\\'.$className; } if (class_exists($fullyClassName)) { $ref = new \ReflectionClass($fullyClassName); if ($ref->isSubclassOf(Type::class) && $ref->isInstantiable()) { $requiredParams = false; foreach ($ref->getConstructor()->getParameters() as $parameter) { if ($parameter->getClass() && $parameter->getClass()->implementsInterface(DefinitionInterface::class)) { continue 2; } } if ($requiredParams) { $error = sprintf('The graphql type defined in class "%s" is not instantiable because has some required parameters in the constructor.', $fullyClassName); throw new \LogicException($error); } /** @var Type $instance */ $instance = $ref->newInstance(); TypeRegistry::addTypeMapping($instance->name, $fullyClassName); } } } }
php
{ "resource": "" }
q6926
TimeUtil.dateTimeToTimePoint
train
private function dateTimeToTimePoint(DateTime $date) { // missing or offset only timezone? correct to UTC if (!$date->getTimezone() instanceof DateTimeZone || preg_match('#^[+-]{1}[0-9]{2}:?[0-9]{2}$#', $date->getTimezone()->getName())) { $date->setTimezone(new DateTimeZone('UTC')); } try { // DateTime::createFromFormat() will create an invalid DateTimeZone object when the timezone is an offset // (-05:00, for example) instead of a named timezone. By recreating the DateTimeZone object, we can expose // this problem and ensure that a valid DateTimeZone object is always set. $timezone = new DateTimeZone($date->getTimezone()->getName()); } catch (Exception $e) { // @codeCoverageIgnoreStart $date->setTimezone(new DateTimeZone('UTC')); // @codeCoverageIgnoreEnd } return new TimePoint( (int) $date->format('Y'), (int) $date->format('m'), (int) $date->format('d'), (int) $date->format('H'), (int) $date->format('i'), (int) $date->format('s'), $date->getTimezone()->getName(), (int) $date->format('u') ); }
php
{ "resource": "" }
q6927
TimeUtil.dateIntervalToIntervalSpec
train
private function dateIntervalToIntervalSpec(DateInterval $interval) { $date = sprintf('%uY%uM%uD', $interval->y, $interval->m, $interval->d); $time = sprintf('%uH%uM%uS', $interval->h, $interval->i, $interval->s); // build extra spec $extra = ''; if ($interval->invert) { $extra .= 'I'; } if ($interval->days) { $extra .= $interval->days . 'D'; } if (strlen($extra) > 0) { $extra = '-' . $extra; } return sprintf('P%sT%s%s', $date, $time, $extra); }
php
{ "resource": "" }
q6928
StaticTranslator.sortPluralizedCompare
train
protected static function sortPluralizedCompare($a, $b) { if ($a == $b) { return 0; } $rangeA = explode(':', $a); $rangeB = explode(':', $b); // Both range starts provided. if (isset($rangeA[0]) && isset($rangeB[0])) { return strcmp($rangeA[0], $rangeB[0]); } // Only second range has a starting point. if (!isset($rangeA[0]) && isset($rangeB[0])) { return -1; } // Only first range has a starting point. if (isset($rangeA[0]) && !isset($rangeB[0])) { return 1; } // Both are an open start range. if (isset($rangeA[1]) && isset($rangeB[1])) { return strcmp($rangeA[1], $rangeB[1]); } // Only second range is open => First is first. if (!isset($rangeA[1]) && isset($rangeB[1])) { return 1; } // Only first range is open => Second is first. if (isset($rangeA[1]) && !isset($rangeB[1])) { return -1; } // Just here to make the IDEs happy - is already handled above as early exit point. return 0; }
php
{ "resource": "" }
q6929
StaticTranslator.setValuePluralized
train
public function setValuePluralized($string, $value, $min = null, $max = null, $domain = null, $locale = null) { if (!$domain) { $domain = 'default'; } if (!$locale) { $locale = 'default'; } if (!(isset($this->values[$locale]) && is_array($this->values[$locale]))) { $this->values[$locale] = array(); } if (!(isset($this->values[$locale][$domain]) && is_array($this->values[$locale][$domain]))) { $this->values[$locale][$domain] = array(); } if (isset($this->values[$locale][$domain][$string]) && is_array($this->values[$locale][$domain][$string])) { $lang = $this->values[$locale][$domain][$string]; } else { // NOTE: we kill any value previously stored as there is no way to tell which value to use. $lang = array(); } $lang[$this->determineKey($min, $max)] = $value; $lang = $this->sortPluralized($lang); $this->setValue($string, $lang, $domain, $locale); return $this; }
php
{ "resource": "" }
q6930
StaticTranslator.determineKey
train
protected function determineKey($min, $max) { $minGiven = ($min !== null); $maxGiven = ($max !== null); if (!$minGiven && !$maxGiven) { throw new InvalidArgumentException('You must specify a valid value for min, max or both.'); } if ($minGiven && !$maxGiven) { // Open end range. return $min . ':'; } elseif (!$minGiven && $maxGiven) { // Open start range. return ':' . $max; } if ($min === $max) { // Exact number. return $min; } // Full defined range. return $min . ':' . $max; }
php
{ "resource": "" }
q6931
StaticTranslator.setValue
train
public function setValue($string, $value, $domain = null, $locale = null) { if (!$domain) { $domain = 'default'; } if (!$locale) { $locale = 'default'; } if (!(isset($this->values[$locale]) && is_array($this->values[$locale]))) { $this->values[$locale] = array(); } if (!(isset($this->values[$locale][$domain]) && is_array($this->values[$locale][$domain]))) { $this->values[$locale][$domain] = array(); } $this->values[$locale][$domain][$string] = $value; return $this; }
php
{ "resource": "" }
q6932
StaticTranslator.getValue
train
protected function getValue($string, $domain, $locale) { if (!$domain) { $domain = 'default'; } if (!$locale) { $locale = 'default'; } if (!isset($this->values[$locale][$domain][$string])) { return $string; } return $this->values[$locale][$domain][$string]; }
php
{ "resource": "" }
q6933
ThisData.getOrCreateEndpoint
train
private function getOrCreateEndpoint($endpoint) { if (!array_key_exists($endpoint, $this->endpoints)) { if (!array_key_exists($endpoint, self::$endpointClassMap)) { throw new \Exception(sprintf('Unknown endpoint "%s"', $endpoint)); } $endpointClass = self::$endpointClassMap[$endpoint]; $this->endpoints[$endpoint] = $this->createEndpoint($endpointClass); } return $this->endpoints[$endpoint]; }
php
{ "resource": "" }
q6934
SolrSearchService.getQueryBuilder
train
public function getQueryBuilder($type='default') { return isset($this->queryBuilders[$type]) ? Injector::inst()->create($this->queryBuilders[$type]) : Injector::inst()->create($this->queryBuilders['default']); }
php
{ "resource": "" }
q6935
SolrSearchService.index
train
public function index($dataObject, $stage=null, $fieldBoost = array()) { $document = $this->convertObjectToDocument($dataObject, $stage, $fieldBoost); if ($document) { try { $this->getSolr()->addDocument($document); $this->getSolr()->commit(); // optimize every so often if (mt_rand(0, 100) == 42) { $this->getSolr()->optimize(); } } catch (Exception $ie) { SS_Log::log($ie, SS_Log::ERR); } } }
php
{ "resource": "" }
q6936
SolrSearchService.objectToFields
train
protected function objectToFields($dataObject) { $ret = array(); $fields = Config::inst()->get($dataObject->ClassName, 'db'); $fields['Created'] = 'SS_Datetime'; $fields['LastEdited'] = 'SS_Datetime'; $ret['ClassName'] = array('Type' => 'Varchar', 'Value' => $dataObject->class); $ret['SS_ID'] = array('Type' => 'Int', 'Value' => $dataObject->ID); foreach ($fields as $name => $type) { if (preg_match('/^(\w+)\(/', $type, $match)) { $type = $match[1]; } // Just index everything; the query can figure out what to exclude... ! $value = $dataObject->$name; if ($type == 'MultiValueField' && $value instanceof MultiValueField) { $value = $value->getValues(); } $ret[$name] = array('Type' => $type, 'Value' => $value); } $rels = Config::inst()->get($dataObject->ClassName, 'has_one'); if($rels) foreach(array_keys($rels) as $rel) { $ret["{$rel}ID"] = array( 'Type' => 'ForeignKey', 'Value' => $dataObject->{$rel . "ID"} ); } if ($dataObject->hasMethod('additionalSolrValues')) { $extras = $dataObject->invokeWithExtensions('additionalSolrValues'); if ($extras && is_array($extras)) { foreach ($extras as $add) { foreach ($add as $k => $v) { $ret[$k] = array( 'Type' => $this->mapper->mapValueToType($k, $v), 'Value' => $v, ); } } } } return $ret; }
php
{ "resource": "" }
q6937
SolrSearchService.unindex
train
public function unindex($typeOrId) { $id = $typeOrId; if (is_object($typeOrId)) { $type = $typeOrId->class; // get_class($type); $id = $type . '_' . $typeOrId->ID; } else { $id = self::RAW_DATA_KEY . $id; } try { // delete all published/non-published versions of this item, so delete _* too $this->getSolr()->deleteByQuery('id:' . $id); $this->getSolr()->deleteByQuery('id:' . $id .'_*'); $this->getSolr()->commit(); } catch (Exception $ie) { SS_Log::log($ie, SS_Log::ERR); } }
php
{ "resource": "" }
q6938
SolrSearchService.parseSearch
train
public function parseSearch($query, $type='default') { // if there's a colon in the search, assume that the user is doing a custom power search if (strpos($query, ':')) { return $query; } if (isset($this->queryBuilders[$type])) { return $this->queryBuilders[$type]->parse($query); } $lucene = implode(':' . $query . ' OR ', self::$default_query_fields) . ':' . $query; return $lucene; }
php
{ "resource": "" }
q6939
SolrSearchService.query
train
public function query($query, $offset = 0, $limit = 20, $params = array(), $andWith = array()) { if (is_string($query)) { $builder = $this->getQueryBuilder('default'); $builder->baseQuery($query); $query = $builder; } // be very specific about the subsite support :). if (ClassInfo::exists('Subsite')) { $query->andWith('SubsiteID_i', Subsite::currentSubsiteID()); } // add the stage details in - we should probably use an extension mechanism for this, // but for now this will have to do. @TODO Refactor this.... $stage = Versioned::current_stage(); if (!$stage && !(isset($params['ignore_stage']) && $params['ignore_stage'])) { // default to searching live content only $stage = 'Live'; } if(!isset($params['ignore_stage']) || !$params['ignore_stage']) { $query->addFilter('SS_Stage_ms', $stage); } if($andWith) { foreach($andWith as $field => $value) { $query->andWith($field, $value); } } $extraParams = $query->getParams(); $params = array_merge($params, $extraParams); $query = $query->toString(); $response = null; $rawResponse = null; $solr = $this->getSolr(); $key = null; if ($this->cache) { $key = md5($query.$offset.$limit.serialize($params)); if ($rawResponse = $this->cache->load($key)) { $response = new Apache_Solr_Response( $rawResponse, // we fake the following headers... :o array( 'HTTP/1.1 200 OK', 'Content-Type: text/plain; charset=utf-8' ), $solr->getCreateDocuments(), $solr->getCollapseSingleValueArrays() ); } } if (!$response) { // Execute the query and log any errors on failure, always displaying the search results to the user. if ($this->isConnected()) { try { $response = $this->getSolr()->search($query, $offset, $limit, $params); } catch(Exception $e) { SS_Log::log($e, SS_Log::WARN); } } } $queryParams = new stdClass(); $queryParams->offset = $offset; $queryParams->limit = $limit; $queryParams->params = $params; $results = new SolrResultSet($query, $response, $queryParams, $this); if ($this->cache && !$rawResponse && $key && $response) { $this->cache->save($response->getRawResponse(), $key, array(), $this->cacheTime); } return $results; }
php
{ "resource": "" }
q6940
SolrSearchService.getFacetsForFields
train
public function getFacetsForFields($fields, $number=10) { if (!is_array($fields)) { $fields = array($fields); } return $this->query('*', 0, 1, array('facet' => 'true', 'facet.field' => $fields, 'facet.limit' => 10, 'facet.mincount' => 1)); }
php
{ "resource": "" }
q6941
SolrSearchService.getSolr
train
public function getSolr() { if (!$this->client) { if (!$this->solrTransport) { $this->solrTransport = new Apache_Solr_HttpTransport_Curl; } $this->client = new Apache_Solr_Service(self::$solr_details['host'], self::$solr_details['port'], self::$solr_details['context'], $this->solrTransport); } return $this->client; }
php
{ "resource": "" }
q6942
SolrSearchService.getAllSearchableFieldsFor
train
public function getAllSearchableFieldsFor($classNames) { $allfields = array(); foreach ($classNames as $className) { $fields = $this->getSearchableFieldsFor($className); $allfields = array_merge($allfields, $fields); } return $allfields; }
php
{ "resource": "" }
q6943
SolrSearchService.buildSearchableFieldCache
train
protected function buildSearchableFieldCache() { if (!$this->searchableCache) { $objects = DataObject::get('SolrTypeConfiguration'); if ($objects) { foreach ($objects as $obj) { $this->searchableCache[$obj->Title] = $obj->FieldMappings->getValues(); } } } return $this->searchableCache; }
php
{ "resource": "" }
q6944
SolrSearchService.getSolrFieldName
train
public function getSolrFieldName($field, $classNames = null) { if (!$classNames) { $classNames = Config::inst()->get('SolrSearch', 'default_searchable_types'); } if (!is_array($classNames)) { $classNames = array($classNames); } foreach ($classNames as $className) { if (!class_exists($className)) { continue; } $dummy = singleton($className); $fields = $this->objectToFields($dummy); if ($field == 'ID') { $field = 'SS_ID'; } if (isset($fields[$field])) { $configForType = $this->getSearchableFieldsFor($className); $hint = isset($configForType[$field]) ? $configForType[$field] : false; return $this->mapper->mapFieldNameFromType($field, $fields[$field]['Type'], $hint); } } }
php
{ "resource": "" }
q6945
SolrSchemaMapper.mapFieldNameFromType
train
public function mapFieldNameFromType($field, $type, $hint = '') { if (isset($this->solrFields[$field])) { return $this->solrFields[$field]; } if (strpos($type, '(')) { $type = substr($type, 0, strpos($type, '(')); } if ($hint && is_string($hint) && $hint != 'default') { return str_replace(':field', $field, $hint); } if ($pos = strpos($field, ':')) { $field = substr($field, 0, $pos); } // otherwise, lets use a generic field for it switch ($type) { case 'MultiValueField': { return $field . '_ms'; } case 'Text': case 'HTMLText': { return $field . '_t'; } case 'Date': case 'SS_Datetime': { return $field . '_dt'; } case 'Str': case 'Enum': { return $field . '_ms'; } case 'Attr': { return 'attr_' . $field; } case 'Double': case 'Decimal': case 'Currency': case 'Float': case 'Money': { return $field . '_f'; } case 'Int': case 'Integer': { return $field . '_i'; } case 'SolrGeoPoint': { return $field . '_p'; } case 'String': { return $field . '_s'; } case 'Varchar': default: { return $field . '_as'; } } }
php
{ "resource": "" }
q6946
SolrSchemaMapper.mapValueToType
train
public function mapValueToType($name, $value) { // just store as an untokenised string $type = 'String'; if (strpos($name, ':')) { list($name, $type) = explode(':', $name); return $type; } // or an array of strings if (is_array($value)) { $type = 'MultiValueField'; } if (is_double($value)) { return 'Double'; } if (is_int($value)) { return 'Int'; } return $type; }
php
{ "resource": "" }
q6947
SolrSchemaMapper.convertValue
train
public function convertValue($value, $type) { if (is_array($value)) { $newReturn = array(); foreach ($value as $v) { $newReturn[] = $this->convertValue($v, $type); } return $newReturn; } else { switch ($type) { case 'Date': case 'SS_Datetime': { // we don't want a complete iso8601 date, we want it // in UTC time with a Z at the end. It's okay, php's // strtotime will correctly re-convert this to the correct // timestamp, but this is how Solr wants things. // If we don't have a full DateTime stamp we won't remove any hours $hoursToRemove = date('Z'); $ts = strtotime($value); $tsHTR = $ts - $hoursToRemove; $date = date('Y-m-d\TH:i:s\Z', $tsHTR); return $date; } case 'HTMLText': { return strip_tags($value); } case 'SolrGeoPoint': { return $value->y . ',' . $value->x; } default: { return $value; } } } }
php
{ "resource": "" }
q6948
ObjectAccess.get
train
public function get($property) { if (!$this->exists($property)) { throw new UndefinedPropertyException($property); } return $this->data()->$property; }
php
{ "resource": "" }
q6949
TagFigInclude.fig_include
train
private function fig_include(Context $context) { $file = $this->includedFile; $realFilename = dirname($context->getFilename()).'/'.$file; //Create a sub-view, attached to the current element. $view = new View(); if ($context->view->getCachePath() && $context->view->getTemplatesRoot()) { $view->setCachePath($context->view->getCachePath(), $context->view->getTemplatesRoot()); } $view->loadFile($realFilename); //Parse the subview (build its own tree). $context->pushInclude($realFilename, $view->figNamespace); $view->parse(); // If the included template specifies a doctype, use it globally for our context. if ($view->getRootNode() instanceof ViewElementTag) { $doctype = $view->getRootNode()->getAttribute($context->figNamespace . 'doctype'); if ($doctype) { $context->setDoctype($doctype); } } $result = $view->getRootNode()->render($context); $context->popInclude(); return $result; }
php
{ "resource": "" }
q6950
SuperCMSUser.getUserDefaultLocation
train
public static function getUserDefaultLocation() { try { $user = self::getLoggedInUser(); if ($user->PrimaryLocation) { return $user->PrimaryLocation; } if ($user->Locations && $user->Locations->count()) { $user->PrimaryLocationID = $user->Locations[0]->UniqueIdentifier; $user->save(); return $user->PrimaryLocation; } } catch (NotLoggedInException $ex) { } $basket = Basket::getCurrentBasket(); if ($basket->Locations && $basket->Locations->count()) { if (isset($user)) { $user->PrimaryLocationID = $basket->Locations[0]; $user->save(); return $user->PrimaryLocation; } return $basket->Locations[0]; } return null; }
php
{ "resource": "" }
q6951
ResponseContext.theResponseIsGraphQLErrorWith
train
public function theResponseIsGraphQLErrorWith(string $message) { $this->assertResponseStatus(Response::HTTP_OK); //success GraphQL response should not contains errors if ($this->client->getGraphQL()) { if ($this->isValidGraphQLResponse() && $errors = $this->getGraphQLResponseError()) { $errorsStack = ''; foreach ($errors as $error) { $errorsStack .= $error->message."\n"; } Assert::assertContains($message, $errorsStack); } else { $this->graphQLContext->debugLastQuery(); throw new AssertionFailedError('The response is not the expected error response.'); } } }
php
{ "resource": "" }
q6952
UsersController.newPassword
train
public function newPassword($id = null) { $user = $this->Users->get($id, [ 'contain' => [] ]); $user->accessible('send_mail', true); // checkbox to send an e-mail if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { if ($user->send_mail) { $this->EmailListener->passwordConfirmation($user); } $this->Flash->success(__('The user has been saved.')); return $this->redirect($this->referer()); } else { $this->Flash->error(__('The password could not be saved. Please, try again.')); } } $this->set(compact('user')); $this->render(Configure::read('CM.AdminUserViews.newPassword')); }
php
{ "resource": "" }
q6953
UsersController.sendActivationMail
train
public function sendActivationMail($id = null) { $user = $this->Users->get($id, [ 'contain' => [] ]); $user->set('active', false); $user->set('activation_key', $this->Users->generateActivationKey()); if ($this->Users->save($user)) { $this->EmailListener->activation($user); $this->Flash->success(__('The e-mail has been sent.')); return $this->redirect($this->referer()); } else { $this->Flash->error(__('The e-mail could not be sent. Please, try again.')); } }
php
{ "resource": "" }
q6954
ImageShack.withCredentials
train
public function withCredentials($username, $password) { $this->cookie = null; $this->credentials = array('username' => $username, 'password' => $password); return $this; }
php
{ "resource": "" }
q6955
ImageShack.upload
train
public function upload($file, $format = 'json') { // Is this "file" a URL? $url = filter_var($file, FILTER_VALIDATE_URL) !== false; $data = array( 'key' => $this->key, 'format' => $format ); if ($url) { $data['url'] = $file; } else { $data['fileupload'] = $file; } if ($this->credentials) { $data['a_username'] = $this->credentials['username']; $data['a_password'] = $this->credentials['password']; } else if($this->cookie) { $data['cookie'] = $this->cookie; } return $this->post('https://post.imageshack.us/upload_api.php', $data); }
php
{ "resource": "" }
q6956
ObjectTypeAnnotationParser.copyFieldsFromInterface
train
protected function copyFieldsFromInterface(InterfaceDefinition $intDef, FieldsAwareDefinitionInterface $fieldsAwareDefinition) { foreach ($intDef->getFields() as $field) { if (!$fieldsAwareDefinition->hasField($field->getName())) { $newField = clone $field; $newField->addInheritedFrom($intDef->getName()); $fieldsAwareDefinition->addField($newField); } else { $fieldsAwareDefinition->getField($field->getName())->addInheritedFrom($intDef->getName()); } } }
php
{ "resource": "" }
q6957
ObjectTypeAnnotationParser.isExposed
train
protected function isExposed(ObjectDefinitionInterface $definition, $prop): bool { $exposed = $definition->getExclusionPolicy() === ObjectDefinitionInterface::EXCLUDE_NONE; if ($prop instanceof \ReflectionMethod) { $exposed = false; //implicit inclusion if ($this->getFieldAnnotation($prop, Annotation\Field::class)) { $exposed = true; } } if ($exposed && $this->getFieldAnnotation($prop, Annotation\Exclude::class)) { $exposed = false; } elseif (!$exposed && $this->getFieldAnnotation($prop, Annotation\Expose::class)) { $exposed = true; } /** @var Annotation\Field $fieldAnnotation */ if ($fieldAnnotation = $this->getFieldAnnotation($prop, Annotation\Field::class)) { $exposed = true; if ($fieldAnnotation->in) { $exposed = \in_array($definition->getName(), $fieldAnnotation->in); } elseif (($fieldAnnotation->notIn)) { $exposed = !\in_array($definition->getName(), $fieldAnnotation->notIn); } } return $exposed; }
php
{ "resource": "" }
q6958
ObjectTypeAnnotationParser.getFieldAnnotation
train
protected function getFieldAnnotation($prop, string $annotationClass) { if ($prop instanceof \ReflectionProperty) { return $this->reader->getPropertyAnnotation($prop, $annotationClass); } return $this->reader->getMethodAnnotation($prop, $annotationClass); }
php
{ "resource": "" }
q6959
VerifyEndpoint.verify
train
public function verify($ip, array $user, $userAgent = null, array $source = null, array $session = null, array $device = null) { $event = [ self::PARAM_IP => $ip ]; if (!is_null($userAgent)) { $event[self::PARAM_USER_AGENT] = $userAgent; } $event[self::PARAM_USER] = array_filter([ self::PARAM_USER__ID => $this->findValue(self::PARAM_USER__ID, $user), self::PARAM_USER__NAME => $this->findValue(self::PARAM_USER__NAME, $user), self::PARAM_USER__EMAIL => $this->findValue(self::PARAM_USER__EMAIL, $user), self::PARAM_USER__MOBILE => $this->findValue(self::PARAM_USER__MOBILE, $user), self::PARAM_USER__AUTHENTICATED => $this->findValue(self::PARAM_USER__AUTHENTICATED, $user), ]); if (!is_null($source)) { $event[self::PARAM_SOURCE] = array_filter([ self::PARAM_SOURCE__NAME => $this->findValue(self::PARAM_SOURCE__NAME, $source), self::PARAM_SOURCE__LOGO_URL => $this->findValue(self::PARAM_SOURCE__LOGO_URL, $source) ]); } // Add information about the session // First, the session ID if it's passed $event[self::PARAM_SESSION] = array_filter([ self::PARAM_SESSION__ID => $this->findValue(self::PARAM_SESSION__ID, $session) ]); // Then pull the TD cookie if its present if (isset($_COOKIE[ThisData::TD_COOKIE_NAME])) { $event[self::PARAM_SESSION][self::PARAM_SESSION__TD_COOKIE_ID] = $_COOKIE[ThisData::TD_COOKIE_NAME]; } // Then whether we expect the JS Cookie at all if ($this->configuration[Builder::CONF_EXPECT_JS_COOKIE]) { $event[self::PARAM_SESSION][self::PARAM_SESSION__TD_COOKIE_EXPECTED] = $this->configuration[Builder::CONF_EXPECT_JS_COOKIE]; } if (!is_null($device)) { $event[self::PARAM_DEVICE] = array_filter([ self::PARAM_DEVICE__ID => $this->findValue(self::PARAM_DEVICE__ID, $device) ]); } $response = $this->synchronousExecute('POST', ThisData::ENDPOINT_VERIFY, array_filter($event)); return json_decode($response->getBody(), TRUE); }
php
{ "resource": "" }
q6960
Whois.clean
train
public function clean($domain) { $domain = trim($domain); $domain = preg_replace('#^https?://#', '', $domain); if (substr(strtolower($domain), 0, 4) == "www.") $domain = substr($domain, 4); return $domain; }
php
{ "resource": "" }
q6961
Whois.lookup
train
public function lookup() { if ($this->ip) { $result = $this->lookupIp($this->ip); } else { $result = $this->lookupDomain($this->domain); } return $result; }
php
{ "resource": "" }
q6962
Whois.lookupDomain
train
public function lookupDomain($domain) { $serverObj = new Server(); $server = $serverObj->getServerByTld($this->tld); if (!$server) { throw new Exception("Error: No appropriate Whois server found for $domain domain!"); } $result = $this->queryServer($server, $domain); if (!$result) { throw new Exception("Error: No results retrieved from $server server for $domain domain!"); } else { while (strpos($result, "Whois Server:") !== false) { preg_match("/Whois Server: (.*)/", $result, $matches); $secondary = $matches[1]; if ($secondary) { $result = $this->queryServer($secondary, $domain); $server = $secondary; } } } return "$domain domain lookup results from $server server:\n\n" . $result; }
php
{ "resource": "" }
q6963
Whois.lookupIp
train
public function lookupIp($ip) { $results = array(); $continentServer = new Server(); foreach ($continentServer->getContinentServers() as $server) { $result = $this->queryServer($server, $ip); if ($result && !in_array($result, $results)) { $results[$server]= $result; } } $res = "RESULTS FOUND: " . count($results); foreach ($results as $server => $result) { $res .= "Lookup results for " . $ip . " from " . $server . " server: " . $result; } return $res; }
php
{ "resource": "" }
q6964
Whois.queryServer
train
public function queryServer($server, $domain) { $port = 43; $timeout = 10; $fp = @fsockopen($server, $port, $errno, $errstr, $timeout); if ( !$fp ) { throw new Exception("Socket Error " . $errno . " - " . $errstr); } // if($server == "whois.verisign-grs.com") $domain = "=".$domain; // whois.verisign-grs.com requires the equals sign ("=") or it returns any result containing the searched string. fputs($fp, $domain . "\r\n"); $out = ""; while (!feof($fp)) { $out .= fgets($fp); } fclose($fp); $res = ""; if ((strpos(strtolower($out), "error") === false) && (strpos(strtolower($out), "not allocated") === false)) { $rows = explode("\n", $out); foreach ($rows as $row) { $row = trim($row); if (($row != '') && ($row{0} != '#') && ($row{0} != '%')) { $res .= $row."\n"; } } } return $res; }
php
{ "resource": "" }
q6965
MGP25.getRegistrationClient
train
private function getRegistrationClient($number) { $file = $this->customPath ? $this->customPath . '/phone-id-' . $number . '.dat' : null; $registration = new Registration($number, $this->debug, $file); $this->listener->registerRegistrationEvents($registration); return $registration; }
php
{ "resource": "" }
q6966
Section.isAvailable
train
public function isAvailable(): bool { foreach ($this->items as $item) { if ($item->isVisible()) { return true; } } return false; }
php
{ "resource": "" }
q6967
Skin.ResourceLoaderRegisterModules
train
public static function ResourceLoaderRegisterModules( \ResourceLoader $rl ){ self::$_modulesRegistered = true; $rl->register( self::$modules ); return true; }
php
{ "resource": "" }
q6968
Skin.initPage
train
public function initPage( \OutputPage $out ){ parent::initPage( $out ); $out->addModules(self::$autoloadModules); }
php
{ "resource": "" }
q6969
Skin.setupSkinUserCss
train
function setupSkinUserCss( \OutputPage $out ) { parent::setupSkinUserCss( $out ); //TODO: load modules from parent of layout, too... $layoutClass = self::getLayoutClass(); $layoutTree = \Skinny::getClassAncestors($layoutClass); $styles = array('mediawiki.skinning.interface'); foreach ($layoutTree as $lc) { $styles = array_merge($styles, $lc::getHeadModules()); } $out->addModuleStyles( $styles ); }
php
{ "resource": "" }
q6970
Skin.addToBodyAttributes
train
public function addToBodyAttributes( $out, &$attrs){ $classes = array(); $layout = $this->getLayout(); $attrs['class'] .= ' sitename-'.strtolower(str_replace(' ','_',$GLOBALS['wgSitename'])); $layoutClass = self::getLayoutClass(); $layoutTree = \Skinny::getClassAncestors($layoutClass); $layoutNames = array_flip(self::$layouts); foreach ($layoutTree as $lc) { if (isset($layoutNames[$lc])) { $classes[] = 'layout-'.$layoutNames[$lc]; } } if( $GLOBALS['wgUser']->isLoggedIn() ){ $classes[] = 'user-loggedin'; }else{ $classes[] = 'user-anonymous'; } $attrs['class'] .= ' '.implode(' ',$classes); }
php
{ "resource": "" }
q6971
Skin.addLayout
train
public static function addLayout ($name, $className){ if (!class_exists($className)) { throw new \Exception('Invalid Layout class: '.$className); } static::$layouts[$name] = $className; self::addModules($className::getResourceModules()); }
php
{ "resource": "" }
q6972
Skin.addModules
train
public static function addModules ($modules=array(), $load=false){ if( static::$_modulesRegistered ){ throw new Exception('Skin is attempting to add modules after modules have already been registered.'); } if(empty($modules)){ return; } static::$modules += (array) $modules; if($load){ static::$autoloadModules += array_keys($modules); } }
php
{ "resource": "" }
q6973
Validator.validateIp
train
public function validateIp($ip) { $ipnums = explode(".", $ip); if (count($ipnums) != 4) { return false; } foreach($ipnums as $ipnum) { if (!is_numeric($ipnum) || ($ipnum > 255)) { return false; } } return $ip; }
php
{ "resource": "" }
q6974
E621.prepareRequestParams
train
private function prepareRequestParams(array $data) { $has_resource = false; $multipart = []; foreach ($data as $key => $value) { if (!is_array($value)) { $multipart[] = ['name' => $key, 'contents' => $value]; continue; } foreach ($value as $multiKey => $multiValue) { is_resource($multiValue) && $has_resource = true; $multiName = $key . '[' . $multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '') . ''; $multipart[] = ['name' => $multiName, 'contents' => (is_array($multiValue) ? reset($multiValue) : $multiValue)]; } } if ($has_resource) { return ['multipart' => $multipart]; } return ['form_params' => $data]; }
php
{ "resource": "" }
q6975
E621.debugLog
train
private function debugLog($message) { $this->debug_log_handler !== null && is_callable($this->debug_log_handler) && call_user_func($this->debug_log_handler, $message); }
php
{ "resource": "" }
q6976
E621.endDebugStream
train
private function endDebugStream() { if (is_resource($this->debug_log_stream_handle)) { rewind($this->debug_log_stream_handle); $this->debugLog('E621 API Verbose HTTP Request output:' . PHP_EOL . stream_get_contents($this->debug_log_stream_handle) . PHP_EOL); fclose($this->debug_log_stream_handle); $this->debug_log_stream_handle = null; } }
php
{ "resource": "" }
q6977
E621.setProgressHandler
train
public function setProgressHandler($progress_handler) { if ($progress_handler !== null && is_callable($progress_handler)) { $this->progress_handler = $progress_handler; } elseif ($progress_handler === null) { $this->progress_handler = null; } else { throw new \InvalidArgumentException('Argument "progress_handler" must be a callable'); } }
php
{ "resource": "" }
q6978
E621.setDebugLogHandler
train
public function setDebugLogHandler($debug_log_handler) { if ($debug_log_handler !== null && is_callable($debug_log_handler)) { $this->debug_log_handler = $debug_log_handler; } elseif ($debug_log_handler === null) { $this->debug_log_handler = null; } else { throw new \InvalidArgumentException('Argument "debug_log_handler" must be a callable'); } }
php
{ "resource": "" }
q6979
E621.login
train
public function login($login, $api_key) { if (empty($login) || !is_string($login)) { throw new \InvalidArgumentException('Argument "login" cannot be empty and must be a string'); } if (empty($login) || !is_string($api_key)) { throw new \InvalidArgumentException('Argument "api_key" cannot be empty and must be a string'); } $this->auth = [ 'login' => $login, 'password_hash' => $api_key, ]; }
php
{ "resource": "" }
q6980
Api.getClient
train
private function getClient(): Client { if (null !== $this->client) { return $this->client; } return $this->client = new Client( $this->config['carrier'], $this->config['key'], $this->config['cache'], $this->config['debug'] ); }
php
{ "resource": "" }
q6981
Basket.getCurrentBasket
train
public static function getCurrentBasket() { $settings = SuperCMSSession::singleton(); try { $user = SCmsLoginProvider::getLoggedInUser(); try { $basket = Basket::findLast(new AndGroup( [ new Equals('UserID', $user->UniqueIdentifier), new Not(new Equals('Status', self::STATUS_COMPLETED)) ] )); } catch (RecordNotFoundException $ex) { $basket = new Basket(); $basket->UserID = $user->UniqueIdentifier; $basket->save(); } if ($settings->basketId != $basket->UniqueIdentifier) { self::joinAnonymousBasketItemsToUserBasket($basket); self::updateSession($basket); } } catch (NotLoggedInException $ex) { try { $basket = new Basket($settings->basketId); } catch (RecordNotFoundException $ex) { $basket = new Basket(); $basket->save(); self::updateSession($basket); } } return $basket; }
php
{ "resource": "" }
q6982
Basket.markBasketPaid
train
public static function markBasketPaid(Basket $basket) { $basket->Status = Basket::STATUS_COMPLETED; $basket->save(); $session = SuperCMSSession::singleton(); $session->basketId = 0; $session->storeSession(); }
php
{ "resource": "" }
q6983
Listener.registerEvents
train
protected function registerEvents(WhatsApiEventsManager $manager) { foreach ($this->events as $event) { if (is_callable(array($this, $event))) { $manager->bind($event, [$this, $event]); } } return $this; }
php
{ "resource": "" }
q6984
RolesController.update
train
public function update(RoleProcessor $processor, $roles) { return $processor->update($this, Input::all(), $roles); }
php
{ "resource": "" }
q6985
Synchronizer.handle
train
public function handle() { $admin = $this->app->make('orchestra.role')->admin(); $this->acl->allow($admin->name, ['Manage Users', 'Manage Orchestra', 'Manage Roles', 'Manage Acl']); }
php
{ "resource": "" }
q6986
ContainerLoader.get
train
public function get(string $name): AbstractCommand { if (!$this->has($name)) { throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name)); } return $this->container->get($this->commandMap[$name]); }
php
{ "resource": "" }
q6987
ContainerLoader.has
train
public function has($name): bool { return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]); }
php
{ "resource": "" }
q6988
TypeExtensionsManager.getManager
train
static function getManager(?string $name = null): \Plasma\Types\TypeExtensionsManager { if($name === null) { if(!isset(static::$instances[static::GLOBAL_NAME])) { static::$instances[static::GLOBAL_NAME] = new static(); } return static::$instances[static::GLOBAL_NAME]; } if(isset(static::$instances[$name])) { return static::$instances[$name]; } throw new \Plasma\Exception('Unknown name'); }
php
{ "resource": "" }
q6989
TypeExtensionsManager.registerManager
train
static function registerManager(string $name, ?\Plasma\Types\TypeExtensionsManager $manager = null): void { if(isset(static::$instances[$name])) { throw new \Plasma\Exception('Name is already in use'); } if($manager === null) { $manager = new static(); } static::$instances[$name] = $manager; }
php
{ "resource": "" }
q6990
TypeExtensionsManager.encodeType
train
function encodeType($value, \Plasma\ColumnDefinitionInterface $column): \Plasma\Types\TypeExtensionResultInterface { $type = \gettype($value); if($type === 'double') { $type = 'float'; } if($type === 'object') { $classes = \array_merge( array(\get_class($value)), \class_parents($value), \class_implements($value) ); /** @var \Plasma\Types\TypeExtensionInterface $encoder */ foreach($this->classTypes as $key => $encoder) { if(\in_array($key, $classes, true)) { return $encoder->encode($value, $column); } } } /** @var \Plasma\Types\TypeExtensionInterface $encoder */ foreach($this->regularTypes as $key => $encoder) { if($type === $key) { return $encoder->encode($value, $column); } } if($this->enabledFuzzySearch) { /** @var \Plasma\Types\TypeExtensionInterface $encoder */ foreach($this->classTypes as $key => $encoder) { if($encoder->canHandleType($value, $column)) { return $encoder->encode($value, $column); } } /** @var \Plasma\Types\TypeExtensionInterface $encoder */ foreach($this->regularTypes as $key => $encoder) { if($encoder->canHandleType($value, $column)) { return $encoder->encode($value, $column); } } } throw new \Plasma\Exception('Unable to encode given value'); }
php
{ "resource": "" }
q6991
TypeExtensionsManager.decodeType
train
function decodeType($type, $value): \Plasma\Types\TypeExtensionResultInterface { if($type === null && $this->enabledFuzzySearch) { /** @var \Plasma\Types\TypeExtensionInterface $decoder */ foreach($this->dbTypes as $dbType => $decoder) { if($decoder->canHandleType($value, null)) { return $decoder->decode($value); } } } elseif(isset($this->dbTypes[$type])) { return $this->dbTypes[$type]->decode($value); } throw new \Plasma\Exception('Unable to decode given value'); }
php
{ "resource": "" }
q6992
ColumnDefinition.parseValue
train
function parseValue($value) { try { return \Plasma\Types\TypeExtensionsManager::getManager()->decodeType($this->type, $value)->getValue(); } catch (\Plasma\Exception $e) { /* Continue regardless of error */ } return $value; }
php
{ "resource": "" }
q6993
SolrSearchPermissionIndexExtension.updateQueryBuilder
train
public function updateQueryBuilder($builder) { // Make sure the extension requirements have been met before enabling the custom search index. if(SiteTree::has_extension('SolrIndexable') && SiteTree::has_extension('SiteTreePermissionIndexExtension') && ClassInfo::exists('QueuedJob')) { // Define the initial user permissions using the general public access flag. $groups = array( 'anyone' ); // Apply the logged in access flag and listing of groups for the current authenticated user. $user = Member::currentUser(); if($user) { // Don't restrict the search results for an administrator. if(Permission::checkMember($user, array('ADMIN', 'SITETREE_VIEW_ALL'))) { return; } $groups[] = 'logged-in'; foreach($user->Groups() as $group) { $groups[] = (string)$group->ID; } } // Apply this permission filter. $builder->andWith('Groups_ms', $groups); } }
php
{ "resource": "" }
q6994
GraphQLClient.sendQuery
train
public function sendQuery(): Response { $data = [ 'query' => $this->getGraphQL(), 'variables' => $this->getVariables(), ]; if ($this->operationName) { $data['operationName'] = $this->operationName; } $content = json_encode($data); $this->insulated = $this->config['insulated'] ?? false; $this->sendRequest(Request::METHOD_POST, $this->getEndpoint(), $this->getRequestsParameters(), [], $this->getServerParameters(), $content); return $this->response = $this->getResponse(); }
php
{ "resource": "" }
q6995
GraphQLClient.sendRequest
train
public function sendRequest($method, $uri, array $parameters = [], array $files = [], array $server = [], $content = null, $changeHistory = true) { set_error_handler( function ($level, $message, $errFile, $errLine) { if ($this->deprecationAdviser) { $this->deprecationAdviser->addWarning($message, $errFile, $errLine); } }, E_USER_DEPRECATED ); $result = parent::request($method, $uri, $parameters, $files, $server, $content, $changeHistory); restore_error_handler(); return $result; }
php
{ "resource": "" }
q6996
SocialShareUrl.getUrl
train
public function getUrl($service, $url, $params = []) { if (!empty($this->stubs[$service])) { $tokens = []; $params['url'] = $url; foreach ($this->tokens as $token) { $tokens['/{' . $token . '}/'] = urlencode( !empty($params[$token]) ? $params[$token] : '' ); } return preg_replace(array_keys($tokens), $tokens, $this->stubs[$service]); } }
php
{ "resource": "" }
q6997
NativeFunctionFactory.create
train
public function create($funcName) { $dirname = dirname(__FILE__).'/functions'; $filename = "$dirname/Function_$funcName.php"; if( !file_exists($filename) ) { return null; } require_once "$dirname/Function_$funcName.php"; $funcClassName = '\\figdice\\classes\\functions\\Function_'.$funcName; $reflection = new \ReflectionClass($funcClassName); /** @var FigFunction $function */ $function = $reflection->newInstance(); return $function; }
php
{ "resource": "" }
q6998
InvalidConfigurationException.buildMessage
train
protected function buildMessage(array $errors) { $errorList = array(); foreach ($errors as $error) { $errorList[] = sprintf( ' - [%s] %s', $error['property'], $error['message'] ); } return sprintf( "The supplied Composer configuration is invalid:\n%s", implode("\n", $errorList) ); }
php
{ "resource": "" }
q6999
SparkPostTransport.send
train
public function send(Email $email) { // Load SparkPost configuration settings $apiKey = $this->config('apiKey'); // Set up HTTP request adapter $adapter = new CakeHttpAdapter(new Client()); // Create SparkPost API accessor $sparkpost = new SparkPost($adapter, [ 'key' => $apiKey ]); // Pre-process CakePHP email object fields $from = (array) $email->from(); $sender = sprintf('%s <%s>', mb_encode_mimeheader(array_values($from)[0]), array_keys($from)[0]); $to = (array) $email->to(); $replyTo = $email->getReplyTo() ? array_values($email->getReplyTo())[0] : null; foreach ($to as $toEmail => $toName) { $recipients[] = ['address' => [ 'name' => mb_encode_mimeheader($toName), 'email' => $toEmail]]; } // Build message to send $message = [ 'from' => $sender, 'html' => empty($email->message('html')) ? $email->message('text') : $email->message('html'), 'text' => $email->message('text'), 'subject' => mb_decode_mimeheader($email->subject()), 'recipients' => $recipients ]; if ($replyTo) { $message['replyTo'] = $replyTo; } // Send message try { $sparkpost->transmission->send($message); } catch(APIResponseException $e) { // TODO: Determine if BRE is the best exception type throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)', $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription())); } }
php
{ "resource": "" }