_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q8900
Bindings.replace
train
private function replace($bindings) { $search = array_keys($bindings); $replace = array_values($bindings); foreach ($search as $key => &$value) { $value = $this->delimiters[0].$value.$this->delimiters[1]; } array_walk_recursive($this->rules, function(&$value, $key) use($search, $replace) { $value = str_ireplace($search, $replace, $value); }); }
php
{ "resource": "" }
q8901
Worker.registerJob
train
public function registerJob(string $jobName, callable $callback) : bool { $this->callbacks[$jobName] = $callback; $this->jobSocket->subscribe($jobName); // register job at server: $this->replySocket->send(json_encode([ 'request' => 'register_job', 'worker_id' => $this->workerId, 'job_name' => $jobName ])); $response = $this->replySocket->recv(); return ($response === 'ok'); }
php
{ "resource": "" }
q8902
Worker.createJobSocket
train
protected function createJobSocket() { /** @var Context|\ZMQContext $jobContext */ $jobContext = new Context($this->loop); $this->jobSocket = $jobContext->getSocket(\ZMQ::SOCKET_SUB); $this->jobSocket->connect($this->config['sockets']['worker_job']); $this->jobSocket->on('messages', [$this, 'onJobMessage']); }
php
{ "resource": "" }
q8903
Worker.createReplySocket
train
protected function createReplySocket() { $replyContext = new \ZMQContext; $this->replySocket = $replyContext->getSocket(\ZMQ::SOCKET_REQ); $this->replySocket->connect($this->config['sockets']['worker_reply']); }
php
{ "resource": "" }
q8904
Worker.onJobMessage
train
public function onJobMessage(array $message) : bool { $jobName = $message[0]; $jobId = $message[1]; $workerId = $message[2]; $payload = $message[3]; // Skip if job is assigned to another worker: if ($workerId !== $this->workerId) { return false; } // Skip if worker can not handle the requested job if (!isset($this->callbacks[$jobName])) { throw new WorkerException('No callback found for requested job.'); } // Switch to busy state handle job and switch back to idle state: $this->jobId = $jobId; $this->setState(Worker::WORKER_STATE_BUSY); $result = call_user_func($this->callbacks[$jobName], $payload); $this->onJobCompleted($result); $this->setState(Worker::WORKER_STATE_IDLE); return true; }
php
{ "resource": "" }
q8905
Worker.setState
train
protected function setState(int $state) : bool { $this->workerState = $state; // report idle state to server: $this->replySocket->send(json_encode([ 'request' => 'change_state', 'worker_id' => $this->workerId, 'state' => $this->workerState ])); $response = $this->replySocket->recv(); return ($response === 'ok'); }
php
{ "resource": "" }
q8906
Worker.onJobCompleted
train
protected function onJobCompleted(string $result) : bool { $this->replySocket->send(json_encode([ 'request' => 'job_completed', 'worker_id' => $this->workerId, 'job_id' => $this->jobId, 'result' => $result ])); $response = $this->replySocket->recv(); $this->jobId = null; return ($response === 'ok'); }
php
{ "resource": "" }
q8907
Worker.loadConfig
train
protected function loadConfig() { $options = getopt('c:'); if (!isset($options['c'])) { throw new WorkerException('No path to configuration provided.'); } $pathToConfig = $options['c']; if (!file_exists($pathToConfig)) { throw new WorkerException('Config file not found.'); } $this->config = require $pathToConfig; }
php
{ "resource": "" }
q8908
Worker.run
train
public function run() { try { $this->loop->run(); } catch (WorkerException $e) { $this->logger->error('Worker Error: ' . $e->getMessage()); } }
php
{ "resource": "" }
q8909
UserSessionResource.handleGET
train
protected function handleGET() { $serviceName = $this->getOAuthServiceName(); if (!empty($serviceName)) { /** @type BaseOAuthService $service */ $service = ServiceManager::getService($serviceName); $serviceGroup = $service->getServiceTypeInfo()->getGroup(); if ($serviceGroup !== ServiceTypeGroups::OAUTH) { throw new BadRequestException('Invalid login service provided. Please use an OAuth service.'); } return $service->handleLogin($this->request->getDriver()); } return Session::getPublicInfo(); }
php
{ "resource": "" }
q8910
UserSessionResource.handlePOST
train
protected function handlePOST() { $serviceName = $this->getOAuthServiceName(); if (empty($serviceName)) { $credentials = [ 'email' => $this->getPayloadData('email'), 'username' => $this->getPayloadData('username'), 'password' => $this->getPayloadData('password'), 'is_sys_admin' => false ]; return $this->handleLogin($credentials, boolval($this->getPayloadData('remember_me'))); } /** @type ADLdap $service */ $service = ServiceManager::getService($serviceName); $serviceGroup = $service->getServiceTypeInfo()->getGroup(); switch ($serviceGroup) { case ServiceTypeGroups::LDAP: if ( config('df.enable_windows_auth', false) === true && $service->getServiceTypeInfo()->getName() === 'adldap' ) { // get windows authenticated user $username = array_get($_SERVER, 'LOGON_USER', array_get($_SERVER, 'REMOTE_USER')); if (!empty($username)) { return $service->handleWindowsAuth($username); } } $credentials = [ 'username' => $this->getPayloadData('username'), 'password' => $this->getPayloadData('password') ]; return $service->handleLogin($credentials, $this->getPayloadData('remember_me')); case ServiceTypeGroups::OAUTH: $oauthCallback = $this->request->getParameterAsBool('oauth_callback'); /** @type BaseOAuthService $service */ if (!empty($oauthCallback)) { return $service->handleOAuthCallback(); } else { return $service->handleLogin($this->request->getDriver()); } default: throw new BadRequestException('Invalid login service provided. Please use an OAuth or AD/Ldap service.'); } }
php
{ "resource": "" }
q8911
UserSessionResource.getOAuthServiceName
train
protected function getOAuthServiceName() { $serviceName = $this->getPayloadData('service', $this->request->getParameter('service')); if (empty($serviceName)) { $state = $this->getPayloadData('state', $this->request->getParameter('state')); if (empty($state)) { $state = $this->getPayloadData('oauth_token', $this->request->getParameter('oauth_token')); } if (!empty($state)) { $key = BaseOAuthService::CACHE_KEY_PREFIX . $state; $serviceName = \Cache::pull($key); } } return $serviceName; }
php
{ "resource": "" }
q8912
UserSessionResource.handleLogin
train
protected function handleLogin(array $credentials = [], $remember = false) { $loginAttribute = strtolower(config('df.login_attribute', 'email')); if ($loginAttribute === 'username') { $username = array_get($credentials, 'username'); if (empty($username)) { throw new BadRequestException('Login request is missing required username.'); } unset($credentials['email']); } else { $email = array_get($credentials, 'email'); if (empty($email)) { throw new BadRequestException('Login request is missing required email.'); } unset($credentials['username']); } $password = array_get($credentials, 'password'); if (empty($password)) { throw new BadRequestException('Login request is missing required password.'); } $credentials['is_active'] = 1; // if user management not available then only system admins can login. if (!class_exists('\DreamFactory\Core\User\Resources\System\User')) { $credentials['is_sys_admin'] = 1; } if (Session::authenticate($credentials, $remember, true, $this->getAppId())) { return Session::getPublicInfo(); } else { throw new UnauthorizedException('Invalid credentials supplied.'); } }
php
{ "resource": "" }
q8913
Module.prepareMiniTemplateConfig
train
public function prepareMiniTemplateConfig() { $pluginsFormat = array(); $userSites = $_SERVER['DOCUMENT_ROOT'] . '/../module/MelisSites'; if(file_exists($userSites) && is_dir($userSites)) { $sites = $this->getDir($userSites); if(!empty($sites)){ foreach($sites as $key => $val) { //public site folder $publicFolder = $userSites . DIRECTORY_SEPARATOR . $val . DIRECTORY_SEPARATOR . 'public'; //mini template image folder // $imgFolder = $publicFolder . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR . 'miniTemplate'; //get the mini template folder path $miniTplPath = $publicFolder . DIRECTORY_SEPARATOR . 'miniTemplatesTinyMce'; //check if directory is available if(file_exists($miniTplPath) && is_dir($miniTplPath)) { //get the plugin config format $pluginsConfig = include __DIR__ . '/../config/plugins/MiniTemplatePlugin.config.php'; if(!empty($pluginsConfig)) { //get all the mini template $tpls = array_diff(scandir($miniTplPath), array('..', '.')); if (!empty($tpls)) { //set the site name as sub category title $pluginsConfig['melis']['subcategory']['title'] = $val; //set the id of the plugin $pluginsConfig['melis']['subcategory']['id'] = $pluginsConfig['melis']['subcategory']['id'] . '_' . $val; //get the content of the mini template foreach ($tpls as $k => $v) { //remove the file extension from the filename $name = pathinfo($v, PATHINFO_FILENAME); //create a plugin post name $postName = $k . strtolower($name); //prepare the content of the mini template $content = $miniTplPath . DIRECTORY_SEPARATOR . $v; //set the default layout for the plugin based on mini template $pluginsConfig['front']['default'] = file_get_contents($content); //set the plugin name using the template name $pluginsConfig['melis']['name'] = $name; //include the mini tpl plugin config $pluginsFormat['plugins']['MelisMiniTemplate']['plugins']['MiniTemplatePlugin_' . $postName] = $pluginsConfig; } } } } } } } return $pluginsFormat; }
php
{ "resource": "" }
q8914
PresetListener.extend
train
private function extend(array $backup) { $preset = $this->presetStore->getPreset($this->application, $this->version, $this->options); return array_merge($preset, $backup); }
php
{ "resource": "" }
q8915
Database.prepareWhere
train
public function prepareWhere($whereObject) { $where = null; $params = []; if (!empty($whereObject)) { $arr = []; /** @var \Dframe\Database\Chunk\ChunkInterface $chunk */ foreach ($whereObject as $chunk) { list($wSQL, $wParams) = $chunk->build(); $arr[] = $wSQL; foreach ($wParams as $k => $v) { $params[] = $v; } } $this->setWhere = ' WHERE ' . implode(' AND ', $arr); if (is_array($this->setParams) and !empty($this->setParams)) { $this->setParams = array_merge($this->setParams, $params); } else { $this->setParams = $params; } } else { $this->setWhere = null; //$this->setParams = []; } //if (!empty($order)) // $this->prepareOrder($order, $sort); // return $this; }
php
{ "resource": "" }
q8916
Database.prepareHaving
train
public function prepareHaving($havingObject) { $where = null; $params = []; if (!empty($havingObject)) { $arr = []; /** @var \Dframe\Database\Chunk\ChunkInterface $chunk */ foreach ($havingObject as $chunk) { list($wSQL, $wParams) = $chunk->build(); $arr[] = $wSQL; foreach ($wParams as $k => $v) { $params[] = $v; } } $this->setHaving = ' HAVING ' . implode(' AND ', $arr); if (is_array($this->setParams) and !empty($this->setParams)) { $this->setParams = array_merge($this->setParams, $params); } else { $this->setParams = $params; } } else { $this->setHaving = null; //$this->setParams = []; } //if (!empty($order)) // $this->prepareOrder($order, $sort); // return $this; }
php
{ "resource": "" }
q8917
Database.prepareOrder
train
public function prepareOrder($order = null, $sort = null) { if ($order == null or $sort == null) { $this->setOrderBy = ''; return $this; } if (!in_array($sort, ['ASC', 'DESC'])) { $sort = 'DESC'; } $this->setOrderBy = ' ORDER BY ' . $order . ' ' . $sort; return $this; }
php
{ "resource": "" }
q8918
Database.prepareQuery
train
public function prepareQuery($query, $params = false) { if (isset($params) and is_array($params)) { $this->prepareParms($params); } if (!isset($this->setQuery)) { $this->setQuery = $query . ' '; } else { $this->setQuery .= $this->getQuery() . ' ' . $query . ' '; } return $this; }
php
{ "resource": "" }
q8919
Database.prepareParms
train
public function prepareParms($params) { if (is_array($params)) { foreach ($params as $key => $value) { array_push($this->setParams, $value); } } else { array_push($this->setParams, $params); } }
php
{ "resource": "" }
q8920
Database.getQuery
train
public function getQuery() { $sql = $this->setQuery; $sql .= $this->getWhere(); $sql .= $this->getGroupBy(); $sql .= $this->getOrderBy(); $sql .= $this->getHaving(); $sql .= $this->getLimit(); $this->setQuery = null; $this->setWhere = null; $this->setHaving = null; $this->setOrderBy = null; $this->setGroupBy = null; $this->setLimit = null; return str_replace(' ', ' ', $sql); }
php
{ "resource": "" }
q8921
Database.getWhere
train
public function getWhere() { if (!isset($this->setWhere) or empty($this->setWhere)) { $this->setWhere = null; } return $this->setWhere; }
php
{ "resource": "" }
q8922
Database.getHaving
train
public function getHaving() { if (!isset($this->setHaving) or empty($this->setHaving)) { $this->setHaving = null; } return $this->setHaving; }
php
{ "resource": "" }
q8923
Database.prepareLimit
train
public function prepareLimit($limit, $offset = null) { if ($offset) { $this->setLimit = ' LIMIT ' . $limit . ', ' . $offset . ''; } else { $this->setLimit = ' LIMIT ' . $limit . ''; } return $this; }
php
{ "resource": "" }
q8924
ProductMediaGalleryRepository.findOneByAttributeIdAndValue
train
public function findOneByAttributeIdAndValue($attributeId, $value) { // initialize the params $params = array( MemberNames::ATTRIBUTE_ID => $attributeId, MemberNames::VALUE => $value ); // load and return the prodcut media gallery with the passed attribute ID + value $this->productMediaGalleryStmt->execute($params); return $this->productMediaGalleryStmt->fetch(\PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q8925
WebformWithOverride.preRenderWebformElement
train
public static function preRenderWebformElement($element) { $webform = ($element['#webform'] instanceof WebformInterface) ? $element['#webform'] : WebformEntity::load($element['#webform']); if (!$webform) { return $element; } if ($webform->access('submission_create')) { $values = []; // Set data. $values['data'] = $element['#default_data']; // Set source entity type and id. if (!empty($element['#entity']) && $element['#entity'] instanceof EntityInterface) { $values['entity_type'] = $element['#entity']->getEntityTypeId(); $values['entity_id'] = $element['#entity']->id(); } elseif (!empty($element['#entity_type']) && !empty($element['#entity_id'])) { $values['entity_type'] = $element['#entity_type']; $values['entity_id'] = $element['#entity_id']; } if (!empty($element['#override'])) { $new_settings = $element['#override']; $webform->setSettingsOverride($new_settings); $values['strawberryfield:override'] = $new_settings; } // Build the webform. $element['webform_build'] = $webform->getSubmissionForm($values); // Set custom form action. if (!empty($element['#action'])) { $element['webform_build']['#action'] = $element['#action']; } } elseif ($webform->getSetting('form_access_denied') !== WebformInterface::ACCESS_DENIED_DEFAULT) { // Set access denied message. $element['webform_access_denied'] = static::buildAccessDenied($webform); } else { // Add config and webform to cache contexts. $config = \Drupal::configFactory()->get('webform.settings'); $renderer = \Drupal::service('renderer'); $renderer->addCacheableDependency($element, $config); $renderer->addCacheableDependency($element, $webform); } return $element; }
php
{ "resource": "" }
q8926
MinifyAssetsService.generateAllAssets
train
public function generateAllAssets ($files, $sitePath, $siteName, $isFromVendor) { $cssMinifier = new Minify\CSS(); $jsMinifier = new Minify\JS(); if($isFromVendor){ $bundleDir = $sitePath.'/public/'; /** * we need to remove the site name on the path * since the site name is already included * in the file name inside the assets.config */ $sitePath = dirname($sitePath); }else{ $bundleDir = $sitePath.'/'.$siteName.'/public/'; } $messages = array(); //check if the directory for the bundle is exist if($this->checkDir($bundleDir)) { //check if bundle is writable if (is_writable($bundleDir)) { if (!empty($files)) { foreach ($files as $key => $file) { //create a bundle for js $key = strtolower($key); if ($key == 'js') { $messages['error'] = $this->createBundleFile($jsMinifier, 'bundle.js', $file, $sitePath, $bundleDir); } //create a bundle for css if ($key == 'css') { $messages['error'] = $this->createBundleFile($cssMinifier, 'bundle.css', $file, $sitePath, $bundleDir, false); } } } }else { $messages['error'] = array('message' => $bundleDir . ' is not writable.', 'success' => false); } }else{ $messages['error'] = array('message' => $bundleDir . ' does not exist.', 'success' => false); } return $messages; }
php
{ "resource": "" }
q8927
MinifyAssetsService.createBundleFile
train
private function createBundleFile ($minifier, $fileName, $files, $sitePath, $bundleDir, $cleanCode = true) { $translator = $this->getServiceLocator()->get('translator'); $message = ''; $success = false; if (!empty($files)) { try { foreach ($files as $key => $file) { //remove comments if($cleanCode) { $codeToAdd = $this->removeComments($sitePath . $file); }else{ $codeToAdd = $sitePath . $file; } //add the file to minify later $minifier->add($codeToAdd); // $minifier = $this->getFileContentsViaCurl($minifier, $file); } //minify all the files $minifier->minify($bundleDir . $fileName); $message = $translator->translate('tr_front_minify_assets_compiled_successfully'); $success = true; } catch (\Exception $ex) { /** * this will occur only if the bundle.css or bundle.js * is not writable or no permission or other errors */ $message = wordwrap($ex->getMessage(), 20, "\n", true); } }else{ $success = true; } return array( 'message' => $message, 'success' => $success ); }
php
{ "resource": "" }
q8928
MinifyAssetsController.minifyAssetsAction
train
public function minifyAssetsAction () { $request = $this->getRequest(); $siteID = $request->getPost('siteId'); /** @var \MelisFront\Service\MinifyAssetsService $minifyAssets */ $minifyAssets = $this->getServiceLocator()->get('MinifyAssets'); $result = $minifyAssets->minifyAssets($siteID); $title = 'Compiling assets'; /** * modify a little the result */ $success = true; $message = ''; if(!empty($result['results'])){ foreach($result['results'] as $key => $val){ if(!$val['success']){ $success = false; $message = $val['message']; } } } return new JsonModel(array( 'title' => $title, 'message' => wordwrap($message, 20, "\n", true), 'success' => $success, )); }
php
{ "resource": "" }
q8929
EventManagerTrait.mergeEventListeners
train
public function mergeEventListeners($eventListeners) { if ($eventListeners instanceof EventManagerInterface) { $eventListeners = $eventListeners->getEventListeners(); } foreach (((array) $eventListeners) as $eventName => $listeners) { $queue = []; if (isset($this->eventListeners[$eventName])) { $innerListeners = clone $this->eventListeners[$eventName]; $innerListeners->setExtractFlags(ListenerQueue::EXTR_DATA); foreach ($innerListeners as $callback) { $queue[] = $callback; } } $listeners = clone $listeners; $listeners->setExtractFlags(ListenerQueue::EXTR_BOTH); foreach ($listeners as $listener) { if (!in_array($listener['data'], $queue)) { $this->attach($eventName, $listener['data'], $listener['priority']); } } } return true; }
php
{ "resource": "" }
q8930
EventManagerTrait.attach
train
public function attach($event, $callback, $priority = 0) { if (!isset($this->eventListeners[$event])) { $this->clearListeners($event); } $this->eventListeners[$event]->insert($callback, $priority); return true; }
php
{ "resource": "" }
q8931
EventManagerTrait.detach
train
public function detach($event, $callback) { if (!isset($this->eventListeners[$event]) || $this->eventListeners[$event]->isEmpty()) { return false; } $removed = false; $listeners = $this->eventListeners[$event]; $newListeners = new ListenerQueue(); $listeners->setExtractFlags(ListenerQueue::EXTR_BOTH); foreach ($listeners as $item) { if ($item['data'] === $callback) { $removed = true; continue; } $newListeners->insert($item['data'], $item['priority']); } $listeners->setExtractFlags(ListenerQueue::EXTR_DATA); $this->eventListeners[$event] = $newListeners; return $removed; }
php
{ "resource": "" }
q8932
Request.toXML
train
public function toXML() { $namespace = 'tns'; $writer = new XMLWriter(); $writer->openMemory(); $writer->setIndent(true); $writer->setIndentString(' '); $writer->startElementNs($namespace, $this->getRequestName(), 'http://www.apis-it.hr/fin/2012/types/f73'); $writer->writeAttribute('Id', uniqid()); $writer->startElementNs($namespace, 'Zaglavlje', null); $writer->writeElementNs($namespace, 'IdPoruke', null, $this->generateUUID()); $writer->writeElementNs($namespace, 'DatumVrijeme', null, $this->generateDateTime()); $writer->endElement(); $writer->writeRaw($this->getRequest()->toXML()); $writer->endElement(); return $writer->outputMemory(); }
php
{ "resource": "" }
q8933
EnumDescriptorProto.addValue
train
public function addValue(\google\protobuf\EnumValueDescriptorProto $value) { if ($this->value === null) { $this->value = new \Protobuf\MessageCollection(); } $this->value->add($value); }
php
{ "resource": "" }
q8934
Shortcode.register
train
public function register( $context = null ) { if ( null !== $context ) { $this->add_context( $context ); } if ( ! $this->is_needed( $this->context ) ) { return; } \add_shortcode( $this->get_tag(), [ $this, 'render' ] ); }
php
{ "resource": "" }
q8935
Shortcode.render
train
public function render( $atts, $content = null, $tag = null ) { $atts = $this->atts_parser->parse_atts( $atts, $this->get_tag() ); $this->enqueue_dependencies( $this->get_dependency_handles(), $atts ); return $this->render_view( $this->get_view(), $this->context, $atts, $content ); }
php
{ "resource": "" }
q8936
Shortcode.enqueue_dependencies
train
protected function enqueue_dependencies( $handles, $context = null ) { if ( null !== $context ) { $this->add_context( $context ); } if ( ! $this->dependencies || count( $handles ) < 1 ) { return; } foreach ( $handles as $handle ) { $found = $this->dependencies->enqueue_handle( $handle, $this->context, true ); if ( ! $found ) { $message = sprintf( __( 'Could not enqueue dependency "%1$s" for shortcode "%2$s".', 'bn-shortcodes' ), $handle, $this->get_tag() ); trigger_error( $message, E_USER_WARNING ); } } }
php
{ "resource": "" }
q8937
Shortcode.do_this
train
public function do_this( array $atts = [ ], $content = null ) { return \BrightNucleus\Shortcode\do_tag( $this->get_tag(), $atts, $content ); }
php
{ "resource": "" }
q8938
MediaGalleryObserver.prepareProductMediaGalleryAttributes
train
protected function prepareProductMediaGalleryAttributes() { // load the attribute ID of the media gallery EAV attribute $mediaGalleryAttribute = $this->getEavAttributeByAttributeCode(MediaGalleryObserver::ATTRIBUTE_CODE); $attributeId = $mediaGalleryAttribute[MemberNames::ATTRIBUTE_ID]; // initialize the gallery data $disabled = 0; $mediaType = 'image'; $image = $this->getValue(ColumnKeys::IMAGE_PATH_NEW); // initialize and return the entity return $this->initializeEntity( array( MemberNames::ATTRIBUTE_ID => $attributeId, MemberNames::VALUE => $image, MemberNames::MEDIA_TYPE => $mediaType, MemberNames::DISABLED => $disabled ) ); }
php
{ "resource": "" }
q8939
MediaGalleryObserver.prepareProductMediaGalleryValueToEntityAttributes
train
protected function prepareProductMediaGalleryValueToEntityAttributes() { // initialize and return the entity return $this->initializeEntity( array( MemberNames::VALUE_ID => $this->valueId, MemberNames::ENTITY_ID => $this->parentId ) ); }
php
{ "resource": "" }
q8940
ValidatorChain.getValidator
train
public function getValidator($alias) { if (array_key_exists($alias, $this->validators)) { return $this->validators[$alias]; } throw new JbFileUploaderException('Unknown validator ' . $alias); }
php
{ "resource": "" }
q8941
MaintenanceClient.Alarm
train
public function Alarm(AlarmRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/etcdserverpb.Maintenance/Alarm', $argument, ['\Etcdserverpb\AlarmResponse', 'decode'], $metadata, $options); }
php
{ "resource": "" }
q8942
MaintenanceClient.Status
train
public function Status(StatusRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/etcdserverpb.Maintenance/Status', $argument, ['\Etcdserverpb\StatusResponse', 'decode'], $metadata, $options); }
php
{ "resource": "" }
q8943
MaintenanceClient.Defragment
train
public function Defragment(DefragmentRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/etcdserverpb.Maintenance/Defragment', $argument, ['\Etcdserverpb\DefragmentResponse', 'decode'], $metadata, $options); }
php
{ "resource": "" }
q8944
MaintenanceClient.Hash
train
public function Hash(HashRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/etcdserverpb.Maintenance/Hash', $argument, ['\Etcdserverpb\HashResponse', 'decode'], $metadata, $options); }
php
{ "resource": "" }
q8945
MaintenanceClient.Snapshot
train
public function Snapshot(SnapshotRequest $argument, $metadata = [], $options = []) { return $this->_serverStreamRequest('/etcdserverpb.Maintenance/Snapshot', $argument, ['\Etcdserverpb\SnapshotResponse', 'decode'], $metadata, $options); }
php
{ "resource": "" }
q8946
InstallerServiceProvider.registerRedirection
train
protected function registerRedirection(): void { if (! empty($this->redirectAfterInstalled) && \is_string($this->redirectAfterInstalled)) { Installation::$redirectAfterInstalled = $this->redirectAfterInstalled; } }
php
{ "resource": "" }
q8947
InstallerServiceProvider.addDefaultSpecifications
train
protected function addDefaultSpecifications(RequirementContract $requirement) { return $requirement->add(new Specifications\WritableStorage($this->app)) ->add(new Specifications\WritableBootstrapCache($this->app)) ->add(new Specifications\WritableAsset($this->app)) ->add(new Specifications\DatabaseConnection($this->app)) ->add(new Specifications\Authentication($this->app)); }
php
{ "resource": "" }
q8948
Authentication.retrieveResetToken
train
public function retrieveResetToken($token) { return $this->queryBuilder->from($this->getTokenTable()) ->where('token', $token) ->first(); }
php
{ "resource": "" }
q8949
Authentication.deleteToken
train
public function deleteToken($token) { return $this->queryBuilder->from($this->getTokenTable()) ->where('token', $token) ->delete(); }
php
{ "resource": "" }
q8950
Authentication.registerToken
train
public function registerToken(\Globalis\PuppetSkilled\Database\Magic\Model $user) { $this->queryBuilder->from($this->getTokenTable()) ->insert([ 'user_id' => $user->getKey(), 'token' => ($token = $this->generateResetToken()), 'created_at' => new Carbon(), ]); return $token; }
php
{ "resource": "" }
q8951
Connection.getConfig
train
public function getConfig($key = null, $default = null) { $name = $this->current ?: 'default'; $configs = $this->configs[$name]; if ($key === null) { return $configs; } return isset($configs[$key]) ? $configs[$key] : $default; }
php
{ "resource": "" }
q8952
Connection.getOption
train
public function getOption($key = null, $default = null) { $name = $this->current ?: 'default'; $options = isset($this->configs[$name]['options']) ? $this->configs[$name]['options'] : []; if ($key === null) { return $options; } return isset($options[$key]) ? $options[$key] : $default; }
php
{ "resource": "" }
q8953
Connection.addConnection
train
public function addConnection($name, $dsn, $username = null, $password = null, $options = []) { //default driver options static $defaultOptions = array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, //PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ); if (isset($options['prefix'])) { $prefix = $options['prefix']; unset($options['prefix']); } else { $prefix = ''; } $this->configs[$name] = [ 'dsn' => $dsn, 'username' => $username, 'password' => $password, 'prefix' => $prefix, 'options' => $options + $defaultOptions, ]; return $this; }
php
{ "resource": "" }
q8954
Connection.quoteIdentifier
train
public function quoteIdentifier($name) { $quote = null; switch ($this->getAttribute(\PDO::ATTR_DRIVER_NAME)) { case 'pgsql': case 'sqlsrv': case 'dblib': case 'mssql': case 'sybase': $quote = '"'; break; case 'mysql': case 'sqlite': case 'sqlite2': default: $quote = '`'; } $parts = explode('.', $name); foreach ($parts as $k => $part) { if ($part !== '*') { $parts[$k] = $quote . $part . $quote; } } return implode('.', $parts); }
php
{ "resource": "" }
q8955
Client.writeClientInit
train
public function writeClientInit($compression = false, $ssl = false) { // MMM dd yyyy HH:mm:ss $date = date('M d Y H:i:s'); $data = array( 'MsgType' => 'ClientInit', 'ClientDate' => $date, 'ClientVersion' => 'clue/quassel-react alpha' ); if ($this->protocol->isLegacy()) { $data += array( 'ProtocolVersion' => 10, 'UseCompression' => (bool)$compression, 'UseSsl' => (bool)$ssl ); } return $this->write($data); }
php
{ "resource": "" }
q8956
Client.writeCoreSetupData
train
public function writeCoreSetupData($user, $password, $backend = 'SQLite', $properties = array()) { return $this->write(array( 'MsgType' => 'CoreSetupData', 'SetupData' => array( 'AdminUser' => (string)$user, 'AdminPasswd' => (string)$password, 'Backend' => (string)$backend, 'ConnectionProperties' => $properties ) )); }
php
{ "resource": "" }
q8957
Client.writeHeartBeatRequest
train
public function writeHeartBeatRequest(\DateTime $dt = null) { if ($dt === null) { $dt = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true))); } return $this->write(array( Protocol::REQUEST_HEARTBEAT, $dt )); }
php
{ "resource": "" }
q8958
Client.writeBufferRequestBacklogAll
train
public function writeBufferRequestBacklogAll($messageIdFirst, $messageIdLast, $maxAmount, $additional) { return $this->write(array( Protocol::REQUEST_SYNC, "BacklogManager", "", "requestBacklogAll", new QVariant((int)$messageIdFirst, 'MsgId'), new QVariant((int)$messageIdLast, 'MsgId'), (int)$maxAmount, (int)$additional )); }
php
{ "resource": "" }
q8959
Client.write
train
public function write($data) { return $this->stream->write( $this->splitter->writePacket( $this->protocol->serializeVariantPacket($data) ) ); }
php
{ "resource": "" }
q8960
Pipeline.execute
train
public function execute() { $groups = array(); $results = array(); $currentOperation = null; $currentGroup = array(); foreach ($this->commands as $command) { if ($currentOperation !== $command[0]) { $groups[] = array($currentOperation, $currentGroup); $currentOperation = $command[0]; $currentGroup = array(); } if ($currentOperation === 'get') { $currentGroup[] = $command[1]; } else { $currentGroup[$command[1]] = $command[2]; } } $groups[] = array($currentOperation, $currentGroup); array_shift($groups); foreach ($groups as $group) { list($op, $args) = $group; if ($op === 'set') { $result = $this->backend->setMulti($args, $this->ttl); $results = array_merge($results, array_fill(0, count($args), $result)); } else { $results = array_merge($results, $this->backend->getMulti($args)); } } $this->commands = array(); return $results; }
php
{ "resource": "" }
q8961
ReconfigureCommand.rebuild
train
protected function rebuild(InputInterface $input, OutputInterface $output) { $puli = new Puli(Path::join([getcwd(), NANBANDO_DIR])); $puli->start(); /** @var EmbeddedComposerInterface $embeddedComposer */ $embeddedComposer = $this->getApplication()->getEmbeddedComposer(); $packageManager = $puli->getPackageManager(); $io = new ConsoleIO($input, $output, $this->getApplication()->getHelperSet()); $composer = $embeddedComposer->createComposer($io); $installationManager = $composer->getInstallationManager(); $rootPackage = $composer->getPackage(); $repository = $composer->getRepositoryManager()->getLocalRepository(); $packages = []; foreach ($repository->getPackages() as $package) { $packages[$package->getName()] = $package; } foreach ($rootPackage->getRequires() as $require) { if (!array_key_exists($require->getTarget(), $packages)) { continue; } $packageManager->installPackage( Path::normalize($installationManager->getInstallPath($packages[$require->getTarget()])), $require->getTarget(), 'nanbando' ); } $filesystem = new Filesystem(); $filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, '.puli'])); $discoveryManager = $puli->getDiscoveryManager(); if (!$discoveryManager->hasRootTypeDescriptor('nanbando/bundle')) { $discoveryManager->addRootTypeDescriptor(new BindingTypeDescriptor(new BindingType('nanbando/bundle')), 0); } $discoveryManager->clearDiscovery(); $discoveryManager->buildDiscovery(); $filesystem = new Filesystem(); $filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, 'app', 'cache'])); }
php
{ "resource": "" }
q8962
ExtLipsum._getParagraph
train
private function _getParagraph($first = false) { $words = $this->_dictionary; shuffle($words); if ($first) { $pre = array('lorem', 'ipsum'); $words = array_merge($pre, $words); } $nbrWordsPerParagraph = $this->_nbrWordsPerParagraph + mt_rand(-20, 20); $nbrWordsPerSentence = $this->_nbrWordsPerSentence + mt_rand(-8, 8); $words = array_slice($words, 0, $nbrWordsPerParagraph); $sentences = array_chunk($words, $nbrWordsPerSentence); $result = array(); foreach ($sentences as &$sentence) { $this->_punctuate($sentence); $result[] = ucfirst(implode(' ', $sentence)); } return ('<p>' . implode(' ', $result) . '</p>'); }
php
{ "resource": "" }
q8963
ExtLipsum._numberOfCommas
train
private function _numberOfCommas($len) { $avg = (float)log($len, 6); $stdDev = (float)($avg / 6.000); return ((int)round($this->_gauss($avg, $stdDev))); }
php
{ "resource": "" }
q8964
HtmlMaker.get
train
public function get($name) { if(isset($this->global_vars[$name])) { return $this->global_vars[$name]; } return null; }
php
{ "resource": "" }
q8965
Frontmatter.parseLines
train
public function parseLines() { $text = []; while (($line = $this->nextLine()) !== false) { $line = rtrim($line); // Skip empty lines if ($line == "") { $text[] = null; continue; } // Look at start of line to detect valid blocktypes $blockTypes = []; $marker = $line[0]; if (isset($this->blockTypes[$marker])) { foreach ($this->blockTypes[$marker] as $blockType) { $blockTypes[] = $blockType; } } // Check if line is matching a detected blocktype foreach ($blockTypes as $blockType) { if ($this->{"block".$blockType}($line)) { continue; } } } $text = implode("\n", $this->lines); return [ "text" => $text, "frontmatter" => $this->frontmatter, ]; }
php
{ "resource": "" }
q8966
Frontmatter.currentLine
train
public function currentLine() { return isset($this->lines[$this->lineNumber - 1]) ? $this->lines[$this->lineNumber - 1] : false; }
php
{ "resource": "" }
q8967
Frontmatter.blockInclude
train
protected function blockInclude($line) { if ($this->config["include"] && preg_match("/^#include[ \t]([\w.]+)$/", $line, $matches) ) { $file = $this->config["include_base"]."/".$matches[1]; if (!is_readable($file)) { throw new Exception("Could not find include file: '$file'"); } $include = file_get_contents($file); $include = str_replace(array("\r\n", "\r"), "\n", $include); $include = explode("\n", $include); array_splice( $this->lines, $this->lineNumber - 1, 1, $include ); $this->lineNumber--; return true; } }
php
{ "resource": "" }
q8968
Frontmatter.blockYamlFrontmatter
train
protected function blockYamlFrontmatter($line) { if ($this->config["frontmatter_yaml"] && strlen($line) === 3 && $line[2] === "-" && $line[1] === "-" ) { $startLineNumber = $this->lineNumber; // Detect end of block and move it to frontmatter while (($line = $this->nextLine()) !== false) { $line = rtrim($line); // Block ends with --- or ... if (strlen($line) === 3 && ( ($line[2] === "-" && $line[1] === "-" && $line[0] === "-") || ($line[2] === "." && $line[1] === "." && $line[0] === ".") ) ) { $linesRemoved = $this->lineNumber + 1 - $startLineNumber; $this->linesRemoved += $linesRemoved; $frontmatter = array_splice( $this->lines, $startLineNumber - 1, $linesRemoved ); unset($frontmatter[$linesRemoved - 1]); unset($frontmatter[0]); $this->addYamlFrontmatter($frontmatter); $this->lineNumber = $startLineNumber - 1; return true; } } if ($this->currentLine() === false) { throw new Exception("Start of YAML detected at line: $startLineNumber but no end of block detected."); } } }
php
{ "resource": "" }
q8969
Frontmatter.addYamlFrontmatter
train
protected function addYamlFrontmatter($lines) { $text = implode("\n", $lines); $parsed = $this->parseYaml($text); if (!is_array($parsed)) { $parsed = [$parsed]; } $this->frontmatter = array_merge($this->frontmatter, $parsed); }
php
{ "resource": "" }
q8970
Frontmatter.parseYaml
train
protected function parseYaml($text) { if ($this->config["yaml_parser_pecl"] && function_exists("yaml_parse") ) { // PECL php5-yaml extension $parsed = yaml_parse($text); if ($parsed === false) { throw new Exception("Failed parsing YAML frontmatter using PECL."); } return $parsed; } if ($this->config["yaml_parser_symfony"] && method_exists("Symfony\Component\Yaml\Yaml", "parse") ) { // symfony/yaml $parsed = Yaml::parse($text); return $parsed; } if ($this->config["yaml_parser_spyc"] && function_exists("spyc_load") ) { // mustangostang/spyc $parsed = spyc_load($text); return $parsed; } throw new Exception("Could not find support for YAML."); }
php
{ "resource": "" }
q8971
Frontmatter.addJsonFrontmatter
train
protected function addJsonFrontmatter($lines) { if (!function_exists("json_decode")) { throw new Exception("Missing JSON support, perhaps install JSON module with PHP."); } $text = implode("\n", $lines); $parsed = json_decode($text."\n", true); if (is_null($parsed)) { throw new Exception("Failed parsing JSON frontmatter."); } if (!is_array($parsed)) { $parsed = [$parsed]; } $this->frontmatter = array_merge($this->frontmatter, $parsed); }
php
{ "resource": "" }
q8972
DescriptorProto.addField
train
public function addField(\google\protobuf\FieldDescriptorProto $value) { if ($this->field === null) { $this->field = new \Protobuf\MessageCollection(); } $this->field->add($value); }
php
{ "resource": "" }
q8973
DescriptorProto.addNestedType
train
public function addNestedType(\google\protobuf\DescriptorProto $value) { if ($this->nested_type === null) { $this->nested_type = new \Protobuf\MessageCollection(); } $this->nested_type->add($value); }
php
{ "resource": "" }
q8974
DescriptorProto.addExtensionRange
train
public function addExtensionRange(\google\protobuf\DescriptorProto\ExtensionRange $value) { if ($this->extension_range === null) { $this->extension_range = new \Protobuf\MessageCollection(); } $this->extension_range->add($value); }
php
{ "resource": "" }
q8975
DescriptorProto.addOneofDecl
train
public function addOneofDecl(\google\protobuf\OneofDescriptorProto $value) { if ($this->oneof_decl === null) { $this->oneof_decl = new \Protobuf\MessageCollection(); } $this->oneof_decl->add($value); }
php
{ "resource": "" }
q8976
DescriptorProto.addReservedRange
train
public function addReservedRange(\google\protobuf\DescriptorProto\ReservedRange $value) { if ($this->reserved_range === null) { $this->reserved_range = new \Protobuf\MessageCollection(); } $this->reserved_range->add($value); }
php
{ "resource": "" }
q8977
DescriptorProto.addReservedName
train
public function addReservedName($value) { if ($this->reserved_name === null) { $this->reserved_name = new \Protobuf\ScalarCollection(); } $this->reserved_name->add($value); }
php
{ "resource": "" }
q8978
CropController.filterAction
train
public function filterAction(Request $request, $endpoint) { $form = $this->createForm(CropType::class); $form->handleRequest($request); // Form invalid. Exit. if (!$form->isValid()) { return $this->createErrorResponse( $this->get('translator')->trans('Invalid crop parameters') ); } // Else process crop try { return new JsonResponse( $this->get('jb_fileuploader.croper')->crop($endpoint, $form->getData()) ); } catch (\Exception $e) { return $this->createErrorResponse($e->getMessage()); } }
php
{ "resource": "" }
q8979
LocalStorage.parseDateFromFilename
train
protected function parseDateFromFilename($filename) { if ($date = \DateTime::createFromFormat(self::FILE_NAME_PATTERN, explode('_', $filename)[0])) { return $date; } /** * @deprecated handle BC break of PR #62. will be remove in 1.0-RC1. */ return \DateTime::createFromFormat('H-i-s-Y-m-d', explode('_', $filename)[0]); }
php
{ "resource": "" }
q8980
QueryBuilder.prepare
train
public function prepare() { if (null === $this->statement) { $this->statement = $this->db->prepare($this->getSql()); } return $this; }
php
{ "resource": "" }
q8981
QueryBuilder.groupBy
train
public function groupBy($fields) { if (!is_array($fields)) { $fields = $this->splitParts($fields); } foreach ($fields as $k => $field) { $fields[$k] = $this->db->quoteColumn($field); } $this->query['group'] = implode(',', $fields); return $this; }
php
{ "resource": "" }
q8982
QueryBuilder.buildQuery
train
public function buildQuery($query = null) { if (null === $query) { $query = $this->query; } $sql = "SELECT "; if (isset($query['distinct']) && $query['distinct']) { $sql .= 'DISTINCT '; } $sql .= isset($query['select']) ? $query['select'] : '*'; if (!isset($query['from'])) { return false; } $sql .= "\nFROM " . $query['from']; if (isset($query['join'])) { $sql .= "\n" . (is_array($query['join']) ? implode("\n", $query['join']) : $query['join']); } if (isset($query['where']) && $query['where'] !== '') { $sql .= "\nWHERE " . $query['where']; } if (isset($query['group'])) { $sql .= "\nGROUP BY " . $query['group']; if (isset($query['having'])) { $sql .= "\nHAVING " . $query['having']; } } if (isset($query['order'])) { $sql .= "\n ORDER BY " . $query['order']; } $limit = isset($query['limit']) ? $query['limit'] : 0; $offset = isset($query['offset']) ? $query['offset'] : 0; $sql = $this->db->buildLimitOffset($sql, $limit, $offset); if (isset($query['union'])) { $sql .= "\n" . (is_array($query['union']) ? implode("\n", $query['union']) : $query['union']); } return $sql; }
php
{ "resource": "" }
q8983
QueryBuilder.setSql
train
public function setSql($sql) { if ('' !== $prefix = $this->db->getPrefix()) { $sql = preg_replace('#{{(.*?)}}#', $prefix . '\1', $sql); } $this->sql = $sql; return $this; }
php
{ "resource": "" }
q8984
QueryBuilder.getSql
train
public function getSql() { if (null === $this->sql) { if (!empty($this->query)) { $this->setSql($this->buildQuery()); } else { return false; } } return $this->sql; }
php
{ "resource": "" }
q8985
QueryBuilder.beginQuery
train
protected function beginQuery() { $autoSlave = $this->db->isAutoSlave(); if ($autoSlave) { $this->db->switchConnection('slave'); } $reconnect = $this->db->getOption('reconnect'); $reconnectRetries = $this->db->getOption('reconnect_retries', 3); $reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000); while (true) { $e = null; $errorCode = null; $errorInfo = null; $result = null; $isReconnectError = false; try { $this->prepare(); $result = $this->statement->execute($this->params ? $this->params : $this->positionParams); } catch (\Exception $e) { } if ($result === false || !$e) { $errorCode = $this->statement->errorCode(); $errorInfo = $this->statement->errorInfo(); } $isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e); // reconnect if ($reconnect && $isReconnectError && $reconnectRetries > 0) { $reconnectRetries--; $this->statement = null; $this->db->close(); $reconnectDelayMS && usleep($reconnectDelayMS * 1000); continue; } break; } if ($autoSlave) { $this->db->switchConnection(); } if ($e) { $this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage())); throw $e; } if ($result === false) { $errorMsg = sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]); $this->db->logError($errorMsg); throw new Exception($errorMsg); } }
php
{ "resource": "" }
q8986
QueryBuilder.queryAll
train
public function queryAll($params = array()) { $this->mergeParams($params); $this->beginQuery(); $rst = $this->statement->fetchAll(\PDO::FETCH_ASSOC); $this->statement->closeCursor(); return $rst; }
php
{ "resource": "" }
q8987
QueryBuilder.queryRow
train
public function queryRow($params = array()) { $this->mergeParams($params); $this->beginQuery(); $rst = $this->statement->fetch(\PDO::FETCH_ASSOC); $this->statement->closeCursor(); return $rst; }
php
{ "resource": "" }
q8988
QueryBuilder.queryColumn
train
public function queryColumn($params = array()) { $this->mergeParams($params); $this->beginQuery(); $rst = $this->statement->fetchAll(\PDO::FETCH_COLUMN); $this->statement->closeCursor(); return $rst; }
php
{ "resource": "" }
q8989
QueryBuilder.queryValue
train
public function queryValue($params = array()) { $this->mergeParams($params); $this->beginQuery(); $rst = $this->statement->fetchColumn(); $this->statement->closeCursor(); return $rst; }
php
{ "resource": "" }
q8990
QueryBuilder.execute
train
public function execute($params = array()) { $this->mergeParams($params); $reconnect = $this->db->getOption('reconnect'); $reconnectRetries = $this->db->getOption('reconnect_retries', 3); $reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000); while (true) { $e = null; $errorCode = null; $errorInfo = null; $result = null; $isReconnectError = false; try { $this->prepare(); foreach ($this->positionParams as $index => $value) { $this->statement->bindValue($index + 1, $value); } $result = $this->statement->execute($this->params?:null); } catch (\Exception $e) { } if ($result === false || !$e) { $errorCode = $this->statement->errorCode(); $errorInfo = $this->statement->errorInfo(); } $isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e); // reconnect if ($reconnect && $isReconnectError && $reconnectRetries > 0) { $reconnectRetries--; $this->statement = null; $this->db->close(); $reconnectDelayMS && usleep($reconnectDelayMS * 1000); continue; } break; } if ($e) { $this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage())); throw $e; } if ($result === false) { $this->db->logError(sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2])); return false; } return $this->statement->rowCount(); }
php
{ "resource": "" }
q8991
Cache.computeTTL
train
public function computeTTL($ttl = null) { $ttl = $ttl ?: $this->defaultTTL; if ($ttl === null) { return null; } return $ttl + rand(0, $this->ttlVariation); }
php
{ "resource": "" }
q8992
Cache.capturePage
train
public function capturePage($id = null, $ttl = null, $exit = true) { if ($id === null) { $id = md5(serialize($_SERVER['REQUEST_URI']) . serialize($_REQUEST)); } if ($this->start($id)) { if ($exit) { exit; } return true; } $self = $this; register_shutdown_function(function() use ($self, $ttl) { $self->end($ttl); }); return false; }
php
{ "resource": "" }
q8993
Cache.pipeline
train
public function pipeline($callback = null) { $pipe = $this->createPipeline(); if ($callback === null) { return $pipe; } call_user_func($callback, $pipe); return $pipe->execute(); }
php
{ "resource": "" }
q8994
Field.unIndexed
train
public static function unIndexed($name, $value, $encoding = 'UTF-8') { return new self($name, $value, $encoding, true, false, false); }
php
{ "resource": "" }
q8995
AbstractImageValidator.validateConfig
train
protected function validateConfig($key, array $configuration, $isFloat = false) { if (!$isFloat && !ctype_digit((string) $configuration[$key])) { throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key)); } if ($isFloat && !is_numeric((string) $configuration[$key])) { throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key)); } return true; }
php
{ "resource": "" }
q8996
GdaemonFiles.metadata
train
public function metadata($path) { $writeBinn= new BinnList; $writeBinn->addUint8(self::FSERV_FILEINFO); $writeBinn->addStr($path); $read = $this->writeAndReadSocket($writeBinn->serialize()); $readBinn = new BinnList; $readBinn->binnOpen($read); $results = $readBinn->unserialize(); if ($results[0] != self::FSERV_STATUS_OK) { throw new RuntimeException('GDaemon metadata error:' . isset($results[1]) ? $results[1] : 'Unknown'); } $fileInfo = $results[2]; return [ 'name' => basename($fileInfo[0]), 'size' => $fileInfo[1], 'type' => ($fileInfo[2] == 1) ? 'dir' : 'file', 'mtime' => $fileInfo[3], 'atime' => $fileInfo[4], 'ctime' => $fileInfo[5], 'permissions' => $fileInfo[6], 'mimetype' => $fileInfo[7], ]; }
php
{ "resource": "" }
q8997
GdaemonFiles.chmod
train
public function chmod($mode, $path) { $writeBinn = new BinnList; $writeBinn->addUint8(self::FSERV_CHMOD); $writeBinn->addStr($path); $writeBinn->addUint16($mode); $read = $this->writeAndReadSocket($writeBinn->serialize()); $readBinn = new BinnList; $readBinn->binnOpen($read); $results = $readBinn->unserialize(); if ($results[0] != self::FSERV_STATUS_OK) { throw new RuntimeException('Couldn\'t chmod: ' . isset($results[1]) ? $results[1] : 'Unknown'); } return true; }
php
{ "resource": "" }
q8998
Zipper.zip
train
public function zip($directory, $fileName) { $path = sprintf('%s/%s/%s.zip', $this->localDirectory, $this->name, $fileName); $this->filesystem->mkdir(dirname($path)); // FIXME find better place for this message $this->output->writeln(PHP_EOL . 'Creating zip file (it may take a few minutes) ...'); $zip = $this->openZip($path); $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)); foreach ($files as $filePath => $file) { $relative = Path::makeRelative($filePath, $directory); if (is_dir($filePath)) { $zip->addEmptyDir($relative); continue; } $zip->addFile($filePath, $relative); } $zip->close(); return $path; }
php
{ "resource": "" }
q8999
Zipper.openZip
train
private function openZip($path) { $zip = new \ZipArchive(); if (!$zip->open($path, \ZipArchive::CREATE)) { throw new IOException('Cannot create zip file'); } return $zip; }
php
{ "resource": "" }