_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11000 | ChatCommands.addCommand | train | protected function addCommand($pluginId, $cmdTxt, ChatCommandInterface $command)
{
if (isset($this->commands[$cmdTxt])) {
throw new CommandExistException(
"$pluginId tries to register command '$cmdTxt' already registered"
);
}
$this->commands[$cmdTxt] = $command;
$this->commandPlugin[$pluginId][$cmdTxt] = $command;
} | php | {
"resource": ""
} |
q11001 | CakeThemeAppHelper._getOptionsForElem | train | protected function _getOptionsForElem($path = null) {
if (empty($path)) {
return null;
}
$result = Hash::get($this->_optionsForElem, $path);
return $result;
} | php | {
"resource": ""
} |
q11002 | Menu.displayMenu | train | protected function displayMenu()
{
foreach ($this->adminGroups->getUserGroups() as $userGroup) {
$this->menuGuiFactory->create($userGroup);
}
} | php | {
"resource": ""
} |
q11003 | BreadCrumbBehavior.getModelName | train | public function getModelName(Model $model, $toLowerCase = false) {
$modelName = $model->name;
if ($toLowerCase) {
$modelName = mb_strtolower($modelName);
}
return $modelName;
} | php | {
"resource": ""
} |
q11004 | BreadCrumbBehavior.getModelNamePlural | train | public function getModelNamePlural(Model $model, $toLowerCase = false) {
$modelName = $this->getModelName($model, $toLowerCase);
return Inflector::pluralize($modelName);
} | php | {
"resource": ""
} |
q11005 | BreadCrumbBehavior.getControllerName | train | public function getControllerName(Model $model) {
$modelNamePlural = $this->getModelNamePlural($model, false);
$controllerName = mb_strtolower(Inflector::underscore($modelNamePlural));
return $controllerName;
} | php | {
"resource": ""
} |
q11006 | BreadCrumbBehavior.getGroupName | train | public function getGroupName(Model $model) {
$modelNamePlural = $this->getModelNamePlural($model);
$groupNameCamel = Inflector::humanize(Inflector::underscore($modelNamePlural));
$groupName = mb_ucfirst(mb_strtolower($groupNameCamel));
return $groupName;
} | php | {
"resource": ""
} |
q11007 | BreadCrumbBehavior.getName | train | public function getName(Model $model, $id = null) {
if (empty($id) || empty($model->displayField)) {
return false;
}
if (is_array($id)) {
if (!isset($id[$model->alias][$model->displayField])) {
return false;
}
$result = $id[$model->alias][$model->displayField];
} else {
$model->id = $id;
$result = $model->field($model->displayField);
}
return $result;
} | php | {
"resource": ""
} |
q11008 | BreadCrumbBehavior.getFullName | train | public function getFullName(Model $model, $id = null) {
$name = $this->getName($model, $id);
if (empty($name)) {
return false;
}
$modelName = $this->getModelName($model);
$result = $modelName . ' \'' . $name . '\'';
return $result;
} | php | {
"resource": ""
} |
q11009 | BreadCrumbBehavior.createBreadcrumb | train | public function createBreadcrumb(Model $model, $id = null, $link = null, $escape = true) {
$result = [];
if (empty($id)) {
$name = $model->getGroupName();
} else {
$name = $model->getName($id);
}
if (empty($name)) {
return $result;
}
if ($escape) {
$name = h($name);
}
if ($link === false) {
$link = null;
} else {
if (!is_array($link)) {
$link = [];
}
$plugin = $model->getPluginName();
$controller = $model->getControllerName();
if (empty($id)) {
$action = 'index';
} else {
$action = $model->getActionName();
if (empty($link)) {
$link[] = $id;
}
}
$link += compact('plugin', 'controller', 'action');
}
$name = CakeText::truncate($name, CAKE_THEME_BREADCRUMBS_TEXT_LIMIT);
$result = [
$name,
$link
];
return $result;
} | php | {
"resource": ""
} |
q11010 | BreadCrumbBehavior.getBreadcrumbInfo | train | public function getBreadcrumbInfo(Model $model, $id = null, $includeRoot = null) {
if (!empty($id) && ($includeRoot === null)) {
$includeRoot = true;
}
$result = [];
$root = [];
if ($includeRoot) {
$root = $model->getBreadcrumbInfo();
if (empty($root)) {
return $result;
}
}
$info = $model->createBreadcrumb($id);
if (empty($info)) {
return $result;
}
if (!empty($root)) {
$result = $root;
}
$result[] = $info;
return $result;
} | php | {
"resource": ""
} |
q11011 | Result.detectFetchType | train | public final function detectFetchType($fetchType): int
{
switch (gettype($fetchType)) {
case 'NULL':
return ResultInterface::AS_OBJECT;
case 'integer':
if (in_array($fetchType, [ResultInterface::AS_OBJECT, ResultInterface::AS_ARRAY_ASC,
ResultInterface::AS_ARRAY_NUM, ResultInterface::AS_ARRAY_ASCNUM])) {
return $fetchType;
}
break;
case 'string':
// shorthands
if ($fetchType == 'array') return ResultInterface::AS_ARRAY_ASC;
if ($fetchType == 'object') return ResultInterface::AS_OBJECT;
// object, array_asc etc.
$fetchTypeConst = 'Oppa\Query\Result\ResultInterface::AS_'. strtoupper($fetchType);
if (defined($fetchTypeConst)) {
return constant($fetchTypeConst);
}
// user classes
if (class_exists($fetchType)) {
$this->setFetchObject($fetchType);
return ResultInterface::AS_OBJECT;
}
break;
}
throw new InvalidValueException("Given '{$fetchType}' fetch type is not implemented!");
} | php | {
"resource": ""
} |
q11012 | Result.setFetchObject | train | public final function setFetchObject(string $fetchObject): void
{
if (!class_exists($fetchObject)) {
throw new InvalidValueException("Fetch object class '{$fetchObject}' not found!");
}
$this->fetchObject = $fetchObject;
} | php | {
"resource": ""
} |
q11013 | Result.setIds | train | public final function setIds(array $ids): void
{
foreach ($ids as $id) {
$this->ids[] = (int) $id;
}
} | php | {
"resource": ""
} |
q11014 | Result.toObject | train | public final function toObject(): ?array
{
$data = null;
if (!empty($this->data)) {
// no need to type-cast
if (is_object($this->data[0])) {
return $this->data;
}
$data = $this->data;
foreach ($data as &$dat) {
$dat = (object) $dat;
}
}
return $data;
} | php | {
"resource": ""
} |
q11015 | Result.toClass | train | public final function toClass(string $class): ?array
{
$data = null;
if (!empty($this->data)) {
$data = $this->data;
foreach ($data as &$dat) {
$datClass = new $class();
foreach ((array) $dat as $key => $value) {
$datClass->{$key} = $value;
}
$dat = $datClass;
}
}
return $data;
} | php | {
"resource": ""
} |
q11016 | Arrays.copyIfKeysExist | train | public static function copyIfKeysExist(array $source, array &$dest, array $keyMap)
{
$callable = function (array $source, $key) {
return array_key_exists($key, $source);
};
self::copyValueIf($source, $dest, $keyMap, $callable);
} | php | {
"resource": ""
} |
q11017 | Arrays.copyIfSet | train | public static function copyIfSet(array $source, array &$dest, array $keyMap)
{
$callable = function (array $source, $key) {
return isset($source[$key]);
};
self::copyValueIf($source, $dest, $keyMap, $callable);
} | php | {
"resource": ""
} |
q11018 | Arrays.project | train | public static function project(array $input, $key, bool $strictKeyCheck = true) : array
{
$projection = [];
foreach ($input as $itemKey => $item) {
self::ensureIsArray($item, 'a value in $input was not an array');
if (array_key_exists($key, $item)) {
$projection[$itemKey] = $item[$key];
} elseif ($strictKeyCheck) {
throw new \InvalidArgumentException('key was not in one of the $input arrays');
}
}
return $projection;
} | php | {
"resource": ""
} |
q11019 | Arrays.embedInto | train | public static function embedInto(
array $items,
string $fieldName,
array $destination = [],
bool $overwrite = false
) : array {
foreach ($items as $key => $item) {
if (!array_key_exists($key, $destination)) {
$destination[$key] = [$fieldName => $item];
continue;
}
self::ensureIsArray($destination[$key], 'a value in $destination was not an array');
if (!$overwrite && array_key_exists($fieldName, $destination[$key])) {
throw new \Exception('$fieldName key already exists in a $destination array');
}
$destination[$key][$fieldName] = $item;
}
return $destination;
} | php | {
"resource": ""
} |
q11020 | Arrays.extract | train | public static function extract(
array $input,
$keyIndex,
$valueIndex,
string $duplicateBehavior = 'takeLast'
) : array {
if (!in_array($duplicateBehavior, ['takeFirst', 'takeLast', 'throw'])) {
throw new \InvalidArgumentException("\$duplicateBehavior was not 'takeFirst', 'takeLast', or 'throw'");
}
self::ensureValidKey($keyIndex, '$keyIndex was not a string or integer');
self::ensureValidKey($valueIndex, '$valueIndex was not a string or integer');
$result = [];
foreach ($input as $index => $array) {
self::ensureIsArray($array, '$arrays was not a multi-dimensional array');
$key = self::get($array, $keyIndex);
self::ensureValidKey(
$key,
"Value for \$arrays[{$index}][{$keyIndex}] was not a string or integer",
'\\UnexpectedValueException'
);
$value = self::get($array, $valueIndex);
if (!array_key_exists($key, $result)) {
$result[$key] = $value;
continue;
}
if ($duplicateBehavior === 'throw') {
throw new \Exception("Duplicate entry for '{$key}' found.");
}
if ($duplicateBehavior === 'takeLast') {
$result[$key] = $value;
}
}
return $result;
} | php | {
"resource": ""
} |
q11021 | Arrays.changeKeyCase | train | public static function changeKeyCase(array $input, int $case = self::CASE_LOWER) : array
{
if ($case & self::CASE_UNDERSCORE) {
$input = self::underscoreKeys($input);
}
if ($case & self::CASE_CAMEL_CAPS) {
$input = self::camelCaseKeys($input);
}
if ($case & self::CASE_UPPER) {
$input = array_change_key_case($input, \CASE_UPPER);
}
if ($case & self::CASE_LOWER) {
$input = array_change_key_case($input, \CASE_LOWER);
}
return $input;
} | php | {
"resource": ""
} |
q11022 | Arrays.flatten | train | final public static function flatten(array $input, string $delimiter = '.') : array
{
$args = func_get_args();
$prefix = count($args) === 3 ? array_pop($args) : '';
$result = [];
foreach ($input as $key => $value) {
$newKey = $prefix . (empty($prefix) ? '' : $delimiter) . $key;
if (is_array($value)) {
$result = array_merge($result, self::flatten($value, $delimiter, $newKey));
continue;
}
$result[$newKey] = $value;
}
return $result;
} | php | {
"resource": ""
} |
q11023 | Process.restart | train | public function restart(callable $callback = null)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
$process = clone $this;
$process->start($callback);
return $process;
} | php | {
"resource": ""
} |
q11024 | Process.getExitCode | train | public function getExitCode()
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$this->updateStatus(false);
return $this->exitcode;
} | php | {
"resource": ""
} |
q11025 | Process.hasBeenSignaled | train | public function hasBeenSignaled()
{
$this->requireProcessIsTerminated(__FUNCTION__);
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
}
return $this->processInformation['signaled'];
} | php | {
"resource": ""
} |
q11026 | Process.addOutput | train | public function addOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stdout, 0, SEEK_END);
fwrite($this->stdout, $line);
fseek($this->stdout, $this->incrementalOutputOffset);
} | php | {
"resource": ""
} |
q11027 | Process.addErrorOutput | train | public function addErrorOutput($line)
{
$this->lastOutputTime = microtime(true);
fseek($this->stderr, 0, SEEK_END);
fwrite($this->stderr, $line);
fseek($this->stderr, $this->incrementalErrorOutputOffset);
} | php | {
"resource": ""
} |
q11028 | Process.readPipesForOutput | train | private function readPipesForOutput($caller, $blocking = false)
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
}
$this->requireProcessIsStarted($caller);
$this->updateStatus($blocking);
} | php | {
"resource": ""
} |
q11029 | Attendee.getBetterButtonsActions | train | public function getBetterButtonsActions()
{
/** @var FieldList $fields */
$fields = parent::getBetterButtonsActions();
if ($this->TicketFile()->exists() && !empty($this->getEmail())) {
$fields->push(BetterButtonCustomAction::create('sendTicket', _t('Attendee.SEND', 'Send the ticket')));
}
if (!empty($this->getName()) && !empty($this->getEmail())) {
$fields->push(BetterButtonCustomAction::create('createTicketFile', _t('Attendee.CREATE_TICKET', 'Create the ticket')));
}
return $fields;
} | php | {
"resource": ""
} |
q11030 | Attendee.onBeforeWrite | train | public function onBeforeWrite()
{
// Set the title of the attendee
$this->Title = $this->getName();
// Generate the ticket code
if ($this->exists() && empty($this->TicketCode)) {
$this->TicketCode = $this->generateTicketCode();
}
if (
$this->getEmail()
&& $this->getName()
&& !$this->TicketFile()->exists()
&& !$this->TicketQRCode()->exists()
) {
$this->createQRCode();
$this->createTicketFile();
}
if ($fields = $this->Fields()) {
foreach ($fields as $field) {
if ($value = $this->{"$field->Name[$field->ID]"}) {
//$cache = self::getCacheFactory();
//$cache->save(serialize($value), $this->getFieldCacheKey($field));
$fields->add($field->ID, array('Value' => $value));
}
}
}
parent::onBeforeWrite();
} | php | {
"resource": ""
} |
q11031 | Attendee.onBeforeDelete | train | public function onBeforeDelete()
{
// If an attendee is deleted from the guest list remove it's qr code
// after deleting the code it's not validatable anymore, simply here for cleanup
if ($this->TicketQRCode()->exists()) {
$this->TicketQRCode()->delete();
}
// cleanup the ticket file
if ($this->TicketFile()->exists()) {
$this->TicketFile()->delete();
}
if ($this->Fields()->exists()) {
$this->Fields()->removeAll();
}
parent::onBeforeDelete();
} | php | {
"resource": ""
} |
q11032 | Attendee.getName | train | public function getName()
{
$mainContact = $this->Reservation()->MainContact();
if ($this->getSurname()) {
return trim("{$this->getFirstName()} {$this->getSurname()}");
} elseif ($mainContact->exists() && $mainContact->getSurname()) {
return _t('Attendee.GUEST_OF', 'Guest of {name}', null, array('name' => $mainContact->getName()));
} else {
return null;
}
} | php | {
"resource": ""
} |
q11033 | Attendee.getTableFields | train | public function getTableFields()
{
$fields = new ArrayList();
foreach (self::config()->get('table_fields') as $field) {
$data = new ViewableData();
$data->Header = _t("Attendee.$field", $field);
$data->Value = $this->{$field};
$fields->add($data);
}
return $fields;
} | php | {
"resource": ""
} |
q11034 | Attendee.createQRCode | train | public function createQRCode()
{
$folder = $this->fileFolder();
$relativeFilePath = "/{$folder->Filename}{$this->TicketCode}.png";
$absoluteFilePath = Director::baseFolder() . $relativeFilePath;
if (!$image = Image::get()->find('Filename', $relativeFilePath)) {
// Generate the QR code
$renderer = new BaconQrCode\Renderer\Image\Png();
$renderer->setHeight(256);
$renderer->setWidth(256);
$writer = new BaconQrCode\Writer($renderer);
if (self::config()->get('qr_as_link')) {
$writer->writeFile($this->getCheckInLink(), $absoluteFilePath);
} else {
$writer->writeFile($this->TicketCode, $absoluteFilePath);
}
// Store the image in an image object
$image = Image::create();
$image->ParentID = $folder->ID;
$image->OwnerID = (Member::currentUser()) ? Member::currentUser()->ID : 0;
$image->Title = $this->TicketCode;
$image->setFilename($relativeFilePath);
$image->write();
// Attach the QR code to the Attendee
$this->TicketQRCodeID = $image->ID;
$this->write();
}
return $image;
} | php | {
"resource": ""
} |
q11035 | Attendee.createTicketFile | train | public function createTicketFile()
{
// Find or make a folder
$folder = $this->fileFolder();
$relativeFilePath = "/{$folder->Filename}{$this->TicketCode}.pdf";
$absoluteFilePath = Director::baseFolder() . $relativeFilePath;
if (!$this->TicketQRCode()->exists()) {
$this->createQRCode();
}
if (!$file = File::get()->find('Filename', $relativeFilePath)) {
$file = File::create();
$file->ParentID = $folder->ID;
$file->OwnerID = (Member::currentUser()) ? Member::currentUser()->ID : 0;
$file->Title = $this->TicketCode;
$file->setFilename($relativeFilePath);
$file->write();
}
// Set the template and parse the data
$template = new SSViewer('PrintableTicket');
$html = $template->process($this->data());// getViewableData());
// Create a DomPDF instance
$domPDF = new Dompdf();
$domPDF->loadHtml($html);
$domPDF->setPaper('A4');
$domPDF->getOptions()->setDpi(150);
$domPDF->render();
// Save the pdf stream as a file
file_put_contents($absoluteFilePath, $domPDF->output());
// Attach the ticket file to the Attendee
$this->TicketFileID = $file->ID;
$this->write();
return $file;
} | php | {
"resource": ""
} |
q11036 | Attendee.sendTicket | train | public function sendTicket()
{
// Get the mail sender or fallback to the admin email
if (empty($from = Reservation::config()->get('mail_sender'))) {
$from = Config::inst()->get('Email', 'admin_email');
}
$email = new Email();
$email->setSubject(_t(
'AttendeeMail.TITLE',
'Your ticket for {event}',
null,
array(
'event' => $this->Event()->Title
)
));
$email->setFrom($from);
$email->setTo($this->getEmail());
$email->setTemplate('AttendeeMail');
$email->populateTemplate($this);
$this->extend('updateTicketMail', $email);
return $email->send();
} | php | {
"resource": ""
} |
q11037 | AbstractScriptMethod.get | train | public function get($function)
{
$this->toDispatch[] = $function;
if (is_null($this->dataProvider)) {
$this->currentData = null;
$this->dispatchData();
return;
}
if (is_null($this->currentData)) {
if (!$this->callMade) {
$this->callMade = true;
$this->dataProvider->request();
}
return;
}
$this->dispatchData();
} | php | {
"resource": ""
} |
q11038 | AbstractScriptMethod.dispatchData | train | protected function dispatchData()
{
foreach ($this->toDispatch as $callback) {
$callback($this->currentData);
}
$this->toDispatch = [];
$this->callMade = false;
} | php | {
"resource": ""
} |
q11039 | RemoveController.removeAction | train | public function removeAction(Request $request, $userClass)
{
$form = $this->get('form.factory')->createNamedBuilder('', RemoveType::class, null, [
'csrf_protection' => false,
])->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
try {
$this->get('bengor_user.' . $userClass . '.api_command_bus')->handle(
$form->getData()
);
return new JsonResponse();
} catch (UserDoesNotExistException $exception) {
return new JsonResponse(
sprintf(
'The "%s" user id does not exist',
$form->getData()->id()
),
400
);
}
}
return new JsonResponse(FormErrorSerializer::errors($form), 400);
} | php | {
"resource": ""
} |
q11040 | AbstractBinary.run | train | protected function run(Process $process, $bypassErrors = false, $listeners = null)
{
if (null !== $listeners) {
if (!is_array($listeners)) {
$listeners = array($listeners);
}
$listenersManager = clone $this->listenersManager;
foreach ($listeners as $listener) {
$listenersManager->register($listener, $this);
}
} else {
$listenersManager = $this->listenersManager;
}
return $this->processRunner->run($process, $listenersManager->storage, $bypassErrors);
} | php | {
"resource": ""
} |
q11041 | Throwable.parseThrowableMessage | train | public static function parseThrowableMessage($ex)
{
$message = $ex['message'];
if ($ex['isError'] && strpos($message, ' in ') !== false)
{
$message = preg_replace('#([a-zA-Z0-9-_]+?)/#siU', '', $message);
$message = preg_replace('#/#si', '', $message, 1);
}
else
{
$message = trim($message, '"');
$file = str_replace('.php', '', basename($ex['file']));
$line = $ex['line'];
$message = '"' . $message . '" in ' . $file . ':' . $line;
}
return '[' . static::getBasename($ex['class']) . '] ' . $message;
} | php | {
"resource": ""
} |
q11042 | Throwable.getThrowableStack | train | public static function getThrowableStack($ex, &$data = [], $offset = 0)
{
$data = static::getThrowableData($ex, $offset);
if (($current = $ex->getPrevious()) !== null)
{
static::getThrowableStack($current, $data['prev'], count(static::getTraceElements($ex)));
}
return $data;
} | php | {
"resource": ""
} |
q11043 | Throwable.getThrowableData | train | public static function getThrowableData($ex, $offset = 0)
{
return [
'message' => $ex->getMessage(),
'class' => get_class($ex),
'file' => $ex->getFile(),
'line' => $ex->getLine(),
'code' => $ex->getCode(),
'trace' => static::getTraceElements($ex, $offset),
'isError' => $ex instanceof \Error,
'prev' => null
];
} | php | {
"resource": ""
} |
q11044 | Html.stripTags | train | public static function stripTags($html, $allowable = [])
{
if (!is_array($allowable)) {
$allowable = preg_split("/, */", $allowable, -1, PREG_SPLIT_NO_EMPTY);
}
if ($allowable) {
return strip_tags($html, '<' . implode('><', $allowable) . '>');
}
return strip_tags($html);
} | php | {
"resource": ""
} |
q11045 | Create.handle | train | public function handle()
{
/** @var string $path path to the env file */
$path = $this->getFilePath();
if (!file_exists($path)) {
file_put_contents($path, "");
}
/** @var string $content current content in the env file */
$content = file_get_contents($path);
foreach ($this->generateKeys() as $key) {
/** try and match the value in the env file by regex, if not
* found then append the key to the bottom of the
* file
*/
preg_match($key['regex'], $content, $matches);
if ($matches) {
$content = preg_replace($key['regex'], $key['value'], $content);
} else {
$content .= $key['value'] . PHP_EOL;
}
}
/** apply changes */
file_put_contents($path, $content);
$this->info('Wordpress keys regenerated');
} | php | {
"resource": ""
} |
q11046 | Create.generateKeys | train | private function generateKeys()
{
$content = [];
for ($i = 0; $i < count($this->keys); $i++) {
$holder = [];
$value = !$this->option($this->keys[$i]) || $this->option($this->keys[$i]) === 'generate' ? str_random(64) : $this->option($this->keys[$i]);
$holder['regex'] = str_replace_first($this->findRegExPlaceholder, $this->keys[$i], $this->findRegEx);
$holder['value'] = $this->keys[$i] . '="' . $value . '"';
array_push($content, $holder);
}
return $content;
} | php | {
"resource": ""
} |
q11047 | Php53Adapter.setSaveHandler | train | public static function setSaveHandler(\SessionHandlerInterface $handler)
{
return session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);
} | php | {
"resource": ""
} |
q11048 | Consumer.parsePayload | train | protected function parsePayload($payload)
{
$database = 0;
$client = null;
$pregCallback = function ($matches) use (&$database, &$client) {
if (2 === $count = \count($matches)) {
// Redis <= 2.4
$database = (int) $matches[1];
}
if (4 === $count) {
// Redis >= 2.6
$database = (int) $matches[2];
$client = $matches[3];
}
return ' ';
};
$event = \preg_replace_callback('/ \(db (\d+)\) | \[(\d+) (.*?)\] /', $pregCallback, $payload, 1);
@list($timestamp, $command, $arguments) = \explode(' ', $event, 3);
return (object) [
'timestamp' => (float) $timestamp,
'database' => $database,
'client' => $client,
'command' => \substr($command, 1, -1),
'arguments' => $arguments,
];
} | php | {
"resource": ""
} |
q11049 | RouteGroup.addRoute | train | public function addRoute(array $methods, string $path, string $handler)
{
$this->routeCollector->addRoute(
$methods,
$this->getPrefix().$path,
$handler
);
return $this;
} | php | {
"resource": ""
} |
q11050 | ContainerFactory.createContainer | train | public function createContainer()
{
# Create the container
$container = new Container;
# If we have auto-wire option on ...
if (($this->options['autowire'] ?? false)) {
# Add reflection delegate, so auto-wiring is possible
$container->delegate( new ReflectionContainer );
}
\logger()->debug('Created PSR-11 Container (The Leauge Container)');
return $container;
} | php | {
"resource": ""
} |
q11051 | Transformation.apply | train | public function apply(EntityInterface $entity, SpecificationInterface $specification)
{
$attribute_name = $specification->getOption('attribute', $specification->getName());
$entity_value = $entity->getValue($attribute_name);
return $entity_value;
} | php | {
"resource": ""
} |
q11052 | RecordQueryBuilder.getMapRecords | train | public function getMapRecords($mapUid, $nbLaps, $sort, $nbRecords)
{
$query = new RecordQuery();
$query->filterByMapuid($mapUid);
$query->filterByNblaps($nbLaps);
$query->orderByScore($sort);
$query->limit($nbRecords);
$result = $query->find();
$result->populateRelation('Player');
RecordTableMap::clearInstancePool();
return $result->getData();
} | php | {
"resource": ""
} |
q11053 | RecordQueryBuilder.getPlayerMapRecords | train | public function getPlayerMapRecords($mapUid, $nbLaps, $logins)
{
$query = new RecordQuery();
$query->filterByMapuid($mapUid);
$query->filterByNblaps($nbLaps);
$query->filterByPlayerLogins($logins);
$result = $query->find();
$result->populateRelation('Player');
RecordTableMap::clearInstancePool();
return $result->getData();
} | php | {
"resource": ""
} |
q11054 | SocketHandler.closeSocket | train | public function closeSocket()
{
if (is_resource($this->resource)) {
fclose($this->resource);
$this->resource = null;
}
} | php | {
"resource": ""
} |
q11055 | Document.handleErrors | train | public function handleErrors($msg_prefix = '', $msg_suffix = '', $user_error_handling = false)
{
if (libxml_get_last_error() !== false) {
$errors = libxml_get_errors();
libxml_clear_errors();
libxml_use_internal_errors($user_error_handling);
throw new DOMException(
$msg_prefix .
$this->getErrorMessage($errors) .
$msg_suffix
);
}
libxml_use_internal_errors($user_error_handling);
} | php | {
"resource": ""
} |
q11056 | Document.getErrorMessage | train | protected function getErrorMessage(array $errors)
{
$error_message = '';
foreach ($errors as $error) {
$error_message .= $this->parseError($error) . PHP_EOL . PHP_EOL;
}
return $error_message;
} | php | {
"resource": ""
} |
q11057 | Document.parseError | train | protected function parseError(LibXMLError $error)
{
$prefix_map = [
LIBXML_ERR_WARNING => '[warning]',
LIBXML_ERR_FATAL => '[fatal]',
LIBXML_ERR_ERROR => '[error]'
];
$prefix = isset($prefix_map[$error->level]) ? $prefix_map[$error->level] : $prefix_map[LIBXML_ERR_ERROR];
$msg_parts = [];
$msg_parts[] = sprintf('%s %s: %s', $prefix, $error->level, trim($error->message));
$msg_parts[] = sprintf('Line: %d', $error->line);
$msg_parts[] = sprintf('Column: %d', $error->column);
if ($error->file) {
$msg_parts[] = sprintf('File: %s', $error->file);
}
return implode(PHP_EOL, $msg_parts);
} | php | {
"resource": ""
} |
q11058 | TokenUtils.positionForSequence | train | public static function positionForSequence(array $sequence, $tokens, $startFrom = null)
{
$seqIterator = (new ArrayObject($sequence))->getIterator();
$tokenIterator = (new ArrayObject($tokens))->getIterator();
if ($startFrom != null) {
$tokenIterator->seek($startFrom);
}
while ($tokenIterator->valid()) {
$seqIterator->rewind();
$keys = array();
list($allowedTokens, $timesAllowed) = $seqIterator->current();
self::seekToNextType($tokenIterator, $allowedTokens);
while ($tokenIterator->valid()) {
if (!$seqIterator->valid()) {
$first = array_shift($keys);
$last = array_pop($keys);
return array($first, $last);
}
list($allowedTokens, $timesAllowed) = $seqIterator->current();
if ($timesAllowed == '*') {
while ($tokenIterator->valid() && self::isTokenType($tokenIterator->current(),
$allowedTokens)) {
$keys[] = $tokenIterator->key();
$tokenIterator->next();
}
} else {
for ($i = 0; $i < $timesAllowed; $i++) {
if (self::isTokenType($tokenIterator->current(), $allowedTokens)) {
$keys[] = $tokenIterator->key();
$tokenIterator->next();
} else {
continue 3;
}
}
}
$seqIterator->next();
}
}
} | php | {
"resource": ""
} |
q11059 | TokenUtils.seekToNextType | train | private static function seekToNextType(ArrayIterator $tokenIterator, $type)
{
while ($tokenIterator->valid()) {
if (self::isTokenType($tokenIterator->current(), $type)) {
return;
}
$tokenIterator->next();
}
} | php | {
"resource": ""
} |
q11060 | TokenUtils.isTokenType | train | public static function isTokenType($token, $types)
{
if (!is_array($types)) {
$types = array($types);
}
return is_array($token) ? in_array($token[0], $types) : in_array($token, $types);
} | php | {
"resource": ""
} |
q11061 | Locales.addLocale | train | public function addLocale($locale)
{
// Get sanitized locale
$locale = Locale::sanitizeLocale($locale);
if (!isset($this->available[$locale])) {
$locale = new Locale($locale);
$this->available[$locale->getLocale()] = $locale;
}
return $this;
} | php | {
"resource": ""
} |
q11062 | Locales.findByCountry | train | public function findByCountry($country)
{
$country = Text::toUpper($country);
foreach ($this->getAvailable() as $locale) {
if ($country == $locale->getCountry(Text::UPPER)) {
return $locale;
}
}
return null;
} | php | {
"resource": ""
} |
q11063 | Locales.findByLanguage | train | public function findByLanguage($language)
{
$language = Text::toLower($language);
foreach ($this->getAvailable() as $locale) {
if ($language == $locale->getLanguage(Text::LOWER)) {
return $locale;
}
}
return null;
} | php | {
"resource": ""
} |
q11064 | Locales.findByLocale | train | public function findByLocale($locale)
{
// Get sanitized locale
$locale = Locale::sanitizeLocale($locale);
return isset($this->available[$locale]) ? $this->available[$locale] : null;
} | php | {
"resource": ""
} |
q11065 | Locales.setActive | train | public function setActive($locale)
{
$active = $this->findByLocale($locale);
if (!$active) {
throw new Exception(sprintf("Locale '%s' not in list.", $locale));
}
// Mark as current locale
$this->active = $active;
// Set as global default for other classes
\Locale::setDefault($active->getLocale());
return $this;
} | php | {
"resource": ""
} |
q11066 | Login.CreateNewUser | train | protected function CreateNewUser()
{
if (!$this->_login->getCanRegister())
{
$this->FormLogin();
return;
}
$myWords = $this->WordCollection();
$this->defaultXmlnukeDocument->setPageTitle($myWords->Value("CREATEUSERTITLE"));
$this->_login->setAction(ModuleActionLogin::NEWUSER);
$this->_login->setNextAction(ModuleActionLogin::NEWUSERCONFIRM);
$this->_login->setPassword("");
$this->_login->setCanRegister(false); // Hide buttons
$this->_login->setCanRetrievePassword(false); // Hide buttons
return;
} | php | {
"resource": ""
} |
q11067 | Login.CreateNewUserConfirm | train | protected function CreateNewUserConfirm()
{
if (!$this->_login->getCanRegister())
{
$this->FormLogin();
return;
}
$myWords = $this->WordCollection();
$container = new XmlnukeUIAlert($this->_context, UIAlert::BoxAlert);
$container->setAutoHide(5000);
$this->_blockCenter->addXmlnukeObject($container);
if (($this->_login->getName() == "") || ($this->_login->getEmail() == "") || ($this->_login->getUsername() == "") ||
!Util::isValidEmail($this->_login->getEmail()))
{
$container->addXmlnukeObject(new XmlnukeText($myWords->Value("INCOMPLETEDATA"), true));
$this->CreateNewUser();
}
elseif (!XmlInputImageValidate::validateText($this->_context))
{
$container->addXmlnukeObject(new XmlnukeText($myWords->Value("OBJECTIMAGEINVALID"), true));
$this->CreateNewUser();
}
else
{
$newpassword = $this->getRandomPassword();
if (!$this->_users->addUser( $this->_login->getName(), $this->_login->getUsername(), $this->_login->getEmail(), $newpassword ) )
{
$container->addXmlnukeObject(new XmlnukeText($myWords->Value("CREATEUSERFAIL"), true));
$this->CreateNewUser();
}
else
{
$this->sendWelcomeMessage($myWords, $this->_context->get("name"), $this->_context->get("newloguser"), $this->_context->get("email"), $newpassword );
$this->_users->Save();
$container->addXmlnukeObject(new XmlnukeText($myWords->Value("CREATEUSEROK"), true));
$container->setUIAlertType(UIAlert::BoxInfo);
$this->FormLogin($block);
}
}
} | php | {
"resource": ""
} |
q11068 | Login.getRandomPassword | train | public function getRandomPassword()
{
//Random rand = new Random();
//int type, number;
$password = "";
for($i=0; $i<7; $i++)
{
$type = rand(0,21) % 3;
$number = rand(0,25);
if ($type == 1)
{
$password = $password . chr(48 + ($number%10));
}
else
{
if ($type == 2)
{
$password = $password . chr(65 + $number);
}
else
{
$password = $password . chr(97 + $number);
}
}
}
return $password;
} | php | {
"resource": ""
} |
q11069 | ListAbstract.input | train | public function input($name, $value = '', $id = '', $class = '', array $attrs = array())
{
return '<input id="' . $id . '" class="' . $class . '" type="' . $this->_type . '" name="' . $name . '"
value="' . $value . '" ' . $this->buildAttrs($attrs) . '/>';
} | php | {
"resource": ""
} |
q11070 | ListAbstract.label | train | public function label($id, $valAlias, $content = '')
{
$class = implode(' ', array(
$this->_jbSrt($this->_type . '-lbl'),
$this->_jbSrt('label-' . $valAlias),
));
return '<label for="' . $id . '" class="' . $class . '">' . $content . '</label>';
} | php | {
"resource": ""
} |
q11071 | ListAbstract._checkedOptions | train | protected function _checkedOptions($value, $selected, array $attrs)
{
$attrs['checked'] = false;
if (is_array($selected)) {
foreach ($selected as $val) {
if ($value == $val) {
$attrs['checked'] = 'checked';
break;
}
}
} else {
if ($value == $selected) {
$attrs['checked'] = 'checked';
}
}
return $attrs;
} | php | {
"resource": ""
} |
q11072 | ListAbstract._elementTpl | train | protected function _elementTpl($name, $value = '', $id = '', $text = '', array $attrs = array())
{
$alias = Str::slug($value, true);
$inpClass = $this->_jbSrt('val-' . $alias);
$input = $this->input($name, $value, $id, $inpClass, $attrs);
if ($this->_tpl === 'default') {
return $input . $this->label($id, $alias, $text);
} elseif ($this->_tpl === 'wrap') {
return $this->label($id, $alias, $input . ' ' . $text);
}
if (is_callable($this->_tpl)) {
return call_user_func($this->_tpl, $this, $name, $value, $id, $text, $attrs);
}
return null;
} | php | {
"resource": ""
} |
q11073 | ListAbstract._setTpl | train | protected function _setTpl($tpl)
{
$this->_tpl = $tpl;
if ($tpl === true) {
$this->_tpl = self::TPL_WRAP;
}
if ($tpl === false) {
$this->_tpl = self::TPL_DEFAULT;
}
} | php | {
"resource": ""
} |
q11074 | BaseRokkaCliCommand.verifyStackExists | train | public function verifyStackExists($stackName, $organization, OutputInterface $output, Image $client = null)
{
if (!$client) {
$client = $this->clientProvider->getImageClient($organization);
}
if (!$stackName || !$this->rokkaHelper->stackExists($client, $stackName, $organization)) {
$output->writeln(
$this->formatterHelper->formatBlock([
'Error!',
'Stack "'.$stackName.'" does not exist on "'.$organization.'" organization!',
], 'error', true)
);
return false;
}
return true;
} | php | {
"resource": ""
} |
q11075 | BaseRokkaCliCommand.resolveOrganizationName | train | public function resolveOrganizationName($organizationName, OutputInterface $output)
{
if (!$organizationName) {
$organizationName = $this->rokkaHelper->getDefaultOrganizationName();
}
if (!$this->rokkaHelper->validateOrganizationName($organizationName)) {
$output->writeln($this->formatterHelper->formatBlock([
'Error!',
'The organization name "'.$organizationName.'" is not valid!',
], 'error', true));
return false;
}
$client = $this->clientProvider->getUserClient();
if ($this->rokkaHelper->organizationExists($client, $organizationName)) {
return $organizationName;
}
$output->writeln($this->formatterHelper->formatBlock([
'Error!',
'The organization "'.$organizationName.'" does not exists!',
], 'error', true));
return false;
} | php | {
"resource": ""
} |
q11076 | BaseRokkaCliCommand.verifySourceImageExists | train | public function verifySourceImageExists($hash, $organizationName, OutputInterface $output, Image $client)
{
if (!$this->rokkaHelper->validateImageHash($hash)) {
$output->writeln($this->formatterHelper->formatBlock([
'Error!',
'The Image HASH "'.$hash.'" is not valid!',
], 'error', true));
return false;
}
if ($this->rokkaHelper->imageExists($client, $hash, $organizationName)) {
return true;
}
$output->writeln($this->formatterHelper->formatBlock([
'Error!',
'The SourceImage "'.$hash.'" has not been found in Organization "'.$organizationName.'"',
], 'error', true));
return false;
} | php | {
"resource": ""
} |
q11077 | HandlerBuilder.build | train | public function build(FormFactoryInterface $form_factory, $data = null)
{
$options = is_callable($this->options) ? call_user_func($this->options, $data) : $this->options;
if (null !== $this->name) {
$form = $form_factory->createNamed($this->name, $this->type, $data, $options);
} else {
$form = $form_factory->create($this->type, $data, $options);
}
return new FormSubmitProcessor($form, $this->on_success, $this->on_failure, $this->form_submit_processor);
} | php | {
"resource": ""
} |
q11078 | FilterComponent.getFilterConditions | train | public function getFilterConditions($plugin = null) {
$filterData = null;
$filterCond = null;
if ($this->_controller->request->is('get')) {
$filterData = $this->_controller->request->query('data.FilterData');
$filterCond = $this->_controller->request->query('data.FilterCond');
} elseif ($this->_controller->request->is('post')) {
$filterData = $this->_controller->request->data('FilterData');
$filterCond = $this->_controller->request->data('FilterCond');
}
$conditions = $this->_modelFilter->buildConditions($filterData, $filterCond, $plugin);
return $conditions;
} | php | {
"resource": ""
} |
q11079 | FilterComponent.getGroupAction | train | public function getGroupAction($groupActions = null) {
if (!$this->_controller->request->is('post')) {
return false;
}
$action = $this->_controller->request->data('FilterGroup.action');
if (empty($action) || (!empty($groupActions) && !is_array($groupActions))) {
return false;
}
if (empty($groupActions)) {
return $action;
} elseif (in_array($action, $groupActions)) {
return $action;
} else {
return false;
}
} | php | {
"resource": ""
} |
q11080 | FilterComponent.getExtendPaginationOptions | train | public function getExtendPaginationOptions($options = null) {
if (empty($options) || !is_array($options)) {
$options = [];
}
if (!property_exists($this->_controller, 'Paginator')) {
throw new InternalErrorException(__d('view_extension', 'Paginator component is not loaded'));
}
$paginatorOptions = $this->_controller->Paginator->mergeOptions(null);
$page = (int)Hash::get($paginatorOptions, 'page');
if (!$this->_controller->RequestHandler->prefers('prt') || ($page > 1)) {
return $options;
}
$options['limit'] = CAKE_THEME_PRINT_DATA_LIMIT;
$options['maxLimit'] = CAKE_THEME_PRINT_DATA_LIMIT;
return $options;
} | php | {
"resource": ""
} |
q11081 | Window.setBusy | train | public function setBusy($bool = true)
{
$this->busyCounter = 0;
$this->isBusy = (bool)$bool;
if ($bool) {
$text = "Please wait...";
if (is_string($bool)) {
$text = (string)$bool;
}
$lbl = Label::create();
$lbl->setText($text)->setTextColor("fff")->setTextSize(6)
->setSize(90, 12)->setAlign("center", "center")
->setPosition($this->busyFrame->getWidth() / 2, -($this->busyFrame->getHeight() / 2));
$this->busyFrame->addChild($lbl);
$quad = Quad::create();
$quad->setStyles("Bgs1", "BgDialogBlur");
$quad->setBackgroundColor("f00")->setSize($this->busyFrame->getWidth(), $this->busyFrame->getHeight());
$this->busyFrame->addChild($quad);
} else {
$this->busyFrame->removeAllChildren();
}
} | php | {
"resource": ""
} |
q11082 | ManiaScriptFactory.createScript | train | public function createScript($params)
{
$className = $this->className;
$filePath = $this->fileLocator->locate('@'.$this->relativePath);
return new $className($filePath, $params);
} | php | {
"resource": ""
} |
q11083 | ProductIndexListener.onProductIndex | train | public function onProductIndex(ResourceControllerEvent $event): void
{
$currentRequest = $this->requestStack->getCurrentRequest();
if (!$currentRequest instanceof Request) {
return;
}
// Only sane way to extract the reference to the taxon
if (!$currentRequest->attributes->has('slug')) {
return;
}
$taxon = $this->taxonRepository->findOneBySlug(
$currentRequest->attributes->get('slug'),
$this->localeContext->getLocaleCode()
);
if (!$taxon instanceof TaxonInterface) {
return;
}
$currentRequest->attributes->set('nglayouts_sylius_taxon', $taxon);
// We set context here instead in a ContextProvider, since sylius.taxon.show
// event happens too late, after onKernelRequest event has already been executed
$this->context->set('sylius_taxon_id', (int) $taxon->getId());
} | php | {
"resource": ""
} |
q11084 | GameCurrencyQueryBuilder.save | train | public function save(Gamecurrency $gamecurrency)
{
// First clear references. entry has no references that needs saving.
$gamecurrency->clearAllReferences(false);
// Save and free memory.
$gamecurrency->save();
GamecurrencyTableMap::clearInstancePool();
} | php | {
"resource": ""
} |
q11085 | PlayerDataProvider.onPlayerHit | train | public function onPlayerHit($params)
{
$this->dispatch(__FUNCTION__, [
$params['shooter'],
$params['victim'],
$params['weapon'],
$params['damage'],
$params['points'],
$params['distance'],
Position::fromArray($params['shooterposition']),
Position::fromArray($params['victimposition']),
]);
} | php | {
"resource": ""
} |
q11086 | PlayerDataProvider.onArmorEmpty | train | public function onArmorEmpty($params)
{
$this->dispatch(__FUNCTION__, [
$params['shooter'],
$params['victim'],
$params['weapon'],
$params['distance'],
Position::fromArray($params['shooterposition']),
Position::fromArray($params['victimposition']),
]);
} | php | {
"resource": ""
} |
q11087 | TicketPayment.onAuthorized | train | public function onAuthorized(ServiceResponse $response)
{
if ($response->getPayment()->Gateway === 'Manual') {
if (($reservation = Reservation::get()->byID($this->owner->ReservationID)) && $reservation->exists()) {
$reservation->complete();
}
}
} | php | {
"resource": ""
} |
q11088 | TicketPayment.onCaptured | train | public function onCaptured(ServiceResponse $response)
{
/** @var Reservation $reservation */
if (($reservation = Reservation::get()->byID($this->owner->ReservationID)) && $reservation->exists()) {
$reservation->complete();
}
} | php | {
"resource": ""
} |
q11089 | Html._ | train | public static function _($render, $ns = __NAMESPACE__)
{
$html = self::getInstance();
$render = Str::low($render);
$alias = $ns . '\\' . $render;
if (!isset($html[$alias])) {
$html[$alias] = self::_register($render, $ns);
}
return $html[$alias];
} | php | {
"resource": ""
} |
q11090 | Html._register | train | private static function _register($render, $ns)
{
return function () use ($render, $ns) {
$render = Str::clean($render);
$render = implode('\\', array(
$ns,
Html::RENDER_DIR,
ucfirst($render)
));
return new $render();
};
} | php | {
"resource": ""
} |
q11091 | SignUpUserCommandBuilder.invitationHandlerArguments | train | private function invitationHandlerArguments($user)
{
return [
$this->container->getDefinition(
'bengor.user.infrastructure.persistence.' . $user . '_repository'
),
$this->container->getDefinition(
'bengor.user.infrastructure.security.symfony.' . $user . '_password_encoder'
),
];
} | php | {
"resource": ""
} |
q11092 | SignUpUserCommandBuilder.withConfirmationSpecification | train | private function withConfirmationSpecification($user)
{
(new EnableUserCommandBuilder($this->container, $this->persistence))->build($user);
return [
'command' => WithConfirmationSignUpUserCommand::class,
'handler' => WithConfirmationSignUpUserHandler::class,
'handlerArguments' => $this->handlerArguments($user),
];
} | php | {
"resource": ""
} |
q11093 | SignUpUserCommandBuilder.byInvitationSpecification | train | private function byInvitationSpecification($user)
{
(new InviteUserCommandBuilder($this->container, $this->persistence))->build($user);
(new ResendInvitationUserCommandBuilder($this->container, $this->persistence))->build($user);
return [
'command' => ByInvitationSignUpUserCommand::class,
'handler' => ByInvitationSignUpUserHandler::class,
'handlerArguments' => $this->invitationHandlerArguments($user),
];
} | php | {
"resource": ""
} |
q11094 | Logger.pushProcessor | train | public function pushProcessor($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
}
array_unshift($this->processors, $callback);
return $this;
} | php | {
"resource": ""
} |
q11095 | ErrorHandler.logError | train | protected function logError(Throwable $e)
{
if ($this->settings['displayErrorDetails']) {
return;
}
if (!$this->logger) {
return;
}
static $errorsLogged = [];
// Get hash of Throwable object
$errorObjectHash = spl_object_hash($e);
// check: only log if we haven't logged this exact error before
if (!isset($errorsLogged[$errorObjectHash])) {
// Log
$this->logger->error(get_class($e), ['exception' => $e]);
// Save information that we have logged this error
$errorsLogged[$errorObjectHash] = true;
}
} | php | {
"resource": ""
} |
q11096 | Chart.setTitle | train | public function setTitle( $title )
{
$this->title = $title;
$this->jsWriter->setOption( 'title', $title );
return $this;
} | php | {
"resource": ""
} |
q11097 | Chart.setAxisOptions | train | public function setAxisOptions( $axis, $name, $value )
{
$this->jsWriter->setAxisOptions( $axis, $name, $value );
return $this;
} | php | {
"resource": ""
} |
q11098 | Chart.setAxisLabel | train | public function setAxisLabel( $axis, $label )
{
if ( in_array( $axis, array( 'x', 'y', 'z' ) ) ) {
$originalAxisOptions = $this->jsWriter->getOption( 'axes', array() );
$desiredAxisOptions = array( "{$axis}axis" => array( 'label' => $label ) );
$this->jsWriter->setOption( 'axes', array_merge_recursive( $originalAxisOptions, $desiredAxisOptions ) );
}
return $this;
} | php | {
"resource": ""
} |
q11099 | Chart.setType | train | public function setType( $type, $seriesTitle = null )
{
$this->jsWriter->setType( $type, $seriesTitle );
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.