_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q250500 | HandlerWrapperGenerator.addNamedRoute | validation | public function addNamedRoute($name, $httpMethod, $routeData, $handler)
{
$handler = array(
'name' => $name,
'handler' => $handler,
);
$this->addRoute($httpMethod, $routeData, $handler);
} | php | {
"resource": ""
} |
q250501 | CachedCollector.isCacheable | validation | private function isCacheable($data)
{
$cacheable = true;
array_walk_recursive($data, function ($value) use (&$cacheable) {
if ($value instanceof \Closure) {
$cacheable = false;
}
});
return $cacheable;
} | php | {
"resource": ""
} |
q250502 | RouteCollector.map | validation | public function map($route, $name, $handler, array $methods = array('GET'))
{
foreach ($methods as $method) {
if (null === $name) {
$this->addRoute($method, $route, $handler);
} else {
$this->addNamedRoute($name, $method, $route, $handler);
}
}
} | php | {
"resource": ""
} |
q250503 | RouteCollector.addRoute | validation | private function addRoute($httpMethod, $route, $handler)
{
$routeData = $this->routeParser->parse($route);
foreach ($routeData as $routeDatum) {
$this->dataGenerator->addRoute($httpMethod, $routeDatum, $handler);
}
} | php | {
"resource": ""
} |
q250504 | RouteCollector.addNamedRoute | validation | private function addNamedRoute($name, $httpMethod, $route, $handler)
{
if (! ($this->dataGenerator instanceof NamedDataGeneratorInterface)) {
throw new \RuntimeException('The injected generator does not support named routes');
}
$routeData = $this->routeParser->parse($route);
foreach ($routeData as $routeDatum) {
$this->dataGenerator->addNamedRoute($name, $httpMethod, $routeDatum, $handler);
}
} | php | {
"resource": ""
} |
q250505 | ContainerAwareControllerResolver.createController | validation | protected function createController($controller)
{
$parts = explode(':', $controller);
if (count($parts) === 2) {
$service = $this->container->get($parts[0]);
return array($service, $parts[1]);
}
$controller = parent::createController($controller);
if ($controller[0] instanceof ContainerAwareInterface) {
$controller[0]->setContainer($this->container);
}
return $controller;
} | php | {
"resource": ""
} |
q250506 | ServiceProviderMiddleware.setProviders | validation | public function setProviders()
{
$services = $this->container['services']??null;
if (is_array($services)) {
foreach ($services as $service) {
$service::register($this->container);
$service::boot($this->container);
}
}
} | php | {
"resource": ""
} |
q250507 | Space.from | validation | public function from(Contract $contract, string $string, callable $callback = null): string
{
return $this->callback(
trim($contract->recipe($string, 'space')),
$callback
);
} | php | {
"resource": ""
} |
q250508 | Space.recipe | validation | public function recipe(string $string, string $method, callable $callback = null): string
{
return preg_replace_callback(
RegEx::REGEX_SPACE,
[$this, $method],
$this->callback($string, $callback)
);
} | php | {
"resource": ""
} |
q250509 | OrchestrationTask.setTimeoutMinutes | validation | public function setTimeoutMinutes($value)
{
if ($value)
$this->timeoutMinutes = (int) $value;
else
$this->timeoutMinutes = null;
return $this;
} | php | {
"resource": ""
} |
q250510 | OrchestrationTask.setPhase | validation | public function setPhase($value)
{
$value = (int) $value;
if ($value)
$this->phase = $value;
else
$this->phase = null;
return $this;
} | php | {
"resource": ""
} |
q250511 | FileConfigurationProvider.load | validation | public function load(ContainerBuilder $container)
{
$loader = $this->getContainerLoader($container);
$loader->load($this->configFile);
} | php | {
"resource": ""
} |
q250512 | BaseRepository.setUri | validation | protected function setUri($uriToSet)
{
$uri_parts = [];
array_push($uri_parts, 'api');
array_push($uri_parts, config('ckan_api.api_version'));
array_push($uri_parts, trim($uriToSet, '/'));
$uri_parts = array_filter($uri_parts);
$this->uri = implode('/', $uri_parts);
} | php | {
"resource": ""
} |
q250513 | BaseRepository.dataToMultipart | validation | protected function dataToMultipart(array $data = [])
{
$multipart = [];
foreach($data as $name => $contents) {
array_push($multipart, ['name' => $name, 'contents' => $contents]);
}
return $multipart;
} | php | {
"resource": ""
} |
q250514 | Bbcode.filter | validation | public function filter($text)
{
//removing /r because it's bad!
$text = str_replace("\r", '', $text);
//transform all double spaces in ' ' to respect multiples spaces
$text = str_replace(' ', ' ', $text);
// first [nobbcode][/nobbcode] -> don't interpret bbcode
$this->_parseBbcodeNobbcode($text);
// parse strange bbcode, before other bbcode
$this->_parseBbcodeCode($text);
$this->_parseBbcodeQuote($text);
$this->_parseBbcodeList($text);
// easy bbcode replacement
// [i]txt[/i]
$this->_parseSimpleBbcode('i', '<em>$1</em>', $text);
// [u]txt[/u]
$this->_parseSimpleBbcode('u', '<u>$1</u>', $text);
// [b]txt[/b]
$this->_parseSimpleBbcode('b', '<strong>$1</strong>', $text);
// [del]txt[/del] & [strike]txt[/strike]
$this->_parseSimpleBbcode('del', '<del>$1</del>', $text);
$this->_parseSimpleBbcode('strike', '<del>$1</del>', $text);
// [color=color]txt[/color]
$this->_parseParamBbcode('color', '([a-zA-Z]*|\#?[0-9a-fA-F]{6})', '<span style="color: $1">$2</span>', $text);
// [bgcolor=color]txt[/bgcolor]
$this->_parseParamBbcode('bgcolor', '([a-zA-Z]*|\#?[0-9a-fA-F]{6})', '<span style="background-color: $1">$2</span>', $text);
// [align=(center|left|right)][/align]
$this->_parseParamBbcode('align', '(center|left|right|justify){1}', '<div style="text-alignement: $1">$2</div>', $text);
// [size=$size][/size]
$this->_parseParamBbcode('size', '([0-9].*)', '<span style="font-size: $1">$2</span>', $text);
$this->_parseBbcodeEmail($text);
$this->_parseBbcodeUrl($text);
$this->_parseBbcodeImg($text);
$this->_parseBbcodeSpoiler($text);
$this->_parseScriptTags($text);
$this->_parseSmiley($text);
//[br]
$this->_parseBbcodeBr($text);
return $text;
} | php | {
"resource": ""
} |
q250515 | Module.getServiceConfig | validation | public function getServiceConfig()
{
return array(
'factories' => array(
'CronHelper\Service\CronService' => function ($serviceManager) {
$mainConfig = $serviceManager->get('config');
$serviceConfig = array();
if (is_array($mainConfig)) {
if (array_key_exists('cron_helper', $mainConfig)) {
$serviceConfig = $mainConfig['cron_helper'];
}
}
$cronService = new CronService($serviceConfig);
return $cronService;
},
),
);
} | php | {
"resource": ""
} |
q250516 | Module.onBootstrap | validation | public function onBootstrap(MvcEvent $event)
{
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
//$sharedEventManager->attach('CronHelper\Service\CronService', function($aEvent) {
// var_dump($aEvent);
//}, 100);
} | php | {
"resource": ""
} |
q250517 | FieldValidator.validateFields | validation | public function validateFields(Request $request, Repository $repository, $data)
{
$config = [];
$validation = [];
foreach ($this->versions as $version) {
foreach ($version['endpoints'] as $endpoint) {
if ($endpoint['repository'] == $request->attributes->get('repository')) {
$config = $endpoint;
break;
}
}
if ($config != []) {
break;
}
}
if (!$config['allow_extra_fields'] || $config['allow_fields']) {
$mapping = $this->manager->getMetadataCollector()->getMapping(
$repository->getClassName()
);
$forbiddenFields = $mapping['properties'];
if ($config['allow_fields']) {
foreach ($config['allow_fields'] as $field) {
unset($forbiddenFields[$field]);
}
}
foreach ($data as $parameter => $value) {
if (!array_key_exists($parameter, $mapping['properties']) && $parameter != '_id') {
$validation['message'] = sprintf(
'Property `%s` does not exist in the mapping of `%s`.',
$parameter,
$repository->getType()
);
return $validation;
}
if ($config['allow_fields'] && array_key_exists($parameter, $forbiddenFields)) {
$validation['message'] = sprintf(
'You are not allowed to insert or modify the field `%s` in `%s`',
$parameter,
$repository->getType()
);
return $validation;
}
}
}
return $validation;
} | php | {
"resource": ""
} |
q250518 | AbstractRestController.renderRest | validation | public function renderRest(
$request,
$data,
$statusCode = Response::HTTP_OK,
$headers = []
) {
$requestSerializer = $this->get('ongr_api.request_serializer');
return new Response(
$requestSerializer->serializeRequest($request, $data),
$statusCode,
array_merge(
['Content-Type' => 'application/' . $requestSerializer->checkAcceptHeader($request)],
$headers
)
);
} | php | {
"resource": ""
} |
q250519 | JobMapper.fetchByWhere | validation | public function fetchByWhere($where = null, array $options = array())
{
$select = $this->sql->select();
if ($where instanceof Where) {
$select->where($where);
} elseif (is_string($where) && !empty($where)) {
$select->where($where);
}
// Options: limit
$limit = array_key_exists('limit', $options) ? (int) $limit : null;
if (!is_null($limit) && (int) $limit > 0) {
$select->limit($limit);
}
$stmt = $this->sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
// Option: hydrate
$hydrate = array_key_exists('hydrate', $options) ? (bool) $options['hydrate'] : true;
if ($hydrate !== true) {
return $result;
}
return $this->hydrateResult($result);
} | php | {
"resource": ""
} |
q250520 | JobMapper.save | validation | public function save(JobEntity $job)
{
$query = null;
if ((int) $job->getId() == 0) {
$query = $this->sql->insert();
$query->values($job->getArrayCopy());
} else {
$query = $this->sql->update();
$query->set($job->getArrayCopy());
$query->where(array('id' => $job->getId()));
}
$stmt = $this->sql->prepareStatementForSqlObject($query);
$res = $stmt->execute();
if ((int) $job->getId() == 0) {
$job->setId((int) $res->getGeneratedValue());
}
return $job;
} | php | {
"resource": ""
} |
q250521 | JobMapper.deleteByWhere | validation | public function deleteByWhere($where = null, array $options = array())
{
$delete = $this->sql->delete();
if ($where instanceof Where) {
$delete->where($where);
} elseif (is_string($where) && !empty($where)) {
$delete->where($where);
}
$delete->where($where);
// Options: limit
$limit = array_key_exists('limit', $options) ? (int) $limit : null;
if (!is_null($limit) && (int) $limit > 0) {
$delete->limit($limit);
}
$stmt = $this->sql->prepareStatementForSqlObject($delete);
return $stmt->execute();
} | php | {
"resource": ""
} |
q250522 | JobMapper.getPending | validation | public function getPending(array $options = array())
{
$where = new Where();
$where->equalTo("{$this->tableName}.status", JobEntity::STATUS_PENDING);
return $this->fetchByWhere($where, $options);
} | php | {
"resource": ""
} |
q250523 | JobMapper.getRunning | validation | public function getRunning(array $options = array())
{
$where = new Where();
$where->equalTo("{$this->tableName}.status", JobEntity::STATUS_RUNNING);
return $this->fetchByWhere($where, $options);
} | php | {
"resource": ""
} |
q250524 | LessServerCompiler.needsCompilation | validation | private function needsCompilation($lessPath, $cssPath)
{
/**
* Checks whether $subject has been modified since $reference was
*/
$isNewer = function($subject, $reference) {
return filemtime($subject) > filemtime($reference);
};
// Check for obvious cases
if ($this->forceCompile || !file_exists($lessPath)
|| !file_exists($cssPath) || $isNewer($lessPath, $cssPath))
{
return true;
}
// Finally, check if any imported file has changed
return $this->checkImports($lessPath, $cssPath, $isNewer);
} | php | {
"resource": ""
} |
q250525 | LessServerCompiler.checkImports | validation | private function checkImports($lessPath, $cssPath, $callback)
{
static $needsRecompile = false;
if ($needsRecompile)
return $needsRecompile;
$lessContent = file_get_contents($lessPath);
preg_match_all('/(?<=@import)\s+"([^"]+)/im', $lessContent, $imports);
foreach ($imports[1] as $import)
{
$importPath = realpath(dirname($lessPath).DIRECTORY_SEPARATOR.$import);
if (file_exists($importPath))
{
if ($callback($importPath, $cssPath))
{
$needsRecompile = true;
break;
}
else
$needsRecompile = $this->checkImports($importPath, $cssPath, $callback);
}
}
return $needsRecompile;
} | php | {
"resource": ""
} |
q250526 | LessServerCompiler.compileFile | validation | protected function compileFile($lessPath, $cssPath)
{
$options = array();
if ($this->strictImports === true)
$options[] = '--strict-imports';
if ($this->compression === self::COMPRESSION_WHITESPACE)
$options[] = '--compress';
else if ($this->compression === self::COMPRESSION_YUI)
$options[] = '--yui-compress';
if ($this->optimizationLevel !== false)
$options[] = '-O' . $this->optimizationLevel;
if (isset($this->rootPath))
$options[] = '--rootpath ' . $this->rootPath;
if ($this->relativeUrls === true)
$options[] = '--relative-urls';
// 2>&1 at the end redirects STDERR (where error's appear) to STDOUT
// (which is returned by shell_exec())
$nodePath = $this->nodePath? '"' . $this->nodePath . '" ' : '';
$command = $nodePath . '"' . $this->compilerPath . '" '
. implode(' ', $options) . ' "' . $lessPath . '" "' . $cssPath . '" 2>&1';
$return = 0;
$output = array();
@exec($command, $output, $return);
switch ($return)
{
case 2:
case 1:
// Replace shell color codes in the output
$output = preg_replace('/\[[0-9]+m/i', '', implode("\n", $output));
throw new CException(
'Failed to compile file "' . $lessPath . '" using command: ' . $command . '. The error was: ' . $output);
}
} | php | {
"resource": ""
} |
q250527 | JobTable.create | validation | public function create()
{
$adapter = $this->dbAdapter;
$ddl = new Ddl\CreateTable();
$ddl->setTable(self::TABLE_NAME)
->addColumn(new Column\Integer('id', false, null, array('autoincrement' => true)))
->addColumn(new Column\Varchar('code', 55))
->addColumn(new Column\Varchar('status', 55))
->addColumn(new Column\Text('error_msg'))
->addColumn(new Column\Text('stack_trace'))
->addColumn(new Column\Varchar('created', 255))
->addColumn(new Column\Varchar('scheduled', 255))
->addColumn(new Column\Varchar('executed', 255))
->addColumn(new Column\Varchar('finished', 255))
->addConstraint(new Constraint\PrimaryKey('id'));
$sql = (new Sql($adapter))->getSqlStringForSqlObject($ddl);
$adapter->query($sql, $adapter::QUERY_MODE_EXECUTE);
} | php | {
"resource": ""
} |
q250528 | JobTable.drop | validation | public function drop()
{
$adapter = $this->dbAdapter;
$ddl = new Ddl\DropTable(self::TABLE_NAME);
$sql = (new Sql($adapter))->getSqlStringForSqlObject($ddl);
$adapter->query($sql, $adapter::QUERY_MODE_EXECUTE);
} | php | {
"resource": ""
} |
q250529 | JobTable.truncate | validation | public function truncate()
{
$adapter = $this->dbAdapter;
$mapper = new \CronHelper\Model\JobMapper($adapter);
$where = new \Zend\Db\Sql\Where();
$mapper->deleteByWhere($where);
} | php | {
"resource": ""
} |
q250530 | JobEntity.getDuration | validation | public function getDuration()
{
$executed = $this->getExecuted();
$finished = $this->getFinished();
if (is_null($executed) || is_null($finished)) {
return 0;
}
return strtotime($finished) - strtotime($executed);
} | php | {
"resource": ""
} |
q250531 | Serializer.applySerializeMetadataToArray | validation | public function applySerializeMetadataToArray(array $array, $className) {
$classMetadata = $this->documentManager->getClassMetadata($className);
$fieldList = $this->fieldListForSerialize($classMetadata);
$return = array_merge($array, $this->serializeClassNameAndDiscriminator($classMetadata));
foreach ($classMetadata->fieldMappings as $field=>$mapping){
if ( ! in_array($field, $fieldList)){
if (isset($return[$field])){
unset($return[$field]);
}
continue;
}
if ( isset($mapping['id']) && $mapping['id'] && isset($array['_id'])){
$return[$field] = $array['_id'];
unset($return['_id']);
}
if ( ! isset($return[$field])){
continue;
}
$return[$field] = $this->applySerializeMetadataToField($return[$field], $field, $className);
}
return $return;
} | php | {
"resource": ""
} |
q250532 | Grid16Layout.addGrid16CSS | validation | public function addGrid16CSS(\PageModel $objPage, \LayoutModel $objLayout, \PageRegular $objPageRegular)
{
/*
* vor internen laden
* $GLOBALS['TL_CSS'][] = 'assets/contao-grid16/css/grid-1120-16-pixel.min.css';
* nach den anderen
* $GLOBALS['TL_HEAD'][] = '<link ...>';
*/
$arrFrameworkGrid16 = \StringUtil::deserialize($objLayout->frameworkGrid16);
// Add the Grid16 CSS framework style sheets
if (is_array($arrFrameworkGrid16))
{
foreach ($arrFrameworkGrid16 as $strFile)
{
if ($objLayout->loadingOrderGrid16 == 'before_framework')
{
$GLOBALS['TL_CSS'][] = 'bundles/bugbustergrid16/' . basename($strFile, '.css') . '.min.css';
}
else
{
$GLOBALS['TL_HEAD'][] = '<link rel="stylesheet" href="bundles/bugbustergrid16/' . basename($strFile, '.css') . '.min.css">';
}
}
}
return;
} | php | {
"resource": ""
} |
q250533 | Configuration.getEndpointNode | validation | public function getEndpointNode()
{
$builder = new TreeBuilder();
$node = $builder->root('endpoints');
$node
->info('Defines version endpoints.')
->useAttributeAsKey('endpoint')
->prototype('array')
->children()
->scalarNode('endpoint')
->info('Endpoint name (will be included in url (e.g. products))')
->example('products')
->end()
->scalarNode('repository')
->isRequired()
->info('Document service from Elasticsearch bundle which will be used for data fetching')
->example('es.manager.default.products')
->end()
->arrayNode('methods')
->defaultValue(
[
Request::METHOD_POST,
Request::METHOD_GET,
Request::METHOD_PUT,
Request::METHOD_DELETE
]
)
->prototype('scalar')
->validate()
->ifNotInArray(
[
Request::METHOD_HEAD,
Request::METHOD_POST,
Request::METHOD_PATCH,
Request::METHOD_GET,
Request::METHOD_PUT,
Request::METHOD_DELETE
]
)
->thenInvalid(
'Invalid HTTP method used! Please check your ongr_api endpoint configuration.'
)
->end()
->end()
->end()
->booleanNode('allow_extra_fields')
->defaultFalse()
->info(
'Allows to pass unknown fields to an api. '.
'Make sure you have configured elasticsearch respectively.'
)
->end()
->arrayNode('allow_fields')
->defaultValue([])
->info('A list off a allowed fields to operate through api for a document.')
->prototype('scalar')->end()
->end()
->booleanNode('allow_get_all')
->defaultTrue()
->info(
'Allows to use `_all` elasticsearch api to get all documents from a type.'
)
->end()
->booleanNode('allow_batch')
->defaultTrue()
->info(
'Allows to use `_batch` elasticsearch api to pass multiple documents in single API request.'
)
->end()
->booleanNode('variants')
->defaultFalse()
->info(
'If set to true user can manipulate document variants over API.'
)
->end()
->booleanNode('batch')
->defaultTrue()
->info(
'If set to true user can sent documents in batch\'s.'
)
->end()
->end()
->end();
return $node;
} | php | {
"resource": ""
} |
q250534 | LessClientCompiler.getAssetsUrl | validation | protected function getAssetsUrl()
{
if (!isset($this->_assetsUrl))
{
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets';
$this->_assetsUrl = Yii::app()->assetManager->publish($path, false, -1, $this->forceCopyAssets);
}
return $this->_assetsUrl;
} | php | {
"resource": ""
} |
q250535 | DashServicesProvider.themeDefaults | validation | public function themeDefaults()
{
view()->composer("*", function ($view) {
/* get the theme if set in config */
$theme = config("dash.theme", null);
/* if not theme is set in the config */
/* check the theme folder if exist or use the theme in package*/
if (!$theme):
if (view()->exists("theme.dash.index")):
$theme = "theme.dash.";
else :
$theme = "dash::";
endif;
endif;
view()->share('dashTheme', $theme);
});
} | php | {
"resource": ""
} |
q250536 | GenerateFormsFields.buildCustomFields | validation | public function buildCustomFields($form_fields = [], $config_name = 'custom_form')
{
$fields = collect($form_fields)->map(function ($field, $name) use ($config_name) {
return $this->render(
isset($field['type']) ? $field['type'] : 'text',
[
$name,
$field['label'],
['data-table' => $config_name]
]
);
});
return $fields ;
} | php | {
"resource": ""
} |
q250537 | BatchRequestHandler.update | validation | private function update($documents, $repository, $commitSize)
{
if (count($documents) > $commitSize && $commitSize > 1) {
$esResponse = [];
$i = 1;
foreach ($documents as $document) {
$id = $document['_id'];
unset($document['_id']);
$this->crud->update($repository, $id, $document);
if ($i++ % ($commitSize - 1) == 0) {
$esResponse[] = $this->crud->commit($repository);
}
}
} else {
foreach ($documents as $document) {
$id = $document['_id'];
unset($document['_id']);
$this->crud->update($repository, $id, $document);
}
$esResponse = $this->crud->commit($repository);
}
return json_encode($esResponse);
} | php | {
"resource": ""
} |
q250538 | ResourceRepository.update | validation | public function update(array $data = [])
{
$this->setActionUri(__FUNCTION__);
$response = $this->client->post($this->uri, [
'multipart' => $this->dataToMultipart($data),
]);
return $this->responseToJson($response);
} | php | {
"resource": ""
} |
q250539 | CategoryRepository.getHome | validation | public function getHome()
{
$query = $this->createQueryBuilder('c')
->join('c.forums', 'f')
->join('f.lastMessage', 'm')
->join('m.user', 'u')
->addSelect('f')
->addSelect('m')
->addSelect('u')
->where('f.status = :status')
->setParameter('status', Forum::STATUS_PUBLIC);
$query->orderBy('c.position', 'ASC')
->addOrderBy('f.position', 'ASC');
return $query->getQuery();
} | php | {
"resource": ""
} |
q250540 | BatchController.postAction | validation | public function postAction(Request $request)
{
try {
$data = $this->get('ongr_api.batch_request_handler')->handleRequest(
$request,
$repository = $this->getRequestRepository($request),
'create'
);
return $this->renderRest($request, $data, Response::HTTP_OK);
} catch (\Exception $e) {
return $this->renderError($request, $e->getMessage(), Response::HTTP_BAD_REQUEST);
}
} | php | {
"resource": ""
} |
q250541 | CronService.setOptions | validation | public function setOptions(array $options)
{
if (!array_key_exists('options', $options)) {
$options['options'] = array();
}
$this->options = array_merge($this->getDefaultOptions(), $options['options']);
return $this;
} | php | {
"resource": ""
} |
q250542 | CronService.setScheduleAhead | validation | public function setScheduleAhead($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('`scheduleAhead` expects integer value!');
}
$this->options['scheduleAhead'] = (int) $time;
return $this;
} | php | {
"resource": ""
} |
q250543 | CronService.setScheduleLifetime | validation | public function setScheduleLifetime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('`scheduleLifetime` expects integer value!');
}
$this->options['scheduleLifetime'] = (int) $time;
return $this;
} | php | {
"resource": ""
} |
q250544 | CronService.setSuccessLogLifetime | validation | public function setSuccessLogLifetime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('`successLogLifetime` expects integer value!');
}
$this->options['successLogLifetime'] = (int) $time;
return $this;
} | php | {
"resource": ""
} |
q250545 | CronService.setFailureLogLifetime | validation | public function setFailureLogLifetime($time)
{
if (!is_numeric($time)) {
throw new \InvalidArgumentException('`failureLogLifetime` expects integer value!');
}
$this->options['failureLogLifetime'] = (int) $time;
return $this;
} | php | {
"resource": ""
} |
q250546 | CronService.setEmitEvents | validation | public function setEmitEvents($emitEvents)
{
if (!is_bool($emitEvents)) {
throw new \InvalidArgumentException('`emitEvents` expects boolean value!');
}
$this->options['emitEvents'] = (bool) $emitEvents;
return $this;
} | php | {
"resource": ""
} |
q250547 | CronService.setAllowJsonApi | validation | public function setAllowJsonApi($allowJsonApi)
{
if (!is_bool($allowJsonApi)) {
throw new \InvalidArgumentException('`allowJsonApi` expects boolean value!');
}
$this->options['allowJsonApi'] = (bool) $allowJsonApi;
return $this;
} | php | {
"resource": ""
} |
q250548 | CronService.setJsonApiSecurityHash | validation | public function setJsonApiSecurityHash($jsonApiSecurityHash)
{
if (!is_string($jsonApiSecurityHash)) {
throw new \InvalidArgumentException('`jsonApiSecurityHash` expects string value!');
}
$this->options['jsonApiSecurityHash'] = (string) $jsonApiSecurityHash;
return $this;
} | php | {
"resource": ""
} |
q250549 | CkanServiceProvider.register | validation | public function register()
{
$app = $this->app;
$app->bind('Germanazo\CkanApi\CkanApiClient', function () {
// Build http client
$config = [
'base_uri' => config('ckan_api.url'),
'headers' => ['Authorization' => config('ckan_api.api_key')],
];
return new CkanApiClient(new Client($config));
});
$app->alias('Germanazo\CkanApi\CkanApiClient', 'CkanApi');
} | php | {
"resource": ""
} |
q250550 | RestApiTrait.show | validation | public function show($id, $params = [])
{
$data = ['id' => $id] + $params;
return $this->query(__FUNCTION__, $data);
} | php | {
"resource": ""
} |
q250551 | RestApiTrait.doPostAction | validation | protected function doPostAction($uri, array $data = [])
{
$this->setActionUri($uri);
try {
$response = $this->client->post($this->uri, ['json' => $data]);
} catch (ClientException $e) {
$response = $e->getResponse();
} catch (ServerException $e) {
$response = $e->getResponse();
}
return $this->responseToJson($response);
} | php | {
"resource": ""
} |
q250552 | RestApiTrait.query | validation | protected function query($uri, $data = [])
{
$this->setActionUri($uri);
try {
$response = $this->client->get($this->uri, ['query' => $data]);
} catch(ClientException $e) {
$response = $e->getResponse();
} catch(ServerException $e) {
$response = $e->getResponse();
}
return $this->responseToJson($response);
} | php | {
"resource": ""
} |
q250553 | IndexController.indexAction | validation | public function indexAction()
{
if (!$this->isConsoleRequest()) {
throw new \RuntimeException('You can only use this action from a console!');
}
$console = $this->getConsole();
$this->printConsoleBanner($console);
$console->writeLine('TODO Finish indexAction!', ConsoleColor::LIGHT_RED);
} | php | {
"resource": ""
} |
q250554 | IndexController.infoAction | validation | public function infoAction()
{
if (!$this->isConsoleRequest()) {
throw new \RuntimeException('You can only use this action from a console!');
}
$console = $this->getConsole();
$this->printConsoleBanner($console);
$mapper = $this->getJobMapper();
try {
$pendingJobs = $mapper->getPending()->count();
$runningJobs = $mapper->getRunning()->count();
$finishedJobs = $mapper->getHistory()->count();
$console->writeLine(sprintf('Pending jobs: %s', $pendingJobs));
$console->writeLine(sprintf('Running jobs: %s', $runningJobs));
$console->writeLine(sprintf('Finished jobs: %s', $finishedJobs));
} catch (\PDOException $exception) {
// Note: It's look like that either database adapter is not properly
// defined or table database doesn't exist.
$console->writeLine(
'Something is bad with your database - either database ' .
'adapter is not properly configured or database table is ' .
'not created.', ConsoleColor::LIGHT_RED
);
}
} | php | {
"resource": ""
} |
q250555 | IndexController.storageClearAction | validation | public function storageClearAction()
{
if (!$this->isConsoleRequest()) {
throw new \RuntimeException('You can only use this action from a console!');
}
$dbAdapter = $this->getDbAdapter();
$console = $this->getConsole();
$this->printConsoleBanner($console);
try {
$table = new JobTable($dbAdapter);
$table->truncate();
} catch (\Exception $exception) {
$console->writeLine('Truncating database table failed!', ConsoleColor::LIGHT_RED);
return;
}
$console->writeLine('Storage was successfully cleared!', ConsoleColor::LIGHT_GREEN);
} | php | {
"resource": ""
} |
q250556 | RequestSerializer.checkAcceptHeader | validation | public function checkAcceptHeader(Request $request)
{
$headers = $request->getAcceptableContentTypes();
if (array_intersect($headers, ['application/json', 'text/json'])) {
return 'json';
} elseif (array_intersect($headers, ['application/xml', 'text/xml'])) {
return 'xml';
}
return $this->defaultAcceptType;
} | php | {
"resource": ""
} |
q250557 | eZIEImageToolCrop.filter | validation | public static function filter( $region )
{
$r = array(
'x' => intval( $region['x'] ),
'y' => intval( $region['y'] ),
'width' => intval( $region['w'] ),
'height' => intval( $region['h'] )
);
return array( new ezcImageFilter( 'crop', $r ) );
} | php | {
"resource": ""
} |
q250558 | eZIEezcImageConverter.perform | validation | public function perform( $src, $dst )
{
// fetch the input file locally
$inClusterHandler = eZClusterFileHandler::instance( $src );
$inClusterHandler->fetch();
try {
$this->converter->transform( 'transformation', $src, $dst );
}
catch ( Exception $e )
{
$inClusterHandler->deleteLocal();
throw $e;
}
// store the output file to the cluster
$outClusterHandler = eZClusterFileHandler::instance();
// @todo Check if the local output file can be deleted at that stage. Theorically yes.
$outClusterHandler->fileStore( $dst, 'image' );
// fixing the file permissions
eZImageHandler::changeFilePermissions( $dst );
} | php | {
"resource": ""
} |
q250559 | eZIEEzcImageMagickHandler.rotate | validation | public function rotate( $angle, $background = 'FFFFFF' )
{
$angle = intval( $angle );
if ( !is_int( $angle ) || ( $angle < 0 ) || ( $angle > 360 ) )
{
throw new ezcBaseValueException( 'height', $height, 'angle < 0 or angle > 360' );
}
$angle = 360 - $angle;
$background = "#{$background}";
$this->addFilterOption(
$this->getActiveReference(),
'-background',
$background
);
$this->addFilterOption(
$this->getActiveReference(),
'-rotate',
$angle
);
} | php | {
"resource": ""
} |
q250560 | MarkdownBladeCompiler.markdown | validation | public function markdown($contents)
{
$contents = app('markdown')->convertToHtml($contents);
if (! is_null($this->cachePath)) {
$this->files->put($this->getCompiledPath($this->getPath()), $contents);
}
return $contents;
} | php | {
"resource": ""
} |
q250561 | BladeExtCompiler.getEchoMethods | validation | protected function getEchoMethods()
{
$methods = [
'compileRawEchos' => strlen(stripcslashes($this->rawTags[0])),
'compileEscapedEchos' => strlen(stripcslashes($this->escapedTags[0])),
'compileMarkdownEchos' => strlen(stripcslashes($this->markdownTags[0])),
'compileRegularEchos' => strlen(stripcslashes($this->contentTags[0])),
];
uksort($methods, function ($method1, $method2) use ($methods) {
// Ensure the longest tags are processed first
if ($methods[$method1] > $methods[$method2]) {
return -1;
}
if ($methods[$method1] < $methods[$method2]) {
return 1;
}
// Otherwise give preference to raw tags (assuming they've overridden)
if ($method1 === 'compileRawEchos') {
return -1;
}
if ($method2 === 'compileRawEchos') {
return 1;
}
if ($method1 === 'compileEscapedEchos') {
return -1;
}
if ($method2 === 'compileEscapedEchos') {
return 1;
}
if ($method1 === 'compileMarkdownEchos') {
return -1;
}
if ($method2 === 'compileMarkdownEchos') {
return 1;
}
});
return $methods;
} | php | {
"resource": ""
} |
q250562 | BladeExtCompiler.compileMarkdownEchos | validation | protected function compileMarkdownEchos($value)
{
$pattern = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->markdownTags[0], $this->markdownTags[1]);
$callback = function ($matches) {
$wrapper = sprintf($this->markdownFormat, $this->compileEchoDefaults($matches[2]));
return $matches[1] ? strlen(stripcslashes($this->markdownTags[0])) > 2 ? $matches[0] : substr($matches[0], 1) : '<?php echo '.$wrapper.'; ?>';
};
return preg_replace_callback($pattern, $callback, $value);
} | php | {
"resource": ""
} |
q250563 | MarkdownServiceProvider.registerMarkdownEnvironment | validation | protected function registerMarkdownEnvironment()
{
$app = $this->app;
$app->singleton('commonmark.environment', function ($app) {
$config = $app['config']['markdown'];
$environment = Environment::createCommonMarkEnvironment();
if ($config['configurations']) {
$environment->mergeConfig($config['configurations']);
}
foreach ($config['extensions'] as $extension) {
if (class_exists($extension)) {
$environment->addExtension(new $extension());
}
}
return $environment;
});
$app->alias('commonmark.environment', Environment::class);
} | php | {
"resource": ""
} |
q250564 | MarkdownServiceProvider.registerMarkdownParser | validation | protected function registerMarkdownParser()
{
$app = $this->app;
$app->singleton('commonmark.docparser', function ($app) {
$environment = $app['commonmark.environment'];
return new DocParser($environment);
});
$app->alias('commonmark.docparser', DocParser::class);
} | php | {
"resource": ""
} |
q250565 | MarkdownServiceProvider.registerMarkdownHtmlRenderer | validation | protected function registerMarkdownHtmlRenderer()
{
$app = $this->app;
$app->singleton('commonmark.htmlrenderer', function ($app) {
$environment = $app['commonmark.environment'];
return new HtmlRenderer($environment);
});
$app->alias('commonmark.htmlrenderer', HtmlRenderer::class);
} | php | {
"resource": ""
} |
q250566 | MarkdownServiceProvider.registerMarkdown | validation | protected function registerMarkdown()
{
$app = $this->app;
$app->singleton('markdown', function ($app) {
return new Converter($app['commonmark.docparser'], $app['commonmark.htmlrenderer']);
});
$app->alias('markdown', Converter::class);
} | php | {
"resource": ""
} |
q250567 | MarkdownServiceProvider.registerEngines | validation | protected function registerEngines()
{
$app = $this->app;
$config = $app['config'];
$resolver = $app['view.engine.resolver'];
if ($config['markdown.tags']) {
$this->registerBladeEngine($resolver);
}
if ($config['markdown.views']) {
$this->registerMarkdownEngine($resolver);
$this->registerMarkdownPhpEngine($resolver);
$this->registerMarkdownBladeEngine($resolver);
}
} | php | {
"resource": ""
} |
q250568 | MarkdownServiceProvider.registerMarkdownEngine | validation | protected function registerMarkdownEngine($resolver)
{
$app = $this->app;
$app->singleton('markdown.compiler', function ($app) {
$cache = $app['config']['view.compiled'];
return new MarkdownCompiler($app['files'], $cache);
});
$resolver->register('markdown', function () use ($app) {
return new MarkdownEngine($app['markdown.compiler'], $app['files']);
});
$app['view']->addExtension('md', 'markdown');
} | php | {
"resource": ""
} |
q250569 | MarkdownServiceProvider.registerMarkdownPhpEngine | validation | protected function registerMarkdownPhpEngine($resolver)
{
$app = $this->app;
$app->singleton('markdown.php.compiler', function ($app) {
$cache = $app['config']['view.compiled'];
return new MarkdownPhpCompiler($app['files'], $cache);
});
$resolver->register('markdown.php', function () use ($app) {
return new MarkdownEngine($app['markdown.php.compiler'], $app['files']);
});
$app['view']->addExtension('md.php', 'markdown.php');
} | php | {
"resource": ""
} |
q250570 | MarkdownServiceProvider.registerMarkdownBladeEngine | validation | protected function registerMarkdownBladeEngine($resolver)
{
$app = $this->app;
$app->singleton('markdown.blade.compiler', function ($app) {
$cache = $app['config']['view.compiled'];
return new MarkdownBladeCompiler($app['files'], $cache);
});
$resolver->register('markdown.blade', function () use ($app) {
return new MarkdownEngine($app['markdown.blade.compiler'], $app['files']);
});
$app['view']->addExtension('md.blade.php', 'markdown.blade');
} | php | {
"resource": ""
} |
q250571 | eZIEImageToolResize.filter | validation | static function filter( $width, $height )
{
return array(
new ezcImageFilter(
'scale',
array(
'width' => intval( $width ),
'height' => intval( $height ),
'direction' => ezcImageGeometryFilters::SCALE_BOTH
)
)
);
} | php | {
"resource": ""
} |
q250572 | eZIEEzcGDHandler.region | validation | private function region( $filter, $resource, $region, $colorspace = null, $value = null )
{
$dest = imagecreatetruecolor( $region["w"], $region["h"] );
if ( !imagecopy( $dest, $resource, 0, 0, $region["x"], $region["y"], $region["w"], $region["h"] ) )
{
throw new ezcImageFilterFailedException( "1/ {$function} applied on region {$region['x']}x{$region['y']}" );
}
if ( !$colorspace )
{
if ( $filter == "pixelateImg" )
{
$result = $this->$filter( $dest, imagesx( $resource ), imagesy( $resource ) );
}
else
$result = $this->$filter( $dest, $value );
}
else
{
$this->setActiveResource( $dest );
parent::colorspace( $colorspace );
$result = $dest;
}
if ( !imagecopy( $resource, $result, $region["x"], $region["y"], 0, 0, $region["w"], $region["h"] ) )
{
throw new ezcImageFilterFailedException( "2/ {$function} applied on region {$region['x']}x{$region['y']}" );
}
return $resource;
} | php | {
"resource": ""
} |
q250573 | DBFontIcon.requireField | validation | public function requireField()
{
// Obtain Charset and Collation:
$charset = MySQLDatabase::config()->charset;
$collation = MySQLDatabase::config()->collation;
// Define Field Specification:
$spec = [
'type' => 'varchar',
'parts' => [
'datatype' => 'varchar',
'precision' => 64,
'collate' => $collation,
'character set' => $charset,
'arrayValue' => $this->arrayValue
]
];
// Require Database Field:
DB::require_field($this->tableName, $this->name, $spec);
} | php | {
"resource": ""
} |
q250574 | DBFontIcon.scaffoldFormField | validation | public function scaffoldFormField($title = null, $params = null)
{
return FontIconField::create($this->name, $title);
} | php | {
"resource": ""
} |
q250575 | Angle.deg | validation | public function deg()
{
if ($this->original->type == self::TYPE_DEG) {
return $this->original->value;
}
return rad2deg($this->float_rad);
} | php | {
"resource": ""
} |
q250576 | Angle.rad | validation | public function rad()
{
if ($this->original->type == self::TYPE_RAD) {
return $this->original->value;
}
return $this->float_rad;
} | php | {
"resource": ""
} |
q250577 | Angle.turn | validation | public function turn()
{
if ($this->original->type == self::TYPE_TURN) {
return $this->original->value;
}
return $this->float_rad / (2 * pi());
} | php | {
"resource": ""
} |
q250578 | Angle.isComplementary | validation | public function isComplementary(Angle $angle)
{
$out = new self($this->float_rad + $angle->rad);
return $out->isRight();
} | php | {
"resource": ""
} |
q250579 | Angle.isSupplementary | validation | public function isSupplementary(Angle $angle)
{
$out = new self($this->float_rad + $angle->rad);
return $out->isStraight();
} | php | {
"resource": ""
} |
q250580 | Configuration.get | validation | public function get($key, $default = null)
{
$keys = array_filter(explode('.', $key));
$length = count($keys);
$data = $this->data;
for ($i = 0; $i < $length; $i++) {
$index = $keys[$i];
$data = &$data[$index];
}
return $data !== null ? $data : $default;
} | php | {
"resource": ""
} |
q250581 | Configuration.load | validation | public function load($directory)
{
$configurations = glob($directory . '/*.php');
foreach ($configurations as $configuration) {
$items = require $configuration;
$name = basename($configuration, '.php');
$this->data = array_merge($this->data, array($name => $items));
}
return $this->data;
} | php | {
"resource": ""
} |
q250582 | Configuration.set | validation | public function set($key, $value, $fromFile = false)
{
$keys = array_filter(explode('.', $key));
$value = ($fromFile) ? require $value : $value;
$this->save($keys, $this->data, $value);
return $this;
} | php | {
"resource": ""
} |
q250583 | Matrix.populate | validation | public function populate($arrAll)
{
$this->arr = array_chunk($arrAll, $this->size->cols);
return $this;
} | php | {
"resource": ""
} |
q250584 | Matrix.addRow | validation | public function addRow(array $arr_row)
{
if (count($this->arr) == $this->size->rows) {
throw new \OutOfRangeException(sprintf('You cannot add another row! Max number of rows is %d', $this->size->rows));
}
if (count($arr_row) != $this->size->cols) {
throw new \InvalidArgumentException('New row must have same amout of columns than defined into the size matrix');
}
$this->arr[] = $arr_row;
return $this;
} | php | {
"resource": ""
} |
q250585 | Matrix.addCol | validation | public function addCol($arr_col)
{
if (isset($this->arr[0]) && (count($this->arr[0]) == $this->size->cols)) {
throw new \OutOfRangeException(sprintf('You cannot add another column! Max number of columns is %d', $this->size->cols));
}
if (count($arr_col) != $this->size->rows) {
throw new \InvalidArgumentException('New column must have same amout of rows than previous columns.');
}
$arr_col = array_values($arr_col); //to be sure to have index 0, 1, 2…
foreach ($arr_col as $k => $v) {
$this->arr[$k][] = $arr_col[$k];
}
return $this;
} | php | {
"resource": ""
} |
q250586 | Matrix.getRow | validation | public function getRow($int = 0)
{
if (!isset($this->arr[$int])) {
throw new \OutOfRangeException('There is no line having this index.');
}
return $this->arr[$int];
} | php | {
"resource": ""
} |
q250587 | Matrix.getCol | validation | public function getCol($int = 0)
{
if ($int >= $this->size->cols) {
throw new \OutOfRangeException('There is not column having this index.');
}
$arr_out = array();
foreach ($this->arr as $row) {
$arr_out[] = $row[$int];
}
return $arr_out;
} | php | {
"resource": ""
} |
q250588 | Matrix.isDiagonal | validation | public function isDiagonal()
{
$int_size = min((array) $this->size);
if($int_size > 0){
for($i = 0; $i < $int_size; $i++){
$arr_row = $this->getRow($i);
if($arr_row[$i] != 0){
unset($arr_row[$i]);
foreach($arr_row as $v){
if($v != 0){
return false;
}
}
} else {
return false;
}
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q250589 | Matrix.sameSize | validation | public function sameSize($matrix)
{
return (
$this->size->cols == $matrix->cols
&&
$this->size->rows == $matrix->rows
);
} | php | {
"resource": ""
} |
q250590 | Matrix.multiplyAllow | validation | public function multiplyAllow($matrix)
{
if (is_numeric($matrix)) {
return true;
}
if ($matrix instanceof Complex) {
return true;
}
if ($matrix instanceof Matrix) {
return $this->size->cols == $matrix->rows;
}
return false;
} | php | {
"resource": ""
} |
q250591 | Matrix.transpose | validation | public function transpose()
{
$out = new self($this->size->cols, $this->size->rows);
foreach ($this->arr as $row) {
$out->addCol($row);
}
return $out;
} | php | {
"resource": ""
} |
q250592 | Matrix.add | validation | public function add($matrix)
{
if (!($matrix instanceof Matrix)) {
throw new \InvalidArgumentException('Given argument must be an instance of \Malenki\Math\Matrix');
}
if (!$this->sameSize($matrix)) {
throw new \RuntimeException('Cannot adding given matrix: it has wrong size.');
}
$out = new self($this->size->rows, $this->size->cols);
foreach ($this->arr as $k => $v) {
$arrOther = $matrix->getRow($k);
$arrNew = array();
foreach ($v as $kk => $vv) {
if ($arrOther[$kk] instanceof Complex) {
$arrNew[] = $arrOther[$kk]->add($vv);
} elseif ($vv instanceof Complex) {
$arrNew[] = $vv->add($arrOther[$kk]);
} else {
$arrNew[] = $arrOther[$kk] + $vv;
}
}
$out->addRow($arrNew);
}
return $out;
} | php | {
"resource": ""
} |
q250593 | Matrix.cofactor | validation | public function cofactor()
{
$c = new self($this->size->rows, $this->size->cols);
for ($m = 0; $m < $this->size->rows; $m++) {
$arr_row = array();
for ($n = 0; $n < $this->size->cols; $n++) {
if ($this->size->cols == 2) {
$arr_row[] = pow(-1, $m + $n) * $this->subMatrix($m, $n)->get(0,0);
} else {
$arr_row[] = pow(-1, $m + $n) * $this->subMatrix($m, $n)->det();
}
}
$c->addRow($arr_row);
}
return $c;
} | php | {
"resource": ""
} |
q250594 | Matrix.inverse | validation | public function inverse()
{
$det = $this->det();
if ($det == 0) {
throw new \RuntimeException('Cannot get inverse matrix: determinant is nul!');
}
return $this->adjugate()->multiply(1 / $det);
} | php | {
"resource": ""
} |
q250595 | Matrix.subMatrix | validation | public function subMatrix($int_m, $int_n)
{
$sm = new self($this->size->rows - 1, $this->size->cols - 1);
foreach ($this->arr as $m => $row) {
if ($m != $int_m) {
$arr_row = array();
foreach ($row as $n => $v) {
if ($n != $int_n) {
$arr_row[] = $v;
}
}
$sm->addRow($arr_row);
}
}
return $sm;
} | php | {
"resource": ""
} |
q250596 | Matrix.det | validation | public function det()
{
if (!$this->isSquare()) {
throw new \RuntimeException('Cannot compute determinant of non square matrix!');
}
if ($this->size->rows == 2) {
return $this->get(0,0) * $this->get(1,1) - $this->get(0,1) * $this->get(1,0);
} else {
$int_out = 0;
$arr_row = $this->arr[0];
foreach ($arr_row as $n => $v) {
$int_out += pow(-1, $n + 2) * $v * $this->subMatrix(0, $n)->det();
}
return $int_out;
}
} | php | {
"resource": ""
} |
q250597 | Request.withUri | validation | public function withUri(UriInterface $uri, $preserve = false)
{
$static = clone $this;
$static->uri = $uri;
if (! $preserve && $host = $uri->getHost()) {
$port = $host . ':' . $uri->getPort();
$host = $uri->getPort() ? $port : $host;
$static->headers['Host'] = (array) $host;
}
return $static;
} | php | {
"resource": ""
} |
q250598 | Message.withoutHeader | validation | public function withoutHeader($name)
{
$instance = clone $this;
if ($this->hasHeader($name)) {
$static = clone $this;
unset($static->headers[$name]);
$instance = $static;
}
return $instance;
} | php | {
"resource": ""
} |
q250599 | ModuleDetailRetriever.getModulePath | validation | public function getModulePath($moduleName)
{
if (array_key_exists($moduleName, $this->loadedModules)) {
$module = $this->loadedModules[$moduleName];
$moduleConfig = $module->getAutoloaderConfig();
return $moduleConfig[self::STANDARD_AUTOLOLOADER][self::NAMESPACE_KEY][$moduleName];
}
return null;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.