_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1100 | Time.dontSeeTimeIsInMins | train | public function dontSeeTimeIsInMins($time, $minutes) {
\PHPUnit_Framework_Assert::assertNotEquals($minutes, $this->_GetNow()->diffInMinutes($this->_ParseDate($time), false));
} | php | {
"resource": ""
} |
q1101 | Time.dontSeeTimeIsInHours | train | public function dontSeeTimeIsInHours($time, $hours) {
\PHPUnit_Framework_Assert::assertNotEquals($hours, $this->_GetNow()->diffInHours($this->_ParseDate($time), false));
} | php | {
"resource": ""
} |
q1102 | Time.seeTimeWasInHours | train | public function seeTimeWasInHours($time, $hours) {
\PHPUnit_Framework_Assert::assertEquals($hours, $this->_ParseDate($time)->diffInHours($this->_GetNow(), false));
} | php | {
"resource": ""
} |
q1103 | Time.seeTimeMatches | train | public function seeTimeMatches($t1, $t2) {
\PHPUnit_Framework_Assert::assertTrue($this->_ParseDate($t1)->eq($this->_ParseDate($t2)));
} | php | {
"resource": ""
} |
q1104 | Time.dontSeeTimeMatches | train | public function dontSeeTimeMatches($t1, $t2) {
\PHPUnit_Framework_Assert::assertTrue($this->_ParseDate($t1)->ne($this->_ParseDate($t2)));
} | php | {
"resource": ""
} |
q1105 | CiscoSparkDriver.getBotId | train | private function getBotId()
{
if (is_null($this->botId)) {
$response = $this->http->get(self::API_ENDPOINT.'people/me', [], $this->getHeaders());
$bot = json_decode($response->getContent());
$this->botId = $bot->id;
}
return $this->botId;
} | php | {
"resource": ""
} |
q1106 | Template.parse | train | public function parse()
{
$strBuffer = parent::parse();
if (TL_MODE == 'BE')
{
$strBuffer = '<div class="tl_ce ' . $this->strTemplate . '">' . $strBuffer . '</div>';
}
return $strBuffer;
} | php | {
"resource": ""
} |
q1107 | Template.addImage | train | public function addImage ($image, $size, $width=0, $height=0)
{
if (!is_array($image))
{
return;
}
if (@unserialize($size) === false)
{
$size = serialize(array((string)$width, (string)$height, $size));
}
$image['size'] = $size;
$image['singleSRC'] = $image['path'];
Pattern::addImageToTemplate($picture = new \stdClass(), $image);
$picture = $picture->picture;
$picture['imageUrl'] = $image['imageUrl'];
$picture['caption'] = $image['caption'];
$picture['id'] = $image['id'];
$picture['uuid'] = $image['uuid'];
$picture['name'] = $image['name'];
$picture['path'] = $image['path'];
$picture['extension'] = $image['extension'];
return $picture;
} | php | {
"resource": ""
} |
q1108 | Template.addCSS | train | public function addCSS ($strCSS, $strType='scss', $bolStatic=true)
{
if ($strCSS == '')
{
return;
}
$strType = strtoupper($strType);
if (!in_array($strType, array('CSS', 'SCSS' , 'LESS')))
{
return;
}
if (!$bolStatic && $strType == 'css')
{
$strKey = substr(md5($strType . $strCSS), 0, 12);
$strPath = 'assets/css/' . $strKey . '.' . $strType;
// Write to a temporary file in the assets folder
if (!file_exists($strPath))
{
$objFile = new File($strPath, true);
$objFile->write($strCSS);
$objFile->close();
}
// Add the file path to TL_USER_CSS
$GLOBALS[TL_USER_CSS][] = $strPath;
return;
}
// Add to the combined CSS string
$GLOBALS['TL_CTB_' . $strType] .= $strCSS;
} | php | {
"resource": ""
} |
q1109 | Template.addJS | train | public function addJS ($strJS, $bolStatic=true)
{
if ($strJS == '')
{
return;
}
if (!$bolStatic)
{
$strKey = substr(md5('js' . $strJS), 0, 12);
$strPath = 'assets/js/' . $strKey . '.js';
// Write to a temporary file in the assets folder
if (!file_exists($strPath))
{
$objFile = new File($strPath, true);
$objFile->write($strCSS);
$objFile->close();
}
// Add the file path to TL_USER_CSS
$GLOBALS[TL_JAVASCRIPT][] = $strPath;
return;
}
// Add to the combined CSS string
$GLOBALS['TL_CTB_JS'] .= $strJS;
} | php | {
"resource": ""
} |
q1110 | Template.prevElement | train | public function prevElement ()
{
if (($arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'.$this->pid]) === null)
{
$objCte = \ContentModel::findPublishedByPidAndTable($this->pid, $this->ptable);
if ($objCte === null)
{
return;
}
$arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'.$this->pid] = $objCte->fetchEach('type');
}
return $arrTypes[array_keys($arrTypes)[array_search($this->id, array_keys($arrTypes)) - 1]];
} | php | {
"resource": ""
} |
q1111 | Template.insert | train | public function insert($name, array $data=null)
{
// Register the template file (to find the custom templates)
if (!array_key_exists($name, TemplateLoader::getFiles()))
{
$objTheme = \LayoutModel::findById(Controller::getLayoutId($this->ptable, $this->pid))->getRelated('pid');
TemplateLoader::addFile($name, $objTheme->templates);
}
/** @var \Template $tpl */
if ($this instanceof \Template)
{
$tpl = new static($name);
}
elseif (TL_MODE == 'BE')
{
$tpl = new BackendTemplate($name);
}
else
{
$tpl = new FrontendTemplate($name);
}
if ($data !== null)
{
$tpl->setData($data);
}
echo $tpl->parse();
} | php | {
"resource": ""
} |
q1112 | WebSocketEventTrait.onMessage | train | public function onMessage(Server $server, Frame $frame)
{
$fd = $frame->fd;
// init fd and coId mapping
WebSocketContext::setFdToCoId($fd);
App::trigger(WsEvent::ON_MESSAGE, null, $server, $frame);
$this->log("received message: {$frame->data} from fd #{$fd}, co ID #" . Coroutine::tid(), [], 'debug');
/** @see Dispatcher::message() */
\bean('wsDispatcher')->message($server, $frame);
// delete coId to fd mapping
WebSocketContext::delFdByCoId();
RequestContext::destroy();
} | php | {
"resource": ""
} |
q1113 | AbstractBoleto.getTotal | train | public function getTotal()
{
return (float)($this->valorDocumento + $this->taxa + $this->outrosAcrescimos) - ($this->desconto + $this->outrasDeducoes);
} | php | {
"resource": ""
} |
q1114 | ArticlesController.index | train | public function index(ArticlesDataTable $dataTable)
{
$categories = [];
$allYesNo = [];
$statuses = [];
if (! request()->wantsJson()) {
$categories = Category::root()->getDescendants()->map(function(Category $category) {
$category->title = $category->present()->name;
return $category;
})->pluck('title', 'id');
$categories = collect(['' => '- Select Category -'])->union($categories);
$allYesNo = [
'' => '- Select Article Type -',
0 => 'Article',
1 => 'Page',
];
$statuses = [
'' => '- Select Status -',
0 => 'Unpublished',
1 => 'Published',
];
}
return $dataTable->render('administrator.articles.index', compact('categories', 'allYesNo', 'statuses'));
} | php | {
"resource": ""
} |
q1115 | ArticlesController.create | train | public function create(Article $article)
{
$article->published = true;
$article->setHighestOrderNumber();
$tags = Article::existingTags()->pluck('name');
return view('administrator.articles.create', compact('article', 'tags'));
} | php | {
"resource": ""
} |
q1116 | ArticlesController.store | train | public function store(ArticlesFormRequest $request)
{
$article = new Article;
$article->fill($request->all());
$article->published = $request->get('published', false);
$article->featured = $request->get('featured', false);
$article->authenticated = $request->get('authenticated', false);
$article->is_page = $request->get('is_page', false);
$article->save();
$article->permissions()->sync($request->get('permissions', []));
if ($request->tags) {
$article->tag(explode(',', $request->tags));
}
event(new ArticleWasCreated($article));
flash()->success(trans('cms::article.store.success'));
return redirect()->route('administrator.articles.index');
} | php | {
"resource": ""
} |
q1117 | ArticlesController.edit | train | public function edit(Article $article)
{
$tags = Article::existingTags()->pluck('name');
$selectedTags = implode(',', $article->tagNames());
return view('administrator.articles.edit', compact('article', 'tags', 'selectedTags'));
} | php | {
"resource": ""
} |
q1118 | ArticlesController.update | train | public function update(Article $article, ArticlesFormRequest $request)
{
$article->fill($request->all());
$article->published = $request->get('published', false);
$article->featured = $request->get('featured', false);
$article->authenticated = $request->get('authenticated', false);
$article->is_page = $request->get('is_page', false);
$article->save();
$article->permissions()->sync($request->get('permissions', []));
if ($request->tags) {
$article->retag(explode(',', $request->tags));
}
event(new ArticleWasUpdated($article));
flash()->success(trans('cms::article.update.success'));
return redirect()->route('administrator.articles.index');
} | php | {
"resource": ""
} |
q1119 | RedirectCommandController.listCommand | train | public function listCommand($host = null, $match = null)
{
$outputByHost = function ($host = null) use ($match) {
$redirects = $this->redirectStorage->getAll($host);
$this->outputLine();
if ($host !== null) {
$this->outputLine('<info>==</info> <b>Redirect for %s</b>', [$host]);
} else {
$this->outputLine('<info>==</info> <b>Redirects valid for all hosts</b>', [$host]);
}
if ($match !== null) {
$this->outputLine(' <info>++</info> <b>Only showing redirects where source or target URI matches <u>%s</u></b>', [$match]);
sleep(1);
}
$this->outputLine();
/** @var $redirect RedirectInterface */
foreach ($redirects as $redirect) {
$outputLine = function ($source, $target, $statusCode) {
$this->outputLine(' <comment>></comment> %s <info>=></info> %s <comment>(%d)</comment>', [
$source,
$target,
$statusCode
]);
};
$source = $redirect->getSourceUriPath();
$target = $redirect->getTargetUriPath();
$statusCode = $redirect->getStatusCode();
if ($match === null) {
$outputLine($source, $target, $statusCode);
} else {
$regexp = sprintf('#%s#', $match);
$matches = preg_grep($regexp, [$target, $source]);
if (count($matches) > 0) {
$replace = "<error>$0</error>";
$source = preg_replace($regexp, $replace, $source);
$target = preg_replace($regexp, $replace, $target);
$outputLine($source, $target, $statusCode);
}
}
}
};
if ($host !== null) {
$outputByHost($host);
} else {
$hosts = $this->redirectStorage->getDistinctHosts();
array_map($outputByHost, $hosts);
}
$this->outputLine();
} | php | {
"resource": ""
} |
q1120 | RedirectCommandController.exportCommand | train | public function exportCommand($filename = null, $host = null)
{
if (!class_exists(Writer::class)) {
$this->outputWarningForLeagueCsvPackage();
}
$writer = Writer::createFromFileObject(new \SplTempFileObject());
if ($host !== null) {
$redirects = $this->redirectStorage->getAll($host);
} else {
$redirects = new \AppendIterator();
foreach ($this->redirectStorage->getDistinctHosts() as $host) {
$redirects->append($this->redirectStorage->getAll($host));
}
}
/** @var $redirect RedirectInterface */
foreach ($redirects as $redirect) {
$writer->insertOne([
$redirect->getSourceUriPath(),
$redirect->getTargetUriPath(),
$redirect->getStatusCode(),
$redirect->getHost()
]);
}
if ($filename === null) {
$writer->output();
} else {
file_put_contents($filename, (string)$writer);
}
} | php | {
"resource": ""
} |
q1121 | RedirectCommandController.removeCommand | train | public function removeCommand($source, $host = null)
{
$redirect = $this->redirectStorage->getOneBySourceUriPathAndHost($source, $host);
if ($redirect === null) {
$this->outputLine('There is no redirect with the source URI path "%s", maybe you forgot the --host argument ?', [$source]);
$this->quit(1);
}
$this->redirectStorage->removeOneBySourceUriPathAndHost($source, $host);
$this->outputLine('Removed redirect with the source URI path "%s"', [$source]);
} | php | {
"resource": ""
} |
q1122 | RedirectCommandController.removeByHostCommand | train | public function removeByHostCommand($host)
{
if ($host === 'all') {
$this->redirectStorage->removeByHost(null);
$this->outputLine('Removed redirects matching all hosts');
} else {
$this->redirectStorage->removeByHost($host);
$this->outputLine('Removed all redirects for host "%s"', [$host]);
}
} | php | {
"resource": ""
} |
q1123 | MetaTagAwareTrait.render | train | public function render()
{
$block = $this->config('viewBlockName');
foreach ((array)$this->config('tags') as $namespace => $values) {
foreach ($values as $tag => $content) {
$property = "$namespace:$tag";
if (!is_array($content)) {
$this->Html->meta(null, null, compact('property', 'content', 'block'));
continue;
}
$options = array_pop($content);
$content = array_shift($content);
$this->Html->meta(null, null, compact('property', 'content', 'block'));
foreach ($options as $key => $value) {
if (!is_array($value)) {
$this->Html->meta(null, null, [
'property' => "$property:$key",
'content' => $value,
'block' => $block
]);
continue;
}
foreach ($value as $content) {
$this->Html->meta(null, null, [
'property' => "$property:$key",
'content' => $content,
'block' => $block
]);
}
}
}
}
return $this->_View->fetch($block);
} | php | {
"resource": ""
} |
q1124 | UploadCommand.uploadFileToCloudinary | train | protected function uploadFileToCloudinary($file, $publicId)
{
$result = $this->uploader->upload(
$file->getRealPath(),
[
'public_id' => $publicId,
]
);
return $result;
} | php | {
"resource": ""
} |
q1125 | PhpOpcache.memory | train | public function memory()
{
$usedInBytes = $this->data['memory_usage']['used_memory'];
$wastedInBytes = $this->data['memory_usage']['wasted_memory'];
$sizeInBytes = $usedInBytes + $wastedInBytes + $this->data['memory_usage']['free_memory'];
return new Memory(
$this->bytesToMb($usedInBytes),
$this->bytesToMb($sizeInBytes),
$this->bytesToMb($wastedInBytes)
);
} | php | {
"resource": ""
} |
q1126 | PhpOpcache.scripts | train | public function scripts()
{
$scripts = array_map(function ($scriptData) {
/* @var $scriptData array<string, mixed> */
return new Script(
$scriptData['full_path'],
$this->bytesToMb($scriptData['memory_consumption']),
$scriptData['hits'],
new \DateTimeImmutable('@' . $scriptData['last_used_timestamp'])
);
}, $this->data['scripts']);
return new ScriptCollection($scripts, $this->calculateCacheSlots());
} | php | {
"resource": ""
} |
q1127 | PhpOpcache.internedStrings | train | public function internedStrings(): InternedStrings
{
$usageInMb = $this->bytesToMb($this->data['interned_strings_usage']['used_memory'] ?? 0);
$sizeInMb = $this->bytesToMb($this->data['interned_strings_usage']['buffer_size'] ?? 0);
$freeInMb = $this->bytesToMb($this->data['interned_strings_usage']['free_memory'] ?? 0);
$stringCount = $this->data['interned_strings_usage']['number_of_strings'] ?? 0;
return new InternedStrings(
$usageInMb,
$sizeInMb,
$freeInMb,
$stringCount
);
} | php | {
"resource": ""
} |
q1128 | PhpOpcache.calculateCacheSlots | train | protected function calculateCacheSlots()
{
$cachedScripts = $this->data['opcache_statistics']['num_cached_scripts'];
$wasted = $this->data['opcache_statistics']['num_cached_keys'] - $cachedScripts;
return new ScriptSlots(
$cachedScripts,
$this->data['opcache_statistics']['max_cached_keys'],
$wasted
);
} | php | {
"resource": ""
} |
q1129 | SecurityAlertCheckTask.discernIdentifier | train | protected function discernIdentifier($cve, $title)
{
$identifier = $cve;
if (!$identifier || $identifier === '~') {
$identifier = explode(':', $title);
$identifier = array_shift($identifier);
}
$this->extend('updateIdentifier', $identifier, $cve, $title);
return $identifier;
} | php | {
"resource": ""
} |
q1130 | ArticlePresenter.published | train | public function published()
{
$class = $this->entity->published ? 'fa fa-check-circle-o' : 'fa fa-circle-o';
$state = $this->entity->published ? 'Published' : 'Unpublished';
return html()->tag('i', '', ["class" => $class, "data-toggle" => "tooltip", "data-title" => $state]);
} | php | {
"resource": ""
} |
q1131 | ArticlePresenter.author | train | public function author()
{
$author = ! empty($this->entity->author_alias)
? $this->entity->author_alias
: $this->entity->createdByName;
return $author ?? config('site.author');
} | php | {
"resource": ""
} |
q1132 | ArticlePresenter.title | train | public function title()
{
$heading = null;
if (session()->has('active_menu')) {
$heading = session('active_menu')->param('page_heading');
}
return $heading ? $heading : $this->entity->title;
} | php | {
"resource": ""
} |
q1133 | ArticlePresenter.introText | train | public function introText()
{
$body = explode('<hr id="system-readmore" />', $this->entity->body);
if ($body[0] === $this->entity->body) {
return '';
}
return $body[0];
} | php | {
"resource": ""
} |
q1134 | ArticlePresenter.image | train | public function image()
{
if ($image = $this->articleImage()) {
return $image;
}
if ($image = $this->introImage()) {
return $image;
}
return config('article.image');
} | php | {
"resource": ""
} |
q1135 | WebSocketContext.setFdToCoId | train | public static function setFdToCoId(int $fd)
{
$cid = self::getCoroutineId();
self::$map[$cid] = $fd;
} | php | {
"resource": ""
} |
q1136 | WebSocketContext.delFdByCoId | train | public static function delFdByCoId(int $cid = null): bool
{
$cid = $cid > -1 ? $cid : self::getCoroutineId();
if (isset(self::$map[$cid])) {
unset(self::$map[$cid]);
return true;
}
return false;
} | php | {
"resource": ""
} |
q1137 | CacheRepository.findOrFail | train | public function findOrFail($id)
{
return $this->cache->rememberForever('extension.' . $id, function () use ($id){
return $this->repository->findOrFail($id);
});
} | php | {
"resource": ""
} |
q1138 | ViewComposerServiceProvider.bootAdministratorViewComposer | train | protected function bootAdministratorViewComposer()
{
view()->composer('administrator.widgets.*', function (View $view) {
/** @var \Yajra\CMS\Themes\Repositories\Repository $themes */
$themes = $this->app['themes'];
$theme = $themes->current();
$positions = $theme->positions;
$data = [];
foreach ($positions as $position) {
$data[$position] = Str::title($position);
}
$view->with('widget_positions', $data);
$view->with('theme', $theme);
/** @var \Yajra\CMS\Repositories\Extension\Repository $extensions */
$extensions = $this->app['extensions'];
$widgets = $extensions->allWidgets()->filter(function ($extension) {
return $extension->enabled;
});
$view->with('extensions', $widgets);
});
view()->composer(['administrator.partials.permissions'], function (View $view) {
$view->with('permissions', Permission::orderBy('resource')->get());
});
} | php | {
"resource": ""
} |
q1139 | CssPathToUrl.replaceCssPaths | train | public function replaceCssPaths(array $links)
{
foreach ($links as $key => $link) {
if (!$this->isExternalStylesheet($link)) {
$links[$key] = $this->getUrl() . $link;
}
}
return $links;
} | php | {
"resource": ""
} |
q1140 | UtilitiesController.backup | train | public function backup($task = 'run')
{
if (! in_array($task, ['run', 'clean'])) {
$message = trans('cms::utilities.backup.not_allowed',
['task' => $task]) . trans('cms::utilities.field.executed_by',
['name' => $this->getCurrentUserName()]);
$this->log->info($message);
return $this->notifyError($message);
}
Artisan::call('backup:' . $task);
$message = $task == 'clean' ? trans('cms::utilities.backup.cleanup_complete') : trans('cms::utilities.backup.complete');
$this->log->info($message . trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()]));
return $this->notifySuccess($message);
} | php | {
"resource": ""
} |
q1141 | UtilitiesController.cache | train | public function cache()
{
Artisan::call('cache:clear');
$this->log->info(trans('cms::utilities.cache.success') . trans('cms::utilities.field.executed_by',
['name' => $this->getCurrentUserName()]));
return $this->notifySuccess(trans('cms::utilities.cache.success'));
} | php | {
"resource": ""
} |
q1142 | UtilitiesController.views | train | public function views()
{
Artisan::call('view:clear');
$this->log->info(sprintf("%s %s",
trans('cms::utilities.views.success'),
trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
));
return $this->notifySuccess(trans('cms::utilities.views.success'));
} | php | {
"resource": ""
} |
q1143 | UtilitiesController.route | train | public function route($task)
{
if (! in_array($task, ['cache', 'clear'])) {
$this->log->info(sprintf("%s %s",
trans('cms::utilities.route.not_allowed', ['task' => $task]),
trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
));
return $this->notifyError($message);
}
$message = $task == 'cache' ? trans('cms::utilities.route.cached') : trans('cms::utilities.route.cleared');
$this->log->info(sprintf("%s %s",
$message,
trans('cms::utilities.field.executed_by', ['name' => $this->getCurrentUserName()])
));
try {
Artisan::call('route:' . $task);
} catch (\Exception $e) {
return $this->notifyError($e->getMessage());
}
return $this->notifySuccess($message);
} | php | {
"resource": ""
} |
q1144 | UtilitiesController.logs | train | public function logs(Request $request, DataTables $dataTables)
{
if ($request->input('l')) {
LaravelLogViewer::setFile(base64_decode($request->input('l')));
}
if ($request->input('dl')) {
return response()->download(LaravelLogViewer::pathToLogFile(base64_decode($request->input('dl'))));
} elseif ($request->has('del')) {
File::delete(LaravelLogViewer::pathToLogFile(base64_decode($request->input('del'))));
return redirect()->to($request->url());
}
$logs = LaravelLogViewer::all();
if ($request->wantsJson()) {
return $dataTables->collection(collect($logs))
->editColumn('stack', '{!! nl2br($stack) !!}')
->editColumn('level', function ($log) {
$content = html()->tag('span', '', [
'class' => "glyphicon glyphicon-{$log['level_img']}-sign",
]);
$content .= ' ' . $log['level'];
return html()->tag('span', $content, ['class' => "text-{$log['level_class']}"]);
})
->addColumn('content', function ($log) {
$html = '';
if ($log['stack']) {
$html = '<a class="pull-right expand btn btn-default btn-xs"><span class="glyphicon glyphicon-search"></span></a>';
}
$html .= $log['text'];
if (isset($log['in_file'])) {
$html .= '<br>' . $log['in_file'];
}
return $html;
})
->rawColumns(['content'])
->toJson();
}
return view('administrator.utilities.log', [
'logs' => $logs,
'files' => LaravelLogViewer::getFiles(true),
'current_file' => LaravelLogViewer::getFileName(),
]);
} | php | {
"resource": ""
} |
q1145 | PdfGenerator.generate | train | public function generate($input, $output, array $options = array(),
$overwrite = false)
{
$this->log(sprintf(
'Generate from file (%s) to file (%s)',
$input, $output
));
return $this->getGenerator()->generate(
$input, $output, $options, $overwrite
);
} | php | {
"resource": ""
} |
q1146 | PdfGenerator.generateFromHtml | train | public function generateFromHtml($html, $output, array $options = array(),
$overwrite = false)
{
$this->log(sprintf('Generate output in file (%s) from html.', $output));
return $this->getGenerator()->generateFromHtml(
$html, $output, $options, $overwrite
);
} | php | {
"resource": ""
} |
q1147 | PdfGenerator.getOutput | train | public function getOutput($input, array $options = array())
{
$this->log(sprintf('Getting output from file (%s)', $input));
return $this->getGenerator()->getOutput($input, $options);
} | php | {
"resource": ""
} |
q1148 | PdfGenerator.getOutputFromView | train | public function getOutputFromView($view, array $parameters = array(),
array $options = array())
{
$this->log(sprintf('Get converted output from view (%s).', $view));
$html = $this->getTemplatingEngine()->render($view, $parameters);
return $this->getOutputFromHtml($html, $options);
} | php | {
"resource": ""
} |
q1149 | PdfGenerator.downloadFromView | train | public function downloadFromView($view, array $parameters = array(),
array $options = array())
{
$this->log(sprintf('Download pdf from view (%s).', $view));
$contentDisposition = 'attachment; filename="' . $this->getName() . '"';
return $this->generateResponse($view, $contentDisposition, $parameters,
$options);
} | php | {
"resource": ""
} |
q1150 | PdfGenerator.generateResponse | train | private function generateResponse($view, $contentDisposition, $parameters,
$options)
{
return new Response(
$this->getOutputFromView($view, $parameters, $options),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => $contentDisposition,
)
);
} | php | {
"resource": ""
} |
q1151 | CoreServiceProvider.bootCustomBladeDirectives | train | protected function bootCustomBladeDirectives()
{
/** @var BladeCompiler $blade */
$blade = $this->app['blade.compiler'];
$blade->directive('tooltip', function ($expression) {
return "<?php echo app('Yajra\\CMS\\View\\Directives\\TooltipDirective')->handle({$expression}); ?>";
});
$blade->directive('pageHeader', function ($expression) {
return "<?php echo app('Yajra\\CMS\\View\\Directives\\PageHeaderDirective')->handle({$expression}); ?>";
});
$blade->directive('error', function ($expression) {
return "<?php echo app('Yajra\\CMS\\View\\Directives\\ErrorDirective')->handle({$expression}); ?>";
});
} | php | {
"resource": ""
} |
q1152 | CoreServiceProvider.registerProviders | train | protected function registerProviders()
{
$this->app->register(ConfigurationServiceProvider::class);
$this->app->register(RouteServiceProvider::class);
$this->app->register(ViewComposerServiceProvider::class);
$this->app->register(BaumServiceProvider::class);
$this->app->register(RepositoryServiceProvider::class);
$this->app->register(FormServiceProvider::class);
$this->app->register(WidgetServiceProvider::class);
$this->app->register(TaggingServiceProvider::class);
} | php | {
"resource": ""
} |
q1153 | CoreServiceProvider.registerBindings | train | protected function registerBindings()
{
$this->app->singleton(PageHeaderDirective::class, PageHeaderDirective::class);
$this->app->singleton(TooltipDirective::class, TooltipDirective::class);
$this->app->singleton(SearchEngine::class, LocalSearch::class);
} | php | {
"resource": ""
} |
q1154 | RolesController.create | train | public function create()
{
$role = new Role;
$permissions = Permission::all();
$selectedPermissions = $this->request->old('permissions', []);
return view('administrator.roles.create', compact('role', 'permissions', 'selectedPermissions'));
} | php | {
"resource": ""
} |
q1155 | RolesController.store | train | public function store()
{
$this->validate($this->request, [
'name' => 'required',
'slug' => 'required|unique:roles,slug',
]);
$role = Role::create($this->request->all());
$role->syncPermissions($this->request->get('permissions', []));
flash()->success('Role ' . $role->name . ' successfully created!');
return redirect()->route('administrator.roles.index');
} | php | {
"resource": ""
} |
q1156 | RolesController.update | train | public function update(Role $role)
{
$this->validate($this->request, [
'name' => 'required',
'slug' => 'required|unique:roles,slug,' . $role->id,
]);
$role->name = $this->request->get('name');
if (! $role->system) {
$role->slug = $this->request->get('slug');
}
$role->save();
$role->syncPermissions($this->request->get('permissions', []));
flash()->success('Role ' . $role->name . ' successfully updated!');
return redirect()->route('administrator.roles.index');
} | php | {
"resource": ""
} |
q1157 | RolesController.destroy | train | public function destroy(Role $role)
{
if (! $role->system) {
try {
$role->delete();
return $this->notifySuccess('Role successfully deleted!');
} catch (QueryException $e) {
return $this->notifyError($e->getMessage());
}
}
return $this->notifyError('Role is protected and cannot be deleted!');
} | php | {
"resource": ""
} |
q1158 | CLI.printPHPCSUsage | train | public function printPHPCSUsage()
{
ob_start();
parent::printPHPCSUsage();
$help = ob_get_contents();
ob_end_clean();
echo $this->fixHelp($help);
} | php | {
"resource": ""
} |
q1159 | CLI.fixHelp | train | private function fixHelp($help)
{
$help = $this->fixCLIName($help);
$help = $this->fixStandard($help);
return $help;
} | php | {
"resource": ""
} |
q1160 | Post.getThumbnailImage | train | public function getThumbnailImage($alias, $options=[])
{
$thumbnail = $this->getThumbnailModel();
if (empty($thumbnail)) {
return '';
}
return $thumbnail->getThumbImage($alias, $options);
} | php | {
"resource": ""
} |
q1161 | ImportResolver.getDeclaringClass | train | private function getDeclaringClass(\Reflector $reflector) : ?\ReflectionClass
{
if ($reflector instanceof \ReflectionClass) {
return $reflector;
}
if ($reflector instanceof \ReflectionProperty) {
return $reflector->getDeclaringClass();
}
if ($reflector instanceof \ReflectionMethod) {
return $reflector->getDeclaringClass();
}
if ($reflector instanceof \ReflectionParameter) {
return $reflector->getDeclaringClass();
}
return null;
} | php | {
"resource": ""
} |
q1162 | CloudinaryExtension.getUrl | train | public function getUrl($id, $options = [])
{
$cloudinary = $this->cloudinary;
return $cloudinary::cloudinary_url($id, $options);
} | php | {
"resource": ""
} |
q1163 | SnapshotsManager.getAssertionIdentifier | train | public static function getAssertionIdentifier($identifier = null)
{
// Keep a registry of how many assertions were run
// in this test suite, and in this test
$methodName = static::$suite->getName();
static::$assertionsInTest[$methodName] = isset(static::$assertionsInTest[$methodName])
? static::$assertionsInTest[$methodName]
: -1;
$name = $methodName.'-'.++static::$assertionsInTest[$methodName];
$name = $identifier ? $name.': '.$identifier : $name;
return $name;
} | php | {
"resource": ""
} |
q1164 | DynamicMenusBuilder.generateMenu | train | protected function generateMenu($menuBuilder, $menu)
{
$subMenu = $this->registerMenu($menuBuilder, $menu);
$menu->children->each(function (Menu $subItem) use ($subMenu) {
$subMenuChild = $this->registerMenu($subMenu, $subItem);
if (count($subItem->children)) {
$this->generateMenu($subMenuChild, $subItem);
}
});
} | php | {
"resource": ""
} |
q1165 | JSToHTML.convertToString | train | public function convertToString($html)
{
$externalJavaScript = $this->extractExternalJavaScript($html);
return $this->replaceJavaScriptTags($html, $externalJavaScript);
} | php | {
"resource": ""
} |
q1166 | JSToHTML.extractExternalJavaScript | train | public function extractExternalJavaScript($html)
{
$matches = array();
preg_match_all(
'!' . $this->getExternalJavaScriptRegex() . '!isU',
$html, $matches
);
$links = $this->createJavaScriptPaths($matches['links']);
return array('tags' => $matches[0], 'links' => $links);
} | php | {
"resource": ""
} |
q1167 | JSToHTML.createJavaScriptPaths | train | private function createJavaScriptPaths(array $javascripts)
{
$files = array();
foreach ($javascripts as $file) {
if (!$this->isExternalJavaScriptFile($file)) {
if (false !== strpos($file, '?')) {
$file = strstr($file, '?', true);
}
$file = $this->getBasePath() . $file;
}
$files[] = $file;
}
return $files;
} | php | {
"resource": ""
} |
q1168 | JSToHTML.getJavaScriptContent | train | private function getJavaScriptContent($path)
{
if ($this->isExternalJavaScriptFile($path)) {
$fileData = $this->getRequestHandler()->getContent($path);
} else {
$fileData = '';
if (file_exists($path)) {
$fileData = file_get_contents($path);
}
}
return "<script type=\"text/javascript\">\n" . $fileData . "</script>";
} | php | {
"resource": ""
} |
q1169 | JSToHTML.replaceJavaScriptTags | train | private function replaceJavaScriptTags($html, array $javaScriptFiles)
{
foreach ($javaScriptFiles['links'] as $key => $file) {
if (!$this->isExternalJavaScriptFile($file)) {
$html = str_replace(
$javaScriptFiles['tags'][$key],
$this->getJavaScriptContent($file),
$html
);
}
}
return $html;
} | php | {
"resource": ""
} |
q1170 | Configuration.key | train | public static function key($key)
{
$config = static::where('key', $key)->first();
return $config->value ?? config($key, null);
} | php | {
"resource": ""
} |
q1171 | CategoryPresenter.slugList | train | public function slugList()
{
$categories = explode('/', $this->alias());
$html = [];
foreach ($categories as $category) {
$html[] = new HtmlString('<span class="label label-info">' . e(Str::title($category)) . '</span> ');
}
return new HtmlString(implode('', $html));
} | php | {
"resource": ""
} |
q1172 | WsCommand.start | train | public function start()
{
$server = $this->createServerManager();
// 是否正在运行
if ($server->isRunning()) {
$serverOpts = $server->getServerSetting();
\output()->writeln("<error>The server have been running!(PID: {$serverOpts['masterPid']})</error>", true, true);
} else {
$serverOpts = $server->getServerSetting();
}
// 启动参数
$this->configServer($server);
$ws = $server->getWsSettings();
$tcp = $server->getTcpSetting();
// Setting
$workerNum = $server->setting['worker_num'];
// Ws(http) 启动参数
$wsHost = $ws['host'];
$wsPort = $ws['port'];
$wsMode = $ws['mode'];
$wsType = $ws['type'];
$httpStatus = $ws['enable_http'] ? '<info>Enabled</info>' : '<warning>Disabled</warning>';
// TCP 启动参数
$tcpHost = $tcp['host'];
$tcpPort = $tcp['port'];
$tcpType = $tcp['type'];
$tcpStatus = $serverOpts['tcpable'] ? '<info>Enabled</info>' : '<warning>Disabled</warning>';
// 信息面板
$lines = [
' Server Information ',
'************************************************************************************',
"* WS | host: <note>$wsHost</note>, port: <note>$wsPort</note>, type: <note>$wsType</note>, worker: <note>$workerNum</note>, mode: <note>$wsMode</note> (http is $httpStatus)",
"* TCP | host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, type: <note>$tcpType</note>, worker: <note>$workerNum</note> ($tcpStatus)",
'************************************************************************************',
];
// 启动服务器
\output()->writeln(implode("\n", $lines));
$server->start();
} | php | {
"resource": ""
} |
q1173 | WsCommand.reload | train | public function reload()
{
$server = $this->createServerManager();
if (!$server->isRunning()) {
\output()->writeln('<error>The server is not running! cannot reload</error>', true, true);
}
\output()->writeln(sprintf('<info>Server %s is reloading</info>', input()->getScript()));
$reloadTask = input()->hasOpt('t');
$server->reload($reloadTask);
\output()->writeln(sprintf('<success>Server %s reload success</success>', input()->getScript()));
} | php | {
"resource": ""
} |
q1174 | WsCommand.stop | train | public function stop()
{
$server = $this->createServerManager();
// 是否已启动
if (!$server->isRunning()) {
\output()->writeln('<error>The server is not running! cannot stop</error>', true, true);
}
// pid文件
$serverOpts = $server->getServerSetting();
$pidFile = $serverOpts['pfile'];
\output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getScript()));
$result = $server->stop();
// 停止失败
if (!$result) {
\output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getScript()), true, true);
}
//删除pid文件
@unlink($pidFile);
\output()->writeln(sprintf('<success>Swoft %s stop success!</success>', input()->getScript()));
} | php | {
"resource": ""
} |
q1175 | WsCommand.restart | train | public function restart()
{
$server = $this->createServerManager();
// 是否已启动
if ($server->isRunning()) {
$this->stop();
}
// 重启默认是守护进程
$server->setDaemonize();
$this->start();
} | php | {
"resource": ""
} |
q1176 | Helper.cutStr | train | public static function cutStr($str, $length=100, $postfix='...')
{
if ( strlen($str) < $length)
return $str;
$temp = substr($str, 0, $length);
return substr($temp, 0, strrpos($temp, ' ') ) . $postfix;
} | php | {
"resource": ""
} |
q1177 | Helper.isJustInstalled | train | public static function isJustInstalled()
{
$types = Type::find()->all();
$categories = Category::find()->all();
return empty($types) || empty($categories) ? : false;
} | php | {
"resource": ""
} |
q1178 | tl_settings_advanced_classes.getAvailableSetFiles | train | public function getAvailableSetFiles()
{
$arrSets = array();
foreach ($GLOBALS['TL_CONFIG']['advancedClassesSets'] as $key => $value)
{
if(!strpos($value,"system/")!==false)
{
$arrSets[$value] = basename( $value ) . ' (custom)';
continue;
}
$arrSets[$value] = basename( $value );
}
return $arrSets;
} | php | {
"resource": ""
} |
q1179 | Request.authorizeResource | train | protected function authorizeResource($resource)
{
if ($this->isEditing($resource)) {
return $this->user()->can($resource . '.update');
}
return $this->user()->can($resource . '.create');
} | php | {
"resource": ""
} |
q1180 | HasParameters.setParametersAttribute | train | public function setParametersAttribute($parameters)
{
if (is_array($parameters)) {
$this->attributes['parameters'] = json_encode($parameters);
} else {
$this->attributes['parameters'] = $parameters;
}
} | php | {
"resource": ""
} |
q1181 | ImageBrowserController.index | train | public function index(Request $request)
{
$currentPath = $request->get('path');
$dir = storage_path('app/public/' . $currentPath);
$imageFiles = $this->getImageFiles($dir);
foreach (Finder::create()->in($dir)->sortByType()->directories() as $file) {
$imageFiles->name($file->getBaseName());
}
$files = new Collection;
$parts = explode('/', $currentPath);
array_pop($parts);
if ($parts <> '' && $currentPath <> '') {
$files->push([
'name' => '.. Up',
'relPath' => implode('/', $parts),
'type' => 'dir',
'url' => \Storage::url($currentPath),
]);
}
foreach ($imageFiles as $file) {
$path = str_replace(storage_path('app/public/'), '', $file->getRealPath());
$files->push([
'name' => $file->getFilename(),
'relPath' => $path,
'type' => $file->getType(),
'url' => \Storage::url($path),
]);
}
return response()->json($files->groupBy('type'));
} | php | {
"resource": ""
} |
q1182 | ImageBrowserController.getImageFiles | train | protected function getImageFiles($path)
{
$finder = Finder::create()->in($path)->sortByType()->depth(0);
foreach (config('media.images_ext') as $file) {
$finder->name('*' . $file);
}
return $finder;
} | php | {
"resource": ""
} |
q1183 | PostController.actionUpdate | train | public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('postSaved');
}
if ($model->type->show_category) {
$model->setScenario('required_category');
}
return $this->render('update', ['model' => $model]);
} | php | {
"resource": ""
} |
q1184 | InfoCommand.renderProperties | train | protected function renderProperties(OutputInterface $output, Response $response)
{
$table = new Table($output);
$table->setHeaders(['Property', 'Value']);
foreach ($response as $property => $value) {
if (is_scalar($value)) {
$table->addRow([$property, $value]);
}
}
$table->render();
} | php | {
"resource": ""
} |
q1185 | InfoCommand.renderDerivedResources | train | protected function renderDerivedResources(OutputInterface $output, array $derivedResources)
{
$table = new Table($output);
$table->setHeaders(
[
[new TableCell('Derived resources', ['colspan' => 5])],
['ID', 'Format', 'Size', 'Transformation', 'URL'],
]
);
foreach ($derivedResources as $resource) {
$table->addRow(
[
$resource['id'],
$resource['format'],
$this->formatSize($resource['bytes']),
$resource['transformation'],
$resource['url'],
]
);
}
$table->render();
} | php | {
"resource": ""
} |
q1186 | InfoCommand.formatSize | train | private function formatSize($bytes)
{
$unit = 1024;
if ($bytes <= $unit) {
return $bytes.' b';
}
$exp = (int)(log($bytes) / log($unit));
$pre = 'kMGTPE';
$pre = $pre[$exp - 1];
return sprintf('%.1f %sB', $bytes / pow($unit, $exp), $pre);
} | php | {
"resource": ""
} |
q1187 | AuthController.authenticated | train | public function authenticated(Request $request, $user)
{
if ($user->is_blocked || ! $user->is_activated) {
if ($user->is_blocked) {
$message = 'Your account is currently banned from accessing the site!';
} else {
$message = 'Your account is not yet activated!';
}
$this->guard()->logout();
flash()->error($message);
return redirect()->route('administrator.login')->withErrors($message);
}
return redirect()->intended($this->redirectPath);
} | php | {
"resource": ""
} |
q1188 | UserAgentDefinition.filter | train | public function filter(array $information)
{
$information = $this->filterBots($information);
$information = $this->filterBrowserNames($information);
$information = $this->filterBrowserVersions($information);
$information = $this->filterBrowserEngines($information);
$information = $this->filterOperatingSystems($information);
$information = $this->filterDevices($information);
return $information;
} | php | {
"resource": ""
} |
q1189 | UserAgentDefinition.filterBrowserNames | train | protected function filterBrowserNames(array $userAgent)
{
// IE11 hasn't 'MSIE' in its user agent string
if (empty($userAgent['browser_name']) && $userAgent['browser_engine'] === 'trident' && strpos($userAgent['string'], 'rv:')) {
$userAgent['browser_name'] = 'msie';
$userAgent['browser_version'] = preg_replace('|.+rv:([0-9]+(?:\.[0-9]+)+).+|', '$1', $userAgent['string']);
return $userAgent;
}
return $userAgent;
} | php | {
"resource": ""
} |
q1190 | UserAgentDefinition.filterBrowserVersions | train | protected function filterBrowserVersions(array $userAgent)
{
// Safari and Opera 10.00+ version number is not encoded "normally"
if (in_array($userAgent['browser_name'], ['safari', 'opera']) && stripos($userAgent['string'], ' version/')) {
$userAgent['browser_version'] = preg_replace('|.+ version/([0-9]+(?:\.[0-9]+)?).*|i', '$1', $userAgent['string']);
return $userAgent;
}
return $userAgent;
} | php | {
"resource": ""
} |
q1191 | ModulesController.destroy | train | public function destroy($module)
{
/** @var \Nwidart\Modules\Module $module */
$module = $this->modules->find($module);
$module->delete();
return $this->notifySuccess(trans('cms::module.destroy', ['module' => (string) $module]));
} | php | {
"resource": ""
} |
q1192 | ModulesController.toggle | train | public function toggle($module)
{
/** @var \Nwidart\Modules\Module $module */
$module = $this->modules->findByAlias($module);
if ($module->disabled()) {
$module->enable();
} else {
$module->disable();
}
$message = 'cms::module.toggle.' . ($module->enabled() ? 'enable' : 'disable');
return $this->notifySuccess(trans($message, ['module' => (string) $module]));
} | php | {
"resource": ""
} |
q1193 | PackageSecurityExtension.updateBadges | train | public function updateBadges($badges)
{
if ($this->owner->SecurityAlerts()->exists()) {
$badges->push(ArrayData::create([
'Title' => _t(__CLASS__ . '.BADGE_SECURITY', 'RISK: Security'),
'Type' => 'warning security-alerts__toggler',
]));
}
} | php | {
"resource": ""
} |
q1194 | PackageSecurityExtension.updateDataSchema | train | public function updateDataSchema(&$schema)
{
// The keys from the SecurityAlert model that we need in the React component
$keysToPass = ['Identifier', 'ExternalLink'];
$alerts = [];
foreach ($this->owner->SecurityAlerts()->toNestedArray() as $alert) {
$alerts[] = array_intersect_key($alert, array_flip($keysToPass));
}
$schema['securityAlerts'] = $alerts;
} | php | {
"resource": ""
} |
q1195 | WebSocketServer.sendToAll | train | public function sendToAll(string $data, int $sender = 0, int $pageSize = 50): int
{
$startFd = 0;
$count = 0;
$fromUser = $sender < 1 ? 'SYSTEM' : $sender;
$this->log("(broadcast)The #{$fromUser} send a message to all users. Data: {$data}");
while (true) {
$fdList = $this->server->connection_list($startFd, $pageSize);
if ($fdList === false || ($num = \count($fdList)) === 0) {
break;
}
$count += $num;
$startFd = \end($fdList);
/** @var $fdList array */
foreach ($fdList as $fd) {
$info = $this->getClientInfo($fd);
if (isset($info['websocket_status']) && $info['websocket_status'] > 0) {
$this->server->push($fd, $data);
}
}
}
return $count;
} | php | {
"resource": ""
} |
q1196 | WebSocketServer.writeTo | train | public function writeTo($fd, string $data): int
{
return $this->server->send($fd, $data) ? 0 : 1;
} | php | {
"resource": ""
} |
q1197 | BuzzRequestHandler.getContent | train | public function getContent($url)
{
$this->getRequest()->setHost($url);
$this->getClient()->send(
$this->getRequest(),
$this->getResponse()
);
return $this->getResponse()->getContent();
} | php | {
"resource": ""
} |
q1198 | Dispatcher.handshake | train | public function handshake(Request $request, Response $response): array
{
try {
$path = $request->getUri()->getPath();
list($className,) = $this->getHandler($path);
} catch (\Throwable $e) {
/* @var ErrorHandler $errorHandler */
// $errorHandler = \bean(ErrorHandler::class);
// $response = $errorHandler->handle($e);
if ($e instanceof WsRouteException) {
return [
HandlerInterface::HANDSHAKE_FAIL,
$response->withStatus(404)->withAddedHeader('Failure-Reason', 'Route not found')
];
}
// other error
throw $e;
}
/** @var HandlerInterface $handler */
$handler = \bean($className);
if (!\method_exists($handler, 'checkHandshake')) {
return [
HandlerInterface::HANDSHAKE_OK,
$response->withAddedHeader('swoft-ws-handshake', 'auto')
];
}
return $handler->checkHandshake($request, $response);
} | php | {
"resource": ""
} |
q1199 | Dispatcher.message | train | public function message(Server $server, Frame $frame)
{
$fd = $frame->fd;
try {
if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new ContextLostException("The connection info has lost of the fd#$fd, on message");
}
$className = $this->getHandler($path)[0];
/** @var HandlerInterface $handler */
$handler = \bean($className);
$handler->onMessage($server, $frame);
} catch (\Throwable $e) {
/** @see \Swoft\Event\EventManager::hasListenerQueue() */
if (App::hasBean('eventManager') && \bean('eventManager')->hasListenerQueue(WsEvent::ON_ERROR)) {
App::trigger(WsEvent::ON_ERROR, $frame, $e);
} else {
App::error($e->getMessage(), ['fd' => $fd, 'data' => $frame->data]);
// close connection
$server->close($fd);
}
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.