_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10700 | TicketControllerExtension.TicketForm | train | public function TicketForm()
{
if ($this->owner->Tickets()->count() && $this->owner->getTicketsAvailable()) {
$ticketForm = new TicketForm($this->owner, 'TicketForm', $this->owner->Tickets(), $this->owner->dataRecord);
$ticketForm->setNextStep(CheckoutSteps::start());
return $ticketForm;
} else {
return null;
}
} | php | {
"resource": ""
} |
q10701 | TicketControllerExtension.WaitingListRegistrationForm | train | public function WaitingListRegistrationForm()
{
if (
$this->owner->Tickets()->count()
&& $this->owner->getTicketsSoldOut()
&& !$this->owner->getEventExpired()
) {
return new WaitingListRegistrationForm($this->owner, 'WaitingListRegistrationForm');
} else {
return null;
}
} | php | {
"resource": ""
} |
q10702 | HipChatHandler.getAlertColor | train | protected function getAlertColor($level)
{
switch (true) {
case $level >= Logger::ERROR:
return 'red';
case $level >= Logger::WARNING:
return 'yellow';
case $level >= Logger::INFO:
return 'green';
case $level == Logger::DEBUG:
return 'gray';
default:
return 'yellow';
}
} | php | {
"resource": ""
} |
q10703 | SonarTask.setConfig | train | private function setConfig(\Phalcon\Config $config) {
if(defined(CURRENT_TASK) === true) {
$this->taskName = CURRENT_TASK;
}
$this->config = $config->cli->{$this->taskName};
return $this;
} | php | {
"resource": ""
} |
q10704 | SonarTask.setLogger | train | private function setLogger() {
$config = $this->getConfig();
if($config->offsetExists('errors') === true && $config->errors === true) {
$this->logger = new FileAdapter($this->getConfig()->errorLog);
}
return $this;
} | php | {
"resource": ""
} |
q10705 | SonarTask.setSilentErrorHandler | train | public function setSilentErrorHandler() {
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
if (0 === error_reporting()) {
return false;
}
if($this->logger != null) {
// logging all warnings & notices
$this->getLogger()->log($errstr, Logger::CRITICAL);
}
});
} | php | {
"resource": ""
} |
q10706 | Cache.checkFile | train | private function checkFile(string &$file): bool
{
$file = "{$this->directory}/{$file}";
return file_exists($file) || (touch($file) && chmod($file, 0600));
} | php | {
"resource": ""
} |
q10707 | EntityMap.getKey | train | public function getKey($item, $return_all = false)
{
if ($return_all === true) {
return $this->getKeys();
}
if ($this->hasKey($item->getIdentifier())) {
return $item->getIdentifier();
}
return false;
} | php | {
"resource": ""
} |
q10708 | RecordHandler.getPlayerPosition | train | public function getPlayerPosition($login)
{
return isset($this->positionPerPlayer[$login]) ? $this->positionPerPlayer[$login] : null;
} | php | {
"resource": ""
} |
q10709 | RecordHandler.getPlayerRecord | train | public function getPlayerRecord($login)
{
return isset($this->recordsPerPlayer[$login]) ? $this->recordsPerPlayer[$login] : null;
} | php | {
"resource": ""
} |
q10710 | RecordHandler.loadForMap | train | public function loadForMap($mapUid, $nbLaps)
{
// Free old records from memory first.
foreach ($this->records as $record) {
$record->clearAllReferences(false);
unset($record);
}
foreach ($this->recordsPerPlayer as $record) {
$record->clearAllReferences(false);
unset($record);
}
RecordTableMap::clearInstancePool();
// Load them amm new.
$this->recordsPerPlayer = [];
$this->positionPerPlayer = [];
$this->currentMapUid = $mapUid;
$this->currentNbLaps = $nbLaps;
$this->records = $this->recordQueryBuilder
->getMapRecords($mapUid, $nbLaps, $this->getScoreOrdering(), $this->nbRecords->get());
$position = 1;
foreach ($this->records as $record) {
$this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
$this->positionPerPlayer[$record->getPlayer()->getLogin()] = $position++;
}
} | php | {
"resource": ""
} |
q10711 | RecordHandler.loadForPlayers | train | public function loadForPlayers($mapUid, $nbLaps, $logins)
{
$logins = array_diff($logins, array_keys($this->recordsPerPlayer));
if (!empty($logins)) {
$records = $this->recordQueryBuilder->getPlayerMapRecords($mapUid, $nbLaps, $logins);
foreach ($records as $record) {
$this->recordsPerPlayer[$record->getPlayer()->getLogin()] = $record;
}
}
} | php | {
"resource": ""
} |
q10712 | RecordHandler.save | train | public function save()
{
$con = Propel::getWriteConnection(RecordTableMap::DATABASE_NAME);
$con->beginTransaction();
foreach ($this->recordsPerPlayer as $record) {
$record->save();
}
$con->commit();
RecordTableMap::clearInstancePool();
} | php | {
"resource": ""
} |
q10713 | RecordHandler.getNewRecord | train | protected function getNewRecord($login)
{
$record = new Record();
$record->setPlayer($this->playerDb->get($login));
$record->setNbLaps($this->currentNbLaps);
$record->setNbFinish(0);
$record->setMapUid($this->currentMapUid);
return $record;
} | php | {
"resource": ""
} |
q10714 | RecordHandler.updateRecordStats | train | protected function updateRecordStats(Record $record, $score)
{
$record->setAvgScore(
(($record->getAvgScore() * $record->getNbFinish()) + $score) / ($record->getNbFinish() + 1)
);
$record->setNbFinish($record->getNbFinish() + 1);
} | php | {
"resource": ""
} |
q10715 | GeoService.location | train | public function location($param) {
try {
$result = $this->geocoder->geocode($param);
// parse data from geo locator
return (new Geo($result))->toArray();
} catch (\Exception $e) {
throw new GeoServiceException($e->getMessage());
}
} | php | {
"resource": ""
} |
q10716 | Flot.getExtraFunctionCalls | train | public function getExtraFunctionCalls($dataArrayJs, $optionsJs)
{
$extraFunctionCalls = array();
if ($this->zooming) {
$extraFunctionCalls[] = sprintf( self::ZOOMING_FUNCTION, $dataArrayJs, $optionsJs, $dataArrayJs, $optionsJs );
}
if ($this->useLabels) {
$seriesLabels = json_encode($this->pointLabels);
$top = '';
$left = '';
$pixelCount = '15';
for ( $i = 0; $i < strlen($this->labelSettings['location']); $i++ ) {
switch ( $this->labelSettings['location'][$i] ) {
case 'n':
$top = '-'.$pixelCount;
break;
case 'e':
$left = '+'.$pixelCount;
break;
case 's':
$top = '+'.$pixelCount;
break;
case 'w':
$left = '-'.$pixelCount;
}
}
$paddingx = '-'.(isset($this->labelSettings['xpadding']) ? $this->labelSettings['xpadding'] : '0');
$paddingy = '-'.(isset($this->labelSettings['ypadding']) ? $this->labelSettings['ypadding'] : '0');
$extraFunctionCalls[] = sprintf( self::LABELS_FUNCTION, $seriesLabels, $left, $paddingx, $top, $paddingy );
}
if ($this->highlighting) {
$formatPoints = "x + ',' + y";
foreach ($this->dateAxes as $axis=>$flag) {
if ($flag) {
$formatPoints = str_replace($axis, "(new Date(parseInt({$axis}))).toLocaleDateString()",$formatPoints);
}
}
$extraFunctionCalls[] = sprintf( self::HIGHLIGHTING_FUNCTION, $formatPoints );
}
return $extraFunctionCalls;
} | php | {
"resource": ""
} |
q10717 | Flot.setAxisOptions | train | public function setAxisOptions($axis, $name, $value)
{
if( strtolower($axis) === 'x' || strtolower($axis) === 'y' ) {
$axis = strtolower($axis) . 'axis';
if ( array_key_exists( $name, $this->nativeOpts[$axis] ) ) {
$this->setNestedOptVal( $this->options, $axis, $name, $value );
} else {
$key = 'axes.'.$axis.'.'.$name;
if ( isset( $this->optsMapper[$key] ) ) {
$this->setOpt($this->options, $this->optsMapper[$key], $value);
}
if ( $name == 'formatString' ) {
$this->options[$axis]['tickFormatter'] = $this->getCallbackPlaceholder('function(val, axis){return "'.$value.'".replace(/%d/, val);}');
}
}
}
return $this;
} | php | {
"resource": ""
} |
q10718 | Flot.initializeSeries | train | public function initializeSeries( $series )
{
parent::initializeSeries($series);
$title = $this->getSeriesTitle($series);
$this->options['seriesStorage'][$title]['label'] = $title;
return $this;
} | php | {
"resource": ""
} |
q10719 | Flot.getOptionsJS | train | protected function getOptionsJS()
{
foreach ($this->optsMapper as $opt => $mapped)
{
if (($currOpt = $this->getOptVal($this->options, $opt)) && ($currOpt !== null)) {
$this->setOpt($this->options, $mapped, $currOpt);
$this->unsetOpt($this->options, $opt);
}
}
$opts = $this->options;
// stupid pie plugin
if ( $this->getOptVal( $opts, 'seriesStorage', 'pie', 'show' ) === null ) {
$this->setNestedOptVal( $opts, 'seriesStorage', 'pie', 'show', false );
}
$this->unsetOpt( $opts, 'seriesStorage' );
$this->unsetOpt( $opts, 'seriesDefault' );
return $this->makeJSArray($opts);
} | php | {
"resource": ""
} |
q10720 | Flot.getOptVal | train | protected function getOptVal(array $opts, $option)
{
$ploded = explode('.', $option);
$arr = $opts;
$val = null;
while ($curr = array_shift($ploded)) {
if (isset($arr[$curr])) {
if (is_array($arr[$curr])) {
$arr = $arr[$curr];
} else {
return $arr[$curr];
}
} else {
return null;
}
}
} | php | {
"resource": ""
} |
q10721 | Flot.setOpt | train | protected function setOpt(array &$opts, $mapperString, $val)
{
$args = explode( '.', $mapperString );
array_push( $args, $val );
$this->setNestedOptVal( $opts, $args );
} | php | {
"resource": ""
} |
q10722 | Flot.unsetOpt | train | protected function unsetOpt(array &$opts, $mapperString)
{
$ploded = explode('.', $mapperString);
$arr = &$opts;
while ($curr = array_shift($ploded)) {
if (isset($arr[$curr])) {
if (is_array($arr[$curr])) {
$arr = &$arr[$curr];
} else {
unset($arr[$curr]);
}
}
}
} | php | {
"resource": ""
} |
q10723 | Flot.setSeriesLineWidth | train | public function setSeriesLineWidth( $series, $value )
{
return $this->setNestedOptVal( $this->options, 'seriesStorage', $this->getSeriesTitle( $series ), 'lines', 'linewidth', $value );
} | php | {
"resource": ""
} |
q10724 | Flot.setSeriesShowLine | train | public function setSeriesShowLine( $series, $bool )
{
return $this->setNestedOptVal( $this->options, 'seriesStorage', $this->getSeriesTitle( $series ), 'lines', 'show', $bool );
} | php | {
"resource": ""
} |
q10725 | Flot.setSeriesShowMarker | train | public function setSeriesShowMarker( $series, $bool )
{
return $this->setNestedOptVal( $this->options, 'seriesStorage', $this->getSeriesTitle( $series ), 'points', 'show', $bool );
} | php | {
"resource": ""
} |
q10726 | Flot.setAxisTicks | train | public function setAxisTicks($axis, array $ticks = array() )
{
if ( in_array($axis, array('x', 'y') ) ) {
$isString = false;
$alternateTicks = array();
$cnt = 1;
foreach ($ticks as $tick) {
if (!(ctype_digit($tick) || is_int($tick))) {
$isString = true;
// this is O(2N) so deal with it
foreach ( $ticks as $tick ) {
$alternateTicks[] = array($cnt++, $tick);
}
break;
}
}
$this->setNestedOptVal( $this->options, $axis.'axis', 'ticks', $isString ? $alternateTicks : $ticks );
}
return $this;
} | php | {
"resource": ""
} |
q10727 | EmbeddedEntityListRule.execute | train | protected function execute($value, EntityInterface $parent_entity = null)
{
$success = true;
$list = null;
if ($value instanceof EntityList) {
$list = $value;
} elseif (null === $value) {
$list = new EntityList();
} elseif ($value instanceof EntityInterface) {
$list = new EntityList();
$list->push($value);
} elseif (is_array($value)) {
$list = new EntityList();
$success = $this->createEntityList($value, $list, $parent_entity);
} else {
$this->throwError('invalid_value_type');
return false;
}
$count = count($list);
if ($this->hasOption(self::OPTION_MIN_COUNT)) {
$min_count = $this->getOption(self::OPTION_MIN_COUNT, 0);
if ($count < (int)$min_count) {
$this->throwError('min_count', [ 'count' => $count, 'min_count' => $min_count ]);
$success = false;
}
}
if ($this->hasOption(self::OPTION_MAX_COUNT)) {
$max_count = $this->getOption(self::OPTION_MAX_COUNT, 0);
if ($count > (int)$max_count) {
$this->throwError('max_count', [ 'count' => $count, 'max_count' => $max_count ]);
$success = false;
}
}
if ($success) {
$this->setSanitizedValue($list);
return true;
}
return false;
} | php | {
"resource": ""
} |
q10728 | Jukebox.onPodiumStart | train | public function onPodiumStart($time)
{
$jbMap = $this->jukeboxService->getFirst();
if ($jbMap) {
$length = count($this->jukeboxService->getMapQueue());
$this->chatNotification->sendMessage('expansion_jukebox.chat.nextjbmap', null, [
"%mapname%" => $jbMap->getMap()->name,
"%mapauthor%" => $jbMap->getMap()->author,
"%nickname%" => $jbMap->getPlayer()->getNickName(),
"%length%" => $length,
]);
} else {
$map = $this->mapStorage->getNextMap();
$this->chatNotification->sendMessage('expansion_jukebox.chat.nextmap', null, [
"%name%" => $map->name,
"%author%" => $map->author,
]);
}
} | php | {
"resource": ""
} |
q10729 | DefaultTemplateEngine.draw | train | public function draw(string $file, array $data) : string
{
$this->file = $file;
$this->data = $data;
return $this->getOutputs();
} | php | {
"resource": ""
} |
q10730 | DefaultTemplateEngine.getOutputs | train | private function getOutputs() : string
{
ob_start();
extract($this->data);
require $this->file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
} | php | {
"resource": ""
} |
q10731 | EloquentSetting.update | train | public function update(array $data, $Setting = null)
{
if(empty($Setting))
{
$Setting = $this->byId($data['id']);
}
foreach ($data as $key => $value)
{
$Setting->$key = $value;
}
$Setting->save();
return $Setting;
} | php | {
"resource": ""
} |
q10732 | Text.maxCharWidth | train | public static function maxCharWidth($string)
{
$chars = preg_split('//u', $string, null, PREG_SPLIT_NO_EMPTY);
if (!$chars) {
return 0;
}
$sizes = array_map('strlen', $chars);
return max($sizes);
} | php | {
"resource": ""
} |
q10733 | Text.stripLinks | train | public static function stripLinks($text, $replaceWith = '')
{
$text = preg_replace('/(?:(?:[^\s\:>]+:)?\/\/|www\.)[^\s\.]+\.\w+[^\s<]+/u', $replaceWith, $text);
$text = preg_replace('/[^\s\.>]+\.[a-z]{2,}\/[^\s<]+/u', $replaceWith, $text);
return $text;
} | php | {
"resource": ""
} |
q10734 | Text.stripSocials | train | public static function stripSocials($text, $replaceWith = '')
{
$text = preg_replace('/(?<=\s|^|>)@[^\s<]+/u', $replaceWith, $text);
$text = preg_replace('/(?:[^\s>]+\.)?facebook.com\/[^\s<]+/u', $replaceWith, $text);
return $text;
} | php | {
"resource": ""
} |
q10735 | Text.toBool | train | public static function toBool($string)
{
if (is_null($string)) {
return false;
}
if (!is_scalar($string)) {
throw new InvalidArgumentException("Value must be scalar");
}
if (!is_string($string)) {
return (bool) $string;
}
return !in_array(strtolower($string), ['false', 'off', '-', 'no', 'n', '0', '']);
} | php | {
"resource": ""
} |
q10736 | Text.toCase | train | public static function toCase($string, $case)
{
switch ($case) {
case self::UPPER:
$string = mb_strtoupper($string);
break;
case self::LOWER:
$string = mb_strtolower($string);
break;
case self::UPPER_FIRST:
$string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
break;
case self::UPPER_WORDS:
$string = mb_convert_case($string, MB_CASE_TITLE);
break;
case self::NONE:
break;
default:
throw new InvalidArgumentException("Cannot set case {$case}");
}
return $string;
} | php | {
"resource": ""
} |
q10737 | Text.toSingleWhitespace | train | public static function toSingleWhitespace($string, $trim = true)
{
$string = preg_replace("/\r|\n|\t/", " ", $string);
$string = preg_replace("/ {2,}/", " ", $string);
if ($trim) {
$string = self::trim($string);
}
return $string;
} | php | {
"resource": ""
} |
q10738 | PlayerRepository.majRankPointGame | train | public function majRankPointGame()
{
$players = $this->findBy(array(), array('pointGame' => 'DESC'));
Ranking::addObjectRank($players, 'rankPointGame', array('pointGame'));
$this->getEntityManager()->flush();
} | php | {
"resource": ""
} |
q10739 | PlayerRepository.majRankMedal | train | public function majRankMedal()
{
$players = $this->findBy(array(), array('chartRank0' => 'DESC', 'chartRank1' => 'DESC', 'chartRank2' => 'DESC', 'chartRank3' => 'DESC'));
Ranking::addObjectRank($players, 'rankMedal', array('chartRank0', 'chartRank1', 'chartRank2', 'chartRank3'));
$this->getEntityManager()->flush();
} | php | {
"resource": ""
} |
q10740 | PlayerRepository.majRankProof | train | public function majRankProof()
{
$players = $this->findBy(array(), array('nbChartProven' => 'DESC'));
Ranking::addObjectRank($players, 'rankProof', array('nbChartProven'));
$this->getEntityManager()->flush();
} | php | {
"resource": ""
} |
q10741 | ComposerUtils.getDirectories | train | public static function getDirectories() {
Logger::info("Resolving dependencies for project");
$packages = array();
$root = dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))));
$composer = file_get_contents($root . DIRECTORY_SEPARATOR . 'composer.json');
$composer = json_decode($composer, true);
if (array_key_exists('require', $composer) && !empty($composer['require'])) {
foreach ($composer['require'] as $requirement => $version) {
$packages = array_merge(self::readFile($requirement), $packages);
}
} else {
Logger::trace("Project has no dependencies");
}
foreach ($packages as $package) {
Logger::debug("Project references package %s", $package);
}
Logger::info("%d dependencies found", count($packages));
return $packages;
} | php | {
"resource": ""
} |
q10742 | ComposerUtils.readFile | train | public static function readFile($package)
{
$root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))));
$path = implode(DIRECTORY_SEPARATOR, array($root, $package, 'composer.json'));
Logger::trace("Reading composer file %s", $path);
if (file_exists($path)) {
$composer = json_decode(file_get_contents($path), true);
if (array_key_exists('require', $composer) && !empty($composer['require'])) {
$directories = array($package);
Logger::trace("Checking dependencies for package %s", $package);
foreach ($composer['require'] as $requirement => $version) {
$directories = array_merge(self::readFile($requirement), $directories);
}
return $directories;
} else {
Logger::trace("Package %s has no dependencies", $package);
return array($package);
}
} else {
return array();
}
} | php | {
"resource": ""
} |
q10743 | PaymentSlipPdf.writePaymentSlipLines | train | protected function writePaymentSlipLines($elementName, array $element)
{
if (!is_string($elementName)) {
throw new \InvalidArgumentException('$elementName is not a string!');
}
if (!isset($element['lines'])) {
throw new \InvalidArgumentException('$element contains not "lines" key!');
}
if (!isset($element['attributes'])) {
throw new \InvalidArgumentException('$element contains not "attributes" key!');
}
$lines = $element['lines'];
$attributes = $element['attributes'];
if (!is_array($lines)) {
throw new \InvalidArgumentException('$lines is not an array!');
}
if (!is_array($attributes)) {
throw new \InvalidArgumentException('$attributes is not an array!');
}
$posX = $attributes['PosX'];
$posY = $attributes['PosY'];
$height = $attributes['Height'];
$width = $attributes['Width'];
$fontFamily = $attributes['FontFamily'];
$background = $attributes['Background'];
$fontSize = $attributes['FontSize'];
$fontColor = $attributes['FontColor'];
$lineHeight = $attributes['LineHeight'];
$textAlign = $attributes['TextAlign'];
$this->setFont($fontFamily, $fontSize, $fontColor);
if ($background != 'transparent') {
$this->setBackground($background);
$fill = true;
} else {
$fill = false;
}
foreach ($lines as $lineNr => $line) {
$this->setPosition(
$this->paymentSlip->getSlipPosX() + $posX,
$this->paymentSlip->getSlipPosY() + $posY + ($lineNr * $lineHeight)
);
$this->createCell($width, $height, $line, $textAlign, $fill);
}
return $this;
} | php | {
"resource": ""
} |
q10744 | PaymentSlipPdf.createPaymentSlip | train | public function createPaymentSlip(PaymentSlip $paymentSlip)
{
$this->paymentSlip = $paymentSlip;
// Place background image
if ($paymentSlip->getDisplayBackground()) {
$this->displayImage($paymentSlip->getSlipBackground());
}
$elements = $paymentSlip->getAllElements();
// Go through all elements, write each line
foreach ($elements as $elementName => $element) {
$this->writePaymentSlipLines($elementName, $element);
}
$this->paymentSlip = null;
return $this;
} | php | {
"resource": ""
} |
q10745 | Builder.setTable | train | public function setTable(string $table): self
{
$this->table = $this->agent->escapeIdentifier($table);
return $this;
} | php | {
"resource": ""
} |
q10746 | Builder.selectMore | train | public function selectMore($field, string $as = null): self
{
return $this->select($field, $as, false);
} | php | {
"resource": ""
} |
q10747 | Builder.selectJsonMore | train | public function selectJsonMore($field, string $as, string $type = 'object'): self
{
return $this->selectJson($field, $as, $type, false);
} | php | {
"resource": ""
} |
q10748 | Builder.selectRandom | train | public function selectRandom($field): self
{
return $this->push('select', $this->prepareField($field))
->push('where', [[$this->sql('random() < 0.01'), '']]);
} | php | {
"resource": ""
} |
q10749 | Builder.joinLeft | train | public function joinLeft(string $to, string $as, string $on, $onParams = null): self
{
return $this->join($to, $as, $on, $onParams, 'LEFT');
} | php | {
"resource": ""
} |
q10750 | Builder.joinUsing | train | public function joinUsing(string $to, string $as, string $using, $usingParams = null, string $type = ''): self
{
return $this->push('join', sprintf('%sJOIN %s AS %s USING (%s)',
$type ? strtoupper($type) .' ' : '',
$this->prepareField($to),
$this->agent->quoteField($as),
$this->agent->prepareIdentifier($using, $usingParams))
);
} | php | {
"resource": ""
} |
q10751 | Builder.joinLeftUsing | train | public function joinLeftUsing(string $to, string $as, string $using, $usingParams = null): self
{
return $this->joinUsing($to, $as, $using, $usingParams, 'LEFT');
} | php | {
"resource": ""
} |
q10752 | Builder.whereEqual | train | public function whereEqual($field, $param, string $op = ''): self
{
return $this->where($this->prepareField($field) .' = ?', $param, $op);
} | php | {
"resource": ""
} |
q10753 | Builder.whereNull | train | public function whereNull($field, string $op = ''): self
{
return $this->where($this->prepareField($field) .' IS NULL', null, $op);
} | php | {
"resource": ""
} |
q10754 | Builder.whereIn | train | public function whereIn($field, $param, string $op = ''): self
{
$ops = ['?'];
if (is_array($param)) {
$ops = array_fill(0, count($param), '?');
}
return $this->where($this->prepareField($field) .' IN ('. join(', ', $ops) .')', $param, $op);
} | php | {
"resource": ""
} |
q10755 | Builder.whereBetween | train | public function whereBetween($field, array $params, string $op = ''): self
{
return $this->where($this->prepareField($field) .' BETWEEN ? AND ?', $params, $op);
} | php | {
"resource": ""
} |
q10756 | Builder.whereLike | train | public function whereLike($field, $arguments, bool $ilike = false, bool $not = false, string $op = ''): self
{
// @note to me..
// 'foo%' Anything starts with "foo"
// '%foo' Anything ends with "foo"
// '%foo%' Anything have "foo" in any position
// 'f_o%' Anything have "o" in the second position
// 'f_%_%' Anything starts with "f" and are at least 3 characters in length
// 'f%o' Anything starts with "f" and ends with "o"
$arguments = (array) $arguments;
$searchArguments = array_slice($arguments, 0, 3);
if ($arguments != null) {
// eg: (??, ['%', 'apple', '%', 'id']), (%n, ['%', 'apple', '%', 'id'])
$field = $this->agent->prepare($field, array_slice($arguments, 3));
}
$search = '';
switch (count($searchArguments)) {
case 1: // none, eg: 'apple', ['apple']
[$start, $search, $end] = ['', $searchArguments[0], ''];
break;
case 2: // start/end, eg: ['%', 'apple'], ['apple', '%']
if ($searchArguments[0] == '%') {
[$start, $search, $end] = ['%', $searchArguments[1], ''];
} elseif ($searchArguments[1] == '%') {
[$start, $search, $end] = ['', $searchArguments[0], '%'];
}
break;
case 3: // both, eg: ['%', 'apple', '%']
[$start, $search, $end] = $searchArguments;
break;
}
$search = trim((string) $search);
if ($search == '') {
throw new BuilderException('Like search cannot be empty!');
}
$not = $not ? 'NOT ' : '';
if (is_string($field) && strpos($field, '(') === false) {
$field = $this->prepareField($field, false);
}
$search = $end . $this->agent->escape($search, '%sl', false) . $start;
$where = [];
$fields = (array) $field;
if (!$ilike) {
foreach ($fields as $field) {
$where[] = sprintf("%s %sLIKE '%s'", $field, $not, $search);
}
} else {
foreach ($fields as $field) {
if ($this->agent->isMysql()) {
$where[] = sprintf("lower(%s) %sLIKE lower('%s')", $field, $not, $search);
} elseif ($this->agent->isPgsql()) {
$where[] = sprintf("%s %sILIKE '%s'", $field, $not, $search);
}
}
}
$where = count($where) > 1 ? '('. join(' OR ', $where) .')' : join(' OR ', $where);
return $this->where($where);
} | php | {
"resource": ""
} |
q10757 | Builder.whereNotLike | train | public function whereNotLike($field, $arguments, bool $ilike = false, string $op = ''): self
{
return $this->whereLike($field, $arguments, $ilike, true, $op);
} | php | {
"resource": ""
} |
q10758 | Builder.whereLikeBoth | train | public function whereLikeBoth($field, string $search, bool $ilike = false, bool $not = false, string $op = ''): self
{
return $this->whereLike($field, ['%', $search, '%'], $ilike, $not, $op);
} | php | {
"resource": ""
} |
q10759 | Builder.whereExists | train | public function whereExists($query, array $queryParams = null, string $op = ''): self
{
if ($query instanceof Builder) {
$query = $query->toString();
}
if ($queryParams != null) {
$query = $this->agent->prepare($query, $queryParams);
}
return $this->where('EXISTS ('. $query .')', null, $op);
} | php | {
"resource": ""
} |
q10760 | Builder.whereId | train | public function whereId(string $field, $id, string $op = ''): self
{
return $this->where('?? = ?', [$field, $id], $op);
} | php | {
"resource": ""
} |
q10761 | Builder.whereIds | train | public function whereIds(string $field, array $ids, string $op = ''): self
{
return $this->where('?? IN (?)', [$field, $ids], $op);
} | php | {
"resource": ""
} |
q10762 | Builder.orderBy | train | public function orderBy($field, string $op = null): self
{
// check operator is valid
if ($op == null) {
return $this->push('orderBy', $this->prepareField($field));
}
$op = strtoupper($op);
if ($op != self::OP_ASC && $op != self::OP_DESC) {
throw new BuilderException('Available ops: ASC, DESC');
}
return $this->push('orderBy', $this->prepareField($field) .' '. $op);
} | php | {
"resource": ""
} |
q10763 | Builder.prepareField | train | private function prepareField($field, bool $join = true)
{
if ($field == '*') {
return $field;
}
if ($field instanceof Builder || $field instanceof Sql) {
return '('. $field->toString() .')';
} elseif ($field instanceof Identifier) {
return $this->agent->escapeIdentifier($field);
}
if (is_string($field)) {
$field = Util::split(',', trim($field));
}
if (is_array($field)) {
return $this->agent->escapeIdentifier($field, $join);
}
throw new BuilderException(sprintf('String, array or Builder type fields are accepted only,'.
' %s given', gettype($field)));
} | php | {
"resource": ""
} |
q10764 | Locale.sanitizeCountry | train | public static function sanitizeCountry($locale, $default = null)
{
if ($locale instanceof Locale) {
return $locale->getCountry();
}
if ($default) {
$default = Locale::sanitizeCountry($default, null);
}
$locale = (string) $locale;
$locale = trim($locale);
if (!$locale || !preg_match("/(?<country>[a-z]{2})$/ui", $locale, $found)) {
return $default;
}
return Text::toUpper($found['country']);
} | php | {
"resource": ""
} |
q10765 | Locale.sanitizeLanguage | train | public static function sanitizeLanguage($locale, $default = null)
{
if ($locale instanceof Locale) {
return $locale->getLanguage();
}
if ($default) {
$default = Locale::sanitizeLanguage($default, null);
}
$locale = (string) $locale;
$locale = trim($locale);
if (!$locale || !preg_match("/^(?<language>[a-z]{2})/ui", $locale, $found)) {
return $default;
}
return Text::toLower($found['language']);
} | php | {
"resource": ""
} |
q10766 | Locale.sanitizeLocale | train | public static function sanitizeLocale($locale, $default = null)
{
if ($locale instanceof Locale) {
return $locale->getLocale();
}
if ($default) {
$default = Locale::sanitizeLocale($default, null);
}
$locale = (string) $locale;
$locale = trim($locale);
if (!$locale || !preg_match("/^" . Locale::REGEX_LOCALE . "$/ui", $locale, $found)) {
return $default;
}
$found['language'] = Text::toLower($found['language']);
$found['country'] = Text::toUpper($found['country']);
return sprintf("%s_%s", $found['language'], $found['country']);
} | php | {
"resource": ""
} |
q10767 | Locale.getCountryName | train | public function getCountryName($inLocale = null)
{
$inLocale = Locale::sanitizeLocale($inLocale, $this->locale);
return \Locale::getDisplayRegion($this->locale, $inLocale);
} | php | {
"resource": ""
} |
q10768 | Locale.getCountryNameFor | train | public function getCountryNameFor($locale, $inLocale = null)
{
$locale = '_' . Locale::sanitizeCountry($locale);
$inLocale = Locale::sanitizeLanguage($inLocale, $this->locale);
return \Locale::getDisplayRegion($locale, $inLocale);
} | php | {
"resource": ""
} |
q10769 | Locale.getLanguageName | train | public function getLanguageName($inLocale = null)
{
$inLocale = Locale::sanitizeLocale($inLocale, $this->locale);
return \Locale::getDisplayLanguage($this->locale, $inLocale);
} | php | {
"resource": ""
} |
q10770 | Locale.getLanguageNameFor | train | public function getLanguageNameFor($locale, $inLocale = null)
{
$locale = Locale::sanitizeLanguage($locale) . '_';
$inLocale = Locale::sanitizeLanguage($inLocale, $this->locale);
return \Locale::getDisplayLanguage($locale, $inLocale);
} | php | {
"resource": ""
} |
q10771 | Locale.getLocaleName | train | public function getLocaleName($inLocale = null)
{
$inLocale = Locale::sanitizeLocale($inLocale, $this->locale);
return \Locale::getDisplayName($this->locale, $inLocale);
} | php | {
"resource": ""
} |
q10772 | Exception.toStackTrace | train | public static function toStackTrace($ex)
{
$list = [];
for ($stack = Throwable::getThrowableStack($ex); $stack !== null; $stack = $stack['prev'])
{
$list = array_merge($stack['trace'], $list);
}
return $list;
} | php | {
"resource": ""
} |
q10773 | Exception.toThrowableTrace | train | public static function toThrowableTrace($ex)
{
$list = [];
for ($stack = Throwable::getThrowableStack($ex); $stack !== null; $stack = $stack['prev'])
{
$list[] = Throwable::parseThrowableMessage($stack);
}
return array_reverse($list);
} | php | {
"resource": ""
} |
q10774 | Exception.toStackString | train | public static function toStackString($ex)
{
$stack = [];
$i = 0;
$trace = static::toStackTrace($ex);
$pad = strlen(count($trace)) > 2 ?: 2;
foreach ($trace as $element)
{
$stack[] = "\t" . str_pad('' . $i, $pad, ' ', STR_PAD_LEFT) . '. ' . $element;
++$i;
}
return implode("\n", $stack);
} | php | {
"resource": ""
} |
q10775 | Exception.toThrowableString | train | public static function toThrowableString($ex)
{
$stack = [];
$i = 0;
$trace = static::toThrowableTrace($ex);
$pad = strlen(count($trace)) > 2 ?: 2;
foreach ($trace as $element)
{
$stack[] = "\t" . str_pad('' . $i, $pad, ' ', STR_PAD_LEFT) . '. ' . $element;
++$i;
}
return implode("\n", $stack);
} | php | {
"resource": ""
} |
q10776 | MapRatings.loadRatings | train | private function loadRatings(Map $map)
{
try {
$this->mapRatingsService->load($map);
} catch (PropelException $e) {
$this->logger->error("error loading map ratings", ["exception" => $e]);
}
} | php | {
"resource": ""
} |
q10777 | GameTitleFetchPass.fetchDataFromRemote | train | protected function fetchDataFromRemote(Filesystem $fileSytem, ContainerBuilder $container)
{
$curl = new Curl();
$curl->setUrl("https://mp-expansion.com/api/maniaplanet/toZto");
$curl->run();
if ($curl->getCurlInfo()['http_code'] == 200) {
$fileSytem->put(self::MAPPINGS_FILE, $curl->getResponse());
} else {
echo "Can't fetch title mappings from expansion website!\n";
}
} | php | {
"resource": ""
} |
q10778 | QueryParser.parseFunctionArgument | train | private function parseFunctionArgument($funcName, $context)
{
try
{
return $this->parsePrimitiveValue();
}
catch(\Exception $e)
{
$name = $this->tokenizer->getTokenValue();
if($name)
{
// ADVANCE
$this->tokenizer->readNextToken();
// NESTED FUNCTION
if($this->tokenizer->is(TokenType::LEFT_PAREN))
{
return $this->parseFunctionExpression($name, $context);
}
// ARBITRARY IDENTIFIER, e.g. SOQL NAME
return new AST\SoqlName($name);
}
throw $e;
}
} | php | {
"resource": ""
} |
q10779 | QueryParser.parseOrderByField | train | private function parseOrderByField()
{
$retVal = null;
$fieldName = $this->tokenizer->getTokenValue();
$this->tokenizer->expect(TokenType::EXPRESSION);
if($this->tokenizer->is(TokenType::LEFT_PAREN))
{
$retVal = new AST\OrderByFunction($this->parseFunctionExpression($fieldName, Functions\SoqlFunctionInterface::CONTEXT_ORDER_BY));
}
else
{
$retVal = new AST\OrderByField($fieldName);
}
// ASC/DESC
if($this->tokenizer->isKeyword('asc'))
{
$retVal->setDirection(AST\OrderByField::DIRECTION_ASC);
$this->tokenizer->readNextToken();
}
elseif($this->tokenizer->isKeyword('desc'))
{
$retVal->setDirection(AST\OrderByField::DIRECTION_DESC);
$this->tokenizer->readNextToken();
}
if($this->tokenizer->isKeyword('NULLS'))
{
$this->tokenizer->readNextToken();
if($this->tokenizer->isKeyword('last'))
{
$retVal->setNulls(AST\OrderByField::NULLS_LAST);
}
elseif($this->tokenizer->isKeyword('first'))
{
$retVal->setNulls(AST\OrderByField::NULLS_FIRST);
}
else
{
throw new ParseException(sprintf('Unexpected "%s"', $this->tokenizer->getTokenValue()), $this->tokenizer->getLine(), $this->tokenizer->getLinePos(), $this->tokenizer->getInput());
}
$this->tokenizer->expect(TokenType::KEYWORD);
}
return $retVal;
} | php | {
"resource": ""
} |
q10780 | MonologInit.createLoggerInstance | train | protected function createLoggerInstance($handler, $target)
{
$handlerClassName = $handler . 'Handler';
if (class_exists('\Monolog\Logger') && class_exists('\Monolog\Handler\\' . $handlerClassName)) {
if (null !== $handlerInstance = $this->createHandlerInstance($handlerClassName, $target)) {
$this->instance = new \Monolog\Logger('main');
$this->instance->pushHandler($handlerInstance);
}
$this->handler = $handler;
$this->target = $target;
}
} | php | {
"resource": ""
} |
q10781 | MonologInit.createHandlerInstance | train | protected function createHandlerInstance($className, $handlerArgs)
{
if (method_exists($this, 'init' . $className)) {
return call_user_func(array($this, 'init' . $className), explode(',', $handlerArgs));
} else {
return null;
}
} | php | {
"resource": ""
} |
q10782 | Mxmap.setMap | train | public function setMap(ChildMap $v = null)
{
if ($v === null) {
$this->setTrackuid(NULL);
} else {
$this->setTrackuid($v->getMapuid());
}
$this->aMap = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildMap object, it will not be re-added.
if ($v !== null) {
$v->addMxmap($this);
}
return $this;
} | php | {
"resource": ""
} |
q10783 | Mxmap.getMap | train | public function getMap(ConnectionInterface $con = null)
{
if ($this->aMap === null && (($this->trackuid !== "" && $this->trackuid !== null))) {
$this->aMap = ChildMapQuery::create()
->filterByMxmap($this) // here
->findOne($con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aMap->addMxmaps($this);
*/
}
return $this->aMap;
} | php | {
"resource": ""
} |
q10784 | Requester.get_content_type | train | public function get_content_type() {
$headers = wp_remote_retrieve_headers( $this->response );
if ( ! $headers ) {
return;
}
if ( ! is_object( $headers ) || ! method_exists( $headers, 'offsetGet' ) ) {
return;
}
return $headers->offsetGet( 'content-type' );
} | php | {
"resource": ""
} |
q10785 | Requester.get_content | train | public function get_content() {
$content = wp_remote_retrieve_body( $this->response );
if ( empty( $content ) ) {
return;
}
return $this->_encode( $content );
} | php | {
"resource": ""
} |
q10786 | ObjectStorage.executeCommand | train | private function executeCommand(array $parameters, string $command)
{
foreach ($parameters as $index => $object) {
$parameters[$index]['command'] = $command;
}
$result = $this->execute($parameters);
if (isset($index)) {
unset($index);
}
if (isset($object)) {
unset($object);
}
unset($parameters);
unset($command);
return $result;
} | php | {
"resource": ""
} |
q10787 | ObjectStorage.validate | train | public function validate($key): bool
{
if (!is_string($key) || strlen($key) === 0 || $key === '.' || $key === '..' || strpos($key, '/../') !== false || strpos($key, '/./') !== false || strpos($key, '/') === 0 || strpos($key, './') === 0 || strpos($key, '../') === 0 || substr($key, -2) === '/.' || substr($key, -3) === '/..' || substr($key, -1) === '/') {
return false;
}
return preg_match("/^[a-z0-9\.\/\-\_]*$/", $key) === 1;
} | php | {
"resource": ""
} |
q10788 | ObjectStorage.createFileDirIfNotExists | train | private function createFileDirIfNotExists(string $filename): bool
{
$pathinfo = pathinfo($filename);
if (isset($pathinfo['dirname']) && $pathinfo['dirname'] !== '.') {
if (is_dir($pathinfo['dirname'])) {
return true;
} elseif (is_file($pathinfo['dirname'])) {
return false;
} else {
return $this->createDirIfNotExists($pathinfo['dirname']);
}
}
return false;
} | php | {
"resource": ""
} |
q10789 | ObjectStorage.createDirIfNotExists | train | private function createDirIfNotExists(string $dir): bool
{
if (!is_dir($dir)) {
try {
set_error_handler(function($errno, $errstr, $errfile, $errline) {
restore_error_handler();
throw new \IvoPetkov\ObjectStorage\ErrorException($errstr, 0, $errno, $errfile, $errline);
});
$result = mkdir($dir, 0777, true);
restore_error_handler();
return (bool) $result;
} catch (\IvoPetkov\ObjectStorage\ErrorException $e) {
if ($e->getMessage() !== 'mkdir(): File exists') { // The directory may be just created in other process.
throw $e;
}
}
}
return true;
} | php | {
"resource": ""
} |
q10790 | ObjectStorage.getFiles | train | private function getFiles(string $dir, bool $recursive = false, $limit = null): array
{
if ($limit === 0) {
return [];
}
$result = [];
if (is_dir($dir)) {
$list = scandir($dir);
if (is_array($list)) {
foreach ($list as $filename) {
if ($filename != '.' && $filename != '..') {
if (is_dir($dir . $filename)) {
if ($recursive === true) {
$dirResult = $this->getFiles($dir . $filename . '/', true, $limit !== null ? ($limit - sizeof($result)) : null);
if (!empty($dirResult)) {
foreach ($dirResult as $index => $value) {
$dirResult[$index] = $filename . '/' . $value;
}
$result = array_merge($result, $dirResult);
}
}
} else {
$result[] = $filename;
if ($limit !== null && $limit === sizeof($result)) {
break;
}
}
}
}
}
}
return $result;
} | php | {
"resource": ""
} |
q10791 | RaceDataProvider.isCompatible | train | public function isCompatible(Map $map): bool
{
if (!$map->lapRace) {
return false;
}
$nbLaps = 1;
if ($map->lapRace) {
$nbLaps = $map->nbLaps;
}
$scriptSettings = $this->gameDataStorage->getScriptOptions();
if ($scriptSettings['S_ForceLapsNb'] != -1) {
$nbLaps = $scriptSettings['S_ForceLapsNb'];
}
// If rounds is configured to be single laps then no need for race data. lap is sufficient.
return $nbLaps > 1; } | php | {
"resource": ""
} |
q10792 | Renderer.compile | train | public function compile($string, $filename = null)
{
$compiler = $this->getCompiler();
$this->setDebugString($string);
$this->setDebugFile($filename);
$this->setDebugFormatter($compiler->getFormatter());
return $compiler->compile($string, $filename);
} | php | {
"resource": ""
} |
q10793 | Renderer.compileFile | train | public function compileFile($path)
{
$compiler = $this->getCompiler();
$this->setDebugFile($path);
$this->setDebugFormatter($compiler->getFormatter());
return $compiler->compileFile($path);
} | php | {
"resource": ""
} |
q10794 | Renderer.renderAndWriteFile | train | public function renderAndWriteFile($inputFile, $outputFile, array $parameters = [])
{
$outputDirectory = dirname($outputFile);
if (!file_exists($outputDirectory) && !@mkdir($outputDirectory, 0777, true)) {
return false;
}
return is_int($this->getNewSandBox(function () use ($outputFile, $inputFile, $parameters) {
return file_put_contents($outputFile, $this->renderFile($inputFile, $parameters));
})->getResult());
} | php | {
"resource": ""
} |
q10795 | Renderer.renderDirectory | train | public function renderDirectory($path, $destination = null, $extension = '.html', array $parameters = [])
{
if (is_array($destination)) {
$parameters = $destination;
$destination = null;
} elseif (is_array($extension)) {
$parameters = $extension;
$extension = '.html';
}
if (!$destination) {
$destination = $path;
}
$path = realpath($path);
$destination = realpath($destination);
$success = 0;
$errors = 0;
if ($path && $destination) {
$path = rtrim($path, '/\\');
$destination = rtrim($destination, '/\\');
$length = mb_strlen($path);
foreach ($this->scanDirectory($path) as $file) {
$relativeDirectory = trim(mb_substr(dirname($file), $length), '//\\');
$filename = pathinfo($file, PATHINFO_FILENAME);
$outputDirectory = $destination.DIRECTORY_SEPARATOR.$relativeDirectory;
$counter = $this->renderAndWriteFile(
$file,
$outputDirectory.DIRECTORY_SEPARATOR.$filename.$extension,
$parameters
) ? 'success' : 'errors';
$$counter++;
}
}
return [$success, $errors];
} | php | {
"resource": ""
} |
q10796 | BenGorUserExtension.loadCommands | train | private function loadCommands(ContainerBuilder $container, $user)
{
$container->setDefinition(
'bengor.user.command.create_' . $user . '_command',
(new Definition(CreateUserCommand::class))->addTag('console.command')
);
$container->setDefinition(
'bengor.user.command.change_' . $user . '_password_command',
(new Definition(ChangePasswordCommand::class))->addTag('console.command')
);
$container->setDefinition(
'bengor.user.command.purge_outdated_' . $user . '_invitation_tokens_command',
(new Definition(PurgeOutdatedInvitationTokensCommand::class))->addTag('console.command')
);
$container->setDefinition(
'bengor.user.command.purge_outdated_' . $user . '_remember_password_tokens_command',
(new Definition(PurgeOutdatedRememberPasswordTokensCommand::class))->addTag('console.command')
);
} | php | {
"resource": ""
} |
q10797 | Smarty_CacheResource_Mysql.fetch | train | protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
{
$this->fetch->execute(array('id' => $id));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$content = $row['content'];
$mtime = strtotime($row['modified']);
} else {
$content = null;
$mtime = null;
}
} | php | {
"resource": ""
} |
q10798 | Smarty_CacheResource_Mysql.fetchTimestamp | train | protected function fetchTimestamp($id, $name, $cache_id, $compile_id)
{
$this->fetchTimestamp->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestamp->fetchColumn());
$this->fetchTimestamp->closeCursor();
return $mtime;
} | php | {
"resource": ""
} |
q10799 | Smarty_CacheResource_Mysql.save | train | protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
{
$this->save->execute(array(
'id' => $id,
'name' => $name,
'cache_id' => $cache_id,
'compile_id' => $compile_id,
'content' => $content,
));
return !!$this->save->rowCount();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.