_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q6500
AdvancedSearchable.resolveSearchKeywords
train
protected function resolveSearchKeywords(string $keyword): array { $basic = []; $advanced = []; $tags = \array_map(function ($value) { [$tag, ] = \explode(':', $value, 2); return "{$tag}:"; }, \array_keys($this->getSearchableRules())); if (\preg_match_all('/([\w]+:\"[\w\s]*\"|[\w]+:[\w\S]+|[\w\S]+)\s?/', $keyword, $keywords)) { foreach ($keywords[1] as $index => $keyword) { if (! Str::startsWith($keyword, $tags)) { \array_push($basic, $keyword); } else { \array_push($advanced, $keyword); } } } return [ 'basic' => \implode(' ', $basic), 'advanced' => $advanced, ]; }
php
{ "resource": "" }
q6501
TreeNodeSurv.loadNodeCache
train
public function loadNodeCache($nID = -3, $nCache = []) { if (sizeof($nCache) > 0) { if (isset($nCache["pID"])) { $this->parentID = $nCache["pID"]; } if (isset($nCache["pOrd"])) { $this->parentOrd = $nCache["pOrd"]; } if (isset($nCache["opts"])) { $this->nodeOpts = $nCache["opts"]; } if (isset($nCache["type"])) { $this->nodeType = $nCache["type"]; } if (isset($nCache["branch"])) { $this->dataBranch = $nCache["branch"]; } if (isset($nCache["store"])) { $this->dataStore = $nCache["store"]; } if (isset($nCache["set"])) { $this->responseSet = $nCache["set"]; } if (isset($nCache["def"])) { $this->defaultVal = $nCache["def"]; } } return true; }
php
{ "resource": "" }
q6502
GlobalsTables.getTblFldTypes
train
public function getTblFldTypes($tbl) { $flds = []; if (isset($this->fldTypes[$tbl]) && sizeof($this->fldTypes[$tbl]) > 0) { $flds = $this->fldTypes[$tbl]; } else { $tblRow = SLTables::where('TblName', $tbl) ->first(); if ($tblRow) { $chk = SLFields::where('FldTable', $tblRow->TblID) ->orderBy('FldOrd', 'asc') ->get(); if ($chk->isNotEmpty()) { foreach ($chk as $fldRow) { $flds[$tblRow->TblAbbr . $fldRow->FldName] = $fldRow->FldType; } } } } return $flds; }
php
{ "resource": "" }
q6503
SurvLoopController.checkSystemInit
train
public function checkSystemInit() { if (!session()->has('chkSysInit') || $GLOBALS["SL"]->REQ->has('refresh')) { $sysChk = User::select('id') ->get(); if ($sysChk->isEmpty()) { return $this->freshUser($GLOBALS["SL"]->REQ); } $sysChk = SLDatabases::select('DbID') ->where('DbUser', '>', 0) ->get(); if ($sysChk->isEmpty()) { return $this->redir('/fresh/database', true); } if (!$this->chkHasTreeOne()) { return $this->redir('/fresh/survey', true); } $survInst = new SurvLoopInstaller; $survInst->checkSysInit(); session()->put('chkSysInit', 1); } return ''; }
php
{ "resource": "" }
q6504
SurvLoopController.isPageFirstTime
train
protected function isPageFirstTime($currPage = '') { if (trim($currPage) == '') { $currPage = $this->v["currPage"][0]; } $chk = SLUsersActivity::where('UserActUser', Auth::user()->id) ->where('UserActCurrPage', 'LIKE', '%'.$currPage) ->get(); if ($chk->isNotEmpty()) { return false; } return true; }
php
{ "resource": "" }
q6505
SurvLoopController.doublecheckSurvTables
train
protected function doublecheckSurvTables() { if (!session()->has('doublecheckSurvTables')) { $chks = []; $chks[] = "ALTER TABLE `SL_Tree` CHANGE `TreeRootURL` `TreeSlug` VARCHAR(255)"; $chks[] = "ALTER TABLE `SL_Tree` ADD `TreeOpts` INT(11) DEFAULT 1 AFTER `TreeCoreTable`"; $chks[] = "ALTER TABLE `SL_DesignTweaks` ADD `TweakUniqueStr` INT(11) DEFAULT NULL AFTER `TweakVersionAB`"; $chks[] = "ALTER TABLE `SL_DesignTweaks` ADD `TweakIsMobile` VARCHAR(50) DEFAULT NULL AFTER " . "`TweakUniqueStr`"; ob_start(); try { foreach ($chks as $chk) { DB::select($chk); } } catch (QueryException $e) { } ob_end_clean(); session()->put('doublecheckSurvTables', 1); } return true; }
php
{ "resource": "" }
q6506
UpdatePasswordController.runUpdate
train
public function runUpdate(Request $request) { $user = User::find(Auth::id()); $this->validate($request, [ 'old' => 'required', 'password' => 'required|min:8|confirmed', ]); if (Auth::attempt(['name' => $user->name, 'password' => $request->old])) { $user->fill([ 'password' => bcrypt($request->password) ])->save(); $request->session()->flash('success', 'Your password has been changed.'); return redirect('/my-profile'); } $request->session()->flash('failure', 'Your password has not been changed.'); return redirect('/my-profile'); }
php
{ "resource": "" }
q6507
PHPArray.encode
train
protected function encode($data) { $data = [ '<?php', '', 'return ' . $this->render($data, 0) . ';', ]; return implode(Data::LE, $data); }
php
{ "resource": "" }
q6508
HumanDate.transform
train
public function transform($date) { if (!$date instanceof DateTime) { $date = new DateTime($date); } $current = new DateTime('now'); if ($this->isToday($date)) { return $this->trans('Today'); } if ($this->isYesterday($date)) { return $this->trans('Yesterday'); } if ($this->isTomorrow($date)) { return $this->trans('Tomorrow'); } if ($this->isNextWeek($date)) { return $this->trans('Next %weekday%', [ '%weekday%' => $date->format('l') ]); } if ($this->isLastWeek($date)) { return $this->trans('Last %weekday%', [ '%weekday%' => $date->format('l') ]); } if ($this->isThisYear($date)) { return $date->format('F j'); } return $date->format('F j, Y'); }
php
{ "resource": "" }
q6509
AttributeAttributeType.copy
train
public function copy($deepCopy = false) { // we use get_class(), because this might be a subclass $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); return $copyObj; }
php
{ "resource": "" }
q6510
AttributeAttributeType.setAttribute
train
public function setAttribute(ChildAttribute $v = null) { if ($v === null) { $this->setAttributeId(NULL); } else { $this->setAttributeId($v->getId()); } $this->aAttribute = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildAttribute object, it will not be re-added. if ($v !== null) { $v->addAttributeAttributeType($this); } return $this; }
php
{ "resource": "" }
q6511
AttributeAttributeType.getAttribute
train
public function getAttribute(ConnectionInterface $con = null) { if ($this->aAttribute === null && ($this->attribute_id !== null)) { $this->aAttribute = AttributeQuery::create()->findPk($this->attribute_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aAttribute->addAttributeAttributeTypes($this); */ } return $this->aAttribute; }
php
{ "resource": "" }
q6512
AttributeAttributeType.getAttributeType
train
public function getAttributeType(ConnectionInterface $con = null) { if ($this->aAttributeType === null && ($this->attribute_type_id !== null)) { $this->aAttributeType = ChildAttributeTypeQuery::create()->findPk($this->attribute_type_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aAttributeType->addAttributeAttributeTypes($this); */ } return $this->aAttributeType; }
php
{ "resource": "" }
q6513
AttributeAttributeType.initAttributeTypeAvMetas
train
public function initAttributeTypeAvMetas($overrideExisting = true) { if (null !== $this->collAttributeTypeAvMetas && !$overrideExisting) { return; } $this->collAttributeTypeAvMetas = new ObjectCollection(); $this->collAttributeTypeAvMetas->setModel('\AttributeType\Model\AttributeTypeAvMeta'); }
php
{ "resource": "" }
q6514
AttributeAttributeType.getAttributeTypeAvMetas
train
public function getAttributeTypeAvMetas($criteria = null, ConnectionInterface $con = null) { $partial = $this->collAttributeTypeAvMetasPartial && !$this->isNew(); if (null === $this->collAttributeTypeAvMetas || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeTypeAvMetas) { // return empty collection $this->initAttributeTypeAvMetas(); } else { $collAttributeTypeAvMetas = ChildAttributeTypeAvMetaQuery::create(null, $criteria) ->filterByAttributeAttributeType($this) ->find($con); if (null !== $criteria) { if (false !== $this->collAttributeTypeAvMetasPartial && count($collAttributeTypeAvMetas)) { $this->initAttributeTypeAvMetas(false); foreach ($collAttributeTypeAvMetas as $obj) { if (false == $this->collAttributeTypeAvMetas->contains($obj)) { $this->collAttributeTypeAvMetas->append($obj); } } $this->collAttributeTypeAvMetasPartial = true; } reset($collAttributeTypeAvMetas); return $collAttributeTypeAvMetas; } if ($partial && $this->collAttributeTypeAvMetas) { foreach ($this->collAttributeTypeAvMetas as $obj) { if ($obj->isNew()) { $collAttributeTypeAvMetas[] = $obj; } } } $this->collAttributeTypeAvMetas = $collAttributeTypeAvMetas; $this->collAttributeTypeAvMetasPartial = false; } } return $this->collAttributeTypeAvMetas; }
php
{ "resource": "" }
q6515
AttributeAttributeType.countAttributeTypeAvMetas
train
public function countAttributeTypeAvMetas(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { $partial = $this->collAttributeTypeAvMetasPartial && !$this->isNew(); if (null === $this->collAttributeTypeAvMetas || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeTypeAvMetas) { return 0; } if ($partial && !$criteria) { return count($this->getAttributeTypeAvMetas()); } $query = ChildAttributeTypeAvMetaQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByAttributeAttributeType($this) ->count($con); } return count($this->collAttributeTypeAvMetas); }
php
{ "resource": "" }
q6516
AttributeAttributeType.addAttributeTypeAvMeta
train
public function addAttributeTypeAvMeta(ChildAttributeTypeAvMeta $l) { if ($this->collAttributeTypeAvMetas === null) { $this->initAttributeTypeAvMetas(); $this->collAttributeTypeAvMetasPartial = true; } if (!in_array($l, $this->collAttributeTypeAvMetas->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddAttributeTypeAvMeta($l); } return $this; }
php
{ "resource": "" }
q6517
AttributeAttributeType.getAttributeTypeAvMetasJoinAttributeAv
train
public function getAttributeTypeAvMetasJoinAttributeAv($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildAttributeTypeAvMetaQuery::create(null, $criteria); $query->joinWith('AttributeAv', $joinBehavior); return $this->getAttributeTypeAvMetas($query, $con); }
php
{ "resource": "" }
q6518
ChainSearchProvider.getClient
train
public function getClient() { $client = $this->reduceFirst(function (SearchProviderInterface $provider) { return $provider->getClient(); }); if (null === $client) { throw new \RuntimeException('No provider was able to return a client'); } return $client; }
php
{ "resource": "" }
q6519
ChainSearchProvider.getIndex
train
public function getIndex($indexName) { return $this->reduceFirst(function (SearchProviderInterface $provider) use ($indexName) { return $provider->getIndex($this->indexNamePrefix . $indexName); }); }
php
{ "resource": "" }
q6520
ChainSearchProvider.createDocument
train
public function createDocument($document, $uid, $indexName = '', $indexType = '') { return new DocumentReference($document, $uid, $this->indexNamePrefix . $indexName, $indexType); }
php
{ "resource": "" }
q6521
ChainSearchProvider.addDocument
train
public function addDocument($indexName, $indexType, $document, $uid) { if ("" === $indexName && $document instanceof DocumentReference) { $indexName = $document->getIndexName(); } else { $indexName = $this->indexNamePrefix . $indexName; } $this->mapProviders(function (SearchProviderInterface $provider) use ($document, $uid, $indexName, $indexType) { $provider->addDocument($document, $uid, $indexName, $indexType); }); }
php
{ "resource": "" }
q6522
ChainSearchProvider.addDocuments
train
public function addDocuments($documents, $indexName = '', $indexType = '') { if ("" === $indexName && isset($documents[0])) { $indexName = $documents[0]->getIndexName(); } else { $indexName = $this->indexNamePrefix . $indexName; } $this->mapProviders(function (SearchProviderInterface $provider) use ($documents, $indexName, $indexType) { $documents = array_map(function (DocumentReference $document) use ($provider) { return $provider->createDocument( $document->getDocument(), $document->getUid(), $document->getIndexName(), $document->getIndexType() ); }, $documents); $provider->addDocuments($documents, $indexName, $indexType); }); }
php
{ "resource": "" }
q6523
ChainSearchProvider.deleteDocument
train
public function deleteDocument($indexName, $indexType, $uid) { $this->mapProviders(function (SearchProviderInterface $provider) use ($indexName, $indexType, $uid) { $provider->deleteDocument($this->indexNamePrefix . $indexName, $indexType, $uid); }); }
php
{ "resource": "" }
q6524
ChainSearchProvider.deleteIndex
train
public function deleteIndex($indexName) { $this->mapProviders(function (SearchProviderInterface $provider) use ($indexName) { try { $provider->deleteIndex($this->indexNamePrefix . $indexName); } catch (\Exception $e) { // we don’t care } }); }
php
{ "resource": "" }
q6525
ValidatingMiddleware.handle
train
public function handle($command, Closure $next) { if (property_exists($command, 'rules') && is_array($command->rules)) { $this->validate($command); } return $next($command); }
php
{ "resource": "" }
q6526
ValidatingMiddleware.validate
train
protected function validate($command) { if (method_exists($command, 'validate')) { $command->validate(); } $messages = property_exists($command, 'validationMessages') ? $command->validationMessages : []; $validator = $this->factory->make($this->getData($command), $command->rules, $messages); if ($validator->fails()) { throw new ValidationException($validator->getMessageBag()); } }
php
{ "resource": "" }
q6527
ValidatingMiddleware.getData
train
protected function getData($command) { $data = []; foreach ((new ReflectionClass($command))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { $name = $property->getName(); $value = $property->getValue($command); if (in_array($name, ['rules', 'validationMessages'], true)) { continue; } $data[$name] = $value; } return $data; }
php
{ "resource": "" }
q6528
TelegramHandler.send
train
private function send($message) { $url = self::BASE_URI . $this->token . '/sendMessage'; $data = [ 'chat_id' => $this->chatId, 'text' => $message, 'disable_web_page_preview' => true // Just in case there is a link in the message ]; // Set HTML parse mode when HTML code is detected if (preg_match('/<[^<]+>/', $data['text']) !== false) { $data['parse_mode'] = 'HTML'; } if ($this->useCurl === true && extension_loaded('curl')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); $result = curl_exec($ch); if (!$result) { throw new \RuntimeException('Request to Telegram API failed: ' . curl_error($ch)); } } else { $opts = [ 'http' => [ 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($data), 'timeout' => $this->timeout, ], 'ssl' => [ 'verify_peer' => $this->verifyPeer, 'verify_peer_name' => $this->verifyPeer, ], ]; $result = @file_get_contents($url, false, stream_context_create($opts)); if (!$result) { $error = error_get_last(); if (isset($error['message'])) { throw new \RuntimeException('Request to Telegram API failed: ' . $error['message']); } throw new \RuntimeException('Request to Telegram API failed'); } } $result = json_decode($result, true); if (isset($result['ok']) && $result['ok'] === true) { return true; } if (isset($result['description'])) { throw new \RuntimeException('Telegram API error: ' . $result['description']); } return false; }
php
{ "resource": "" }
q6529
HttpTrait.getParameter
train
protected function getParameter($key, $type = Validate::TYPE_STRING, array $filter = array(), $title = null, $required = true) { $parameter = $this->request->getUri()->getParameter($key); if (isset($parameter)) { return $this->validate->apply($parameter, $type, $filter, $title, $required); } else { return null; } }
php
{ "resource": "" }
q6530
HttpTrait.setBody
train
protected function setBody($data) { $this->responseWriter->setBody($this->response, $data, $this->request); }
php
{ "resource": "" }
q6531
RedirectTrait.forward
train
protected function forward($source, array $parameters = array()) { $path = $this->reverseRouter->getPath($source, $parameters); if ($path !== null) { $this->request->setUri($this->request->getUri()->withPath($path)); $this->loader->load($this->request, $this->response, $this->context); } else { throw new RuntimeException('Could not find route for source ' . $source); } }
php
{ "resource": "" }
q6532
RedirectTrait.redirect
train
protected function redirect($source, array $parameters = array(), $code = 307) { if ($source instanceof Url) { $url = $source->toString(); } elseif (filter_var($source, FILTER_VALIDATE_URL)) { $url = $source; } else { $url = $this->reverseRouter->getUrl($source, $parameters); } if ($code == 301) { throw new StatusCode\MovedPermanentlyException($url); } elseif ($code == 302) { throw new StatusCode\FoundException($url); } elseif ($code == 307) { throw new StatusCode\TemporaryRedirectException($url); } else { throw new RuntimeException('Invalid redirect status code'); } }
php
{ "resource": "" }
q6533
GeneratorService.generateRemotingApi
train
public function generateRemotingApi() { $list = array(); foreach($this->remotingBundles as $bundle) { $bundleRef = new \ReflectionClass($bundle); $controllerDir = new Finder(); $controllerDir->files()->in(dirname($bundleRef->getFileName()).'/Controller/')->name('/.*Controller\.php$/'); foreach($controllerDir as $controllerFile) { $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4); $controllerRef = new \ReflectionClass($controller); foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { /** @var $methodDirectAnnotation Direct */ $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\ExtjsBundle\Annotation\Direct'); if ($methodDirectAnnotation !== null) { $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName()); $className = str_replace("Controller", "", $controllerRef->getShortName()); $methodName = str_replace("Action", "", $method->getName()); $list[$nameSpace][$className][] = array( 'name'=>$methodName, 'len' => count($method->getParameters()) ); } } } } return $list; }
php
{ "resource": "" }
q6534
GeneratorService.tryToGetJoinColumnNameOfMappedBy
train
protected function tryToGetJoinColumnNameOfMappedBy($annotation){ $annotation = $this->tryToGetJoinColumnAnnotationOfMappedBy($annotation); if ($annotation !== null) { if ($annotation instanceof JoinColumn) { return $annotation->name; } else if ($annotation instanceof JoinColumns) { if (count($annotation->value) > 1) { throw new \Exception('Multiple foreign key is not supported'); } return $annotation->value[0]->name; } } return ''; }
php
{ "resource": "" }
q6535
GeneratorService.tryToGetJoinColumnAnnotationOfMappedBy
train
protected function tryToGetJoinColumnAnnotationOfMappedBy($annotation){ $result = null; if($annotation->targetEntity && $annotation->mappedBy) { $result = $this->getAnnotation( $annotation->targetEntity, $annotation->mappedBy, 'Doctrine\ORM\Mapping\JoinColumn' ); if ($result === null) { $result = $this->getAnnotation( $annotation->targetEntity, $annotation->mappedBy, 'Doctrine\ORM\Mapping\JoinColumns' ); } } return $result; }
php
{ "resource": "" }
q6536
GeneratorService.getEntityColumnType
train
public function getEntityColumnType($entity, $property) { $classRef = new \ReflectionClass($entity); if ($classRef->hasProperty($property)) { $propertyRef = $classRef->getProperty($property); $columnRef = $this->annoReader->getPropertyAnnotation($propertyRef, 'Doctrine\ORM\Mapping\Column'); } else { /** Can not find the property on the class. Check the all the Column annotation */ foreach ($classRef->getProperties() as $propertyRef) { $columnRef = $this->annoReader->getPropertyAnnotation($propertyRef, 'Doctrine\ORM\Mapping\Column'); if ($columnRef->name == $property) { break; } else { $columnRef = null; } } } if ($columnRef === null) { $idRef = $this->annoReader->getPropertyAnnotation($propertyRef, 'Doctrine\ORM\Mapping\Id'); if ($idRef !== null) { return "int"; } else { return "string"; } } else { return $this->getColumnType($columnRef->type); } }
php
{ "resource": "" }
q6537
GeneratorService.getValidator
train
protected function getValidator($name, $annotation) { $validate = array(); switch($name) { case 'NotBlank': case 'NotNull': $validate['type'] = "presence"; break; case 'Email': $validate['type'] = "email"; break; case 'Length': $validate['type'] = "length"; $validate['max'] = (int)$annotation->max; $validate['min'] = (int)$annotation->min; break; case 'Regex': if ($annotation->match) { $validate['type'] = "format"; $validate['matcher']['skipEncode'] = true; $validate['matcher']['value'] = $annotation->pattern; } break; case 'MaxLength': case 'MinLength': $validate['type'] = "length"; if ($name == "MaxLength") { $validate['max'] = (int)$annotation->limit; } else { $validate['min'] = (int)$annotation->limit; } break; case 'Choice': $validate['type'] = "inclusion"; $validate['list'] = $annotation->choices; break; default: $validate['type'] = strtolower($name); $validate += get_object_vars($annotation); break; } return $validate; }
php
{ "resource": "" }
q6538
GeneratorService.getModelName
train
public function getModelName($entity) { $classRef = new \ReflectionClass($entity); $classModelAnnotation = $this->annoReader->getClassAnnotation($classRef, 'Tpg\ExtjsBundle\Annotation\Model'); if ($classModelAnnotation !== null) { if ($classModelAnnotation->name) { return $classModelAnnotation->name; } else { return str_replace("\\", ".", $classRef->getName()); } } return null; }
php
{ "resource": "" }
q6539
Dispatch.route
train
public function route(RequestInterface $request, ResponseInterface $response, Context $context = null) { $this->level++; $this->eventDispatcher->dispatch(Event::REQUEST_INCOMING, new RequestIncomingEvent($request)); // load controller if ($context === null) { $factory = $this->config->get('psx_context_factory'); if ($factory instanceof \Closure) { $context = $factory(); } else { $context = new Context(); } } try { $this->loader->load($request, $response, $context); } catch (StatusCode\NotModifiedException $e) { $response->setStatus($e->getStatusCode()); $response->setBody(new StringStream()); } catch (StatusCode\RedirectionException $e) { $response->setStatus($e->getStatusCode()); $response->setHeader('Location', $e->getLocation()); $response->setBody(new StringStream()); } catch (\Throwable $e) { $this->eventDispatcher->dispatch(Event::EXCEPTION_THROWN, new ExceptionThrownEvent($e, new ControllerContext($request, $response))); $this->handleException($e, $response); try { $context->setException($e); $class = isset($this->config['psx_error_controller']) ? $this->config['psx_error_controller'] : ErrorController::class; $controller = $this->controllerFactory->getController($class, $context); $this->loader->execute($controller, $request, $response); } catch (\Throwable $e) { // in this case the error controller has thrown an exception. // This can happen i.e. if we can not represent the error in an // fitting media type. In this case we send json to the client $this->handleException($e, $response); $record = $this->exceptionConverter->convert($e); $response->setHeader('Content-Type', 'application/json'); $response->setBody(new StringStream(Parser::encode($record, JSON_PRETTY_PRINT))); } } // for HEAD requests we never return a response body if ($request->getMethod() == 'HEAD') { $response->setHeader('Content-Length', $response->getBody()->getSize()); $response->setBody(new StringStream('')); } $this->eventDispatcher->dispatch(Event::RESPONSE_SEND, new ResponseSendEvent($response)); $this->level--; return $response; }
php
{ "resource": "" }
q6540
Queue.consume
train
public static function consume($name) { $config = static::get($name); if (empty($config['consume'])) { throw new Exception('Missing consumer configuration (' . $name . ')'); } $config = $config['consume']; $config += [ 'connection' => 'rabbit', 'prefetchCount' => 1, ]; if (!array_key_exists($name, static::$_consumers)) { $connection = ConnectionManager::get($config['connection']); static::$_consumers[$name] = $connection->queue($config['queue'], $config); } return static::$_consumers[$name]; }
php
{ "resource": "" }
q6541
Queue.publish
train
public static function publish($name, $data, array $options = []) { $config = static::get($name); if (empty($config['publish'])) { throw new Exception('Missing publisher configuration (' . $name . ')'); } $config = $config['publish']; $config += $options; $config += [ 'connection' => 'rabbit', 'className' => 'RabbitMQ.RabbitQueue' ]; if (!array_key_exists($name, static::$_publishers)) { static::$_publishers[$name] = ConnectionManager::get($config['connection']); } return static::$_publishers[$name]->send($config['exchange'], $config['routing'], $data, $config); }
php
{ "resource": "" }
q6542
ExtjsExtension.injectModel
train
public function injectModel() { $params = func_get_args(); $injection = array_shift($params); if ($injection == false) { $url = $this->router->generate('extjs_generate_model', array('model'=>$params), false); return "<script type='text/javascript' src='$url'></script>"; } else { $code = ''; foreach ($params as $model) { $model = str_replace(".", "\\", $model); $code .= $this->generator->generateMarkupForEntity($model); } return $code; } }
php
{ "resource": "" }
q6543
MenuItemsTable.beforeSave
train
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options): void { // fallback to default icon if (!$entity->get('icon')) { $entity->set('icon', Configure::read('Icons.default')); } // fallback to hashtag as default url if (!$entity->get('url')) { $entity->set('url', '#'); } }
php
{ "resource": "" }
q6544
ObjectTrait.set
train
public function set($name, $value, $where = '') { if (($name && $this->canSetProperty($name)) || strpos($name, 'on ') === 0 || strpos($name, 'as ') === 0) { parent::__set($name, $value); } else { $this->setItem($name, $value, $where); } }
php
{ "resource": "" }
q6545
ObjectTrait.add
train
public function add($name, $value = null, $where = '') { if (!$this->has($name)) { $this->set($name, $value, $where); } return $this; }
php
{ "resource": "" }
q6546
FileCommentCopyrightSniff.processCopyrightTags
train
private function processCopyrightTags(File $phpcs_file, $stack_ptr, $comment_start): void { $tokens = $phpcs_file->getTokens(); foreach ($tokens[$comment_start]['comment_tags'] as $tag) { if ($tokens[$tag]['content'] === $this->copyright_tag) { $this->checkForContentInCopyrightTag($phpcs_file, $tag, $tokens[$comment_start]['comment_closer']); //Use default PEAR style copyright notation checking. $this->processCopyright($phpcs_file, [$tag]); return; } } //No @copyright tag because not returned $error = 'Missing ' . $this->copyright_tag . ' tag in file doc-block'; if (false === $phpcs_file->addFixableError($error, $stack_ptr, 'MissingCopyrightTag')) { return; } if ($tokens[$tokens[$comment_start]['comment_closer']]['line'] === $tokens[$comment_start]['line']) { $phpcs_file->fixer->replaceToken($tokens[$comment_start]['comment_closer'] - 1, ''); $phpcs_file->fixer->addContentBefore( $tokens[$comment_start]['comment_closer'], sprintf("\n * %s %s\n ", $this->copyright_tag, $this->getCopyrightLine()) ); return; } $phpcs_file->fixer->addContentBefore( $tokens[$comment_start]['comment_closer'], sprintf("* %s %s\n ", $this->copyright_tag, $this->getCopyrightLine()) ); }
php
{ "resource": "" }
q6547
ManagerTrait.getItem
train
public function getItem($name, $default = null) { if (empty($this->_items[$name])) { $this->_items[$name] = $default; } $item = &$this->_items[$name]; if (is_array($item) || is_null($item)) { $item = $this->createItem($name, $item ?: []); } return $item; }
php
{ "resource": "" }
q6548
ManagerTrait.getItems
train
public function getItems() { foreach ($this->_items as $name => $item) { $this->getItem($name); } return $this->_items; }
php
{ "resource": "" }
q6549
UriExtended.withoutQueryValue
train
public function withoutQueryValue($key):UriExtended{ $current = $this->getQuery(); if($current === ''){ return $this; } $decodedKey = \rawurldecode($key); $result = \array_filter(\explode('&', $current), function($part) use ($decodedKey){ return \rawurldecode(\explode('=', $part)[0]) !== $decodedKey; }); return $this->withQuery(\implode('&', $result)); }
php
{ "resource": "" }
q6550
AttributeType.initAttributeAttributeTypes
train
public function initAttributeAttributeTypes($overrideExisting = true) { if (null !== $this->collAttributeAttributeTypes && !$overrideExisting) { return; } $this->collAttributeAttributeTypes = new ObjectCollection(); $this->collAttributeAttributeTypes->setModel('\AttributeType\Model\AttributeAttributeType'); }
php
{ "resource": "" }
q6551
AttributeType.getAttributeAttributeTypes
train
public function getAttributeAttributeTypes($criteria = null, ConnectionInterface $con = null) { $partial = $this->collAttributeAttributeTypesPartial && !$this->isNew(); if (null === $this->collAttributeAttributeTypes || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeAttributeTypes) { // return empty collection $this->initAttributeAttributeTypes(); } else { $collAttributeAttributeTypes = ChildAttributeAttributeTypeQuery::create(null, $criteria) ->filterByAttributeType($this) ->find($con); if (null !== $criteria) { if (false !== $this->collAttributeAttributeTypesPartial && count($collAttributeAttributeTypes)) { $this->initAttributeAttributeTypes(false); foreach ($collAttributeAttributeTypes as $obj) { if (false == $this->collAttributeAttributeTypes->contains($obj)) { $this->collAttributeAttributeTypes->append($obj); } } $this->collAttributeAttributeTypesPartial = true; } reset($collAttributeAttributeTypes); return $collAttributeAttributeTypes; } if ($partial && $this->collAttributeAttributeTypes) { foreach ($this->collAttributeAttributeTypes as $obj) { if ($obj->isNew()) { $collAttributeAttributeTypes[] = $obj; } } } $this->collAttributeAttributeTypes = $collAttributeAttributeTypes; $this->collAttributeAttributeTypesPartial = false; } } return $this->collAttributeAttributeTypes; }
php
{ "resource": "" }
q6552
AttributeType.countAttributeAttributeTypes
train
public function countAttributeAttributeTypes(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { $partial = $this->collAttributeAttributeTypesPartial && !$this->isNew(); if (null === $this->collAttributeAttributeTypes || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeAttributeTypes) { return 0; } if ($partial && !$criteria) { return count($this->getAttributeAttributeTypes()); } $query = ChildAttributeAttributeTypeQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByAttributeType($this) ->count($con); } return count($this->collAttributeAttributeTypes); }
php
{ "resource": "" }
q6553
AttributeType.addAttributeAttributeType
train
public function addAttributeAttributeType(ChildAttributeAttributeType $l) { if ($this->collAttributeAttributeTypes === null) { $this->initAttributeAttributeTypes(); $this->collAttributeAttributeTypesPartial = true; } if (!in_array($l, $this->collAttributeAttributeTypes->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddAttributeAttributeType($l); } return $this; }
php
{ "resource": "" }
q6554
AttributeType.getAttributeAttributeTypesJoinAttribute
train
public function getAttributeAttributeTypesJoinAttribute($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildAttributeAttributeTypeQuery::create(null, $criteria); $query->joinWith('Attribute', $joinBehavior); return $this->getAttributeAttributeTypes($query, $con); }
php
{ "resource": "" }
q6555
AttributeType.initAttributeTypeI18ns
train
public function initAttributeTypeI18ns($overrideExisting = true) { if (null !== $this->collAttributeTypeI18ns && !$overrideExisting) { return; } $this->collAttributeTypeI18ns = new ObjectCollection(); $this->collAttributeTypeI18ns->setModel('\AttributeType\Model\AttributeTypeI18n'); }
php
{ "resource": "" }
q6556
AttributeType.getAttributeTypeI18ns
train
public function getAttributeTypeI18ns($criteria = null, ConnectionInterface $con = null) { $partial = $this->collAttributeTypeI18nsPartial && !$this->isNew(); if (null === $this->collAttributeTypeI18ns || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeTypeI18ns) { // return empty collection $this->initAttributeTypeI18ns(); } else { $collAttributeTypeI18ns = ChildAttributeTypeI18nQuery::create(null, $criteria) ->filterByAttributeType($this) ->find($con); if (null !== $criteria) { if (false !== $this->collAttributeTypeI18nsPartial && count($collAttributeTypeI18ns)) { $this->initAttributeTypeI18ns(false); foreach ($collAttributeTypeI18ns as $obj) { if (false == $this->collAttributeTypeI18ns->contains($obj)) { $this->collAttributeTypeI18ns->append($obj); } } $this->collAttributeTypeI18nsPartial = true; } reset($collAttributeTypeI18ns); return $collAttributeTypeI18ns; } if ($partial && $this->collAttributeTypeI18ns) { foreach ($this->collAttributeTypeI18ns as $obj) { if ($obj->isNew()) { $collAttributeTypeI18ns[] = $obj; } } } $this->collAttributeTypeI18ns = $collAttributeTypeI18ns; $this->collAttributeTypeI18nsPartial = false; } } return $this->collAttributeTypeI18ns; }
php
{ "resource": "" }
q6557
AttributeType.countAttributeTypeI18ns
train
public function countAttributeTypeI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { $partial = $this->collAttributeTypeI18nsPartial && !$this->isNew(); if (null === $this->collAttributeTypeI18ns || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collAttributeTypeI18ns) { return 0; } if ($partial && !$criteria) { return count($this->getAttributeTypeI18ns()); } $query = ChildAttributeTypeI18nQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByAttributeType($this) ->count($con); } return count($this->collAttributeTypeI18ns); }
php
{ "resource": "" }
q6558
AttributeType.addAttributeTypeI18n
train
public function addAttributeTypeI18n(ChildAttributeTypeI18n $l) { if ($l && $locale = $l->getLocale()) { $this->setLocale($locale); $this->currentTranslations[$locale] = $l; } if ($this->collAttributeTypeI18ns === null) { $this->initAttributeTypeI18ns(); $this->collAttributeTypeI18nsPartial = true; } if (!in_array($l, $this->collAttributeTypeI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated $this->doAddAttributeTypeI18n($l); } return $this; }
php
{ "resource": "" }
q6559
AttributeType.validate
train
public function validate(Validator $validator = null) { if (null === $validator) { $validator = new Validator(new ClassMetadataFactory(new StaticMethodLoader()), new ConstraintValidatorFactory(), new DefaultTranslator()); } $failureMap = new ConstraintViolationList(); if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $retval = $validator->validate($this); if (count($retval) > 0) { $failureMap->addAll($retval); } if (null !== $this->collAttributeAttributeTypes) { foreach ($this->collAttributeAttributeTypes as $referrerFK) { if (method_exists($referrerFK, 'validate')) { if (!$referrerFK->validate($validator)) { $failureMap->addAll($referrerFK->getValidationFailures()); } } } } if (null !== $this->collAttributeTypeI18ns) { foreach ($this->collAttributeTypeI18ns as $referrerFK) { if (method_exists($referrerFK, 'validate')) { if (!$referrerFK->validate($validator)) { $failureMap->addAll($referrerFK->getValidationFailures()); } } } } $this->alreadyInValidation = false; } $this->validationFailures = $failureMap; return (Boolean) (!(count($this->validationFailures) > 0)); }
php
{ "resource": "" }
q6560
RabbitMQConnection.logQueries
train
public function logQueries($enable = null) { if ($enable !== null) { $this->_logQueries = $enable; } if ($this->_logQueries) { return $this->_logQueries; } return $this->_logQueries = $enable; }
php
{ "resource": "" }
q6561
RabbitMQConnection.logger
train
public function logger($logger = null) { if ($logger) { $this->_logger = $logger; } if ($this->_logger) { return $this->_logger; } $this->_logger = new QueryLogger(); return $this->_logger; }
php
{ "resource": "" }
q6562
RabbitMQConnection.connect
train
public function connect() { $connection = $this->_connection; $connection->setLogin($this->_config['user']); $connection->setPassword($this->_config['password']); $connection->setHost($this->_config['host']); $connection->setPort($this->_config['port']); $connection->setVhost($this->_config['vhost']); $connection->setReadTimeout($this->_config['readTimeout']); # You shall not use persistent connections # # AMQPChannelException' with message 'Could not create channel. Connection has no open channel slots remaining # # The PECL extension is foobar, http://stackoverflow.com/questions/23864647/how-to-avoid-max-channels-per-tcp-connection-with-amqp-php-persistent-connectio # $connection->connect(); }
php
{ "resource": "" }
q6563
RabbitMQConnection.channel
train
public function channel($name, $options = []) { if (empty($this->_channels[$name])) { $this->_channels[$name] = new AMQPChannel($this->connection()); if (!empty($options['prefetchCount'])) { $this->_channels[$name]->setPrefetchCount((int)$options['prefetchCount']); } } return $this->_channels[$name]; }
php
{ "resource": "" }
q6564
RabbitMQConnection.exchange
train
public function exchange($name, $options = []) { if (empty($this->_exchanges[$name])) { $channel = $this->channel($name, $options); $exchange = new AMQPExchange($channel); $exchange->setName($name); if (!empty($options['type'])) { $exchange->setType($options['type']); } if (!empty($options['flags'])) { $exchange->setFlags($options['flags']); } $this->_exchanges[$name] = $exchange; } return $this->_exchanges[$name]; }
php
{ "resource": "" }
q6565
RabbitMQConnection.queue
train
public function queue($name, $options = []) { if (empty($this->_queues[$name])) { $channel = $this->channel($name, $options); $queue = new AMQPQueue($channel); $queue->setName($name); if (!empty($options['flags'])) { $queue->setFlags($options['flags']); } $this->_queues[$name] = $queue; } return $this->_queues[$name]; }
php
{ "resource": "" }
q6566
RabbitMQConnection._prepareMessage
train
protected function _prepareMessage($data, array $options) { $attributes = []; $options += [ 'silent' => false, 'compress' => true, 'serializer' => extension_loaded('msgpack') ? 'msgpack' : 'json', 'delivery_mode' => 1 ]; switch ($options['serializer']) { case 'json': $data = json_encode($data); $attributes['content_type'] = 'application/json'; break; case 'text': $attributes['content_type'] = 'application/text'; break; default: throw new RuntimeException('Unknown serializer: ' . $options['serializer']); } if (!empty($options['compress'])) { $data = gzcompress($data); $attributes += ['content_encoding' => 'gzip']; } if (!empty($options['delivery_mode'])) { $attributes['delivery_mode'] = $options['delivery_mode']; } return [$data, $attributes, $options]; }
php
{ "resource": "" }
q6567
TreeSurvBasicNav.chkKidMapTrue
train
protected function chkKidMapTrue($nID) { $found = false; if (sizeof($this->kidMaps) > 0) { foreach ($this->kidMaps as $parent => $kids) { if (sizeof($kids) > 0) { foreach ($kids as $nKid => $ress) { if ($nID == $nKid && sizeof($ress) > 0) { $found = true; foreach ($ress as $cnt => $res) { if (isset($res[2]) && $res[2]) { return 1; } } } } } } } return (($found) ? -1 : 0); }
php
{ "resource": "" }
q6568
Contentful.getContentTypeByName
train
public function getContentTypeByName($name, $space, array $options = []) { $envelope = $this->findEnvelopeForSpace($space); $promise = coroutine( function () use ($name, $space, $envelope, $options) { $contentTypeFromEnvelope = $envelope->findContentTypeByName($name); if ($contentTypeFromEnvelope) { yield promise_for($contentTypeFromEnvelope); return; } $contentTypes = (yield $this->getContentTypes([], $space, array_merge($options, ['async' => true]))); $foundContentType = null; foreach ($contentTypes as $contentType) { if ($contentType->getName() === $name) { $foundContentType = $contentType; } $envelope->insertContentType($contentType); } yield $foundContentType; } ); return (isset($options['async']) && $options['async']) ? $promise : $promise->wait(); }
php
{ "resource": "" }
q6569
Contentful.flushCache
train
public function flushCache($spaceName) { $spaceData = $this->getSpaceDataForName($spaceName); return $this->ensureCache($spaceData['cache'])->clear(); }
php
{ "resource": "" }
q6570
Contentful.completeParameter
train
private function completeParameter(ParameterInterface $parameter, $spaceName) { if (!$parameter instanceof IncompleteParameterInterface) { return $parameter; } switch ($parameter->getName()) { case 'content_type_name': $contentTypeFilter = $this->resolveContentTypeNameFilter($parameter, $spaceName); if (null === $contentTypeFilter) { throw new \RuntimeException(sprintf('Could not resolve content type with name "%s".', $parameter->getValue())); } return $contentTypeFilter; break; default: throw new \LogicException(sprintf('Unknown incomplete parameter of type "%s" is being used.', $parameter->getName())); break; } }
php
{ "resource": "" }
q6571
SchemaApiAbstract.parseRequest
train
protected function parseRequest(RequestInterface $request, MethodAbstract $method) { if ($method->hasRequest()) { $schema = $method->getRequest(); if ($schema instanceof Passthru) { $data = $this->requestReader->getBody($request); } elseif ($schema instanceof SchemaInterface) { $data = $this->requestReader->getBodyAs($request, $method->getRequest(), $this->getValidator($method)); } else { $data = new Record(); } } else { $data = null; } return $data; }
php
{ "resource": "" }
q6572
SchemaApiAbstract.sendResponse
train
private function sendResponse(MethodAbstract $method, RequestInterface $request, ResponseInterface $response, $data) { $statusCode = $response->getStatusCode(); if (empty($statusCode)) { // in case we have only one defined response use this code $responses = $method->getResponses(); if (count($responses) == 1) { $statusCode = key($responses); } else { $statusCode = 200; } $response->setStatus($statusCode); } $this->responseWriter->setBody($response, $data, $request); }
php
{ "resource": "" }
q6573
SchemaApiAbstract.getResource
train
private function getResource() { $resource = $this->resourceListing->getResource($this->context->getPath(), $this->context->getVersion()); if (!$resource instanceof Resource) { throw new StatusCode\InternalServerErrorException('Resource is not available'); } return $resource; }
php
{ "resource": "" }
q6574
ContentTypePromise.getField
train
public function getField($fieldId) { $resolved = $this->getResolved(); if (!$resolved instanceof ContentTypeInterface) { return null; } return $resolved->getField($fieldId); }
php
{ "resource": "" }
q6575
UserProvider.get
train
public function get(string $key = null, $default = null) { $key = \str_replace('.', '/user-', $key); $value = Arr::get($this->items, $key); // We need to consider if the value pending to be deleted, // in this case return the default. if ($value === ':to-be-deleted:') { return \value($default); } // If the result is available from data, simply return it so we // don't have to fetch the same result again from the database. if (! \is_null($value)) { return $value; } if (\is_null($value = $this->handler->retrieve($key))) { return \value($default); } $this->put($key, $value); return $value; }
php
{ "resource": "" }
q6576
Python.isJson
train
protected function isJson($string) { $output = json_decode($string, true); if ($output === null) { return false; } return true; }
php
{ "resource": "" }
q6577
BasicDocumentor.getTemplate
train
protected static function getTemplate($path) { if(file_exists($path)) $template = file_get_contents($path); elseif(file_exists(__DIR__ . '/templates/' . $path)) $template = file_get_contents(__DIR__ . '/templates/' . $path); else throw new \InvalidArgumentException('Template file not found.'); return $template; }
php
{ "resource": "" }
q6578
RedisSessionHandler.read
train
public function read($sessionId) { $sessionId = $this->keyPrefix . $sessionId; $sessionData = $this->redis->get($sessionId); $this->redis->expire($sessionId, $this->maxLifetime); return $sessionData; }
php
{ "resource": "" }
q6579
NotFoundManager.removeForRedirect
train
public function removeForRedirect(Redirect $redirect) { $notFounds = $this->om->getRepository($this->class)->findBy(array('path' => $redirect->getSource())); foreach ($notFounds as $notFound) { $this->om->remove($notFound); } $this->om->flush(); }
php
{ "resource": "" }
q6580
PublicNodeVersions.getRef
train
public function getRef($nodeVersionId) { $this->initNodeVersions(); return isset($this->refs[$nodeVersionId]) ? $this->refs[$nodeVersionId] : null; }
php
{ "resource": "" }
q6581
PublicNodeVersions.getNodeRef
train
public function getNodeRef($nodeId, $lang = null) { $this->initNodeVersions(); $lang = $lang ?: $this->currentLocale->getCurrentLocale(); return isset($this->nodeRefs[$lang][$nodeId]) ? $this->nodeRefs[$lang][$nodeId] : null; }
php
{ "resource": "" }
q6582
Parser.read
train
public function read($filePath) { $this->rawEntries = array(); $this->currentEntry = $this->createNewEntryAsArray(); $this->state = null; $this->justNewEntry = false; $handle = $this->openFile($filePath); while (!feof($handle)) { $line = trim(fgets($handle)); $this->processLine($line); } fclose($handle); $this->addFinalEntry(); $this->prepareResults(); return $this->entriesAsArrays; }
php
{ "resource": "" }
q6583
Parser.prepareResults
train
protected function prepareResults() { $this->entriesAsArrays = array(); $this->entries = array(); $this->headers = array(); $counter = 0; foreach ($this->rawEntries as $entry) { $entry = $this->prepareEntry($entry, $counter); $id = $this->getMsgId($entry); $this->entriesAsArrays[$id] = $entry; $this->entries[$id] = new Entry($entry); $counter++; } return true; }
php
{ "resource": "" }
q6584
Parser.removeFuzzyFlagForMsgId
train
protected function removeFuzzyFlagForMsgId($msgid) { if (!isset($this->entriesAsArrays[$msgid])) { throw new \Exception('Entry does not exist'); } if ($this->entriesAsArrays[$msgid]['fuzzy']) { $flags = $this->entriesAsArrays[$msgid]['flags']; unset($flags[array_search('fuzzy', $flags, true)]); $this->entriesAsArrays[$msgid]['flags'] = $flags; $this->entriesAsArrays[$msgid]['fuzzy'] = false; } }
php
{ "resource": "" }
q6585
Parser.updateEntries
train
public function updateEntries($msgid, $translation) { if ( !isset($this->entriesAsArrays[$msgid]) || !is_array($translation) || sizeof($translation) != sizeof($this->entriesAsArrays[$msgid]['msgstr']) ) { throw new \Exception('Cannot update entry translation'); } $this->removeFuzzyFlagForMsgId($msgid); $this->entriesAsArrays[$msgid]['msgstr'] = $translation; }
php
{ "resource": "" }
q6586
Parser.updateEntry
train
public function updateEntry($msgid, $translation, $positionMsgstr = 0) { if ( !isset($this->entriesAsArrays[$msgid]) || !is_string($translation) || !isset($this->entriesAsArrays[$msgid]['msgstr'][$positionMsgstr]) ) { throw new \Exception('Cannot update entry translation'); } $this->removeFuzzyFlagForMsgId($msgid); $this->entriesAsArrays[$msgid]['msgstr'][$positionMsgstr] = $translation; }
php
{ "resource": "" }
q6587
AdminDatabaseInstall.manualMySql
train
public function manualMySql(Request $request) { $this->admControlInit($request, '/dashboard/db/all'); if ($this->v["uID"] == 1) { // && in_array($_SERVER["REMOTE_ADDR"], ['192.168.10.1'])) { $this->v["manualMySql"] = 'Connected successfully<br />'; $db = mysqli_connect(env('DB_HOST', 'localhost'), env('DB_USERNAME', 'homestead'), env('DB_PASSWORD', 'secret'), env('DB_DATABASE', 'homestead')); if ($db->connect_error) { $this->v["manualMySql"] = "Connection failed: " . $db->connect_error . '<br />'; } $this->v["lastSql"] = ''; $this->v["lastResults"] = []; if ($request->has('mys') && trim($request->mys) != '') { $this->v["lastSql"] = trim($request->mys); $this->v["manualMySql"] .= '<b>Statements submitted...</b><br />'; $statements = $GLOBALS["SL"]->mexplode(';', $request->mys); foreach ($statements as $sql) { $cnt = 0; if (trim($sql) != '') { ob_start(); $res = mysqli_query($db, $sql); $errorCatch = ob_get_contents(); ob_end_clean(); $this->v["lastResults"][$cnt][0] = $sql; $this->v["lastResults"][$cnt][1] = $errorCatch; if ($res->isNotEmpty()) { ob_start(); print_r($res); $this->v["lastResults"][$cnt][2] = ob_get_contents(); ob_end_clean(); } $cnt++; } } } mysqli_close($db); return view('vendor.survloop.admin.db.manualMySql', $this->v); } return $this->redir('/dashboard/db/export'); }
php
{ "resource": "" }
q6588
Metable.getOriginalMetaData
train
public function getOriginalMetaData(string $key, $default = null) { $meta = $this->accessMetableAttribute($this->getOriginal('meta')); return $meta->get($key, $default); }
php
{ "resource": "" }
q6589
Metable.getMetaData
train
public function getMetaData(string $key, $default = null) { $meta = $this->getAttribute('meta'); return $meta->get($key, $default); }
php
{ "resource": "" }
q6590
Metable.putMetaData
train
public function putMetaData($key, $value = null): void { $meta = $this->getAttribute('meta'); if (\is_array($key)) { foreach ($key as $name => $value) { $meta->put($name, $value); } } else { $meta->put($key, $value); } $this->setMetaAttribute($meta); }
php
{ "resource": "" }
q6591
Metable.forgetMetaData
train
public function forgetMetaData($key): void { $meta = $this->getAttribute('meta'); if (\is_array($key)) { foreach ($key as $name) { $meta->forget($name); } } else { $meta->forget($key); } $this->setMetaAttribute($meta); }
php
{ "resource": "" }
q6592
Metable.accessMetableAttribute
train
protected function accessMetableAttribute($value): Meta { $meta = []; if ($value instanceof Meta) { return $value; } elseif (! \is_null($value)) { $meta = $this->fromJson($value); } return new Meta($meta); }
php
{ "resource": "" }
q6593
TreeSurvNodeEdit.updateTreeOpts
train
public function updateTreeOpts($treeID = -3) { $treeRow = $GLOBALS["SL"]->treeRow; if ($treeID <= 0) { $treeID = $GLOBALS["SL"]->treeID; } else { $treeRow = SLTree::find($treeID); } if ($treeRow->TreeType == 'Page') { /* // auto-setting $skipConds = []; $testCond = SLConditions::where('CondTag', '#TestLink') ->where('CondDatabase', $treeRow->TreeDatabase) ->first(); if (!$testCond || !isset($testCond->CondID)) { $testCond = SLConditions::where('CondTag', '#TestLink') ->first(); } if ($testCond && isset($testCond->CondID)) $skipConds[] = $testCond->CondID; $chk = DB::select( DB::raw( "SELECT c.`CondNodeCondID`, n.`NodeID` FROM `SL_ConditionsNodes` c LEFT OUTER JOIN `SL_Node` n ON c.`CondNodeNodeID` LIKE n.`NodeID` WHERE n.`NodeTree` LIKE '" . $treeID . "'" . ((sizeof($skipConds) > 0) ? " AND c.`CondNodeCondID` NOT IN ('" . implode("', '", $skipConds) . "')" : "") ) ); if ($chk && sizeof($chk)) { if ($treeRow->TreeOpts%29 > 0) $treeRow->TreeOpts *= 29; } else { if ($treeRow->TreeOpts%29 == 0) $treeRow->TreeOpts = $treeRow->TreeOpts/29; } $treeRow->save(); */ } return true; }
php
{ "resource": "" }
q6594
Model.shard
train
static function shard($collector = null) { if (func_num_args()) { if ($collector) { static::$_shards[static::class] = $collector; } else { unset(static::$_shards[static::class]); } return; } if (!isset(static::$_shards[static::class])) { static::$_shards[static::class] = new Map(); } return static::$_shards[static::class]; }
php
{ "resource": "" }
q6595
Model.find
train
public static function find($options = []) { $options = Set::extend(static::query(), $options); $schema = static::definition(); return $schema->query(['query' => $options] + ['finders' => static::finders()]); }
php
{ "resource": "" }
q6596
Model.load
train
public static function load($id, $options = [], $fetchOptions = []) { $options = ['conditions' => [static::definition()->key() => $id]] + $options; return static::find($options)->first($fetchOptions); }
php
{ "resource": "" }
q6597
Model.reset
train
public static function reset() { unset(static::$_dependencies[static::class]); static::conventions(null); static::connection(null); static::definition(null); static::validator(null); static::query([]); unset(static::$_unicities[static::class]); unset(static::$_definitions[static::class]); unset(static::$_shards[static::class]); }
php
{ "resource": "" }
q6598
Model.fetch
train
public function fetch($name) { return $this->get($name, function($instance, $name) { $collection = [$instance]; $this->schema()->embed($collection, $name); return isset($this->_data[$name]) ? $this->_data[$name] : null; }); }
php
{ "resource": "" }
q6599
Model.sync
train
public function sync($data = false) { if ($this->_exists !== null) { return; } $id = $this->id(); if ($id !== null) { $persisted = static::load($id); if ($persisted && $data) { $this->amend($persisted->data(), ['exists' => true]); } else { $this->_exists = !!$persisted; } } else { $this->_exists = false; } }
php
{ "resource": "" }