_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9100 | MelisFrontSEODispatchRouterAbstractListener.getQueryParameters | train | public function getQueryParameters($e)
{
$request = $e->getRequest();
$getString = $request->getQuery()->toString();
if ($getString != '')
$getString = '?' . $getString;
return $getString;
} | php | {
"resource": ""
} |
q9101 | MelisFrontSEODispatchRouterAbstractListener.createTranslations | train | public function createTranslations($e, $siteFolder, $locale)
{
$sm = $e->getApplication()->getServiceManager();
$translator = $sm->get('translator');
$langFileTarget = $_SERVER['DOCUMENT_ROOT'] . '/../module/MelisSites/' .$siteFolder . '/language/' . $locale . '.php';
if (!file_exists($langFileTarget))
{
$langFileTarget = $_SERVER['DOCUMENT_ROOT'] . '/../module/MelisSites/' .$siteFolder . '/language/en_EN.php';
if (!file_exists($langFileTarget))
{
$langFileTarget = null;
}
}
else
{
$langFileTarget = null;
}
if (!is_null($langFileTarget) && !empty($siteFolder) && !empty($locale))
{
$translator->addTranslationFile(
'phparray',
$langFileTarget
);
}
} | php | {
"resource": ""
} |
q9102 | SshServerCompilerPass.createSshConnectionDefinition | train | private function createSshConnectionDefinition(
$sshId,
$serverName,
$directory,
$executable,
array $sshConfig
) {
$connectionDefinition = new Definition(
SshConnection::class, [
new Reference($sshId),
new Reference('input'),
new Reference('output'),
$serverName,
$directory,
$executable,
$sshConfig,
]
);
$connectionDefinition->setLazy(true);
return $connectionDefinition;
} | php | {
"resource": ""
} |
q9103 | SshServerCompilerPass.createCommandDefinition | train | private function createCommandDefinition($id, $connectionId, $class, $serverName, $command)
{
$commandDefinition = new DefinitionDecorator($id);
$commandDefinition->setClass($class);
$commandDefinition->setLazy(true);
$commandDefinition->replaceArgument(0, new Reference($connectionId));
$commandDefinition->addTag('nanbando.server_command', ['server' => $serverName, 'command' => $command]);
return $commandDefinition;
} | php | {
"resource": ""
} |
q9104 | Server.start | train | public function start()
{
try {
$this->createClientSocket();
$this->createWorkerJobSocket();
$this->createWorkerReplySocket();
$this->startWorkerPools();
$this->loop->addPeriodicTimer(5, [$this, 'monitorChildProcesses']);
$this->loop->addPeriodicTimer(10, [$this, 'monitorQueue']);
$this->loop->run();
} catch (ServerException $e) {
$errorMsgPattern = 'Server error: %s (%s:%d)';
$this->logger->emergency(sprintf($errorMsgPattern, $e->getMessage(), $e->getFile(), $e->getLine()));
}
} | php | {
"resource": ""
} |
q9105 | Server.stop | train | public function stop()
{
$this->stopWorkerPools();
$this->workerJobSocket->disconnect($this->config['sockets']['worker_job']);
$this->workerReplySocket->close();
$this->clientSocket->close();
$this->loop->stop();
} | php | {
"resource": ""
} |
q9106 | Server.createClientSocket | train | protected function createClientSocket()
{
/** @var Context|\ZMQContext $clientContext */
$clientContext = new Context($this->loop);
$this->clientSocket = $clientContext->getSocket(\ZMQ::SOCKET_ROUTER);
$this->clientSocket->bind($this->config['sockets']['client']);
$this->clientSocket->on('messages', [$this, 'onClientMessage']);
} | php | {
"resource": ""
} |
q9107 | Server.createWorkerJobSocket | train | protected function createWorkerJobSocket()
{
$workerJobContext = new \ZMQContext;
$this->workerJobSocket = $workerJobContext->getSocket(\ZMQ::SOCKET_PUB);
$this->workerJobSocket->bind($this->config['sockets']['worker_job']);
} | php | {
"resource": ""
} |
q9108 | Server.createWorkerReplySocket | train | protected function createWorkerReplySocket()
{
/** @var Context|\ZMQContext $workerReplyContext */
$workerReplyContext = new Context($this->loop);
$this->workerReplySocket = $workerReplyContext->getSocket(\ZMQ::SOCKET_REP);
$this->workerReplySocket->bind($this->config['sockets']['worker_reply']);
$this->workerReplySocket->on('message', [$this, 'onWorkerReplyMessage']);
} | php | {
"resource": ""
} |
q9109 | Server.onClientMessage | train | public function onClientMessage(array $message)
{
try {
$clientAddress = $message[0];
$data = json_decode($message[2], true);
if (empty($clientAddress) || empty($data) || !isset($data['action'])) {
throw new ServerException('Received malformed client message.');
}
switch ($data['action']) {
case 'command':
$this->handleCommand($clientAddress, $data['command']['name']);
break;
case 'job':
$this->handleJobRequest($clientAddress, $data['job']['name'], $data['job']['workload'], false);
break;
case 'background_job':
$this->handleJobRequest($clientAddress, $data['job']['name'], $data['job']['workload'], true);
break;
default:
$this->clientSocket->send('error: unknown action');
throw new ServerException('Received request for invalid action.');
}
} catch (ServerException $e) {
$errorMsgPattern = 'Client message error: %s (%s:%d)';
$this->logger->error(sprintf($errorMsgPattern, $e->getMessage(), $e->getFile(), $e->getLine()));
}
} | php | {
"resource": ""
} |
q9110 | Server.onWorkerReplyMessage | train | public function onWorkerReplyMessage(string $message)
{
try {
$data = json_decode($message, true);
if (empty($data) || !isset($data['request'])) {
throw new ServerException('Invalid worker request received.');
}
$result = null;
switch ($data['request']) {
case 'register_job':
$result = $this->registerJob($data['job_name'], $data['worker_id']);
break;
case 'unregister_job':
$result = $this->unregisterJob($data['job_name'], $data['worker_id']);
break;
case 'change_state':
$result = $this->changeWorkerState($data['worker_id'], $data['state']);
break;
case 'job_completed':
$this->onJobCompleted($data['worker_id'], $data['job_id'], $data['result']);
break;
}
$response = ($result === true) ? 'ok' : 'error';
$this->workerReplySocket->send($response);
} catch (ServerException $e) {
$errorMsgPattern = 'Worker message error: %s (%s:%d)';
$this->logger->error(sprintf($errorMsgPattern, $e->getMessage(), $e->getFile(), $e->getLine()));
}
} | php | {
"resource": ""
} |
q9111 | Server.onChildProcessExit | train | public function onChildProcessExit($exitCode, $termSignal)
{
$this->logger->error(sprintf('Child process exited. (Code: %d, Signal: %d)', $exitCode, $termSignal));
$this->monitorChildProcesses();
} | php | {
"resource": ""
} |
q9112 | Server.respondToClient | train | protected function respondToClient(string $address, string $payload = '')
{
try {
$clientSocket = $this->clientSocket->getWrappedSocket();
$clientSocket->send($address, \ZMQ::MODE_SNDMORE);
$clientSocket->send('', \ZMQ::MODE_SNDMORE);
$clientSocket->send($payload);
} catch (\ZMQException $e) {
$this->logger->error('Error respoding to client: ' . $e->getMessage());
}
} | php | {
"resource": ""
} |
q9113 | Server.registerJob | train | protected function registerJob(string $jobName, string $workerId) : bool
{
if (!isset($this->workerJobCapabilities[$workerId])) {
$this->workerJobCapabilities[$workerId] = [];
}
if (!in_array($jobName, $this->workerJobCapabilities[$workerId])) {
array_push($this->workerJobCapabilities[$workerId], $jobName);
}
return true;
} | php | {
"resource": ""
} |
q9114 | Server.unregisterJob | train | protected function unregisterJob(string $jobName, string $workerId) : bool
{
if (!isset($this->workerJobCapabilities[$jobName])) {
return true;
}
if (($key = array_search($workerId, $this->workerJobCapabilities[$jobName])) !== false) {
unset($this->workerJobCapabilities[$jobName][$key]);
}
if (empty($this->workerJobCapabilities[$jobName])) {
unset($this->workerJobCapabilities[$jobName]);
}
return true;
} | php | {
"resource": ""
} |
q9115 | Server.changeWorkerState | train | protected function changeWorkerState(string $workerId, int $workerState) : bool
{
$this->workerStates[$workerId] = $workerState;
if ($workerState === Worker::WORKER_STATE_IDLE) {
$this->pushJobs();
}
return true;
} | php | {
"resource": ""
} |
q9116 | Server.onJobCompleted | train | protected function onJobCompleted(string $workerId, string $jobId, string $result = '')
{
$jobType = $this->jobTypes[$jobId];
$clientAddress = $this->jobAddresses[$jobId];
if ($jobType === 'normal') {
$this->respondToClient($clientAddress, $result);
}
unset(
$this->jobTypes[$jobId],
$this->jobAddresses[$jobId],
$this->workerJobMap[$workerId]
);
} | php | {
"resource": ""
} |
q9117 | Server.handleCommand | train | protected function handleCommand(string $clientAddress, string $command) : bool
{
switch ($command) {
case 'stop':
$this->respondToClient($clientAddress, 'ok');
$this->stop();
return true;
case 'status':
$statusData = $this->getStatusData();
$this->respondToClient($clientAddress, json_encode($statusData));
return true;
case 'flush_queue':
$result = ($this->flushQueue() === true) ? 'ok' : 'error';
$this->respondToClient($clientAddress, $result);
return true;
}
$this->respondToClient($clientAddress, 'error');
throw new ServerException('Received unknown command.');
} | php | {
"resource": ""
} |
q9118 | Server.handleJobRequest | train | protected function handleJobRequest(
string $clientAddress,
string $jobName,
string $payload = '',
bool $backgroundJob = false
) : string {
$jobId = $this->addJobToQueue($jobName, $payload);
$this->jobTypes[$jobId] = ($backgroundJob === true) ? 'background' : 'normal';
$this->jobAddresses[$jobId] = $clientAddress;
$this->pushJobs();
if ($backgroundJob === true) {
$this->respondToClient($clientAddress, $jobId);
}
$this->totalJobRequests++;
return $jobId;
} | php | {
"resource": ""
} |
q9119 | Server.addJobToQueue | train | protected function addJobToQueue(string $jobName, string $payload = '') : string
{
if (!isset($this->jobQueues[$jobName])) {
$this->jobQueues[$jobName] = [];
}
$jobId = $this->getJobId();
array_push($this->jobQueues[$jobName], [
'job_id' => $jobId,
'payload' => $payload
]);
$this->jobsInQueue++;
return $jobId;
} | php | {
"resource": ""
} |
q9120 | Server.pushJobs | train | protected function pushJobs() : bool
{
// Skip if no jobs currently in queue
if (empty($this->jobQueues)) {
return true;
}
// Run trough list of (idle) workers and check if there is a job in queue the worker can handle
foreach ($this->workerStates as $workerId => $workerState) {
if ($workerState !== Worker::WORKER_STATE_IDLE) {
continue;
}
$jobData = $this->getJobFromQueue($workerId);
if (empty($jobData)) {
continue;
}
try {
$this->workerStats[$workerId]++;
$this->workerJobMap[$workerId] = $jobData['job_id'];
$this->workerJobSocket->send($jobData['job_name'], \ZMQ::MODE_SNDMORE);
$this->workerJobSocket->send($jobData['job_id'], \ZMQ::MODE_SNDMORE);
$this->workerJobSocket->send($workerId, \ZMQ::MODE_SNDMORE);
$this->workerJobSocket->send($jobData['payload']);
} catch (\ZMQException $e) {
$this->logger->error('Error sending job to worker: ' . $e->getMessage());
}
}
return true;
} | php | {
"resource": ""
} |
q9121 | Server.startWorkerPools | train | protected function startWorkerPools() : bool
{
if (empty($this->config['pool'])) {
throw new ServerException('No worker pool defined. Check config file.');
}
foreach ($this->config['pool'] as $poolName => $poolConfig) {
$this->startWorkerPool($poolName, $poolConfig);
}
return true;
} | php | {
"resource": ""
} |
q9122 | Server.startWorkerPool | train | protected function startWorkerPool(string $poolName, array $poolConfig)
{
if (!isset($poolConfig['worker_file'])) {
throw new ServerException('Path to worker file not set in pool config.');
}
$this->processes[$poolName] = [];
$processesToStart = $poolConfig['cp_start'] ?? 5;
for ($i = 0; $i < $processesToStart; $i++) {
// start child process:
try {
$process = $this->startChildProcess($poolConfig['worker_file']);
$this->registerChildProcess($process, $poolName);
} catch (\Exception $e) {
throw new ServerException('Could not start child process.');
}
}
} | php | {
"resource": ""
} |
q9123 | Server.stopWorkerPools | train | protected function stopWorkerPools() : bool
{
if (empty($this->processes)) {
return true;
}
foreach (array_keys($this->processes) as $poolName) {
$this->stopWorkerPool($poolName);
}
return true;
} | php | {
"resource": ""
} |
q9124 | Server.stopWorkerPool | train | protected function stopWorkerPool(string $poolName) : bool
{
if (empty($this->processes[$poolName])) {
return true;
}
foreach ($this->processes[$poolName] as $process) {
/** @var Process $process */
$process->terminate();
}
return true;
} | php | {
"resource": ""
} |
q9125 | Server.monitorPoolProcesses | train | protected function monitorPoolProcesses(string $poolName) : bool
{
if (empty($this->processes[$poolName])) {
return true;
}
/** @var Process $process */
foreach ($this->processes[$poolName] as $i => $process) {
$pid = $process->getPid();
$workerId = $this->config['server_id'] . '_' . $pid;
// check if process is still running:
if ($process->isRunning() === true) {
continue;
}
// if process is not running remove it from system:
$this->unregisterChildProcess($workerId);
unset($this->processes[$poolName][$i]);
// fire up a new process:
$workerFile = $this->config['pool'][$poolName]['worker_file'];
$process = $this->startChildProcess($workerFile);
$this->registerChildProcess($process, $poolName);
}
return true;
} | php | {
"resource": ""
} |
q9126 | Server.monitorQueue | train | public function monitorQueue() : bool
{
if ($this->jobsInQueue === 0) {
return true;
}
foreach (array_keys($this->jobQueues) as $jobName) {
if (empty($this->jobQueues[$jobName])) {
continue;
}
if ($this->jobCanBeProcessed($jobName)) {
continue;
}
$jobsCount = count($this->jobQueues[$jobName]);
$this->jobQueues[$jobName] = [];
$this->jobsInQueue -= $jobsCount;
}
return $this->pushJobs();
} | php | {
"resource": ""
} |
q9127 | Server.jobCanBeProcessed | train | protected function jobCanBeProcessed(string $jobName) : bool
{
foreach ($this->workerJobCapabilities as $workerId => $jobs) {
if (in_array($jobName, $jobs)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9128 | Server.getStatusData | train | protected function getStatusData() : array
{
$statusData = [
'version' => self::VERSION,
'starttime' => '',
'uptime' => '',
'active_worker' => [],
'job_info' => [],
];
$starttime = date('Y-m-d H:i:s', $this->startTime);
$start = new \DateTime($starttime);
$now = new \DateTime('now');
$uptime = $start->diff($now)->format('%ad %Hh %Im %Ss');
$statusData['starttime'] = $starttime;
$statusData['uptime'] = $uptime;
foreach (array_keys($this->processes) as $poolName) {
if (!isset($statusData['active_worker'][$poolName])) {
$statusData['active_worker'][$poolName] = 0;
}
/** @var Process $process */
foreach ($this->processes[$poolName] as $process) {
$processIsRunning = $process->isRunning();
if ($processIsRunning === true) {
$statusData['active_worker'][$poolName]++;
}
}
}
$statusData['job_info']['job_requests_total'] = $this->totalJobRequests;
$statusData['job_info']['queue_length'] = $this->jobsInQueue;
$statusData['job_info']['worker_stats'] = $this->workerStats;
return $statusData;
} | php | {
"resource": ""
} |
q9129 | Server.registerChildProcess | train | protected function registerChildProcess(Process $process, string $poolName) : bool
{
array_push($this->processes[$poolName], $process);
$workerPid = $process->getPid();
$workerId = $this->config['server_id'] . '_' . $workerPid;
$this->workerStates[$workerId] = Worker::WORKER_STATE_IDLE;
$this->workerStats[$workerId] = 0;
return true;
} | php | {
"resource": ""
} |
q9130 | Server.flushQueue | train | protected function flushQueue() : bool
{
foreach (array_keys($this->jobQueues) as $jobName) {
$this->jobQueues[$jobName] = [];
}
$this->jobsInQueue = 0;
return true;
} | php | {
"resource": ""
} |
q9131 | UninterpretedOption.addName | train | public function addName(\google\protobuf\UninterpretedOption\NamePart $value)
{
if ($this->name === null) {
$this->name = new \Protobuf\MessageCollection();
}
$this->name->add($value);
} | php | {
"resource": ""
} |
q9132 | UninterpretedOption.setStringValue | train | public function setStringValue($value = null)
{
if ($value !== null && ! $value instanceof \Protobuf\Stream) {
$value = \Protobuf\Stream::wrap($value);
}
$this->string_value = $value;
} | php | {
"resource": ""
} |
q9133 | MediaGalleryValueObserver.prepareAttributes | train | protected function prepareAttributes()
{
try {
// try to load the product SKU and map it the entity ID
$parentId= $this->getValue(ColumnKeys::IMAGE_PARENT_SKU, null, array($this, 'mapParentSku'));
} catch (\Exception $e) {
throw $this->wrapException(array(ColumnKeys::IMAGE_PARENT_SKU), $e);
}
// load the store ID
$storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);
// load the value ID and the position counter
$valueId = $this->getParentValueId();
$position = $this->raisePositionCounter();
// load the image label
$imageLabel = $this->getValue(ColumnKeys::IMAGE_LABEL);
// prepare the media gallery value
return $this->initializeEntity(
array(
MemberNames::VALUE_ID => $valueId,
MemberNames::STORE_ID => $storeId,
MemberNames::ENTITY_ID => $parentId,
MemberNames::LABEL => $imageLabel,
MemberNames::POSITION => $position,
MemberNames::DISABLED => 0
)
);
} | php | {
"resource": ""
} |
q9134 | AbstractRESTCall.getRequestData | train | protected function getRequestData()
{
if ($this->PWE->getHeader('content-type') != 'application/json') {
throw new HTTP4xxException("API requires 'application/json' as type for request body", HTTP4xxException::UNSUPPORTED_MEDIA_TYPE);
}
return json_decode(file_get_contents("php://input"), true);
} | php | {
"resource": ""
} |
q9135 | AbstractRESTCall.handleGet | train | protected function handleGet($item = null)
{
PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s", $item);
throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
} | php | {
"resource": ""
} |
q9136 | AbstractRESTCall.handlePut | train | protected function handlePut($item, $data)
{
PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s %s", $item, $data);
throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
} | php | {
"resource": ""
} |
q9137 | AbstractRESTCall.handlePost | train | protected function handlePost($data)
{
PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s", $data);
throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
} | php | {
"resource": ""
} |
q9138 | AbstractRESTCall.handleDelete | train | protected function handleDelete($item)
{
PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s", $item);
throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
} | php | {
"resource": ""
} |
q9139 | AbstractRESTCall.handlePatch | train | protected function handlePatch($item, $data)
{
PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s %s", $item, $data);
throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
} | php | {
"resource": ""
} |
q9140 | ShortcodeManager.init_shortcode | train | protected function init_shortcode( $tag ) {
$shortcode_class = $this->get_shortcode_class( $tag );
$shortcode_atts_parser = $this->get_shortcode_atts_parser_class( $tag );
$atts_parser = $this->instantiate(
ShortcodeAttsParserInterface::class,
$shortcode_atts_parser,
[ 'config' => $this->config->getSubConfig( $tag ) ]
);
$this->shortcodes[] = $this->instantiate(
ShortcodeInterface::class,
$shortcode_class,
[
'shortcode_tag' => $tag,
'config' => $this->config->getSubConfig( $tag ),
'atts_parser' => $atts_parser,
'dependencies' => $this->dependencies,
'view_builder' => $this->view_builder,
]
);
if ( $this->hasConfigKey( $tag, self::KEY_UI ) ) {
$this->init_shortcode_ui( $tag );
}
} | php | {
"resource": ""
} |
q9141 | ShortcodeManager.get_shortcode_class | train | protected function get_shortcode_class( $tag ) {
$shortcode_class = $this->hasConfigKey( $tag, self::KEY_CUSTOM_CLASS )
? $this->getConfigKey( $tag, self::KEY_CUSTOM_CLASS )
: self::DEFAULT_SHORTCODE;
return $shortcode_class;
} | php | {
"resource": ""
} |
q9142 | ShortcodeManager.get_shortcode_atts_parser_class | train | protected function get_shortcode_atts_parser_class( $tag ) {
$atts_parser = $this->hasConfigKey( $tag, self::KEY_CUSTOM_ATTS_PARSER )
? $this->getConfigKey( $tag, self::KEY_CUSTOM_ATTS_PARSER )
: self::DEFAULT_SHORTCODE_ATTS_PARSER;
return $atts_parser;
} | php | {
"resource": ""
} |
q9143 | ShortcodeManager.init_shortcode_ui | train | protected function init_shortcode_ui( $tag ) {
$shortcode_ui_class = $this->get_shortcode_ui_class( $tag );
$this->shortcode_uis[] = $this->instantiate(
ShortcodeUIInterface::class,
$shortcode_ui_class,
[
'shortcode_tag' => $tag,
'config' => $this->config->getSubConfig( $tag, self::KEY_UI ),
'dependencies' => $this->dependencies,
]
);
} | php | {
"resource": ""
} |
q9144 | ShortcodeManager.get_shortcode_ui_class | train | protected function get_shortcode_ui_class( $tag ) {
$ui_class = $this->hasConfigKey( $tag, self::KEY_CUSTOM_UI )
? $this->getConfigKey( $tag, self::KEY_CUSTOM_UI )
: self::DEFAULT_SHORTCODE_UI;
return $ui_class;
} | php | {
"resource": ""
} |
q9145 | ShortcodeManager.register | train | public function register( $context = null ) {
$this->init_shortcodes();
$context = $this->validate_context( $context );
$context['page_template'] = $this->get_page_template();
array_walk( $this->shortcodes,
function ( ShortcodeInterface $shortcode ) use ( $context ) {
$shortcode->register( $context );
} );
// This hook only gets fired when Shortcode UI plugin is active.
\add_action(
'register_shortcode_ui',
[ $this, 'register_shortcode_ui', ]
);
} | php | {
"resource": ""
} |
q9146 | ShortcodeManager.register_shortcode_ui | train | public function register_shortcode_ui() {
$template = $this->get_page_template();
$context = [ 'page_template' => $template ];
array_walk( $this->shortcode_uis,
function ( ShortcodeUIInterface $shortcode_ui ) use ( $context ) {
$shortcode_ui->register( $context );
}
);
} | php | {
"resource": ""
} |
q9147 | ShortcodeManager.do_tag | train | public function do_tag( $tag, array $atts = [], $content = null ) {
return \BrightNucleus\Shortcode\do_tag( $tag, $atts, $content );
} | php | {
"resource": ""
} |
q9148 | ShortcodeManager.instantiate | train | protected function instantiate( $interface, $class, array $args ) {
try {
if ( is_callable( $class ) ) {
$class = call_user_func_array( $class, $args );
}
if ( is_string( $class ) ) {
if ( null !== $this->injector ) {
$class = $this->injector->make( $class, $args );
} else {
$class = $this->instantiateClass( $class, $args );
}
}
} catch ( Exception $exception ) {
throw FailedToInstantiateObject::fromFactory(
$class,
$interface,
$exception
);
}
if ( ! is_subclass_of( $class, $interface ) ) {
throw FailedToInstantiateObject::fromInvalidObject(
$class,
$interface
);
}
return $class;
} | php | {
"resource": ""
} |
q9149 | BaseOperatorVisitor.parseNode | train | public function parseNode($query, $node)
{
if ($node instanceof Nodes\KeyNode) {
return $this->parseKey($node->getValue());
}
if ($node instanceof Nodes\ValueNode) {
return $this->parseValue($node->getValue());
}
if ($node instanceof Nodes\FunctionNode) {
// .. ?
$f = $this->getBuilder()->getFunctions()->first(function ($item, $key) use ($node) {
$class = $item->getNode();
return $node instanceof $class;
});
if (!$f) {
throw new \Railken\SQ\Exceptions\QuerySyntaxException();
}
$childs = new Collection();
foreach ($node->getChildren() as $child) {
$childs[] = $this->parseNode($query, $child);
}
$childs = $childs->map(function ($v) use ($query) {
if ($v instanceof \Illuminate\Database\Query\Expression) {
return $v->getValue();
}
$query->addBinding($v, 'where');
return '?';
});
return DB::raw($f->getName().'('.$childs->implode(',').')');
}
} | php | {
"resource": ""
} |
q9150 | BaseOperatorVisitor.parseKey | train | public function parseKey($key)
{
$keys = explode('.', $key);
$keys = [implode(".", array_slice($keys, 0, -1)), $keys[count($keys) - 1]];
$key = (new Collection($keys))->map(function ($part) {
return '`'.$part.'`';
})->implode('.');
return DB::raw($key);
} | php | {
"resource": ""
} |
q9151 | ModesManager.prepareDataBits | train | private function prepareDataBits()
{
$n = $this->structureAppendN;
$m = $this->structureAppendM;
$parity = $this->structureAppendParity;
$originalData = $this->structureAppendOriginalData;
$dataCounter = 0;
if ( $this->checkStructureAppend($n, $m) )
{
$dataValue[0] = 3;
$dataBits[0] = 4;
$dataValue[1] = $m - 1;
$dataBits[1] = 4;
$dataValue[2] = $n - 1;
$dataBits[2] = 4;
$originalDataLength = strlen($originalData);
if ( $originalDataLength > 1 )
{
$parity = 0;
$i = 0;
while ($i < $originalDataLength)
{
$parity = ($parity ^ ord(substr($originalData, $i, 1)));
$i++;
}
}
$dataValue[3] = $parity;
$dataBits[3] = 8;
$dataCounter = 4;
}
$dataBits[$dataCounter] = 4;
return $dataBits;
} | php | {
"resource": ""
} |
q9152 | ModesManager.getModeName | train | public function getModeName()
{
return $this->isNumericData()
? self::NUMERIC_MODE
: ( $this->isAlphaNumericData()
? self::ALPHA_NUMERIC_MODE
: self::EIGHT_BITS_MODE
);
} | php | {
"resource": ""
} |
q9153 | ModesManager.switchMode | train | private function switchMode()
{
switch ( $this->getModeName() )
{
case self::NUMERIC_MODE:
return new NumericMode;
case self::ALPHA_NUMERIC_MODE:
return new AlphanumericMode;
case self::EIGHT_BITS_MODE:
default:
return new EightBitMode;
}
} | php | {
"resource": ""
} |
q9154 | LoggerFactory.create | train | public function create() : LoggerInterface
{
$loggerType = $this->config['type'] ?? 'null';
switch ($loggerType) {
case 'file':
return new Logger($this->config['path'], $this->config['level']);
case 'null':
return new NullLogger;
default:
throw new \RuntimeException('Invalid logger type');
}
} | php | {
"resource": ""
} |
q9155 | taoSimpleDelivery_models_classes_DeliveryCompiler.compile | train | public function compile() {
$test = $this->getResource()->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_DELIVERYCONTENT_TEST));
if (is_null($test)) {
throw new EmptyDeliveryException($this->getResource());
}
return $this->subCompile($test);
} | php | {
"resource": ""
} |
q9156 | Client.parseCookies | train | protected function parseCookies ()
{
$cookie = '';
foreach( $this->cookies as $name => $value )
$cookie .= $name . '=' . $value . '; ';
return rtrim( $cookie, ';' );
} | php | {
"resource": ""
} |
q9157 | Client.getSoapVariables | train | public function getSoapVariables($requestObject, $lowerCaseFirst = false, $keepNullProperties = true)
{
if (!is_object($requestObject)) {
throw new InvalidParameterException('Parameter requestObject is not an object');
}
$objectName = $this->getClassNameWithoutNamespaces($requestObject);
if ($lowerCaseFirst) {
$objectName = lcfirst($objectName);
}
$stdClass = new \stdClass();
$stdClass->$objectName = $requestObject;
return $this->objectToArray($stdClass, $keepNullProperties);
} | php | {
"resource": ""
} |
q9158 | Client.logCurlMessage | train | protected function logCurlMessage($message, \DateTime $messageTimestamp)
{
if (!$this->debugLogFilePath) {
throw new \RuntimeException('Debug log file path not defined.');
}
$logMessage = '[' . $messageTimestamp->format('Y-m-d H:i:s') . "] ----------------------------------------------------------\n" . $message . "\n\n";
$logHandle = fopen($this->debugLogFilePath, 'a+');
fwrite($logHandle, $logMessage);
fclose($logHandle);
} | php | {
"resource": ""
} |
q9159 | Base64Converter.convert | train | public function convert() {
$resource = $file = \tao_helpers_Http::getUploadedFile('content');
$base64Converter = new Base64ConverterModel($resource);
$this -> returnJson($base64Converter->convertToBase64());
} | php | {
"resource": ""
} |
q9160 | FatalThread.emulateFatal | train | public function emulateFatal()
{
if ($this->isExternal()) {
$obj = null;
$obj->callOnNull();
} else {
$this->callOnChild(__FUNCTION__, func_get_args());
}
} | php | {
"resource": ""
} |
q9161 | FatalThread.emulateExceptionOnRemoteLoop | train | public function emulateExceptionOnRemoteLoop()
{
if ($this->isExternal()) {
$this->loop->nextTick(function () {
$this->emulateException();
});
} else {
$this->callOnChild(__FUNCTION__, func_get_args());
}
} | php | {
"resource": ""
} |
q9162 | FatalThread.emulateFatalOnRemoteLoop | train | public function emulateFatalOnRemoteLoop()
{
if ($this->isExternal()) {
$this->loop->nextTick(function () {
$this->emulateFatal();
});
} else {
$this->callOnChild(__FUNCTION__, func_get_args());
}
} | php | {
"resource": ""
} |
q9163 | ModelAdminController.getTrashed | train | public function getTrashed()
{
if (!$this->modelAdmin->hasSoftDeleting()) {
return $this->missingMethod();
}
return view('flare::admin.modeladmin.trashed', [
'modelItems' => $this->modelAdmin->onlyTrashedItems(),
'totals' => $this->modelAdmin->totals(),
]
);
} | php | {
"resource": ""
} |
q9164 | ModelAdminController.getAll | train | public function getAll()
{
if (!$this->modelAdmin->hasSoftDeleting()) {
return $this->missingMethod();
}
return view('flare::admin.modeladmin.all', [
'modelItems' => $this->modelAdmin->allItems(),
'totals' => $this->modelAdmin->totals(),
]
);
} | php | {
"resource": ""
} |
q9165 | ModelAdminController.postCreate | train | public function postCreate(ModelCreateRequest $request)
{
if (!$this->modelAdmin->hasCreating()) {
return $this->missingMethod();
}
$this->modelAdmin->create();
return redirect($this->modelAdmin->currentUrl())->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'The '.$this->modelAdmin->getTitle().' was successfully created.', 'dismissable' => false]]);
} | php | {
"resource": ""
} |
q9166 | ModelAdminController.getView | train | public function getView($modelitemId)
{
if (!$this->modelAdmin->hasViewing()) {
return $this->missingMethod();
}
$this->modelAdmin->find($modelitemId);
event(new ModelView($this->modelAdmin));
return view('flare::admin.modeladmin.view', ['modelItem' => $this->modelAdmin->model]);
} | php | {
"resource": ""
} |
q9167 | ModelAdminController.getEdit | train | public function getEdit($modelitemId)
{
if (!$this->modelAdmin->hasEditing()) {
return $this->missingMethod();
}
$this->modelAdmin->find($modelitemId);
return view('flare::admin.modeladmin.edit', ['modelItem' => $this->modelAdmin->model]);
} | php | {
"resource": ""
} |
q9168 | ModelAdminController.postEdit | train | public function postEdit(ModelEditRequest $request, $modelitemId)
{
if (!$this->modelAdmin->hasEditing()) {
return $this->missingMethod();
}
$this->modelAdmin->edit($modelitemId);
return redirect($this->modelAdmin->currentUrl())->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'The '.$this->modelAdmin->getTitle().' was successfully updated.', 'dismissable' => false]]);
} | php | {
"resource": ""
} |
q9169 | ModelAdminController.getDelete | train | public function getDelete($modelitemId)
{
if (!$this->modelAdmin->hasDeleting()) {
return $this->missingMethod();
}
if ($this->modelAdmin->hasSoftDeleting()) {
$this->modelAdmin->findWithTrashed($modelitemId);
} else {
$this->modelAdmin->find($modelitemId);
}
return view('flare::admin.modeladmin.delete', ['modelItem' => $this->modelAdmin->model]);
} | php | {
"resource": ""
} |
q9170 | ModelAdminController.postDelete | train | public function postDelete($modelitemId)
{
if (!$this->modelAdmin->hasDeleting()) {
return $this->missingMethod();
}
$this->modelAdmin->delete($modelitemId);
return redirect($this->modelAdmin->currentUrl())->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'The '.$this->modelAdmin->getTitle().' was successfully removed.', 'dismissable' => false]]);
} | php | {
"resource": ""
} |
q9171 | ModelAdminController.getRestore | train | public function getRestore($modelitemId)
{
if (!$this->modelAdmin->hasSoftDeleting()) {
return $this->missingMethod();
}
return view('flare::admin.modeladmin.restore', ['modelItem' => $this->modelAdmin->model]);
} | php | {
"resource": ""
} |
q9172 | ModelAdminController.postRestore | train | public function postRestore($modelitemId)
{
if (!$this->modelAdmin->hasSoftDeleting()) {
return $this->missingMethod();
}
$this->modelAdmin->restore($modelitemId);
return redirect($this->modelAdmin->currentUrl())->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'The '.$this->modelAdmin->getTitle().' was successfully restored.', 'dismissable' => false]]);
} | php | {
"resource": ""
} |
q9173 | ModelAdminController.getClone | train | public function getClone($modelitemId)
{
if (!$this->modelAdmin->hasCloning()) {
return $this->missingMethod();
}
$this->modelAdmin->clone($modelitemId);
return redirect($this->modelAdmin->currentUrl())->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'The '.$this->modelAdmin->getTitle().' was successfully cloned.', 'dismissable' => false]]);
} | php | {
"resource": ""
} |
q9174 | Impersonator.start | train | public function start(Impersonatable $impersonater, Impersonatable $impersonated)
{
$this->checkImpersonation($impersonater, $impersonated);
try {
session()->put($this->getSessionKey(), $impersonater->getAuthIdentifier());
$this->auth()->silentLogout();
$this->auth()->silentLogin($impersonated);
$this->events()->dispatch(
new Events\ImpersonationStarted($impersonater, $impersonated)
);
return true;
}
catch (\Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q9175 | Impersonator.stop | train | public function stop()
{
try {
$impersonated = $this->auth()->user();
$impersonater = $this->findUserById($this->getImpersonatorId());
$this->auth()->silentLogout();
$this->auth()->silentLogin($impersonater);
$this->clear();
$this->events()->dispatch(
new Events\ImpersonationStopped($impersonater, $impersonated)
);
return true;
}
catch (\Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q9176 | Impersonator.checkImpersonation | train | private function checkImpersonation(Impersonatable $impersonater, Impersonatable $impersonated)
{
$this->mustBeEnabled();
$this->mustBeDifferentImpersonatable($impersonater, $impersonated);
$this->checkImpersonater($impersonater);
$this->checkImpersonated($impersonated);
} | php | {
"resource": ""
} |
q9177 | Impersonator.mustBeDifferentImpersonatable | train | private function mustBeDifferentImpersonatable(Impersonatable $impersonater, Impersonatable $impersonated)
{
if ($impersonater->getAuthIdentifier() == $impersonated->getAuthIdentifier())
throw new Exceptions\ImpersonationException(
'The impersonater & impersonated with must be different.'
);
} | php | {
"resource": ""
} |
q9178 | UserService.searchUser | train | public function searchUser($searchTerm, $page = 1, $limit = 10)
{
$total = $this->userRepository->countNumberOfUserInSearch($searchTerm);
$users = $this->userRepository->searchUsers($searchTerm, $page, $limit);
$results = [];
foreach ($users as $user) {
$results[] = $user->listView();
}
return new PageModel($results, $page, $total, $limit, 'users');
} | php | {
"resource": ""
} |
q9179 | UserService.registerUser | train | public function registerUser(BaseUser $user, $source = self::SOURCE_TYPE_WEBSITE)
{
$user->setRoles(["ROLE_USER"])
->setSource($source)
->setEnabled(true);
$this->saveUserWithPlainPassword($user);
$this->dispatcher->dispatch(self::REGISTER_EVENT, new UserEvent($user));
return $user;
} | php | {
"resource": ""
} |
q9180 | UserService.saveUserForResetPassword | train | public function saveUserForResetPassword(BaseUser $user)
{
$user->setForgetPasswordToken(null)
->setForgetPasswordExpired(null);
$this->saveUserWithPlainPassword($user);
} | php | {
"resource": ""
} |
q9181 | UserService.updateUserRefreshToken | train | public function updateUserRefreshToken(BaseUser $user)
{
if (!$user->isRefreshTokenValid()) {
$user->setRefreshToken(bin2hex(random_bytes(90)));
}
$expirationDate = new \DateTime();
$expirationDate->modify('+' . $this->refreshTokenTTL . ' seconds');
$user->setRefreshTokenExpire($expirationDate);
$this->save($user);
return $user;
} | php | {
"resource": ""
} |
q9182 | Email.create | train | public static function create()
{
$email = new static();
$email->from(Yii::$app->params['mandrill']['from_name'], Yii::$app->params['mandrill']['from_email']);
return $email;
} | php | {
"resource": ""
} |
q9183 | Email.from | train | public function from($name, $email)
{
$this->from_email = $email;
$this->from_name = $name;
return $this;
} | php | {
"resource": ""
} |
q9184 | Email.send | train | public function send()
{
if (!$this->validate()) {
return $this->getErrors();
}
foreach ($this->multipleRecipients as $to) {
$email_copy = clone $this;
if (is_array($to)) {
$email_copy->to_email = $to['email'];
$email_copy->to_name = $to['name'];
} else {
$email_copy->to_email = $to;
$email_copy->to_name = '';
}
$email_copy->save(false);
}
return true;
} | php | {
"resource": ""
} |
q9185 | Email.sendEmail | train | public function sendEmail()
{
$mandrill = new Mandrill(Yii::$app->params['mandrill']['key']);
$message = [
'html' => $this->html,
'text' => $this->text,
'subject' => $this->subject,
'from_email' => $this->from_email,
'from_name' => $this->from_name,
'track_opens' => true,
'track_clicks' => true,
'auto_text' => true,
'to' => [['email' => $this->to_email, 'name' => $this->to_name]],
'bcc_address' => 'mihai.petrescu@gmail.com',
];
$result = $mandrill->messages->send($message);
if ($result[0]['status'] == 'sent') {
$this->status = 'sent';
} else {
$this->tries++;
}
$this->save();
} | php | {
"resource": ""
} |
q9186 | Event.haltQueue | train | public function haltQueue($early = false)
{
if ($early) {
$this->haltedQueueEarly = true;
}
$this->haltedQueue = true;
return $this;
} | php | {
"resource": ""
} |
q9187 | Searchable.getElasticaFields | train | public function getElasticaFields() {
$db = \DataObject::database_fields(get_class($this->owner));
$fields = $this->owner->searchableFields();
$result = new \ArrayObject();
foreach ($fields as $name => $params) {
$type = null;
$spec = array();
if (array_key_exists($name, $db)) {
$class = $db[$name];
if (($pos = strpos($class, '('))) {
$class = substr($class, 0, $pos);
}
if (array_key_exists($class, self::$mappings)) {
$spec['type'] = self::$mappings[$class];
}
}
$result[$name] = $spec;
}
$result['LastEdited'] = array('type' => 'date');
$result['Created'] = array('type' => 'date');
$result['ID'] = array('type' => 'integer');
$result['ParentID'] = array('type' => 'integer');
$result['Sort'] = array('type' => 'integer');
$result['Name'] = array('type' => 'string');
$result['MenuTitle'] = array('type' => 'string');
$result['ShowInSearch'] = array('type' => 'integer');
$result['ClassName'] = array('type' => 'string');
$result['ClassNameHierarchy'] = array('type' => 'string');
$result['SS_Stage'] = array('type' => 'keyword');
$result['PublicView'] = array('type' => 'boolean');
if ($this->owner->hasExtension('Hierarchy') || $this->owner->hasField('ParentID')) {
$result['ParentsHierarchy'] = array('type' => 'long',);
}
// fix up dates
foreach ($result as $field => $spec) {
if (isset($spec['type']) && ($spec['type'] == 'date')) {
$spec['format'] = 'yyyy-MM-dd HH:mm:ss';
$result[$field] = $spec;
}
}
if (isset($result['Content']) && count($result['Content'])) {
$spec = $result['Content'];
$spec['store'] = false;
$result['Content'] = $spec;
}
$this->owner->invokeWithExtensions('updateElasticMappings', $result);
return $result->getArrayCopy();
} | php | {
"resource": ""
} |
q9188 | Searchable.onAfterWrite | train | public function onAfterWrite() {
if (\Config::inst()->get('ElasticSearch', 'disabled') || !$this->owner->autoIndex()) {
return;
}
$stage = \Versioned::current_stage();
$this->service->index($this->owner, $stage);
} | php | {
"resource": ""
} |
q9189 | Searchable.onAfterDelete | train | public function onAfterDelete() {
if (\Config::inst()->get('ElasticSearch', 'disabled')) {
return;
}
$stage = \Versioned::current_stage();
$this->service->remove($this->owner, $stage);
} | php | {
"resource": ""
} |
q9190 | UsersController.massUpdate | train | public function massUpdate(UsersRequest $request, User $users)
{
$this->authorize('otherUpdate', User::class);
$data = $request->except('_token', 'updated_at', 'image', 'submit');
$users = $users->whereIn('id', $data['users']);
$messages = [];
switch ($data['mass_action']) {
case 'mass_activate':
// if (! $users->update(['approve' => 1])) {
// $messages[] = '!mass_activate';
// }
break;
case 'mass_lock':
// if (! $users->update(['approve' => 0])) {
// $messages[] = '!mass_lock';
// }
break;
case 'mass_delete':
$usersTemp = $users->get();
foreach ($usersTemp as $user) {
if (! $user->delete()) {
$messages[] = '!mass_delete';
}
}
break;
case 'mass_delete_inactive':
// if (! $users->update(['on_mainpage' => 1])) {
// $messages[] = '!mass_delete_inactive';
// }
break;
}
$message = empty($messages) ? 'msg.complete' : 'msg.complete_but_null';
return $this->makeRedirect(true, 'admin.users.index', $message);
} | php | {
"resource": ""
} |
q9191 | EloquentTranslation.allToArray | train | public function allToArray($locale, $group, $namespace = null)
{
$args = func_get_args();
$args[] = config('app.locale');
return $this->executeCallback(static::class, __FUNCTION__, $args, function () use ($locale, $group) {
$array = DB::table('translations')
->select(DB::raw("JSON_UNQUOTE(JSON_EXTRACT(`translation`, '$.".$locale."')) AS translation"), 'key')
->where('group', $group)
->pluck('translation', 'key')
->all();
return $array;
});
} | php | {
"resource": ""
} |
q9192 | PluginWrapper.setInstance | train | public function setInstance(PluginInstance $instance)
{
$this->instance = $instance;
$this->pluginInstanceId = $instance->getInstanceId();
} | php | {
"resource": ""
} |
q9193 | TagController.actionList | train | public function actionList($type, $term)
{
$tags = Tag::find()->where('type = :type AND LOWER(name) LIKE :term AND status<>"deleted"', [':type' => $type, ':term' => '%' . strtolower($term) . '%'])->all();
$response = [];
foreach($tags as $tag) {
$response[] = ["id" => $tag->id, "label" => $tag->name, "value" => $tag->name];
}
Yii::$app->response->format = 'json';
return $response;
} | php | {
"resource": ""
} |
q9194 | QuoteProvider.setFilename | train | protected function setFilename($filename) {
if (false === realpath($filename)) {
throw new FileNotFoundException(sprintf("The file \"%s\" was not found", $filename));
}
$this->filename = realpath($filename);
return $this;
} | php | {
"resource": ""
} |
q9195 | Route.match | train | public function match(string $uri): bool
{
if ($this->uri == $uri) {
return true;
}
$pattern = '/^' . $this->regex . '$/';
return !is_null($this->regex) && preg_match($pattern, $uri);
} | php | {
"resource": ""
} |
q9196 | Route.getArguments | train | public function getArguments(string $uri, $callback = null): array
{
$values = [];
$pattern = '/^' . $this->regex . '$/';
preg_match_all($pattern, $uri, $matches);
$matchCount = count($matches);
for ($i = 1; $i < $matchCount; ++$i) {
$values[] = (!is_null($callback))
? (new Callback($callback))->execute($matches[$i][0])
: $matches[$i][0];
}
$arguments = [];
$i = 0;
foreach ($this->parameters as $parameter) {
$arguments[$parameter] = $values[$i];
++$i;
}
return $arguments;
} | php | {
"resource": ""
} |
q9197 | ResultList.getDataObjects | train | public function getDataObjects($limit = 0, $start = 0) {
$pagination = \PaginatedList::create($this->toArrayList())
->setPageLength($limit)
->setPageStart($start)
->setTotalItems($this->getTotalResults())
->setLimitItems(false);
return $pagination;
} | php | {
"resource": ""
} |
q9198 | ApiGuard.onAuthenticationFailure | train | public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$this->dispatcher->dispatch(self::API_GUARD_FAILED, new AuthFailedEvent($request, $exception));
return $this->removeAuthCookieFromResponse(new Response('Authentication Failed', Response::HTTP_FORBIDDEN));
} | php | {
"resource": ""
} |
q9199 | AbstractCall.setClient | train | public function setClient(ClientInterface $client = null): self
{
if (null === $client) {
$this->client = new Client();
return $this;
}
$this->client = $client;
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.