_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q2600
Media.getDimensions
train
private function getDimensions(\media_subdef $subdef) { $outWidth = $subdef->get_width(); $outHeight = $subdef->get_height() | $outWidth; $thumbnail_height = $subdef->get_height() > 0 ? $subdef->get_height() : 120; $thumbnail_width = $subdef->get_width() > 0 ? $subdef->get_width() : 120; $subdefRatio = 0; $thumbnailRatio = $thumbnail_width / $thumbnail_height; if ($outWidth > 0 && $outHeight > 0) { $subdefRatio = $outWidth / $outHeight; } if ($thumbnailRatio > $subdefRatio) { if ($outWidth > $thumbnail_width) { $outWidth = $thumbnail_width; } $outHeight = $outWidth / $thumbnail_width * $thumbnail_height; $top = ($outHeight - $outHeight) / 2; } else { if ($outHeight > $thumbnail_height) { $outHeight = $thumbnail_height; } $outWidth = $outHeight * $thumbnail_width / $thumbnail_height; $top = (($outHeight - $outHeight) / 2); } return [ 'width' => round($outWidth), 'height' => round($outHeight), 'top' => $top ]; }
php
{ "resource": "" }
q2601
Media.getVideoTextTrackContent
train
public function getVideoTextTrackContent(MediaInformation $media, $id) { $id = (int)$id; $record = $media->getResource()->get_record(); $videoTextTrack = false; if ($record->getType() === 'video') { $databox = $record->getDatabox(); $vttIds = []; // list available vtt ids foreach ($databox->get_meta_structure() as $meta) { if (preg_match('/^VideoTextTrack(.*)$/iu', $meta->get_name(), $foundParts)) { $vttIds[] = $meta->get_id(); } } // extract vtt content from ids foreach ($record->get_caption()->get_fields(null, true) as $field) { // if a category is matching, ensure it's vtt related if (!in_array($id, $vttIds) || $id !== $field->get_meta_struct_id()) { continue; } foreach ($field->get_values() as $value) { // get vtt raw content $videoTextTrack = $value->getValue(); } } } return $videoTextTrack; }
php
{ "resource": "" }
q2602
Maintenance.ignoreif
train
public static function ignoreif($callback) { if (is_callable($callback) === false) { throw new Exception('Invalid callback'); } App::on('init', function () use ($callback) { if ($callback()) { App::env('maintenance', false); } }); }
php
{ "resource": "" }
q2603
JDate.createFromFormat
train
public static function createFromFormat($format, $date, $tz = null) { if ($tz !== null) { $tz = static::safeCreateDateTimeZone($tz); } $instance = new static($tz); $instance->parseFormat($format, $date); return $instance; }
php
{ "resource": "" }
q2604
JDate.calculateYearInQuadCycle
train
private static function calculateYearInQuadCycle($year) { $yearInGrandCycle = static::calculateYearInGrandCycle($year); // static::FIRST_QUAD_CYCLE; $yearInQuadCycle = $yearInGrandCycle % static::FIRST_QUAD_CYCLE; if ((static::GRAND_CYCLE_LENGTH - static::SECOND_QUAD_CYCLE) < $yearInGrandCycle) { // static::SECOND_QUAD_CYCLE; $yearInQuadCycle = $yearInGrandCycle - (21 * static::FIRST_QUAD_CYCLE); } return $yearInQuadCycle; }
php
{ "resource": "" }
q2605
JDate.calculateYearInGrandCycle
train
private static function calculateYearInGrandCycle($year) { $grandCycle = static::calculateGrandCycle($year); if ($grandCycle < 0) { $year = (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH)) - $year; } elseif ($grandCycle > 0) { $year = $year - (static::GRAND_CYCLE_BEGINNING + ($grandCycle * static::GRAND_CYCLE_LENGTH)); } else { $year -= static::GRAND_CYCLE_BEGINNING; } $yearInGrandCycle = abs($year) + 1; return $yearInGrandCycle; }
php
{ "resource": "" }
q2606
JDate.calculateGrandCycle
train
private static function calculateGrandCycle($year) { $endOfFirstGrandCycle = static::GRAND_CYCLE_BEGINNING + static::GRAND_CYCLE_LENGTH; // by default we are in the first grand cycle $grandCycle = 0; if ($year < static::GRAND_CYCLE_BEGINNING) { $beginningYear = static::GRAND_CYCLE_BEGINNING; while ($year < $beginningYear) { $beginningYear -= static::GRAND_CYCLE_LENGTH; $grandCycle--; } } elseif ($year >= $endOfFirstGrandCycle) { $beginningYear = $endOfFirstGrandCycle; while ($year >= $beginningYear) { $beginningYear += static::GRAND_CYCLE_LENGTH; $grandCycle++; } } return $grandCycle; }
php
{ "resource": "" }
q2607
JDate.setYear
train
private function setYear($year) { //preventing duplication process if ($year == $this->year) { return; } $this->year = (int) $year; $maximumDayAvailable = static::getMonthLength($this->year, $this->month); if ($this->day > $maximumDayAvailable) { $this->day = $maximumDayAvailable; } }
php
{ "resource": "" }
q2608
JDate.setMonth
train
private function setMonth($month) { //preventing duplication process if ($month == $this->month) { return; } $yearToSet = $this->year; $monthToSet = $month; if ($monthToSet < 1) { $monthToSet = abs($monthToSet); $yearToSet--; $yearToSet -= floor($monthToSet / 12); $monthToSet = 12 - ($monthToSet % 12); } elseif ($monthToSet > 12) { $yearToSet += floor($monthToSet / 12); $monthToSet = ($month % 12); if ($monthToSet == 0) { $monthToSet = 12; $yearToSet--; } } $this->month = (int) $monthToSet; $this->setYear($yearToSet); }
php
{ "resource": "" }
q2609
JDate.setDay
train
private function setDay($day) { //preventing duplication process if ($day == $this->day) { return; } $maximumDayOfMonth = static::getMonthLength($this->month, $this->year); $dayToSet = $day; if ($dayToSet < 1) { $dayToSet = abs($dayToSet); while ($dayToSet > $maximumDayOfMonth) { $dayToSet -= $maximumDayOfMonth; $month = $this->month - 1; $this->setMonth($month); $maximumDayOfMonth = static::getMonthLength($this->month, $this->year); } $dayToSet = $maximumDayOfMonth - $dayToSet; $month = $this->month - 1; $this->setMonth($month); } elseif ($dayToSet > $maximumDayOfMonth) { while ($dayToSet > $maximumDayOfMonth) { $dayToSet -= $maximumDayOfMonth; $month = $this->month + 1; $this->setMonth($month); $maximumDayOfMonth = static::getMonthLength($this->month, $this->year); } } $this->day = (int) $dayToSet; }
php
{ "resource": "" }
q2610
JDate.year
train
public function year($value) { $this->setDate($value, $this->month, $this->day); return $this; }
php
{ "resource": "" }
q2611
JDate.setDate
train
public function setDate($year, $month, $day) { $this->setYear((int) $year); $this->setMonth((int) $month); $this->setDay((int) $day); $this->updateGeorgianFromJalali(); return $this; }
php
{ "resource": "" }
q2612
JDate.setTime
train
public function setTime($hour, $minute, $second = 0) { $this->carbon->setTime($hour, $minute, $second); return $this; }
php
{ "resource": "" }
q2613
JDate.updateJalaliFromGeorgian
train
private function updateJalaliFromGeorgian($force = false) { if ($this->converted && ! $force) { return; } list($year, $month, $day) = self::julian2jalali(self::georgian2julian($this->carbon->year, $this->carbon->month, $this->carbon->day)); $this->year = $year; $this->month = $month; $this->day = $day; // it tells that the jalali core is updated $this->converted = true; }
php
{ "resource": "" }
q2614
JDate.jalali2julian
train
protected static function jalali2julian($year, $month, $day) { $parsed = self::parseJalali($year); return self::georgian2julian($parsed['gYear'], 3, $parsed['march']) + ($month - 1) * 31 - self::division($month, 7) * ($month - 7) + $day - 1; }
php
{ "resource": "" }
q2615
JDate.julian2jalali
train
protected static function julian2jalali($julianDayNumber) { $gYear = self::julian2georgian($julianDayNumber)[0]; $year = $gYear - static::HEGIRA_STARTING_YEAR; $parsed = self::parseJalali($year); $jdn1f = self::georgian2julian($gYear, 3, $parsed['march']); // Find number of days that passed since 1 Farvardin. $passed = $julianDayNumber - $jdn1f; if ($passed >= 0) { if ($passed <= 185) { $month = 1 + self::division($passed, 31); $day = ($passed % 31) + 1; return [$year, $month, $day]; } else { $passed -= 186; } } else { $year -= 1; $passed += 179; if ($parsed['leap'] === 1) { $passed += 1; } } $month = 7 + self::division($passed, 30); $day = ($passed % 30) + 1; return [$year, $month, $day]; }
php
{ "resource": "" }
q2616
Document.fromArray
train
public function fromArray(array $data) { if (empty($data)) { throw new DomException('Array is empty', 2); } elseif (count($data) > 1) { throw new DomException('Root array accepts only a key', 2); } elseif (Helper::seq($data)) { throw new DomException('Document accpet only a node', 2); } if ($this->documentElement) { $this->removeChild($this->documentElement); } $this->enableRestoreInternal(true); $this->generate($this, $data); $this->raise($this->exceptionlevel); $this->enableRestoreInternal(false); }
php
{ "resource": "" }
q2617
Document.toJson
train
public function toJson($format = Document::MININAL, $options = 0) { $this->exceptionlevel = 4; $json = json_encode($this->toArray($format), $options); $this->exceptionlevel = 3; return $json; }
php
{ "resource": "" }
q2618
Document.toArray
train
public function toArray($type = Document::SIMPLE) { switch ($type) { case Document::MININAL: $this->simple = false; $this->complete = false; break; case Document::SIMPLE: $this->simple = true; break; case Document::COMPLETE: $this->complete = true; break; default: throw new DomException('Invalid type', 2); } return $this->getNodes($this->childNodes, true); }
php
{ "resource": "" }
q2619
Document.save
train
public function save($path, $format = Document::XML) { switch ($format) { case Document::XML: $format = 'saveXML'; break; case Document::HTML: $format = 'saveHTML'; break; case Document::JSON: $format = 'toJson'; break; default: throw new DomException('Invalid format', 2); } $tmp = Storage::temp($this->$format(), 'tmp', '~xml-'); if ($tmp === false) { throw new DomException('Can\'t create tmp file', 2); } elseif (copy($tmp, $path) === false) { throw new DomException('Can\'t copy tmp file to ' . $path, 2); } else { unlink($tmp); } }
php
{ "resource": "" }
q2620
Document.getNamespaces
train
public function getNamespaces(\DOMElement $element = null) { if ($this->xpath === null) { $this->xpath = new \DOMXPath($this); } if ($element === null) { $nodes = $this->xpath->query('namespace::*'); } else { $nodes = $this->xpath->query('namespace::*', $element); } $ns = array(); if ($nodes) { foreach ($nodes as $node) { $arr = $element->getAttribute($node->nodeName); if ($arr) { $ns[$node->nodeName] = $arr; } } $nodes = null; } return $ns; }
php
{ "resource": "" }
q2621
Document.query
train
public function query($selector, \DOMNode $context = null) { $this->enableRestoreInternal(true); if ($this->selector === null) { $this->selector = new Selector($this); } $nodes = $this->selector->get($selector, $context); $this->raise($this->exceptionlevel); $this->enableRestoreInternal(false); return $nodes; }
php
{ "resource": "" }
q2622
Document.first
train
public function first($selector, \DOMNode $context = null) { $this->exceptionlevel = 4; $nodes = $this->query($selector, $context); $this->exceptionlevel = 3; $node = $nodes->length ? $nodes->item(0) : null; $nodes = null; return $node; }
php
{ "resource": "" }
q2623
Slot.getCard
train
public function getCard($index = 0, $failOnNoCardFound = false) { if (!array_key_exists($index, $this->reel['cards'])) { if ($failOnNoCardFound) { throw new Exception\NoCardFoundException(sprintf( "Cannot resolve a card value for the '%s' slot. (Perhaps you need to set a '_default' alias for the slot or the card of index 0 is missing from the slot's assigned reel?)", $this->name )); } switch ($this->undefinedCardResolution) { case UndefinedCardResolution::NO_CARD_FOUND_EXCEPTION: default: throw new Exception\NoCardFoundException(sprintf( "Card of index %d was not found in the slot `%s`.", $index, $this->name )); case UndefinedCardResolution::DEFAULT_CARD: return $this->getDefaultCard(); case UndefinedCardResolution::FALLBACK_CARD: return $this->getFallbackCard(); case UndefinedCardResolution::BLANK_CARD: return ''; // End Switch } } return $this->reel['cards'][$index]; }
php
{ "resource": "" }
q2624
Slot.getCardByAlias
train
public function getCardByAlias($alias) { if (!array_key_exists($alias, $this->aliases)) { throw new Exception\NoSuchAliasException(sprintf('Alias "%s" has not been assigned to any cards.', $alias)); } return $this->getCard($this->aliases[$alias]); }
php
{ "resource": "" }
q2625
FrontMatter.FrontMatter
train
function FrontMatter($input) { if (!$this->startsWith($input, $this->yaml_separator)) { # No front matter # Store Content in Final array $final['content'] = $input; # Return Final array return $final; } # Explode Seperators. At most, make three pieces out of the input file $document = explode($this->yaml_separator,$input, 3); switch( sizeof($document) ) { case 0: case 1: // Empty document $front_matter = ""; $content = ""; break; case 2: # Only front matter given $front_matter = $document[1]; $content = ""; break; default: # Normal document $front_matter = $document[1]; $content = $document[2]; } # Parse YAML try { $final = Yaml::parse($front_matter); } catch (ParseException $e) { printf("Unable to parse the YAML string: %s", $e->getMessage()); } # Store Content in Final array $final['content'] = $content; # Return Final array return $final; }
php
{ "resource": "" }
q2626
FrontMatter.Read
train
protected function Read($file) { # Open File $fh = fopen($file, 'r'); $fileSize = filesize($file); if(!empty($fileSize)) { # Read Data $data = fread($fh, $fileSize); # Fix Data Stream to be the exact same format as PHP's strings $data = str_replace(array("\r\n", "\r", "\n"), "\n", $data); } else { $data = ''; } # Close File fclose($fh); # Return Data return $data; }
php
{ "resource": "" }
q2627
Helper.parseVersion
train
public static function parseVersion($version) { if (preg_match('#^(\d+)\.(\d+)\.(\d+)(\-([\w.\-]+)|)$#', $version, $match)) { return (object) array( 'major' => $match[1], 'minor' => $match[2], 'patch' => $match[3], 'extra' => empty($match[5]) ? null : $match[5] ); } return false; }
php
{ "resource": "" }
q2628
Helper.toAscii
train
public static function toAscii($text) { $encode = mb_detect_encoding($text, mb_detect_order(), true); return 'ASCII' === $encode ? $text : iconv($encode, 'ASCII//TRANSLIT//IGNORE', $text); }
php
{ "resource": "" }
q2629
Helper.capitalize
train
public static function capitalize($text, $delimiter = '-', $glue = '') { return implode($glue, array_map('ucfirst', explode($delimiter, strtolower($text)))); }
php
{ "resource": "" }
q2630
Helper.extract
train
public static function extract($path, $items) { $paths = explode('.', $path); foreach ($paths as $value) { if (self::iterable($items) && array_key_exists($value, $items)) { $items = $items[$value]; } else { return false; } } return $items; }
php
{ "resource": "" }
q2631
Storage.resolve
train
public static function resolve($path) { if (empty($path)) { return false; } $path = Uri::canonpath($path); if ($path . '/' === self::path() || strpos($path, self::path()) === 0) { return $path; } return self::path() . $path; }
php
{ "resource": "" }
q2632
Storage.autoclean
train
public static function autoclean($path, $time = -1) { $path = self::resolve($path); if ($path !== false && is_dir($path) && ($dh = opendir($path))) { if ($time < 0) { $time = App::env('appdata_expires'); } $expires = REQUEST_TIME - $time; $path .= '/'; while (false !== ($file = readdir($dh))) { $current = $path . $file; if (is_file($current) && filemtime($current) < $expires) { unlink($current); } } closedir($dh); $dh = null; } }
php
{ "resource": "" }
q2633
Storage.put
train
public static function put($path, $data = null, $flags = null) { $path = self::resolve($path); if ($path === false) { return false; } $data = is_numeric($data) === false && !$data ? '' : $data; if (is_file($path) && !$data) { return true; } $flags = $flags ? $flags : FILE_APPEND|LOCK_EX; return self::createFolder(dirname($path)) && file_put_contents($path, $data, $flags) !== false; }
php
{ "resource": "" }
q2634
Storage.remove
train
public static function remove($path) { $path = self::resolve($path); return $path && is_file($path) && unlink($path); }
php
{ "resource": "" }
q2635
Storage.removeFolder
train
public static function removeFolder($path) { $path = self::resolve($path); return $path && is_dir($path) && self::rrmdir($path); }
php
{ "resource": "" }
q2636
Storage.rrmdir
train
private static function rrmdir($path) { $path .= '/'; foreach (array_diff(scandir($path), array('..', '.')) as $file) { $current = $path . $file; if (is_dir($current)) { if (self::rrmdir($current) === false) { return false; } } elseif (unlink($current) === false) { return false; } } return rmdir($path); }
php
{ "resource": "" }
q2637
Session.commit
train
public function commit($unlock = true) { if (empty($this->insertions) && empty($this->deletions)) { return null; } $this->lock(); $data = ''; rewind($this->handle); $data = trim(stream_get_contents($this->handle)); if ($data !== '') { $data = unserialize($data); $this->data = $this->insertions + $data; $data = null; foreach ($this->deletions as $key => $value) { unset($this->data[$key]); } } else { $this->data = $this->insertions; } $this->insertions = array(); $this->deletions = array(); $this->write(); if ($unlock) { flock($this->handle, LOCK_UN); } $this->iterator = new \ArrayIterator($this->data); }
php
{ "resource": "" }
q2638
Session.read
train
private function read() { $this->lock(); $data = ''; rewind($this->handle); $data = trim(stream_get_contents($this->handle)); if ($data !== '') { $this->data = unserialize($data); $data = null; } flock($this->handle, LOCK_UN); $this->iterator = new \ArrayIterator($this->data); }
php
{ "resource": "" }
q2639
Session.write
train
private function write() { ftruncate($this->handle, 0); rewind($this->handle); fwrite($this->handle, serialize($this->data)); }
php
{ "resource": "" }
q2640
Form.setup
train
public static function setup($byType, array $attributes) { if (0 !== preg_match('#^(' . self::$alloweds . '|select|form)$#', $type)) { self::$preAttrs[$byType] = $attributes; } }
php
{ "resource": "" }
q2641
Form.comboRange
train
public static function comboRange($name, $low, $high, $step = null, $value = null, array $attributes = array()) { $range = $step !== null ? range($low, $high, $step) : range($low, $high); $range = array_combine($range, $range); return self::combo($name, $range, $value, $attributes); }
php
{ "resource": "" }
q2642
Form.combo
train
public static function combo($name, array $options, $value = null, array $attributes = array()) { $input = self::setAttr($attributes, '<select{{attr}}>', $name, 'select'); foreach ($options as $key => $val) { $input .= '<option value="' . self::entities($val) . '"'; if ($value === $val) { $input .= ' selected'; } $input .= '>' . $key . '</option>'; } return $input . '</select>'; }
php
{ "resource": "" }
q2643
Form.input
train
public static function input($type, $name, $value = null, array $attributes = array()) { if ($type === 'textarea') { $input = '<textarea{{attr}}>'; if ($value !== null) { $input .= self::entities($value); } $input .= '</textarea>'; } elseif (preg_match('#^(' . self::$alloweds . ')$#', $type)) { $input = '<input type="' . $type . '" value="'; if ($value !== null) { $input .= self::entities($value); } $input .= '"{{attr}}' . self::$useXhtml . '>'; } else { throw new Exception('Invalid type'); } return self::setAttr($attributes, $input, $name, $type); }
php
{ "resource": "" }
q2644
Form.setAttr
train
private static function setAttr(array $attributes, $field, $name, $type) { $attrs = ''; if (in_array($type, array_keys(self::$preAttrs))) { $attributes = self::$preAttrs[$type] + $attributes; } if ($name !== null) { $attributes = array( 'name' => $name ) + $attributes; } if ($type !== 'select' && $type !== 'textarea' && $type !== 'form') { $attributes = array( 'type' => $type ) + $attributes; } foreach ($attributes as $key => $val) { $attrs .= ' ' . $key . '="' . self::entities($val) . '"'; } return str_replace('{{attr}}', $attrs, $field); }
php
{ "resource": "" }
q2645
SeoPatternHelper.isCallbackPattern
train
protected static function isCallbackPattern($patternKey) { $patternKeyPrefix = self::getPatternKeyPrefix($patternKey); $patternPrefixesOptions = self::getFunctionalPatternPrefixesOptions(); return ArrayHelper::keyExists($patternKeyPrefix, $patternPrefixesOptions); }
php
{ "resource": "" }
q2646
SeoPatternHelper.replace
train
public static function replace($patternString, $model) { //$patternString = '%%model_title%% %%sep%% %%appParam_contactEmail%% %%viewParam_titleSeparator%% %%appConfig_name%%'; $replacedString = ''; $patterns = self::findPatterns($patternString); $replacements = []; foreach ($patterns as $patternKey) { if (self::isCallbackPattern($patternKey)) { $replacement = self::callbackRetrievedStaticFunction($patternKey, $model); } if (self::isSeparatorPattern($patternKey)) { $replacement = self::retrieveSeparator(); } // Replacement retrievals can return null if no replacement can be determined, root those outs. if (isset($replacement)) { $patternKey = self::addPatternDelimeter($patternKey); $replacements[$patternKey] = $replacement; } unset($replacement); } // Do the actual replacements. $replacedString = (is_array($replacements) && $replacements !== []) ? str_replace(array_keys($replacements), array_values($replacements), $patternString) : $patternString; $replacedString = self::sanitizeReplacedString($replacedString); return $replacedString; }
php
{ "resource": "" }
q2647
SeoPatternHelper.findPatterns
train
protected static function findPatterns($patternString) { $patternString = self::sanitizePatternString($patternString); $patternRegExp = self::getPatternRegExp(); return (preg_match_all($patternRegExp, $patternString, $patternsMatches)) ? $patternsMatches[1] : []; }
php
{ "resource": "" }
q2648
SeoPatternHelper.callbackRetrievedStaticFunction
train
protected static function callbackRetrievedStaticFunction($patternKey, $model) { $patternPrefixesOptions = self::getFunctionalPatternPrefixesOptions(); $patternKeyPrefix = self::getPatternKeyPrefix($patternKey); $patternKeyValue = self::getPatternKeyValue($patternKey); $patternPrefixFunctionName = ArrayHelper::getValue($patternPrefixesOptions, $patternKeyPrefix); if (!method_exists(__CLASS__, $patternPrefixFunctionName)) { throw new InvalidConfigException('"'.__CLASS__.'" does not exist function with name "'.$patternPrefixFunctionName.'"'); } return call_user_func([__CLASS__, $patternPrefixFunctionName], $patternKeyValue, $model); }
php
{ "resource": "" }
q2649
SeoPatternHelper.retrieveAppConfigValue
train
public static function retrieveAppConfigValue($patternKeyValue, $model) { return (property_exists(Yii::$app, $patternKeyValue) || Yii::$app->canGetProperty($patternKeyValue)) ? Yii::$app->{$patternKeyValue} : ''; }
php
{ "resource": "" }
q2650
SeoPatternHelper.retrieveViewParamValue
train
public static function retrieveViewParamValue($patternKeyValue, $model) { return ArrayHelper::getValue(Yii::$app->view->params, $patternKeyValue); }
php
{ "resource": "" }
q2651
SeoPatternHelper.retrieveSeparator
train
public static function retrieveSeparator() { $separatorViewParamKey = self::SEPARATOR_VIEW_PARAMETER_KEY; return (ArrayHelper::keyExists($separatorViewParamKey, Yii::$app->view->params)) ? Yii::$app->view->params[$separatorViewParamKey] : self::SEPARATOR_DEFAULT; }
php
{ "resource": "" }
q2652
ExtendedUriTrait.getStandardPort
train
public function getStandardPort() { $scheme = $this->getScheme(); if (isset(self::$standardPorts[$scheme])) { return self::$standardPorts[$scheme]; } return null; }
php
{ "resource": "" }
q2653
ExtendedUriTrait.getUsername
train
public function getUsername() { $info = $this->getUserInfo(); $username = strstr($info, ':', true); return rawurldecode($username === false ? $info : $username); }
php
{ "resource": "" }
q2654
ExtendedUriTrait.getPassword
train
public function getPassword() { $password = strstr($this->getUserInfo(), ':'); return $password === false ? '' : rawurldecode(substr($password, 1)); }
php
{ "resource": "" }
q2655
ExtendedUriTrait.getIpAddress
train
public function getIpAddress() { $pattern = new UriPattern(); $pattern->matchHost($this->getHost(), $match); if (isset($match['IPv4address'])) { return $match['IPv4address']; } elseif (isset($match['IP_literal'])) { return preg_replace('/^\\[(v[^.]+\\.)?([^\\]]+)\\]$/', '$2', $match['IP_literal']); } return null; }
php
{ "resource": "" }
q2656
ExtendedUriTrait.getTopLevelDomain
train
public function getTopLevelDomain() { if ($this->getIpAddress() !== null) { return ''; } $host = rawurldecode($this->getHost()); $tld = strrchr($host, '.'); if ($tld === '.') { $host = substr($host, 0, -1); $tld = strrchr($host, '.'); } return $tld === false ? $host : substr($tld, 1); }
php
{ "resource": "" }
q2657
ExtendedUriTrait.getPathExtension
train
public function getPathExtension() { $segments = $this->getPathSegments(); $filename = array_pop($segments); $extension = strrchr($filename, '.'); if ($extension === false) { return ''; } return substr($extension, 1); }
php
{ "resource": "" }
q2658
Theme.getName
train
final public function getName(): string { try { $reflexionConstant = new ReflectionClassConstant($this, 'NAME'); $this->name = $reflexionConstant->getValue(); } catch (Exception $e) { } return $this->name; }
php
{ "resource": "" }
q2659
Theme.getDescription
train
final public function getDescription(): string { try { $reflexionConstant = new ReflectionClassConstant($this, 'DESCRIPTION'); $this->description = $reflexionConstant->getValue(); } catch (Exception $e) { } return $this->description; }
php
{ "resource": "" }
q2660
Theme.getPreview
train
public function getPreview(): ?string { $array = glob($this->getPath() . '/assets/images/preview.{jpg,jpeg,png,gif}', GLOB_BRACE); if (isset($array[0])) { return sprintf('/themes/%s/images/%s', $this->shortName, (new SplFileInfo($array[0]))->getBasename()); } return null; }
php
{ "resource": "" }
q2661
Config.doPathValidate
train
public function doPathValidate(string $pathValue = null, $isWritable = true) { if ($pathValue != null) { if (!is_dir($pathValue)) { throw new ConfigSettingFailException("`{$pathValue}` does NOT existed", '400'); } if ($isWritable == true) { if (!is_writable($pathValue)) { throw new ConfigSettingFailException("`{$pathValue}`is NOT writable", '400'); } } } }
php
{ "resource": "" }
q2662
Uri.encodepath
train
public static function encodepath($text, $type = null) { $text = preg_replace('#[`\'"\^~{}\[\]()]#', '', $text); $text = preg_replace('#[\n\s\/\p{P}]#u', '-', $text); if ($type === self::UNICODE) { $text = preg_replace('#[^\d\p{L}\p{N}\-]#u', '', $text); } elseif ($type === self::ASCII) { $text = preg_replace('#[^\d\p{L}\-]#u', '', $text); $text = self::encodepath($text); } else { $text = Helper::toAscii($text); $text = preg_replace('#[^a-z\d\-]#i', '', $text); } return trim(preg_replace('#--+#', '-', $text), '-'); }
php
{ "resource": "" }
q2663
Uri.normalize
train
public static function normalize($url) { $u = parse_url(preg_replace('#^file:/+([a-z]+:)#i', '$1', $url)); if ($u === false) { return $url; } if (empty($u['scheme'])) { $u = null; return false; } $scheme = strtolower($u['scheme']); if (strlen($scheme) > 1) { $normalized = $scheme . '://'; } else { $normalized = strtoupper($scheme) . ':'; } if (isset($u['user'])) { $normalized .= $u['user']; $normalized .= isset($u['pass']) ? (':' . $u['pass']) : ''; $normalized .= '@'; } if (isset($u['host'])) { if (in_array($scheme, static::$defaultSchemes)) { $host = urldecode($u['host']); $normalized .= mb_strtolower($host, mb_detect_encoding($host)); } else { $normalized .= $u['host']; } } if (isset($u['port']) && !in_array($scheme . ':' . $u['port'], static::$defaultPorts)) { $normalized .= ':' . $u['port']; } if (empty($u['path']) || $u['path'] === '/') { $normalized .= '/'; } else { $normalized .= '/' . ltrim(self::canonpath($u['path']), '/'); } if (isset($u['query'])) { $normalized .= self::canonquery($u['query'], '?'); } if (isset($u['fragment'])) { $normalized .= '#' . $u['fragment']; } $u = null; return $normalized; }
php
{ "resource": "" }
q2664
HydrationLogger.start
train
public function start($type) { if ($this->enabled) { $this->start = microtime(true); $this->hydrations[++$this->currentHydration]['type'] = $type; } }
php
{ "resource": "" }
q2665
HydrationLogger.stop
train
public function stop($resultNum, $aliasMap) { if ($this->enabled) { $this->hydrations[$this->currentHydration]['executionMS'] = microtime(true) - $this->start; $this->hydrations[$this->currentHydration]['resultNum'] = $resultNum; $this->hydrations[$this->currentHydration]['aliasMap'] = $aliasMap; } }
php
{ "resource": "" }
q2666
BenchMark.getRuntime
train
public function getRuntime(int $precision = 10) { if ($this->startTime == $this::NOT_INITIALIZED || $this->endTime == $this::NOT_INITIALIZED) { return FALSE; } $runTime = round($this->endTime - $this->startTime, $precision); return $runTime; }
php
{ "resource": "" }
q2667
BenchMark.checkNow
train
private function checkNow(string $storeVarName) : bool { $now = $this->microtimeFloat(); $this->{$storeVarName} = $now; return true; }
php
{ "resource": "" }
q2668
SqlServer._renderFunc
train
protected function _renderFunc(Func $func) { if($func->getName() != 'CONCAT') return parent::_renderFunc($func); $args = $func->getArgs(); array_walk($args, function(&$arg){ $arg = $this->_renderValue($arg); }); return implode(' + ', $args); }
php
{ "resource": "" }
q2669
ServicePacker.formatData
train
public function formatData(string $interface, string $version, string $method, array $params): array { return [ 'interface' => $interface, 'version' => $version, 'method' => $method, 'params' => $params, 'logid' => RequestContext::getLogid(), 'spanid' => RequestContext::getSpanid() + 1, ]; }
php
{ "resource": "" }
q2670
ContainerExtensionTrait.getNamespace
train
final public function getNamespace(): string { if (null === $this->namespace) { $pos = strrpos(static::class, '\\'); $this->namespace = false === $pos ? '' : substr(static::class, 0, $pos); } return $this->namespace; }
php
{ "resource": "" }
q2671
ContainerExtensionTrait.getContainerExtension
train
public function getContainerExtension(): ?ExtensionInterface { if (null === $this->extension) { $extension = $this->createContainerExtension(); if (null !== $extension) { if (!$extension instanceof ExtensionInterface) { throw new \LogicException(sprintf('Extension %s must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface.', \get_class($extension))); } // check naming convention $basename = str_replace(['Component', 'Module', 'Plugin'], ['', '', ''], $this->getIdentifier()); $expectedAlias = Container::underscore($basename); if ($expectedAlias != $extension->getAlias()) { throw new \LogicException(sprintf('Users will expect the alias of the default extension of a bundle to be the underscored version of the bundle name ("%s"). You can override "Bundle::getContainerExtension()" if you want to use "%s" or another alias.', $expectedAlias, $extension->getAlias())); } $this->extension = $extension; } } return $this->extension; }
php
{ "resource": "" }
q2672
Redirect.only
train
public static function only($path, $code = 302, $trigger = true) { self::$debuglvl = 3; self::to($path, $code, $trigger); Response::dispatch(); exit; }
php
{ "resource": "" }
q2673
Redirect.to
train
public static function to($path, $code = 302, $trigger = true) { $debuglvl = self::$debuglvl; self::$debuglvl = 2; if (headers_sent()) { throw new Exception('Headers already sent', $debuglvl); } elseif ($code < 300 || $code > 399) { throw new Exception('Invalid redirect HTTP status', $debuglvl); } elseif (empty($path)) { throw new Exception('Path is not defined', $debuglvl); } elseif (strpos($path, '/') === 0) { $path = Uri::root($path); } Response::status($code, $trigger); Response::putHeader('Location', $path); }
php
{ "resource": "" }
q2674
Redirect.back
train
public static function back($only = false, $trigger = true) { $referer = Request::header('referer'); if ($referer === false) { return false; } self::$debuglvl = 3; if ($only) { static::only($referer, 302, $trigger); } else { static::to($referer, 302, $trigger); } }
php
{ "resource": "" }
q2675
Group.domain
train
public function domain($domain) { if (empty($domain) || trim($domain) !== $domain) { throw new Exception('Invalid domain "' . $domain . '"', 2); } else { $this->domain = $domain; } return $this; }
php
{ "resource": "" }
q2676
Group.path
train
public function path($path) { if ($path !== '/' . trim($path, '/') . '/') { throw new Exception('Invalid path "' . $path . '", use like this /foo/', 2); } $this->path = $path; return $this; }
php
{ "resource": "" }
q2677
Group.secure
train
public function secure($level) { if ($level < 1 || $level > 3) { throw new Exception('Invalid security level', 2); } $this->levelSecure = (int) $level; return $this; }
php
{ "resource": "" }
q2678
Group.then
train
public function then(\Closure $callback) { if ($this->ready) { return null; } $this->ready = true; if (!$this->checkDomain() || !$this->checkPath() || !$this->checkSecurity()) { return null; } $oNS = parent::$prefixNS; $oPP = parent::$prefixPath; if ($this->ns) { parent::$prefixNS = $this->ns; } if ($this->path) { parent::$prefixPath = rtrim($this->currentPrefixPath, '/'); } call_user_func_array($callback, $this->arguments); parent::$prefixNS = $oNS; parent::$prefixPath = $oPP; }
php
{ "resource": "" }
q2679
Group.checkSecurity
train
protected function checkSecurity() { if (!$this->levelSecure || $this->levelSecure === self::BOTH) { return true; } $secure = Request::is('secure'); return ($this->levelSecure === self::SECURE && $secure) || ($this->levelSecure === self::NONSECURE && !$secure); }
php
{ "resource": "" }
q2680
Group.checkDomain
train
protected function checkDomain() { if ($this->domain === null) { return true; } if (self::$cachehost !== null) { $host = self::$cachehost; } else { $fhost = Request::header('Host'); $host = strstr($fhost, ':', true); $host = $host ? $host : $fhost; self::$cachehost = $host; } if ($host === $this->domain) { return true; } elseif ($host) { $re = Regex::parse($this->domain); if ($re === false || preg_match('#^' . $re . '$#', $host, $matches) === 0) { return false; } array_shift($matches); $this->arguments = array_merge($this->arguments, $matches); return true; } return false; }
php
{ "resource": "" }
q2681
Group.checkPath
train
protected function checkPath() { if ($this->path === null) { return true; } $pathinfo = \UtilsPath(); if (strpos($pathinfo, $this->path) === 0) { $this->currentPrefixPath = $this->path; return true; } else { $re = Regex::parse($this->path); if ($re !== false && preg_match('#^' . $re . '#', $pathinfo, $matches)) { $this->currentPrefixPath = $matches[0]; array_shift($matches); $this->arguments = array_merge($this->arguments, $matches); return true; } } return false; }
php
{ "resource": "" }
q2682
HornetEngine.getProperty
train
public function getProperty($name) { if (isset($this->$name)) { return $this->$name; } if (isset(static::$name)) { return static::$name; } return null; }
php
{ "resource": "" }
q2683
HornetEngine.underlineToUppercase
train
private function underlineToUppercase($str) { $fnc = function ($matches) { return strtoupper($matches[1]); }; $str = preg_replace_callback('/_+([a-z])/', $fnc, $str); return $str; }
php
{ "resource": "" }
q2684
HornetEngine.handleCtrlResult
train
private function handleCtrlResult($ret) { if ($ret === null) { return; } register_shutdown_function("closeResources"); if (isset($_GET['format']) && $_GET['format'] == 'xml') { header('Content-type: application/xml; charset=utf-8'); $ret = (object)$ret; echo $this->objectToXml($ret); die; } header('Content-type: application/json; charset=utf-8'); echo json_encode($ret); die; }
php
{ "resource": "" }
q2685
SlotMachine.initialize
train
private function initialize() { $this->undefinedCardResolution = isset($this->config['options']['undefined_card']) ? static::translateUndefinedCardResolution($this->config['options']['undefined_card']) : UndefinedCardResolution::DEFAULT_CARD; if (isset($this->config['options']['delimiter'])) { $this->delimiter = $this->config['options']['delimiter']; } foreach ($this->config['slots'] as $slotName => &$slotData) { $slotData['name'] = $slotName; if (is_string($slotData['reel'])) { $slotData['reel'] = $this->config['reels'][$slotData['reel']]; } if (!isset($slotData['nested'])) { $slotData['nested'] = array(); } $slotData['undefined_card'] = (!isset($slotData['undefined_card'])) ? $this->undefinedCardResolution : static::translateUndefinedCardResolution($slotData['undefined_card']); $this->offsetSet($slotName, function () use ($slotData) { return new Slot($slotData); }); } }
php
{ "resource": "" }
q2686
SlotMachine.interpolate
train
public static function interpolate($card, array $nestedCards = array(), array $delimiter = array('{', '}')) { if (2 > $tokens = count($delimiter)) { throw new \LengthException('Number of delimiter tokens too short. Method requires exactly 2.'); } // SlotMachine can still function with more than two delimiter tokens, // but will generate a warning. if ($tokens > 2) { trigger_error('Too many delimiter tokens given', E_USER_WARNING); } // build a replacement array with braces around the context keys $replace = array(); foreach ($nestedCards as $slot => $nestedCard) { $replace[$delimiter[0] . $slot . $delimiter[1]] = $nestedCard; } // interpolate replacement values into the message and return return strtr($card, $replace); }
php
{ "resource": "" }
q2687
SlotMachine.count
train
public function count() { $c = 0; // Using Pimple::$values will return the Closures, so instead get the // values in the container via ArrayAccess. foreach ($this->keys() as $valueName) { if ($this[$valueName] instanceof Slot) { ++$c; } } return $c; }
php
{ "resource": "" }
q2688
SlotMachine.all
train
public function all() { $all = array(); // Pimple::keys() foreach ($this->keys() as $slotName) { $all[$slotName] = $this->get($slotName); } return $all; }
php
{ "resource": "" }
q2689
Styles.addCss
train
public function addCss($handle = null, $src = null, $dependency = null, array $attributes = []) { // Set default media attribute if (!isset($attributes['media'])) { $attributes['media'] = 'all'; } return $this->styles[$handle] = new Css($handle, $src, $dependency, $attributes); }
php
{ "resource": "" }
q2690
Styles.removeCss
train
public function removeCss($handle = null) { if (is_null($handle)) { return $this->styles = []; } unset($this->styles[$handle]); }
php
{ "resource": "" }
q2691
Styles.renderStyles
train
public function renderStyles() { $this->loadPackageCss(); if (empty($this->styles)) { return PHP_EOL; } $assets = []; foreach ($this->sort($this->styles) as $handle => $data) { $assets[] = $this->getCss($handle); } return implode(PHP_EOL, $assets); }
php
{ "resource": "" }
q2692
ContainerCommands.containersStart
train
public function containersStart($container = NULL) { $this->validateConfig(); $this->title('Starting containers'); $command = $this->taskDockerComposeUp(); if ($container) { $this->limitComposeContainer($command, $container); } $command->file($this->dockerComposeFile) ->projectName($this->config->get('name')) ->detachedMode() ->run(); }
php
{ "resource": "" }
q2693
ContainerCommands.containersDestroy
train
public function containersDestroy() { $this->validateConfig(); $this->title('Destroying containers'); $this->taskDockerComposeDown() ->file($this->dockerComposeFile) ->projectName($this->config->get('name')) ->removeOrphans() ->rmi('all') ->run(); }
php
{ "resource": "" }
q2694
ContainerCommands.containersExec
train
public function containersExec($container, $execute_command) { $this->validateConfig(); $this->title('Executing in container: ' . $container, FALSE); $this->taskDockerComposeExecute() ->file($this->dockerComposeFile) ->projectName($this->config->get('name')) ->disablePseudoTty() ->setContainer(' ' . $container) ->exec($execute_command) ->run(); }
php
{ "resource": "" }
q2695
ContainerCommands.containersActive
train
public function containersActive() { $ps = $this->taskDockerComposePs() ->file($this->dockerComposeFile) ->projectName($this->config->get('name')) ->setVerbosityThreshold(VerbosityThresholdInterface::VERBOSITY_DEBUG) ->printOutput(FALSE) ->run() ->getMessage(); $this->say("$ps"); }
php
{ "resource": "" }
q2696
Cache.allowHeaders
train
protected static function allowHeaders() { if (self::$needHeaders !== null) { return self::$needHeaders; } return self::$needHeaders = Request::is('GET') || Request::is('HEAD'); }
php
{ "resource": "" }
q2697
Cache.match
train
public static function match($modified, $etag = null) { $modifiedsince = Request::header('If-Modified-Since'); if ($modifiedsince && preg_match('#^[a-z]{3}[,] \d{2} [a-z]{3} \d{4} \d{2}[:]\d{2}[:]\d{2} GMT$#i', $modifiedsince) !== 0 && strtotime($modifiedsince) == $modified) { return true; } $nonematch = Request::header('If-None-Match'); return $nonematch && trim($nonematch) === $etag; }
php
{ "resource": "" }
q2698
JsonDecoder.decode
train
public function decode(string $json) { // max depth is 0+ for json_encode(), and 1+ for json_decode() $result = json_decode($json, $this->decodeObjectAsArray, $this->maxDepth + 1, $this->options); $this->checkLastError(); return $result; }
php
{ "resource": "" }
q2699
UserPermission.grant
train
public function grant($flag) { if (is_string($flag) && defined('static::' . strtoupper($flag))) { $flag = constant('static::' . strtoupper($flag)); } $this->mask |= $flag; return $this; }
php
{ "resource": "" }